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