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