2 # This file is part of LyX, the document processor.
3 # Licence details can be found in the file COPYING.
5 # author Enrico Forestieri
6 # author Richard Kimberly Heck
8 # Full author contact details are available in file CREDITS
10 # This script creates a tar or zip archive with a lyx file and all included
11 # files (graphics and so on). By default, the created archive is the standard
12 # type on a given platform, such that a zip archive is created on Windows and
13 # a gzip compressed tar archive on *nix. This can be controlled by command
14 # line options, however.
16 import gzip, os, re, sys
17 from io import BytesIO
20 # The path to the current python executable. sys.executable may fail, so in
21 # this case we revert to simply calling "python" from the path.
22 PYTHON_BIN = sys.executable if sys.executable else "python"
24 running_on_windows = (os.name == 'nt')
26 if running_on_windows:
27 from shutil import copyfile
28 from tempfile import NamedTemporaryFile
29 from lyxwin_getopt import getopt
31 from getopt import getopt
33 # Pre-compiled regular expressions.
34 re_lyxfile = re.compile(br"\.lyx$")
35 re_input = re.compile(b'^(.*)\\\\(input|include){(\\s*)(.+)(\\s*)}.*$')
36 re_ertinput = re.compile(b'^(input|include)({)(\\s*)(.+)(\\s*)}.*$')
37 re_package = re.compile(b'^(.*)\\\\(usepackage){(\\s*)(.+)(\\s*)}.*$')
38 re_class = re.compile(b'^(\\\\)(textclass)(\\s+)(.+)\\s*$')
39 re_norecur = re.compile(b'^(.*)\\\\(verbatiminput|lstinputlisting|includegraphics\\[*.*\\]*){(\\s*)(.+)(\\s*)}.*$')
40 re_ertnorecur = re.compile(b'^(verbatiminput|lstinputlisting|includegraphics\\[*.*\\]*)({)(\\s*)(.+)(\\s*)}.*$')
41 re_filename = re.compile(b'^(\\s*)(filename)(\\s+)(.+)\\s*$')
42 re_options = re.compile(b'^(\\s*)options(\\s+)(.+)\\s*$')
43 re_bibfiles = re.compile(b'^(\\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')
67 return message.decode(sys.getfilesystemencoding())
71 input = open(file.decode('utf-8'), 'rb')
72 magicnum = input.read(2)
74 if magicnum == b"\x1f\x8b":
75 return gzip.open(file.decode('utf-8'))
76 return open(file.decode('utf-8'), 'rb')
79 def find_exe(candidates, extlist, path):
80 for prog in candidates:
81 for directory in path:
83 full_path = os.path.join(directory, prog + ext)
84 if os.access(full_path, os.X_OK):
85 return prog, full_path
90 " Resolve symlinks and returns the absolute normalized name."
91 newname = os.path.normpath(os.path.abspath(name))
92 if not running_on_windows:
93 newname = os.path.realpath(newname)
97 def gather_files(curfile, incfiles, lyx2lyx):
98 " Recursively gather files."
99 curdir = os.path.dirname(abspath(curfile))
100 is_lyxfile = re_lyxfile.search(curfile)
103 if running_on_windows:
104 # subprocess cannot cope with unicode arguments and we cannot be
105 # sure that curfile can be correctly converted to the current
106 # code page. So, we resort to running lyx2lyx on a copy.
107 tmp = NamedTemporaryFile(delete=False)
109 copyfile(curfile.decode('utf-8'), tmp.name)
111 l2l_stdout = subprocess.check_output([PYTHON_BIN, lyx2lyx, tmp.name])
112 except subprocess.CalledProcessError:
113 error(f'{lyx2lyx} failed to convert "{tostr(curfile)}"')
117 l2l_stdout = subprocess.check_output([PYTHON_BIN, lyx2lyx, curfile])
118 except subprocess.CalledProcessError:
119 error(f'{lyx2lyx} failed to convert "{tostr(curfile)}"')
120 if l2l_stdout.startswith(b"\x1f\x8b"):
121 l2l_stdout = gzip.GzipFile("", "rb", 0, BytesIO(l2l_stdout)).read()
122 elif running_on_windows:
123 # For some unknown reason, there can be a spurious '\r' in the line
124 # separators, causing spurious empty lines when calling splitlines.
125 l2l_stdout = l2l_stdout.replace(b'\r\r\n', b'\r\n')
126 lines = l2l_stdout.splitlines()
128 input = gzopen(curfile)
129 lines = input.readlines()
134 while i < len(lines):
138 match = re_filename.match(lines[i])
141 match = re_ertinput.match(lines[i])
143 match = re_input.match(lines[i])
145 match = re_package.match(lines[i])
148 match = re_class.match(lines[i])
152 match = re_ertnorecur.match(lines[i])
154 match = re_norecur.match(lines[i])
155 extlist = [b'', b'.eps', b'.pdf', b'.png', b'.jpg']
157 maybe_in_ert = is_lyxfile and lines[i] == b"\\backslash"
159 file = match.group(4).strip(b'"')
160 if not os.path.isabs(file):
161 file = os.path.join(curdir, file)
163 if not os.path.isdir(file):
165 if os.path.exists(file + ext):
169 if file_exists and not abspath(file) in incfiles:
170 incfiles.append(abspath(file))
172 gather_files(file, incfiles, lyx2lyx)
180 # Gather bibtex *.bst files.
181 match = re_options.match(lines[i])
183 file = match.group(3).strip(b'"')
184 if file.startswith(b"bibtotoc,"):
186 if not os.path.isabs(file):
187 file = os.path.join(curdir, file + b'.bst')
188 if os.path.exists(file):
189 incfiles.append(abspath(file))
193 # Gather bibtex *.bib files.
194 match = re_bibfiles.match(lines[i])
196 bibfiles = match.group(3).strip(b'"').split(b',')
198 while j < len(bibfiles):
199 if os.path.isabs(bibfiles[j]):
200 file = bibfiles[j] + b'.bib'
202 file = os.path.join(curdir, bibfiles[j] + b'.bib')
203 if os.path.exists(file):
204 incfiles.append(abspath(file))
214 def find_lyx2lyx(progloc, path):
215 " Find a usable version of the lyx2lyx script. "
216 # first we will see if the script is roughly where we are
217 # i.e., we will assume we are in $SOMEDIR/scripts and look
218 # for $SOMEDIR/lyx2lyx/lyx2lyx.
219 ourpath = os.path.dirname(abspath(progloc))
220 (upone, discard) = os.path.split(ourpath)
221 if running_on_windows:
222 tryit = os.path.join(upone, b"lyx2lyx", b"lyx2lyx")
224 tryit = os.path.join(upone, "lyx2lyx", "lyx2lyx")
225 if os.access(tryit, os.X_OK):
228 # now we will try to query LyX itself to find the path.
230 if "PATHEXT" in os.environ:
231 extlist = extlist + os.environ["PATHEXT"].split(os.pathsep)
232 lyx_exe, full_path = find_exe(["lyxc", "lyx"], extlist, path)
234 error('Cannot find the LyX executable in the path.')
236 cmd_stdout = subprocess.check_output([lyx_exe, '-version'], stderr=subprocess.STDOUT)
237 except subprocess.CalledProcessError:
238 error('Cannot query LyX about the lyx2lyx script.')
239 re_msvc = re.compile(r'^(\s*)(Host type:)(\s+)(win32)$')
240 re_sysdir = re.compile(r'^(\s*)(LyX files dir:)(\s+)(\S+)$')
241 lines = cmd_stdout.splitlines()
243 match = re_msvc.match(line)
245 # The LyX executable was built with MSVC, so the
246 # "LyX files dir:" line is unusable
247 basedir = os.path.dirname(os.path.dirname(full_path))
248 tryit = os.path.join(basedir, 'Resources', 'lyx2lyx', 'lyx2lyx')
250 match = re_sysdir.match(line)
252 tryit = os.path.join(match.group(4), 'lyx2lyx', 'lyx2lyx')
255 if not os.access(tryit, os.X_OK):
256 error('Unable to find the lyx2lyx script.')
265 if running_on_windows:
266 (options, argv) = getopt(args[1:], b"htzl:o:")
268 (options, argv) = getopt(args[1:], "htzl:o:")
270 error(usage(ourprog))
272 # we expect the filename to be left
274 error(usage(ourprog))
276 makezip = running_on_windows
280 for (opt, param) in options:
282 print(usage(ourprog))
292 if not os.path.isdir(outdir):
293 error('Error: "%s" is not a directory.' % outdir)
296 if not os.path.exists(lyxfile):
297 error('File "%s" not found.' % tostr(lyxfile))
299 # Check that it actually is a LyX document
300 input = gzopen(lyxfile)
301 line = input.readline()
303 if not (line and line.startswith(b'#LyX')):
304 error('File "%s" is not a LyX document.' % tostr(lyxfile))
315 ar_name = re_lyxfile.sub(ar_ext, abspath(lyxfile)).decode('utf-8')
317 ar_name = os.path.join(abspath(outdir), os.path.basename(ar_name))
319 path = os.environ["PATH"].split(os.pathsep)
322 lyx2lyx = find_lyx2lyx(ourprog, path)
324 # Initialize the list with the specified LyX file and recursively
325 # gather all required files (also from child documents).
326 incfiles = [abspath(lyxfile)]
327 gather_files(lyxfile, incfiles, lyx2lyx)
329 # Find the topmost dir common to all files
330 path_sep = os.path.sep.encode('utf-8')
331 if len(incfiles) > 1:
332 topdir = os.path.commonprefix(incfiles)
333 # As os.path.commonprefix() works on a character by character basis,
334 # rather than on path elements, we need to remove any trailing bytes.
335 topdir = topdir.rpartition(path_sep)[0] + path_sep
337 topdir = os.path.dirname(incfiles[0]) + path_sep
339 # Remove the prefix common to all paths in the list
341 while i < len(incfiles):
342 incfiles[i] = incfiles[i].replace(topdir, b'', 1)
345 # Remove duplicates and sort the list
346 incfiles = list(set(incfiles))
355 zip = zipfile.ZipFile(ar_name, "w", zipfile.ZIP_DEFLATED)
356 for file in incfiles:
357 zip.write(file.decode('utf-8'))
360 tar = tarfile.open(ar_name, "w:gz")
361 for file in incfiles:
362 tar.add(file.decode('utf-8'))
365 error('Failed to create LyX archive "%s"' % ar_name)
367 print('LyX archive "%s" created successfully.' % ar_name)
371 if __name__ == "__main__":
372 if running_on_windows:
373 # This works around <http://bugs.python.org/issue2128> for Python 2.
374 # All arguments are retrieved in unicode format and converted to utf-8.
375 # In this way, when launched from the command line, lyxpak.py can deal
376 # with any non-ascii names. Unfortunately, this is not the case when
377 # launched by LyX, because LyX converts the arguments of the converters
378 # to the filesystem encoding. On Windows this corresponds to the current
379 # code page and not to the UTF-16 encoding used by NTFS, such that they
380 # are transliterated if not exactly encodable. As an example, α may
381 # become a, β may become ß, and so on. However, this is a problem only
382 # if the full path of the LyX document contains an unencodable character
383 # as all other paths are extracted from the document in utf-8 format.
384 from ctypes import WINFUNCTYPE, windll, POINTER, byref, c_int
385 from ctypes.wintypes import LPWSTR, LPCWSTR
386 GetCommandLineW = WINFUNCTYPE(LPWSTR)(("GetCommandLineW", windll.kernel32))
387 CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(("CommandLineToArgvW", windll.shell32))
389 argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc))
390 # unicode_argv[0] is the Python interpreter, so skip that.
391 argv = [argv_unicode[i].encode('utf-8') for i in range(1, argc.value)]
392 # Also skip option arguments to the Python interpreter.
394 if not argv[0].startswith(b"-"):