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
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). A zip archive is created only if tar is not
14 # found in the path. The tar archive is then compressed with gzip or bzip2.
16 import os, re, string, sys
17 if sys.version_info < (2, 4, 0):
18 from sets import Set as set
20 # Replace with the actual path to the 1.5.x or 1.6.x lyx2lyx.
21 # If left undefined and the LyX executable is in the path, the script will
22 # try to locate lyx2lyx by querying LyX about the system dir.
24 # lyx2lyx = /usr/share/lyx/lyx2lyx/lyx2lyx
27 # Pre-compiled regular expressions.
28 re_lyxfile = re.compile("\.lyx$")
29 re_input = re.compile(r'^(.*)\\(input|include){(\s*)(\S+)(\s*)}.*$')
30 re_package = re.compile(r'^(.*)\\(usepackage){(\s*)(\S+)(\s*)}.*$')
31 re_class = re.compile(r'^(\\)(textclass)(\s+)(\S+)$')
32 re_norecur = re.compile(r'^(.*)\\(verbatiminput|lstinputlisting|includegraphics\[*.*\]*){(\s*)(\S+)(\s*)}.*$')
33 re_filename = re.compile(r'^(\s*)(filename)(\s+)(\S+)$')
34 re_options = re.compile(r'^(\s*)options(\s+)(\S+)$')
35 re_bibfiles = re.compile(r'^(\s*)bibfiles(\s+)(\S+)$')
39 return "Usage: %s file.lyx [output_dir]\n" % prog_name
43 sys.stderr.write(message + '\n')
48 handle = os.popen(cmd, 'r')
49 cmd_stdout = handle.read()
50 cmd_status = handle.close()
51 return cmd_status, cmd_stdout
54 def find_exe(candidates, extlist, path):
55 for prog in candidates:
56 for directory in path:
58 full_path = os.path.join(directory, prog + ext)
59 if os.access(full_path, os.X_OK):
60 return prog, full_path
65 " Resolve symlinks and returns the absolute normalized name."
66 newname = os.path.normpath(os.path.abspath(name))
68 newname = os.path.realpath(newname)
72 def gather_files(curfile, incfiles):
73 " Recursively gather files."
74 curdir = os.path.dirname(abspath(curfile))
75 is_lyxfile = re_lyxfile.search(curfile)
77 lyx2lyx_cmd = 'python "%s" "%s"' % (lyx2lyx, curfile)
78 l2l_status, l2l_stdout = run_cmd(lyx2lyx_cmd)
79 if l2l_status != None:
80 error('%s failed to convert "%s"' % (lyx2lyx, curfile))
81 lines = l2l_stdout.splitlines()
83 input = open(curfile, 'rU')
84 lines = input.readlines()
92 match = re_filename.match(lines[i])
94 match = re_input.match(lines[i])
96 match = re_package.match(lines[i])
99 match = re_class.match(lines[i])
102 match = re_norecur.match(lines[i])
103 extlist = ['', '.eps', '.pdf', '.png', '.jpg']
106 file = match.group(4).strip('"')
107 if not os.path.isabs(file):
108 file = os.path.join(curdir, file)
111 if os.path.exists(file + ext):
116 incfiles.append(abspath(file))
118 gather_files(file, incfiles)
126 # Gather bibtex *.bst files.
127 match = re_options.match(lines[i])
129 file = match.group(3).strip('"')
130 if not os.path.isabs(file):
131 file = os.path.join(curdir, file + '.bst')
132 if os.path.exists(file):
133 incfiles.append(abspath(file))
137 # Gather bibtex *.bib files.
138 match = re_bibfiles.match(lines[i])
140 bibfiles = match.group(3).strip('"').split(',')
142 while j < len(bibfiles):
143 if os.path.isabs(bibfiles[j]):
146 file = os.path.join(curdir, bibfiles[j] + '.bib')
147 if os.path.exists(file):
148 incfiles.append(abspath(file))
160 if len(argv) < 2 and len(argv) > 3:
161 error(usage(argv[0]))
164 if not os.path.exists(lyxfile):
165 error('File "%s" not found.' % lyxfile)
170 if not os.path.isdir(outdir):
171 error('Error: "%s" is not a directory.' % outdir)
173 # Check that it actually is a LyX document
174 input = open(lyxfile, 'rU')
175 line = input.readline()
177 if not (line and line.startswith('#LyX')):
178 error('File "%s" is not a LyX document.' % lyxfile)
180 # Either tar or zip must be available
182 if os.environ.has_key("PATHEXT"):
183 extlist = extlist + os.environ["PATHEXT"].split(os.pathsep)
184 path = string.split(os.environ["PATH"], os.pathsep)
185 archiver, full_path = find_exe(["tar", "zip"], extlist, path)
187 if archiver == "tar":
189 ar_name = re_lyxfile.sub(".tar", abspath(lyxfile))
190 # Archive will be compressed if either gzip or bzip2 are available
191 compress, full_path = find_exe(["gzip", "bzip2"], extlist, path)
192 if compress == "gzip":
194 elif compress == "bzip2":
196 elif archiver == "zip":
198 ar_name = re_lyxfile.sub(".zip", abspath(lyxfile))
201 error("Unable to find either tar or zip.")
204 ar_name = os.path.join(abspath(outdir), os.path.basename(ar_name))
206 # Try to find the location of the lyx2lyx script
209 # first we will see if the script is roughly where we are
210 # i.e., we will assume we are in $SOMEDIR/scripts and look
211 # for $SOMEDIR/lyx2lyx/lyx2lyx.
212 ourpath = os.path.dirname(abspath(argv[0]))
213 (upone, discard) = os.path.split(ourpath)
214 tryit = os.path.join(upone, "lyx2lyx", "lyx2lyx")
215 if os.path.exists(tryit):
218 lyx_exe, full_path = find_exe(["lyxc", "lyx"], extlist, path)
220 error('Cannot find the LyX executable in the path.')
221 cmd_status, cmd_stdout = run_cmd("%s -version 2>&1" % lyx_exe)
222 if cmd_status != None:
223 error('Cannot query LyX about the lyx2lyx script.')
224 re_msvc = re.compile(r'^(\s*)(Host type:)(\s+)(win32)$')
225 re_sysdir = re.compile(r'^(\s*)(LyX files dir:)(\s+)(\S+)$')
226 lines = cmd_stdout.splitlines()
228 match = re_msvc.match(line)
230 # The LyX executable was built with MSVC, so the
231 # "LyX files dir:" line is unusable
232 basedir = os.path.dirname(os.path.dirname(full_path))
233 lyx2lyx = os.path.join(basedir, 'Resources', 'lyx2lyx', 'lyx2lyx')
235 match = re_sysdir.match(line)
237 lyx2lyx = os.path.join(match.group(4), 'lyx2lyx', 'lyx2lyx')
239 if not os.access(lyx2lyx, os.X_OK):
240 error('Unable to find the lyx2lyx script.')
242 # Initialize the list with the specified LyX file and recursively
243 # gather all required files (also from child documents).
244 incfiles = [abspath(lyxfile)]
245 gather_files(lyxfile, incfiles)
247 # Find the topmost dir common to all files
248 if len(incfiles) > 1:
249 topdir = os.path.commonprefix(incfiles)
251 topdir = os.path.dirname(incfiles[0]) + os.path.sep
253 # Remove the prefix common to all paths in the list
255 while i < len(incfiles):
256 incfiles[i] = string.replace(incfiles[i], topdir, '')
259 # Remove duplicates and sort the list
260 incfiles = list(set(incfiles))
263 # Build the archive command
264 ar_cmd = '%s "%s"' % (ar_cmd, ar_name)
265 for file in incfiles:
267 ar_cmd = ar_cmd + ' "' + file + '"'
272 cmd_status, cmd_stdout = run_cmd(ar_cmd)
273 if cmd_status != None:
274 error('Failed to create LyX archive "%s"' % ar_name)
276 # If possible, compress the archive
278 compress_cmd = '%s "%s"' % (compress, ar_name)
279 cmd_status, cmd_stdout = run_cmd(compress_cmd)
280 if cmd_status != None:
281 error('Failed to compress LyX archive "%s"' % ar_name)
282 ar_name = ar_name + ext
284 print 'LyX archive "%s" created successfully.' % ar_name
288 if __name__ == "__main__":