Example #1
0
    def fetch(self, node):
        """
        return key and target document name for provided asset

        When given a asset, cached information will return the name of the
        target document this asset will be published to. In the event an asset
        exists on a single page, the name of that respective page will be
        returned; however, if the asset is found on multiple pages, the root
        document name will be returned instead.

        Args:
            node: the node to interpret

        Returns:
            the key and document name
        """
        docname = None
        key = None

        path = self._interpretAssetPath(node)
        if path:
            asset = self.path2asset.get(path, None)

            # process node if asset is missing (third-party extensions)
            #
            # If a node's asset cannot be found, this image node may have been
            # created after pre-processing occurred. Attempt to re-process the
            # node as a standalone image.
            if not asset and node.document:
                docname = canon_path(self.env.path2doc(
                    node.document['source']))

                if isinstance(node, nodes.image):
                    self.processImageNode(node, docname, standalone=True)
                elif isinstance(node, addnodes.download_reference):
                    self.processFileNode(node, docname, standalone=True)

                asset = self.path2asset.get(path, None)

            if asset:
                key = asset.key

                if not docname:
                    if self.force_standalone:
                        docname = canon_path(
                            self.env.path2doc(node.document['source']))
                        assert docname in asset.docnames
                    else:
                        if len(asset.docnames) > 1:
                            docname = self.root_doc
                        else:
                            docname = next(iter(asset.docnames))

        if not key:
            docname = None

        return key, docname
Example #2
0
 def _collect_templates(self):
     template_files = set()
     for template_path in self.config.templates_path:
         tmpl_abs_path = path.join(self.app.srcdir, template_path)
         for dirpath, dirs, files in walk(tmpl_abs_path):
             for fn in files:
                 if fn.endswith('.html'):
                     filename = canon_path(path.join(dirpath, fn))
                     template_files.add(filename)
     return template_files
 def _collect_templates(self) -> Set[str]:
     template_files = set()
     for template_path in self.config.templates_path:
         tmpl_abs_path = path.join(self.app.srcdir, template_path)
         for dirpath, dirs, files in walk(tmpl_abs_path):
             for fn in files:
                 if fn.endswith('.html'):
                     filename = canon_path(path.join(dirpath, fn))
                     template_files.add(filename)
     return template_files
Example #4
0
    def finish(self):
        # type: () -> None
        super(MessageCatalogBuilder, self).finish()
        data = {
            'version':
            self.config.version,
            'copyright':
            self.config.copyright,
            'project':
            self.config.project,
            'ctime':
            datetime.fromtimestamp(timestamp,
                                   ltz).strftime('%Y-%m-%d %H:%M%z'),
        }
        for textdomain, catalog in status_iterator(
                self.catalogs.items(),  # type: ignore
                __("writing message catalogs... "),
                "darkgreen",
                len(self.catalogs),
                self.app.verbosity,
                lambda textdomain__: textdomain__[0]):
            # noop if config.gettext_compact is set
            ensuredir(path.join(self.outdir, path.dirname(textdomain)))

            pofn = path.join(self.outdir, textdomain + '.pot')
            output = StringIO()
            output.write(POHEADER % data)  # type: ignore

            for message in catalog.messages:
                positions = catalog.metadata[message]

                if self.config.gettext_location:
                    # generate "#: file1:line1\n#: file2:line2 ..."
                    output.write("#: %s\n" % "\n#: ".join(  # type: ignore
                        "%s:%s" %
                        (canon_path(relpath(source, self.outdir)), line)
                        for source, line, _ in positions))
                if self.config.gettext_uuid:
                    # generate "# uuid1\n# uuid2\n ..."
                    output.write("# %s\n" % "\n# ".join(  # type: ignore
                        uid for _, _, uid in positions))

                # message contains *one* line of text ready for translation
                message = message.replace('\\', r'\\'). \
                    replace('"', r'\"'). \
                    replace('\n', '\\n"\n"')
                output.write('msgid "%s"\nmsgstr ""\n\n' %
                             message)  # type: ignore

            content = output.getvalue()

            if should_write(pofn, content):
                with open(pofn, 'w',
                          encoding='utf-8') as pofile:  # type: ignore
                    pofile.write(content)
Example #5
0
    def get_project_files(self, outdir: str) -> List[str]:
        if not outdir.endswith(os.sep):
            outdir += os.sep
        olen = len(outdir)
        project_files = []
        staticdir = path.join(outdir, '_static')
        imagesdir = path.join(outdir, self.imagedir)
        for root, dirs, files in os.walk(outdir):
            resourcedir = root.startswith((staticdir, imagesdir))
            for fn in sorted(files):
                if (resourcedir and not fn.endswith('.js')) or fn.endswith('.html'):
                    filename = path.join(root, fn)[olen:]
                    project_files.append(canon_path(filename))

        return project_files
Example #6
0
    def finish(self):
        # type: () -> None
        I18nBuilder.finish(self)
        data = dict(
            version = self.config.version,
            copyright = self.config.copyright,
            project = self.config.project,
            ctime = datetime.fromtimestamp(
                timestamp, ltz).strftime('%Y-%m-%d %H:%M%z'),
        )
        for textdomain, catalog in status_iterator(iteritems(self.catalogs),  # type: ignore
                                                   "writing message catalogs... ",
                                                   "darkgreen", len(self.catalogs),
                                                   self.app.verbosity,
                                                   lambda textdomain__: textdomain__[0]):
            # noop if config.gettext_compact is set
            ensuredir(path.join(self.outdir, path.dirname(textdomain)))

            pofn = path.join(self.outdir, textdomain + '.pot')
            output = StringIO()
            output.write(POHEADER % data)  # type: ignore

            for message in catalog.messages:
                positions = catalog.metadata[message]

                if self.config.gettext_location:
                    # generate "#: file1:line1\n#: file2:line2 ..."
                    output.write("#: %s\n" % "\n#: ".join(  # type: ignore
                        "%s:%s" % (canon_path(
                            safe_relpath(source, self.outdir)), line)
                        for source, line, _ in positions))
                if self.config.gettext_uuid:
                    # generate "# uuid1\n# uuid2\n ..."
                    output.write("# %s\n" % "\n# ".join(  # type: ignore
                        uid for _, _, uid in positions))

                # message contains *one* line of text ready for translation
                message = message.replace('\\', r'\\'). \
                    replace('"', r'\"'). \
                    replace('\n', '\\n"\n"')
                output.write('msgid "%s"\nmsgstr ""\n\n' % message)  # type: ignore

            content = output.getvalue()

            if should_write(pofn, content):
                with open(pofn, 'w', encoding='utf-8') as pofile:  # type: ignore
                    pofile.write(content)
Example #7
0
    def finish(self):
        I18nBuilder.finish(self)
        data = dict(
            version=self.config.version,
            copyright=self.config.copyright,
            project=self.config.project,
            ctime=datetime.fromtimestamp(timestamp,
                                         ltz).strftime('%Y-%m-%d %H:%M%z'),
        )
        for textdomain, catalog in self.app.status_iterator(
                iteritems(self.catalogs), "writing message catalogs... ",
                darkgreen, len(self.catalogs),
                lambda textdomain__: textdomain__[0]):
            # noop if config.gettext_compact is set
            ensuredir(path.join(self.outdir, path.dirname(textdomain)))

            pofn = path.join(self.outdir, textdomain + '.pot')

            output = StringIO()
            output.write(POHEADER % data)

            for message in catalog.messages:
                positions = catalog.metadata[message]

                if self.config.gettext_location:
                    # generate "#: file1:line1\n#: file2:line2 ..."
                    output.write("#: %s\n" % "\n#: ".join(
                        "%s:%s" %
                        (canon_path(safe_relpath(source, self.outdir)), line)
                        for source, line, _ in positions))
                if self.config.gettext_uuid:
                    # generate "# uuid1\n# uuid2\n ..."
                    output.write("# %s\n" %
                                 "\n# ".join(uid for _, _, uid in positions))

                # message contains *one* line of text ready for translation
                message = message.replace('\\', r'\\'). \
                    replace('"', r'\"'). \
                    replace('\n', '\\n"\n"')
                output.write('msgid "%s"\nmsgstr ""\n\n' % message)

            content = output.getvalue()

            if should_write(pofn, content):
                with open(pofn, 'w', encoding='utf-8') as pofile:
                    pofile.write(content)
Example #8
0
    def finish(self):
        I18nBuilder.finish(self)
        data = dict(
            version=self.config.version,
            copyright=self.config.copyright,
            project=self.config.project,
            ctime=datetime.fromtimestamp(timestamp, ltz).strftime("%Y-%m-%d %H:%M%z"),
        )
        for textdomain, catalog in self.app.status_iterator(
            iteritems(self.catalogs),
            "writing message catalogs... ",
            darkgreen,
            len(self.catalogs),
            lambda textdomain__: textdomain__[0],
        ):
            # noop if config.gettext_compact is set
            ensuredir(path.join(self.outdir, path.dirname(textdomain)))

            pofn = path.join(self.outdir, textdomain + ".pot")
            pofile = open(pofn, "w", encoding="utf-8")
            try:
                pofile.write(POHEADER % data)

                for message in catalog.messages:
                    positions = catalog.metadata[message]

                    if self.config.gettext_location:
                        # generate "#: file1:line1\n#: file2:line2 ..."
                        pofile.write(
                            "#: %s\n"
                            % "\n#: ".join(
                                "%s:%s" % (canon_path(safe_relpath(source, self.outdir)), line)
                                for source, line, _ in positions
                            )
                        )
                    if self.config.gettext_uuid:
                        # generate "# uuid1\n# uuid2\n ..."
                        pofile.write("# %s\n" % "\n# ".join(uid for _, _, uid in positions))

                    # message contains *one* line of text ready for translation
                    message = message.replace("\\", r"\\").replace('"', r"\"").replace("\n", '\\n"\n"')
                    pofile.write('msgid "%s"\nmsgstr ""\n\n' % message)

            finally:
                pofile.close()
Example #9
0
    def relfn2path(self, filename: str, docname: str = None) -> Tuple[str, str]:
        """Return paths to a file referenced from a document, relative to
        documentation root and absolute.

        In the input "filename", absolute filenames are taken as relative to the
        source dir, while relative filenames are relative to the dir of the
        containing document.
        """
        filename = os_path(filename)
        if filename.startswith('/') or filename.startswith(os.sep):
            rel_fn = filename[1:]
        else:
            docdir = path.dirname(self.doc2path(docname or self.docname,
                                                base=None))
            rel_fn = path.join(docdir, filename)

        return (canon_path(path.normpath(rel_fn)),
                path.normpath(path.join(self.srcdir, rel_fn)))
Example #10
0
    def fetch(self, node, docname=None):
        """
        return key and target document name for provided asset

        When given a asset, cached information will return the name of the
        target document this asset will be published to. In the event an asset
        exists on a single page, the name of that respective page will be
        returned; however, if the asset is found on multiple pages, the root
        document name will be returned instead.

        Args:
            node: the node to interpret
            docname (optional): force the document name for this asset

        Returns:
            the key, document name and path
        """
        key = None

        path = self._interpret_asset_path(node)
        if path:
            asset = self.path2asset.get(path, None)

            if asset:
                key = asset.key

                if not docname:
                    if self.force_standalone:
                        docname = canon_path(
                            self.env.path2doc(node.document['source']))
                        assert docname in asset.docnames
                    else:
                        if len(asset.docnames) > 1:
                            docname = self.root_doc
                        else:
                            docname = next(iter(asset.docnames))

        if not key:
            docname = None
            path = None

        return key, docname, path
Example #11
0
    def __init__(self, document, builder):
        BaseTranslator.__init__(self, document)
        self.builder = builder
        self.state = builder.state
        self.verbose = ConfluenceLogger.verbose
        self.warn = ConfluenceLogger.warn
        config = builder.config

        # acquire the active document name from the builder
        assert 'source' in document
        self.docname = canon_path(self.builder.env.path2doc(document['source']))

        # determine the active document's parent path to assist it title mapping
        # for relative document uris
        # (see '_visit_reference_intern_uri')
        if SEP in self.docname:
            self.docparent = self.docname[0 : self.docname.rfind(SEP) + 1]
        else:
            self.docparent = ''

        self.assets = builder.assets
        self.body = []
        self.context = []
        self.nl = '\n'
        self._docnames = [self.docname]
        self._literal = False
        self._section_level = 1
        self._topic = False

        if config.confluence_default_alignment:
            self._default_alignment = config.confluence_default_alignment
        else:
            self._default_alignment = DEFAULT_ALIGNMENT

        if config.highlight_language:
            self._highlight = config.highlight_language
        else:
            self._highlight = DEFAULT_HIGHLIGHT_STYLE
        self._linenothreshold = sys.maxsize
 def _relpath(s: str) -> str:
     return canon_path(relpath(s, self.outdir))
Example #13
0
 def catalogs(self):
     # type: () -> Generator[CatalogInfo, None, None]
     for basedir, filename in self.pofiles:
         domain = canon_path(path.splitext(filename)[0])
         yield CatalogInfo(basedir, domain, self.encoding)
Example #14
0
 def match(self, string: str) -> bool:
     string = canon_path(string)
     return any(pat(string) for pat in self.patterns)
Example #15
0
 def match(self, string):
     # type: (unicode) -> bool
     string = canon_path(string)
     return any(pat(string) for pat in self.patterns)
Example #16
0
 def match(self, string):
     # type: (str) -> bool
     string = canon_path(string)
     return any(pat(string) for pat in self.patterns)