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 gzip, os, re, string, sys
19 from getopt import getopt
20 from cStringIO import StringIO
23 # The path to the current python executable. sys.executable may fail, so in
24 # this case we revert to simply calling "python" from the path.
25 PYTHON_BIN = sys.executable if sys.executable else "python"
27 running_on_windows = (os.name == 'nt')
29 if running_on_windows:
30 from shutil import copyfile
31 from tempfile import NamedTemporaryFile
33 # Pre-compiled regular expressions.
34 re_lyxfile = re.compile("\.lyx$")
35 re_input = re.compile(r'^(.*)\\(input|include){(\s*)(.+)(\s*)}.*$')
36 re_ertinput = re.compile(r'^(input|include)({)(\s*)(.+)(\s*)}.*$')
37 re_package = re.compile(r'^(.*)\\(usepackage){(\s*)(.+)(\s*)}.*$')
38 re_class = re.compile(r'^(\\)(textclass)(\s+)(.+)\s*$')
39 re_norecur = re.compile(r'^(.*)\\(verbatiminput|lstinputlisting|includegraphics\[*.*\]*){(\s*)(.+)(\s*)}.*$')
40 re_ertnorecur = re.compile(r'^(verbatiminput|lstinputlisting|includegraphics\[*.*\]*)({)(\s*)(.+)(\s*)}.*$')
41 re_filename = re.compile(r'^(\s*)(filename)(\s+)(.+)\s*$')
42 re_options = re.compile(r'^(\s*)options(\s+)(.+)\s*$')
43 re_bibfiles = re.compile(r'^(\s*)bibfiles(\s+)(.+)\s*$')
48 Usage: %s [-t] [-z] [-l path] [-o output_dir] file.lyx
50 -l: Path to lyx2lyx script
51 -o: Directory for output
52 -t: Create gzipped tar file
54 By default, we create file.zip on Windows and file.tar.gz on *nix,
55 with the file output to where file.lyx is, and we look for lyx2lyx
56 in the known locations, querying LyX itself if necessary.
58 return msg % prog_name
62 sys.stderr.write(message + '\n')
66 def gzopen(file, mode):
67 input = open(unicode(file, 'utf-8'), 'rb')
68 magicnum = input.read(2)
70 if magicnum == "\x1f\x8b":
71 return gzip.open(unicode(file, 'utf-8'), mode)
72 return open(unicode(file, 'utf-8'), mode)
75 def find_exe(candidates, extlist, path):
76 for prog in candidates:
77 for directory in path:
79 full_path = os.path.join(directory, prog + ext)
80 if os.access(full_path, os.X_OK):
81 return prog, full_path
86 " Resolve symlinks and returns the absolute normalized name."
87 newname = os.path.normpath(os.path.abspath(name))
88 if not running_on_windows:
89 newname = os.path.realpath(newname)
93 def gather_files(curfile, incfiles, lyx2lyx):
94 " Recursively gather files."
95 curdir = os.path.dirname(abspath(curfile))
96 is_lyxfile = re_lyxfile.search(curfile)
99 if running_on_windows:
100 # os.popen cannot cope with unicode arguments and we cannot be
101 # sure that curfile can be correctly converted to the current
102 # code page. So, we resort to running lyx2lyx on a copy.
103 tmp = NamedTemporaryFile(delete=False)
105 copyfile(unicode(curfile, 'utf-8'), tmp.name)
107 l2l_stdout = subprocess.check_output([PYTHON_BIN, lyx2lyx, tmp.name])
108 except subprocess.CalledProcessError:
109 error('%s failed to convert "%s"' % (lyx2lyx, curfile))
113 l2l_stdout = subprocess.check_output([PYTHON_BIN, lyx2lyx, curfile])
114 except subprocess.CalledProcessError:
115 error('%s failed to convert "%s"' % (lyx2lyx, curfile))
116 if l2l_stdout.startswith("\x1f\x8b"):
117 l2l_stdout = gzip.GzipFile("", "r", 0, StringIO(l2l_stdout)).read()
118 lines = l2l_stdout.splitlines()
120 input = gzopen(curfile, 'rU')
121 lines = input.readlines()
126 while i < len(lines):
130 match = re_filename.match(lines[i])
133 match = re_ertinput.match(lines[i])
135 match = re_input.match(lines[i])
137 match = re_package.match(lines[i])
140 match = re_class.match(lines[i])
144 match = re_ertnorecur.match(lines[i])
146 match = re_norecur.match(lines[i])
147 extlist = ['', '.eps', '.pdf', '.png', '.jpg']
149 maybe_in_ert = is_lyxfile and lines[i] == "\\backslash"
151 file = match.group(4).strip('"')
152 if not os.path.isabs(file):
153 file = os.path.join(curdir, file)
155 if not os.path.isdir(unicode(file, 'utf-8')):
157 if os.path.exists(unicode(file + ext, 'utf-8')):
161 if file_exists and not abspath(file) in incfiles:
162 incfiles.append(abspath(file))
164 gather_files(file, incfiles, lyx2lyx)
172 # Gather bibtex *.bst files.
173 match = re_options.match(lines[i])
175 file = match.group(3).strip('"')
176 if file.startswith("bibtotoc,"):
178 if not os.path.isabs(file):
179 file = os.path.join(curdir, file + '.bst')
180 if os.path.exists(unicode(file, 'utf-8')):
181 incfiles.append(abspath(file))
185 # Gather bibtex *.bib files.
186 match = re_bibfiles.match(lines[i])
188 bibfiles = match.group(3).strip('"').split(',')
190 while j < len(bibfiles):
191 if os.path.isabs(bibfiles[j]):
192 file = bibfiles[j] + '.bib'
194 file = os.path.join(curdir, bibfiles[j] + '.bib')
195 if os.path.exists(unicode(file, 'utf-8')):
196 incfiles.append(abspath(file))
206 def find_lyx2lyx(progloc, path):
207 " Find a usable version of the lyx2lyx script. "
208 # first we will see if the script is roughly where we are
209 # i.e., we will assume we are in $SOMEDIR/scripts and look
210 # for $SOMEDIR/lyx2lyx/lyx2lyx.
211 ourpath = os.path.dirname(abspath(progloc))
212 (upone, discard) = os.path.split(ourpath)
213 tryit = os.path.join(upone, "lyx2lyx", "lyx2lyx")
214 if os.access(tryit, os.X_OK):
217 # now we will try to query LyX itself to find the path.
219 if "PATHEXT" in os.environ:
220 extlist = extlist + os.environ["PATHEXT"].split(os.pathsep)
221 lyx_exe, full_path = find_exe(["lyxc", "lyx"], extlist, path)
223 error('Cannot find the LyX executable in the path.')
225 cmd_stdout = subprocess.check_output([lyx_exe, '-version'], stderr=subprocess.STDOUT)
226 except subprocess.CalledProcessError:
227 error('Cannot query LyX about the lyx2lyx script.')
228 re_msvc = re.compile(r'^(\s*)(Host type:)(\s+)(win32)$')
229 re_sysdir = re.compile(r'^(\s*)(LyX files dir:)(\s+)(\S+)$')
230 lines = cmd_stdout.splitlines()
232 match = re_msvc.match(line)
234 # The LyX executable was built with MSVC, so the
235 # "LyX files dir:" line is unusable
236 basedir = os.path.dirname(os.path.dirname(full_path))
237 tryit = os.path.join(basedir, 'Resources', 'lyx2lyx', 'lyx2lyx')
239 match = re_sysdir.match(line)
241 tryit = os.path.join(match.group(4), 'lyx2lyx', 'lyx2lyx')
244 if not os.access(tryit, os.X_OK):
245 error('Unable to find the lyx2lyx script.')
254 (options, argv) = getopt(args[1:], "htzl:o:")
256 error(usage(ourprog))
258 # we expect the filename to be left
260 error(usage(ourprog))
262 makezip = running_on_windows
266 for (opt, param) in options:
278 if not os.path.isdir(unicode(outdir, 'utf-8')):
279 error('Error: "%s" is not a directory.' % outdir)
282 if not running_on_windows:
283 lyxfile = unicode(lyxfile, sys.getfilesystemencoding()).encode('utf-8')
284 if not os.path.exists(unicode(lyxfile, 'utf-8')):
285 error('File "%s" not found.' % lyxfile)
287 # Check that it actually is a LyX document
288 input = gzopen(lyxfile, 'rU')
289 line = input.readline()
291 if not (line and line.startswith('#LyX')):
292 error('File "%s" is not a LyX document.' % lyxfile)
303 ar_name = re_lyxfile.sub(ar_ext, abspath(lyxfile))
305 ar_name = os.path.join(abspath(outdir), os.path.basename(ar_name))
307 path = string.split(os.environ["PATH"], os.pathsep)
310 lyx2lyx = find_lyx2lyx(ourprog, path)
312 # Initialize the list with the specified LyX file and recursively
313 # gather all required files (also from child documents).
314 incfiles = [abspath(lyxfile)]
315 gather_files(lyxfile, incfiles, lyx2lyx)
317 # Find the topmost dir common to all files
318 if len(incfiles) > 1:
319 topdir = os.path.commonprefix(incfiles)
320 # As os.path.commonprefix() works on a character by character basis,
321 # rather than on path elements, we need to remove any trailing bytes.
322 topdir = topdir.rpartition(os.path.sep)[0] + os.path.sep
324 topdir = os.path.dirname(incfiles[0]) + os.path.sep
326 # Remove the prefix common to all paths in the list
328 while i < len(incfiles):
329 incfiles[i] = string.replace(incfiles[i], topdir, '', 1)
332 # Remove duplicates and sort the list
333 incfiles = list(set(incfiles))
337 os.chdir(unicode(topdir, 'utf-8'))
342 zip = zipfile.ZipFile(ar_name, "w", zipfile.ZIP_DEFLATED)
343 for file in incfiles:
344 zip.write(file.decode('utf-8'), unicode(file, 'utf-8'))
347 tar = tarfile.open(ar_name, "w:gz")
348 for file in incfiles:
352 error('Failed to create LyX archive "%s"' % ar_name)
354 print 'LyX archive "%s" created successfully.' % ar_name
358 if __name__ == "__main__":
359 if running_on_windows:
360 # This works around <http://bugs.python.org/issue2128> for Python 2.
361 # All arguments are retrieved in unicode format and converted to utf-8.
362 # In this way, when launched from the command line, lyxpak.py can deal
363 # with any non-ascii names. Unfortunately, this is not the case when
364 # launched by LyX, because LyX converts the arguments of the converters
365 # to the filesystem encoding. On Windows this corresponds to the current
366 # code page and not to the UTF-16 encoding used by NTFS, such that they
367 # are transliterated if not exactly encodable. As an example, α may
368 # become a, β may become ß, and so on. However, this is a problem only
369 # if the full path of the LyX document contains an unencodable character
370 # as all other paths are extracted from the document in utf-8 format.
371 from ctypes import WINFUNCTYPE, windll, POINTER, byref, c_int
372 from ctypes.wintypes import LPWSTR, LPCWSTR
373 GetCommandLineW = WINFUNCTYPE(LPWSTR)(("GetCommandLineW", windll.kernel32))
374 CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(("CommandLineToArgvW", windll.shell32))
376 argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc))
377 # unicode_argv[0] is the Python interpreter, so skip that.
378 argv = [argv_unicode[i].encode('utf-8') for i in xrange(1, argc.value)]
379 # Also skip option arguments to the Python interpreter.
381 if not argv[0].startswith("-"):