Debian Codegraph @

lib/dbtexmf/core/dbtex.py

raw ◀ ▶
Source reconstructed at patch state 1 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
1 #
2 # DbTex base class handling the compilation of a DocBook file via
3 # XSL Transformation and some TeX engine compilation.
4 #
5 from __future__ import print_function
6
7 import sys
8 import os
9 import re
10 import shlex
11 import tempfile
12 import shutil
13 try:
14 from urllib import pathname2url
15 except ImportError:
16 from urllib.request import pathname2url
17 import glob
18 import importlib
19 from optparse import OptionParser
20 from io import open
21
22 from dbtexmf.core.txtparser import texinputs_parse, texstyle_parse
23 from dbtexmf.core.confparser import DbtexConfig
24 from dbtexmf.xslt import xslt
25 import dbtexmf.core.logger as logger
26 from dbtexmf.core.error import signal_error, failed_exit, dump_stack
27
28
29 def suffix_replace(path, oldext, newext=""):
30 (root, ext) = os.path.splitext(path)
31 if ext == oldext:
32 return (root+newext)
33 else:
34 return (path+newext)
35
36 def path_to_uri(path):
37 if os.name == 'nt':
38 return 'file:' + pathname2url(path).replace('|', ':', 1)
39 else:
40 return pathname2url(path)
41
42
43 class Document:
44 """
45 Wrapper structure of the files built during the compilation per document
46 """
47 def __init__(self, filename, binfmt="pdf"):
48 self.inputname = filename
49 self.basename = os.path.splitext(filename)[0]
50 self.rawfile = self.basename + ".rtex"
51 self.texfile = self.basename + ".tex"
52 self.binfile = self.basename + "." + binfmt
53
54 def has_subext(self, ext):
55 return (os.path.splitext(self.basename)[1] == ext)
56
57 def __eq__(self, other):
58 if self.rawfile == other:
59 return True
60 if self.texfile == other:
61 return True
62 if self.binfile == other:
63 return True
64 return False
65
66 def __ne__(self, other):
67 return not self.__eq__(other)
68
69 def __lt__(self, other):
70 return self.__ne__(other)
71
72 def __le__(self, other):
73 return False
74
75 def __gt__(self, other):
76 return False
77
78 def __ge__(self, other):
79 return False
80
81
82 class DbTex:
83 USE_MKLISTINGS = 1
84
85 xsl_header = \
86 """<?xml version="1.0"?>
87 <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
88 xmlns:m="http://www.w3.org/1998/Math/MathML"
89 version="1.0">
90 \n"""
91
92 def __init__(self, base=""):
93 self.name = None
94 self.debug = 0
95 self.verbose = 0
96 if base:
97 self.set_base(base)
98 self.xslopts = []
99 self.xslparams = []
100 self.xslusers = []
101 self.flags = self.USE_MKLISTINGS
102 self.stdindir = ""
103 self.inputdir = ""
104 self.input = ""
105 self.input_format = "xml"
106 self.outputdir = ""
107 self.output = ""
108 self.format = "pdf"
109 self.tmpdir = ""
110 self.tmpdir_user = None
111 self.fig_paths = []
112 self.bib_paths = []
113 self.bst_paths = []
114 self.texinputs = []
115 self.texbatch = 1
116 self.texpost = ""
117 self.fig_format = ""
118 self.backend = ""
119
120 # Temporary files
121 self.documents = []
122 self.interms = []
123 self.included = []
124 self.basefile = ""
125 self.rawfile = ""
126
127 # Engines to use
128 self.runtex = None
129 self.rawtex = None
130 self.xsltproc = None
131 self.sgmlxml = None
132
133 def set_base(self, topdir):
134 self.topdir = os.path.realpath(topdir)
135 self.xslmain = os.path.join(self.topdir, "xsl", "docbook.xsl")
136 self.xsllist = os.path.join(self.topdir, "xsl", "common", "mklistings.xsl")
137 self.xslset = os.path.join(self.topdir, "xsl", "common", "mkdoclist.xsl")
138 self.texdir = os.path.join(self.topdir, "texstyle")
139 self.texlocal = ""
140 self.confdir = os.path.join(self.topdir, "confstyle")
141
142 def update_texinputs(self):
143 sep = os.pathsep
144 # Get a uniform list of paths (not a list of lists)
145 ti = []
146 for t in self.texinputs:
147 ti += t.split(sep)
148
149 # Systematically put the package style in TEXINPUTS
150 ti_opts = ti + [self.texdir + "//"]
151
152 # The original environment variable
153 texinputs = os.getenv("TEXINPUTS") or ""
154 ti_env = texinputs.split(sep)
155
156 # Find where system default is in the paths
157 try:
158 syspos = ti_env.index('')
159 except:
160 # By default system has precedence (i.e. is the first one)
161 ti_env = [''] + ti_env
162 syspos = 0
163
164 ti_before = ti_env[:syspos]
165 ti_after = ti_env[syspos+1:]
166
167 # Paths passed by options have no precedence over the system
168 ti_after = ti_opts + ti_after
169
170 # Texlocal has precedence over the standard (and added) paths
171 if self.texlocal:
172 ti_before = [ self.texlocal + "//" ] + ti_before
173
174 # Export the whole paths
175 texinputs = sep.join(ti_before + [''] + ti_after)
176 os.environ["TEXINPUTS"] = texinputs
177
178 def set_xslt(self, xsltmod=None):
179 # Set the XSLT to use. Set a default XSLT if none specified.
180 # One can replace an already defined XSLT if explicitely required.
181 if not(xsltmod):
182 if self.xsltproc:
183 return
184 xsltmod = "xsltproc"
185 self.xsltproc = xslt.load(xsltmod)
186
187 def set_backend(self):
188 # Set the backend to use or retrieve the default one
189 if self.backend:
190 self.runtex.set_backend(self.backend)
191 else:
192 self.backend = self.runtex.get_backend()
193
194 def set_format(self, format):
195 if not(format in ("rtex", "tex", "dvi", "ps", "pdf")):
196 raise ValueError("unknown format '%s'" % format)
197 else:
198 self.format = format
199
200 def unset_flags(self, what):
201 self.flags &= ~what
202
203 def get_version(self):
204 f = open(os.path.join(self.topdir, "xsl", "version.xsl"), "rt", encoding="latin-1")
205 versions = re.findall("<xsl:variable[^>]*>([^<]*)<", f.read())
206 f.close()
207 if versions:
208 return versions[0].strip()
209 else:
210 return "unknown"
211
212 def build_stylesheet(self, wrapper="custom.xsl"):
213 if not(self.xslparams or self.xslusers):
214 self.xslbuild = self.xslmain
215 return
216
217 f = open(wrapper, "wt", encoding="latin-1")
218 f.write(self.xsl_header)
219 f.write('<xsl:import href="%s"/>\n' % path_to_uri(self.xslmain))
220 for xsluser in self.xslusers:
221 f.write('<xsl:import href="%s"/>\n' % path_to_uri(xsluser))
222
223 # Reverse to set the latest parameter first (case of overriding)
224 self.xslparams.reverse()
225 for param in self.xslparams:
226 v = param.split("=", 1)
227 f.write('<xsl:param name="%s">' % v[0])
228 if len(v) == 2:
229 f.write('%s' % v[1])
230 f.write('</xsl:param>\n')
231
232 f.write('</xsl:stylesheet>\n')
233 f.close()
234 self.xslbuild = os.path.realpath(wrapper)
235
236 def make_xml(self):
237 self.log.info("Build the XML file...")
238 xmlfile = self.basefile + ".xml"
239 self.sgmlxml.run(self.input, xmlfile)
240 self.input = xmlfile
241
242 def make_listings(self):
243 self.listings = os.path.join(self.tmpdir, "listings.xml")
244 if (self.flags & self.USE_MKLISTINGS):
245 self.log.info("Build the listings...")
246 param = {"current.dir": self.inputdir}
247 self.xsltproc.use_catalogs = 0
248 self.xsltproc.run(self.xsllist, self.input,
249 self.listings, opts=self.xslopts, params=param)
250 else:
251 self.log.info("No external file support")
252 f = open(self.listings, "wt", encoding="latin-1")
253 f.write("<listings/>\n")
254 f.close()
255
256 def _single_setup(self):
257 # If not specified the output name can be deduced from the input one:
258 # /path/to/input.{xml|sgml} -> /path/to/input.{tex|pdf|dvi|ps}
259 if not(self.output):
260 output = suffix_replace(self.input, "."+self.input_format,
261 ".%s" % self.format)
262 self.output = output
263
264 self.documents.append(Document(self.basefile + \
265 "." + self.input_format,
266 binfmt=self.format))
267
268 def _multiple_setup(self, doclist):
269 # If not specified, output the chunked books in the working dir
270 if not(self.outputdir):
271 self.log.info("No specified output dir (-O). "\
272 "Use the working directory")
273 self.outputdir = self.cwdir
274
275 f = open(doclist, "rt", encoding="latin-1")
276 books = f.readlines()
277 f.close()
278
279 for b in books:
280 d = Document(b.strip() + ".tex", binfmt=self.format)
281 self.documents.append(d)
282
283 def build_doclist(self):
284 # The stylesheet must include the building stylesheets to have the
285 # actual parameter values (e.g. set.book.num) needed to give the book
286 # set list
287 self.log.info("Build the book set list...")
288 xslset = "doclist.xsl"
289 f = open(xslset, "wt", encoding="latin-1")
290 f.write(self.xsl_header)
291 f.write('<xsl:import href="%s"/>\n' % path_to_uri(self.xslbuild))
292 f.write('<xsl:import href="%s"/>\n' % path_to_uri(self.xslset))
293 f.write('</xsl:stylesheet>\n')
294 f.close()
295
296 doclist = os.path.join(self.tmpdir, "doclist.txt")
297 self.xsltproc.use_catalogs = 0
298 self.xsltproc.run(xslset, self.input, doclist, opts=self.xslopts)
299
300 # If <doclist> is missing or is empty, there's no set, or only one
301 # book from the set is compiled
302 if os.path.isfile(doclist) and os.path.getsize(doclist) > 0:
303 self._multiple_setup(doclist)
304 else:
305 self._single_setup()
306
307 def make_rawtex(self):
308 if len(self.documents) == 1:
309 self.rawfile = self.documents[0].rawfile
310 else:
311 self.rawfile = "output.rtex"
312
313 param = {"listings.xml": self.listings,
314 "current.dir": self.inputdir}
315 self.xsltproc.use_catalogs = 1
316 self.xsltproc.run(self.xslbuild, self.input,
317 self.rawfile, opts=self.xslopts, params=param)
318
319 # Now, find the intermediate raw files
320 rawfiles = glob.glob("*.rtex")
321 for rawfile in rawfiles:
322 if not(rawfile in self.documents):
323 d = Document(rawfile, binfmt=self.format)
324 if d.has_subext(".input"):
325 self.included.append(d)
326 else:
327 self.interms.append(d)
328
329 def make_tex(self):
330 self.rawtex.set_format(self.format, self.backend)
331 if self.fig_format:
332 self.rawtex.fig_format(self.fig_format)
333
334 # By default figures are relative to the source file directory
335 self.rawtex.set_fig_paths([self.inputdir] + self.fig_paths)
336
337 for d in self.documents + self.interms + self.included:
338 self.rawtex.parse(d.rawfile, d.texfile)
339
340 def make_bin(self):
341 self.runtex.texpost = self.texpost
342 self.runtex.set_fig_paths([self.inputdir] + self.fig_paths)
343 self.runtex.set_bib_paths([self.inputdir] + self.bib_paths,
344 [self.inputdir] + self.bst_paths)
345
346 # Build the intermediate files and (after) the main documents
347 for d in self.interms + self.documents:
348 self.log.info("Build %s" % d.binfile)
349 self.runtex.compile(d.texfile, d.binfile, self.format,
350 batch=self.texbatch)
351 # Only reinit, to not lose the produced working files
352 # used to track the dependencies on other documents
353 self.runtex.reinit()
354
355 def compile(self):
356 self.set_xslt()
357 self.set_backend()
358 self.cwdir = os.getcwd()
359 self.tmpdir = self.tmpdir_user or tempfile.mkdtemp()
360 if self.input:
361 self.inputdir = os.path.dirname(self.input)
362 else:
363 self._stdin_write()
364 os.chdir(self.tmpdir)
365 try:
366 donefiles = self._compile()
367 if len(donefiles) == 1:
368 shutil.move(donefiles[0], self.output)
369 self.log.info("'%s' successfully built" % \
370 os.path.basename(self.output))
371 else:
372 for d in donefiles:
373 shutil.move(d, self.outputdir)
374 donefiles.sort()
375 self.log.info("Files successfully built in '%s':\n%s" % \
376 (self.outputdir, "\n".join(donefiles)))
377 finally:
378 os.chdir(self.cwdir)
379 if not(self.debug):
380 shutil.rmtree(self.tmpdir)
381 else:
382 self.log.info("%s not removed" % self.tmpdir)
383
384 def _stdin_write(self):
385 # Find out the stdin working directory
386 self.inputdir = self.stdindir or self.cwdir
387
388 # Need to dump the stdin input, because of the two passes
389 self.input = os.path.join(self.tmpdir, "stdin.xml")
390 if sys.stdin.encoding is None:
391 f = open(self.input, "wb")
392 else:
393 f = open(self.input, "wt", encoding=sys.stdin.encoding)
394 for line in sys.stdin:
395 f.write(line)
396 f.close()
397
398 def _compile(self):
399 # The temporary output file
400 tmpout = os.path.basename(self.input)
401 for s in (" ", "\t"):
402 tmpout = tmpout.replace(s, "_")
403 self.basefile = suffix_replace(tmpout, "." + self.input_format)
404
405 # Convert SGML to XML if needed
406 if self.input_format == "sgml":
407 self.make_xml()
408
409 # Build the user XSL stylesheet if needed
410 self.build_stylesheet()
411
412 # List the documents to build
413 self.build_doclist()
414
415 # Refresh the TEXINPUTS
416 self.update_texinputs()
417
418 # For easy debug
419 if self.debug and "TEXINPUTS" in os.environ:
420 if os.name != "nt":
421 f = open("env_tex", "wt")
422 f.write("TEXINPUTS=%s\nexport TEXINPUTS\n" % \
423 os.environ["TEXINPUTS"])
424 f.close()
425 else:
426 f = open("env_tex.bat", "wt")
427 f.write("set TEXINPUTS=%s\n" % os.environ["TEXINPUTS"])
428 f.close()
429
430 # Build the tex file(s), and compile it(them)
431 self.make_listings()
432 self.make_rawtex()
433 if self.format == "rtex":
434 return [ d.rawfile for d in self.documents ]
435
436 self.make_tex()
437 if self.format == "tex":
438 return [ d.texfile for d in self.documents ]
439
440 self.make_bin()
441 return [ d.binfile for d in self.documents ]
442
443
444 #
445 # Command entry point
446 #
447 class DbTexCommand:
448 def __init__(self, base):
449 prog = os.path.splitext(os.path.basename(sys.argv[0]))[0]
450 usage = "%s [options] file" % prog
451 parser = OptionParser(usage=usage)
452 parser.add_option("-b", "--backend",
453 help="Backend driver to use. The available drivers"
454 " are 'pdftex' (default), 'dvips' and 'xetex'.")
455 parser.add_option("-B", "--no-batch", action="store_true",
456 help="All the tex output is printed")
457 parser.add_option("-c", "-S", "--config", action="append",
458 help="Configuration file")
459 parser.add_option("-C", "--changedir",
460 help="Standard input working directory")
461 parser.add_option("-d", "--debug", action="store_true",
462 help="Debug mode. Keep the temporary directory in "
463 "which %s actually works" % prog)
464 parser.add_option("-D", "--dump", action="store_true",
465 help="Dump error stack (debug purpose)")
466 parser.add_option("-e", "--indexstyle",
467 help="Index Style file to pass to makeindex")
468 parser.add_option("-f", "--fig-format",
469 help="Input figure format, used when not deduced "
470 "from figure extension")
471 parser.add_option("-F", "--input-format",
472 help="Input file format: sgml, xml. (default=xml)")
473 parser.add_option("-i", "--texinputs", action="append",
474 help="Path added to TEXINPUTS")
475 parser.add_option("-I", "--fig-path", action="append",
476 dest="fig_paths", metavar="FIG_PATH",
477 help="Additional lookup path of the figures")
478 parser.add_option("-l", "--bst-path", action="append",
479 dest="bst_paths", metavar="BST_PATH",
480 help="Bibliography style file path")
481 parser.add_option("-L", "--bib-path", action="append",
482 dest="bib_paths", metavar="BIB_PATH",
483 help="BibTeX database path")
484 parser.add_option("-m", "--xslt",
485 help="XSLT engine to use. (default=xsltproc)")
486 parser.add_option("-o", "--output", dest="output",
487 help="Output filename. "
488 "When not used, the input filename "
489 "is used, with the suffix of the output format")
490 parser.add_option("-O", "--output-dir",
491 help="Output directory for the built books."
492 " When not defined, the current working "
493 "directory is used. Option used only for "
494 "a document having a <set>")
495 parser.add_option("-p", "--xsl-user", action="append",
496 help="XSL user configuration file to use")
497 parser.add_option("-P", "--param", dest="xslparams",
498 action="append", metavar="PARAM=VALUE",
499 help="Set an XSL parameter value from command line")
500 parser.add_option("-q", "--quiet", action="store_true",
501 help="Less verbose, showing only error messages")
502 parser.add_option("-r", "--texpost", metavar="SCRIPT",
503 help="Script called at the very end of the tex "
504 "compilation. Its role is to modify the tex file "
505 "or one of the compilation file before the last "
506 "round.")
507 parser.add_option("-s", "--texstyle", metavar="STYFILE",
508 help="Latex style to apply. It can be a package name, or "
509 "directly a package path that must ends with "
510 "'.sty'")
511 parser.add_option("-t", "--type", dest="format",
512 help="Output format. Available formats:\n"
513 "tex, dvi, ps, pdf (default=pdf)")
514 parser.add_option("--dvi", action="store_true", dest="format_dvi",
515 help="DVI output. Equivalent to -tdvi")
516 parser.add_option("--pdf", action="store_true", dest="format_pdf",
517 help="PDF output. Equivalent to -tpdf")
518 parser.add_option("--ps", action="store_true", dest="format_ps",
519 help="PostScript output. Equivalent to -tps")
520 parser.add_option("-T", "--style",
521 help="Predefined output style")
522 parser.add_option("--tmpdir",
523 help="Temporary working directory to use (for debug only)")
524 parser.add_option("-v", "--version", action="store_true",
525 help="Print the %s version" % prog)
526 parser.add_option("-V", "--verbose", action="store_true",
527 help="Verbose mode, showing the running commands")
528 parser.add_option("-x", "--xslt-opts", dest="xslopts",
529 action="append", metavar="XSLT_OPTIONS",
530 help="Arguments directly passed to the XSLT engine")
531 parser.add_option("-X", "--no-external", action="store_true",
532 help="Disable the external text file support used for "
533 "some callout processing")
534
535 self.parser = parser
536 self.base = base
537 self.prog = prog
538 # The actual engine to use is unknown
539 self.run = None
540
541 def load_plugin(self, pathname):
542 moddir, modname = os.path.split(pathname)
543 spec = importlib.machinery.PathFinder.find_spec(modname, [moddir])
544 if not spec:
545 spec = importlib.machinery.PathFinder.find_spec(modname)
546 if not spec:
547 failed_exit("Error: '%s' module not found" % modname)
548 mod = importlib.util.module_from_spec(spec)
549 spec.loader.exec_module(mod)
550 sys.modules[modname] = mod
551 return mod
552
553 def run_setup(self, options):
554 run = self.run
555
556 if not(options.format):
557 if options.format_pdf:
558 options.format = "pdf"
559 elif options.format_ps:
560 options.format = "ps"
561 elif options.format_dvi:
562 options.format = "dvi"
563
564 if options.format:
565 try:
566 run.set_format(options.format)
567 except Exception as e:
568 failed_exit("Error: %s" % e)
569
570 # Always set the XSLT (default or not)
571 try:
572 run.set_xslt(options.xslt)
573 except Exception as e:
574 failed_exit("Error: %s" % e)
575
576 if options.xslopts:
577 for o in options.xslopts:
578 run.xslopts += shlex.split(o)
579
580 if options.xslparams:
581 run.xslparams += options.xslparams
582
583 if options.debug:
584 run.debug = options.debug
585
586 if options.fig_paths:
587 run.fig_paths += [os.path.realpath(p) for p in options.fig_paths]
588
589 if options.bib_paths:
590 run.bib_paths += [os.path.realpath(p) for p in options.bib_paths]
591
592 if options.bst_paths:
593 run.bst_paths += [os.path.realpath(p) for p in options.bst_paths]
594
595 if options.texstyle:
596 try:
597 xslparam, texpath = texstyle_parse(options.texstyle)
598 except Exception as e:
599 failed_exit("Error: %s" % e)
600 run.xslparams.append(xslparam)
601 if texpath: run.texinputs.append(texpath)
602
603 if options.indexstyle:
604 run.runtex.index_style = os.path.abspath(options.indexstyle)
605
606 if options.texinputs:
607 for texinputs in options.texinputs:
608 run.texinputs += texinputs_parse(texinputs)
609
610 if options.fig_format:
611 run.fig_format = options.fig_format
612
613 if options.input_format:
614 run.input_format = options.input_format
615
616 if options.no_batch:
617 run.texbatch = 0
618
619 if options.backend:
620 run.backend = options.backend
621
622 if options.xsl_user:
623 for xfile in options.xsl_user:
624 xsluser = os.path.realpath(xfile)
625 if not(os.path.isfile(xsluser)):
626 failed_exit("Error: '%s' does not exist" % options.xsl_user)
627 run.xslusers.append(xsluser)
628
629 if options.texpost:
630 is_plugin = options.texpost.startswith("plugin:")
631 if is_plugin:
632 path = self.load_plugin(options.texpost[len("plugin:"):])
633 else:
634 path = os.path.realpath(options.texpost)
635 if not(os.path.isfile(path)):
636 failed_exit("Error: '%s' does not exist" % options.texpost)
637 run.texpost = path
638
639 if options.no_external:
640 run.unset_flags(run.USE_MKLISTINGS)
641
642 if options.verbose:
643 run.verbose = options.verbose
644
645 if options.quiet:
646 run.verbose = logger.QUIET
647 run.xslparams.append("output.quietly=1")
648
649 if options.tmpdir:
650 if not(os.path.exists(options.tmpdir)):
651 try:
652 os.mkdir(options.tmpdir)
653 except Exception as e:
654 failed_exit("Error: %s" % e)
655 run.tmpdir_user = os.path.abspath(options.tmpdir)
656
657 if options.dump:
658 dump_stack()
659
660 def get_config_paths(self):
661 # Allows user directories where to look for configuration files
662 paths = [os.getcwd()]
663 paths.append(os.path.expanduser(os.path.join("~", "."+self.prog)))
664
665 # Unix specific system-wide config files
666 if "posix" in sys.builtin_module_names:
667 paths.append(os.path.join("/etc", self.prog))
668
669 # Last but not least, the tool config dir
670 paths.append(self.run.confdir)
671
672 # Optionally the paths from an environment variable
673 conf_paths = os.getenv("DBLATEX_CONFIG_FILES")
674 if not(conf_paths):
675 return paths
676
677 paths += conf_paths.split(os.pathsep)
678 return paths
679
680 def main(self):
681 (options, args) = self.parser.parse_args()
682
683 run = self.run
684 parser = self.parser
685
686 if options.version:
687 version = run.get_version()
688 print("%s version %s" % (self.prog, version))
689 if not(args):
690 sys.exit(0)
691
692 # At least the input file is expected
693 if not(args):
694 parser.parse_args(args=["-h"])
695
696 # Load the specified configurations
697 conf = DbtexConfig()
698 if options.dump:
699 dump_stack()
700
701 if options.style:
702 try:
703 conf.paths = self.get_config_paths()
704 conf.fromstyle(options.style)
705 except Exception as e:
706 failed_exit("Error: %s" % e)
707
708 if options.config:
709 try:
710 for config in options.config:
711 conf.fromfile(config)
712 except Exception as e:
713 failed_exit("Error: %s" % e)
714
715 if conf.options:
716 options2, args2 = parser.parse_args(conf.options)
717 self.run_setup(options2)
718
719 # Now apply the command line setup
720 self.run_setup(options)
721
722 # Verbose mode
723 run.log = logger.logger(self.prog, run.verbose)
724
725 # Data from standard input?
726 if args[0] == "-":
727 if not(options.output):
728 failed_exit("Error: -o expected when input from stdin")
729 input = ""
730 if options.changedir:
731 run.stdindir = os.path.realpath(options.changedir)
732 else:
733 input = os.path.realpath(args[0])
734
735 # Output file in case of single document (main case)
736 if not(options.output):
737 output = None
738 else:
739 output = os.path.realpath(options.output)
740
741 # Output directory in case of chunked books (from a set)
742 if not(options.output_dir):
743 outputdir = None
744 else:
745 # Check the output dir is OK
746 outputdir = os.path.realpath(options.output_dir)
747 if not(os.path.isdir(outputdir)):
748 failed_exit("Error: '%s' is not a directory" %\
749 options.output_dir)
750
751 run.input = input
752 run.output = output
753 run.outputdir = outputdir
754
755 # Try to buid the file
756 try:
757 run.compile()
758 except Exception as e:
759 signal_error(self, e)
760 failed_exit("Error: %s" % e)
761