Skip to content

Commit 8e7cad1

Browse files
authored
Merge pull request timvink#162 from timvink/99-add-ability-to-show-tagcommitdirty
Add git hash and git tag information
2 parents db0c72c + 420de89 commit 8e7cad1

File tree

6 files changed

+79
-31
lines changed

6 files changed

+79
-31
lines changed

README.md

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,18 +7,12 @@
77

88
# mkdocs-git-revision-date-localized-plugin
99

10-
[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).
10+
[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. Works with [`mkdocs-material`](https://squidfunk.github.io/mkdocs-material/), see [adding a git repository](https://squidfunk.github.io/mkdocs-material/setup/adding-a-git-repository/).
1111

1212
![demo](https://github.com/timvink/mkdocs-git-revision-date-localized-plugin/raw/master/demo_screencast.gif)
1313

1414
(*Example when used together with the [mkdocs-material](https://github.com/squidfunk/mkdocs-material) theme*)
1515

16-
Other related MkDocs plugins:
17-
18-
- [mkdocs-git-authors-plugin](https://github.com/timvink/mkdocs-git-authors-plugin) for displaying the authors from git
19-
- [mkdocs-git-committers-plugin](https://github.com/byrnereese/mkdocs-git-committers-plugin) for displaying authors' github user profiles
20-
- [mkdocs-document-dates](https://github.com/jaywhj/mkdocs-document-dates) for displaying dates based on file creation and modification dates.
21-
2216
## Setup
2317

2418
Install the plugin using `pip3` with the following command:
@@ -69,3 +63,10 @@ See [timvink.github.io/mkdocs-git-revision-date-localized-plugin](https://timvin
6963
## Contributing
7064

7165
Contributions are very welcome! Please read [CONTRIBUTING.md](https://github.com/timvink/mkdocs-git-revision-date-localized-plugin/blob/master/CONTRIBUTING.md) before putting in any work.
66+
67+
## Related MkDocs plugins:
68+
69+
- [mkdocs-git-authors-plugin](https://github.com/timvink/mkdocs-git-authors-plugin) for displaying the authors from git
70+
- [mkdocs-git-committers-plugin-2](https://github.com/ojacques/mkdocs-git-committers-plugin-2) for displaying authors' github user profiles
71+
- [mkdocs-document-dates](https://github.com/jaywhj/mkdocs-document-dates) for displaying dates based on file creation and modification dates.
72+
- Initial fork from [mkdocs-git-revision-date-plugin](https://github.com/zhaoterryy/mkdocs-git-revision-date-plugin).

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:

mkdocs.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,8 @@ markdown_extensions:
6060
- pymdownx.tabbed:
6161
alternate_style: true
6262
- pymdownx.emoji:
63-
emoji_index: !!python/name:materialx.emoji.twemoji
64-
emoji_generator: !!python/name:materialx.emoji.to_svg
63+
emoji_index: !!python/name:material.extensions.emoji.twemoji
64+
emoji_generator: !!python/name:material.extensions.emoji.to_svg
6565
options:
6666
custom_icons:
6767
- site/overrides/.icons

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: 37 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,8 @@ 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+
if not any(commit_hash.startswith(x) for x in self.ignored_commits):
123124
break
124125
else:
125126
n_ignored_commits += 1
@@ -195,7 +196,7 @@ def get_git_commit_timestamp(
195196
msg += f" (ignored {n_ignored_commits} commits)"
196197
log(msg)
197198

198-
return int(commit_timestamp)
199+
return commit_hash, int(commit_timestamp)
199200

200201
def get_date_formats_for_timestamp(
201202
self,
@@ -261,3 +262,33 @@ def parse_git_ignore_revs(filename: str) -> List[str]:
261262
logger.error(f"An error occurred while reading the file {filename}: {e}")
262263

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

tests/test_builds.py

Lines changed: 7 additions & 9 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
)
@@ -303,7 +301,7 @@ def validate_mkdocs_file(temp_path: str, mkdocs_yml_file: str):
303301
)
304302
setup_commit_history(testproject_path)
305303
result = build_docs_setup(testproject_path)
306-
assert result.exit_code == 0, "'mkdocs build' command failed"
304+
assert result.exit_code == 0, f"'mkdocs build' command failed with output:\n{result.stdout}"
307305

308306
# validate build with locale retrieved from mkdocs config file
309307
validate_build(

0 commit comments

Comments
 (0)