def __init__ (self, doc, dict):
     doc.vars["program"] = "xelatex"
     doc.vars["engine"] = "XeLaTeX"
     if doc.env.final != doc and doc.prods[0][-4:] != ".pdf":
         msg.error(_("there is already a post-processor registered"))
         sys.exit(2)
     doc.prods = [doc.src_base + ".pdf"]
Esempio n. 2
0
	def run_pythontex(self):
		call = ['pythontex', self.doc.target + '.tex', ]
		msg.debug(_("pythontex call is '%s'") % ' '.join(call), pkg="pythontex")
		if not self.doc.env.is_in_unsafe_mode_:
			msg.error(_("the document tries to run external programs which could be dangerous.  use rubber --unsafe if the document is trusted."))
			return
		subprocess.call(call)
Esempio n. 3
0
 def __init__(self, doc, dict):
     doc.vars["program"] = "xelatex"
     doc.vars["engine"] = "XeLaTeX"
     if doc.env.final != doc and doc.prods[0][-4:] != ".pdf":
         msg.error(_("there is already a post-processor registered"))
         sys.exit(2)
     doc.prods = [doc.src_base + ".pdf"]
Esempio n. 4
0
def run(doc, env, base):
	msg.progress(_("running slatex on %s") % doc.src_base)
	if env.execute(["slatex", "-n", base], {}):
		msg.error(_("Error executing slatex"))
		return 1
			
	doc.must_compile = 1
	return 0
Esempio n. 5
0
def run(doc, env, base):
    msg.progress(_("running slatex on %s") % doc.src_base)
    if env.execute(["slatex", "-n", base], {}):
        msg.error(_("Error executing slatex"))
        return 1

    doc.must_compile = 1
    return 0
Esempio n. 6
0
def setup(doc, context):
    dvi = doc.env.final.products[0]
    if dvi[-4:] != ".dvi":
        msg.error(_("I can't use dvipdfm when not producing a DVI"))
        sys.exit(2)
    pdf = dvi[:-3] + "pdf"
    global dep
    dep = Dep(doc, pdf, dvi)
    doc.env.final = dep
Esempio n. 7
0
def setup(doc, context):
    dvi = doc.env.final.products[0]
    if dvi[-4:] != '.dvi':
        msg.error(_("I can't use dvipdfm when not producing a DVI"))
        sys.exit(2)
    pdf = dvi[:-3] + 'pdf'
    global dep
    dep = Dep(doc, pdf, dvi, doc.env.final)
    doc.env.final = dep
Esempio n. 8
0
 def mode_dvi (self):
     if self.mode == 'dvi':
         return
     if self.doc.env.final != self.doc and self.doc.products[0][-4:] != '.dvi':
         msg.error(_("there is already a post-processor registered"))
         return
     self.doc.set_primary_product_suffix (".dvi")
     self.doc.cmdline.insert(0, '\\pdfoutput=0')
     self.mode = 'dvi'
Esempio n. 9
0
    def __init__ (self, document, context):
        document.vars['program'] = 'xelatex'
        document.vars['engine'] = 'XeLaTeX'

        if document.env.final != document and document.products[0][-4:] != '.pdf':
            msg.error(_("there is already a post-processor registered"))
            return

        document.set_primary_product_suffix (".pdf")
Esempio n. 10
0
def setup (doc, context):
	dvi = doc.env.final.products[0]
	if dvi[-4:] != '.dvi':
		msg.error(_("I can't use dvips when not producing a DVI"))
		sys.exit(2)
	ps = dvi[:-3] + 'ps'
	global dep
	dep = Dep(doc, ps, dvi)
	doc.env.final = dep
Esempio n. 11
0
def setup(doc, context):
    doc.vars['program'] = 'xelatex'
    doc.vars['engine'] = 'XeLaTeX'

    if doc.env.final != doc and doc.products[0][-4:] != '.pdf':
        msg.error(_("there is already a post-processor registered"))
        return

    doc.reset_products([doc.target + '.pdf'])
Esempio n. 12
0
 def mode_pdf (self):
     if self.mode == 'pdf':
         return
     if self.doc.env.final != self.doc and self.doc.products[0][-4:] != '.pdf':
         msg.error(_("there is already a post-processor registered"))
         return
     self.doc.set_primary_product_suffix (".pdf")
     self.doc.cmdline = [
         opt for opt in self.doc.cmdline if opt != '\\pdfoutput=0']
     self.mode = 'pdf'
Esempio n. 13
0
 def run(self):
     msg.progress(_("running dvipdfm on %s") % self.source)
     cmd = ["dvipdfm"]
     for opt in self.doc.vars["paper"].split():
         cmd.extend(["-p", opt])
     cmd.extend(self.options + ["-o", self.target, self.source])
     if self.env.execute(cmd, kpse=1):
         msg.error(_("dvipdfm failed on %s") % self.source)
         return False
     return True
Esempio n. 14
0
 def run (self):
     msg.progress (_ ("compressing %s into %s") % (self.source, self.target))
     try:
         with open (self.source, 'rb') as f_in:
             with self.constructor (self.target, 'wb') as f_out:
                 f_out.writelines (f_in)
     except:
         msg.error (_ ("compression failed"))
         return False
     return True
Esempio n. 15
0
	def run (self):
		# check if the input file exists. if not, refuse to run.
		if not os.path.exists (self.sources[0]):
			msg.info (_('input file for %s does not yet exist, deferring')
				% self.tool, pkg='pythontex')
			return True
		if not self.doc.env.is_in_unsafe_mode_:
			msg.error (_('The document tries to run embedded Python code which could be dangerous.  Use rubber --unsafe if the document is trusted.'))
			return False
		return super (PythonTeXDep, self).run ()
Esempio n. 16
0
    def __init__(self, document, context):
        document.vars['program'] = 'xelatex'
        document.vars['engine'] = 'XeLaTeX'

        if document.env.final != document and document.products[0][
                -4:] != '.pdf':
            msg.error(_("there is already a post-processor registered"))
            return

        document.set_primary_product_suffix(".pdf")
Esempio n. 17
0
 def mode_dvi(self):
     if self.mode == 'dvi':
         return
     if self.doc.env.final != self.doc and self.doc.products[0][
             -4:] != '.dvi':
         msg.error(_("there is already a post-processor registered"))
         return
     self.doc.set_primary_product_suffix(".dvi")
     self.doc.cmdline.insert(0, '\\pdfoutput=0')
     self.mode = 'dvi'
Esempio n. 18
0
def mode_dvi ():
	global mode
	if mode == 'dvi':
		return
	if doc.env.final != doc and doc.products[0][-4:] != '.dvi':
		msg.error(_("there is already a post-processor registered"))
		return
	doc.reset_products([doc.target + '.dvi'])
	doc.cmdline.insert(0, '-output-format dvi')
	mode = 'dvi'
Esempio n. 19
0
def mode_xdv ():
	global mode
	if mode == 'xdv':
		return
	if doc.env.final != doc and doc.products[0][-4:] != '.xdv':
		msg.error(_("there is already a post-processor registered"))
		return
	doc.reset_products([doc.target + '.xdv'])
	doc.cmdline.insert(0, '-no-pdf')
	mode = 'xdv'
Esempio n. 20
0
def mode_pdf():
    global mode
    if mode == 'pdf':
        return
    if doc.env.final != doc and doc.products[0][-4:] != '.pdf':
        msg.error(_("there is already a post-processor registered"))
        return
    doc.reset_products([doc.target + '.pdf'])
    doc.cmdline = [opt for opt in doc.cmdline if opt != '\\pdfoutput=0']
    mode = 'pdf'
Esempio n. 21
0
 def run(self):
     msg.progress(_("compressing %s into %s") % (self.source, self.target))
     try:
         with open(self.source, 'rb') as f_in:
             with self.constructor(self.target, 'wb') as f_out:
                 f_out.writelines(f_in)
     except:
         msg.error(_("compression failed"))
         return False
     return True
Esempio n. 22
0
 def run(self):
     msg.progress(_("running dvipdfm on %s") % self.source)
     cmd = ['dvipdfm']
     for opt in self.doc.vars['paper'].split():
         cmd.extend(['-p', opt])
     cmd.extend(self.options + ['-o', self.target, self.source])
     if self.env.execute(cmd, kpse=1):
         msg.error(_("dvipdfm failed on %s") % self.source)
         return False
     return True
Esempio n. 23
0
def mode_pdf ():
	global mode
	if mode == 'pdf':
		return
	if doc.env.final != doc and doc.products[0][-4:] != '.pdf':
		msg.error(_("there is already a post-processor registered"))
		return
	doc.reset_products([doc.target + '.pdf'])
	doc.cmdline = [
		opt for opt in doc.cmdline if opt != '-output-format dvi']
	mode = 'pdf'
Esempio n. 24
0
    def post_compile(self):
        """
		Run makeindex if needed, with appropriate options and environment.
		"""
        if not os.path.exists(self.source):
            msg.log(_("strange, there is no %s") % self.source, pkg="index")
            return True
        if not self.run_needed():
            return True

        msg.progress(_("processing index %s") % msg.simplify(self.source))

        if self.tool == "makeindex":
            cmd = ["makeindex", "-q", "-o", self.target] + self.opts
            cmd.extend(["-t", self.transcript])
            if self.style:
                cmd.extend(["-s", self.style])
            cmd.append(self.source)
            path_var = "INDEXSTYLE"

        elif self.tool == "xindy":
            cmd = ["texindy", "--quiet"]
            for opt in self.opts:
                if opt == "-g":
                    if self.lang != "":
                        msg.warn(_("'language' overrides 'order german'"),
                                 pkg="index")
                    else:
                        self.lang = "german-din"
                elif opt == "-l":
                    self.modules.append("letter-ordering")
                    msg.warn(_(
                        "use 'module letter-ordering' instead of 'order letter'"
                    ),
                             pkg="index")
                else:
                    msg.error("unknown option to xindy: %s" % opt, pkg="index")
            for mod in self.modules:
                cmd.extend(["--module", mod])
            if self.lang:
                cmd.extend(["--language", self.lang])
            cmd.append(self.source)
            path_var = "XINDY_SEARCHPATH"

        if self.path != []:
            env = {path_var: ':'.join(self.path + [os.getenv(path_var, '')])}
        else:
            env = {}
        if self.doc.env.execute(cmd, env):
            msg.error(_("could not make index %s") % self.target)
            return False

        self.doc.must_compile = 1
        return True
Esempio n. 25
0
def mode_dvi ():
	global mode
	if mode == 'dvi':
		msg.error(_("XeTeX doesn't roll with dvi files"))
		return
	if doc.env.final != doc and doc.products[0][-4:] != '.dvi':
		msg.error(_("there is already a post-processor registered"))
		return
	doc.reset_products([doc.target + '.dvi'])
	doc.cmdline.insert(0, '\\pdfoutput=0')
	mode = 'dvi'
Esempio n. 26
0
 def mode_pdf(self):
     if self.mode == 'pdf':
         return
     if self.doc.env.final != self.doc and self.doc.products[0][
             -4:] != '.pdf':
         msg.error(_("there is already a post-processor registered"))
         return
     self.doc.set_primary_product_suffix(".pdf")
     self.doc.cmdline = [
         opt for opt in self.doc.cmdline if opt != '\\pdfoutput=0'
     ]
     self.mode = 'pdf'
Esempio n. 27
0
	def post_compile (self):
		"""
		Run makeindex if needed, with appropriate options and environment.
		"""
		if not os.path.exists(self.source):
			msg.log(_("strange, there is no %s") % self.source, pkg="index")
			return True
		if not self.run_needed():
			return True

		msg.progress(_("processing index %s") % msg.simplify(self.source))

		if self.tool == "makeindex":
			cmd = ["makeindex", "-q", "-o", self.target] + self.opts
			cmd.extend(["-t", self.transcript])
			if self.style:
				cmd.extend(["-s", self.style])
			cmd.append(self.source)
			path_var = "INDEXSTYLE"

		elif self.tool == "xindy":
			cmd = ["texindy", "--quiet"]
			for opt in self.opts:
				if opt == "-g":
					if self.lang != "":
						msg.warn(_("'language' overrides 'order german'"),
							pkg="index")
					else:
						self.lang = "german-din"
				elif opt == "-l":
					self.modules.append("letter-ordering")
					msg.warn(_("use 'module letter-ordering' instead of 'order letter'"),
						pkg="index")
				else:
					msg.error("unknown option to xindy: %s" % opt, pkg="index")
			for mod in self.modules:
				cmd.extend(["--module", mod])
			if self.lang:
				cmd.extend(["--language", self.lang])
			cmd.append(self.source)
			path_var = "XINDY_SEARCHPATH"

		if self.path != []:
			env = { path_var: ':'.join(self.path + [os.getenv(path_var, '')]) }
		else:
			env = {}
		if self.doc.env.execute(cmd, env):
			msg.error(_("could not make index %s") % self.target)
			return False

		self.doc.must_compile = 1
		return True
Esempio n. 28
0
	def run (self):
		if self.doc.vars['engine'] == 'Omega':
			cmd = ['odvips']
		else:
			cmd = ['dvips']
		msg.progress(_("running %s on %s") % (cmd[0], self.source))
		for opt in self.doc.vars['paper'].split():
			cmd.extend(['-t', opt])
		cmd.extend(self.options + ['-o', self.target, self.source])
		if self.env.execute(cmd, kpse=1):
			msg.error(_("%s failed on %s") % (cmd[0], self.source))
			return False
		return True
Esempio n. 29
0
 def run_pythontex(self):
     call = [
         'pythontex',
         self.doc.target + '.tex',
     ]
     msg.debug(_("pythontex call is '%s'") % ' '.join(call),
               pkg="pythontex")
     if not self.doc.env.is_in_unsafe_mode_:
         msg.error(
             _("the document tries to run external programs which could be dangerous.  use rubber --unsafe if the document is trusted."
               ))
         return
     subprocess.call(call)
Esempio n. 30
0
    def run (self):
        # build command line
        tool = self.tool
        if tool == 'dvips' and self.doc.vars ['engine'] == 'Omega':
            tool = 'odvips'
        cmd = [ tool ]
        cmd.extend (self.extra_args)
        cmd.append (self.source)

        # run
        if self.doc.env.execute (cmd) != 0:
            msg.error (_('%s failed on %s') % (tool, self.source))
            return False
        return True
Esempio n. 31
0
    def run(self):
        # build command line
        tool = self.tool
        if tool == 'dvips' and self.doc.vars['engine'] == 'Omega':
            tool = 'odvips'
        cmd = [tool]
        for opt in self.doc.vars['paper'].split():
            cmd.extend((paper_selection_option[self.tool], opt))
        cmd.extend(self.extra_args)
        cmd.append(self.source)

        # run
        if self.doc.env.execute(cmd, kpse=1) != 0:
            msg.error(_('%s failed on %s') % (tool, self.source))
            return False
        return True
Esempio n. 32
0
    def run(self):
        """
		This method reads the source file (which is supposed to be a
		gzip-compressed PostScript file) until it finds a line that contains a
		bounding box indication. Then it creates the target file with this
		single line.
		"""
        msg.progress(_("extracting bounding box from %s") % self.source)
        with GzipFile(self.source) as source:
            for line in source:
                if re_bbox.match(line):
                    with open(self.target, "w") as target:
                        target.write(line)
                    return True
        msg.error(_("no bounding box was found in %s!") % self.source)
        return False
Esempio n. 33
0
    def __init__ (self, document, context, tool):
        super (Module, self).__init__ (document.env.depends)

        self.tool = tool
        assert tool in ('dvipdfm', 'dvips')
        self.doc = document

        assert type (self.doc.env.final) is rubber.converters.latex.LaTeXDep
        self.source = self.doc.env.final.products[0]
        if not self.source.endswith ('.dvi'):
            msg.error (_('I can\'t use %s when not producing a DVI') % tool)
            rubber.util.abort_generic_error ()
        self.doc.env.final = self
        self.add_product (self.source [:-3] + product_extension [tool])
        self.add_source (self.source)
        self.extra_args = []
Esempio n. 34
0
	def run (self):
		"""
		This method reads the source file (which is supposed to be a
		gzip-compressed PostScript file) until it finds a line that contains a
		bounding box indication. Then it creates the target file with this
		single line.
		"""
		msg.progress(_("extracting bounding box from %s") % self.source)
		with GzipFile(self.source) as source:
			for line in source:
				if re_bbox.match(line):
					with open(self.target, "w") as target:
						target.write(line)
					return True
		msg.error(_("no bounding box was found in %s!") % self.source)
		return False
Esempio n. 35
0
 def command (self, cmd, args):
     """
     This is called when a directive for the module is found in the source.
     We treat syntax errors in the directive as fatal, aborting the run.
     """
     try:
         handler = getattr (self, "do_" + cmd)
     except AttributeError:
         # there is no do_ method for this directive, which means there
         # is no such directive.
         msg.error (_("no such directive '%s'") % cmd, pkg=self.__module__)
         rubber.util.abort_rubber_syntax_error ()
     try:
         return handler (*args)
     except TypeError:
         # Python failed to coerce the arguments given into whatever
         # the handler would like to see.  report a generic failure.
         msg.error (_("invalid syntax for directive '%s'") % cmd, pkg=self.__module__)
         rubber.util.abort_rubber_syntax_error ()
Esempio n. 36
0
 def command(self, cmd, args):
     """
     This is called when a directive for the module is found in the source.
     We treat syntax errors in the directive as fatal, aborting the run.
     """
     try:
         handler = getattr(self, "do_" + cmd)
     except AttributeError:
         # there is no do_ method for this directive, which means there
         # is no such directive.
         msg.error(_("no such directive '%s'") % cmd, pkg=self.__module__)
         rubber.util.abort_rubber_syntax_error()
     try:
         return handler(*args)
     except TypeError:
         # Python failed to coerce the arguments given into whatever
         # the handler would like to see.  report a generic failure.
         msg.error(_("invalid syntax for directive '%s'") % cmd,
                   pkg=self.__module__)
         rubber.util.abort_rubber_syntax_error()
Esempio n. 37
0
 def do_tool(self, tool):
     if tool not in ("makeindex", "xindy"):
         msg.error(_("unknown indexing tool '%s'") % tool)
     self.tool = tool
Esempio n. 38
0
    def main(self, cmdline):
        """
		Run Rubber for the specified command line. This processes each
		specified source in order (for making or cleaning). If an error
		happens while making one of the documents, the whole process stops.
		The method returns the program's exit code.
		"""
        self.jobname = None
        self.prologue = []
        self.epilogue = []
        self.clean = 0
        self.force = 0
        self.shell_escape = 0

        self.warn = 0
        self.warn_boxes = 0
        self.warn_misc = 0
        self.warn_refs = 0

        self.place = "."

        args = self.parse_opts(cmdline)

        initial_dir = os.getcwd()
        msg.cwd = os.path.join(initial_dir, "")

        if self.place != "." and self.place is not None:
            msg.path = self.place
            self.place = os.path.abspath(self.place)

        msg.log(_("This is Rubber version %s.") % version)

        for srcname in args:
            src = os.path.abspath(os.path.join(initial_dir, srcname))

            # Go to the appropriate directory

            if self.place != ".":
                if self.place is None:
                    msg.path = os.path.dirname(src)
                    os.chdir(os.path.dirname(src))
                    src = os.path.basename(src)
                else:
                    os.chdir(self.place)

            # Check the source and prepare it for processing

            env = Environment()

            env.vars.new_key('shell_escape', self.shell_escape)

            if env.set_source(src, jobname=self.jobname):
                return 1
            self.jobname = None

            if self.include_only is not None:
                env.main.includeonly(self.include_only)

            if self.clean:
                if env.main.products == []:
                    msg.warn(_("there is no LaTeX source for %s") % srcname)
                    continue
            else:
                env.make_source()

            saved_vars = env.main.vars
            env.main.vars = Variables(saved_vars, {"cwd": initial_dir})
            for dir in self.path:
                env.main.do_path(dir)
            for cmd in self.prologue:
                cmd = parse_line(cmd, env.main.vars)
                env.main.command(cmd[0], cmd[1:], {'file': 'command line'})
            env.main.vars = saved_vars

            env.main.parse()

            saved_vars = env.main.vars
            env.main.vars = Variables(saved_vars, {"cwd": initial_dir})
            for cmd in self.epilogue:
                cmd = parse_line(cmd, env.main.vars)
                env.main.command(cmd[0], cmd[1:], {'file': 'command line'})
            env.main.vars = saved_vars

            if self.compress is not None:
                last_node = env.final
                filename = last_node.products[0]
                if self.compress == 'gzip':
                    from rubber.converters.gz import GzipDep
                    env.final = GzipDep(env.depends, filename + '.gz',
                                        filename)
                elif self.compress == 'bzip2':
                    from rubber.converters.bzip2 import Bzip2Dep
                    env.final = Bzip2Dep(env.depends, filename + '.bz2',
                                         filename)

            # Compile the document

            if self.clean:
                env.final.clean()
                continue

            if self.force:
                ret = env.main.make(True)
                if ret != ERROR and env.final is not env.main:
                    ret = env.final.make()
                else:
                    # This is a hack for the call to get_errors() below
                    # to work when compiling failed when using -f.
                    env.final.failed_dep = env.main.failed_dep
            else:
                ret = env.final.make(self.force)

            if ret == ERROR:
                msg.info(_("There were errors compiling %s.") % srcname)
                number = self.max_errors
                for err in env.final.failed().get_errors():
                    if number == 0:
                        msg.info(_("More errors."))
                        break
                    msg.display(**err)
                    number -= 1
                return 1

            if ret == UNCHANGED:
                msg(1, _("nothing to be done for %s") % srcname)

            if self.warn:
                log = env.main.log
                if log.read(env.main.target + ".log"):
                    msg.error(_("cannot read the log file"))
                    return 1
                msg.display_all(
                    log.parse(boxes=self.warn_boxes,
                              refs=self.warn_refs,
                              warnings=self.warn_misc))

        return 0
Esempio n. 39
0
    def main(self, cmdline):
        """
		Run Rubber as a pipe for the specified command line. This dumps the
		standard input into a temporary file, compiles it, dumps the result on
		standard output, and then removes the files if requested. If an error
		happens while building the document, the process stops. The method
		returns the program's exit code.
		"""
        self.prologue = []
        self.epilogue = []
        self.clean = 1
        self.place = "."
        self.path = []
        self.parse_opts(cmdline)
        msg.log(_("This is Rubber version %s.") % version)

        # Put the standard input in a file

        initial_dir = os.getcwd()

        if self.place is not None and self.place != ".":
            self.path.insert(0, initial_dir)
            os.chdir(self.place)

        src = make_name() + ".tex"
        try:
            srcfile = open(src, 'w')
        except IOError:
            msg.error(_("cannot create temporary files"))
            return 1

        msg.progress(_("saving the input in %s") % src)
        dump_file(sys.stdin, srcfile)
        srcfile.close()

        # Make the document

        env = Environment()
        env.vars["cwd"] = initial_dir

        if env.set_source(src):
            msg.error(_("cannot open the temporary %s") % src)
            return 1

        if self.include_only is not None:
            env.main.includeonly(self.include_only)

        env.make_source()

        for dir in self.path:
            env.main.do_path(dir)
        for cmd in self.prologue:
            cmd = parse_line(cmd, {})
            env.main.command(cmd[0], cmd[1:], {'file': 'command line'})

        env.main.parse()

        for cmd in self.epilogue:
            cmd = parse_line(cmd, {})
            env.main.command(cmd[0], cmd[1:], {'file': 'command line'})

        ret = env.final.make()

        if ret == ERROR:
            msg.info(_("There were errors."))
            number = self.max_errors
            for err in env.final.failed().get_errors():
                if number == 0:
                    msg.info(_("More errors."))
                    break
                msg.display(**err)
                number -= 1
            return 1

        # Dump the results on standard output

        output = open(env.final.products[0])
        dump_file(output, sys.stdout)

        # Clean the intermediate files

        if self.clean:
            env.final.clean()
            os.unlink(src)
        return 0
Esempio n. 40
0
	def do_tool (self, tool):
		if tool not in ("makeindex", "xindy"):
			msg.error(_("unknown indexing tool '%s'") % tool)
		self.tool = tool
Esempio n. 41
0
    def main(self, cmdline):
        """
		Run Rubber as a pipe for the specified command line. This dumps the
		standard input into a temporary file, compiles it, dumps the result on
		standard output, and then removes the files if requested. If an error
		happens while building the document, the process stops. The method
		returns the program's exit code.
		"""
        self.prologue = []
        self.epilogue = []
        self.clean = 1
        self.place = "."
        self.path = []
        self.parse_opts(cmdline)
        msg.log(_("This is Rubber version %s.") % version)

        # Put the standard input in a file

        initial_dir = os.getcwd()

        if self.place is not None and self.place != ".":
            self.path.insert(0, initial_dir)
            os.chdir(self.place)

        src = make_name() + ".tex"
        try:
            srcfile = open(src, "w")
        except IOError:
            msg.error(_("cannot create temporary files"))
            return 1

        msg.progress(_("saving the input in %s") % src)
        dump_file(sys.stdin, srcfile)
        srcfile.close()

        # Make the document

        env = Environment()
        env.vars["cwd"] = initial_dir

        if env.set_source(src):
            msg.error(_("cannot open the temporary %s") % src)
            return 1

        if self.include_only is not None:
            env.main.includeonly(self.include_only)

        env.make_source()

        for dir in self.path:
            env.main.do_path(dir)
        for cmd in self.prologue:
            cmd = parse_line(cmd, {})
            env.main.command(cmd[0], cmd[1:], {"file": "command line"})

        env.main.parse()

        for cmd in self.epilogue:
            cmd = parse_line(cmd, {})
            env.main.command(cmd[0], cmd[1:], {"file": "command line"})

        ret = env.final.make()

        if ret == ERROR:
            msg.info(_("There were errors."))
            number = self.max_errors
            for err in env.final.failed().get_errors():
                if number == 0:
                    msg.info(_("More errors."))
                    break
                msg.display(**err)
                number -= 1
            return 1

            # Dump the results on standard output

        output = open(env.final.products[0])
        dump_file(output, sys.stdout)

        # Clean the intermediate files

        if self.clean:
            env.final.clean()
            os.unlink(src)
        return 0
Esempio n. 42
0
	def main (self, cmdline):
		"""
		Run Rubber for the specified command line. This processes each
		specified source in order (for making or cleaning). If an error
		happens while making one of the documents, the whole process stops.
		The method returns the program's exit code.
		"""
		self.jobname = None
		self.prologue = []
		self.epilogue = []
		self.clean = 0
		self.force = 0

		self.warn = 0
		self.warn_boxes = 0
		self.warn_misc = 0
		self.warn_refs = 0

		self.place = "."

		args = self.parse_opts(cmdline)

		initial_dir = os.getcwd()
		msg.cwd = os.path.join(initial_dir, "")

		if self.place != "." and self.place is not None:
			msg.path = self.place
			self.place = os.path.abspath(self.place)

		msg.log(_("This is Rubber version %s.") % version)

		for srcname in args:
			src = os.path.abspath(os.path.join(initial_dir, srcname))

			# Go to the appropriate directory

			if self.place != ".":
				if self.place is None:
					msg.path = os.path.dirname(src)
					os.chdir(os.path.dirname(src))
					src = os.path.basename(src)
				else:
					os.chdir(self.place)

			# Check the source and prepare it for processing
	
			env = Environment()

			if env.set_source(src, jobname=self.jobname):
				return 1
			self.jobname = None

			if self.include_only is not None:
				env.main.includeonly(self.include_only)

			if self.clean:
				if env.main.products == []:
					msg.warn(_("there is no LaTeX source for %s") % srcname)
					continue
			else:
				env.make_source()

			saved_vars = env.main.vars
			env.main.vars = Variables(saved_vars, { "cwd": initial_dir })
			for dir in self.path:
				env.main.do_path(dir)
			for cmd in self.prologue:
				cmd = parse_line(cmd, env.main.vars)
				env.main.command(cmd[0], cmd[1:], {'file': 'command line'})
			env.main.vars = saved_vars

			env.main.parse()

			saved_vars = env.main.vars
			env.main.vars = Variables(saved_vars, { "cwd": initial_dir })
			for cmd in self.epilogue:
				cmd = parse_line(cmd, env.main.vars)
				env.main.command(cmd[0], cmd[1:], {'file': 'command line'})
			env.main.vars = saved_vars

			if self.compress is not None:
				last_node = env.final
				filename = last_node.products[0]
				if self.compress == 'gzip':
					from rubber.converters.gz import GzipDep
					env.final = GzipDep(env.depends,
							filename + '.gz', filename)
				elif self.compress == 'bzip2':
					from rubber.converters.bzip2 import Bzip2Dep
					env.final = Bzip2Dep(env.depends,
							filename + '.bz2', filename)

			# Compile the document

			if self.clean:
				env.final.clean()
				continue

			if self.force:
				ret = env.main.make(True)
				if ret != ERROR and env.final is not env.main:
					ret = env.final.make()
				else:
					# This is a hack for the call to get_errors() below
					# to work when compiling failed when using -f.
					env.final.failed_dep = env.main.failed_dep
			else:
				ret = env.final.make(self.force)

			if ret == ERROR:
				msg.info(_("There were errors compiling %s.") % srcname)
				number = self.max_errors
				for err in env.final.failed().get_errors():
					if number == 0:
						msg.info(_("More errors."))
						break
					msg.display(**err)
					number -= 1
				return 1

			if ret == UNCHANGED:
				msg(1, _("nothing to be done for %s") % srcname)

			if self.warn:
				log = env.main.log
				if log.read(env.main.target + ".log"):
					msg.error(_("cannot read the log file"))
					return 1
				msg.display_all(log.parse(boxes=self.warn_boxes,
					refs=self.warn_refs, warnings=self.warn_misc))

		return 0