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*)}.*$')
27 re_ertinput = re.compile(r'^(input|include)({)(\s*)(.+)(\s*)}.*$')
28 re_package = re.compile(r'^(.*)\\(usepackage){(\s*)(.+)(\s*)}.*$')
29 re_class = re.compile(r'^(\\)(textclass)(\s+)(.+)\s*$')
30 re_norecur = re.compile(r'^(.*)\\(verbatiminput|lstinputlisting|includegraphics\[*.*\]*){(\s*)(.+)(\s*)}.*$')
31 re_ertnorecur = re.compile(r'^(verbatiminput|lstinputlisting|includegraphics\[*.*\]*)({)(\s*)(.+)(\s*)}.*$')
32 re_filename = re.compile(r'^(\s*)(filename)(\s+)(.+)\s*$')
33 re_options = re.compile(r'^(\s*)options(\s+)(.+)\s*$')
34 re_bibfiles = re.compile(r'^(\s*)bibfiles(\s+)(.+)\s*$')
39 Usage: %s [-t] [-z] [-l path] [-o output_dir] file.lyx
41 -l: Path to lyx2lyx script
42 -o: Directory for output
43 -t: Create gzipped tar file
45 By default, we create file.zip on Windows and file.tar.gz on *nix,
46 with the file output to where file.lyx is, and we look for lyx2lyx
47 in the known locations, querying LyX itself if necessary.
49 return msg % prog_name
53 sys.stderr.write(message + '\n')
58 handle = os.popen(cmd, 'r')
59 cmd_stdout = handle.read()
60 cmd_status = handle.close()
61 return cmd_status, cmd_stdout
64 def find_exe(candidates, extlist, path):
65 for prog in candidates:
66 for directory in path:
68 full_path = os.path.join(directory, prog + ext)
69 if os.access(full_path, os.X_OK):
70 return prog, full_path
75 " Resolve symlinks and returns the absolute normalized name."
76 newname = os.path.normpath(os.path.abspath(name))
78 newname = os.path.realpath(newname)
82 def gather_files(curfile, incfiles, lyx2lyx):
83 " Recursively gather files."
84 curdir = os.path.dirname(abspath(curfile))
85 is_lyxfile = re_lyxfile.search(curfile)
87 lyx2lyx_cmd = 'python "%s" "%s"' % (lyx2lyx, curfile)
88 l2l_status, l2l_stdout = run_cmd(lyx2lyx_cmd)
89 if l2l_status != None:
90 error('%s failed to convert "%s"' % (lyx2lyx, curfile))
91 lines = l2l_stdout.splitlines()
93 input = open(curfile, 'rU')
94 lines = input.readlines()
103 match = re_filename.match(lines[i])
106 match = re_ertinput.match(lines[i])
108 match = re_input.match(lines[i])
110 match = re_package.match(lines[i])
113 match = re_class.match(lines[i])
117 match = re_ertnorecur.match(lines[i])
119 match = re_norecur.match(lines[i])
120 extlist = ['', '.eps', '.pdf', '.png', '.jpg']
122 maybe_in_ert = is_lyxfile and lines[i] == "\\backslash"
124 file = match.group(4).strip('"')
125 if not os.path.isabs(file):
126 file = os.path.join(curdir, file)
128 if not os.path.isdir(file):
130 if os.path.exists(file + ext):
134 if file_exists and not abspath(file) in incfiles:
135 incfiles.append(abspath(file))
137 gather_files(file, incfiles, lyx2lyx)
145 # Gather bibtex *.bst files.
146 match = re_options.match(lines[i])
148 file = match.group(3).strip('"')
149 if not os.path.isabs(file):
150 file = os.path.join(curdir, file + '.bst')
151 if os.path.exists(file):
152 incfiles.append(abspath(file))
156 # Gather bibtex *.bib files.
157 match = re_bibfiles.match(lines[i])
159 bibfiles = match.group(3).strip('"').split(',')
161 while j < len(bibfiles):
162 if os.path.isabs(bibfiles[j]):
163 file = bibfiles[j] + '.bib'
165 file = os.path.join(curdir, bibfiles[j] + '.bib')
166 if os.path.exists(file):
167 incfiles.append(abspath(file))
177 def find_lyx2lyx(progloc):
178 " Find a usable version of the lyx2lyx script. "
179 # first we will see if the script is roughly where we are
180 # i.e., we will assume we are in $SOMEDIR/scripts and look
181 # for $SOMEDIR/lyx2lyx/lyx2lyx.
182 ourpath = os.path.dirname(abspath(progloc))
183 (upone, discard) = os.path.split(ourpath)
184 tryit = os.path.join(upone, "lyx2lyx", "lyx2lyx")
185 if os.access(tryit, os.X_OK):
188 # now we will try to query LyX itself to find the path.
190 if "PATHEXT" in os.environ:
191 extlist = extlist + os.environ["PATHEXT"].split(os.pathsep)
192 lyx_exe, full_path = find_exe(["lyxc", "lyx"], extlist, path)
194 error('Cannot find the LyX executable in the path.')
195 cmd_status, cmd_stdout = run_cmd("%s -version 2>&1" % lyx_exe)
196 if cmd_status != None:
197 error('Cannot query LyX about the lyx2lyx script.')
198 re_msvc = re.compile(r'^(\s*)(Host type:)(\s+)(win32)$')
199 re_sysdir = re.compile(r'^(\s*)(LyX files dir:)(\s+)(\S+)$')
200 lines = cmd_stdout.splitlines()
202 match = re_msvc.match(line)
204 # The LyX executable was built with MSVC, so the
205 # "LyX files dir:" line is unusable
206 basedir = os.path.dirname(os.path.dirname(full_path))
207 tryit = os.path.join(basedir, 'Resources', 'lyx2lyx', 'lyx2lyx')
209 match = re_sysdir.match(line)
211 tryit = os.path.join(match.group(4), 'lyx2lyx', 'lyx2lyx')
214 if not os.access(tryit, os.X_OK):
215 error('Unable to find the lyx2lyx script.')
224 (options, argv) = getopt(args[1:], "htzl:o:")
226 error(usage(ourprog))
228 # we expect the filename to be left
230 error(usage(ourprog))
232 makezip = (os.name == 'nt')
236 for (opt, param) in options:
248 if not os.path.isdir(outdir):
249 error('Error: "%s" is not a directory.' % outdir)
252 if not os.path.exists(lyxfile):
253 error('File "%s" not found.' % lyxfile)
255 # Check that it actually is a LyX document
256 input = open(lyxfile, 'rU')
257 line = input.readline()
259 if not (line and line.startswith('#LyX')):
260 error('File "%s" is not a LyX document.' % lyxfile)
271 ar_name = re_lyxfile.sub(ar_ext, abspath(lyxfile))
273 ar_name = os.path.join(abspath(outdir), os.path.basename(ar_name))
275 path = string.split(os.environ["PATH"], os.pathsep)
278 lyx2lyx = find_lyx2lyx(ourprog)
280 # Initialize the list with the specified LyX file and recursively
281 # gather all required files (also from child documents).
282 incfiles = [abspath(lyxfile)]
283 gather_files(lyxfile, incfiles, lyx2lyx)
285 # Find the topmost dir common to all files
286 if len(incfiles) > 1:
287 topdir = os.path.commonprefix(incfiles)
288 # Check whether topdir is valid, as os.path.commonprefix() works on
289 # a character by character basis, rather than on path elements.
290 if not os.path.exists(topdir):
291 topdir = os.path.dirname(topdir) + os.path.sep
293 topdir = os.path.dirname(incfiles[0]) + os.path.sep
295 # Remove the prefix common to all paths in the list
297 while i < len(incfiles):
298 incfiles[i] = string.replace(incfiles[i], topdir, '', 1)
301 # Remove duplicates and sort the list
302 incfiles = list(set(incfiles))
311 zip = zipfile.ZipFile(ar_name, "w", zipfile.ZIP_DEFLATED)
312 for file in incfiles:
316 tar = tarfile.open(ar_name, "w:gz")
317 for file in incfiles:
321 error('Failed to create LyX archive "%s"' % ar_name)
323 print 'LyX archive "%s" created successfully.' % ar_name
327 if __name__ == "__main__":