]> git.lyx.org Git - lyx.git/blob - lib/scripts/lyxpak.py
Allow Insetlayout for Branch inset (#8106).
[lyx.git] / lib / scripts / lyxpak.py
1 #! /usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 # file lyxpak.py
5 # This file is part of LyX, the document processor.
6 # Licence details can be found in the file COPYING.
7
8 # author Enrico Forestieri
9 # author Richard Heck
10
11 # Full author contact details are available in file CREDITS
12
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.
18
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
23
24 # Pre-compiled regular expressions.
25 re_lyxfile = re.compile("\.lyx$")
26 re_input = re.compile(r'^(.*)\\(input|include){(\s*)(\S+)(\s*)}.*$')
27 re_ertinput = re.compile(r'^(input|include)({)(\s*)(\S+)(\s*)}.*$')
28 re_package = re.compile(r'^(.*)\\(usepackage){(\s*)(\S+)(\s*)}.*$')
29 re_class = re.compile(r'^(\\)(textclass)(\s+)(\S+)$')
30 re_norecur = re.compile(r'^(.*)\\(verbatiminput|lstinputlisting|includegraphics\[*.*\]*){(\s*)(\S+)(\s*)}.*$')
31 re_ertnorecur = re.compile(r'^(verbatiminput|lstinputlisting|includegraphics\[*.*\]*)({)(\s*)(\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+)$')
35
36
37 def usage(prog_name):
38     msg = '''
39 Usage: %s [-t] [-z] [-l path] [-o output_dir] file.lyx
40 Options:
41 -l: Path to lyx2lyx script
42 -o: Directory for output
43 -t: Create gzipped tar file
44 -z: Create zip 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.
48 '''
49     return msg % prog_name
50
51
52 def error(message):
53     sys.stderr.write(message + '\n')
54     sys.exit(1)
55
56
57 def run_cmd(cmd):
58     handle = os.popen(cmd, 'r')
59     cmd_stdout = handle.read()
60     cmd_status = handle.close()
61     return cmd_status, cmd_stdout
62
63
64 def find_exe(candidates, extlist, path):
65     for prog in candidates:
66         for directory in path:
67             for ext in extlist:
68                 full_path = os.path.join(directory, prog + ext)
69                 if os.access(full_path, os.X_OK):
70                     return prog, full_path
71     return None, None
72
73
74 def abspath(name):
75     " Resolve symlinks and returns the absolute normalized name."
76     newname = os.path.normpath(os.path.abspath(name))
77     if os.name != 'nt':
78         newname = os.path.realpath(newname)
79     return newname
80
81
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)
86     if is_lyxfile:
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()
92     else:
93         input = open(curfile, 'rU')
94         lines = input.readlines()
95         input.close()
96
97     maybe_in_ert = False
98     i = 0
99     while i < len(lines):
100         # Gather used files.
101         recursive = True
102         extlist = ['']
103         match = re_filename.match(lines[i])
104         if not match:
105             if maybe_in_ert:
106                 match = re_ertinput.match(lines[i])
107             else:
108                 match = re_input.match(lines[i])
109             if not match:
110                 match = re_package.match(lines[i])
111                 extlist = ['.sty']
112                 if not match:
113                     match = re_class.match(lines[i])
114                     extlist = ['.cls']
115                     if not match:
116                         if maybe_in_ert:
117                             match = re_ertnorecur.match(lines[i])
118                         else:
119                             match = re_norecur.match(lines[i])
120                         extlist = ['', '.eps', '.pdf', '.png', '.jpg']
121                         recursive = False
122         maybe_in_ert = is_lyxfile and lines[i] == "\\backslash"
123         if match:
124             file = match.group(4).strip('"')
125             if not os.path.isabs(file):
126                 file = os.path.join(curdir, file)
127             file_exists = False
128             if not os.path.isdir(file):
129                 for ext in extlist:
130                     if os.path.exists(file + ext):
131                         file = file + ext
132                         file_exists = True
133                         break
134             if file_exists and not abspath(file) in incfiles:
135                 incfiles.append(abspath(file))
136                 if recursive:
137                     gather_files(file, incfiles, lyx2lyx)
138             i += 1
139             continue
140
141         if not is_lyxfile:
142             i += 1
143             continue
144
145         # Gather bibtex *.bst files.
146         match = re_options.match(lines[i])
147         if match:
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))
153             i += 1
154             continue
155
156         # Gather bibtex *.bib files.
157         match = re_bibfiles.match(lines[i])
158         if match:
159             bibfiles = match.group(3).strip('"').split(',')
160             j = 0
161             while j < len(bibfiles):
162                 if os.path.isabs(bibfiles[j]):
163                     file = bibfiles[j]
164                 else:
165                     file = os.path.join(curdir, bibfiles[j] + '.bib')
166                 if os.path.exists(file):
167                     incfiles.append(abspath(file))
168                 j += 1
169             i += 1
170             continue
171
172         i += 1
173
174     return 0
175
176
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):
186         return tryit
187
188     # now we will try to query LyX itself to find the path.
189     extlist = ['']
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)
193     if lyx_exe == None:
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()
201     for line in lines:
202         match = re_msvc.match(line)
203         if match:
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')
208             break
209         match = re_sysdir.match(line)
210         if match:
211             tryit = os.path.join(match.group(4), 'lyx2lyx', 'lyx2lyx')
212             break
213
214     if not os.access(tryit, os.X_OK):
215         error('Unable to find the lyx2lyx script.')
216     return tryit
217
218
219 def main(args):
220
221     ourprog = args[0]
222
223     try:
224       (options, argv) = getopt(args[1:], "htzl:o:")
225     except:
226       error(usage(ourprog))
227
228     # we expect the filename to be left
229     if len(argv) != 1:
230         error(usage(ourprog))
231
232     makezip = (os.name == 'nt')
233     outdir = ""
234     lyx2lyx = None
235
236     for (opt, param) in options:
237       if opt == "-h":
238         print usage(ourprog)
239         sys.exit(0)
240       elif opt == "-t":
241         makezip = False
242       elif opt == "-z":
243         makezip = True
244       elif opt == "-l":
245         lyx2lyx = param
246       elif opt == "-o":
247         outdir = param
248         if not os.path.isdir(outdir):
249           error('Error: "%s" is not a directory.' % outdir)
250
251     lyxfile = argv[0]
252     if not os.path.exists(lyxfile):
253         error('File "%s" not found.' % lyxfile)
254
255     # Check that it actually is a LyX document
256     input = open(lyxfile, 'rU')
257     line = input.readline()
258     input.close()
259     if not (line and line.startswith('#LyX')):
260         error('File "%s" is not a LyX document.' % lyxfile)
261
262     if makezip:
263         import zipfile
264     else:
265         import tarfile
266
267     ar_ext = ".tar.gz"
268     if makezip:
269         ar_ext = ".zip"
270
271     ar_name = re_lyxfile.sub(ar_ext, abspath(lyxfile))
272     if outdir:
273         ar_name = os.path.join(abspath(outdir), os.path.basename(ar_name))
274
275     path = string.split(os.environ["PATH"], os.pathsep)
276
277     if lyx2lyx == None:
278         lyx2lyx = find_lyx2lyx(ourprog)
279
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)
284
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
292     else:
293         topdir = os.path.dirname(incfiles[0]) + os.path.sep
294
295     # Remove the prefix common to all paths in the list
296     i = 0
297     while i < len(incfiles):
298         incfiles[i] = string.replace(incfiles[i], topdir, '', 1)
299         i += 1
300
301     # Remove duplicates and sort the list
302     incfiles = list(set(incfiles))
303     incfiles.sort()
304
305     if topdir != '':
306         os.chdir(topdir)
307
308     # Create the archive
309     try:
310         if makezip:
311             zip = zipfile.ZipFile(ar_name, "w", zipfile.ZIP_DEFLATED)
312             for file in incfiles:
313                 zip.write(file)
314             zip.close()
315         else:
316             tar = tarfile.open(ar_name, "w:gz")
317             for file in incfiles:
318                 tar.add(file)
319             tar.close()
320     except:
321         error('Failed to create LyX archive "%s"' % ar_name)
322
323     print 'LyX archive "%s" created successfully.' % ar_name
324     return 0
325
326
327 if __name__ == "__main__":
328     main(sys.argv)