Skip to content

Commit be1e0a3

Browse files
authored
Merge pull request #22 from Guts/fix-not-localized-date
Use locale during date formatting
2 parents b6647ef + e0ba530 commit be1e0a3

File tree

8 files changed

+359
-50
lines changed

8 files changed

+359
-50
lines changed

mkdocs_git_revision_date_localized_plugin/plugin.py

Lines changed: 58 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
# standard lib
2+
import logging
23
import re
34

45
# 3rd party
@@ -7,18 +8,17 @@
78
from mkdocs.structure.nav import Page
89

910
# package modules
10-
from .util import Util
11+
from mkdocs_git_revision_date_localized_plugin.util import Util
1112

1213

1314
class GitRevisionDateLocalizedPlugin(BasePlugin):
1415
config_scheme = (
1516
("fallback_to_build_date", config_options.Type(bool, default=False)),
16-
("locale", config_options.Type(str, default="")),
17+
("locale", config_options.Type(str, default=None)),
1718
("type", config_options.Type(str, default="date")),
1819
)
1920

2021
def __init__(self):
21-
self.locale = "en"
2222
self.util = Util()
2323

2424
def on_config(self, config: config_options.Config) -> dict:
@@ -37,24 +37,56 @@ def on_config(self, config: config_options.Config) -> dict:
3737
dict: global configuration object
3838
"""
3939

40-
# Get locale settings
41-
mkdocs_locale = config.get("locale", "")
42-
plugin_locale = self.config["locale"]
43-
theme_locale = vars(config["theme"]).get("_vars", {}).get("locale", "")
44-
if theme_locale == "":
45-
theme_locale = vars(config["theme"]).get("_vars", {}).get("language", "")
40+
# Get locale settings - might be added in future mkdocs versions
41+
# see: https://github.com/timvink/mkdocs-git-revision-date-localized-plugin/issues/24
42+
mkdocs_locale = config.get("locale", None)
43+
44+
# Get locale from plugin configuration
45+
plugin_locale = self.config.get("locale", None)
46+
47+
# theme locale
48+
if "theme" in config and "locale" in config.get("theme"):
49+
custom_theme = config.get("theme")
50+
theme_locale = custom_theme._vars.get("locale")
51+
logging.debug(
52+
"Locale '%s' extracted from the custom theme: '%s'"
53+
% (theme_locale, custom_theme.name)
54+
)
55+
elif "theme" in config and "language" in config.get("theme"):
56+
custom_theme = config.get("theme")
57+
theme_locale = custom_theme._vars.get("language")
58+
logging.debug(
59+
"Locale '%s' extracted from the custom theme: '%s'"
60+
% (theme_locale, custom_theme.name)
61+
)
62+
63+
else:
64+
theme_locale = None
65+
logging.debug(
66+
"No locale found in theme configuration (or no custom theme set)"
67+
)
4668

4769
# First prio: plugin locale
48-
if plugin_locale != "":
49-
self.locale = plugin_locale
70+
if plugin_locale:
71+
locale_set = plugin_locale
72+
logging.debug("Using locale from plugin configuration: %s" % locale_set)
5073
# Second prio: theme locale
51-
elif theme_locale != "":
52-
self.locale = theme_locale
74+
elif theme_locale:
75+
locale_set = theme_locale
76+
logging.debug(
77+
"Locale not set in plugin. Fallback to theme configuration: %s"
78+
% locale_set
79+
)
5380
# Third prio is mkdocs locale (which might be added in the future)
54-
elif mkdocs_locale != "":
55-
self.locale = mkdocs_locale
81+
elif mkdocs_locale:
82+
locale_set = mkdocs_locale
83+
logging.debug("Using locale from mkdocs configuration: %s" % locale_set)
5684
else:
57-
self.locale = "en"
85+
locale_set = "en"
86+
logging.debug("No locale set. Fallback to: %s" % locale_set)
87+
88+
# set locale also in plugin configuration
89+
self.config["locale"] = locale_set
5890

5991
return config
6092

@@ -78,7 +110,7 @@ def on_post_page(self, output_content: str, **kwargs) -> str:
78110
str: output of rendered template as string
79111
"""
80112

81-
if self.config["type"] != "timeago":
113+
if self.config.get("type") != "timeago":
82114
return output_content
83115

84116
extra_js = """
@@ -118,7 +150,7 @@ def on_page_markdown(
118150

119151
revision_dates = self.util.get_revision_date_for_file(
120152
path=page.file.abs_src_path,
121-
locale=self.locale,
153+
locale=self.config.get("locale", "en"),
122154
fallback_to_build_date=self.config.get("fallback_to_build_date"),
123155
)
124156
revision_date = revision_dates[self.config["type"]]
@@ -129,3 +161,11 @@ def on_page_markdown(
129161
markdown,
130162
flags=re.IGNORECASE,
131163
)
164+
165+
166+
# ##############################################################################
167+
# ##### Stand alone program ########
168+
# ##################################
169+
if __name__ == "__main__":
170+
"""Standalone execution and quick tests."""
171+
pass

mkdocs_git_revision_date_localized_plugin/util.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ def _date_formats(unix_timestamp: float, locale="en") -> dict:
5656
timestamp_in_ms = unix_timestamp * 1000
5757

5858
revision_date = datetime.utcfromtimestamp(unix_timestamp)
59+
logging.debug("Revision date: %s - Locale: %s" % (revision_date, locale))
5960

6061
return {
6162
"date": format_date(revision_date, format="long", locale=locale),
@@ -118,7 +119,7 @@ def get_revision_date_for_file(
118119
unix_timestamp = datetime.utcnow().timestamp()
119120
logging.warning("%s has no git logs, using current timestamp" % path)
120121

121-
return self._date_formats(unix_timestamp)
122+
return self._date_formats(unix_timestamp=unix_timestamp, locale=locale)
122123

123124

124125
def is_shallow_clone(repo: Git) -> bool:

tests/basic_setup/mkdocs_datetime.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,4 @@ use_directory_urls: true
44
plugins:
55
- search
66
- git-revision-date-localized:
7-
type: datetime
7+
type: datetime

tests/basic_setup/mkdocs_locale.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
site_name: test gitrevisiondatelocalized_plugin
22
use_directory_urls: true
33

4-
locale: nl
4+
locale: fr
55

66
plugins:
77
- search

tests/basic_setup/mkdocs_plugin_locale.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,4 @@ use_directory_urls: true
44
plugins:
55
- search
66
- git-revision-date-localized:
7-
locale: nl
7+
locale: nl
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
site_name: test gitrevisiondatelocalized_plugin
2+
use_directory_urls: true
3+
4+
theme:
5+
name: 'material'
6+
7+
plugins:
8+
- search
9+
- git-revision-date-localized

tests/test_basic.py

Lines changed: 71 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -9,25 +9,60 @@
99
>>> os.mkdir(tmp_path)
1010
"""
1111

12+
# #############################################################################
13+
# ########## Libraries #############
14+
# ##################################
15+
1216
# standard lib
1317
import logging
1418
import os
1519
import re
1620
import shutil
1721

18-
# 3rd partu
22+
# MkDocs
23+
from mkdocs.__main__ import build_command
24+
from mkdocs.config import load_config
25+
26+
# other 3rd party
1927
import git
2028
import pytest
21-
import yaml
2229
from click.testing import CliRunner
23-
from mkdocs.__main__ import build_command
2430

2531
# package module
2632
from mkdocs_git_revision_date_localized_plugin.util import Util
2733

34+
# #############################################################################
35+
# ######## Globals #################
36+
# ##################################
37+
38+
PLUGIN_NAME = "git-revision-date-localized"
2839

29-
def load_config(mkdocs_path):
30-
return yaml.load(open(mkdocs_path, "rb"), Loader=yaml.Loader)
40+
# custom log level to get plugin info messages
41+
logging.basicConfig(level=logging.INFO)
42+
43+
44+
# #############################################################################
45+
# ########## Helpers ###############
46+
# ##################################
47+
def get_plugin_config_from_mkdocs(mkdocs_path) -> dict:
48+
# instanciate plugin
49+
cfg_mkdocs = load_config(mkdocs_path)
50+
51+
plugins = cfg_mkdocs.get("plugins")
52+
plugin_loaded = plugins.get(PLUGIN_NAME)
53+
54+
cfg = plugin_loaded.on_config(cfg_mkdocs)
55+
logging.info("Fixture configuration loaded: " + str(cfg))
56+
57+
assert (
58+
plugin_loaded.config.get("locale") is not None
59+
), "Locale should never be None after plugin is loaded"
60+
61+
logging.info(
62+
"Locale '%s' determined from %s"
63+
% (plugin_loaded.config.get("locale"), mkdocs_path)
64+
)
65+
return plugin_loaded.config
3166

3267

3368
def setup_clean_mkdocs_folder(mkdocs_yml_path, output_path):
@@ -141,7 +176,7 @@ def build_docs_setup(testproject_path):
141176
raise
142177

143178

144-
def validate_build(testproject_path):
179+
def validate_build(testproject_path, plugin_config: dict):
145180
"""
146181
Validates a build from a testproject
147182
@@ -157,19 +192,21 @@ def validate_build(testproject_path):
157192
# Make sure with markdown tag has valid
158193
# git revision date tag
159194
page_with_tag = testproject_path / "site/page_with_tag/index.html"
160-
contents = page_with_tag.read_text()
195+
contents = page_with_tag.read_text(encoding="utf8")
161196
assert re.search(r"Markdown tag\:\s[<span>|\w].+", contents)
162197

163198
repo = Util(testproject_path)
164199
date_formats = repo.get_revision_date_for_file(
165-
testproject_path / "docs/page_with_tag.md"
200+
path=testproject_path / "docs/page_with_tag.md",
201+
locale=plugin_config.get("locale"),
202+
fallback_to_build_date=plugin_config.get("fallback_to_build_date"),
166203
)
167204

168205
searches = [re.search(x, contents) for x in date_formats.values()]
169206
assert any(searches), "No correct date formats output was found"
170207

171208

172-
def validate_mkdocs_file(temp_path, mkdocs_yml_file):
209+
def validate_mkdocs_file(temp_path: str, mkdocs_yml_file: str):
173210
"""
174211
Creates a clean mkdocs project
175212
for a mkdocs YML file, builds and validates it.
@@ -184,14 +221,18 @@ def validate_mkdocs_file(temp_path, mkdocs_yml_file):
184221
setup_commit_history(testproject_path)
185222
result = build_docs_setup(testproject_path)
186223
assert result.exit_code == 0, "'mkdocs build' command failed"
187-
validate_build(testproject_path)
188-
189-
return testproject_path
190224

225+
# validate build with locale retrieved from mkdocs config file
226+
validate_build(
227+
testproject_path, plugin_config=get_plugin_config_from_mkdocs(mkdocs_yml_file)
228+
)
191229

192-
#### Tests ####
230+
return testproject_path
193231

194232

233+
# #############################################################################
234+
# ########### Tests ################
235+
# ##################################
195236
def test_date_formats():
196237
u = Util()
197238
assert u._date_formats(1582397529) == {
@@ -217,19 +258,6 @@ def test_missing_git_repo(tmp_path):
217258
), "'mkdocs build' command succeeded while there is no GIT repo"
218259

219260

220-
def test_missing_git_repo_ignored(tmp_path):
221-
"""
222-
When there is no GIT repo, the git error should be ignored.
223-
"""
224-
testproject_path = setup_clean_mkdocs_folder(
225-
mkdocs_yml_path="tests/basic_setup/mkdocs_fallback_to_build_date.yml",
226-
output_path=tmp_path,
227-
)
228-
229-
result = build_docs_setup(testproject_path)
230-
assert result.exit_code == 0
231-
232-
233261
def test_build_no_options(tmp_path):
234262
# Enable plugin with no extra options set
235263
validate_mkdocs_file(tmp_path, "tests/basic_setup/mkdocs.yml")
@@ -241,7 +269,7 @@ def test_build_locale_plugin(tmp_path):
241269

242270

243271
def test_build_locale_mkdocs(tmp_path):
244-
# Enable plugin with mkdocs locale set to 'nl'
272+
# Enable plugin with mkdocs locale set to 'fr'
245273
validate_mkdocs_file(tmp_path, "tests/basic_setup/mkdocs_locale.yml")
246274

247275

@@ -257,10 +285,25 @@ def test_material_theme(tmp_path):
257285
# In mkdocs-material, a 'last update' should appear
258286
# in German because locale is set to 'de'
259287
index_file = testproject_path / "site/index.html"
260-
contents = index_file.read_text()
288+
contents = index_file.read_text(encoding="utf8")
261289
assert re.search(r"Letztes Update\:\s[\w].+", contents)
262290

263291

292+
def test_material_theme_no_locale(tmp_path):
293+
"""
294+
When using mkdocs-material theme, test correct working
295+
"""
296+
# theme set to 'material' with 'language' set to 'de'
297+
testproject_path = validate_mkdocs_file(
298+
tmp_path, "tests/basic_setup/mkdocs_theme_no_locale.yml"
299+
)
300+
301+
# In mkdocs-material, a 'last update' should appear
302+
# in German because locale is set to 'de'
303+
index_file = testproject_path / "site/index.html"
304+
contents = index_file.read_text(encoding="utf8")
305+
assert re.search(r"Last update\:\s[\w].+", contents)
306+
264307
def test_type_timeago(tmp_path):
265308
# type: 'timeago'
266309
testproject_path = validate_mkdocs_file(

0 commit comments

Comments
 (0)