Skip to content

Commit 1efdd24

Browse files
committed
Merge branch 'master' of github.com:timvink/mkdocs-git-revision-date-localized-plugin
2 parents 6df930d + 597ae12 commit 1efdd24

File tree

18 files changed

+1029
-37
lines changed

18 files changed

+1029
-37
lines changed

docs/howto/specify-locale.md

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
# Specify a locale
2+
3+
`locale` is a two letter [ISO639](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language code that `git-revision-date-localized` uses to display dates in your preferred language.
4+
5+
For example:
6+
7+
```yaml
8+
April 27, 2021 # `locale: en` with `type: date` (default)
9+
April 27, 2021 13:11:28 # `locale: en` with `type: datetime`
10+
2 weeks ago # `locale: en` with `type: timeago`
11+
27 de marzo de 2021 # `locale: es` with `type: date`
12+
27 de marzo de 2021 13:57:28 # `locale: es` with `type: datetime`
13+
hace 2 semanas # `locale: es` with `type: timeago`
14+
```
15+
16+
You can set the `locale` in different locations, both for your entire site and on a per-page basis. If specified multiple times `git-revision-date-localized` will use the `locale` that is most specific to a page.
17+
18+
Here's the order of priority:
19+
20+
## 1. Page locale set by the `i18n` plugin
21+
22+
The [mkdocs-static-i18n](https://github.com/ultrabug/mkdocs-static-i18n) plugin helps you support multiple language versions of your site. When enabled, `i18n` will add a `locale` attribute to each markdown page that `git-revision-date-localized` will use.
23+
24+
## 2. Page locale set by metadata
25+
26+
The [Metadata](https://python-markdown.github.io/extensions/meta_data/) adds the ability to attach arbitrary key-value pairs to a document via front matter written in YAML syntax before the Markdown. Enable it via mkdocs.yml:
27+
28+
```yaml
29+
# mkdocs.yml
30+
markdown_extensions:
31+
- meta
32+
```
33+
34+
If set `git-revision-date-localized` will use the `locale` key in a markdown page's frontmatter, for example:
35+
36+
```md
37+
---
38+
locale: en
39+
---
40+
41+
# Page title
42+
```
43+
44+
## 3. Site locale set by your theme
45+
46+
Some [MkDocs Themes](https://github.com/mkdocs/mkdocs/wiki/MkDocs-Themes) support [localization](https://www.mkdocs.org/user-guide/localizing-your-theme/) by setting a `locale` or `language` option. See for example the [Changing the language](https://squidfunk.github.io/mkdocs-material/setup/changing-the-language/) section of [Material for MkDocs](https://squidfunk.github.io/mkdocs-material/).
47+
48+
Example:
49+
50+
```yaml
51+
# mkdocs.yml
52+
theme:
53+
language: en
54+
```
55+
56+
## 4. Site locale set by this plugin
57+
58+
Of course `locale` is an [option](../options.md) for this plugin also.
59+
60+
```yaml
61+
plugins:
62+
- git-revision-date-localized:
63+
locale: en
64+
```
65+
66+
## 5. Fallback locale
67+
68+
If no `locale` is specified anywhere, the fallback is English (`en`).
69+
70+
!!! info "Supported locales"
71+
- When used in combination with `type: date` or `type: datetime`, translation is done using [babel](https://github.com/python-babel/babel) which supports [these locales](http://www.unicode.org/cldr/charts/latest/supplemental/territory_language_information.html)
72+
73+
- When used in combination with `type: timeago` then [timeago.js](https://github.com/hustcc/timeago.js) is added to your website, which supports [these locales](https://github.com/hustcc/timeago.js/tree/master/src/lang). If you specify a locale not supported by timeago.js, the fallback is English (`en`)

docs/options.md

Lines changed: 36 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,13 +33,18 @@ November 28, 2019 13:57:28 # type: datetime
3333

3434
Default is `UTC`. Specify a time zone database name ([reference](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones)). This option is especially relevant when using `type: datetime` and `type: iso_datetime`. Note that when using [timeago](http://timeago.yarp.com/) (with `type: timeago`) any difference in time zones between server and client will be handled automatically.
3535

36-
## `locale`
36+
=== ":octicons-file-code-16: mkdocs.yml"
37+
38+
```yaml
39+
plugins:
40+
- git-revision-date-localized:
41+
timezone: Europe/Amsterdam
42+
```
43+
3744

38-
Default is `None`. Specify a two letter [ISO639](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language code to display dates in your preferred language.
45+
## `locale`
3946

40-
- When not set, this plugin will look for `locale` or `language` options set in your theme. If also not set, the fallback is English (`en`)
41-
- When used in combination with `type: date` or `type: datetime`, translation is done using [babel](https://github.com/python-babel/babel) which supports [these locales](http://www.unicode.org/cldr/charts/latest/supplemental/territory_language_information.html)
42-
- When used in combination with `type: timeago` then [timeago.js](https://github.com/hustcc/timeago.js) is added to your website, which supports [these locales](https://github.com/hustcc/timeago.js/tree/master/src/lang). If you specify a locale not supported by timeago.js, the fallback is English (`en`)
47+
Default is `None`. Specify a two letter [ISO639](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language code to display dates in your preferred language. Note this plugin supports many different ways to [specify the locale](howto/specify-locale.md), but if not specified anywhere the fallback is English (`en`).
4348

4449
Example outputs:
4550

@@ -52,14 +57,40 @@ April 27, 2021 13:11:28 # `locale: en` with `type: datetime`
5257
hace 2 semanas # `locale: es` with `type: timeago`
5358
```
5459

60+
=== ":octicons-file-code-16: mkdocs.yml"
61+
62+
```yaml
63+
plugins:
64+
- git-revision-date-localized:
65+
locale: en
66+
```
67+
68+
5569
## `fallback_to_build_date`
5670

5771
Default is `false`. Enables falling back to the time when `mkdocs build` was executed *when git is not available*. This means the revision date will be incorrect, but this can be acceptable if you want your project to also successfully build in environments with no access to GIT.
5872

73+
=== ":octicons-file-code-16: mkdocs.yml"
74+
75+
```yaml
76+
plugins:
77+
- git-revision-date-localized:
78+
fallback_to_build_date: true
79+
```
80+
81+
5982
## `enable_creation_date`
6083

6184
Default is `false` (because it has a small effect on build time). Enables a *Created* date variables, see [available-variables.md]. This will also add a created date at the bottom of each page in `mkdocs-material` as it has native support (see [overriding a theme](howto/override-a-theme.md)).
6285

86+
=== ":octicons-file-code-16: mkdocs.yml"
87+
88+
```yaml
89+
plugins:
90+
- git-revision-date-localized:
91+
enable_creation_date: true
92+
```
93+
6394
## `exclude`
6495

6596
Default is empty. Specify a list of page source paths (one per line) that should not have a revision date included (excluded from processing by this plugin). This can be useful for example to remove the revision date from the front page. The source path of a page is relative to your `docs/` folder. You can also use [globs](https://docs.python.org/3/library/glob.html) instead of full source paths. To exclude `docs/subfolder/page.md` specify in your `mkdocs.yml` a line under `exclude:` with `- subfolder/page.md`. Some examples:

mkdocs.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ nav:
88
- index.md
99
- available-variables.md
1010
- How to:
11+
- howto/specify-locale.md
1112
- howto/custom-styling.md
1213
- howto/override-a-theme.md
1314
- options.md

mkdocs_git_revision_date_localized_plugin/ci.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ def raise_ci_warnings(repo) -> None:
2020

2121
n_commits = commit_count(repo)
2222

23+
2324
# Gitlab Runners
2425
if os.getenv("GITLAB_CI") is not None and n_commits < 50:
2526
# Default is GIT_DEPTH of 50 for gitlab
@@ -85,11 +86,7 @@ def commit_count(repo) -> int:
8586
Returns:
8687
count (int): Number of commits.
8788
"""
88-
refs = repo.for_each_ref().split("\n")
89-
refs = [x.split()[0] for x in refs]
90-
91-
counts = [int(repo.rev_list(x, count=True, first_parent=True)) for x in refs]
92-
return max(counts)
89+
return int(repo.rev_list('--count','HEAD'))
9390

9491

9592
def is_shallow_clone(repo) -> bool:

mkdocs_git_revision_date_localized_plugin/plugin.py

Lines changed: 50 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,14 @@
1414
from mkdocs.plugins import BasePlugin
1515
from mkdocs.structure.nav import Page
1616
from mkdocs.utils import copy_file
17+
from mkdocs.exceptions import ConfigurationError
1718

1819
# package modules
1920
from mkdocs_git_revision_date_localized_plugin.util import Util
2021
from mkdocs_git_revision_date_localized_plugin.exclude import exclude
2122

2223
from typing import Any, Dict
24+
from collections import OrderedDict
2325

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

@@ -59,17 +61,15 @@ def on_config(self, config: config_options.Config, **kwargs) -> Dict[str, Any]:
5961
if not self.config.get('enabled'):
6062
return config
6163

64+
assert self.config['type'] in ["date","datetime","iso_date","iso_datetime","timeago"]
65+
6266
self.util = Util(config=self.config)
6367

6468
# Save last commit timestamp for entire site
6569
self.last_site_revision_timestamp = self.util.get_git_commit_timestamp(
6670
config.get('docs_dir')
6771
)
6872

69-
# Get locale settings - might be added in future mkdocs versions
70-
# see: https://github.com/timvink/mkdocs-git-revision-date-localized-plugin/issues/24
71-
mkdocs_locale = config.get("locale", None)
72-
7373
# Get locale from plugin configuration
7474
plugin_locale = self.config.get("locale", None)
7575

@@ -106,14 +106,15 @@ def on_config(self, config: config_options.Config, **kwargs) -> Dict[str, Any]:
106106
"Locale not set in plugin. Fallback to theme configuration: %s"
107107
% locale_set
108108
)
109-
# Third prio is mkdocs locale (which might be added in the future)
110-
elif mkdocs_locale:
111-
locale_set = mkdocs_locale
112-
logging.debug("Using locale from mkdocs configuration: %s" % locale_set)
109+
# Lastly, fallback is English
113110
else:
114111
locale_set = "en"
115112
logging.debug("No locale set. Fallback to: %s" % locale_set)
116113

114+
# Validate locale
115+
locale_set = str(locale_set)
116+
assert len(locale_set) == 2, "locale must be a 2 letter code, see https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes"
117+
117118
# set locale also in plugin configuration
118119
self.config["locale"] = locale_set
119120

@@ -127,6 +128,14 @@ def on_config(self, config: config_options.Config, **kwargs) -> Dict[str, Any]:
127128
]
128129
config["extra_css"] = ["css/timeago.css"] + config["extra_css"]
129130

131+
# Compatibility with mkdocs-static-i18n
132+
plugins = [*OrderedDict(config["plugins"])]
133+
if "i18n" in plugins:
134+
if plugins.index("git-revision-date-localized") < plugins.index("i18n"):
135+
msg = "[git-revision-date-localized] should be defined after the i18n plugin in your mkdocs.yml file. "
136+
msg += "This is because i18n adds a 'locale' variable to markdown pages that this plugin supports."
137+
raise ConfigurationError(msg)
138+
130139
return config
131140

132141
def on_page_markdown(
@@ -160,14 +169,41 @@ def on_page_markdown(
160169
logging.debug("Excluding page " + page.file.src_path)
161170
return markdown
162171

172+
# Find the locale
173+
174+
# First prio is use mkdocs-static-i18n locale if set
175+
try:
176+
locale = page.locale
177+
178+
except AttributeError:
179+
locale = None
180+
181+
# Second prio is a frontmatter variable 'locale' set in the markdown
182+
if not locale:
183+
if "locale" in page.meta:
184+
locale = page.meta['locale']
185+
186+
# Finally, if no page locale set, we take the locale determined on_config()
187+
if not locale:
188+
locale = self.config.get("locale")
189+
190+
# MkDocs supports 2-letter and 5-letter locales
191+
# https://www.mkdocs.org/user-guide/localizing-your-theme/#supported-locales
192+
# We need the 2 letter variant
193+
if len(locale) == 5:
194+
locale = locale[:2]
195+
assert len(locale) == 2, "locale must be a 2 letter code, see https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes"
196+
197+
198+
163199
# Retrieve git commit timestamp
164200
last_revision_timestamp = self.util.get_git_commit_timestamp(
165201
path=page.file.abs_src_path,
166202
is_first_commit=False,
167203
)
168204

169205
# Last revision date
170-
revision_dates = self.util.get_date_formats_for_timestamp(last_revision_timestamp)
206+
revision_dates = self.util.get_date_formats_for_timestamp(last_revision_timestamp, locale=locale, add_spans=True)
171207
revision_date = revision_dates[self.config["type"]]
172208

173209
# timeago output is dynamic, which breaks when you print a page
@@ -179,7 +215,7 @@ def on_page_markdown(
179215
# Add to page meta information, for developers
180216
# Include variants without the CSS <span> elements (raw date strings)
181217
page.meta["git_revision_date_localized"] = revision_date
182-
revision_dates_raw = self.util.get_date_formats_for_timestamp(last_revision_timestamp, add_spans=False)
218+
revision_dates_raw = self.util.get_date_formats_for_timestamp(last_revision_timestamp, locale=locale, add_spans=False)
183219
for date_type, date_string in revision_dates_raw.items():
184220
page.meta["git_revision_date_localized_raw_%s" % date_type] = date_string
185221

@@ -192,12 +228,12 @@ def on_page_markdown(
192228
)
193229

194230
# Also add site last updated information, for developers
195-
site_dates = self.util.get_date_formats_for_timestamp(self.last_site_revision_timestamp)
231+
site_dates = self.util.get_date_formats_for_timestamp(self.last_site_revision_timestamp, locale=locale, add_spans=True)
196232
site_date = site_dates[self.config["type"]]
197233
if self.config["type"] == "timeago":
198234
site_date += site_dates["iso_date"]
199235
page.meta["git_site_revision_date_localized"] = site_date
200-
site_dates_raw = self.util.get_date_formats_for_timestamp(self.last_site_revision_timestamp, add_spans=False)
236+
site_dates_raw = self.util.get_date_formats_for_timestamp(self.last_site_revision_timestamp, locale=locale, add_spans=False)
201237
for date_type, date_string in site_dates_raw.items():
202238
page.meta["git_site_revision_date_localized_raw_%s" % date_type] = date_string
203239

@@ -222,7 +258,7 @@ def on_page_markdown(
222258
)
223259

224260
# Creation date formats
225-
creation_dates = self.util.get_date_formats_for_timestamp(first_revision_timestamp)
261+
creation_dates = self.util.get_date_formats_for_timestamp(first_revision_timestamp, locale=locale, add_spans=True)
226262
creation_date = creation_dates[self.config["type"]]
227263

228264
# timeago output is dynamic, which breaks when you print a page
@@ -234,7 +270,7 @@ def on_page_markdown(
234270
# Add to page meta information, for developers
235271
# Include variants without the CSS <span> elements (raw date strings)
236272
page.meta["git_creation_date_localized"] = creation_date
237-
creation_dates_raw = self.util.get_date_formats_for_timestamp(first_revision_timestamp, add_spans=False)
273+
creation_dates_raw = self.util.get_date_formats_for_timestamp(first_revision_timestamp, locale=locale, add_spans=False)
238274
for date_type, date_string in creation_dates_raw.items():
239275
page.meta["git_creation_date_localized_raw_%s" % date_type] = date_string
240276

mkdocs_git_revision_date_localized_plugin/util.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -178,23 +178,24 @@ def get_git_commit_timestamp(
178178
def get_date_formats_for_timestamp(
179179
self,
180180
commit_timestamp: int,
181-
add_spans: bool = True
181+
locale: str,
182+
add_spans: bool = True,
182183
) -> Dict[str, str]:
183184
"""
184185
Determine localized date variants for a given timestamp.
185186
186187
Args:
187188
commit_timestamp (int): most recent commit date in unix timestamp.
188189
locale (str, optional): Locale code of language to use. Defaults to 'en'.
189-
time_zone (str): Timezone database name (https://en.wikipedia.org/wiki/List_of_tz_database_time_zones).
190+
add_spans: Wraps output in <span> elements with unique classes for easy CSS formatting
190191
191192
Returns:
192193
dict: Localized date variants.
193194
"""
194195
date_formats = self._date_formats(
195196
unix_timestamp=commit_timestamp,
196197
time_zone=self.config.get("timezone"),
197-
locale=self.config.get("locale")
198+
locale=locale
198199
)
199200
if add_spans:
200201
date_formats = self.add_spans(date_formats)
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
---
2+
locale: en
3+
---
4+
15
# Test home page
26

37
Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?
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+
plugins:
5+
- search
6+
- git-revision-date-localized
7+
8+
markdown_extensions:
9+
- meta

0 commit comments

Comments
 (0)