mkdocs-document-dates 2.0.0__tar.gz → 2.1.8__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. {mkdocs_document_dates-2.0.0 → mkdocs_document_dates-2.1.8}/LICENSE +0 -1
  2. mkdocs_document_dates-2.1.8/PKG-INFO +160 -0
  3. mkdocs_document_dates-2.1.8/README.md +137 -0
  4. mkdocs_document_dates-2.1.8/mkdocs_document_dates/__init__.py +6 -0
  5. mkdocs_document_dates-2.1.8/mkdocs_document_dates/cache_manager.py +231 -0
  6. mkdocs_document_dates-2.1.8/mkdocs_document_dates/hooks/pre-commit +16 -0
  7. mkdocs_document_dates-2.1.8/mkdocs_document_dates/hooks_installer.py +126 -0
  8. mkdocs_document_dates-2.1.8/mkdocs_document_dates/plugin.py +522 -0
  9. mkdocs_document_dates-2.1.8/mkdocs_document_dates/static/config/user.config.css +73 -0
  10. mkdocs_document_dates-2.1.8/mkdocs_document_dates/static/config/user.config.js +45 -0
  11. mkdocs_document_dates-2.1.8/mkdocs_document_dates/static/core/core.css +98 -0
  12. mkdocs_document_dates-2.1.8/mkdocs_document_dates/static/core/core.js +165 -0
  13. mkdocs_document_dates-2.1.8/mkdocs_document_dates/static/languages/ar.json +20 -0
  14. mkdocs_document_dates-2.1.8/mkdocs_document_dates/static/languages/de.json +20 -0
  15. mkdocs_document_dates-2.1.8/mkdocs_document_dates/static/languages/en.json +20 -0
  16. mkdocs_document_dates-2.1.8/mkdocs_document_dates/static/languages/es.json +20 -0
  17. mkdocs_document_dates-2.1.8/mkdocs_document_dates/static/languages/fr.json +20 -0
  18. mkdocs_document_dates-2.1.8/mkdocs_document_dates/static/languages/ja.json +20 -0
  19. mkdocs_document_dates-2.1.8/mkdocs_document_dates/static/languages/ko.json +20 -0
  20. mkdocs_document_dates-2.1.8/mkdocs_document_dates/static/languages/ru.json +20 -0
  21. mkdocs_document_dates-2.1.8/mkdocs_document_dates/static/languages/zh.json +20 -0
  22. mkdocs_document_dates-2.1.8/mkdocs_document_dates/static/languages/zh_tw.json +20 -0
  23. mkdocs_document_dates-2.1.8/mkdocs_document_dates/static/tippy/backdrop.css +1 -0
  24. mkdocs_document_dates-2.1.8/mkdocs_document_dates/static/tippy/light.css +1 -0
  25. mkdocs_document_dates-2.1.8/mkdocs_document_dates/static/tippy/material.css +1 -0
  26. mkdocs_document_dates-2.1.8/mkdocs_document_dates/static/tippy/popper.min.js +6 -0
  27. mkdocs_document_dates-2.1.8/mkdocs_document_dates/static/tippy/scale.css +1 -0
  28. mkdocs_document_dates-2.1.8/mkdocs_document_dates/static/tippy/shift-away.css +1 -0
  29. mkdocs_document_dates-2.1.8/mkdocs_document_dates/static/tippy/tippy.css +1 -0
  30. mkdocs_document_dates-2.1.8/mkdocs_document_dates/static/tippy/tippy.umd.min.js +2 -0
  31. mkdocs_document_dates-2.1.8/mkdocs_document_dates.egg-info/PKG-INFO +160 -0
  32. mkdocs_document_dates-2.1.8/mkdocs_document_dates.egg-info/SOURCES.txt +36 -0
  33. mkdocs_document_dates-2.1.8/setup.py +75 -0
  34. mkdocs_document_dates-2.0.0/PKG-INFO +0 -121
  35. mkdocs_document_dates-2.0.0/README.md +0 -99
  36. mkdocs_document_dates-2.0.0/mkdocs_document_dates/__init__.py +0 -11
  37. mkdocs_document_dates-2.0.0/mkdocs_document_dates/hooks/pre-commit +0 -93
  38. mkdocs_document_dates-2.0.0/mkdocs_document_dates/hooks_installer.py +0 -87
  39. mkdocs_document_dates-2.0.0/mkdocs_document_dates/lang/__init__.py +0 -23
  40. mkdocs_document_dates-2.0.0/mkdocs_document_dates/lang/ar.py +0 -18
  41. mkdocs_document_dates-2.0.0/mkdocs_document_dates/lang/de.py +0 -18
  42. mkdocs_document_dates-2.0.0/mkdocs_document_dates/lang/en.py +0 -18
  43. mkdocs_document_dates-2.0.0/mkdocs_document_dates/lang/es.py +0 -18
  44. mkdocs_document_dates-2.0.0/mkdocs_document_dates/lang/fr.py +0 -18
  45. mkdocs_document_dates-2.0.0/mkdocs_document_dates/lang/ja.py +0 -18
  46. mkdocs_document_dates-2.0.0/mkdocs_document_dates/lang/ko.py +0 -18
  47. mkdocs_document_dates-2.0.0/mkdocs_document_dates/lang/ru.py +0 -18
  48. mkdocs_document_dates-2.0.0/mkdocs_document_dates/lang/zh.py +0 -18
  49. mkdocs_document_dates-2.0.0/mkdocs_document_dates/lang/zh_tw.py +0 -18
  50. mkdocs_document_dates-2.0.0/mkdocs_document_dates/plugin.py +0 -241
  51. mkdocs_document_dates-2.0.0/mkdocs_document_dates/styles.py +0 -28
  52. mkdocs_document_dates-2.0.0/mkdocs_document_dates.egg-info/PKG-INFO +0 -121
  53. mkdocs_document_dates-2.0.0/mkdocs_document_dates.egg-info/SOURCES.txt +0 -25
  54. mkdocs_document_dates-2.0.0/setup.py +0 -52
  55. {mkdocs_document_dates-2.0.0 → mkdocs_document_dates-2.1.8}/mkdocs_document_dates.egg-info/dependency_links.txt +0 -0
  56. {mkdocs_document_dates-2.0.0 → mkdocs_document_dates-2.1.8}/mkdocs_document_dates.egg-info/entry_points.txt +0 -0
  57. {mkdocs_document_dates-2.0.0 → mkdocs_document_dates-2.1.8}/mkdocs_document_dates.egg-info/requires.txt +0 -0
  58. {mkdocs_document_dates-2.0.0 → mkdocs_document_dates-2.1.8}/mkdocs_document_dates.egg-info/top_level.txt +0 -0
  59. {mkdocs_document_dates-2.0.0 → mkdocs_document_dates-2.1.8}/setup.cfg +0 -0
@@ -9,4 +9,3 @@ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
9
  copies of the Software, and to permit persons to whom the Software is
10
10
  furnished to do so, subject to the following conditions:
11
11
 
12
- [... 后续 MIT 许可证内容 ...]
@@ -0,0 +1,160 @@
1
+ Metadata-Version: 2.4
2
+ Name: mkdocs-document-dates
3
+ Version: 2.1.8
4
+ Summary: An easy-to-use, lightweight MkDocs plugin for displaying the exact creation time, last modification time and author info of markdown documents.
5
+ Home-page: https://github.com/jaywhj/mkdocs-document-dates
6
+ Author: Aaron Wang
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Operating System :: OS Independent
10
+ Requires-Python: >=3.7
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: mkdocs>=1.0.0
14
+ Dynamic: author
15
+ Dynamic: classifier
16
+ Dynamic: description
17
+ Dynamic: description-content-type
18
+ Dynamic: home-page
19
+ Dynamic: license-file
20
+ Dynamic: requires-dist
21
+ Dynamic: requires-python
22
+ Dynamic: summary
23
+
24
+ # mkdocs-document-dates
25
+
26
+ English | [简体中文](README_zh.md)
27
+
28
+
29
+
30
+ An easy-to-use, lightweight MkDocs plugin for displaying the <mark>exact</mark> creation time, last modification time and author info of markdown documents.
31
+
32
+ ## Features
33
+
34
+ - Work in any environment, for Git-less environments, CI/CD environments (e.g. GitHub Actions), one-person collaboration, multi-person collaboration, etc
35
+ - Support for manually specifying time and author info in `Front Matter`
36
+ - Support for multiple time formats (date, datetime, timeago)
37
+ - Support for document exclusion mode
38
+ - Flexible display position (top or bottom)
39
+ - Elegant styling (fully customizable)
40
+ - Supports Tooltip Hover Tips
41
+ - Intelligent repositioning to always float optimally in view
42
+ - Supports automatic theme switching following Material's light/dark color scheme
43
+ - Support for customizing themes, styles, animations
44
+ - Compatible with mouse, keyboard and **touch** (mobile) to trigger hover
45
+ - Multi-language support, cross-platform support (Windows, macOS, Linux)
46
+
47
+ ## Showcases
48
+
49
+ ![render](render.gif)
50
+
51
+ ## Installation
52
+
53
+ ```bash
54
+ pip install mkdocs-document-dates
55
+ ```
56
+
57
+ ## Configuration
58
+
59
+ Just add the plugin to your `mkdocs.yml`:
60
+
61
+ ```yaml
62
+ plugins:
63
+ - document-dates
64
+ ```
65
+
66
+ Or, personalize the configuration:
67
+
68
+ ```yaml
69
+ plugins:
70
+ - document-dates:
71
+ position: top # Display position: top (after title) bottom (end of document), default: bottom
72
+ type: date # Date type: date datetime timeago, default: date
73
+ locale: en # Localization: zh zh_tw en es fr de ar ja ko ru, default: en
74
+ date_format: '%Y-%m-%d' # Date format, Supports all Python datetime format strings, e.g., %Y-%m-%d, %b %d, %Y, etc
75
+ time_format: '%H:%M:%S' # Time format (valid only if type=datetime)
76
+ exclude: # List of excluded files
77
+ - temp.md # Exclude specific file
78
+ - private/* # Exclude all files in private directory, including subdirectories
79
+ - drafts/*.md # Exclude all markdown files in the current directory drafts, but not subdirectories
80
+
81
+ show_author: true # Whether to display author: true false, default: true
82
+
83
+ ```
84
+
85
+ ## Specify time manually
86
+
87
+ The plugin will automatically get the exact time of the document, will automatically cache the creation time, but of course, you can also specify it manually in `Front Matter`
88
+
89
+ Priority: `Front Matter` > `Cache Files` > `File System Timestamps`
90
+
91
+ ```yaml
92
+ ---
93
+ created: 2023-01-01
94
+ modified: 2025-02-23
95
+ ---
96
+
97
+ # Document Title
98
+ ```
99
+
100
+ - `created` can be replaced with: `created, date, creation`
101
+ - `modified` can be replaced with: `modified, updated, last_modified, last_updated`
102
+
103
+ ## Specify author manually
104
+
105
+ The plugin will automatically get the author of the document, will parse the email and make a link, also you can specify it manually in `Front Matter`
106
+
107
+ Priority: `Front Matter` > `Git Author Info` > `PC Username`
108
+
109
+ ```yaml
110
+ ---
111
+ author: any-name
112
+ email: e-name@gmail.com
113
+ ---
114
+
115
+ # Document Title
116
+ ```
117
+
118
+ - `author` can be replaced with: `author, name`
119
+ - `email` can be replaced with: `email, mail`
120
+
121
+ ## Customization
122
+
123
+ The plugin supports deep customization, such as icon style, font style, theme color, animation type, dividing line, etc. All of it can be customized by modifying the code in the corresponding file (I've already written the code and comments, you just need to turn on the switch and change the value):
124
+
125
+ - Style & Theme: `docs/assets/document_dates/user.config.css`
126
+ - Properties & Animations: `docs/assets/document_dates/user.config.js`
127
+ - Localized languages: `docs/assets/document_dates/languages/` , refer to the template file `en.json` for any additions or modifications
128
+
129
+ ## Other Tips
130
+
131
+ - In order to get the exact creation time, a separate cache file is used to store the creation time of the file, located in the doc folder (hidden by default), please don't delete it:
132
+ - `docs/.dates_cache.jsonl`, cache file
133
+ - `docs/.gitattributes`, merge mechanism for cache file in case of multi-person collaboration
134
+ - The Git Hooks mechanism is used to automatically trigger the storing of the cache (every time executes a git commit), and the cached file is automatically committed along with it. In addition, the installation of Git Hooks is automatically triggered when the plugin is installed, without any manual intervention!
135
+
136
+ <br />
137
+
138
+ ## Development Stories (Optional)
139
+
140
+ A dispensable, insignificant little plug-in, friends who have time can take a look \^\_\^
141
+
142
+ - **Origin**:
143
+ - Because [mkdocs-git-revision-date-localized-plugin](https://github.com/timvink/mkdocs-git-revision-date-localized-plugin), a great project. When I used it at the end of 2024, I found that I couldn't use it locally because my mkdocs documentation was not included in git management, then I don't understand why not read the file system time, but to use the git time, and raised an issue to the author, but didn't get a reply for about a week (the author had a reply later, nice guy, I guess he was busy at the time), and then I thought, there is nothing to do during the Chinese New Year, and now AI is so hot, why not with the help of the AI try it out for myself, it was born, born in February 2025
144
+ - **Iteration**:
145
+ - After development, I understood why not use filesystem time, because files will be rebuilt when they go through git checkout or clone, resulting in the loss of original timestamp information, and there are many solutions:
146
+ - Method 1: Use the last git commit time as the last update time, and the first git commit time as the creation (there is a margin of error, but it's acceptable), mkdocs-git-revision-date-localized-plugin does this
147
+ - Method 2: You can cache the original time, and then read the cache subsequently. The cache can be in Front Matter of the source document or in a separate file, I chose the latter. Storing in Front Matter makes sense and is simple, but this will modify the source content of the document, although it doesn't have any impact on the body, but I still want to ensure the originality of the data!
148
+ - **Difficulty**:
149
+ 1. When to read and store original time? This is just a plugin for mkdocs, with very limited access and permissions, mkdocs provides only build and serve, so in case a user commits directly without executing build or serve (e.g., when using a CI/CD build system), then you won't be able to retrieve the time information of the file, not to mention caching it!
150
+ - Let's take a straight shot: the Git Hooks mechanism was found, prompted by the AI, which can trigger a custom script when a specific action occurs, such as every time commit is performed
151
+ 2. How can I ensure that a single cache file does not conflict when collaborating with multi-person?
152
+ - My solution: use JSONL (JSON Lines) instead of JSON, and with the merge strategy 'merge=union'
153
+ - **Improve**:
154
+ - Since it has been re-developed, it will be designed in the direction of **excellent products**, and the pursuit of the ultimate **ease of use, simplicity and personalization**
155
+ - Ease of use: don't let users do things manually if you can, e.g., auto-install Git Hooks, auto-cache, auto-commit, provide customized templates, etc
156
+ - Simplicity: no unnecessary configurations, the less the simpler, e.g. git account information, repo information, etc., are not required
157
+ - Personalization: almost everything can be customized, whether it's icons, styles, themes, or features, it's all fully customizable
158
+ - In addition, it has good compatibility and extensibility, and works well in WIN7, mobile devices, old Safari, etc
159
+ - **The Last Secret**:
160
+ - I'm not a programmer, my main job is marketing, can you believe it? (Feel free to leave a comment)
@@ -0,0 +1,137 @@
1
+ # mkdocs-document-dates
2
+
3
+ English | [简体中文](README_zh.md)
4
+
5
+
6
+
7
+ An easy-to-use, lightweight MkDocs plugin for displaying the <mark>exact</mark> creation time, last modification time and author info of markdown documents.
8
+
9
+ ## Features
10
+
11
+ - Work in any environment, for Git-less environments, CI/CD environments (e.g. GitHub Actions), one-person collaboration, multi-person collaboration, etc
12
+ - Support for manually specifying time and author info in `Front Matter`
13
+ - Support for multiple time formats (date, datetime, timeago)
14
+ - Support for document exclusion mode
15
+ - Flexible display position (top or bottom)
16
+ - Elegant styling (fully customizable)
17
+ - Supports Tooltip Hover Tips
18
+ - Intelligent repositioning to always float optimally in view
19
+ - Supports automatic theme switching following Material's light/dark color scheme
20
+ - Support for customizing themes, styles, animations
21
+ - Compatible with mouse, keyboard and **touch** (mobile) to trigger hover
22
+ - Multi-language support, cross-platform support (Windows, macOS, Linux)
23
+
24
+ ## Showcases
25
+
26
+ ![render](render.gif)
27
+
28
+ ## Installation
29
+
30
+ ```bash
31
+ pip install mkdocs-document-dates
32
+ ```
33
+
34
+ ## Configuration
35
+
36
+ Just add the plugin to your `mkdocs.yml`:
37
+
38
+ ```yaml
39
+ plugins:
40
+ - document-dates
41
+ ```
42
+
43
+ Or, personalize the configuration:
44
+
45
+ ```yaml
46
+ plugins:
47
+ - document-dates:
48
+ position: top # Display position: top (after title) bottom (end of document), default: bottom
49
+ type: date # Date type: date datetime timeago, default: date
50
+ locale: en # Localization: zh zh_tw en es fr de ar ja ko ru, default: en
51
+ date_format: '%Y-%m-%d' # Date format, Supports all Python datetime format strings, e.g., %Y-%m-%d, %b %d, %Y, etc
52
+ time_format: '%H:%M:%S' # Time format (valid only if type=datetime)
53
+ exclude: # List of excluded files
54
+ - temp.md # Exclude specific file
55
+ - private/* # Exclude all files in private directory, including subdirectories
56
+ - drafts/*.md # Exclude all markdown files in the current directory drafts, but not subdirectories
57
+
58
+ show_author: true # Whether to display author: true false, default: true
59
+
60
+ ```
61
+
62
+ ## Specify time manually
63
+
64
+ The plugin will automatically get the exact time of the document, will automatically cache the creation time, but of course, you can also specify it manually in `Front Matter`
65
+
66
+ Priority: `Front Matter` > `Cache Files` > `File System Timestamps`
67
+
68
+ ```yaml
69
+ ---
70
+ created: 2023-01-01
71
+ modified: 2025-02-23
72
+ ---
73
+
74
+ # Document Title
75
+ ```
76
+
77
+ - `created` can be replaced with: `created, date, creation`
78
+ - `modified` can be replaced with: `modified, updated, last_modified, last_updated`
79
+
80
+ ## Specify author manually
81
+
82
+ The plugin will automatically get the author of the document, will parse the email and make a link, also you can specify it manually in `Front Matter`
83
+
84
+ Priority: `Front Matter` > `Git Author Info` > `PC Username`
85
+
86
+ ```yaml
87
+ ---
88
+ author: any-name
89
+ email: e-name@gmail.com
90
+ ---
91
+
92
+ # Document Title
93
+ ```
94
+
95
+ - `author` can be replaced with: `author, name`
96
+ - `email` can be replaced with: `email, mail`
97
+
98
+ ## Customization
99
+
100
+ The plugin supports deep customization, such as icon style, font style, theme color, animation type, dividing line, etc. All of it can be customized by modifying the code in the corresponding file (I've already written the code and comments, you just need to turn on the switch and change the value):
101
+
102
+ - Style & Theme: `docs/assets/document_dates/user.config.css`
103
+ - Properties & Animations: `docs/assets/document_dates/user.config.js`
104
+ - Localized languages: `docs/assets/document_dates/languages/` , refer to the template file `en.json` for any additions or modifications
105
+
106
+ ## Other Tips
107
+
108
+ - In order to get the exact creation time, a separate cache file is used to store the creation time of the file, located in the doc folder (hidden by default), please don't delete it:
109
+ - `docs/.dates_cache.jsonl`, cache file
110
+ - `docs/.gitattributes`, merge mechanism for cache file in case of multi-person collaboration
111
+ - The Git Hooks mechanism is used to automatically trigger the storing of the cache (every time executes a git commit), and the cached file is automatically committed along with it. In addition, the installation of Git Hooks is automatically triggered when the plugin is installed, without any manual intervention!
112
+
113
+ <br />
114
+
115
+ ## Development Stories (Optional)
116
+
117
+ A dispensable, insignificant little plug-in, friends who have time can take a look \^\_\^
118
+
119
+ - **Origin**:
120
+ - Because [mkdocs-git-revision-date-localized-plugin](https://github.com/timvink/mkdocs-git-revision-date-localized-plugin), a great project. When I used it at the end of 2024, I found that I couldn't use it locally because my mkdocs documentation was not included in git management, then I don't understand why not read the file system time, but to use the git time, and raised an issue to the author, but didn't get a reply for about a week (the author had a reply later, nice guy, I guess he was busy at the time), and then I thought, there is nothing to do during the Chinese New Year, and now AI is so hot, why not with the help of the AI try it out for myself, it was born, born in February 2025
121
+ - **Iteration**:
122
+ - After development, I understood why not use filesystem time, because files will be rebuilt when they go through git checkout or clone, resulting in the loss of original timestamp information, and there are many solutions:
123
+ - Method 1: Use the last git commit time as the last update time, and the first git commit time as the creation (there is a margin of error, but it's acceptable), mkdocs-git-revision-date-localized-plugin does this
124
+ - Method 2: You can cache the original time, and then read the cache subsequently. The cache can be in Front Matter of the source document or in a separate file, I chose the latter. Storing in Front Matter makes sense and is simple, but this will modify the source content of the document, although it doesn't have any impact on the body, but I still want to ensure the originality of the data!
125
+ - **Difficulty**:
126
+ 1. When to read and store original time? This is just a plugin for mkdocs, with very limited access and permissions, mkdocs provides only build and serve, so in case a user commits directly without executing build or serve (e.g., when using a CI/CD build system), then you won't be able to retrieve the time information of the file, not to mention caching it!
127
+ - Let's take a straight shot: the Git Hooks mechanism was found, prompted by the AI, which can trigger a custom script when a specific action occurs, such as every time commit is performed
128
+ 2. How can I ensure that a single cache file does not conflict when collaborating with multi-person?
129
+ - My solution: use JSONL (JSON Lines) instead of JSON, and with the merge strategy 'merge=union'
130
+ - **Improve**:
131
+ - Since it has been re-developed, it will be designed in the direction of **excellent products**, and the pursuit of the ultimate **ease of use, simplicity and personalization**
132
+ - Ease of use: don't let users do things manually if you can, e.g., auto-install Git Hooks, auto-cache, auto-commit, provide customized templates, etc
133
+ - Simplicity: no unnecessary configurations, the less the simpler, e.g. git account information, repo information, etc., are not required
134
+ - Personalization: almost everything can be customized, whether it's icons, styles, themes, or features, it's all fully customizable
135
+ - In addition, it has good compatibility and extensibility, and works well in WIN7, mobile devices, old Safari, etc
136
+ - **The Last Secret**:
137
+ - I'm not a programmer, my main job is marketing, can you believe it? (Feel free to leave a comment)
@@ -0,0 +1,6 @@
1
+ """MkDocs Document Dates Plugin."""
2
+
3
+ from .hooks_installer import install
4
+
5
+ # 在包被导入时自动执行 hooks 安装
6
+ install()
@@ -0,0 +1,231 @@
1
+ import os
2
+ import sys
3
+ import json
4
+ import logging
5
+ import platform
6
+ import subprocess
7
+ from datetime import datetime
8
+ from pathlib import Path
9
+
10
+ # 配置日志等级 (INFO WARNING ERROR)
11
+ logging.basicConfig(
12
+ level=logging.WARNING,
13
+ format='%(levelname)s: %(message)s'
14
+ )
15
+
16
+ def find_mkdocs_projects():
17
+ try:
18
+ git_root = Path(subprocess.check_output(
19
+ ['git', 'rev-parse', '--show-toplevel'],
20
+ text=True, encoding='utf-8'
21
+ ).strip())
22
+
23
+ projects = []
24
+ # 遍历 git_root 及子目录, 寻找 mkdocs.yml 文件
25
+ for config_file in git_root.rglob('mkdocs.y*ml'):
26
+ if config_file.name.lower() in ('mkdocs.yml', 'mkdocs.yaml'):
27
+ projects.append(config_file.parent)
28
+
29
+ if not projects:
30
+ logging.info("No MkDocs projects found in the repository")
31
+ return projects
32
+ except subprocess.CalledProcessError as e:
33
+ logging.error(f"Failed to find the Git repository root: {e}")
34
+ return []
35
+ except Exception as e:
36
+ logging.error(f"Unexpected error while searching for MkDocs projects: {e}")
37
+ return []
38
+
39
+ def get_file_creation_time(file_path):
40
+ try:
41
+ stat = os.stat(file_path)
42
+ system = platform.system().lower()
43
+ if system.startswith('win'): # Windows
44
+ return datetime.fromtimestamp(stat.st_ctime)
45
+ elif system == 'darwin': # macOS
46
+ try:
47
+ return datetime.fromtimestamp(stat.st_birthtime)
48
+ except AttributeError:
49
+ return datetime.fromtimestamp(stat.st_ctime)
50
+ else: # Linux, 没有创建时间,使用修改时间
51
+ return datetime.fromtimestamp(stat.st_mtime)
52
+ except (OSError, ValueError) as e:
53
+ logging.error(f"Failed to get file creation time for {file_path}: {e}")
54
+ return datetime.now()
55
+
56
+ def get_git_first_commit_time(file_path):
57
+ try:
58
+ # git log --reverse --format="%aI" --date=iso -- {file_path} | head -n 1
59
+ result = subprocess.run(['git', 'log', '--reverse', '--format=%aI', '--', file_path], capture_output=True, text=True)
60
+ if result.returncode == 0:
61
+ commits = result.stdout.strip().split('\n')
62
+ if commits and commits[0]:
63
+ return datetime.fromisoformat(commits[0]).replace(tzinfo=None)
64
+ except Exception as e:
65
+ logging.info(f"Error getting git first commit time for {file_path}: {e}")
66
+ return None
67
+
68
+ def setup_gitattributes(docs_dir):
69
+ gitattributes_path = docs_dir / '.gitattributes'
70
+ union_config_line = ".dates_cache.jsonl merge=union"
71
+ updated = False
72
+
73
+ if gitattributes_path.exists():
74
+ with open(gitattributes_path, 'r', encoding='utf-8') as f:
75
+ content = f.read()
76
+
77
+ if union_config_line not in content:
78
+ with open(gitattributes_path, 'a', encoding='utf-8') as f:
79
+ f.write(f"\n{union_config_line}\n")
80
+ updated = True
81
+ else:
82
+ with open(gitattributes_path, 'w', encoding='utf-8') as f:
83
+ f.write(f"{union_config_line}\n")
84
+ updated = True
85
+
86
+ if updated:
87
+ try:
88
+ subprocess.run(["git", "add", str(gitattributes_path)], check=True)
89
+ logging.info(f"Updated .gitattributes file: {gitattributes_path}")
90
+ except subprocess.CalledProcessError as e:
91
+ logging.error(f"Failed to add .gitattributes to git: {e}")
92
+
93
+ return updated
94
+
95
+ def read_json_cache(cache_file):
96
+ dates_cache = {}
97
+ if cache_file.exists():
98
+ try:
99
+ with open(cache_file, "r", encoding='utf-8') as f:
100
+ dates_cache = json.load(f)
101
+ except (IOError, json.JSONDecodeError) as e:
102
+ logging.error(f"Failed to read existing JSON cache file: {e}")
103
+ return dates_cache
104
+
105
+ def read_jsonl_cache(jsonl_file):
106
+ dates_cache = {}
107
+ if jsonl_file.exists():
108
+ try:
109
+ with open(jsonl_file, "r", encoding='utf-8') as f:
110
+ for line in f:
111
+ try:
112
+ entry = json.loads(line.strip())
113
+ if entry and isinstance(entry, dict) and len(entry) == 1:
114
+ file_path, file_info = next(iter(entry.items()))
115
+ dates_cache[file_path] = file_info
116
+ except (json.JSONDecodeError, StopIteration) as e:
117
+ logging.warning(f"Skipping invalid JSONL line: {e}")
118
+ except IOError as e:
119
+ logging.error(f"Failed to read existing JSONL cache file: {e}")
120
+ return dates_cache
121
+
122
+ def write_jsonl_cache(jsonl_file, dates_cache, tracked_files):
123
+ try:
124
+ # 使用临时文件写入,然后替换原文件,避免写入过程中的问题
125
+ temp_file = jsonl_file.with_suffix('.jsonl.tmp')
126
+ with open(temp_file, "w", encoding='utf-8') as f:
127
+ for file_path in tracked_files:
128
+ if file_path in dates_cache:
129
+ entry = {file_path: dates_cache[file_path]}
130
+ f.write(json.dumps(entry, ensure_ascii=False) + '\n')
131
+
132
+ # 替换原文件
133
+ temp_file.replace(jsonl_file)
134
+
135
+ # 将文件添加到git
136
+ subprocess.run(["git", "add", str(jsonl_file)], check=True)
137
+ logging.info(f"Successfully updated JSONL cache file: {jsonl_file}")
138
+ return True
139
+ except (IOError, json.JSONDecodeError) as e:
140
+ logging.error(f"Failed to write JSONL cache file {jsonl_file}: {e}")
141
+ return False
142
+ except subprocess.CalledProcessError as e:
143
+ logging.error(f"Failed to add JSONL cache file to git: {e}")
144
+ return False
145
+
146
+ def update_cache():
147
+ global_updated = False
148
+ for project_dir in find_mkdocs_projects():
149
+ project_updated = False
150
+
151
+ docs_dir = project_dir / 'docs'
152
+ if not docs_dir.exists():
153
+ logging.error(f"Document directory does not exist: {docs_dir}")
154
+ continue
155
+
156
+ # 设置.gitattributes文件
157
+ gitattributes_updated = setup_gitattributes(docs_dir)
158
+ if gitattributes_updated:
159
+ global_updated = True
160
+
161
+ try:
162
+ # 获取docs目录下已跟踪(tracked)的markdown文件
163
+ cmd = ["git", "ls-files", "*.md"]
164
+ result = subprocess.run(cmd, cwd=docs_dir, capture_output=True, text=True, check=True)
165
+ tracked_files = result.stdout.splitlines() if result.stdout else []
166
+
167
+ if not tracked_files:
168
+ logging.info(f"No tracked markdown files found in {docs_dir}")
169
+ continue
170
+
171
+ # 读取旧的JSON缓存文件(如果存在)
172
+ json_cache_file = docs_dir / '.dates_cache.json'
173
+ json_dates_cache = read_json_cache(json_cache_file)
174
+
175
+ # 读取新的JSONL缓存文件(如果存在)
176
+ jsonl_cache_file = docs_dir / '.dates_cache.jsonl'
177
+ jsonl_dates_cache = read_jsonl_cache(jsonl_cache_file)
178
+
179
+ # 根据 git已跟踪的文件来更新
180
+ for file_path in tracked_files:
181
+ try:
182
+ rel_path = file_path
183
+ full_path = docs_dir / rel_path
184
+
185
+ # 如果文件已在JSONL缓存中,跳过
186
+ if rel_path in jsonl_dates_cache:
187
+ continue
188
+
189
+ # 处理新文件或迁移旧JSON缓存
190
+ if rel_path in json_dates_cache:
191
+ jsonl_dates_cache[rel_path] = json_dates_cache[rel_path]
192
+ project_updated = True
193
+ elif full_path.exists():
194
+ created_time = get_file_creation_time(full_path)
195
+ if not jsonl_cache_file.exists() and not json_cache_file.exists():
196
+ git_time = get_git_first_commit_time(full_path)
197
+ if git_time is not None:
198
+ created_time = min(created_time, git_time)
199
+ jsonl_dates_cache[rel_path] = {
200
+ "created": created_time.isoformat()
201
+ }
202
+ project_updated = True
203
+ except Exception as e:
204
+ logging.error(f"Error processing file {file_path}: {e}")
205
+
206
+ # 标记删除不再跟踪的文件
207
+ files_to_remove = set(jsonl_dates_cache.keys()) - set(tracked_files)
208
+ if files_to_remove:
209
+ project_updated = True
210
+ logging.info(f"Removing {len(files_to_remove)} untracked files from cache")
211
+
212
+ # 如果有更新,写入JSONL缓存文件
213
+ if project_updated or not jsonl_cache_file.exists():
214
+ if write_jsonl_cache(jsonl_cache_file, jsonl_dates_cache, tracked_files):
215
+ global_updated = True
216
+ else:
217
+ logging.info(f"No updates needed for {jsonl_cache_file}")
218
+
219
+ except subprocess.CalledProcessError as e:
220
+ logging.error(f"Failed to execute git command: {e}")
221
+ continue
222
+
223
+ return global_updated
224
+
225
+
226
+ if __name__ == "__main__":
227
+ try:
228
+ update_cache()
229
+ except Exception as e:
230
+ logging.error(f"Hook execution failed: {e}")
231
+ sys.exit(1)
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env python3
2
+
3
+ import sys
4
+ import logging
5
+
6
+ try:
7
+ from mkdocs_document_dates.cache_manager import update_cache
8
+ except ImportError:
9
+ sys.exit(0)
10
+
11
+ if __name__ == "__main__":
12
+ try:
13
+ update_cache()
14
+ except Exception as e:
15
+ logging.error(f"Hook execution failed: {e}")
16
+ sys.exit(1)