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