Example #1
0
    def init_context(self) -> None:
        self.context = DEFAULT_SETTINGS.copy()

        # Add special settings for latex_engine
        self.context.update(ADDITIONAL_SETTINGS.get(self.config.latex_engine, {}))

        # Add special settings for (latex_engine, language_code)
        if self.config.language:
            key = (self.config.latex_engine, self.config.language[:2])
            self.context.update(ADDITIONAL_SETTINGS.get(key, {}))

        # Apply extension settings to context
        self.context['packages'] = self.usepackages
        self.context['packages_after_hyperref'] = self.usepackages_after_hyperref

        # Apply user settings to context
        self.context.update(self.config.latex_elements)
        self.context['release'] = self.config.release
        self.context['use_xindy'] = self.config.latex_use_xindy

        if self.config.today:
            self.context['date'] = self.config.today
        else:
            self.context['date'] = format_date(self.config.today_fmt or _('%b %d, %Y'),
                                               language=self.config.language)

        if self.config.latex_logo:
            self.context['logofilename'] = path.basename(self.config.latex_logo)

        # for compatibilities
        self.context['indexname'] = _('Index')
        if self.config.release:
            # Show the release label only if release value exists
            self.context.setdefault('releasename', _('Release'))
Example #2
0
def _html_page_context(app, pagename, templatename, context, doctree):
    context['last_updated'] = None
    lufmt = app.config.html_last_updated_fmt
    if lufmt is None or 'sourcename' not in context:
        return
    sourcefile = Path(app.confdir, pagename + context['page_source_suffix'])
    try:
        dates = [get_datetime(sourcefile)]
    except subprocess.CalledProcessError as e:
        logger.warning('Git error:\n%s', e.stderr, location=pagename)
        return
    except FileNotFoundError as e:
        logger.warning('"git" command not found: %s', e, location=pagename)
        return

    # Check dependencies (if they are in a Git repo)
    for dep in app.env.dependencies[pagename]:
        path = Path(app.confdir, dep)
        try:
            date = get_datetime(path)
        except Exception:
            continue
        else:
            dates.append(date)

    context['last_updated'] = format_date(
        lufmt or _('%b %d, %Y'),
        date=max(dates),
        language=app.config.language)
Example #3
0
    def __init__(self, document: nodes.document, builder: Builder) -> None:
        super().__init__(document, builder)

        self.in_productionlist = 0

        # first title is the manpage title
        self.section_level = -1

        # docinfo set by man_pages config value
        self._docinfo['title'] = self.settings.title
        self._docinfo['subtitle'] = self.settings.subtitle
        if self.settings.authors:
            # don't set it if no author given
            self._docinfo['author'] = self.settings.authors
        self._docinfo['manual_section'] = self.settings.section

        # docinfo set by other config values
        self._docinfo['title_upper'] = self._docinfo['title'].upper()
        if self.config.today:
            self._docinfo['date'] = self.config.today
        else:
            self._docinfo['date'] = format_date(self.config.today_fmt or _('%b %d, %Y'),
                                                language=self.config.language)
        self._docinfo['copyright'] = self.config.copyright
        self._docinfo['version'] = self.config.version
        self._docinfo['manual_group'] = self.config.project

        # Overwrite admonition label translations with our own
        for label, translation in admonitionlabels.items():
            self.language.labels[label] = self.deunicode(translation)  # type: ignore
Example #4
0
    def __init__(self, builder, *args, **kwds):
        BaseTranslator.__init__(self, *args, **kwds)
        self.builder = builder

        self.in_productionlist = 0

        # first title is the manpage title
        self.section_level = -1

        # docinfo set by man_pages config value
        self._docinfo['title'] = self.document.settings.title
        self._docinfo['subtitle'] = self.document.settings.subtitle
        if self.document.settings.authors:
            # don't set it if no author given
            self._docinfo['author'] = self.document.settings.authors
        self._docinfo['manual_section'] = self.document.settings.section

        # docinfo set by other config values
        self._docinfo['title_upper'] = self._docinfo['title'].upper()
        if builder.config.today:
            self._docinfo['date'] = builder.config.today
        else:
            self._docinfo['date'] = format_date(builder.config.today_fmt or _('%b %d, %Y'),
                                                language=builder.config.language)
        self._docinfo['copyright'] = builder.config.copyright
        self._docinfo['version'] = builder.config.version
        self._docinfo['manual_group'] = builder.config.project

        # In docutils < 0.11 self.append_header() was never called
        if docutils_version < (0, 11):
            self.body.append(MACRO_DEF)

        # Overwrite admonition label translations with our own
        for label, translation in admonitionlabels.items():
            self.language.labels[label] = self.deunicode(translation)
Example #5
0
    def __init__(self, builder, document):
        # type: (Builder, nodes.document) -> None
        super(ManualPageTranslator, self).__init__(builder, document)

        self.in_productionlist = 0

        # first title is the manpage title
        self.section_level = -1

        # docinfo set by man_pages config value
        self._docinfo['title'] = self.settings.title
        self._docinfo['subtitle'] = self.settings.subtitle
        if self.settings.authors:
            # don't set it if no author given
            self._docinfo['author'] = self.settings.authors
        self._docinfo['manual_section'] = self.settings.section

        # docinfo set by other config values
        self._docinfo['title_upper'] = self._docinfo['title'].upper()
        if self.config.today:
            self._docinfo['date'] = self.config.today
        else:
            self._docinfo['date'] = format_date(self.config.today_fmt or _('%b %d, %Y'),
                                                language=self.config.language)
        self._docinfo['copyright'] = self.config.copyright
        self._docinfo['version'] = self.config.version
        self._docinfo['manual_group'] = self.config.project

        # Overwrite admonition label translations with our own
        for label, translation in admonitionlabels.items():
            self.language.labels[label] = self.deunicode(translation)  # type: ignore
    def html_page_context(cls, app, pagename, templatename, context, doctree):
        """Update the Jinja2 HTML context, exposes the Versions class instance to it.

        :param sphinx.application.Sphinx app: Sphinx application object.
        :param str pagename: Name of the page being rendered (without .html or any file extension).
        :param str templatename: Page name with .html.
        :param dict context: Jinja2 HTML context.
        :param docutils.nodes.document doctree: Tree of docutils nodes.
        """
        assert templatename or doctree  # Unused, for linting.
        cls.VERSIONS.context = context
        versions = cls.VERSIONS
        this_remote = versions[cls.CURRENT_VERSION]
        banner_main_remote = versions[cls.BANNER_MAIN_VERSION] if cls.SHOW_BANNER else None

        # Update Jinja2 context.
        context['bitbucket_version'] = cls.CURRENT_VERSION
        context['current_version'] = cls.CURRENT_VERSION
        context['github_version'] = cls.CURRENT_VERSION
        context['html_theme'] = app.config.html_theme
        context['scv_banner_greatest_tag'] = cls.BANNER_GREATEST_TAG
        context['scv_banner_main_ref_is_branch'] = banner_main_remote['kind'] == 'heads' if cls.SHOW_BANNER else None
        context['scv_banner_main_ref_is_tag'] = banner_main_remote['kind'] == 'tags' if cls.SHOW_BANNER else None
        context['scv_banner_main_version'] = banner_main_remote['name'] if cls.SHOW_BANNER else None
        context['scv_banner_recent_tag'] = cls.BANNER_RECENT_TAG
        context['scv_is_branch'] = this_remote['kind'] == 'heads'
        context['scv_is_greatest_tag'] = this_remote == versions.greatest_tag_remote
        context['scv_is_recent_branch'] = this_remote == versions.recent_branch_remote
        context['scv_is_recent_ref'] = this_remote == versions.recent_remote
        context['scv_is_recent_tag'] = this_remote == versions.recent_tag_remote
        context['scv_is_root'] = cls.IS_ROOT
        context['scv_is_tag'] = this_remote['kind'] == 'tags'
        context['scv_show_banner'] = cls.SHOW_BANNER
        context['versions'] = versions
        context['vhasdoc'] = versions.vhasdoc
        context['vpathto'] = versions.vpathto

        # Insert banner into body.
        if cls.SHOW_BANNER and 'body' in context:
            parsed = app.builder.templates.render('banner.html', context)
            context['body'] = parsed + context['body']
            # Handle overridden css_files.
            css_files = context.setdefault('css_files', list())
            if '_static/banner.css' not in css_files:
                css_files.append('_static/banner.css')
            # Handle overridden html_static_path.
            if STATIC_DIR not in app.config.html_static_path:
                app.config.html_static_path.append(STATIC_DIR)

        # Reset last_updated with file's mtime (will be last git commit authored date).
        if app.config.html_last_updated_fmt is not None:
            file_path = app.env.doc2path(pagename)
            if os.path.isfile(file_path):
                lufmt = app.config.html_last_updated_fmt or getattr(locale, '_')('%b %d, %Y')
                mtime = datetime.datetime.fromtimestamp(os.path.getmtime(file_path))
                context['last_updated'] = format_date(lufmt, mtime, language=app.config.language, warn=app.warn)
    def html_page_context(cls, app, pagename, templatename, context, doctree):
        """Update the Jinja2 HTML context, exposes the Versions class instance to it.

        :param sphinx.application.Sphinx app: Sphinx application object.
        :param str pagename: Name of the page being rendered (without .html or any file extension).
        :param str templatename: Page name with .html.
        :param dict context: Jinja2 HTML context.
        :param docutils.nodes.document doctree: Tree of docutils nodes.
        """
        assert templatename or doctree  # Unused, for linting.
        cls.VERSIONS.context = context
        versions = cls.VERSIONS
        this_remote = versions[cls.CURRENT_VERSION]
        banner_main_remote = versions[cls.BANNER_MAIN_VERSION] if cls.SHOW_BANNER else None

        # Update Jinja2 context.
        context['bitbucket_version'] = cls.CURRENT_VERSION
        context['current_version'] = cls.CURRENT_VERSION
        context['github_version'] = cls.CURRENT_VERSION
        context['html_theme'] = app.config.html_theme
        context['scv_banner_greatest_tag'] = cls.BANNER_GREATEST_TAG
        context['scv_banner_main_ref_is_branch'] = banner_main_remote['kind'] == 'heads' if cls.SHOW_BANNER else None
        context['scv_banner_main_ref_is_tag'] = banner_main_remote['kind'] == 'tags' if cls.SHOW_BANNER else None
        context['scv_banner_main_version'] = banner_main_remote['name'] if cls.SHOW_BANNER else None
        context['scv_banner_recent_tag'] = cls.BANNER_RECENT_TAG
        context['scv_is_branch'] = this_remote['kind'] == 'heads'
        context['scv_is_greatest_tag'] = this_remote == versions.greatest_tag_remote
        context['scv_is_recent_branch'] = this_remote == versions.recent_branch_remote
        context['scv_is_recent_ref'] = this_remote == versions.recent_remote
        context['scv_is_recent_tag'] = this_remote == versions.recent_tag_remote
        context['scv_is_root'] = cls.IS_ROOT
        context['scv_is_tag'] = this_remote['kind'] == 'tags'
        context['scv_show_banner'] = cls.SHOW_BANNER
        context['versions'] = versions
        context['vhasdoc'] = versions.vhasdoc
        context['vpathto'] = versions.vpathto

        # Insert banner into body.
        if cls.SHOW_BANNER and 'body' in context:
            parsed = app.builder.templates.render('banner.html', context)
            context['body'] = parsed + context['body']
            # Handle overridden css_files.
            css_files = context.setdefault('css_files', list())
            if '_static/banner.css' not in css_files:
                css_files.append('_static/banner.css')
            # Handle overridden html_static_path.
            if STATIC_DIR not in app.config.html_static_path:
                app.config.html_static_path.append(STATIC_DIR)

        # Reset last_updated with file's mtime (will be last git commit authored date).
        if app.config.html_last_updated_fmt is not None:
            file_path = app.env.doc2path(pagename)
            if os.path.isfile(file_path):
                lufmt = app.config.html_last_updated_fmt or getattr(locale, '_')('%b %d, %Y')
                mtime = datetime.datetime.fromtimestamp(os.path.getmtime(file_path))
                context['last_updated'] = format_date(lufmt, mtime, language=app.config.language, warn=app.warn)
def _html_page_context(app, pagename, templatename, context, doctree):
    if 'sourcename' in context and 'page_source_suffix' in context:
        pass
    else:
        return
    pagename_as_repofile = ospj(wd['project_offset'],
                                wd['t3docdir'],
                                pagename + context['page_source_suffix'])
    v = wd['filedata'].get(pagename_as_repofile, (None, None))
    timestamp = v[0]
    commit_hash = v[1]
    if timestamp is None:
        log.info("[%s] %s :: not found" % (__name__, pagename_as_repofile))
        return
    else:
        log.info("[%s] %s :: found" % (__name__, pagename_as_repofile))
    last_modified_dt = datetime.datetime.fromtimestamp(timestamp, utc_tzinfo)
    last_modified = i18n.format_date(wd['html_last_updated_fmt'],
                                     date=last_modified_dt,
                                     language=app.config.language)
    # Try to assemble or guess a commit url
    commit_url_template = context.get('theme_project_commit_url')
    if not commit_url_template:
        # Maybe we can deduce the url needed
        repo_url = (context.get('theme_project_repository') or
                    context.get('theme_project_issues'))
        if repo_url:
            # Github
            if repo_url.startswith('https://github.com/'):
                if repo_url.endswith('/issues'):
                    repo_url = repo_url[:-7]
                elif repo_url.endswith('.git'):
                    repo_url = repo_url[:-4]
                commit_url_template = repo_url + '/commit/%(commit_hash)s'
            # git.typo3.org
            elif repo_url.startswith('https://git.typo3.org/'):
                if repo_url.endswith('/issues'):
                    repo_url = repo_url[:-7]
                commit_url_template = repo_url + '/commit/%(commit_hash)s'
            # bitbucket
            elif repo_url.startswith('https://bitbucket.org/'):
                if repo_url.endswith('/src/master/'):
                    repo_url = repo_url[:-12]
                commit_url_template = repo_url + '/commits/%(commit_hash)s'
            # gitlab
            elif "gitlab" in repo_url[:repo_url[8:].find('/')+8]:
                if repo_url.endswith('/-/issues'):
                    repo_url = repo_url[:-9]
                commit_url_template = repo_url + '/-/commit/%(commit_hash)s'

    t3ctx = context['t3ctx'] = context.get('t3ctx', {})
    t3ctx['commit_hash'] = commit_hash
    t3ctx['last_modified'] = last_modified
    t3ctx['last_modified_isoformat'] = last_modified_dt.isoformat()
    if commit_url_template:
        t3ctx['commit_url'] = commit_url_template % {'commit_hash': commit_hash}
Example #9
0
def test_format_date():
    date = datetime.date(2016, 2, 7)

    format = None
    assert i18n.format_date(format, date=date) == 'Feb 7, 2016'
    assert i18n.format_date(format, date=date, language='en') == 'Feb 7, 2016'
    assert i18n.format_date(format, date=date, language='ja') == '2016/02/07'
    assert i18n.format_date(format, date=date, language='de') == '07.02.2016'

    format = '%B %d, %Y'
    print(i18n.format_date(format, date=date))
    assert i18n.format_date(format, date=date) == 'February 07, 2016'
    assert i18n.format_date(format, date=date, language='en') == 'February 07, 2016'
    assert i18n.format_date(format, date=date, language='ja') == u'2月 07, 2016'
    assert i18n.format_date(format, date=date, language='de') == 'Februar 07, 2016'
Example #10
0
def correct_copyright_year(app: "Sphinx", config: Config) -> None:
    """correct values of copyright year that are not coherent with
    the SOURCE_DATE_EPOCH environment variable (if set)

    See https://reproducible-builds.org/specs/source-date-epoch/
    """
    if getenv('SOURCE_DATE_EPOCH') is not None:
        for k in ('copyright', 'epub_copyright'):
            if k in config:
                replace = r'\g<1>%s' % format_date('%Y')
                config[k] = copyright_year_re.sub(replace, config[k])
Example #11
0
def test_format_date():
    date = datetime.date(2016, 2, 7)

    format = None
    assert i18n.format_date(format, date=date) == 'Feb 7, 2016'
    assert i18n.format_date(format, date=date, language='en') == 'Feb 7, 2016'
    assert i18n.format_date(format, date=date, language='ja') == '2016/02/07'
    assert i18n.format_date(format, date=date, language='de') == '07.02.2016'

    format = '%B %d, %Y'
    print(i18n.format_date(format, date=date))
    assert i18n.format_date(format, date=date) == 'February 07, 2016'
    assert i18n.format_date(format, date=date,
                            language='en') == 'February 07, 2016'
    assert i18n.format_date(format, date=date, language='ja') == u'2月 07, 2016'
    assert i18n.format_date(format, date=date,
                            language='de') == 'Februar 07, 2016'
Example #12
0
def set_document_metadata(rinoh_document, config, doctree):
    metadata = rinoh_document.metadata
    rinoh_logo = config.rinoh_logo
    if rinoh_logo:
        metadata['logo'] = rinoh_logo
    metadata['title'] = doctree.settings.title
    metadata['subtitle'] = _('Release') + ' {}'.format(config.release)
    metadata['author'] = doctree.settings.author
    date = config.today or format_date(config.today_fmt or _('%b %d, %Y'),
                                       language=config.language)
    metadata['date'] = date
    metadata.update(config.rinoh_metadata)
Example #13
0
def correct_copyright_year(app, config):
    # type: (Sphinx, Config) -> None
    """correct values of copyright year that are not coherent with
    the SOURCE_DATE_EPOCH environment variable (if set)

    See https://reproducible-builds.org/specs/source-date-epoch/
    """
    if getenv('SOURCE_DATE_EPOCH') is not None:
        for k in ('copyright', 'epub_copyright'):
            if k in config:
                replace = r'\g<1>%s' % format_date('%Y')
                config[k] = copyright_year_re.sub(replace, config[k])
Example #14
0
 def apply(self, **kwargs: Any) -> None:
     # only handle those not otherwise defined in the document
     to_handle = default_substitutions - set(self.document.substitution_defs)
     for ref in self.document.traverse(nodes.substitution_reference):
         refname = ref['refname']
         if refname in to_handle:
             text = self.config[refname]
             if refname == 'today' and not text:
                 # special handling: can also specify a strftime format
                 text = format_date(self.config.today_fmt or _('%b %d, %Y'),
                                    language=self.config.language)
             ref.replace_self(nodes.Text(text, text))
Example #15
0
 def apply(self):
     config = self.document.settings.env.config
     # only handle those not otherwise defined in the document
     to_handle = default_substitutions - set(self.document.substitution_defs)
     for ref in self.document.traverse(nodes.substitution_reference):
         refname = ref['refname']
         if refname in to_handle:
             text = config[refname]
             if refname == 'today' and not text:
                 # special handling: can also specify a strftime format
                 text = format_date(config.today_fmt or _('MMMM dd, YYYY'),
                                    language=config.language)
             ref.replace_self(nodes.Text(text, text))
Example #16
0
 def apply(self, **kwargs):
     # type: (Any) -> None
     # only handle those not otherwise defined in the document
     to_handle = default_substitutions - set(self.document.substitution_defs)
     for ref in self.document.traverse(nodes.substitution_reference):
         refname = ref['refname']
         if refname in to_handle:
             text = self.config[refname]
             if refname == 'today' and not text:
                 # special handling: can also specify a strftime format
                 text = format_date(self.config.today_fmt or _('%b %d, %Y'),
                                    language=self.config.language)
             ref.replace_self(nodes.Text(text, text))
Example #17
0
 def init_settings(self):
     settings = self.settings = self.document.settings
     elements = self.elements = self.default_elements.copy()
     elements.update({
         # if empty, the title is set to the first section title
         'title':
         settings.title,
         'author':
         settings.author,
         # if empty, use basename of input file
         'filename':
         settings.texinfo_filename,
         'release':
         self.escape(self.builder.config.release),
         'project':
         self.escape(self.builder.config.project),
         'copyright':
         self.escape(self.builder.config.copyright),
         'date':
         self.escape(
             self.builder.config.today
             or format_date(self.builder.config.today_fmt or _('%b %d, %Y'),
                            language=self.builder.config.language))
     })
     # title
     title = elements['title']
     if not title:
         title = self.document.next_node(nodes.title)
         title = (title and title.astext()) or '<untitled>'
     elements['title'] = self.escape_id(title) or '<untitled>'
     # filename
     if not elements['filename']:
         elements['filename'] = self.document.get('source') or 'untitled'
         if elements['filename'][-4:] in ('.txt', '.rst'):
             elements['filename'] = elements['filename'][:-4]
         elements['filename'] += '.info'
     # direntry
     if settings.texinfo_dir_entry:
         entry = self.format_menu_entry(
             self.escape_menu(settings.texinfo_dir_entry),
             '(%s)' % elements['filename'],
             self.escape_arg(settings.texinfo_dir_description))
         elements['direntry'] = ('@dircategory %s\n'
                                 '@direntry\n'
                                 '%s'
                                 '@end direntry\n') % (self.escape_id(
                                     settings.texinfo_dir_category), entry)
     elements['copying'] = COPYING % elements
     # allow the user to override them all
     elements.update(settings.texinfo_elements)
Example #18
0
 def set_document_metadata(self, rinoh_document, doctree):
     metadata = rinoh_document.metadata
     if self.config.rinoh_logo:
         rinoh_logo = Path(self.config.rinoh_logo)
         if not rinoh_logo.is_absolute():
             rinoh_logo = self.confdir / rinoh_logo
         metadata['logo'] = rinoh_logo
     metadata['title'] = doctree.settings.title
     metadata['subtitle'] = _('Release') + ' {}'.format(self.config.release)
     metadata['author'] = doctree.settings.author
     date = (self.config.today
             or format_date(self.config.today_fmt or _('%b %d, %Y'),
                            language=self.config.language))
     metadata['date'] = date
     metadata.update(self.config.rinoh_metadata)
Example #19
0
    def content_metadata(self) -> Dict:
        """Create a dictionary with all metadata for the content.opf
        file properly escaped.
        """
        writing_mode = self.config.epub_writing_mode

        metadata = super().content_metadata()
        metadata['description'] = html.escape(self.config.epub_description)
        metadata['contributor'] = html.escape(self.config.epub_contributor)
        metadata['page_progression_direction'] = PAGE_PROGRESSION_DIRECTIONS.get(writing_mode)
        metadata['ibook_scroll_axis'] = IBOOK_SCROLL_AXIS.get(writing_mode)
        metadata['date'] = html.escape(format_date("%Y-%m-%dT%H:%M:%SZ"))
        metadata['version'] = html.escape(self.config.version)
        metadata['epub_version'] = self.config.epub_version
        return metadata
Example #20
0
File: epub3.py Project: LFYG/sphinx
    def content_metadata(self):
        # type: () -> Dict
        """Create a dictionary with all metadata for the content.opf
        file properly escaped.
        """
        writing_mode = self.config.epub_writing_mode

        metadata = super(Epub3Builder, self).content_metadata()
        metadata['description'] = self.esc(self.config.epub_description)
        metadata['contributor'] = self.esc(self.config.epub_contributor)
        metadata['page_progression_direction'] = PAGE_PROGRESSION_DIRECTIONS.get(writing_mode)
        metadata['ibook_scroll_axis'] = IBOOK_SCROLL_AXIS.get(writing_mode)
        metadata['date'] = self.esc(format_date("%Y-%m-%dT%H:%M:%SZ"))
        metadata['version'] = self.esc(self.config.version)
        return metadata
Example #21
0
 def content_metadata(self, files, spine, guide):
     """Create a dictionary with all metadata for the content.opf
     file properly escaped.
     """
     metadata = {}
     metadata['title'] = self.esc(self.config.epub_title)
     metadata['author'] = self.esc(self.config.epub_author)
     metadata['uid'] = self.esc(self.config.epub_uid)
     metadata['lang'] = self.esc(self.config.epub_language)
     metadata['publisher'] = self.esc(self.config.epub_publisher)
     metadata['copyright'] = self.esc(self.config.epub_copyright)
     metadata['scheme'] = self.esc(self.config.epub_scheme)
     metadata['id'] = self.esc(self.config.epub_identifier)
     metadata['date'] = self.esc(format_date('YYYY-MM-dd', language=self.config.language))
     metadata['files'] = files
     metadata['spine'] = spine
     metadata['guide'] = guide
     return metadata
Example #22
0
 def content_metadata(self) -> Dict[str, Any]:
     """Create a dictionary with all metadata for the content.opf
     file properly escaped.
     """
     metadata = {}  # type: Dict[str, Any]
     metadata['title'] = html.escape(self.config.epub_title)
     metadata['author'] = html.escape(self.config.epub_author)
     metadata['uid'] = html.escape(self.config.epub_uid)
     metadata['lang'] = html.escape(self.config.epub_language)
     metadata['publisher'] = html.escape(self.config.epub_publisher)
     metadata['copyright'] = html.escape(self.config.epub_copyright)
     metadata['scheme'] = html.escape(self.config.epub_scheme)
     metadata['id'] = html.escape(self.config.epub_identifier)
     metadata['date'] = html.escape(format_date("%Y-%m-%d"))
     metadata['manifest_items'] = []
     metadata['spines'] = []
     metadata['guides'] = []
     return metadata
Example #23
0
 def init_settings(self):
     settings = self.settings = self.document.settings
     elements = self.elements = self.default_elements.copy()
     elements.update({
         # if empty, the title is set to the first section title
         'title': settings.title,
         'author': settings.author,
         # if empty, use basename of input file
         'filename': settings.texinfo_filename,
         'release': self.escape(self.builder.config.release),
         'project': self.escape(self.builder.config.project),
         'copyright': self.escape(self.builder.config.copyright),
         'date': self.escape(self.builder.config.today or
                             format_date(self.builder.config.today_fmt or
                                         _('MMMM dd, YYYY'),
                                         language=self.builder.config.language))
     })
     # title
     title = elements['title']
     if not title:
         title = self.document.next_node(nodes.title)
         title = (title and title.astext()) or '<untitled>'
     elements['title'] = self.escape_id(title) or '<untitled>'
     # filename
     if not elements['filename']:
         elements['filename'] = self.document.get('source') or 'untitled'
         if elements['filename'][-4:] in ('.txt', '.rst'):
             elements['filename'] = elements['filename'][:-4]
         elements['filename'] += '.info'
     # direntry
     if settings.texinfo_dir_entry:
         entry = self.format_menu_entry(
             self.escape_menu(settings.texinfo_dir_entry),
             '(%s)' % elements['filename'],
             self.escape_arg(settings.texinfo_dir_description))
         elements['direntry'] = ('@dircategory %s\n'
                                 '@direntry\n'
                                 '%s'
                                 '@end direntry\n') % (
             self.escape_id(settings.texinfo_dir_category), entry)
     elements['copying'] = COPYING % elements
     # allow the user to override them all
     elements.update(settings.texinfo_elements)
Example #24
0
 def content_metadata(self, files, spine, guide):
     """Create a dictionary with all metadata for the content.opf
     file properly escaped.
     """
     metadata = {}
     metadata['title'] = self.esc(self.config.epub_title)
     metadata['author'] = self.esc(self.config.epub_author)
     metadata['uid'] = self.esc(self.config.epub_uid)
     metadata['lang'] = self.esc(self.config.epub_language)
     metadata['publisher'] = self.esc(self.config.epub_publisher)
     metadata['copyright'] = self.esc(self.config.epub_copyright)
     metadata['scheme'] = self.esc(self.config.epub_scheme)
     metadata['id'] = self.esc(self.config.epub_identifier)
     metadata['date'] = self.esc(format_date('%Y-%m-%d', language=self.config.language,
                                             warn=self.warn))
     metadata['files'] = files
     metadata['spine'] = spine
     metadata['guide'] = guide
     return metadata
Example #25
0
 def content_metadata(self):
     # type: () -> Dict[unicode, Any]
     """Create a dictionary with all metadata for the content.opf
     file properly escaped.
     """
     metadata = {}  # type: Dict[unicode, Any]
     metadata['title'] = self.esc(self.config.epub_title)
     metadata['author'] = self.esc(self.config.epub_author)
     metadata['uid'] = self.esc(self.config.epub_uid)
     metadata['lang'] = self.esc(self.config.epub_language)
     metadata['publisher'] = self.esc(self.config.epub_publisher)
     metadata['copyright'] = self.esc(self.config.epub_copyright)
     metadata['scheme'] = self.esc(self.config.epub_scheme)
     metadata['id'] = self.esc(self.config.epub_identifier)
     metadata['date'] = self.esc(format_date("%Y-%m-%d"))
     metadata['manifest_items'] = []
     metadata['spines'] = []
     metadata['guides'] = []
     return metadata
Example #26
0
    def __init__(self, *args):
        # type: (Any) -> None
        if isinstance(args[0], nodes.document) and isinstance(
                args[1], Builder):
            document, builder = args
        else:
            warnings.warn(
                'The order of arguments for ManualPageTranslator has been changed. '
                'Please give "document" as 1st and "builder" as 2nd.',
                RemovedInSphinx40Warning,
                stacklevel=2)
            builder, document = args
        super().__init__(document, builder)

        self.in_productionlist = 0

        # first title is the manpage title
        self.section_level = -1

        # docinfo set by man_pages config value
        self._docinfo['title'] = self.settings.title
        self._docinfo['subtitle'] = self.settings.subtitle
        if self.settings.authors:
            # don't set it if no author given
            self._docinfo['author'] = self.settings.authors
        self._docinfo['manual_section'] = self.settings.section

        # docinfo set by other config values
        self._docinfo['title_upper'] = self._docinfo['title'].upper()
        if self.config.today:
            self._docinfo['date'] = self.config.today
        else:
            self._docinfo['date'] = format_date(self.config.today_fmt
                                                or _('%b %d, %Y'),
                                                language=self.config.language)
        self._docinfo['copyright'] = self.config.copyright
        self._docinfo['version'] = self.config.version
        self._docinfo['manual_group'] = self.config.project

        # Overwrite admonition label translations with our own
        for label, translation in admonitionlabels.items():
            self.language.labels[label] = self.deunicode(
                translation)  # type: ignore
Example #27
0
    def __init__(self, dirname, filename, overrides, tags):
        # type: (unicode, unicode, Dict, Tags) -> None
        self.overrides = overrides
        self.values = Config.config_values.copy()
        config = {}  # type: Dict[unicode, Any]
        if dirname is not None:
            config_file = path.join(dirname, filename)
            config['__file__'] = config_file
            config['tags'] = tags
            with cd(dirname):
                # we promise to have the config dir as current dir while the
                # config file is executed
                try:
                    execfile_(filename, config)
                except SyntaxError as err:
                    raise ConfigError(CONFIG_SYNTAX_ERROR % err)
                except SystemExit:
                    raise ConfigError(CONFIG_EXIT_ERROR)
                except Exception:
                    raise ConfigError(CONFIG_ERROR % traceback.format_exc())

        self._raw_config = config
        # these two must be preinitialized because extensions can add their
        # own config values
        self.setup = config.get('setup', None)  # type: Callable

        if 'extensions' in overrides:
            if isinstance(overrides['extensions'], string_types):
                config['extensions'] = overrides.pop('extensions').split(',')
            else:
                config['extensions'] = overrides.pop('extensions')
        self.extensions = config.get('extensions', [])  # type: List[unicode]

        # correct values of copyright year that are not coherent with
        # the SOURCE_DATE_EPOCH environment variable (if set)
        # See https://reproducible-builds.org/specs/source-date-epoch/
        if getenv('SOURCE_DATE_EPOCH') is not None:
            for k in ('copyright', 'epub_copyright'):
                if k in config:
                    config[k] = copyright_year_re.sub(r'\g<1>%s' % format_date('%Y'),
                                                      config[k])
Example #28
0
    def __init__(self, dirname, filename, overrides, tags):
        # type: (unicode, unicode, Dict, Tags) -> None
        self.overrides = overrides
        self.values = Config.config_values.copy()
        config = {}  # type: Dict[unicode, Any]
        if dirname is not None:
            config_file = path.join(dirname, filename)
            config['__file__'] = config_file
            config['tags'] = tags
            with cd(dirname):
                # we promise to have the config dir as current dir while the
                # config file is executed
                try:
                    execfile_(filename, config)
                except SyntaxError as err:
                    raise ConfigError(CONFIG_SYNTAX_ERROR % err)
                except SystemExit:
                    raise ConfigError(CONFIG_EXIT_ERROR)
                except Exception:
                    raise ConfigError(CONFIG_ERROR % traceback.format_exc())

        self._raw_config = config
        # these two must be preinitialized because extensions can add their
        # own config values
        self.setup = config.get('setup', None)  # type: Callable

        if 'extensions' in overrides:
            if isinstance(overrides['extensions'], string_types):
                config['extensions'] = overrides.pop('extensions').split(',')
            else:
                config['extensions'] = overrides.pop('extensions')
        self.extensions = config.get('extensions', [])  # type: List[unicode]

        # correct values of copyright year that are not coherent with
        # the SOURCE_DATE_EPOCH environment variable (if set)
        # See https://reproducible-builds.org/specs/source-date-epoch/
        if getenv('SOURCE_DATE_EPOCH') is not None:
            for k in ('copyright', 'epub_copyright'):
                if k in config:
                    config[k] = copyright_year_re.sub(r'\g<1>%s' % format_date('%Y'),
                                                      config[k])
Example #29
0
def test_sphinx_rinoh_documents_defaults(tmp_path):
    rinoh_documents = [dict(doc='index', target='target')]
    today_fmt = '%b %d, %Y'
    app = create_sphinx_app(tmp_path,
                            rinoh_documents=rinoh_documents,
                            project='Project',
                            release='1.2',
                            author='Georgie',
                            today_fmt=today_fmt,
                            language='en-US')

    template_cfg = app.builder.template_configuration('book', LOGGER)
    document_data, = app.builder.document_data(LOGGER)
    rinoh_tree = DocumentTree([])
    rinoh_doc = template_cfg.document(rinoh_tree)
    app.builder.set_document_metadata(rinoh_doc, document_data)
    assert rinoh_doc.metadata['title'] == 'Project documentation'
    assert rinoh_doc.metadata['subtitle'] == 'Release 1.2'
    assert rinoh_doc.metadata['author'] == 'Georgie'
    assert rinoh_doc.metadata['date'] == format_date(today_fmt,
                                                     language='en-US')
Example #30
0
    def init_context(self):
        # type: () -> None
        self.context = DEFAULT_SETTINGS.copy()

        # Add special settings for latex_engine
        self.context.update(
            ADDITIONAL_SETTINGS.get(self.config.latex_engine, {}))

        # for xelatex+French, don't use polyglossia by default
        if self.config.latex_engine == 'xelatex':
            if self.config.language:
                if self.config.language[:2] == 'fr':
                    self.context['polyglossia'] = ''
                    self.context['babel'] = r'\usepackage{babel}'

        # Apply extension settings to context
        self.context['packages'] = self.usepackages

        # Apply user settings to context
        self.context.update(self.config.latex_elements)
        self.context['release'] = self.config.release
        self.context['use_xindy'] = self.config.latex_use_xindy

        if self.config.today:
            self.context['date'] = self.config.today
        else:
            self.context['date'] = format_date(self.config.today_fmt
                                               or _('%b %d, %Y'),
                                               language=self.config.language)

        if self.config.latex_logo:
            self.context['logofilename'] = path.basename(
                self.config.latex_logo)

        # for compatibilities
        self.context['indexname'] = _('Index')
        if self.config.release:
            # Show the release label only if release value exists
            self.context['releasename'] = _('Release')
Example #31
0
def config_inited(app, config):
    """Update the Sphinx builder.
    :param sphinx.application.Sphinx app: Sphinx application object.
    """

    if not config.smv_metadata:
        if not config.smv_metadata_path:
            return

        with open(config.smv_metadata_path, mode="r") as f:
            metadata = json.load(f)

        config.smv_metadata = metadata

    if not config.smv_current_version:
        return

    try:
        data = app.config.smv_metadata[config.smv_current_version]
    except KeyError:
        return

    app.connect("html-page-context", html_page_context)

    # Restore config values
    old_config = sphinx_config.Config.read(data["confdir"])
    old_config.pre_init_values()
    old_config.init_values()
    config.version = data["version"]
    config.release = data["release"]
    config.rst_prolog = data["rst_prolog"]
    config.today = old_config.today
    if not config.today:
        config.today = sphinx_i18n.format_date(
            format=config.today_fmt or _("%b %d, %Y"),
            date=datetime.datetime.strptime(data["creatordate"], DATE_FMT),
            language=config.language,
        )
Example #32
0
 def write_doc(self, docname, doctree, docnames, targetname):
     config = self.config
     rinoh_tree = from_doctree(doctree['source'],
                               doctree,
                               sphinx_builder=self)
     template_cfg = template_from_config(config, self.confdir,
                                         logger.warning)
     rinoh_document = template_cfg.document(rinoh_tree)
     extra_indices = StaticGroupedFlowables(self.generate_indices(docnames))
     rinoh_document.insert('back_matter', extra_indices, 0)
     rinoh_logo = config.rinoh_logo
     if rinoh_logo:
         rinoh_document.metadata['logo'] = rinoh_logo
     rinoh_document.metadata['title'] = doctree.settings.title
     rinoh_document.metadata['subtitle'] = ('Release {}'.format(
         config.release))
     rinoh_document.metadata['author'] = doctree.settings.author
     date = config.today or format_date(config.today_fmt or _('%b %d, %Y'),
                                        language=config.language)
     rinoh_document.metadata['date'] = date
     outfilename = path.join(self.outdir, os_path(targetname))
     ensuredir(path.dirname(outfilename))
     rinoh_document.render(outfilename)
Example #33
0
    def init_context(self):
        # type: () -> None
        self.context = DEFAULT_SETTINGS.copy()

        # Add special settings for latex_engine
        self.context.update(ADDITIONAL_SETTINGS.get(self.config.latex_engine, {}))

        # for xelatex+French, don't use polyglossia by default
        if self.config.latex_engine == 'xelatex':
            if self.config.language:
                if self.config.language[:2] == 'fr':
                    self.context['polyglossia'] = ''
                    self.context['babel'] = r'\usepackage{babel}'

        # Apply extension settings to context
        self.context['packages'] = self.usepackages

        # Apply user settings to context
        self.context.update(self.config.latex_elements)
        self.context['release'] = self.config.release
        self.context['use_xindy'] = self.config.latex_use_xindy

        if self.config.today:
            self.context['date'] = self.config.today
        else:
            self.context['date'] = format_date(self.config.today_fmt or _('%b %d, %Y'),
                                               language=self.config.language)

        if self.config.latex_logo:
            self.context['logofilename'] = path.basename(self.config.latex_logo)

        # for compatibilities
        self.context['indexname'] = _('Index')
        if self.config.release:
            # Show the release label only if release value exists
            self.context['releasename'] = _('Release')
Example #34
0
    def __init__(self, dirname, filename, overrides, tags):
        self.overrides = overrides
        self.values = Config.config_values.copy()
        config = {}
        if "extensions" in overrides:  # XXX do we need this?
            if isinstance(overrides["extensions"], string_types):
                config["extensions"] = overrides.pop("extensions").split(",")
            else:
                config["extensions"] = overrides.pop("extensions")
        if dirname is not None:
            config_file = path.join(dirname, filename)
            config["__file__"] = config_file
            config["tags"] = tags
            with cd(dirname):
                # we promise to have the config dir as current dir while the
                # config file is executed
                try:
                    execfile_(filename, config)
                except SyntaxError as err:
                    raise ConfigError(CONFIG_SYNTAX_ERROR % err)
                except SystemExit:
                    raise ConfigError(CONFIG_EXIT_ERROR)

        self._raw_config = config
        # these two must be preinitialized because extensions can add their
        # own config values
        self.setup = config.get("setup", None)
        self.extensions = config.get("extensions", [])

        # correct values of copyright year that are not coherent with
        # the SOURCE_DATE_EPOCH environment variable (if set)
        # See https://reproducible-builds.org/specs/source-date-epoch/
        if getenv("SOURCE_DATE_EPOCH") is not None:
            for k in ("copyright", "epub_copyright"):
                if k in config:
                    config[k] = copyright_year_re.sub("\g<1>%s" % format_date("%Y"), config[k])
Example #35
0
def test_format_date():
    date = datetime.date(2016, 2, 7)

    # default format
    format = None
    assert i18n.format_date(format, date=date) == 'Feb 7, 2016'
    assert i18n.format_date(format, date=date, language='') == 'Feb 7, 2016'
    assert i18n.format_date(format, date=date, language='unknown') == 'Feb 7, 2016'
    assert i18n.format_date(format, date=date, language='en') == 'Feb 7, 2016'
    assert i18n.format_date(format, date=date, language='ja') == '2016/02/07'
    assert i18n.format_date(format, date=date, language='de') == '07.02.2016'

    # strftime format
    format = '%B %d, %Y'
    assert i18n.format_date(format, date=date) == 'February 07, 2016'
    assert i18n.format_date(format, date=date, language='') == 'February 07, 2016'
    assert i18n.format_date(format, date=date, language='unknown') == 'February 07, 2016'
    assert i18n.format_date(format, date=date, language='en') == 'February 07, 2016'
    assert i18n.format_date(format, date=date, language='ja') == u'2月 07, 2016'
    assert i18n.format_date(format, date=date, language='de') == 'Februar 07, 2016'

    # LDML format
    format = 'MMM dd, YYYY'
    assert i18n.format_date(format, date=date) == 'Feb 07, 2016'
    assert i18n.format_date(format, date=date, language='') == 'Feb 07, 2016'
    assert i18n.format_date(format, date=date, language='unknown') == 'Feb 07, 2016'
    assert i18n.format_date(format, date=date, language='en') == 'Feb 07, 2016'
    assert i18n.format_date(format, date=date, language='ja') == u'2月 07, 2016'
    assert i18n.format_date(format, date=date, language='de') == 'Feb. 07, 2016'

    # raw string
    format = 'Mon Mar 28 12:37:08 2016, commit 4367aef'
    assert i18n.format_date(format, date=date) == format

    format = '%B %d, %Y, %H:%M:%S %I %p'
    datet = datetime.datetime(2016, 2, 7, 5, 11, 17, 0)
    assert i18n.format_date(format, date=datet) == 'February 07, 2016, 05:11:17 05 AM'

    format = '%x'
    assert i18n.format_date(format, date=datet) == 'Feb 7, 2016'
    format = '%X'
    assert i18n.format_date(format, date=datet) == '5:11:17 AM'
    assert i18n.format_date(format, date=date) == 'Feb 7, 2016'
    format = '%c'
    assert i18n.format_date(format, date=datet) == 'Feb 7, 2016, 5:11:17 AM'
    assert i18n.format_date(format, date=date) == 'Feb 7, 2016'
Example #36
0
    def prepare_writing(self, docnames):
        # create the search indexer
        self.indexer = None

        self.docwriter = MarkdownWriter(self)
        self.docsettings = OptionParser(
            defaults=self.env.settings, components=(self.docwriter,), read_config_files=True
        ).get_default_values()
        self.docsettings.compact_lists = bool(self.config.html_compact_lists)

        # determine the additional indices to include
        self.domain_indices = []
        # html_domain_indices can be False/True or a list of index names
        indices_config = self.config.html_domain_indices
        if indices_config:
            for domain_name in sorted(self.env.domains):
                domain = self.env.domains[domain_name]
                for indexcls in domain.indices:
                    indexname = "%s-%s" % (domain.name, indexcls.name)
                    if isinstance(indices_config, list):
                        if indexname not in indices_config:
                            continue
                    # deprecated config value
                    if indexname == "py-modindex" and not self.config.html_use_modindex:
                        continue
                    content, collapse = indexcls(domain).generate()
                    if content:
                        self.domain_indices.append((indexname, indexcls, content, collapse))

        # format the "last updated on" string, only once is enough since it
        # typically doesn't include the time of day
        lufmt = self.config.html_last_updated_fmt
        if lufmt is not None:
            self.last_updated = format_date(lufmt or _("%b %d, %Y"), language=self.config.language, warn=self.warn)
        else:
            self.last_updated = None

        self.relations = self.env.collect_relations()

        rellinks = []
        if self.get_builder_config("use_index", "html"):
            rellinks.append(("genindex", _("General Index"), "I", _("index")))
        for indexname, indexcls, content, collapse in self.domain_indices:
            # if it has a short name
            if indexcls.shortname:
                rellinks.append((indexname, indexcls.localname, "", indexcls.shortname))

        self.globalcontext = dict(
            embedded=self.embedded,
            project=self.config.project,
            release=self.config.release,
            version=self.config.version,
            last_updated=self.last_updated,
            copyright=self.config.copyright,
            master_doc=self.config.master_doc,
            docstitle=self.config.html_title,
            shorttitle=self.config.html_short_title,
            show_copyright=self.config.html_show_copyright,
            show_sphinx=self.config.html_show_sphinx,
            has_source=self.config.html_copy_source,
            show_source=self.config.html_show_sourcelink,
            file_suffix=self.out_suffix,
            language=self.config.language,
            sphinx_version=__display_version__,
            rellinks=rellinks,
            builder=self.name,
            parents=[],
        )
Example #37
0
        rinoh_document.metadata.update(metadata)
        if 'logo' in rinoh_document.metadata:
            logo_path = Path(rinoh_document.metadata['logo'])
            if not logo_path.is_absolute():
                rinoh_document.metadata['logo'] = self.confdir / logo_path
        for key, default in METADATA_DEFAULTS.items():
            if key in rinoh_document.metadata:
                continue
            rinoh_document.metadata[key] = default(self.config)


METADATA_DEFAULTS = dict(
    title=lambda cfg: '{} documentation'.format(cfg.project),
    subtitle=lambda cfg: '{} {}'.format(_('Release'), cfg.release),
    author=lambda cfg: cfg.author,
    date=lambda cfg: (cfg.today or format_date(cfg.today_fmt or _('%b %d, %Y'),
                                               language=cfg.language)))


def fully_qualified_id(docname, id):
    return id if id.startswith('%') else '%' + docname + '#' + id


def rinoh_document_to_document_data(entry, logger):
    if type(entry) in (list, tuple):
        entry = list_to_document_data(entry, logger)
    for key in ('doc', 'target'):
        if key not in entry:
            raise SphinxError("'{}' key is missing from rinoh_documents"
                              " entry".format(key))
    return entry
Example #38
0
    def prepare_writing(self, docnames: Set[str]) -> None:
        # create the search indexer
        self.indexer = None
        if self.search:
            from sphinx.search import IndexBuilder
            lang = self.config.html_search_language or self.config.language
            if not lang:
                lang = 'en'
            self.indexer = IndexBuilder(self.env, lang,
                                        self.config.html_search_options,
                                        self.config.html_search_scorer)
            self.load_indexer(docnames)

        self.docwriter = HTMLWriter(self)
        self.docsettings = OptionParser(
            defaults=self.env.settings,
            components=(self.docwriter,),
            read_config_files=True).get_default_values()  # type: Any
        self.docsettings.compact_lists = bool(self.config.html_compact_lists)

        # determine the additional indices to include
        self.domain_indices = []
        # html_domain_indices can be False/True or a list of index names
        indices_config = self.config.html_domain_indices
        if indices_config:
            for domain_name in sorted(self.env.domains):
                domain = None  # type: Domain
                domain = self.env.domains[domain_name]
                for indexcls in domain.indices:
                    indexname = '%s-%s' % (domain.name, indexcls.name)
                    if isinstance(indices_config, list):
                        if indexname not in indices_config:
                            continue
                    content, collapse = indexcls(domain).generate()
                    if content:
                        self.domain_indices.append(
                            (indexname, indexcls, content, collapse))

        # format the "last updated on" string, only once is enough since it
        # typically doesn't include the time of day
        lufmt = self.config.html_last_updated_fmt
        if lufmt is not None:
            self.last_updated = format_date(lufmt or _('%b %d, %Y'),
                                            language=self.config.language)
        else:
            self.last_updated = None

        logo = self.config.html_logo and \
            path.basename(self.config.html_logo) or ''

        favicon = self.config.html_favicon and \
            path.basename(self.config.html_favicon) or ''

        if not isinstance(self.config.html_use_opensearch, str):
            logger.warning(__('html_use_opensearch config value must now be a string'))

        self.relations = self.env.collect_relations()

        rellinks = []  # type: List[Tuple[str, str, str, str]]
        if self.use_index:
            rellinks.append(('genindex', _('General Index'), 'I', _('index')))
        for indexname, indexcls, content, collapse in self.domain_indices:
            # if it has a short name
            if indexcls.shortname:
                rellinks.append((indexname, indexcls.localname,
                                 '', indexcls.shortname))

        if self.config.html_style is not None:
            stylename = self.config.html_style
        elif self.theme:
            stylename = self.theme.get_config('theme', 'stylesheet')
        else:
            stylename = 'default.css'

        self.globalcontext = {
            'embedded': self.embedded,
            'project': self.config.project,
            'release': return_codes_re.sub('', self.config.release),
            'version': self.config.version,
            'last_updated': self.last_updated,
            'copyright': self.config.copyright,
            'master_doc': self.config.master_doc,
            'use_opensearch': self.config.html_use_opensearch,
            'docstitle': self.config.html_title,
            'shorttitle': self.config.html_short_title,
            'show_copyright': self.config.html_show_copyright,
            'show_sphinx': self.config.html_show_sphinx,
            'has_source': self.config.html_copy_source,
            'show_source': self.config.html_show_sourcelink,
            'sourcelink_suffix': self.config.html_sourcelink_suffix,
            'file_suffix': self.out_suffix,
            'script_files': self.script_files,
            'language': self.config.language,
            'css_files': self.css_files,
            'sphinx_version': __display_version__,
            'style': stylename,
            'rellinks': rellinks,
            'builder': self.name,
            'parents': [],
            'logo': logo,
            'favicon': favicon,
            'html5_doctype': html5_ready and not self.config.html4_writer
        }
        if self.theme:
            self.globalcontext.update(
                ('theme_' + key, val) for (key, val) in
                self.theme.get_options(self.theme_options).items())
        self.globalcontext.update(self.config.html_context)
Example #39
0
def test_format_date():
    date = datetime.date(2016, 2, 7)

    # strftime format
    format = '%B %d, %Y'
    assert i18n.format_date(format, date=date) == 'February 07, 2016'
    assert i18n.format_date(format, date=date,
                            language='') == 'February 07, 2016'
    assert i18n.format_date(format, date=date,
                            language='unknown') == 'February 07, 2016'
    assert i18n.format_date(format, date=date,
                            language='en') == 'February 07, 2016'
    assert i18n.format_date(format, date=date, language='ja') == u'2月 07, 2016'
    assert i18n.format_date(format, date=date,
                            language='de') == 'Februar 07, 2016'

    # raw string
    format = 'Mon Mar 28 12:37:08 2016, commit 4367aef'
    assert i18n.format_date(format, date=date) == format

    format = '%B %d, %Y, %H:%M:%S %I %p'
    datet = datetime.datetime(2016, 2, 7, 5, 11, 17, 0)
    assert i18n.format_date(format,
                            date=datet) == 'February 07, 2016, 05:11:17 05 AM'

    format = '%x'
    assert i18n.format_date(format, date=datet) == 'Feb 7, 2016'
    format = '%X'
    assert i18n.format_date(format, date=datet) == '5:11:17 AM'
    assert i18n.format_date(format, date=date) == 'Feb 7, 2016'
    format = '%c'
    assert i18n.format_date(format, date=datet) == 'Feb 7, 2016, 5:11:17 AM'
    assert i18n.format_date(format, date=date) == 'Feb 7, 2016'
Example #40
0
    def prepare_writing(self, docnames):
        # create the search indexer
        self.indexer = None

        self.docwriter = MarkdownWriter(self)
        self.docsettings = OptionParser(
            defaults=self.env.settings,
            components=(self.docwriter,),
            read_config_files=True).get_default_values()
        self.docsettings.compact_lists = bool(self.config.html_compact_lists)

        # determine the additional indices to include
        self.domain_indices = []
        # html_domain_indices can be False/True or a list of index names
        indices_config = self.config.html_domain_indices
        if indices_config:
            for domain_name in sorted(self.env.domains):
                domain = self.env.domains[domain_name]
                for indexcls in domain.indices:
                    indexname = '%s-%s' % (domain.name, indexcls.name)
                    if isinstance(indices_config, list):
                        if indexname not in indices_config:
                            continue
                    # deprecated config value
                    if indexname == 'py-modindex' and \
                       not self.config.html_use_modindex:
                        continue
                    content, collapse = indexcls(domain).generate()
                    if content:
                        self.domain_indices.append(
                            (indexname, indexcls, content, collapse))

        # format the "last updated on" string, only once is enough since it
        # typically doesn't include the time of day
        lufmt = self.config.html_last_updated_fmt
        if lufmt is not None:
            self.last_updated = format_date(lufmt or _('%b %d, %Y'),
                                            language=self.config.language,
                                            warn=self.warn)
        else:
            self.last_updated = None

        self.relations = self.env.collect_relations()

        rellinks = []
        if self.get_builder_config('use_index', 'html'):
            rellinks.append(('genindex', _('General Index'), 'I', _('index')))
        for indexname, indexcls, content, collapse in self.domain_indices:
            # if it has a short name
            if indexcls.shortname:
                rellinks.append((indexname, indexcls.localname,
                                 '', indexcls.shortname))

        self.globalcontext = dict(
            embedded=self.embedded,
            project=self.config.project,
            release=self.config.release,
            version=self.config.version,
            last_updated=self.last_updated,
            copyright=self.config.copyright,
            master_doc=self.config.master_doc,
            docstitle=self.config.html_title,
            shorttitle=self.config.html_short_title,
            show_copyright=self.config.html_show_copyright,
            show_sphinx=self.config.html_show_sphinx,
            has_source=self.config.html_copy_source,
            show_source=self.config.html_show_sourcelink,
            file_suffix=self.out_suffix,
            language=self.config.language,
            sphinx_version=__display_version__,
            rellinks=rellinks,
            builder=self.name,
            parents=[],
        )
Example #41
0
    def prepare_writing(self, docnames):
        # create the search indexer
        self.indexer = None
        if self.search:
            from sphinx.search import IndexBuilder, languages
            lang = self.config.html_search_language or self.config.language
            if not lang or lang not in languages:
                lang = 'en'
            self.indexer = IndexBuilder(self.env, lang,
                                        self.config.html_search_options,
                                        self.config.html_search_scorer)
            self.load_indexer(docnames)

        self.docwriter = HTMLWriter(self)
        self.docsettings = OptionParser(
            defaults=self.env.settings,
            components=(self.docwriter,),
            read_config_files=True).get_default_values()
        self.docsettings.compact_lists = bool(self.config.html_compact_lists)

        # determine the additional indices to include
        self.domain_indices = []
        # html_domain_indices can be False/True or a list of index names
        indices_config = self.config.html_domain_indices
        if indices_config:
            for domain_name in sorted(self.env.domains):
                domain = self.env.domains[domain_name]
                for indexcls in domain.indices:
                    indexname = '%s-%s' % (domain.name, indexcls.name)
                    if isinstance(indices_config, list):
                        if indexname not in indices_config:
                            continue
                    # deprecated config value
                    if indexname == 'py-modindex' and \
                       not self.config.html_use_modindex:
                        continue
                    content, collapse = indexcls(domain).generate()
                    if content:
                        self.domain_indices.append(
                            (indexname, indexcls, content, collapse))

        # format the "last updated on" string, only once is enough since it
        # typically doesn't include the time of day
        lufmt = self.config.html_last_updated_fmt
        if lufmt is not None:
            self.last_updated = format_date(lufmt or _('MMM dd, YYYY'),
                                            language=self.config.language)
        else:
            self.last_updated = None

        logo = self.config.html_logo and \
            path.basename(self.config.html_logo) or ''

        favicon = self.config.html_favicon and \
            path.basename(self.config.html_favicon) or ''
        if favicon and os.path.splitext(favicon)[1] != '.ico':
            self.warn('html_favicon is not an .ico file')

        if not isinstance(self.config.html_use_opensearch, string_types):
            self.warn('html_use_opensearch config value must now be a string')

        self.relations = self.env.collect_relations()

        rellinks = []
        if self.get_builder_config('use_index', 'html'):
            rellinks.append(('genindex', _('General Index'), 'I', _('index')))
        for indexname, indexcls, content, collapse in self.domain_indices:
            # if it has a short name
            if indexcls.shortname:
                rellinks.append((indexname, indexcls.localname,
                                 '', indexcls.shortname))

        if self.config.html_style is not None:
            stylename = self.config.html_style
        elif self.theme:
            stylename = self.theme.get_confstr('theme', 'stylesheet')
        else:
            stylename = 'default.css'

        self.globalcontext = dict(
            embedded = self.embedded,
            project = self.config.project,
            release = self.config.release,
            version = self.config.version,
            last_updated = self.last_updated,
            copyright = self.config.copyright,
            master_doc = self.config.master_doc,
            use_opensearch = self.config.html_use_opensearch,
            docstitle = self.config.html_title,
            shorttitle = self.config.html_short_title,
            show_copyright = self.config.html_show_copyright,
            show_sphinx = self.config.html_show_sphinx,
            has_source = self.config.html_copy_source,
            show_source = self.config.html_show_sourcelink,
            file_suffix = self.out_suffix,
            script_files = self.script_files,
            language = self.config.language,
            css_files = self.css_files,
            sphinx_version = __display_version__,
            style = stylename,
            rellinks = rellinks,
            builder = self.name,
            parents = [],
            logo = logo,
            favicon = favicon,
        )
        if self.theme:
            self.globalcontext.update(
                ('theme_' + key, val) for (key, val) in
                iteritems(self.theme.get_options(self.theme_options)))
        self.globalcontext.update(self.config.html_context)
Example #42
0
def test_format_date():
    date = datetime.date(2016, 2, 7)

    # strftime format
    format = '%B %d, %Y'
    assert i18n.format_date(format, date=date) == 'February 07, 2016'
    assert i18n.format_date(format, date=date, language='') == 'February 07, 2016'
    assert i18n.format_date(format, date=date, language='unknown') == 'February 07, 2016'
    assert i18n.format_date(format, date=date, language='en') == 'February 07, 2016'
    assert i18n.format_date(format, date=date, language='ja') == u'2月 07, 2016'
    assert i18n.format_date(format, date=date, language='de') == 'Februar 07, 2016'

    # raw string
    format = 'Mon Mar 28 12:37:08 2016, commit 4367aef'
    assert i18n.format_date(format, date=date) == format

    format = '%B %d, %Y, %H:%M:%S %I %p'
    datet = datetime.datetime(2016, 2, 7, 5, 11, 17, 0)
    assert i18n.format_date(format, date=datet) == 'February 07, 2016, 05:11:17 05 AM'

    format = '%B %-d, %Y, %-H:%-M:%-S %-I %p'
    assert i18n.format_date(format, date=datet) == 'February 7, 2016, 5:11:17 5 AM'
    format = '%x'
    assert i18n.format_date(format, date=datet) == 'Feb 7, 2016'
    format = '%X'
    assert i18n.format_date(format, date=datet) == '5:11:17 AM'
    assert i18n.format_date(format, date=date) == 'Feb 7, 2016'
    format = '%c'
    assert i18n.format_date(format, date=datet) == 'Feb 7, 2016, 5:11:17 AM'
    assert i18n.format_date(format, date=date) == 'Feb 7, 2016'
Example #43
0
def test_format_date():
    date = datetime.date(2016, 2, 7)

    # strftime format
    format = '%B %d, %Y'
    with warnings.catch_warnings():
        # Test format_date() with no language argument -- this form will be
        # removed in Sphinx 7 (xref RemovedInSphinx70Warning)
        warnings.simplefilter("ignore")
        assert i18n.format_date(format, date=date) == 'February 07, 2016'
    assert i18n.format_date(format, date=date,
                            language='') == 'February 07, 2016'
    assert i18n.format_date(format, date=date,
                            language='unknown') == 'February 07, 2016'
    assert i18n.format_date(format, date=date,
                            language='en') == 'February 07, 2016'
    assert i18n.format_date(format, date=date, language='ja') == '2月 07, 2016'
    assert i18n.format_date(format, date=date,
                            language='de') == 'Februar 07, 2016'

    # raw string
    format = 'Mon Mar 28 12:37:08 2016, commit 4367aef'
    assert i18n.format_date(format, date=date, language='en') == format

    format = '%B %d, %Y, %H:%M:%S %I %p'
    datet = datetime.datetime(2016, 2, 7, 5, 11, 17, 0)
    assert i18n.format_date(
        format, date=datet,
        language='en') == 'February 07, 2016, 05:11:17 05 AM'

    format = '%B %-d, %Y, %-H:%-M:%-S %-I %p'
    assert i18n.format_date(format, date=datet,
                            language='en') == 'February 7, 2016, 5:11:17 5 AM'
    format = '%x'
    assert i18n.format_date(format, date=datet, language='en') == 'Feb 7, 2016'
    format = '%X'
    assert i18n.format_date(format, date=datet, language='en') == '5:11:17 AM'
    assert i18n.format_date(format, date=date, language='en') == 'Feb 7, 2016'
    format = '%c'
    assert i18n.format_date(format, date=datet,
                            language='en') == 'Feb 7, 2016, 5:11:17 AM'
    assert i18n.format_date(format, date=date, language='en') == 'Feb 7, 2016'

    # timezone
    format = '%Z'
    assert i18n.format_date(format, date=datet, language='en') == 'UTC'
    format = '%z'
    assert i18n.format_date(format, date=datet, language='en') == '+0000'
Example #44
0
File: html.py Project: nunb/sphinx
    def prepare_writing(self, docnames):
        # create the search indexer
        self.indexer = None
        if self.search:
            from sphinx.search import IndexBuilder, languages
            lang = self.config.html_search_language or self.config.language
            if not lang or lang not in languages:
                lang = 'en'
            self.indexer = IndexBuilder(self.env, lang,
                                        self.config.html_search_options,
                                        self.config.html_search_scorer)
            self.load_indexer(docnames)

        self.docwriter = HTMLWriter(self)
        self.docsettings = OptionParser(
            defaults=self.env.settings,
            components=(self.docwriter, ),
            read_config_files=True).get_default_values()
        self.docsettings.compact_lists = bool(self.config.html_compact_lists)

        # determine the additional indices to include
        self.domain_indices = []
        # html_domain_indices can be False/True or a list of index names
        indices_config = self.config.html_domain_indices
        if indices_config:
            for domain_name in sorted(self.env.domains):
                domain = self.env.domains[domain_name]
                for indexcls in domain.indices:
                    indexname = '%s-%s' % (domain.name, indexcls.name)
                    if isinstance(indices_config, list):
                        if indexname not in indices_config:
                            continue
                    # deprecated config value
                    if indexname == 'py-modindex' and \
                       not self.config.html_use_modindex:
                        continue
                    content, collapse = indexcls(domain).generate()
                    if content:
                        self.domain_indices.append(
                            (indexname, indexcls, content, collapse))

        # format the "last updated on" string, only once is enough since it
        # typically doesn't include the time of day
        lufmt = self.config.html_last_updated_fmt
        if lufmt is not None:
            self.last_updated = format_date(lufmt or _('MMM dd, YYYY'),
                                            language=self.config.language)
        else:
            self.last_updated = None

        logo = self.config.html_logo and \
            path.basename(self.config.html_logo) or ''

        favicon = self.config.html_favicon and \
            path.basename(self.config.html_favicon) or ''
        if favicon and os.path.splitext(favicon)[1] != '.ico':
            self.warn('html_favicon is not an .ico file')

        if not isinstance(self.config.html_use_opensearch, string_types):
            self.warn('html_use_opensearch config value must now be a string')

        self.relations = self.env.collect_relations()

        rellinks = []
        if self.get_builder_config('use_index', 'html'):
            rellinks.append(('genindex', _('General Index'), 'I', _('index')))
        for indexname, indexcls, content, collapse in self.domain_indices:
            # if it has a short name
            if indexcls.shortname:
                rellinks.append(
                    (indexname, indexcls.localname, '', indexcls.shortname))

        if self.config.html_style is not None:
            stylename = self.config.html_style
        elif self.theme:
            stylename = self.theme.get_confstr('theme', 'stylesheet')
        else:
            stylename = 'default.css'

        self.globalcontext = dict(
            embedded=self.embedded,
            project=self.config.project,
            release=self.config.release,
            version=self.config.version,
            last_updated=self.last_updated,
            copyright=self.config.copyright,
            master_doc=self.config.master_doc,
            use_opensearch=self.config.html_use_opensearch,
            docstitle=self.config.html_title,
            shorttitle=self.config.html_short_title,
            show_copyright=self.config.html_show_copyright,
            show_sphinx=self.config.html_show_sphinx,
            has_source=self.config.html_copy_source,
            show_source=self.config.html_show_sourcelink,
            file_suffix=self.out_suffix,
            script_files=self.script_files,
            language=self.config.language,
            css_files=self.css_files,
            sphinx_version=__display_version__,
            style=stylename,
            rellinks=rellinks,
            builder=self.name,
            parents=[],
            logo=logo,
            favicon=favicon,
        )
        if self.theme:
            self.globalcontext.update(('theme_' + key, val) for (
                key,
                val) in iteritems(self.theme.get_options(self.theme_options)))
        self.globalcontext.update(self.config.html_context)