Skip to content

Commit d5fcf88

Browse files
authored
Merge pull request #38 from timvink/12-pdf-compat
Release 0.7
2 parents 08e535b + 3191cbb commit d5fcf88

File tree

6 files changed

+149
-71
lines changed

6 files changed

+149
-71
lines changed

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,8 @@ When writing your own [custom themes](https://www.mkdocs.org/user-guide/custom-t
6868
{% endif %}
6969
```
7070

71+
You can style the output using CSS: the date outputs are always wrapped in `<span class='git-revision-date-localized-plugin git-revision-date-localized-plugin-{type}></span>` (where `{type}` is replaced with the `type` option set in the plugin).
72+
7173
## Options
7274

7375
You can customize the plugin by setting options in `mkdocs.yml`. For example:
@@ -86,7 +88,7 @@ plugins:
8688
Default is `date`. To change the date format, set the `type` parameter to one of `date`, `datetime`, `iso_date`, `iso_datetime` or `timeago`. Example outputs:
8789

8890
```bash
89-
28 November, 2019 # type: date
91+
28 November, 2019 # type: date (default)
9092
28 November, 2019 13:57:28 # type: datetime
9193
2019-11-28 # type: iso_date
9294
2019-11-28 13:57:26 # type: iso_datetime
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
import os
2+
import logging
3+
4+
5+
def raise_ci_warnings(repo):
6+
"""
7+
raise warnings when users use mkdocs-git-revision-date-localized-plugin
8+
on CI build runners
9+
10+
Args:
11+
repo (GitPython.git.repo): The Git repo object
12+
"""
13+
14+
if not is_shallow_clone(repo):
15+
return None
16+
17+
n_commits = commit_count(repo)
18+
19+
# Gitlab Runners
20+
if os.environ.get("GITLAB_CI") and n_commits < 50:
21+
# Default is GIT_DEPTH of 50 for gitlab
22+
logging.warning(
23+
"""
24+
[git-revision-date-localized-plugin] Running on a gitlab runner might lead to wrong git revision dates
25+
due to a shallow git fetch depth.
26+
Make sure to set GIT_DEPTH to 1000 in your .gitlab-ci.yml file.
27+
(see https://docs.gitlab.com/ee/user/project/pipelines/settings.html#git-shallow-clone).
28+
"""
29+
)
30+
31+
# Github Actions
32+
if os.environ.get("GITHUB_ACTIONS") and n_commits == 1:
33+
# Default is fetch-depth of 1 for github actions
34+
logging.warning(
35+
"""
36+
[git-revision-date-localized-plugin] Running on github actions might lead to wrong git revision dates
37+
due to a shallow git fetch depth.
38+
Try setting fetch-depth to 0 in your github action
39+
(see https://github.com/actions/checkout).
40+
"""
41+
)
42+
43+
# Bitbucket pipelines
44+
if os.environ.get("CI") and n_commits < 50:
45+
# Default is fetch-depth of 50 for bitbucket pipelines
46+
logging.warning(
47+
"""
48+
[git-revision-date-localized-plugin] Running on bitbucket pipelines might lead to wrong git revision dates
49+
due to a shallow git fetch depth.
50+
Try setting "clone: depth" to "full" in your pipeline
51+
(see https://support.atlassian.com/bitbucket-cloud/docs/configure-bitbucket-pipelinesyml/
52+
and search 'depth').
53+
"""
54+
)
55+
56+
# Azure Devops Pipeline
57+
# Does not limit fetch-depth by default
58+
if os.environ.get("Agent.Source.Git.ShallowFetchDepth", 10e99) < n_commits:
59+
logging.warning(
60+
"""
61+
[git-revision-date-localized-plugin] Running on Azure pipelines with limited fetch-depth might lead to wrong git revision dates
62+
due to a shallow git fetch depth.
63+
Remove any Shallow Fetch settings
64+
(see https://docs.microsoft.com/en-us/azure/devops/pipelines/repos/pipeline-options-for-git?view=azure-devops#shallow-fetch).
65+
"""
66+
)
67+
68+
69+
def commit_count(repo) -> bool:
70+
"""
71+
Helper function to determine the number of commits in a repository
72+
73+
Args:
74+
repo (GitPython.Repo.git): Repository
75+
76+
Returns:
77+
count (int): Number of commits
78+
"""
79+
refs = repo.for_each_ref().split("\n")
80+
refs = [x.split()[0] for x in refs]
81+
82+
counts = [int(repo.rev_list(x, count=True, first_parent=True)) for x in refs]
83+
return max(counts)
84+
85+
86+
def is_shallow_clone(repo) -> bool:
87+
"""
88+
Helper function to determine if repository
89+
is a shallow clone.
90+
91+
References & Context:
92+
https://github.com/timvink/mkdocs-git-revision-date-localized-plugin/issues/10
93+
https://stackoverflow.com/a/37203240/5525118
94+
95+
Args:
96+
repo (GitPython.Repo.git): Repository
97+
98+
Returns:
99+
bool: If a repo is shallow clone
100+
"""
101+
return os.path.exists(".git/shallow")

mkdocs_git_revision_date_localized_plugin/plugin.py

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,7 @@ def on_post_page(self, output_content: str, **kwargs) -> str:
112112
if self.config.get("type") != "timeago":
113113
return output_content
114114

115+
# Insert timeago.js dependencies
115116
extra_js = """
116117
<script src="https://cdnjs.cloudflare.com/ajax/libs/timeago.js/4.0.0-beta.2/timeago.min.js"></script>
117118
<script src="https://cdnjs.cloudflare.com/ajax/libs/timeago.js/4.0.0-beta.2/timeago.locales.min.js"></script>
@@ -122,7 +123,23 @@ def on_post_page(self, output_content: str, **kwargs) -> str:
122123
</script>
123124
"""
124125
idx = output_content.index("</body>")
125-
return output_content[:idx] + extra_js + output_content[idx:]
126+
output_content = output_content[:idx] + extra_js + output_content[idx:]
127+
128+
# timeago output is dynamic, which breaks when you print a page
129+
# This ensures fallback to type "iso_date"
130+
extra_css = """
131+
<style>
132+
.git-revision-date-localized-plugin-iso_date { display: none }
133+
@media print {
134+
.git-revision-date-localized-plugin-iso_date { display: inline }
135+
.git-revision-date-localized-plugin-timeago { display: none }
136+
}
137+
</style>
138+
"""
139+
idx = output_content.index("</head>")
140+
output_content = output_content[:idx] + extra_css + output_content[idx:]
141+
142+
return output_content
126143

127144
def on_page_markdown(
128145
self, markdown: str, page: Page, config: config_options.Config, files, **kwargs
@@ -154,6 +171,13 @@ def on_page_markdown(
154171
fallback_to_build_date=self.config.get("fallback_to_build_date"),
155172
)
156173
revision_date = revision_dates[self.config["type"]]
174+
175+
# timeago output is dynamic, which breaks when you print a page
176+
# This ensures fallback to type "iso_date"
177+
# controlled via CSS (see on_post_page() event)
178+
if self.config["type"] == "timeago":
179+
revision_date += revision_dates["iso_date"]
180+
157181
page.meta["git_revision_date_localized"] = revision_date
158182
return re.sub(
159183
r"\{\{\s*[page\.meta\.]*git_revision_date_localized\s*\}\}",

mkdocs_git_revision_date_localized_plugin/util.py

Lines changed: 14 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
# standard library
22
import logging
3-
import os
43
import time
54
from datetime import datetime
65

6+
from mkdocs_git_revision_date_localized_plugin.ci import raise_ci_warnings
7+
78
# 3rd party
89
from babel.dates import format_date, get_timezone
9-
from git import Repo, Git, GitCommandError, GitCommandNotFound
10+
from git import Repo, GitCommandError, GitCommandNotFound
1011

1112

1213
class Util:
@@ -33,32 +34,8 @@ def __init__(self, path: str = ".", config={}):
3334
raise
3435

3536
# Checks if user is running builds on CI
36-
# See https://github.com/timvink/mkdocs-git-revision-date-localized-plugin/issues/10
37-
if is_shallow_clone(self.repo):
38-
n_commits = commit_count(self.repo)
39-
40-
if os.environ.get("GITLAB_CI") and n_commits < 50:
41-
# Default is GIT_DEPTH of 50 for gitlab
42-
logging.warning(
43-
"""
44-
Running on a gitlab runner might lead to wrong git revision dates
45-
due to a shallow git fetch depth.
46-
Make sure to set GIT_DEPTH to 1000 in your .gitlab-ci.yml file.
47-
(see https://docs.gitlab.com/ee/user/project/pipelines/settings.html#git-shallow-clone).
48-
"""
49-
)
50-
if os.environ.get("GITHUB_ACTIONS") and n_commits == 1:
51-
# Default is fetch-depth of 1 for github actions
52-
logging.warning(
53-
"""
54-
Running on github actions might lead to wrong git revision dates
55-
due to a shallow git fetch depth.
56-
Try setting fetch-depth to 0 in your github action
57-
(see https://github.com/actions/checkout).
58-
"""
59-
)
60-
61-
# TODO add bitbucket
37+
# and raise appropriate warnings
38+
raise_ci_warnings(self.repo)
6239

6340
@staticmethod
6441
def _date_formats(
@@ -87,7 +64,7 @@ def _date_formats(
8764
+ loc_revision_date.strftime("%H:%M:%S"),
8865
"iso_date": loc_revision_date.strftime("%Y-%m-%d"),
8966
"iso_datetime": loc_revision_date.strftime("%Y-%m-%d %H:%M:%S"),
90-
"timeago": "<span class='timeago' datetime='%s' locale='%s'></span>"
67+
"timeago": '<span class="timeago" datetime="%s" locale="%s"></span>'
9168
% (loc_revision_date.isoformat(), locale),
9269
}
9370

@@ -155,41 +132,15 @@ def get_revision_date_for_file(
155132
% path
156133
)
157134

158-
return self._date_formats(
135+
date_formats = self._date_formats(
159136
unix_timestamp=unix_timestamp, time_zone=time_zone, locale=locale
160137
)
161138

139+
# Wrap in <span> for styling
140+
for date_type, date_string in date_formats.items():
141+
date_formats[date_type] = (
142+
'<span class="git-revision-date-localized-plugin git-revision-date-localized-plugin-%s">%s</span>'
143+
% (date_type, date_string)
144+
)
162145

163-
def is_shallow_clone(repo: Git) -> bool:
164-
"""
165-
Helper function to determine if repository
166-
is a shallow clone.
167-
168-
References:
169-
https://github.com/timvink/mkdocs-git-revision-date-localized-plugin/issues/10
170-
https://stackoverflow.com/a/37203240/5525118
171-
172-
Args:
173-
repo (git.Repo): Repository
174-
175-
Returns:
176-
bool: If a repo is shallow clone
177-
"""
178-
return os.path.exists(".git/shallow")
179-
180-
181-
def commit_count(repo: Git) -> bool:
182-
"""
183-
Helper function to determine the number of commits in a repository
184-
185-
Args:
186-
repo (git.Repo): Repository
187-
188-
Returns:
189-
count (int): Number of commits
190-
"""
191-
refs = repo.for_each_ref().split("\n")
192-
refs = [x.split()[0] for x in refs]
193-
194-
counts = [int(repo.rev_list(x, count=True, first_parent=True)) for x in refs]
195-
return max(counts)
146+
return date_formats

setup.py

Lines changed: 1 addition & 1 deletion
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.6",
8+
version="0.7",
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",

tests/test_builds.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,7 @@ def validate_build(testproject_path, plugin_config: dict = {}):
200200
fallback_to_build_date=plugin_config.get("fallback_to_build_date"),
201201
)
202202

203-
searches = [re.search(x, contents) for x in date_formats.values()]
203+
searches = [x in contents for x in date_formats.values()]
204204
assert any(searches), "No correct date formats output was found"
205205

206206

@@ -240,7 +240,7 @@ def test_date_formats():
240240
"datetime": "February 22, 2020 18:52:09",
241241
"iso_date": "2020-02-22",
242242
"iso_datetime": "2020-02-22 18:52:09",
243-
"timeago": "<span class='timeago' datetime='2020-02-22T18:52:09+00:00' locale='en'></span>",
243+
"timeago": '<span class="timeago" datetime="2020-02-22T18:52:09+00:00" locale="en"></span>',
244244
}
245245

246246

@@ -301,7 +301,7 @@ def test_build_material_theme(tmp_path):
301301
# in German because locale is set to 'de'
302302
index_file = testproject_path / "site/index.html"
303303
contents = index_file.read_text(encoding="utf8")
304-
assert re.search(r"Letztes Update\:\s[\w].+", contents)
304+
assert re.search(r"Letztes Update\:\s[<span class].+", contents)
305305

306306

307307
def test_material_theme_locale(tmp_path):
@@ -318,7 +318,7 @@ def test_material_theme_locale(tmp_path):
318318
# The date will be in german though
319319
index_file = testproject_path / "site/index.html"
320320
contents = index_file.read_text(encoding="utf8")
321-
assert re.search(r"Last update\:\s[\w].+", contents)
321+
assert re.search(r"Last update\:\s[<span class].+", contents)
322322

323323

324324
def test_material_theme_no_locale(tmp_path):
@@ -334,7 +334,7 @@ def test_material_theme_no_locale(tmp_path):
334334
# in German because locale is set to 'de'
335335
index_file = testproject_path / "site/index.html"
336336
contents = index_file.read_text(encoding="utf8")
337-
assert re.search(r"Last update\:\s[\w].+", contents)
337+
assert re.search(r"Last update\:\s[<span class].+", contents)
338338

339339

340340
def test_type_timeago(tmp_path):

0 commit comments

Comments
 (0)