Beispiel #1
0
    def on_page_content(self, html: str, page: Page,
                        config: config_options.Config, files, **kwargs) -> str:
        soup = BeautifulSoup(html, 'html.parser')

        description = ''

        for descendant in soup.descendants:
            if type(descendant) not in (NavigableString, CData):
                continue
            if descendant.parent.name in ('h1', 'h2', 'h3', 'h4', 'h5', 'h6'):
                continue
            descendant = descendant.strip()
            if len(descendant) == 0:
                continue
            if descendant == '¶':
                continue
            description += descendant + ' '

        page.meta['smart_description'] = ' '.join(
            description.strip().split()[:25]) + '...'

        image = soup.img
        if image is not None:
            path = remove_prefix(image['src'], '../')
            page.meta['smart_image'] = urllib.parse.urljoin(
                config['site_url'], path)

        return html
Beispiel #2
0
    def on_page_markdown(self, markdown: str, page: Page,
                         config: config_options.Config, files) -> str:
        """
        Replace jinja2 tags in markdown and templates with the localized dates

        The page_markdown event is called after the page's markdown is loaded
        from file and can be used to alter the Markdown source text.
        The meta- data has been stripped off and is available as page.meta
        at this point.

        https://www.mkdocs.org/user-guide/plugins/#on_page_markdown

        Args:
            markdown (str): Markdown source text of page as string
            page: mkdocs.nav.Page instance
            config: global configuration object
            site_navigation: global navigation object

        Returns:
            str: Markdown source text of page as string
        """

        revision_dates = self.util.get_revision_date_for_file(
            path=page.file.abs_src_path,
            locale=self.config.get("locale", "en"),
            fallback_to_build_date=self.config.get("fallback_to_build_date"),
        )
        revision_date = revision_dates[self.config["type"]]
        page.meta["git_revision_date_localized"] = revision_date
        return re.sub(
            r"\{\{\s*[page\.meta\.]*git_revision_date_localized\s*\}\}",
            revision_date,
            markdown,
            flags=re.IGNORECASE,
        )
Beispiel #3
0
    def on_page_markdown(
        self, markdown: str, page: Page, config: config_options.Config, files, **kwargs
    ) -> str:
        """
        Replace jinja2 tags in markdown and templates with the localized dates.

        The page_markdown event is called after the page's markdown is loaded
        from file and can be used to alter the Markdown source text.
        The meta- data has been stripped off and is available as page.meta
        at this point.

        https://www.mkdocs.org/user-guide/plugins/#on_page_markdown

        Args:
            markdown (str): Markdown source text of page as string
            page: mkdocs.nav.Page instance
            config: global configuration object
            site_navigation: global navigation object

        Returns:
            str: Markdown source text of page as string
        """
        if not self.config.get('enabled'):
            return markdown

        # Exclude pages specified in config
        excluded_pages = self.config.get("exclude", [])
        if exclude(page.file.src_path, excluded_pages):
            logging.debug("Excluding page " + page.file.src_path)
            return markdown

        # Retrieve git commit timestamp
        last_revision_timestamp = self.util.get_git_commit_timestamp(
                path=page.file.abs_src_path,
                is_first_commit=False,
        )

        # Last revision date
        revision_dates = self.util.get_date_formats_for_timestamp(last_revision_timestamp)
        revision_date = revision_dates[self.config["type"]]

        # timeago output is dynamic, which breaks when you print a page
        # This ensures fallback to type "iso_date"
        # controlled via CSS (see on_post_build() event)
        if self.config["type"] == "timeago":
            revision_date += revision_dates["iso_date"]

        # Add to page meta information, for developers
        # Include variants without the CSS <span> elements (raw date strings)
        page.meta["git_revision_date_localized"] = revision_date
        revision_dates_raw = self.util.get_date_formats_for_timestamp(last_revision_timestamp, add_spans=False)
        for date_type, date_string in revision_dates_raw.items():
            page.meta["git_revision_date_localized_raw_%s" % date_type] = date_string

        # Replace any occurances in markdown page
        markdown = re.sub(
            r"\{\{\s*git_revision_date_localized\s*\}\}",
            revision_date,
            markdown,
            flags=re.IGNORECASE,
        )

        # If creation date not enabled, return markdown
        # This is for speed: prevents another `git log` operation each file
        if not self.config.get("enable_creation_date"):
            return markdown
    
        # Retrieve git commit timestamp
        first_revision_timestamp = self.util.get_git_commit_timestamp(
            path=page.file.abs_src_path,
            is_first_commit=True,
        )

        # Creation date formats
        creation_dates = self.util.get_date_formats_for_timestamp(first_revision_timestamp)
        creation_date = creation_dates[self.config["type"]]

        # timeago output is dynamic, which breaks when you print a page
        # This ensures fallback to type "iso_date"
        # controlled via CSS (see on_post_build() event)
        if self.config["type"] == "timeago":
            creation_date += creation_dates["iso_date"]

        # Add to page meta information, for developers
        # Include variants without the CSS <span> elements (raw date strings)
        page.meta["git_creation_date_localized"] = creation_date
        creation_dates_raw = self.util.get_date_formats_for_timestamp(first_revision_timestamp, add_spans=False)
        for date_type, date_string in creation_dates_raw.items():
            page.meta["git_creation_date_localized_raw_%s" % date_type] = date_string

        # Replace any occurances in markdown page
        markdown = re.sub(
            r"\{\{\s*git_creation_date_localized\s*\}\}",
            creation_date,
            markdown,
            flags=re.IGNORECASE,
        )

        # Finally,
        # Also add site last updated information, for developers
        site_dates = self.util.get_date_formats_for_timestamp(self.last_site_revision_timestamp)
        site_date = site_dates[self.config["type"]]
        if self.config["type"] == "timeago":
            site_date += site_dates["iso_date"]
        page.meta["git_site_revision_date_localized"] = site_date
        site_dates_raw = self.util.get_date_formats_for_timestamp(self.last_site_revision_timestamp, add_spans=False)
        for date_type, date_string in site_dates_raw.items():
            page.meta["git_site_revision_date_localized_raw_%s" % date_type] = date_string

        return markdown
    def on_page_markdown(
        self, markdown: str, page: Page, config: config_options.Config, files, **kwargs
    ) -> str:
        """
        Replace jinja2 tags in markdown and templates with the localized dates.

        The page_markdown event is called after the page's markdown is loaded
        from file and can be used to alter the Markdown source text.
        The meta- data has been stripped off and is available as page.meta
        at this point.

        https://www.mkdocs.org/user-guide/plugins/#on_page_markdown

        Args:
            markdown (str): Markdown source text of page as string
            page: mkdocs.nav.Page instance
            config: global configuration object
            site_navigation: global navigation object

        Returns:
            str: Markdown source text of page as string
        """
        # Exclude pages specified in config
        excluded_pages = self.config.get("exclude", [])
        if exclude(page.file.src_path, excluded_pages):
            logging.debug("Excluding page " + page.file.src_path)
            return markdown

        # revision date
        revision_dates = self.util.get_date_formats_for_timestamp(
            commit_timestamp=self.util.get_git_commit_timestamp(
                path=page.file.abs_src_path,
                is_first_commit=False,
            )
        )
        revision_date = revision_dates[self.config["type"]]

        # timeago output is dynamic, which breaks when you print a page
        # This ensures fallback to type "iso_date"
        # controlled via CSS (see on_post_build() event)
        if self.config["type"] == "timeago":
            revision_date += revision_dates["iso_date"]

        # Add to page meta information
        page.meta["git_revision_date_localized"] = revision_date
        # Replace any occurances in markdown page
        markdown = re.sub(
            r"\{\{\s*git_revision_date_localized\s*\}\}",
            revision_date,
            markdown,
            flags=re.IGNORECASE,
        )

        # Creation date
        if self.config.get("enable_creation_date"):
            creation_dates = self.util.get_date_formats_for_timestamp(
                commit_timestamp=self.util.get_git_commit_timestamp(
                    path=page.file.abs_src_path,
                    is_first_commit=True,
                )
            )
            creation_date = creation_dates[self.config["type"]]

            # timeago output is dynamic, which breaks when you print a page
            # This ensures fallback to type "iso_date"
            # controlled via CSS (see on_post_build() event)
            if self.config["type"] == "timeago":
                creation_date += creation_dates["iso_date"]

            page.meta["git_creation_date_localized"] = creation_date
            markdown = re.sub(
                r"\{\{\s*git_creation_date_localized\s*\}\}",
                creation_date,
                markdown,
                flags=re.IGNORECASE,
            )

        return markdown
Beispiel #5
0
    def on_page_markdown(self, markdown: str, page: Page,
                         config: config_options.Config, files,
                         **kwargs) -> str:
        """
        Replace jinja2 tags in markdown and templates with the localized dates.

        The page_markdown event is called after the page's markdown is loaded
        from file and can be used to alter the Markdown source text.
        The meta- data has been stripped off and is available as page.meta
        at this point.

        https://www.mkdocs.org/user-guide/plugins/#on_page_markdown

        Args:
            markdown (str): Markdown source text of page as string
            page: mkdocs.nav.Page instance
            config: global configuration object
            site_navigation: global navigation object

        Returns:
            str: Markdown source text of page as string
        """
        if not self.config.get('enabled'):
            return markdown

        # Exclude pages specified in config
        excluded_pages = self.config.get("exclude", [])
        if exclude(page.file.src_path, excluded_pages):
            logging.debug("Excluding page " + page.file.src_path)
            return markdown

        # Find the locale

        # First prio is use mkdocs-static-i18n locale if set
        try:
            locale = page.locale

        except AttributeError:
            locale = None

        # Second prio is a frontmatter variable 'locale' set in the markdown
        if not locale:
            if "locale" in page.meta:
                locale = page.meta['locale']

        # Finally, if no page locale set, we take the locale determined on_config()
        if not locale:
            locale = self.config.get("locale")

        # MkDocs supports 2-letter and 5-letter locales
        # https://www.mkdocs.org/user-guide/localizing-your-theme/#supported-locales
        # We need the 2 letter variant
        if len(locale) == 5:
            locale = locale[:2]
        assert len(
            locale
        ) == 2, "locale must be a 2 letter code, see https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes"

        # Retrieve git commit timestamp
        last_revision_timestamp = self.util.get_git_commit_timestamp(
            path=page.file.abs_src_path,
            is_first_commit=False,
        )

        # Last revision date
        revision_dates = self.util.get_date_formats_for_timestamp(
            last_revision_timestamp, locale=locale, add_spans=True)
        revision_date = revision_dates[self.config["type"]]

        # timeago output is dynamic, which breaks when you print a page
        # This ensures fallback to type "iso_date"
        # controlled via CSS (see on_post_build() event)
        if self.config["type"] == "timeago":
            revision_date += revision_dates["iso_date"]

        # Add to page meta information, for developers
        # Include variants without the CSS <span> elements (raw date strings)
        page.meta["git_revision_date_localized"] = revision_date
        revision_dates_raw = self.util.get_date_formats_for_timestamp(
            last_revision_timestamp, locale=locale, add_spans=False)
        for date_type, date_string in revision_dates_raw.items():
            page.meta["git_revision_date_localized_raw_%s" %
                      date_type] = date_string

        # Replace any occurances in markdown page
        markdown = re.sub(
            r"\{\{\s*git_revision_date_localized\s*\}\}",
            revision_date,
            markdown,
            flags=re.IGNORECASE,
        )

        # Also add site last updated information, for developers
        site_dates = self.util.get_date_formats_for_timestamp(
            self.last_site_revision_timestamp, locale=locale, add_spans=True)
        site_date = site_dates[self.config["type"]]
        if self.config["type"] == "timeago":
            site_date += site_dates["iso_date"]
        page.meta["git_site_revision_date_localized"] = site_date
        site_dates_raw = self.util.get_date_formats_for_timestamp(
            self.last_site_revision_timestamp, locale=locale, add_spans=False)
        for date_type, date_string in site_dates_raw.items():
            page.meta["git_site_revision_date_localized_raw_%s" %
                      date_type] = date_string

        # Replace any occurances in markdown page
        markdown = re.sub(
            r"\{\{\s*git_site_revision_date_localized\s*\}\}",
            site_date,
            markdown,
            flags=re.IGNORECASE,
        )

        # If creation date not enabled, return markdown
        # This is for speed: prevents another `git log` operation each file
        if not self.config.get("enable_creation_date"):
            return markdown

        # Retrieve git commit timestamp
        first_revision_timestamp = self.util.get_git_commit_timestamp(
            path=page.file.abs_src_path,
            is_first_commit=True,
        )

        # Creation date formats
        creation_dates = self.util.get_date_formats_for_timestamp(
            first_revision_timestamp, locale=locale, add_spans=True)
        creation_date = creation_dates[self.config["type"]]

        # timeago output is dynamic, which breaks when you print a page
        # This ensures fallback to type "iso_date"
        # controlled via CSS (see on_post_build() event)
        if self.config["type"] == "timeago":
            creation_date += creation_dates["iso_date"]

        # Add to page meta information, for developers
        # Include variants without the CSS <span> elements (raw date strings)
        page.meta["git_creation_date_localized"] = creation_date
        creation_dates_raw = self.util.get_date_formats_for_timestamp(
            first_revision_timestamp, locale=locale, add_spans=False)
        for date_type, date_string in creation_dates_raw.items():
            page.meta["git_creation_date_localized_raw_%s" %
                      date_type] = date_string

        # Replace any occurances in markdown page
        markdown = re.sub(
            r"\{\{\s*git_creation_date_localized\s*\}\}",
            creation_date,
            markdown,
            flags=re.IGNORECASE,
        )

        return markdown