示例#1
0
    def patch(self, out_filename=None):
        """Apply patches and write changes to specified file.

        Args:
            out_filename: Output filename. If not set then input one is used.
        """
        in_ = FileInput(source_path=self._filename, encoding=self._encoding)
        content = in_.read()
        content = self._patcher.patch(content)
        content = '\n'.join(content)

        out = FileOutput(destination_path=out_filename or self._filename,
                         encoding=self._encoding)
        out.write(content)
示例#2
0
def run(args):
    """The main function."""

    sources = []
    if args.debug:
        from mjstat.testdata import TEST_INPUT
        sources.append(StringInput(source=TEST_INPUT))
    else:
        # XXX
        if isinstance(args.input, (list, tuple)):
            sources.extend(
                FileInput(source_path=i, encoding='sjis', mode='r')
                for i in args.input)
        else:
            sources.append(
                FileInput(source_path=args.input, encoding='sjis', mode='r'))

    parser = MJScoreParser()
    reader = MJScoreReader()

    game_data_list = tuple(reader.read(i, parser, args) for i in sources)
    game_data = merge_games(game_data_list)
    apply_transforms(game_data)

    writer = MJScoreWriter()
    writer.write(game_data, FileOutput(None))
示例#3
0
    def write(self, *ignored):
        super(CustomLaTeXBuilder, self).write(*ignored)

        backup_translator = sphinx.writers.latex.LaTeXTranslator
        sphinx.writers.latex.LaTeXTranslator = CustomLaTeXTranslator
        backup_doc = sphinx.writers.latex.BEGIN_DOC
        sphinx.writers.latex.BEGIN_DOC = ''

        # output these as include files
        for docname in ['abstract', 'dedication', 'acknowledgements']:
            destination = FileOutput(destination_path=os.path.join(
                self.outdir, '%s.inc' % docname),
                                     encoding='utf-8')

            docwriter = LaTeXWriter(self)
            doctree = self.env.get_doctree(docname)

            docsettings = OptionParser(
                defaults=self.env.settings,
                components=(docwriter, )).get_default_values()
            doctree.settings = docsettings
            docwriter.write(doctree, destination)

        sphinx.writers.latex.LaTeXTranslator = backup_translator
        sphinx.writers.latex.BEGIN_DOC = backup_doc
示例#4
0
    def write(self, *ignored):
        docwriter = LaTeXWriter(self)
        docsettings = OptionParser(
            defaults=self.env.settings,
            components=(docwriter,)).get_default_values()

        self.init_document_data()

        for entry in self.document_data:
            docname, targetname, title, author, docclass = entry[:5]
            toctree_only = False
            if len(entry) > 5:
                toctree_only = entry[5]
            destination = FileOutput(
                destination_path=path.join(self.outdir, targetname),
                encoding='utf-8')
            self.info("processing " + targetname + "... ", nonl=1)
            doctree = self.assemble_doctree(docname, toctree_only,
                appendices=((docclass != 'howto') and
                            self.config.latex_appendices or []))
            self.post_process_images(doctree)
            self.info("writing... ", nonl=1)
            doctree.settings = docsettings
            doctree.settings.author = author
            doctree.settings.title = title
            doctree.settings.docname = docname
            doctree.settings.docclass = docclass
            docwriter.write(doctree, destination)
            self.info("done")
示例#5
0
def build_finished(app, exception):
    if exception is not None:
        return
    builder = app.builder
    output_full_name = os.path.join(
        builder.outdir,
        'schedule.ics',
    )
    output_dir_name = os.path.dirname(output_full_name)
    if not os.path.exists(output_dir_name):
        os.makedirs(output_dir_name)
    destination = FileOutput(
        destination_path=output_full_name,
        encoding='utf-8',
    )
    LOG.info('generating {}'.format(output_full_name))
    destination.write(_global_calendar.to_ical())
示例#6
0
 def write(self, *ignored):
     
     self.init_document_data()
     
     if self.config.pdf_verbosity > 1:
         rst2pdf.log.log.setLevel(logging.DEBUG)
     elif self.config.pdf_verbosity > 0:
         rst2pdf.log.log.setLevel(logging.INFO)
 
     for entry in self.document_data:
         try:
             docname, targetname, title, author = entry[:4]
             # Custom options per document
             if len(entry)>4 and isinstance(entry[4],dict): 
                 opts=entry[4]
             else:
                 opts={}
             self.info("processing " + targetname + "... ", nonl=1)
             
             class dummy:
                 extensions=self.config.pdf_extensions
                 
             createpdf.add_extensions(dummy())
             
             self.page_template=opts.get('pdf_page_template',self.config.pdf_page_template)
             
             docwriter = PDFWriter(self,
                             stylesheets=opts.get('pdf_stylesheets',self.config.pdf_stylesheets),
                             language=opts.get('pdf_language',self.config.pdf_language),
                             breaklevel=opts.get('pdf_break_level',self.config.pdf_break_level),
                             breakside=opts.get('pdf_breakside',self.config.pdf_breakside),
                             fontpath=opts.get('pdf_font_path',self.config.pdf_font_path),
                             fitmode=opts.get('pdf_fit_mode',self.config.pdf_fit_mode),
                             compressed=opts.get('pdf_compressed',self.config.pdf_compressed),
                             inline_footnotes=opts.get('pdf_inline_footnotes',self.config.pdf_inline_footnotes),
                             splittables=opts.get('pdf_splittables',self.config.pdf_splittables),
                             default_dpi=opts.get('pdf_default_dpi',self.config.pdf_default_dpi),
                             page_template=self.page_template,
                             invariant=opts.get('pdf_invariant',self.config.pdf_invariant),
                             srcdir=self.srcdir,
                             config=self.config
                             )
             
             tgt_file = path.join(self.outdir, targetname + self.out_suffix)
             destination = FileOutput(destination=open(tgt_file,'wb'), encoding='utf-8')
             doctree = self.assemble_doctree(docname,title,author, 
                 appendices=opts.get('pdf_appendices', self.config.pdf_appendices) or [])
             doctree.settings.author=author
             doctree.settings.title=title
             self.info("done")
             self.info("writing " + targetname + "... ", nonl=1)
             docwriter.write(doctree, destination)
             self.info("done")
         except Exception, e:
             rst2pdf.log.log.error(str(e))
             print_exc()
             self.info(red("FAILED"))
示例#7
0
文件: docutils.py 项目: mgeier/sphinx
    def write(self, data):
        # type: (unicode) -> unicode
        if (self.destination_path and self.autoclose and 'b' not in self.mode and
                self.overwrite_if_changed and os.path.exists(self.destination_path)):
            with codecs.open(self.destination_path, encoding=self.encoding) as f:
                # skip writing: content not changed
                if f.read() == data:
                    return data

        return FileOutput.write(self, data)
示例#8
0
    def write(self, data):
        # type: (unicode) -> unicode
        if (self.destination_path and self.autoclose and 'b' not in self.mode and
                self.overwrite_if_changed and os.path.exists(self.destination_path)):
            with open(self.destination_path, encoding=self.encoding) as f:  # type: ignore
                # skip writing: content not changed
                if f.read() == data:
                    return data

        return FileOutput.write(self, data)
示例#9
0
    def write(self, *ignored):
        if self.config.man_pages:
            # build manpages from config.man_pages as usual
            ManualPageBuilder.write(self, *ignored)

        logger.info(bold("scan master tree for kernel-doc man-pages ... ") + darkgreen("{"), nonl=True)

        master_tree = self.env.get_doctree(self.config.master_doc)
        master_tree = inline_all_toctrees(
            self, set(), self.config.master_doc, master_tree, darkgreen, [self.config.master_doc])
        logger.info(darkgreen("}"))
        man_nodes   = master_tree.traverse(condition=self.is_manpage)
        if not man_nodes and not self.config.man_pages:
            logger.warn('no "man_pages" config value nor manual section found; no manual pages '
                        'will be written')
            return

        logger.info(bold('START writing man pages ... '), nonl=True)

        for man_parent in man_nodes:

            doc_tree = self.get_partial_document(man_parent)
            Section2Manpage(doc_tree).apply()

            if not doc_tree.man_info["authors"] and self.config.author:
                doc_tree.man_info["authors"].append(self.config.author)

            doc_writer   = ManualPageWriter(self)
            doc_settings = OptionParser(
                defaults            = self.env.settings
                , components        = (doc_writer,)
                , read_config_files = True
                , ).get_default_values()

            doc_settings.__dict__.update(doc_tree.man_info)
            doc_tree.settings = doc_settings
            targetname  = '%s.%s' % (doc_tree.man_info.title, doc_tree.man_info.section)
            if doc_tree.man_info.decl_type in [
                    "struct", "enum", "union", "typedef"]:
                targetname = "%s_%s" % (doc_tree.man_info.decl_type, targetname)

            destination = FileOutput(
                destination_path = path.join(self.outdir, targetname)
                , encoding='utf-8')

            logger.info(darkgreen(targetname) + " ", nonl=True)
            self.env.resolve_references(doc_tree, doc_tree.man_info.manpage, self)

            # remove pending_xref nodes
            for pendingnode in doc_tree.traverse(addnodes.pending_xref):
                pendingnode.replace_self(pendingnode.children)
            doc_writer.write(doc_tree, destination)
        logger.info("END writing man pages.")
示例#10
0
    def set_output(self, output_file):
        """
        Set the output file and clear the list of already added
        dependencies.

        `output_file` must be a string.  The specified file is
        immediately overwritten.

        If output_file is '-', the output will be written to stdout.
        If it is None, no file output is done when calling add().
        """
        self.list = []
        if output_file:
            if output_file == '-':
                of = None
            else:
                of = output_file
            self.file = FileOutput(destination_path=of,
                                   encoding='utf8', autoclose=False)
        else:
            self.file = None
示例#11
0
    def write(self, *ignored: Any) -> None:
        docwriter = ManualPageWriter(self)
        with warnings.catch_warnings():
            warnings.filterwarnings('ignore', category=DeprecationWarning)
            # DeprecationWarning: The frontend.OptionParser class will be replaced
            # by a subclass of argparse.ArgumentParser in Docutils 0.21 or later.
            docsettings: Any = OptionParser(
                defaults=self.env.settings,
                components=(docwriter, ),
                read_config_files=True).get_default_values()

        for info in self.config.man_pages:
            docname, name, description, authors, section = info
            if docname not in self.env.all_docs:
                logger.warning(
                    __('"man_pages" config value references unknown '
                       'document %s'), docname)
                continue
            if isinstance(authors, str):
                if authors:
                    authors = [authors]
                else:
                    authors = []

            docsettings.title = name
            docsettings.subtitle = description
            docsettings.authors = authors
            docsettings.section = section

            if self.config.man_make_section_directory:
                dirname = 'man%s' % section
                ensuredir(path.join(self.outdir, dirname))
                targetname = '%s/%s.%s' % (dirname, name, section)
            else:
                targetname = '%s.%s' % (name, section)

            logger.info(darkgreen(targetname) + ' { ', nonl=True)
            destination = FileOutput(destination_path=path.join(
                self.outdir, targetname),
                                     encoding='utf-8')

            tree = self.env.get_doctree(docname)
            docnames: Set[str] = set()
            largetree = inline_all_toctrees(self, docnames, docname, tree,
                                            darkgreen, [docname])
            largetree.settings = docsettings
            logger.info('} ', nonl=True)
            self.env.resolve_references(largetree, docname, self)
            # remove pending_xref nodes
            for pendingnode in largetree.findall(addnodes.pending_xref):
                pendingnode.replace_self(pendingnode.children)

            docwriter.write(largetree, destination)
示例#12
0
    def write(self, *ignored: Any) -> None:
        docwriter = ManualPageWriter(self)
        docsettings = OptionParser(
            defaults=self.env.settings,
            components=(docwriter, ),
            read_config_files=True).get_default_values()  # type: Any

        for info in self.config.man_pages:
            docname, name, description, authors, section = info
            if docname not in self.env.all_docs:
                logger.warning(
                    __('"man_pages" config value references unknown '
                       'document %s'), docname)
                continue
            if isinstance(authors, str):
                if authors:
                    authors = [authors]
                else:
                    authors = []

            docsettings.title = name
            docsettings.subtitle = description
            docsettings.authors = authors
            docsettings.section = section

            if self.config.man_make_section_directory:
                ensuredir(path.join(self.outdir, str(section)))
                targetname = '%s/%s.%s' % (section, name, section)
            else:
                targetname = '%s.%s' % (name, section)

            logger.info(darkgreen(targetname) + ' { ', nonl=True)
            destination = FileOutput(destination_path=path.join(
                self.outdir, targetname),
                                     encoding='utf-8')

            tree = self.env.get_doctree(docname)
            docnames = set()  # type: Set[str]
            largetree = inline_all_toctrees(self, docnames, docname, tree,
                                            darkgreen, [docname])
            largetree.settings = docsettings
            logger.info('} ', nonl=True)
            self.env.resolve_references(largetree, docname, self)
            # remove pending_xref nodes
            for pendingnode in largetree.traverse(addnodes.pending_xref):
                pendingnode.replace_self(pendingnode.children)

            docwriter.write(largetree, destination)
示例#13
0
    def write(self, *ignored):
        self.init_document_data()
        for entry in self.document_data:
            docname, targetname, title, author = entry[:4]
            targetname += '.texi'
            direntry = description = category = ''
            if len(entry) > 6:
                direntry, description, category = entry[4:7]
            toctree_only = False
            if len(entry) > 7:
                toctree_only = entry[7]
            destination = FileOutput(destination_path=path.join(
                self.outdir, targetname),
                                     encoding='utf-8')
            self.info("processing " + targetname + "... ", nonl=1)
            doctree = self.assemble_doctree(
                docname,
                toctree_only,
                appendices=(self.config.texinfo_appendices or []))
            self.info("writing... ", nonl=1)

            # Add an Index section
            if self.config.texinfo_domain_indices:
                doctree.append(
                    nodes.section(
                        '',
                        nodes.title(_("Index"),
                                    nodes.Text(_('Index'), _('Index'))),
                        nodes.raw('@printindex ge\n',
                                  nodes.Text('@printindex ge\n',
                                             '@printindex ge\n'),
                                  format="texinfo")))
            self.post_process_images(doctree)
            docwriter = TexinfoWriter(self)
            settings = OptionParser(
                defaults=self.env.settings,
                components=(docwriter, )).get_default_values()
            settings.author = author
            settings.title = title
            settings.texinfo_filename = targetname[:-5] + '.info'
            settings.texinfo_elements = self.config.texinfo_elements
            settings.texinfo_dir_entry = direntry or ''
            settings.texinfo_dir_category = category or ''
            settings.texinfo_dir_description = description or ''
            settings.docname = docname
            doctree.settings = settings
            docwriter.write(doctree, destination)
            self.info("done")
示例#14
0
文件: builders.py 项目: i386x/abcdoc
    def write_doc(self, docname, doctree):
        """
        """

        html_file_suffix = self.get_builder_config("file_suffix", "html")

        if html_file_suffix is not None:
            self.out_suffix = html_file_suffix

        docfile = docname + self.out_suffix
        destination = FileOutput(
            destination_path = os.path.join(self.outdir, docfile),
            encoding = "utf-8"
        )
        doctree.settings = self.docsettings
        self.docwriter.write(doctree, destination)
示例#15
0
    def write(self, *ignored):
        # type: (Any) -> None
        docwriter = LaTeXWriter(self)
        docsettings = OptionParser(
            defaults=self.env.settings,
            components=(docwriter, ),
            read_config_files=True).get_default_values()

        self.init_document_data()
        self.write_stylesheet()

        for entry in self.document_data:
            docname, targetname, title, author, docclass = entry[:5]
            toctree_only = False
            if len(entry) > 5:
                toctree_only = entry[5]
            destination = FileOutput(destination_path=path.join(
                self.outdir, targetname),
                                     encoding='utf-8')
            logger.info(__("processing %s..."), targetname, nonl=1)
            toctrees = self.env.get_doctree(docname).traverse(addnodes.toctree)
            if toctrees:
                if toctrees[0].get('maxdepth') > 0:
                    tocdepth = toctrees[0].get('maxdepth')
                else:
                    tocdepth = None
            else:
                tocdepth = None
            doctree = self.assemble_doctree(
                docname,
                toctree_only,
                appendices=((docclass != 'howto')
                            and self.config.latex_appendices or []))
            doctree['tocdepth'] = tocdepth
            self.apply_transforms(doctree)
            self.post_process_images(doctree)
            logger.info(__("writing... "), nonl=1)
            doctree.settings = docsettings
            doctree.settings.author = author
            doctree.settings.title = title
            doctree.settings.contentsname = self.get_contentsname(docname)
            doctree.settings.docname = docname
            doctree.settings.docclass = docclass
            docwriter.write(doctree, destination)
            logger.info("done")
示例#16
0
    def write_latex_document(self, latex_document_node,
                             all_latex_document_nodes):
        output_filename = latex_document_node["multilatex-filename"]
        variables = latex_document_node["multilatex-variables"]
        content = latex_document_node["multilatex-content"]
        options = latex_document_node["multilatex-options"]
        docname = latex_document_node["multilatex-docname"]
        doctree = latex_document_node["multilatex-doctree"]

        if not output_filename.endswith(".tex"):
            output_filename += ".tex"
        self.info("processing {0}...".format(output_filename), nonl=1)

        #        for node in doctree.traverse(latex_document):
        #            node.parent.remove(node)
        #        parent_node = latex_document_node.parent
        #        parent_node.remove(latex_document_node)

        self.post_process_images(doctree)

        self.info("writing...", nonl=1)
        docwriter = LaTeXWriter(self)
        option_parser = OptionParser(defaults=self.env.settings,
                                     components=(docwriter, ),
                                     read_config_files=True)

        doctree.settings = option_parser.get_default_values()
        settings = doctree.settings
        settings.contentsname = None
        settings.docname = docname
        for name, value in options.items():
            setattr(settings, name, value)
        settings.multilatex_options = options
        settings.multilatex_variables = variables
        settings.multilatex_content = content
        settings.multilatex_output_filename = output_filename
        settings.multilatex_all_latex_document_nodes = all_latex_document_nodes

        destination = FileOutput(destination_path=os.path.join(
            self.outdir, output_filename),
                                 encoding="utf-8")

        docwriter.write(doctree, destination)
        self.info("done")
示例#17
0
    def write(self, *ignored: Any) -> None:
        self.init_document_data()
        for entry in self.document_data:
            docname, targetname, title, author = entry[:4]
            targetname += '.texi'
            direntry = description = category = ''
            if len(entry) > 6:
                direntry, description, category = entry[4:7]
            toctree_only = False
            if len(entry) > 7:
                toctree_only = entry[7]
            destination = FileOutput(destination_path=path.join(
                self.outdir, targetname),
                                     encoding='utf-8')
            with progress_message(__("processing %s") % targetname):
                appendices = self.config.texinfo_appendices or []
                doctree = self.assemble_doctree(docname,
                                                toctree_only,
                                                appendices=appendices)

            with progress_message(__("writing")):
                self.post_process_images(doctree)
                docwriter = TexinfoWriter(self)
                with warnings.catch_warnings():
                    warnings.filterwarnings('ignore',
                                            category=DeprecationWarning)
                    # DeprecationWarning: The frontend.OptionParser class will be replaced
                    # by a subclass of argparse.ArgumentParser in Docutils 0.21 or later.
                    settings: Any = OptionParser(
                        defaults=self.env.settings,
                        components=(docwriter, ),
                        read_config_files=True).get_default_values()
                settings.author = author
                settings.title = title
                settings.texinfo_filename = targetname[:-5] + '.info'
                settings.texinfo_elements = self.config.texinfo_elements
                settings.texinfo_dir_entry = direntry or ''
                settings.texinfo_dir_category = category or ''
                settings.texinfo_dir_description = description or ''
                settings.docname = docname
                doctree.settings = settings
                docwriter.write(doctree, destination)
                self.copy_image_files(targetname[:-5])
示例#18
0
    def write(self, *ignored):
        # type: (Any) -> None
        docwriter = ManualPageWriter(self)
        docsettings = OptionParser(
            defaults=self.env.settings,
            components=(docwriter, ),
            read_config_files=True).get_default_values()

        logger.info(bold('writing... '), nonl=True)

        for info in self.config.man_pages:
            docname, name, description, authors, section = info
            if isinstance(authors, string_types):
                if authors:
                    authors = [authors]
                else:
                    authors = []

            targetname = '%s.%s' % (name, section)
            logger.info(darkgreen(targetname) + ' { ', nonl=True)
            destination = FileOutput(destination_path=path.join(
                self.outdir, targetname),
                                     encoding='utf-8')

            tree = self.env.get_doctree(docname)
            docnames = set()  # type: Set[unicode]
            largetree = inline_all_toctrees(self, docnames, docname, tree,
                                            darkgreen, [docname])
            logger.info('} ', nonl=True)
            self.env.resolve_references(largetree, docname, self)
            # remove pending_xref nodes
            for pendingnode in largetree.traverse(addnodes.pending_xref):
                pendingnode.replace_self(pendingnode.children)

            largetree.settings = docsettings
            largetree.settings.title = name
            largetree.settings.subtitle = description
            largetree.settings.authors = authors
            largetree.settings.section = section

            docwriter.write(largetree, destination)
        logger.info('')
示例#19
0
    def write_doc(self, docCfg):  # pylint: disable=W0221
        """Where you actually write something to the filesystem.
        """
        self.info("processing " + docCfg.targetname + "... ", nonl=1)

        # The argument doctree are covered by the self.assemble_doctree
        # method. The docCfg is shipped in the writer.document.docCfg

        doctree = self.assemble_doctree(docCfg)
        doctree.docCfg = docCfg

        self.post_process_images(doctree)
        self.info("writing... ", nonl=1)
        outFile = FileOutput(destination_path=path.join(
            self.outdir, docCfg.targetname),
                             encoding='utf-8')

        writer = self.writerClass(self)
        writer.write(doctree, outFile)
        self.info("done")
示例#20
0
    def set_output(self, output_file):
        """
        Set the output file and clear the list of already added
        dependencies.

        `output_file` must be a string.  The specified file is
        immediately overwritten.

        If output_file is '-', the output will be written to stdout.
        If it is None, no file output is done when calling add().
        """
        self.list = []
        if output_file:
            if output_file == '-':
                of = None
            else:
                of = output_file
            self.file = FileOutput(destination_path=of,
                                   encoding='utf8', autoclose=False)
        else:
            self.file = None
示例#21
0
    def write(self, *ignored):
        # type: (Any) -> None
        self.init_document_data()
        for entry in self.document_data:
            docname, targetname, title, author = entry[:4]
            targetname += '.texi'
            direntry = description = category = ''
            if len(entry) > 6:
                direntry, description, category = entry[4:7]
            toctree_only = False
            if len(entry) > 7:
                toctree_only = entry[7]
            destination = FileOutput(destination_path=path.join(
                self.outdir, targetname),
                                     encoding='utf-8')
            with progress_message(__("processing %s") % targetname):
                appendices = self.config.texinfo_appendices or []
                doctree = self.assemble_doctree(docname,
                                                toctree_only,
                                                appendices=appendices)

            with progress_message(__("writing")):
                self.post_process_images(doctree)
                docwriter = TexinfoWriter(self)
                settings = OptionParser(
                    defaults=self.env.settings,
                    components=(docwriter, ),
                    read_config_files=True).get_default_values()  # type: Any
                settings.author = author
                settings.title = title
                settings.texinfo_filename = targetname[:-5] + '.info'
                settings.texinfo_elements = self.config.texinfo_elements
                settings.texinfo_dir_entry = direntry or ''
                settings.texinfo_dir_category = category or ''
                settings.texinfo_dir_description = description or ''
                settings.docname = docname
                doctree.settings = settings
                docwriter.write(doctree, destination)
                self.copy_image_files(targetname[:-5])
示例#22
0
class DependencyList(object):

    """
    List of dependencies, with file recording support.

    Note that the output file is not automatically closed.  You have
    to explicitly call the close() method.
    """

    def __init__(self, output_file=None, dependencies=[]):
        """
        Initialize the dependency list, automatically setting the
        output file to `output_file` (see `set_output()`) and adding
        all supplied dependencies.
        """
        self.set_output(output_file)
        for i in dependencies:
            self.add(i)

    def set_output(self, output_file):
        """
        Set the output file and clear the list of already added
        dependencies.

        `output_file` must be a string.  The specified file is
        immediately overwritten.

        If output_file is '-', the output will be written to stdout.
        If it is None, no file output is done when calling add().
        """
        self.list = []
        if output_file:
            if output_file == '-':
                of = None
            else:
                of = output_file
            self.file = FileOutput(destination_path=of,
                                   encoding='utf8', autoclose=False)
        else:
            self.file = None

    def add(self, *filenames):
        """
        If the dependency `filename` has not already been added,
        append it to self.list and print it to self.file if self.file
        is not None.
        """
        for filename in filenames:
            if not filename in self.list:
                self.list.append(filename)
                if self.file is not None:
                    self.file.write(filename+'\n')

    def close(self):
        """
        Close the output file.
        """
        self.file.close()
        self.file = None

    def __repr__(self):
        try:
            output_file = self.file.name
        except AttributeError:
            output_file = None
        return '%s(%r, %s)' % (self.__class__.__name__, output_file, self.list)
示例#23
0
 def __init__(self, **kwargs):
     # type: (Any) -> None
     self.overwrite_if_changed = kwargs.pop('overwrite_if_changed', False)
     FileOutput.__init__(self, **kwargs)
示例#24
0
def doctree_resolved(app, doctree, docname):
    builder = app.builder

    for node in doctree.traverse(PendingICS):

        series_name = node._series_name
        data = node._data

        LOG.info('building {} calendar'.format(series_name))

        cal = icalendar.Calendar()
        cal.add('prodid', '-//releases.openstack.org//EN')
        cal.add('X-WR-CALNAME', '{} schedule'.format(series_name))

        for week in data['cycle']:
            if not week.get('name'):
                continue

            event = icalendar.Event()

            summary = []
            for item in week.get('x-project', []):
                try:
                    # Look up the cross-reference name to get the
                    # section, then get the title from the first child
                    # node.
                    title = doctree.ids[item].children[0].astext()
                except Exception as e:
                    # NOTE(dhellmann): Catching "Exception" is a bit
                    # ugly, but given the complexity of the expression
                    # above there are a bunch of ways things might
                    # fail.
                    LOG.info('could not get title for {}: {}'.format(item, e))
                    title = item
                summary.append(title)
            if summary:
                summary_text = ' (' + '; '.join(summary) + ')'
            else:
                summary_text = ''
            event.add(
                'summary',
                '{} {}{}'.format(series_name.title(), week['name'],
                                 summary_text),
            )

            event.add('dtstamp', node.last_update)
            event.add('uid', '%s-%s' % (series_name, week.get('name')))

            start = datetime.datetime.strptime(week['start'], '%Y-%m-%d')
            event.add('dtstart', icalendar.vDate(start.date()))

            # NOTE(dhellmann): ical assumes a time of midnight, so in
            # order to have the event span the final day of the week
            # we have to add an extra day.
            raw_end = datetime.datetime.strptime(week['end'], '%Y-%m-%d')
            end = raw_end + datetime.timedelta(days=1)
            event.add('dtend', icalendar.vDate(end.date()))

            # Look up the cross-reference name to get the
            # section, then add the full description to the
            # text.
            description = [
                _format_description(doctree.ids[item])
                for item in week.get('x-project', []) if item in doctree.ids
            ]
            if description:
                event.add('description', '\n\n'.join(description))

            cal.add_component(event)
            _global_calendar.add_component(event)

        output_full_name = os.path.join(
            builder.outdir,
            docname + '.ics',
        )
        output_dir_name = os.path.dirname(output_full_name)
        if not os.path.exists(output_dir_name):
            os.makedirs(output_dir_name)
        destination = FileOutput(
            destination_path=output_full_name,
            encoding='utf-8',
        )
        LOG.info('generating {}'.format(output_full_name))
        destination.write(cal.to_ical())

        # Remove the node that the writer won't understand.
        node.parent.replace(node, [])
示例#25
0
class DependencyList(object):
    """
    List of dependencies, with file recording support.

    Note that the output file is not automatically closed.  You have
    to explicitly call the close() method.
    """
    def __init__(self, output_file=None, dependencies=[]):
        """
        Initialize the dependency list, automatically setting the
        output file to `output_file` (see `set_output()`) and adding
        all supplied dependencies.
        """
        self.set_output(output_file)
        for i in dependencies:
            self.add(i)

    def set_output(self, output_file):
        """
        Set the output file and clear the list of already added
        dependencies.

        `output_file` must be a string.  The specified file is
        immediately overwritten.

        If output_file is '-', the output will be written to stdout.
        If it is None, no file output is done when calling add().
        """
        self.list = []
        if output_file:
            if output_file == '-':
                of = None
            else:
                of = output_file
            self.file = FileOutput(destination_path=of,
                                   encoding='utf8',
                                   autoclose=False)
        else:
            self.file = None

    def add(self, *filenames):
        """
        If the dependency `filename` has not already been added,
        append it to self.list and print it to self.file if self.file
        is not None.
        """
        for filename in filenames:
            if not filename in self.list:
                self.list.append(filename)
                if self.file is not None:
                    self.file.write(filename + '\n')

    def close(self):
        """
        Close the output file.
        """
        self.file.close()
        self.file = None

    def __repr__(self):
        try:
            output_file = self.file.name
        except AttributeError:
            output_file = None
        return '%s(%r, %s)' % (self.__class__.__name__, output_file, self.list)
示例#26
0
    def write(self, *ignored):

        self.init_document_data()

        if self.config.pdf_verbosity > 1:
            log.setLevel(logging.DEBUG)
        elif self.config.pdf_verbosity > 0:
            log.setLevel(logging.INFO)

        for entry in self.document_data:
            try:
                docname, targetname, title, author = entry[:4]
                # Custom options per document
                if len(entry)>4 and isinstance(entry[4],dict):
                    opts=entry[4]
                else:
                    opts={}
                self.spinx_logger.info("processing " + targetname + "... ")
                self.opts = opts
                class dummy:
                    extensions=self.config.pdf_extensions

                createpdf.add_extensions(dummy())

                self.page_template=opts.get('pdf_page_template',self.config.pdf_page_template)

                docwriter = PDFWriter(self,
                                stylesheets=opts.get('pdf_stylesheets',self.config.pdf_stylesheets),
                                language=opts.get('pdf_language',self.config.pdf_language),
                                breaklevel=opts.get('pdf_break_level',self.config.pdf_break_level),
                                breakside=opts.get('pdf_breakside',self.config.pdf_breakside),
                                fontpath=opts.get('pdf_font_path',self.config.pdf_font_path),
                                fitmode=opts.get('pdf_fit_mode',self.config.pdf_fit_mode),
                                compressed=opts.get('pdf_compressed',self.config.pdf_compressed),
                                inline_footnotes=opts.get('pdf_inline_footnotes',self.config.pdf_inline_footnotes),
                                splittables=opts.get('pdf_splittables',self.config.pdf_splittables),
                                repeat_table_rows=opts.get('pdf_repeat_table_rows',self.config.pdf_repeat_table_rows),
                                default_dpi=opts.get('pdf_default_dpi',self.config.pdf_default_dpi),
                                page_template=self.page_template,
                                invariant=opts.get('pdf_invariant',self.config.pdf_invariant),
                                real_footnotes=opts.get('pdf_real_footnotes',self.config.pdf_real_footnotes),
                                use_toc=opts.get('pdf_use_toc',self.config.pdf_use_toc),
                                toc_depth=opts.get('pdf_toc_depth',self.config.pdf_toc_depth),
                                use_coverpage=opts.get('pdf_use_coverpage',self.config.pdf_use_coverpage),
                                use_numbered_links=opts.get('pdf_use_numbered_links',self.config.pdf_use_numbered_links),
                                fit_background_mode=opts.get('pdf_fit_background_mode',self.config.pdf_fit_background_mode),
                                baseurl=opts.get('pdf_baseurl',self.config.pdf_baseurl),
                                section_header_depth=opts.get('section_header_depth',self.config.section_header_depth),
                                srcdir=self.srcdir,
                                style_path=opts.get('pdf_style_path', self.config.pdf_style_path),
                                config=self.config,
                                )

                tgt_file = path.join(self.outdir, targetname + self.out_suffix)
                destination = FileOutput(destination=open(tgt_file,'wb'), encoding='utf-8')
                doctree = self.assemble_doctree(docname,title,author,
                    appendices=opts.get('pdf_appendices', self.config.pdf_appendices) or [])
                doctree.settings.author=author
                doctree.settings.title=title
                self.spinx_logger.info("done")
                self.spinx_logger.info("writing " + targetname + "... ")
                docwriter.write(doctree, destination)
                self.spinx_logger.info("done")
            except Exception as e:
                log.exception(e)
                self.spinx_logger.info(red("FAILED"))
示例#27
0
文件: docutils.py 项目: mgeier/sphinx
 def __init__(self, **kwargs):
     # type: (Any) -> None
     self.overwrite_if_changed = kwargs.pop('overwrite_if_changed', False)
     FileOutput.__init__(self, **kwargs)
示例#28
0
def onIconDoubleClick(tag, keywords):

    c = keywords.get("c")
    p = keywords.get("p")
    # g.trace(c)

    if not c or not p:
        return

    applyConfiguration(c)
    config.tag = tag

    h = p.headString().strip()

    if g.match_word(h, 0, "@rst"):
        if len(h) > 5:
            fname = h[5:]
            ext = os.path.splitext(fname)[1].lower()
            if ext in ('.htm', '.html', '.tex'):
                #@                << write rST as HTML/LaTeX >>
                #@+node:ekr.20040331071319.4:<< write rST as HTML/LaTeX >>
                try:
                    import docutils
                except:
                    g.es('HTML/LaTeX generation requires docutils')
                    return
                else:
                    import docutils.parsers.rst
                    from docutils.core import Publisher
                    from docutils.io import StringOutput, StringInput, FileOutput, FileInput
                    import StringIO

                # Set the writer and encoding for the converted file
                if ext in ('.html', '.htm'):
                    writer = 'html'
                    enc = "utf-8"
                else:
                    writer = 'latex'
                    enc = "iso-8859-1"

                syntax = False
                if writer == 'html':
                    try:
                        import SilverCity

                        #@        << define code-block >>
                        #@+node:ekr.20040331071319.5:<< define code-block >>
                        def code_block(name, arguments, options, content,
                                       lineno, content_offset, block_text,
                                       state, state_machine):
                            """Create a code-block directive for docutils."""

                            # See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252170
                            language = arguments[0]
                            module = getattr(SilverCity, language)
                            generator = getattr(module,
                                                language + "HTMLGenerator")
                            io = StringIO.StringIO()
                            generator().generate_html(io, '\n'.join(content))
                            html = '<div class="code-block">\n%s\n</div>\n' % io.getvalue(
                            )
                            raw = docutils.nodes.raw(
                                '', html, format='html'
                            )  #(self, rawsource='', text='', *children, **attributes):
                            return [raw]

                        # These are documented at http://docutils.sourceforge.net/spec/howto/rst-directives.html.
                        code_block.arguments = (
                            1,  # Number of required arguments.
                            0,  # Number of optional arguments.
                            0
                        )  # True if final argument may contain whitespace.

                        # A mapping from option name to conversion function.
                        code_block.options = {
                            'language': docutils.parsers.rst.directives.
                            unchanged  # Return the text argument, unchanged
                        }

                        code_block.content = 1  # True if content is allowed.

                        # Register the directive with docutils.
                        docutils.parsers.rst.directives.register_directive(
                            'code-block', code_block)

                        config.do_replace_code_blocks = False
                        #@nonl
                        #@-node:ekr.20040331071319.5:<< define code-block >>
                        #@nl
                        syntax = True
                    except ImportError:
                        g.es(
                            'SilverCity not present so no syntax highlighting')
                        #@        << define alternate code block implementation>>
                        #@+node:bwmulder.20050326114320: << define alternate code block implementation>>
                        # Don't know what to do here: Can someone make a suggestion?
                        #import docutils.parsers.rst.directives.admonitions
                        #import docutils.parsers.rst.directives.body
                        # docutils.parsers.rst.directives._directives['code-block'] = docutils.parsers.rst.directives.body.block
                        # docutils.parsers.rst.directives.register_directive('code-block', docutils.parsers.rst.directives.admonitions.admonition)
                        #docutils.parsers.rst.directives._directives['code-block'] = docutils.parsers.rst.directives.body.pull_quote
                        # g.es("Registered some alternate implementation for code-block directive")
                        config.do_replace_code_blocks = config.rst2_replace_code_blocks
                        #@-node:bwmulder.20050326114320: << define alternate code block implementation>>
                        #@nl

                if config.rst2file:
                    rstFileName = os.path.splitext(fname)[0] + ".txt"
                    rstFile = file(rstFileName, "w")
                    g.es("Using %s as rst file" % rstFileName)
                else:
                    rstFile = StringIO.StringIO()
                config.current_file = fname
                writeTreeAsRst(rstFile, fname, p, c, syntax=syntax)
                if config.rst2file:
                    rstFile.close()
                else:
                    rstText = rstFile.getvalue()

                # This code snipped has been taken from code contributed by Paul Paterson 2002-12-05.
                pub = Publisher()
                if config.rst2file:
                    pub.source = FileInput(source_path=rstFileName)
                    pub.destination = FileOutput(destination_path=fname,
                                                 encoding='unicode')
                else:
                    pub.source = StringInput(source=rstText)
                    pub.destination = StringOutput(pub.settings, encoding=enc)
                pub.set_reader('standalone', None, 'restructuredtext')
                pub.set_writer(writer)
                output = pub.publish(argv=[''])

                if config.rst2file:
                    pass
                else:
                    convertedFile = file(fname, 'w')
                    convertedFile.write(output)
                    convertedFile.close()
                rstFile.close()
                writeFullFileName(fname)
                return http_support_main(tag, fname)

                #@-node:ekr.20040331071319.4:<< write rST as HTML/LaTeX >>
                #@nl
            else:
                #@                << write rST file >>
                #@+node:ekr.20040331071319.6:<< write rST file >>
                rstFile = file(fname, 'w')
                writeTreeAsRst(rstFile, fname, p, c)
                rstFile.close()
                writeFullFileName(fname)
                #@nonl
                #@-node:ekr.20040331071319.6:<< write rST file >>
                #@nl
        else:
            # if the headline only contains @rst then open the node and its parent in text editor
            # this works for me but needs to be generalized and should probably be a component
            # of the open_with plugin.
            if 0:
                c.openWith(("os.startfile", None, ".txt"))
                c.selectVnode(p.parent())
                c.openWith(("os.startfile", None, ".tp"))
示例#29
0
 def __set__(self, instance, value, *args, **kwargs):
     if isinstance(value, str):
         destination = FileOutput(destination_path=os.path.abspath(value))
     else:
         destination = StringOutput(encoding='unicode')
     super().__set__(instance, destination)