Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/mkdocs_git_revision_date_localized_plugin/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "1.4.0"
__version__ = "1.4.0"
4 changes: 1 addition & 3 deletions src/mkdocs_git_revision_date_localized_plugin/ci.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ def raise_ci_warnings(repo) -> None:

n_commits = commit_count(repo)


# Gitlab Runners
if os.getenv("GITLAB_CI") is not None and n_commits < 50:
# Default is GIT_DEPTH of 50 for gitlab
Expand Down Expand Up @@ -76,7 +75,6 @@ def raise_ci_warnings(repo) -> None:
)



def commit_count(repo) -> int:
"""
Determine the number of commits in a repository.
Expand All @@ -87,7 +85,7 @@ def commit_count(repo) -> int:
Returns:
count (int): Number of commits.
"""
return int(repo.rev_list('--count','HEAD'))
return int(repo.rev_list("--count", "HEAD"))


def is_shallow_clone(repo) -> bool:
Expand Down
13 changes: 3 additions & 10 deletions src/mkdocs_git_revision_date_localized_plugin/dates.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@

from babel.dates import format_date, get_timezone

from datetime import datetime, timezone
from typing import Any, Dict


def get_date_formats(
unix_timestamp: float,
locale: str = "en",
time_zone: str = "UTC",
custom_format: str = "%d. %B %Y"
unix_timestamp: float, locale: str = "en", time_zone: str = "UTC", custom_format: str = "%d. %B %Y"
) -> Dict[str, Any]:
"""
Calculate different date formats / types.
Expand All @@ -25,11 +21,9 @@ def get_date_formats(
"""
assert time_zone is not None
assert locale is not None

utc_revision_date = datetime.fromtimestamp(int(unix_timestamp), tz=timezone.utc)
loc_revision_date = utc_revision_date.replace(
tzinfo=get_timezone("UTC")
).astimezone(get_timezone(time_zone))
loc_revision_date = utc_revision_date.replace(tzinfo=get_timezone("UTC")).astimezone(get_timezone(time_zone))

return {
"date": format_date(loc_revision_date, format="long", locale=locale),
Expand All @@ -44,4 +38,3 @@ def get_date_formats(
"timeago": '<span class="timeago" datetime="%s" locale="%s"></span>' % (loc_revision_date.isoformat(), locale),
"custom": loc_revision_date.strftime(custom_format),
}

1 change: 1 addition & 0 deletions src/mkdocs_git_revision_date_localized_plugin/exclude.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

Inspired by https://github.com/apenwarr/mkdocs-exclude
"""

import os
import fnmatch
from typing import List
Expand Down
106 changes: 58 additions & 48 deletions src/mkdocs_git_revision_date_localized_plugin/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
https://www.mkdocs.org/
https://github.com/timvink/mkdocs-git-revision-date-localized-plugin/
"""

import logging
import re
import os
Expand All @@ -26,6 +27,7 @@

HERE = os.path.dirname(os.path.abspath(__file__))


class GitRevisionDateLocalizedPlugin(BasePlugin):
"""
Mkdocs plugin to add revision date from Git.
Expand Down Expand Up @@ -62,16 +64,18 @@ def on_config(self, config: config_options.Config, **kwargs) -> Dict[str, Any]:
Returns:
dict: global configuration object
"""
if not self.config.get('enabled'):
if not self.config.get("enabled"):
return config

assert self.config['type'] in ["date","datetime","iso_date","iso_datetime","timeago","custom"]

self.util = Util(config=self.config, mkdocs_dir=os.path.abspath(os.path.dirname(config.get('config_file_path'))))
assert self.config["type"] in ["date", "datetime", "iso_date", "iso_datetime", "timeago", "custom"]

self.util = Util(
config=self.config, mkdocs_dir=os.path.abspath(os.path.dirname(config.get("config_file_path")))
)

# Save last commit timestamp for entire site
self.last_site_revision_hash, self.last_site_revision_timestamp = self.util.get_git_commit_timestamp(
config.get('docs_dir')
config.get("docs_dir")
)

# Get locale from plugin configuration
Expand All @@ -80,24 +84,22 @@ def on_config(self, config: config_options.Config, **kwargs) -> Dict[str, Any]:
# theme locale
if "theme" in config and "language" in config.get("theme"):
custom_theme = config.get("theme")
theme_locale = custom_theme["language"] if Version(mkdocs_version) >= Version("1.6.0") else custom_theme._vars.get("language")
logging.debug(
"Locale '%s' extracted from the custom theme: '%s'"
% (theme_locale, custom_theme.name)
theme_locale = (
custom_theme["language"]
if Version(mkdocs_version) >= Version("1.6.0")
else custom_theme._vars.get("language")
)
logging.debug("Locale '%s' extracted from the custom theme: '%s'" % (theme_locale, custom_theme.name))
elif "theme" in config and "locale" in config.get("theme"):
custom_theme = config.get("theme")
theme_locale = custom_theme.locale if Version(mkdocs_version) >= Version("1.6.0") else custom_theme._vars.get("locale")
logging.debug(
"Locale '%s' extracted from the custom theme: '%s'"
% (theme_locale, custom_theme.name)
theme_locale = (
custom_theme.locale if Version(mkdocs_version) >= Version("1.6.0") else custom_theme._vars.get("locale")
)
logging.debug("Locale '%s' extracted from the custom theme: '%s'" % (theme_locale, custom_theme.name))

else:
theme_locale = None
logging.debug(
"No locale found in theme configuration (or no custom theme set)"
)
logging.debug("No locale found in theme configuration (or no custom theme set)")

# First prio: plugin locale
if plugin_locale:
Expand All @@ -106,30 +108,25 @@ def on_config(self, config: config_options.Config, **kwargs) -> Dict[str, Any]:
# Second prio: theme locale
elif theme_locale:
locale_set = theme_locale
logging.debug(
"Locale not set in plugin. Fallback to theme configuration: %s"
% locale_set
)
logging.debug("Locale not set in plugin. Fallback to theme configuration: %s" % locale_set)
# Lastly, fallback is English
else:
locale_set = "en"
logging.debug("No locale set. Fallback to: %s" % locale_set)

# Validate locale
locale_set = str(locale_set)
assert len(locale_set) == 2, "locale must be a 2 letter code, see https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes"
assert len(locale_set) == 2, (
"locale must be a 2 letter code, see https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes"
)

# set locale also in plugin configuration
self.config["locale"] = locale_set

# Add pointers to support files for timeago.js
if self.config.get("type") == "timeago":
config["extra_javascript"] = ["js/timeago_mkdocs_material.js"] + config[
"extra_javascript"
]
config["extra_javascript"] = ["js/timeago.min.js"] + config[
"extra_javascript"
]
config["extra_javascript"] = ["js/timeago_mkdocs_material.js"] + config["extra_javascript"]
config["extra_javascript"] = ["js/timeago.min.js"] + config["extra_javascript"]
config["extra_css"] = ["css/timeago.css"] + config["extra_css"]

# Compatibility with mkdocs-static-i18n
Expand All @@ -139,12 +136,10 @@ def on_config(self, config: config_options.Config, **kwargs) -> Dict[str, Any]:
msg = "[git-revision-date-localized] should be defined after the i18n plugin in your mkdocs.yml file. "
msg += "This is because i18n adds a 'locale' variable to markdown pages that this plugin supports."
raise ConfigurationError(msg)

return config

def on_page_markdown(
self, markdown: str, page: Page, config: config_options.Config, files, **kwargs
) -> str:
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.

Expand All @@ -164,7 +159,7 @@ def on_page_markdown(
Returns:
str: Markdown source text of page as string
"""
if not self.config.get('enabled'):
if not self.config.get("enabled"):
return markdown

# Exclude pages specified in config
Expand All @@ -185,31 +180,35 @@ def on_page_markdown(
# Second prio is a frontmatter variable 'locale' set in the markdown
if not locale:
if "locale" in page.meta:
locale = page.meta['locale']
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"

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
# Except for generated pages (f.e. by mkdocs-gen-files plugin)
if getattr(page.file, "generated_by", None):
last_revision_hash, last_revision_timestamp = "", int(time.time())
else:
last_revision_hash, last_revision_timestamp = self.util.get_git_commit_timestamp(
path=page.file.abs_src_path,
is_first_commit=False,
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_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
Expand All @@ -223,7 +222,9 @@ def on_page_markdown(
page.meta["git_revision_date_localized"] = revision_date
page.meta["git_revision_date_localized_hash"] = last_revision_hash
page.meta["git_revision_date_localized_tag"] = self.util.get_tag_name_for_commit(last_revision_hash)
revision_dates_raw = self.util.get_date_formats_for_timestamp(last_revision_timestamp, locale=locale, add_spans=False)
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

Expand All @@ -237,13 +238,19 @@ def on_page_markdown(

# Also add site last updated information, for developers
page.meta["git_site_revision_date_localized_hash"] = self.last_site_revision_hash
page.meta["git_site_revision_date_localized_tag"] = self.util.get_tag_name_for_commit(self.last_site_revision_hash)
site_dates = self.util.get_date_formats_for_timestamp(self.last_site_revision_timestamp, locale=locale, add_spans=True)
page.meta["git_site_revision_date_localized_tag"] = self.util.get_tag_name_for_commit(
self.last_site_revision_hash
)
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)
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

Expand All @@ -255,12 +262,11 @@ def on_page_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
# Except for generated pages (f.e. by mkdocs-gen-files plugin)
if getattr(page.file, "generated_by", None):
Expand All @@ -279,7 +285,9 @@ def on_page_markdown(
first_revision_hash, first_revision_timestamp = last_revision_hash, last_revision_timestamp

# Creation date formats
creation_dates = self.util.get_date_formats_for_timestamp(first_revision_timestamp, locale=locale, add_spans=True)
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
Expand All @@ -293,7 +301,9 @@ def on_page_markdown(
page.meta["git_creation_date_localized_hash"] = first_revision_hash
page.meta["git_creation_date_localized_tag"] = self.util.get_tag_name_for_commit(first_revision_hash)
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)
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

Expand All @@ -314,7 +324,7 @@ def on_post_build(self, config: Dict[str, Any], **kwargs) -> None:
Adds the timeago assets to the build.
"""
# Add timeago files:
if self.config.get("type") == "timeago" and self.config.get('enabled'):
if self.config.get("type") == "timeago" and self.config.get("enabled"):
files = [
"js/timeago.min.js",
"js/timeago_mkdocs_material.js",
Expand Down
Loading
Loading