]> git.lyx.org Git - lyx.git/blob - lib/scripts/lyxpak.py
iucr.layout: use Item_Environment for a style as proposed by Jürgen
[lyx.git] / lib / scripts / lyxpak.py
1 # -*- coding: utf-8 -*-
2
3 # file lyxpak.py
4 # This file is part of LyX, the document processor.
5 # Licence details can be found in the file COPYING.
6
7 # author Enrico Forestieri
8 # author Richard Heck
9
10 # Full author contact details are available in file CREDITS
11
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.
17
18 import gzip, os, re, string, sys
19 if sys.version_info < (2, 4, 0):
20     from sets import Set as set
21 from getopt import getopt
22 from cStringIO import StringIO
23
24 # Pre-compiled regular expressions.
25 re_lyxfile = re.compile("\.lyx$")
26 re_input = re.compile(r'^(.*)\\(input|include){(\s*)(.+)(\s*)}.*$')
27 re_ertinput = re.compile(r'^(input|include)({)(\s*)(.+)(\s*)}.*$')
28 re_package = re.compile(r'^(.*)\\(usepackage){(\s*)(.+)(\s*)}.*$')
29 re_class = re.compile(r'^(\\)(textclass)(\s+)(.+)\s*$')
30 re_norecur = re.compile(r'^(.*)\\(verbatiminput|lstinputlisting|includegraphics\[*.*\]*){(\s*)(.+)(\s*)}.*$')
31 re_ertnorecur = re.compile(r'^(verbatiminput|lstinputlisting|includegraphics\[*.*\]*)({)(\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 gzopen(file, mode):
58     input = open(file, 'rb')
59     magicnum = input.read(2)
60     input.close()
61     if magicnum == "\x1f\x8b":
62         return gzip.open(file, mode)
63     return open(file, mode)
64
65
66 def run_cmd(cmd):
67     handle = os.popen(cmd, 'r')
68     cmd_stdout = handle.read()
69     cmd_status = handle.close()
70     return cmd_status, cmd_stdout
71
72
73 def find_exe(candidates, extlist, path):
74     for prog in candidates:
75         for directory in path:
76             for ext in extlist:
77                 full_path = os.path.join(directory, prog + ext)
78                 if os.access(full_path, os.X_OK):
79                     return prog, full_path
80     return None, None
81
82
83 def abspath(name):
84     " Resolve symlinks and returns the absolute normalized name."
85     newname = os.path.normpath(os.path.abspath(name))
86     if os.name != 'nt':
87         newname = os.path.realpath(newname)
88     return newname
89
90
91 def gather_files(curfile, incfiles, lyx2lyx):
92     " Recursively gather files."
93     curdir = os.path.dirname(abspath(curfile))
94     is_lyxfile = re_lyxfile.search(curfile)
95     if is_lyxfile:
96         lyx2lyx_cmd = 'python "%s" "%s"' % (lyx2lyx, curfile)
97         l2l_status, l2l_stdout = run_cmd(lyx2lyx_cmd)
98         if l2l_status != None:
99             error('%s failed to convert "%s"' % (lyx2lyx, curfile))
100         if l2l_stdout.startswith("\x1f\x8b"):
101             l2l_stdout = gzip.GzipFile("", "r", 0, StringIO(l2l_stdout)).read()
102         lines = l2l_stdout.splitlines()
103     else:
104         input = gzopen(curfile, 'rU')
105         lines = input.readlines()
106         input.close()
107
108     maybe_in_ert = False
109     i = 0
110     while i < len(lines):
111         # Gather used files.
112         recursive = True
113         extlist = ['']
114         match = re_filename.match(lines[i])
115         if not match:
116             if maybe_in_ert:
117                 match = re_ertinput.match(lines[i])
118             else:
119                 match = re_input.match(lines[i])
120             if not match:
121                 match = re_package.match(lines[i])
122                 extlist = ['.sty']
123                 if not match:
124                     match = re_class.match(lines[i])
125                     extlist = ['.cls']
126                     if not match:
127                         if maybe_in_ert:
128                             match = re_ertnorecur.match(lines[i])
129                         else:
130                             match = re_norecur.match(lines[i])
131                         extlist = ['', '.eps', '.pdf', '.png', '.jpg']
132                         recursive = False
133         maybe_in_ert = is_lyxfile and lines[i] == "\\backslash"
134         if match:
135             file = match.group(4).strip('"')
136             if not os.path.isabs(file):
137                 file = os.path.join(curdir, file)
138             file_exists = False
139             if not os.path.isdir(file):
140                 for ext in extlist:
141                     if os.path.exists(file + ext):
142                         file = file + ext
143                         file_exists = True
144                         break
145             if file_exists and not abspath(file) in incfiles:
146                 incfiles.append(abspath(file))
147                 if recursive:
148                     gather_files(file, incfiles, lyx2lyx)
149             i += 1
150             continue
151
152         if not is_lyxfile:
153             i += 1
154             continue
155
156         # Gather bibtex *.bst files.
157         match = re_options.match(lines[i])
158         if match:
159             file = match.group(3).strip('"')
160             if file.startswith("bibtotoc,"):
161                 file = file[9:]
162             if not os.path.isabs(file):
163                 file = os.path.join(curdir, file + '.bst')
164             if os.path.exists(file):
165                 incfiles.append(abspath(file))
166             i += 1
167             continue
168
169         # Gather bibtex *.bib files.
170         match = re_bibfiles.match(lines[i])
171         if match:
172             bibfiles = match.group(3).strip('"').split(',')
173             j = 0
174             while j < len(bibfiles):
175                 if os.path.isabs(bibfiles[j]):
176                     file = bibfiles[j] + '.bib'
177                 else:
178                     file = os.path.join(curdir, bibfiles[j] + '.bib')
179                 if os.path.exists(file):
180                     incfiles.append(abspath(file))
181                 j += 1
182             i += 1
183             continue
184
185         i += 1
186
187     return 0
188
189
190 def find_lyx2lyx(progloc, path):
191     " Find a usable version of the lyx2lyx script. "
192     # first we will see if the script is roughly where we are
193     # i.e., we will assume we are in $SOMEDIR/scripts and look
194     # for $SOMEDIR/lyx2lyx/lyx2lyx.
195     ourpath = os.path.dirname(abspath(progloc))
196     (upone, discard) = os.path.split(ourpath)
197     tryit = os.path.join(upone, "lyx2lyx", "lyx2lyx")
198     if os.access(tryit, os.X_OK):
199         return tryit
200
201     # now we will try to query LyX itself to find the path.
202     extlist = ['']
203     if "PATHEXT" in os.environ:
204         extlist = extlist + os.environ["PATHEXT"].split(os.pathsep)
205     lyx_exe, full_path = find_exe(["lyxc", "lyx"], extlist, path)
206     if lyx_exe == None:
207         error('Cannot find the LyX executable in the path.')
208     cmd_status, cmd_stdout = run_cmd("%s -version 2>&1" % lyx_exe)
209     if cmd_status != None:
210         error('Cannot query LyX about the lyx2lyx script.')
211     re_msvc = re.compile(r'^(\s*)(Host type:)(\s+)(win32)$')
212     re_sysdir = re.compile(r'^(\s*)(LyX files dir:)(\s+)(\S+)$')
213     lines = cmd_stdout.splitlines()
214     for line in lines:
215         match = re_msvc.match(line)
216         if match:
217             # The LyX executable was built with MSVC, so the
218             # "LyX files dir:" line is unusable
219             basedir = os.path.dirname(os.path.dirname(full_path))
220             tryit = os.path.join(basedir, 'Resources', 'lyx2lyx', 'lyx2lyx')
221             break
222         match = re_sysdir.match(line)
223         if match:
224             tryit = os.path.join(match.group(4), 'lyx2lyx', 'lyx2lyx')
225             break
226
227     if not os.access(tryit, os.X_OK):
228         error('Unable to find the lyx2lyx script.')
229     return tryit
230
231
232 def main(args):
233
234     ourprog = args[0]
235
236     try:
237       (options, argv) = getopt(args[1:], "htzl:o:")
238     except:
239       error(usage(ourprog))
240
241     # we expect the filename to be left
242     if len(argv) != 1:
243         error(usage(ourprog))
244
245     makezip = (os.name == 'nt')
246     outdir = ""
247     lyx2lyx = None
248
249     for (opt, param) in options:
250       if opt == "-h":
251         print usage(ourprog)
252         sys.exit(0)
253       elif opt == "-t":
254         makezip = False
255       elif opt == "-z":
256         makezip = True
257       elif opt == "-l":
258         lyx2lyx = param
259       elif opt == "-o":
260         outdir = param
261         if not os.path.isdir(outdir):
262           error('Error: "%s" is not a directory.' % outdir)
263
264     lyxfile = argv[0]
265     if not os.path.exists(lyxfile):
266         error('File "%s" not found.' % lyxfile)
267
268     # Check that it actually is a LyX document
269     input = gzopen(lyxfile, 'rU')
270     line = input.readline()
271     input.close()
272     if not (line and line.startswith('#LyX')):
273         error('File "%s" is not a LyX document.' % lyxfile)
274
275     if makezip:
276         import zipfile
277     else:
278         import tarfile
279
280     ar_ext = ".tar.gz"
281     if makezip:
282         ar_ext = ".zip"
283
284     ar_name = re_lyxfile.sub(ar_ext, abspath(lyxfile))
285     if outdir:
286         ar_name = os.path.join(abspath(outdir), os.path.basename(ar_name))
287
288     path = string.split(os.environ["PATH"], os.pathsep)
289
290     if lyx2lyx == None:
291         lyx2lyx = find_lyx2lyx(ourprog, path)
292
293     # Initialize the list with the specified LyX file and recursively
294     # gather all required files (also from child documents).
295     incfiles = [abspath(lyxfile)]
296     gather_files(lyxfile, incfiles, lyx2lyx)
297
298     # Find the topmost dir common to all files
299     if len(incfiles) > 1:
300         topdir = os.path.commonprefix(incfiles)
301         # Check whether topdir is valid, as os.path.commonprefix() works on
302         # a character by character basis, rather than on path elements.
303         if not os.path.exists(topdir):
304             topdir = os.path.dirname(topdir) + os.path.sep
305     else:
306         topdir = os.path.dirname(incfiles[0]) + os.path.sep
307
308     # Remove the prefix common to all paths in the list
309     i = 0
310     while i < len(incfiles):
311         incfiles[i] = string.replace(incfiles[i], topdir, '', 1)
312         i += 1
313
314     # Remove duplicates and sort the list
315     incfiles = list(set(incfiles))
316     incfiles.sort()
317
318     if topdir != '':
319         os.chdir(topdir)
320
321     # Create the archive
322     try:
323         if makezip:
324             zip = zipfile.ZipFile(ar_name, "w", zipfile.ZIP_DEFLATED)
325             for file in incfiles:
326                 zip.write(file)
327             zip.close()
328         else:
329             tar = tarfile.open(ar_name, "w:gz")
330             for file in incfiles:
331                 tar.add(file)
332             tar.close()
333     except:
334         error('Failed to create LyX archive "%s"' % ar_name)
335
336     print 'LyX archive "%s" created successfully.' % ar_name
337     return 0
338
339
340 if __name__ == "__main__":
341     main(sys.argv)