2 # -*- coding: utf-8 -*-
5 # This file is part of LyX, the document processor.
6 # Licence details can be found in the file COPYING.
8 # author Enrico Forestieri
11 # Full author contact details are available in file CREDITS
13 # This script creates a tar or zip archive with a lyx file and all included
14 # files (graphics and so on). By default, the created archive is the standard
15 # type on a given platform, such that a zip archive is created on Windows and
16 # a gzip compressed tar archive on *nix. This can be controlled by command
17 # line options, however.
19 import os, re, string, sys
20 if sys.version_info < (2, 4, 0):
21 from sets import Set as set
22 from getopt import getopt
24 # Pre-compiled regular expressions.
25 re_lyxfile = re.compile("\.lyx$")
26 re_input = re.compile(r'^(.*)\\(input|include){(\s*)(\S+)(\s*)}.*$')
27 re_package = re.compile(r'^(.*)\\(usepackage){(\s*)(\S+)(\s*)}.*$')
28 re_class = re.compile(r'^(\\)(textclass)(\s+)(\S+)$')
29 re_norecur = re.compile(r'^(.*)\\(verbatiminput|lstinputlisting|includegraphics\[*.*\]*){(\s*)(\S+)(\s*)}.*$')
30 re_filename = re.compile(r'^(\s*)(filename)(\s+)(\S+)$')
31 re_options = re.compile(r'^(\s*)options(\s+)(\S+)$')
32 re_bibfiles = re.compile(r'^(\s*)bibfiles(\s+)(\S+)$')
37 Usage: %s [-t] [-z] [-l path] [-o output_dir] file.lyx
39 -l: Path to lyx2lyx script
40 -o: Directory for output
41 -t: Create gzipped tar file
43 By default, we create file.zip on Windows and file.tar.gz on *nix,
44 with the file output to where file.lyx is, and we look for lyx2lyx
45 in the known locations, querying LyX itself if necessary.
47 return msg % prog_name
51 sys.stderr.write(message + '\n')
56 handle = os.popen(cmd, 'r')
57 cmd_stdout = handle.read()
58 cmd_status = handle.close()
59 return cmd_status, cmd_stdout
62 def find_exe(candidates, extlist, path):
63 for prog in candidates:
64 for directory in path:
66 full_path = os.path.join(directory, prog + ext)
67 if os.access(full_path, os.X_OK):
68 return prog, full_path
73 " Resolve symlinks and returns the absolute normalized name."
74 newname = os.path.normpath(os.path.abspath(name))
76 newname = os.path.realpath(newname)
80 def gather_files(curfile, incfiles, lyx2lyx):
81 " Recursively gather files."
82 curdir = os.path.dirname(abspath(curfile))
83 is_lyxfile = re_lyxfile.search(curfile)
85 lyx2lyx_cmd = 'python "%s" "%s"' % (lyx2lyx, curfile)
86 l2l_status, l2l_stdout = run_cmd(lyx2lyx_cmd)
87 if l2l_status != None:
88 error('%s failed to convert "%s"' % (lyx2lyx, curfile))
89 lines = l2l_stdout.splitlines()
91 input = open(curfile, 'rU')
92 lines = input.readlines()
100 match = re_filename.match(lines[i])
102 match = re_input.match(lines[i])
104 match = re_package.match(lines[i])
107 match = re_class.match(lines[i])
110 match = re_norecur.match(lines[i])
111 extlist = ['', '.eps', '.pdf', '.png', '.jpg']
114 file = match.group(4).strip('"')
115 if not os.path.isabs(file):
116 file = os.path.join(curdir, file)
119 if os.path.exists(file + ext):
124 incfiles.append(abspath(file))
126 gather_files(file, incfiles, lyx2lyx)
134 # Gather bibtex *.bst files.
135 match = re_options.match(lines[i])
137 file = match.group(3).strip('"')
138 if not os.path.isabs(file):
139 file = os.path.join(curdir, file + '.bst')
140 if os.path.exists(file):
141 incfiles.append(abspath(file))
145 # Gather bibtex *.bib files.
146 match = re_bibfiles.match(lines[i])
148 bibfiles = match.group(3).strip('"').split(',')
150 while j < len(bibfiles):
151 if os.path.isabs(bibfiles[j]):
154 file = os.path.join(curdir, bibfiles[j] + '.bib')
155 if os.path.exists(file):
156 incfiles.append(abspath(file))
166 def find_lyx2lyx(progloc):
167 " Find a usable version of the lyx2lyx script. "
168 # first we will see if the script is roughly where we are
169 # i.e., we will assume we are in $SOMEDIR/scripts and look
170 # for $SOMEDIR/lyx2lyx/lyx2lyx.
171 ourpath = os.path.dirname(abspath(progloc))
172 (upone, discard) = os.path.split(ourpath)
173 tryit = os.path.join(upone, "lyx2lyx", "lyx2lyx")
174 if os.access(tryit, os.X_OK):
177 # now we will try to query LyX itself to find the path.
179 if "PATHEXT" in os.environ:
180 extlist = extlist + os.environ["PATHEXT"].split(os.pathsep)
181 lyx_exe, full_path = find_exe(["lyxc", "lyx"], extlist, path)
183 error('Cannot find the LyX executable in the path.')
184 cmd_status, cmd_stdout = run_cmd("%s -version 2>&1" % lyx_exe)
185 if cmd_status != None:
186 error('Cannot query LyX about the lyx2lyx script.')
187 re_msvc = re.compile(r'^(\s*)(Host type:)(\s+)(win32)$')
188 re_sysdir = re.compile(r'^(\s*)(LyX files dir:)(\s+)(\S+)$')
189 lines = cmd_stdout.splitlines()
191 match = re_msvc.match(line)
193 # The LyX executable was built with MSVC, so the
194 # "LyX files dir:" line is unusable
195 basedir = os.path.dirname(os.path.dirname(full_path))
196 tryit = os.path.join(basedir, 'Resources', 'lyx2lyx', 'lyx2lyx')
198 match = re_sysdir.match(line)
200 tryit = os.path.join(match.group(4), 'lyx2lyx', 'lyx2lyx')
203 if not os.access(tryit, os.X_OK):
204 error('Unable to find the lyx2lyx script.')
213 (options, argv) = getopt(args[1:], "htzl:o:")
215 error(usage(ourprog))
217 # we expect the filename to be left
219 error(usage(ourprog))
221 makezip = (os.name == 'nt')
225 for (opt, param) in options:
237 if not os.path.isdir(outdir):
238 error('Error: "%s" is not a directory.' % outdir)
241 if not os.path.exists(lyxfile):
242 error('File "%s" not found.' % lyxfile)
244 # Check that it actually is a LyX document
245 input = open(lyxfile, 'rU')
246 line = input.readline()
248 if not (line and line.startswith('#LyX')):
249 error('File "%s" is not a LyX document.' % lyxfile)
260 ar_name = re_lyxfile.sub(ar_ext, abspath(lyxfile))
262 ar_name = os.path.join(abspath(outdir), os.path.basename(ar_name))
264 path = string.split(os.environ["PATH"], os.pathsep)
267 lyx2lyx = find_lyx2lyx(ourprog)
269 # Initialize the list with the specified LyX file and recursively
270 # gather all required files (also from child documents).
271 incfiles = [abspath(lyxfile)]
272 gather_files(lyxfile, incfiles, lyx2lyx)
274 # Find the topmost dir common to all files
275 if len(incfiles) > 1:
276 topdir = os.path.commonprefix(incfiles)
278 topdir = os.path.dirname(incfiles[0]) + os.path.sep
280 # Remove the prefix common to all paths in the list
282 while i < len(incfiles):
283 incfiles[i] = string.replace(incfiles[i], topdir, '', 1)
286 # Remove duplicates and sort the list
287 incfiles = list(set(incfiles))
296 zip = zipfile.ZipFile(ar_name, "w", zipfile.ZIP_DEFLATED)
297 for file in incfiles:
301 tar = tarfile.open(ar_name, "w:gz")
302 for file in incfiles:
306 error('Failed to create LyX archive "%s"' % ar_name)
308 print 'LyX archive "%s" created successfully.' % ar_name
312 if __name__ == "__main__":