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