Skip to content

Commit b8d5cdc

Browse files
committed
refactor code and #6 fix timeago bug
1 parent f7dd9ca commit b8d5cdc

File tree

4 files changed

+111
-58
lines changed

4 files changed

+111
-58
lines changed

README.md

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
# mkdocs-git-revision-date-localized-plugin
66

7-
[MkDocs](https://www.mkdocs.org/) plugin that enables displaying the localized date of the last git modification of a markdown file. Forked from [mkdocs-git-revision-date-plugin](https://github.com/zhaoterryy/mkdocs-git-revision-date-plugin). The plugin uses [babel](https://github.com/python-babel/babel/tree/master/babel) and [timeago](https://github.com/hustcc/timeago) to provide different localized date formats.
7+
[MkDocs](https://www.mkdocs.org/) plugin that enables displaying the date of the last git modification of a page. The plugin uses [babel](https://github.com/python-babel/babel/tree/master/babel) and [timeago.js](https://github.com/hustcc/timeago.js) to provide different localized date formats. Initial fork from [mkdocs-git-revision-date-plugin](https://github.com/zhaoterryy/mkdocs-git-revision-date-plugin).
88

99
![example](https://github.com/timvink/mkdocs-git-revision-date-localized-plugin/raw/master/example.png)
1010

@@ -66,7 +66,12 @@ Set this option to one of `date`, `datetime`, `iso_date`, `iso_datetime` or `tim
6666

6767
### `locale`
6868

69-
Set this option to a two letter [ISO639](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language code to use a another language. If you have also set `locale` or `language` in your theme this setting will be ignored. If no locale is set fallback is English (`en`).
69+
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.
70+
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+
- 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`)
73+
- 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`)
74+
7075

7176
### Example
7277

Lines changed: 85 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,8 @@
11
import re
2-
from os import environ
3-
42
from mkdocs.config import config_options
53
from mkdocs.plugins import BasePlugin
64
from mkdocs.utils import string_types
75
from .util import Util
8-
from datetime import datetime
9-
106

117
class GitRevisionDateLocalizedPlugin(BasePlugin):
128
config_scheme = (
@@ -17,64 +13,109 @@ class GitRevisionDateLocalizedPlugin(BasePlugin):
1713
def __init__(self):
1814
self.locale = 'en'
1915
self.util = Util()
20-
16+
2117
def on_config(self, config):
18+
"""
19+
Determine which locale to use.
20+
21+
The config event is the first event called on build and
22+
is run immediately after the user configuration is loaded and validated.
23+
Any alterations to the config should be made here.
24+
https://www.mkdocs.org/user-guide/plugins/#on_config
25+
26+
Args:
27+
config (dict): global configuration object
28+
29+
Returns:
30+
dict: global configuration object
31+
"""
2232

2333
# Get locale settings
24-
mkdocs_locale = config.get('locale')
34+
mkdocs_locale = config.get('locale', '')
2535
plugin_locale = self.config['locale']
36+
theme_locale = vars(config['theme']).get('_vars', {}).get('locale', '')
37+
if theme_locale == '':
38+
theme_locale = vars(config['theme']).get('_vars', {}).get('language','')
2639

27-
theme_locale = vars(config['theme']).get('_vars', {}).get('locale')
28-
if theme_locale is None:
29-
theme_locale = vars(config['theme']).get('_vars', {}).get('language')
30-
31-
# First prio: theme
32-
if theme_locale:
33-
self.locale = theme_locale
34-
return
35-
36-
# Second prio: plugin locale
40+
# First prio: plugin locale
3741
if plugin_locale != '':
3842
self.locale = plugin_locale
39-
return
40-
41-
# Third is mkdocs locale setting (might be added in the future)
42-
if mkdocs_locale:
43+
# Second prio: theme locale
44+
elif theme_locale != '':
45+
self.locale = theme_locale
46+
# Third prio is mkdocs locale (which might be added in the future)
47+
elif mkdocs_locale != '':
4348
self.locale = mkdocs_locale
49+
else:
50+
self.locale = 'en'
51+
52+
return config
53+
54+
def on_post_page(self, output_content, **kwargs):
55+
"""
56+
Add timeago.js as a CDN to the HTML page.
57+
The CDN with latest version timeago.js can be found on
58+
https://cdnjs.com/libraries/timeago.js
4459
45-
# If none set then english
46-
self.locale = 'en'
47-
return
60+
The `post_template` event is called after the template is rendered,
61+
but before it is written to disc and can be used to alter the output
62+
of the page. If an empty string is returned, the page is skipped
63+
and nothing is written to disc.
4864
65+
https://www.mkdocs.org/user-guide/plugins/#on_post_page
4966
67+
Args:
68+
output_content (str): output of rendered template as string
69+
70+
Returns:
71+
str: output of rendered template as string
72+
"""
73+
74+
if self.config['type'] != 'timeago':
75+
return output_content
76+
77+
extra_js = """
78+
<script src="https://cdnjs.cloudflare.com/ajax/libs/timeago.js/4.0.0-beta.2/timeago.min.js"></script>
79+
<script src="https://cdnjs.cloudflare.com/ajax/libs/timeago.js/4.0.0-beta.2/timeago.locales.min.js"></script>
80+
<script>
81+
const nodes = document.querySelectorAll('.timeago');
82+
const locale = nodes[0].getAttribute('locale');
83+
timeago.render(nodes, locale);
84+
</script>
85+
"""
86+
idx = output_content.index("</body>")
87+
return output_content[:idx] + extra_js + output_content[idx:]
88+
5089
def on_page_markdown(self, markdown, page, config, files):
90+
"""
91+
Replace jinja2 tags in markdown and templates with the localized dates
92+
93+
The page_markdown event is called after the page's markdown is loaded
94+
from file and can be used to alter the Markdown source text.
95+
The meta- data has been stripped off and is available as page.meta
96+
at this point.
97+
98+
https://www.mkdocs.org/user-guide/plugins/#on_page_markdown
99+
100+
Args:
101+
markdown (str): Markdown source text of page as string
102+
page: mkdocs.nav.Page instance
103+
config: global configuration object
104+
site_navigation: global navigation object
105+
106+
Returns:
107+
str: Markdown source text of page as string
108+
"""
51109

52110
revision_dates = self.util.get_revision_date_for_file(
53111
path = page.file.abs_src_path,
54112
locale = self.locale
55113
)
56114
revision_date = revision_dates[self.config['type']]
57-
58115
page.meta['git_revision_date_localized'] = revision_date
59116

60-
if 'macros' in config['plugins']:
61-
keys = list(config['plugins'].keys())
62-
vals = list(config['plugins'].values())
63-
if keys.index('macros') > vals.index(self):
64-
return '{{% set git_revision_date = \'{}\' %}}\n'.format(revision_date) + markdown
65-
else:
66-
print('WARNING - macros plugin must be placed AFTER the git-revision-date-localized plugin. Skipping markdown modifications')
67-
return markdown
68-
else:
69-
markdown = re.sub(r"\{\{(\s)*git_revision_date_localized(\s)*\}\}",
70-
revision_date,
71-
markdown,
72-
flags=re.IGNORECASE)
73-
74-
markdown = re.sub(r"\{\{\s*page\.meta\.git_revision_date_localized\s*\}\}",
75-
revision_date,
76-
markdown,
77-
flags=re.IGNORECASE)
78-
79-
return markdown
117+
return re.sub(r"\{\{\s*[page\.meta\.]*git_revision_date_localized\s*\}\}",
118+
revision_date,
119+
markdown,
120+
flags=re.IGNORECASE)
80121

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
from git import Git
22
from datetime import datetime
3-
import timeago
43
from babel.dates import format_date
54

65
class Util:
@@ -9,21 +8,30 @@ def __init__(self):
98
self.g = Git()
109

1110
def get_revision_date_for_file(self, path: str, locale: str = 'en'):
11+
"""
12+
Determine localized date variants for a given file
13+
14+
Args:
15+
path (str): Location of a file that is part of a GIT repository
16+
locale (str, optional): Locale code of language to use. Defaults to 'en'.
17+
18+
Returns:
19+
dict: localized date variants
20+
"""
21+
22+
unix_timestamp = int(self.g.log(path, n=1, date='short', format='%at'))
23+
timestamp_in_ms = unix_timestamp * 1000
1224

13-
unix_timestamp = self.g.log(path, n=1, date='short', format='%at')
1425
if not unix_timestamp:
1526
revision_date = datetime.now()
1627
print('WARNING - %s has no git logs, revision date defaulting to today\'s date' % path)
1728
else:
18-
revision_date = datetime.utcfromtimestamp(int(unix_timestamp))
29+
revision_date = datetime.utcfromtimestamp(unix_timestamp)
1930

20-
# Localized versions
21-
revision_dates = {
31+
return {
2232
'date' : format_date(revision_date, format="long", locale=locale),
2333
'datetime' : format_date(revision_date, format="long", locale=locale) + ' ' +revision_date.strftime("%H:%M:%S"),
2434
'iso_date' : revision_date.strftime("%Y-%m-%d"),
2535
'iso_datetime' : revision_date.strftime("%Y-%m-%d %H:%M:%S"),
26-
'timeago' : timeago.format(revision_date, locale = locale)
27-
}
28-
29-
return revision_dates
36+
'timeago' : "<span class='timeago' datetime='%s' locale='%s'></span>" % (timestamp_in_ms, locale)
37+
}

setup.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
setup(
77
name='mkdocs-git-revision-date-localized-plugin',
8-
version='0.4.2',
8+
version='0.4.3',
99
description='Mkdocs plugin that enables displaying the localized date of the last git modification of a markdown file.',
1010
long_description=long_description,
1111
long_description_content_type="text/markdown",
@@ -24,8 +24,7 @@
2424
'mkdocs>=0.17',
2525
'GitPython',
2626
'jinja2',
27-
'babel>=2.7.0',
28-
'timeago>=1.0.10'
27+
'babel>=2.7.0'
2928
],
3029
packages=find_packages(),
3130
entry_points={

0 commit comments

Comments
 (0)