Skip to content

Commit 27b4d4a

Browse files
committed
Refactor code
1 parent 0cd1179 commit 27b4d4a

File tree

8 files changed

+89
-79
lines changed

8 files changed

+89
-79
lines changed

mkdocs_git_revision_date_localized_plugin/css/timeago.css

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,4 @@
99
.git-revision-date-localized-plugin-iso_date { display: inline }
1010
.git-revision-date-localized-plugin-timeago { display: none }
1111
}
12+

mkdocs_git_revision_date_localized_plugin/plugin.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -149,14 +149,11 @@ def on_page_markdown(
149149
return markdown
150150

151151
# revision date
152-
revision_dates = self.util.get_revision_date_for_file(
152+
revision_dates = self.util.get_date_formats_for_timestamp(
153153
commit_timestamp=self.util.get_git_commit_timestamp(
154154
path=page.file.abs_src_path,
155155
is_first_commit=False,
156-
fallback_to_build_date=self.config.get("fallback_to_build_date"),
157-
),
158-
locale=self.config.get("locale", "en"),
159-
time_zone=self.config.get("time_zone", "UTC"),
156+
)
160157
)
161158
revision_date = revision_dates[self.config["type"]]
162159

@@ -166,7 +163,9 @@ def on_page_markdown(
166163
if self.config["type"] == "timeago":
167164
revision_date += revision_dates["iso_date"]
168165

166+
# Add to page meta information
169167
page.meta["git_revision_date_localized"] = revision_date
168+
# Replace any occurances in markdown page
170169
markdown = re.sub(
171170
r"\{\{\s*git_revision_date_localized\s*\}\}",
172171
revision_date,
@@ -176,17 +175,17 @@ def on_page_markdown(
176175

177176
# Creation date
178177
if self.config.get("enable_creation_date"):
179-
creation_dates = self.util.get_creation_date_for_file(
178+
creation_dates = self.util.get_date_formats_for_timestamp(
180179
commit_timestamp=self.util.get_git_commit_timestamp(
181180
path=page.file.abs_src_path,
182181
is_first_commit=True,
183-
fallback_to_build_date=self.config.get("fallback_to_build_date"),
184-
),
185-
locale=self.config.get("locale", "en"),
186-
time_zone=self.config.get("time_zone", "UTC"),
182+
)
187183
)
188184
creation_date = creation_dates[self.config["type"]]
189185

186+
# timeago output is dynamic, which breaks when you print a page
187+
# This ensures fallback to type "iso_date"
188+
# controlled via CSS (see on_post_build() event)
190189
if self.config["type"] == "timeago":
191190
creation_date += creation_dates["iso_date"]
192191

mkdocs_git_revision_date_localized_plugin/util.py

Lines changed: 31 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@ class Util:
2929

3030
def __init__(self, config={}):
3131
"""Initialize utility class."""
32-
self.fallback_enabled = False
3332
self.config = config
3433
self.repo_cache = {}
3534

@@ -82,8 +81,7 @@ def _date_formats(
8281
def get_git_commit_timestamp(
8382
self,
8483
path: str,
85-
is_first_commit: bool,
86-
fallback_to_build_date: bool = False,
84+
is_first_commit: bool = False
8785
) -> int:
8886
"""
8987
Get a list of commit dates in unix timestamp, starts with the most recent commit.
@@ -92,47 +90,50 @@ def get_git_commit_timestamp(
9290
is_first_commit (bool): if true, get the timestamp of the first commit,
9391
else, get that of the most recent commit.
9492
path (str): Location of a markdown file that is part of a Git repository.
93+
is_first_commit (bool): retrieve commit timestamp when file was created.
9594
9695
Returns:
97-
list: commit dates in unix timestamp, starts with the most recent commit.
96+
int: commit date in unix timestamp, starts with the most recent commit.
9897
"""
99-
10098
commit_timestamp = ""
10199

102100
# perform git log operation
103101
try:
104-
if not self.fallback_enabled:
105-
# Retrieve author date in UNIX format (%at)
106-
# https://git-scm.com/docs/git-log#Documentation/git-log.txt-ematem
107-
realpath = os.path.realpath(path)
108-
git = self._get_repo(realpath)
109-
if is_first_commit:
110-
commit_timestamp = git.log(
111-
realpath, date="short", format="%at", diff_filter="A"
112-
)
113-
else:
114-
commit_timestamp = git.log(
115-
realpath, date="short", format="%at", n=1
116-
)
102+
# Retrieve author date in UNIX format (%at)
103+
# https://git-scm.com/docs/git-log#Documentation/git-log.txt-ematem
104+
# https://git-scm.com/docs/git-log#Documentation/git-log.txt---diff-filterACDMRTUXB82308203
105+
realpath = os.path.realpath(path)
106+
git = self._get_repo(realpath)
107+
if is_first_commit:
108+
# diff_filter="A" will select the commit that created the file
109+
commit_timestamp = git.log(
110+
realpath, date="short", format="%at", diff_filter="A"
111+
)
112+
else:
113+
commit_timestamp = git.log(
114+
realpath, date="short", format="%at", n=1
115+
)
117116
except (InvalidGitRepositoryError, NoSuchPathError) as err:
118-
if fallback_to_build_date:
117+
if self.config.get('fallback_to_build_date'):
119118
logger.warning(
120119
"[git-revision-date-localized-plugin] Unable to find a git directory and/or git is not installed."
121120
" Option 'fallback_to_build_date' set to 'true': Falling back to build date"
122121
)
122+
commit_timestamp = time.time()
123123
else:
124124
logger.error(
125125
"[git-revision-date-localized-plugin] Unable to find a git directory and/or git is not installed."
126126
" To ignore this error, set option 'fallback_to_build_date: true'"
127127
)
128128
raise err
129129
except GitCommandError as err:
130-
if fallback_to_build_date:
130+
if self.config.get('fallback_to_build_date'):
131131
logger.warning(
132132
"[git-revision-date-localized-plugin] Unable to read git logs of '%s'. Is git log readable?"
133133
" Option 'fallback_to_build_date' set to 'true': Falling back to build date"
134134
% path
135135
)
136+
commit_timestamp = time.time()
136137
else:
137138
logger.error(
138139
"[git-revision-date-localized-plugin] Unable to read git logs of '%s'. "
@@ -141,11 +142,12 @@ def get_git_commit_timestamp(
141142
)
142143
raise err
143144
except GitCommandNotFound as err:
144-
if fallback_to_build_date:
145+
if self.config.get('fallback_to_build_date'):
145146
logger.warning(
146147
"[git-revision-date-localized-plugin] Unable to perform command: 'git log'. Is git installed?"
147148
" Option 'fallback_to_build_date' set to 'true': Falling back to build date"
148149
)
150+
commit_timestamp = time.time()
149151
else:
150152
logger.error(
151153
"[git-revision-date-localized-plugin] Unable to perform command 'git log'. Is git installed?"
@@ -156,19 +158,16 @@ def get_git_commit_timestamp(
156158
# create timestamp
157159
if commit_timestamp == "":
158160
commit_timestamp = time.time()
159-
if not self.fallback_enabled:
160-
logger.warning(
161-
"[git-revision-date-localized-plugin] '%s' has no git logs, using current timestamp"
162-
% path
163-
)
161+
logger.warning(
162+
"[git-revision-date-localized-plugin] '%s' has no git logs, using current timestamp"
163+
% path
164+
)
164165

165166
return int(commit_timestamp)
166167

167-
def get_revision_date_for_file(
168+
def get_date_formats_for_timestamp(
168169
self,
169170
commit_timestamp: int,
170-
locale: str = "en",
171-
time_zone: str = "UTC",
172171
) -> Dict[str, str]:
173172
"""
174173
Determine localized date variants for a given file.
@@ -183,7 +182,9 @@ def get_revision_date_for_file(
183182
"""
184183

185184
date_formats = self._date_formats(
186-
unix_timestamp=commit_timestamp, time_zone=time_zone, locale=locale
185+
unix_timestamp=commit_timestamp,
186+
time_zone=self.config.get("time_zone"),
187+
locale=self.config.get("locale")
187188
)
188189

189190
# Wrap in <span> for styling
@@ -195,33 +196,3 @@ def get_revision_date_for_file(
195196

196197
return date_formats
197198

198-
def get_creation_date_for_file(
199-
self,
200-
commit_timestamp: int,
201-
locale: str = "en",
202-
time_zone: str = "UTC",
203-
) -> Dict[str, str]:
204-
"""
205-
Determine localized date variants for a given file.
206-
207-
Args:
208-
commit_timestamp (int): the first commit date in unix timestamp.
209-
locale (str, optional): Locale code of language to use. Defaults to 'en'.
210-
time_zone (str): Timezone database name (https://en.wikipedia.org/wiki/List_of_tz_database_time_zones).
211-
212-
Returns:
213-
dict: Localized date variants.
214-
"""
215-
216-
date_formats = self._date_formats(
217-
unix_timestamp=commit_timestamp, time_zone=time_zone, locale=locale
218-
)
219-
220-
# Wrap in <span> for styling
221-
for date_type, date_string in date_formats.items():
222-
date_formats[date_type] = (
223-
'<span class="git-revision-date-localized-plugin git-revision-date-localized-plugin-%s">%s</span>'
224-
% (date_type, date_string)
225-
)
226-
227-
return date_formats
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
{% import "partials/language.html" as lang with context %}
2+
3+
<!-- Last updated date -->
4+
{% set label = lang.t("source.revision.date") %}
5+
<hr />
6+
<div class="md-source-date">
7+
<small>
8+
9+
<!-- mkdocs-git-revision-date-localized-plugin -->
10+
{% if page.meta.git_revision_date_localized %}
11+
{{ label }}: {{ page.meta.git_revision_date_localized }}
12+
13+
{% if page.meta.git_creation_date_localized %}
14+
<br />Created: {{ page.meta.git_creation_date_localized }}
15+
{% endif %}
16+
17+
<!-- mkdocs-git-revision-date-plugin -->
18+
{% elif page.meta.revision_date %}
19+
{{ label }}: {{ page.meta.revision_date }}
20+
{% endif %}
21+
</small>
22+
</div>
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
site_name: test gitrevisiondatelocalized_plugin
2+
use_directory_urls: true
3+
4+
theme:
5+
name: 'material'
6+
custom_dir: docs/overrides_material_theme
7+
8+
plugins:
9+
- search
10+
- git-revision-date-localized:
11+
type: timeago
12+
enable_creation_date: true
13+
14+
15+
nav:
16+
- index.md
17+
- first_page.md
18+
- Subpage:
19+
- subpage.md
20+
- second_page.md
21+
- page_with_tag.md

tests/fixtures/basic_project/mkdocs_with_override.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: mkdocs
6-
custom_dir: docs/overrides
6+
custom_dir: docs/overrides_mkdocs_theme
77

88
plugins:
99
- search

tests/test_builds.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -200,14 +200,12 @@ def validate_build(testproject_path, plugin_config: dict = {}):
200200
contents = page_with_tag.read_text(encoding="utf8")
201201
assert re.search(r"renders as\:\s[<span>|\w].+", contents)
202202

203-
repo = Util(str(testproject_path / "docs"))
204-
date_formats = repo.get_revision_date_for_file(
203+
repo = Util(config=plugin_config)
204+
date_formats = repo.get_date_formats_for_timestamp(
205205
commit_timestamp=repo.get_git_commit_timestamp(
206206
path=str(testproject_path / "docs/page_with_tag.md"),
207207
is_first_commit=False,
208-
fallback_to_build_date=plugin_config.get("fallback_to_build_date"),
209-
),
210-
locale=plugin_config.get("locale"), # type: ignore
208+
)
211209
)
212210

213211
searches = [x in contents for x in date_formats.values()]
@@ -217,12 +215,10 @@ def validate_build(testproject_path, plugin_config: dict = {}):
217215
commit_timestamp=repo.get_git_commit_timestamp(
218216
path=str(testproject_path / "docs/page_with_tag.md"),
219217
is_first_commit=True,
220-
fallback_to_build_date=plugin_config.get("fallback_to_build_date"),
221218
)
222219
assert commit_timestamp == 1500854705
223-
date_formats = repo.get_revision_date_for_file(
220+
date_formats = repo.get_date_formats_for_timestamp(
224221
commit_timestamp=commit_timestamp,
225-
locale=plugin_config.get("locale"), # type: ignore
226222
)
227223

228224
searches = [x in contents for x in date_formats.values()]

0 commit comments

Comments
 (0)