]> git.lyx.org Git - lyx.git/blob - lib/scripts/lyxpak.py
Avoid requiring messages with empty language.
[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 file.startswith("bibtotoc,"):
149                 file = file[9:]
150             if not os.path.isabs(file):
151                 file = os.path.join(curdir, file + '.bst')
152             if os.path.exists(file):
153                 incfiles.append(abspath(file))
154             i += 1
155             continue
156
157         # Gather bibtex *.bib files.
158         match = re_bibfiles.match(lines[i])
159         if match:
160             bibfiles = match.group(3).strip('"').split(',')
161             j = 0
162             while j < len(bibfiles):
163                 if os.path.isabs(bibfiles[j]):
164                     file = bibfiles[j] + '.bib'
165                 else:
166                     file = os.path.join(curdir, bibfiles[j] + '.bib')
167                 if os.path.exists(file):
168                     incfiles.append(abspath(file))
169                 j += 1
170             i += 1
171             continue
172
173         i += 1
174
175     return 0
176
177
178 def find_lyx2lyx(progloc, path):
179     " Find a usable version of the lyx2lyx script. "
180     # first we will see if the script is roughly where we are
181     # i.e., we will assume we are in $SOMEDIR/scripts and look
182     # for $SOMEDIR/lyx2lyx/lyx2lyx.
183     ourpath = os.path.dirname(abspath(progloc))
184     (upone, discard) = os.path.split(ourpath)
185     tryit = os.path.join(upone, "lyx2lyx", "lyx2lyx")
186     if os.access(tryit, os.X_OK):
187         return tryit
188
189     # now we will try to query LyX itself to find the path.
190     extlist = ['']
191     if "PATHEXT" in os.environ:
192         extlist = extlist + os.environ["PATHEXT"].split(os.pathsep)
193     lyx_exe, full_path = find_exe(["lyxc", "lyx"], extlist, path)
194     if lyx_exe == None:
195         error('Cannot find the LyX executable in the path.')
196     cmd_status, cmd_stdout = run_cmd("%s -version 2>&1" % lyx_exe)
197     if cmd_status != None:
198         error('Cannot query LyX about the lyx2lyx script.')
199     re_msvc = re.compile(r'^(\s*)(Host type:)(\s+)(win32)$')
200     re_sysdir = re.compile(r'^(\s*)(LyX files dir:)(\s+)(\S+)$')
201     lines = cmd_stdout.splitlines()
202     for line in lines:
203         match = re_msvc.match(line)
204         if match:
205             # The LyX executable was built with MSVC, so the
206             # "LyX files dir:" line is unusable
207             basedir = os.path.dirname(os.path.dirname(full_path))
208             tryit = os.path.join(basedir, 'Resources', 'lyx2lyx', 'lyx2lyx')
209             break
210         match = re_sysdir.match(line)
211         if match:
212             tryit = os.path.join(match.group(4), 'lyx2lyx', 'lyx2lyx')
213             break
214
215     if not os.access(tryit, os.X_OK):
216         error('Unable to find the lyx2lyx script.')
217     return tryit
218
219
220 def main(args):
221
222     ourprog = args[0]
223
224     try:
225       (options, argv) = getopt(args[1:], "htzl:o:")
226     except:
227       error(usage(ourprog))
228
229     # we expect the filename to be left
230     if len(argv) != 1:
231         error(usage(ourprog))
232
233     makezip = (os.name == 'nt')
234     outdir = ""
235     lyx2lyx = None
236
237     for (opt, param) in options:
238       if opt == "-h":
239         print usage(ourprog)
240         sys.exit(0)
241       elif opt == "-t":
242         makezip = False
243       elif opt == "-z":
244         makezip = True
245       elif opt == "-l":
246         lyx2lyx = param
247       elif opt == "-o":
248         outdir = param
249         if not os.path.isdir(outdir):
250           error('Error: "%s" is not a directory.' % outdir)
251
252     lyxfile = argv[0]
253     if not os.path.exists(lyxfile):
254         error('File "%s" not found.' % lyxfile)
255
256     # Check that it actually is a LyX document
257     input = open(lyxfile, 'rU')
258     line = input.readline()
259     input.close()
260     if not (line and line.startswith('#LyX')):
261         error('File "%s" is not a LyX document.' % lyxfile)
262
263     if makezip:
264         import zipfile
265     else:
266         import tarfile
267
268     ar_ext = ".tar.gz"
269     if makezip:
270         ar_ext = ".zip"
271
272     ar_name = re_lyxfile.sub(ar_ext, abspath(lyxfile))
273     if outdir:
274         ar_name = os.path.join(abspath(outdir), os.path.basename(ar_name))
275
276     path = string.split(os.environ["PATH"], os.pathsep)
277
278     if lyx2lyx == None:
279         lyx2lyx = find_lyx2lyx(ourprog, path)
280
281     # Initialize the list with the specified LyX file and recursively
282     # gather all required files (also from child documents).
283     incfiles = [abspath(lyxfile)]
284     gather_files(lyxfile, incfiles, lyx2lyx)
285
286     # Find the topmost dir common to all files
287     if len(incfiles) > 1:
288         topdir = os.path.commonprefix(incfiles)
289         # Check whether topdir is valid, as os.path.commonprefix() works on
290         # a character by character basis, rather than on path elements.
291         if not os.path.exists(topdir):
292             topdir = os.path.dirname(topdir) + os.path.sep
293     else:
294         topdir = os.path.dirname(incfiles[0]) + os.path.sep
295
296     # Remove the prefix common to all paths in the list
297     i = 0
298     while i < len(incfiles):
299         incfiles[i] = string.replace(incfiles[i], topdir, '', 1)
300         i += 1
301
302     # Remove duplicates and sort the list
303     incfiles = list(set(incfiles))
304     incfiles.sort()
305
306     if topdir != '':
307         os.chdir(topdir)
308
309     # Create the archive
310     try:
311         if makezip:
312             zip = zipfile.ZipFile(ar_name, "w", zipfile.ZIP_DEFLATED)
313             for file in incfiles:
314                 zip.write(file)
315             zip.close()
316         else:
317             tar = tarfile.open(ar_name, "w:gz")
318             for file in incfiles:
319                 tar.add(file)
320             tar.close()
321     except:
322         error('Failed to create LyX archive "%s"' % ar_name)
323
324     print 'LyX archive "%s" created successfully.' % ar_name
325     return 0
326
327
328 if __name__ == "__main__":
329     main(sys.argv)