1 # -*- coding: utf-8 -*-
4 # This file is part of LyX, the document processor.
5 # Licence details can be found in the file COPYING.
7 # author Enrico Forestieri
10 # Full author contact details are available in file CREDITS
12 # This script creates a tar or zip archive with a lyx file and all included
13 # files (graphics and so on). By default, the created archive is the standard
14 # type on a given platform, such that a zip archive is created on Windows and
15 # a gzip compressed tar archive on *nix. This can be controlled by command
16 # line options, however.
18 import os, re, string, sys
19 if sys.version_info < (2, 4, 0):
20 from sets import Set as set
21 from getopt import getopt
23 # Pre-compiled regular expressions.
24 re_lyxfile = re.compile("\.lyx$")
25 re_input = re.compile(r'^(.*)\\(input|include){(\s*)(.+)(\s*)}.*$')
26 re_ertinput = re.compile(r'^(input|include)({)(\s*)(.+)(\s*)}.*$')
27 re_package = re.compile(r'^(.*)\\(usepackage){(\s*)(.+)(\s*)}.*$')
28 re_class = re.compile(r'^(\\)(textclass)(\s+)(.+)\s*$')
29 re_norecur = re.compile(r'^(.*)\\(verbatiminput|lstinputlisting|includegraphics\[*.*\]*){(\s*)(.+)(\s*)}.*$')
30 re_ertnorecur = re.compile(r'^(verbatiminput|lstinputlisting|includegraphics\[*.*\]*)({)(\s*)(.+)(\s*)}.*$')
31 re_filename = re.compile(r'^(\s*)(filename)(\s+)(.+)\s*$')
32 re_options = re.compile(r'^(\s*)options(\s+)(.+)\s*$')
33 re_bibfiles = re.compile(r'^(\s*)bibfiles(\s+)(.+)\s*$')
38 Usage: %s [-t] [-z] [-l path] [-o output_dir] file.lyx
40 -l: Path to lyx2lyx script
41 -o: Directory for output
42 -t: Create gzipped tar file
44 By default, we create file.zip on Windows and file.tar.gz on *nix,
45 with the file output to where file.lyx is, and we look for lyx2lyx
46 in the known locations, querying LyX itself if necessary.
48 return msg % prog_name
52 sys.stderr.write(message + '\n')
57 handle = os.popen(cmd, 'r')
58 cmd_stdout = handle.read()
59 cmd_status = handle.close()
60 return cmd_status, cmd_stdout
63 def find_exe(candidates, extlist, path):
64 for prog in candidates:
65 for directory in path:
67 full_path = os.path.join(directory, prog + ext)
68 if os.access(full_path, os.X_OK):
69 return prog, full_path
74 " Resolve symlinks and returns the absolute normalized name."
75 newname = os.path.normpath(os.path.abspath(name))
77 newname = os.path.realpath(newname)
81 def gather_files(curfile, incfiles, lyx2lyx):
82 " Recursively gather files."
83 curdir = os.path.dirname(abspath(curfile))
84 is_lyxfile = re_lyxfile.search(curfile)
86 lyx2lyx_cmd = 'python "%s" "%s"' % (lyx2lyx, curfile)
87 l2l_status, l2l_stdout = run_cmd(lyx2lyx_cmd)
88 if l2l_status != None:
89 error('%s failed to convert "%s"' % (lyx2lyx, curfile))
90 lines = l2l_stdout.splitlines()
92 input = open(curfile, 'rU')
93 lines = input.readlines()
102 match = re_filename.match(lines[i])
105 match = re_ertinput.match(lines[i])
107 match = re_input.match(lines[i])
109 match = re_package.match(lines[i])
112 match = re_class.match(lines[i])
116 match = re_ertnorecur.match(lines[i])
118 match = re_norecur.match(lines[i])
119 extlist = ['', '.eps', '.pdf', '.png', '.jpg']
121 maybe_in_ert = is_lyxfile and lines[i] == "\\backslash"
123 file = match.group(4).strip('"')
124 if not os.path.isabs(file):
125 file = os.path.join(curdir, file)
127 if not os.path.isdir(file):
129 if os.path.exists(file + ext):
133 if file_exists and not abspath(file) in incfiles:
134 incfiles.append(abspath(file))
136 gather_files(file, incfiles, lyx2lyx)
144 # Gather bibtex *.bst files.
145 match = re_options.match(lines[i])
147 file = match.group(3).strip('"')
148 if file.startswith("bibtotoc,"):
150 if not os.path.isabs(file):
151 file = os.path.join(curdir, file + '.bst')
152 if os.path.exists(file):
153 incfiles.append(abspath(file))
157 # Gather bibtex *.bib files.
158 match = re_bibfiles.match(lines[i])
160 bibfiles = match.group(3).strip('"').split(',')
162 while j < len(bibfiles):
163 if os.path.isabs(bibfiles[j]):
164 file = bibfiles[j] + '.bib'
166 file = os.path.join(curdir, bibfiles[j] + '.bib')
167 if os.path.exists(file):
168 incfiles.append(abspath(file))
178 def find_lyx2lyx(progloc, path):
179 " Find a usable version of the lyx2lyx script. "
180 # first we will see if the script is roughly where we are
181 # i.e., we will assume we are in $SOMEDIR/scripts and look
182 # for $SOMEDIR/lyx2lyx/lyx2lyx.
183 ourpath = os.path.dirname(abspath(progloc))
184 (upone, discard) = os.path.split(ourpath)
185 tryit = os.path.join(upone, "lyx2lyx", "lyx2lyx")
186 if os.access(tryit, os.X_OK):
189 # now we will try to query LyX itself to find the path.
191 if "PATHEXT" in os.environ:
192 extlist = extlist + os.environ["PATHEXT"].split(os.pathsep)
193 lyx_exe, full_path = find_exe(["lyxc", "lyx"], extlist, path)
195 error('Cannot find the LyX executable in the path.')
196 cmd_status, cmd_stdout = run_cmd("%s -version 2>&1" % lyx_exe)
197 if cmd_status != None:
198 error('Cannot query LyX about the lyx2lyx script.')
199 re_msvc = re.compile(r'^(\s*)(Host type:)(\s+)(win32)$')
200 re_sysdir = re.compile(r'^(\s*)(LyX files dir:)(\s+)(\S+)$')
201 lines = cmd_stdout.splitlines()
203 match = re_msvc.match(line)
205 # The LyX executable was built with MSVC, so the
206 # "LyX files dir:" line is unusable
207 basedir = os.path.dirname(os.path.dirname(full_path))
208 tryit = os.path.join(basedir, 'Resources', 'lyx2lyx', 'lyx2lyx')
210 match = re_sysdir.match(line)
212 tryit = os.path.join(match.group(4), 'lyx2lyx', 'lyx2lyx')
215 if not os.access(tryit, os.X_OK):
216 error('Unable to find the lyx2lyx script.')
225 (options, argv) = getopt(args[1:], "htzl:o:")
227 error(usage(ourprog))
229 # we expect the filename to be left
231 error(usage(ourprog))
233 makezip = (os.name == 'nt')
237 for (opt, param) in options:
249 if not os.path.isdir(outdir):
250 error('Error: "%s" is not a directory.' % outdir)
253 if not os.path.exists(lyxfile):
254 error('File "%s" not found.' % lyxfile)
256 # Check that it actually is a LyX document
257 input = open(lyxfile, 'rU')
258 line = input.readline()
260 if not (line and line.startswith('#LyX')):
261 error('File "%s" is not a LyX document.' % lyxfile)
272 ar_name = re_lyxfile.sub(ar_ext, abspath(lyxfile))
274 ar_name = os.path.join(abspath(outdir), os.path.basename(ar_name))
276 path = string.split(os.environ["PATH"], os.pathsep)
279 lyx2lyx = find_lyx2lyx(ourprog, path)
281 # Initialize the list with the specified LyX file and recursively
282 # gather all required files (also from child documents).
283 incfiles = [abspath(lyxfile)]
284 gather_files(lyxfile, incfiles, lyx2lyx)
286 # Find the topmost dir common to all files
287 if len(incfiles) > 1:
288 topdir = os.path.commonprefix(incfiles)
289 # Check whether topdir is valid, as os.path.commonprefix() works on
290 # a character by character basis, rather than on path elements.
291 if not os.path.exists(topdir):
292 topdir = os.path.dirname(topdir) + os.path.sep
294 topdir = os.path.dirname(incfiles[0]) + os.path.sep
296 # Remove the prefix common to all paths in the list
298 while i < len(incfiles):
299 incfiles[i] = string.replace(incfiles[i], topdir, '', 1)
302 # Remove duplicates and sort the list
303 incfiles = list(set(incfiles))
312 zip = zipfile.ZipFile(ar_name, "w", zipfile.ZIP_DEFLATED)
313 for file in incfiles:
317 tar = tarfile.open(ar_name, "w:gz")
318 for file in incfiles:
322 error('Failed to create LyX archive "%s"' % ar_name)
324 print 'LyX archive "%s" created successfully.' % ar_name
328 if __name__ == "__main__":