Skip to content

Commit f39ca49

Browse files
authored
Add git hash and git tag information
1 parent db0c72c commit f39ca49

File tree

4 files changed

+69
-21
lines changed

4 files changed

+69
-21
lines changed

docs/available-variables.md

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
# Available variables
22

3-
This plugin offers the following variables:
3+
This plugin offers the following timestamp variables:
44

5-
| timestamp | description |
5+
| variable | description |
66
|:-----------|:------------|
77
| `git_revision_date_localized` | Last git commit that touched a file. Enabled by default. |
88
| `git_creation_date_localized` | First git commit that touched a file. Enable in [options](options.md). |
@@ -33,6 +33,9 @@ To allow for more flexibility when overriding a theme there are also variables f
3333
- `page.meta.git_revision_date_localized_raw_iso_datetime`
3434
- `page.meta.git_revision_date_localized_raw_timeago`
3535
- `page.meta.git_revision_date_localized_raw_custom`
36+
37+
Their are also available on the entire site level:
38+
3639
- `page.meta.git_site_revision_date_localized_raw_datetime`
3740
- `page.meta.git_site_revision_date_localized_raw_iso_date`
3841
- `page.meta.git_site_revision_date_localized_raw_date`
@@ -49,6 +52,15 @@ And if you've enabled creation date in the config:
4952
- `page.meta.git_creation_date_localized_raw_timeago`
5053
- `page.meta.git_creation_date_localized_raw_custom`
5154

55+
We also expose the git hash and the git tag (empty if not tag associated with the commit):
56+
57+
- `page.meta.git_revision_date_localized_hash`
58+
- `page.meta.git_revision_date_localized_tag`
59+
- `page.meta.git_site_revision_date_localized_hash`
60+
- `page.meta.git_site_revision_date_localized_tag`
61+
- `page.meta.git_creation_date_localized_hash`
62+
- `page.meta.git_creation_date_localized_tag`
63+
5264
!!! warning "timeago.js dependency"
5365

5466
The `*_timeago` variables require the [timeago.js](https://timeago.org/) dependency. This is automatically injected when the [option](options.md) `type: timeago` is set. Alternatively, you can add [timeago.js](https://timeago.org/) using the [`extra_javascript`](https://www.mkdocs.org/user-guide/configuration/#extra_javascript) option of MkDocs:

src/mkdocs_git_revision_date_localized_plugin/plugin.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ def on_config(self, config: config_options.Config, **kwargs) -> Dict[str, Any]:
7070
self.util = Util(config=self.config, mkdocs_dir=os.path.abspath(os.path.dirname(config.get('config_file_path'))))
7171

7272
# Save last commit timestamp for entire site
73-
self.last_site_revision_timestamp = self.util.get_git_commit_timestamp(
73+
self.last_site_revision_hash, self.last_site_revision_timestamp = self.util.get_git_commit_timestamp(
7474
config.get('docs_dir')
7575
)
7676

@@ -201,9 +201,9 @@ def on_page_markdown(
201201
# Retrieve git commit timestamp
202202
# Except for generated pages (f.e. by mkdocs-gen-files plugin)
203203
if getattr(page.file, "generated_by", None):
204-
last_revision_timestamp = int(time.time())
204+
last_revision_hash, last_revision_timestamp = "", int(time.time())
205205
else:
206-
last_revision_timestamp = self.util.get_git_commit_timestamp(
206+
last_revision_hash, last_revision_timestamp = self.util.get_git_commit_timestamp(
207207
path=page.file.abs_src_path,
208208
is_first_commit=False,
209209
)
@@ -221,6 +221,8 @@ def on_page_markdown(
221221
# Add to page meta information, for developers
222222
# Include variants without the CSS <span> elements (raw date strings)
223223
page.meta["git_revision_date_localized"] = revision_date
224+
page.meta["git_revision_date_localized_hash"] = last_revision_hash
225+
page.meta["git_revision_date_localized_tag"] = self.util.get_tag_name_for_commit(last_revision_hash)
224226
revision_dates_raw = self.util.get_date_formats_for_timestamp(last_revision_timestamp, locale=locale, add_spans=False)
225227
for date_type, date_string in revision_dates_raw.items():
226228
page.meta["git_revision_date_localized_raw_%s" % date_type] = date_string
@@ -234,6 +236,8 @@ def on_page_markdown(
234236
)
235237

236238
# Also add site last updated information, for developers
239+
page.meta["git_site_revision_date_localized_hash"] = self.last_site_revision_hash
240+
page.meta["git_site_revision_date_localized_tag"] = self.util.get_tag_name_for_commit(self.last_site_revision_hash)
237241
site_dates = self.util.get_date_formats_for_timestamp(self.last_site_revision_timestamp, locale=locale, add_spans=True)
238242
site_date = site_dates[self.config["type"]]
239243
if self.config["type"] == "timeago":
@@ -260,9 +264,9 @@ def on_page_markdown(
260264
# Retrieve git commit timestamp
261265
# Except for generated pages (f.e. by mkdocs-gen-files plugin)
262266
if getattr(page.file, "generated_by", None):
263-
first_revision_timestamp = int(time.time())
267+
first_revision_hash, first_revision_timestamp = "", int(time.time())
264268
else:
265-
first_revision_timestamp = self.util.get_git_commit_timestamp(
269+
first_revision_hash, first_revision_timestamp = self.util.get_git_commit_timestamp(
266270
path=page.file.abs_src_path,
267271
is_first_commit=True,
268272
)
@@ -279,6 +283,8 @@ def on_page_markdown(
279283

280284
# Add to page meta information, for developers
281285
# Include variants without the CSS <span> elements (raw date strings)
286+
page.meta["git_creation_date_localized_hash"] = first_revision_hash
287+
page.meta["git_creation_date_localized_tag"] = self.util.get_tag_name_for_commit(first_revision_hash)
282288
page.meta["git_creation_date_localized"] = creation_date
283289
creation_dates_raw = self.util.get_date_formats_for_timestamp(first_revision_timestamp, locale=locale, add_spans=False)
284290
for date_type, date_string in creation_dates_raw.items():

src/mkdocs_git_revision_date_localized_plugin/util.py

Lines changed: 38 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
NoSuchPathError,
1717
)
1818

19-
from typing import Any, Dict, List
19+
from typing import Dict, List, Tuple
2020

2121
logger = logging.getLogger("mkdocs.plugins")
2222

@@ -53,7 +53,7 @@ def get_git_commit_timestamp(
5353
self,
5454
path: str,
5555
is_first_commit: bool = False
56-
) -> int:
56+
) -> Tuple[str, int]:
5757
"""
5858
Get a list of commit dates in unix timestamp, starts with the most recent commit.
5959
@@ -64,9 +64,10 @@ def get_git_commit_timestamp(
6464
is_first_commit (bool): retrieve commit timestamp when file was created.
6565
6666
Returns:
67-
int: commit date in unix timestamp, starts with the most recent commit.
67+
tuple[str, int]: commit hash and commit date in unix timestamp.
6868
"""
6969
commit_timestamp = ""
70+
commit_hash = ""
7071
n_ignored_commits = 0
7172

7273
# Determine the logging level
@@ -118,8 +119,9 @@ def get_git_commit_timestamp(
118119
if not line:
119120
commit_timestamp = ""
120121
break
121-
commit, commit_timestamp = line.split(" ")
122-
if not any(commit.startswith(x) for x in self.ignored_commits):
122+
commit_hash, commit_timestamp = line.split(" ")
123+
breakpoint()
124+
if not any(commit_hash.startswith(x) for x in self.ignored_commits):
123125
break
124126
else:
125127
n_ignored_commits += 1
@@ -195,7 +197,7 @@ def get_git_commit_timestamp(
195197
msg += f" (ignored {n_ignored_commits} commits)"
196198
log(msg)
197199

198-
return int(commit_timestamp)
200+
return commit_hash, int(commit_timestamp)
199201

200202
def get_date_formats_for_timestamp(
201203
self,
@@ -261,3 +263,33 @@ def parse_git_ignore_revs(filename: str) -> List[str]:
261263
logger.error(f"An error occurred while reading the file {filename}: {e}")
262264

263265
return result
266+
267+
def get_tag_name_for_commit(self, commit_hash: str) -> str:
268+
"""
269+
Get the tag name for a specific commit.
270+
271+
Args:
272+
commit_hash (str): The commit hash to find tags for
273+
274+
Returns:
275+
str: Tag name if found, otherwise empty string
276+
"""
277+
if not commit_hash:
278+
return ""
279+
280+
try:
281+
for path, git in self.repo_cache.items():
282+
try:
283+
# Check if there's a tag pointing to this commit
284+
tags = git.tag('--points-at', commit_hash, format='%(refname:short)')
285+
if tags:
286+
# Return first tag if multiple tags exist for the commit
287+
return tags.split('\n')[0]
288+
except GitCommandError:
289+
# Continue checking other repositories in cache
290+
continue
291+
292+
return "" # No tag found for this commit
293+
except Exception as e:
294+
logger.debug(f"Error getting tag for commit {commit_hash}: {str(e)}")
295+
return ""

tests/test_builds.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -255,11 +255,12 @@ def validate_build(testproject_path, plugin_config: dict = {}):
255255
assert re.search(r"renders as\:\s[<span>|\w].+", contents)
256256

257257
repo = Util(config=plugin_config, mkdocs_dir=testproject_path)
258-
date_formats = repo.get_date_formats_for_timestamp(
259-
commit_timestamp=repo.get_git_commit_timestamp(
258+
commit_hash, commit_timestamp =repo.get_git_commit_timestamp(
260259
path=str(testproject_path / "docs/page_with_tag.md"),
261260
is_first_commit=False,
262-
),
261+
)
262+
date_formats = repo.get_date_formats_for_timestamp(
263+
commit_timestamp,
263264
locale=plugin_config['locale'],
264265
add_spans=True,
265266
)
@@ -268,10 +269,7 @@ def validate_build(testproject_path, plugin_config: dict = {}):
268269
assert any(searches), "No correct revision date formats output was found"
269270

270271
if plugin_config.get("enable_creation_date"):
271-
commit_timestamp=repo.get_git_commit_timestamp(
272-
path=str(testproject_path / "docs/page_with_tag.md"),
273-
is_first_commit=True,
274-
)
272+
commit_hash, commit_timestamp = repo.get_git_commit_timestamp(path=str(testproject_path / "docs/page_with_tag.md"),is_first_commit=True,)
275273
assert commit_timestamp == 1500854705
276274
date_formats = repo.get_date_formats_for_timestamp(
277275
commit_timestamp=commit_timestamp,
@@ -283,7 +281,7 @@ def validate_build(testproject_path, plugin_config: dict = {}):
283281
assert any(searches), "No correct creation date formats output was found"
284282

285283
if os.path.exists(str(testproject_path / "docs/subfolder/page_with_renamed.md")):
286-
commit_timestamp=repo.get_git_commit_timestamp(
284+
commit_hash, commit_timestamp=repo.get_git_commit_timestamp(
287285
path=str(testproject_path / "docs/subfolder/page_with_renamed.md"),
288286
is_first_commit=True
289287
)

0 commit comments

Comments
 (0)