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