Skip to content

Commit 08e535b

Browse files
authored
Merge pull request #36 from timvink/release06
Release06
2 parents dd82961 + 53a949d commit 08e535b

File tree

9 files changed

+165
-76
lines changed

9 files changed

+165
-76
lines changed

README.md

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -32,14 +32,17 @@ plugins:
3232
3333
> If you have no `plugins` entry in your config file yet, you'll likely also want to add the `search` plugin. MkDocs enables it by default if there is no `plugins` entry set.
3434

35-
### Note when using on CI runners
35+
### Note when using build environments
3636

37-
The plugin needs access to the last commit that touched a file to be able to retrieve the date. If you build your docs using CI then you might need to change your settings:
37+
This plugin needs access to the last commit that touched a specific file to be able to retrieve the date. By default many build environments only retrieve the last commit, which means you might need to:
38+
<details>
39+
<summary>Change your CI settings</summary>
40+
41+
- github actions: set `fetch_depth` to `0` ([docs](https://github.com/actions/checkout))
42+
- gitlab runners: set `GIT_DEPTH` to `1000` ([docs](https://docs.gitlab.com/ee/user/project/pipelines/settings.html#git-shallow-clone))
43+
- bitbucket pipelines: set `clone: depth: full` ([docs](https://support.atlassian.com/bitbucket-cloud/docs/configure-bitbucket-pipelinesyml/))
44+
</details>
3845

39-
- github actions: set `fetch_depth` to `0` ([docs](https://github.com/actions/checkout))
40-
- gitlab runners: set `GIT_DEPTH` to `1000` ([docs](https://docs.gitlab.com/ee/user/project/pipelines/settings.html#git-shallow-clone))
41-
42-
----
4346

4447
## Usage
4548

@@ -72,9 +75,10 @@ You can customize the plugin by setting options in `mkdocs.yml`. For example:
7275
```yml
7376
plugins:
7477
- git-revision-date-localized:
75-
type: timeago
76-
locale: en
77-
fallback_to_build_date: false
78+
type: timeago
79+
time_zone: Europe/Amsterdam
80+
locale: en
81+
fallback_to_build_date: false
7882
```
7983

8084
### `type`
@@ -89,6 +93,10 @@ Default is `date`. To change the date format, set the `type` parameter to one of
8993
20 hours ago # type: timeago
9094
```
9195

96+
### `time_zone`
97+
98+
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.
99+
92100
### `locale`
93101

94102
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.
@@ -99,7 +107,7 @@ Default is `None`. Specify a two letter [ISO639](https://en.wikipedia.org/wiki/L
99107

100108
### `fallback_to_build_date`
101109

102-
Default is `false`. If set to `true` the plugin will use the time when running `mkdocs build` instead of the git revision date. This means the revision date will be inaccurate, but this can be useful if your build environment has no access to GIT and you want to ignore the Git exceptions during `git log`.
110+
Default is `false`. If set to `true` the plugin will use the time at `mkdocs build` instead of the file's last git revision date. This means the revision date is incorrect, but this can be acceptable if you want your project to also successfully build in environments with no access to GIT.
103111

104112
## Contributing
105113

mkdocs_git_revision_date_localized_plugin/plugin.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,10 @@ class GitRevisionDateLocalizedPlugin(BasePlugin):
1616
("fallback_to_build_date", config_options.Type(bool, default=False)),
1717
("locale", config_options.Type(str, default=None)),
1818
("type", config_options.Type(str, default="date")),
19+
("timezone", config_options.Type(str, default="UTC")),
1920
)
2021

21-
def on_config(self, config: config_options.Config) -> dict:
22+
def on_config(self, config: config_options.Config, **kwargs) -> dict:
2223
"""
2324
Determine which locale to use.
2425
@@ -33,7 +34,7 @@ def on_config(self, config: config_options.Config) -> dict:
3334
Returns:
3435
dict: global configuration object
3536
"""
36-
self.util = Util(path=config["docs_dir"])
37+
self.util = Util(path=config["docs_dir"], config=self.config)
3738

3839
# Get locale settings - might be added in future mkdocs versions
3940
# see: https://github.com/timvink/mkdocs-git-revision-date-localized-plugin/issues/24
@@ -124,7 +125,7 @@ def on_post_page(self, output_content: str, **kwargs) -> str:
124125
return output_content[:idx] + extra_js + output_content[idx:]
125126

126127
def on_page_markdown(
127-
self, markdown: str, page: Page, config: config_options.Config, files
128+
self, markdown: str, page: Page, config: config_options.Config, files, **kwargs
128129
) -> str:
129130
"""
130131
Replace jinja2 tags in markdown and templates with the localized dates
@@ -149,6 +150,7 @@ def on_page_markdown(
149150
revision_dates = self.util.get_revision_date_for_file(
150151
path=page.file.abs_src_path,
151152
locale=self.config.get("locale", "en"),
153+
time_zone=self.config.get("time_zone", "UTC"),
152154
fallback_to_build_date=self.config.get("fallback_to_build_date"),
153155
)
154156
revision_date = revision_dates[self.config["type"]]

mkdocs_git_revision_date_localized_plugin/util.py

Lines changed: 70 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,34 @@
55
from datetime import datetime
66

77
# 3rd party
8-
from babel.dates import format_date
8+
from babel.dates import format_date, get_timezone
99
from git import Repo, Git, GitCommandError, GitCommandNotFound
1010

1111

1212
class Util:
13-
def __init__(self, path: str = "."):
14-
git_repo = Repo(path, search_parent_directories=True)
15-
self.repo = git_repo.git
13+
def __init__(self, path: str = ".", config={}):
1614

17-
# Checks when running builds on CI
15+
self.fallback_enabled = False
16+
17+
try:
18+
git_repo = Repo(path, search_parent_directories=True)
19+
self.repo = git_repo.git
20+
except:
21+
if config.get("fallback_to_build_date"):
22+
self.fallback_enabled = True
23+
logging.warning(
24+
"[git-revision-date-localized-plugin] Unable to find a git directory and/or git is not installed."
25+
" Option 'fallback_to_build_date' set to 'true': Falling back to build date"
26+
)
27+
return None
28+
else:
29+
logging.error(
30+
"[git-revision-date-localized-plugin] Unable to find a git directory and/or git is not installed."
31+
" To ignore this error, set option 'fallback_to_build_date: true'"
32+
)
33+
raise
34+
35+
# Checks if user is running builds on CI
1836
# See https://github.com/timvink/mkdocs-git-revision-date-localized-plugin/issues/10
1937
if is_shallow_clone(self.repo):
2038
n_commits = commit_count(self.repo)
@@ -40,89 +58,106 @@ def __init__(self, path: str = "."):
4058
"""
4159
)
4260

61+
# TODO add bitbucket
62+
4363
@staticmethod
44-
def _date_formats(unix_timestamp: float, locale="en") -> dict:
64+
def _date_formats(
65+
unix_timestamp: float, locale: str = "en", time_zone: str = "UTC"
66+
) -> dict:
4567
"""
4668
Returns different date formats / types.
4769
4870
Args:
49-
unix_timestamp (datetiment): a timestamp in seconds since 1970
71+
unix_timestamp (float): a timestamp in seconds since 1970
5072
locale (str): Locale code of language to use. Defaults to 'en'.
73+
time_zone (str): timezone database name (https://en.wikipedia.org/wiki/List_of_tz_database_time_zones)
5174
5275
Returns:
5376
dict: different date formats
5477
"""
55-
56-
# Convert to millisecond timestamp
57-
unix_timestamp = int(unix_timestamp)
58-
timestamp_in_ms = unix_timestamp * 1000
59-
60-
revision_date = datetime.utcfromtimestamp(unix_timestamp)
61-
logging.debug("Revision date: %s - Locale: %s" % (revision_date, locale))
78+
utc_revision_date = datetime.utcfromtimestamp(int(unix_timestamp))
79+
loc_revision_date = utc_revision_date.replace(
80+
tzinfo=get_timezone("UTC")
81+
).astimezone(get_timezone(time_zone))
6282

6383
return {
64-
"date": format_date(revision_date, format="long", locale=locale),
65-
"datetime": format_date(revision_date, format="long", locale=locale)
84+
"date": format_date(loc_revision_date, format="long", locale=locale),
85+
"datetime": format_date(loc_revision_date, format="long", locale=locale)
6686
+ " "
67-
+ revision_date.strftime("%H:%M:%S"),
68-
"iso_date": revision_date.strftime("%Y-%m-%d"),
69-
"iso_datetime": revision_date.strftime("%Y-%m-%d %H:%M:%S"),
87+
+ loc_revision_date.strftime("%H:%M:%S"),
88+
"iso_date": loc_revision_date.strftime("%Y-%m-%d"),
89+
"iso_datetime": loc_revision_date.strftime("%Y-%m-%d %H:%M:%S"),
7090
"timeago": "<span class='timeago' datetime='%s' locale='%s'></span>"
71-
% (timestamp_in_ms, locale),
91+
% (loc_revision_date.isoformat(), locale),
7292
}
7393

7494
def get_revision_date_for_file(
75-
self, path: str, locale: str = "en", fallback_to_build_date: bool = False
95+
self,
96+
path: str,
97+
locale: str = "en",
98+
time_zone: str = "UTC",
99+
fallback_to_build_date: bool = False,
76100
) -> dict:
77101
"""
78102
Determine localized date variants for a given file
79103
80104
Args:
81105
path (str): Location of a markdownfile that is part of a GIT repository
82106
locale (str, optional): Locale code of language to use. Defaults to 'en'.
107+
timezone (str): timezone database name (https://en.wikipedia.org/wiki/List_of_tz_database_time_zones)
83108
84109
Returns:
85110
dict: localized date variants
86111
"""
112+
113+
unix_timestamp = None
114+
87115
# perform git log operation
88116
try:
89-
unix_timestamp = self.repo.log(path, n=1, date="short", format="%at")
117+
if not self.fallback_enabled:
118+
# Retrieve author date in UNIX format (%at)
119+
# https://git-scm.com/docs/git-log#Documentation/git-log.txt-ematem
120+
unix_timestamp = self.repo.log(path, n=1, date="short", format="%at")
121+
90122
except GitCommandError as err:
91123
if fallback_to_build_date:
92-
unix_timestamp = None
93124
logging.warning(
94-
"Unable to read git logs of '%s'."
95-
" Is git log readable?"
96-
" Option 'fallback_to_build_date' enabled: so keep building..."
125+
"[git-revision-date-localized-plugin] Unable to read git logs of '%s'. Is git log readable?"
126+
" Option 'fallback_to_build_date' set to 'true': Falling back to build date"
97127
% path
98128
)
99129
else:
100130
logging.error(
101-
"Unable to read git logs of '%s'. "
102-
"To ignore this error, set option 'fallback_to_build_date: true'"
131+
"[git-revision-date-localized-plugin] Unable to read git logs of '%s'. "
132+
" To ignore this error, set option 'fallback_to_build_date: true'"
103133
% path
104134
)
105135
raise err
106136
except GitCommandNotFound as err:
107137
if fallback_to_build_date:
108-
unix_timestamp = None
109138
logging.warning(
110-
"Unable to perform command: git log. Is git installed?"
111-
" Option 'fallback_to_build_date' enabled: so keep building..."
139+
"[git-revision-date-localized-plugin] Unable to perform command: 'git log'. Is git installed?"
140+
" Option 'fallback_to_build_date' set to 'true': Falling back to build date"
112141
)
113142
else:
114143
logging.error(
115-
"Unable to perform command: git log. Is git installed?"
116-
"To ignore this error, set option 'fallback_to_build_date: true'"
144+
"[git-revision-date-localized-plugin] Unable to perform command 'git log'. Is git installed?"
145+
" To ignore this error, set option 'fallback_to_build_date: true'"
117146
)
118147
raise err
119148

120149
# create timestamp
121150
if not unix_timestamp:
122151
unix_timestamp = time.time()
123-
logging.warning("%s has no git logs, using current timestamp" % path)
152+
if not self.fallback_enabled:
153+
logging.warning(
154+
"[git-revision-date-localized-plugin] '%s' has no git logs, using current timestamp"
155+
% path
156+
)
124157

125-
return self._date_formats(unix_timestamp=unix_timestamp, locale=locale)
158+
return self._date_formats(
159+
unix_timestamp=unix_timestamp, time_zone=time_zone, locale=locale
160+
)
126161

127162

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

setup.py

Lines changed: 2 additions & 2 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.5.2",
8+
version="0.6",
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",
@@ -20,7 +20,7 @@
2020
"License :: OSI Approved :: MIT License",
2121
"Operating System :: OS Independent",
2222
],
23-
install_requires=["mkdocs>=0.17", "GitPython", "jinja2", "babel>=2.7.0"],
23+
install_requires=["mkdocs>=1.0", "GitPython", "babel>=2.7.0"],
2424
packages=find_packages(),
2525
entry_points={
2626
"mkdocs.plugins": [
Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,3 @@
11
# test page
22

3-
this page has a git authors tag.
4-
5-
Markdown tag: {{ git_revision_date_localized }}
6-
3+
Tag <mark>\{\{ git_revision_date_localized \}\}</mark> renders as: {{ git_revision_date_localized }}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
site_name: test gitrevisiondatelocalized_plugin
2+
use_directory_urls: true
3+
4+
theme:
5+
name: 'material'
6+
language: de
7+
8+
plugins:
9+
- search
10+
- git-revision-date-localized

tests/fixtures/basic_project/mkdocs_theme_locale.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use_directory_urls: true
33

44
theme:
55
name: 'material'
6-
language: de
6+
locale: de
77

88
plugins:
99
- search
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
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:
10+
type: timeago

0 commit comments

Comments
 (0)