0
# Git Operations & Date Formatting
1
2
Core utilities for extracting git commit timestamps, handling repository operations, and formatting dates in various localized formats. These functions form the foundation of the plugin's ability to retrieve and display git revision information.
3
4
## Capabilities
5
6
### Git Repository Operations
7
8
Core git operations for extracting commit information and handling repository state.
9
10
```python { .api }
11
class Util:
12
def __init__(self, config: Dict, mkdocs_dir: str):
13
"""
14
Initialize utility class for git operations.
15
16
Parameters:
17
- config (Dict): Plugin configuration dictionary
18
- mkdocs_dir (str): Path to MkDocs directory
19
"""
20
21
def get_git_commit_timestamp(self, path: str, is_first_commit: bool = False) -> Tuple[str, int]:
22
"""
23
Get git commit timestamp for a file.
24
25
Parameters:
26
- path (str): File path to get commit info for
27
- is_first_commit (bool): If True, get creation commit; if False, get latest commit
28
29
Returns:
30
Tuple[str, int]: (commit_hash, unix_timestamp)
31
"""
32
33
def get_tag_name_for_commit(self, commit_hash: str) -> str:
34
"""
35
Get git tag name for a specific commit.
36
37
Parameters:
38
- commit_hash (str): Git commit hash
39
40
Returns:
41
str: Tag name or empty string if no tag found
42
"""
43
```
44
45
**Usage:**
46
47
```python
48
from mkdocs_git_revision_date_localized_plugin.util import Util
49
50
# Initialize utility
51
config = {"timezone": "UTC", "enable_git_follow": True}
52
util = Util(config, "/path/to/mkdocs/dir")
53
54
# Get latest commit info
55
commit_hash, timestamp = util.get_git_commit_timestamp("/path/to/file.md")
56
57
# Get creation commit info
58
first_hash, first_timestamp = util.get_git_commit_timestamp("/path/to/file.md", is_first_commit=True)
59
60
# Get tag for commit
61
tag_name = util.get_tag_name_for_commit(commit_hash)
62
```
63
64
### Date Formatting Functions
65
66
Functions for converting timestamps to various localized date formats.
67
68
```python { .api }
69
def get_date_formats(unix_timestamp: float, locale: str = "en", time_zone: str = "UTC", custom_format: str = "%d. %B %Y") -> Dict[str, Any]:
70
"""
71
Calculate different date formats for a timestamp.
72
73
Parameters:
74
- unix_timestamp (float): Unix timestamp in seconds
75
- locale (str): Locale code for language (e.g., "en", "fr", "de")
76
- time_zone (str): Timezone name (e.g., "UTC", "America/New_York")
77
- custom_format (str): strftime format for custom type
78
79
Returns:
80
Dict[str, Any]: Dictionary with date format keys and formatted strings
81
"""
82
83
def strftime_to_babel_format(fmt: str) -> str:
84
"""
85
Convert strftime format string to Babel format pattern.
86
87
Parameters:
88
- fmt (str): strftime format string
89
90
Returns:
91
str: Babel format pattern
92
"""
93
```
94
95
**Usage:**
96
97
```python
98
from mkdocs_git_revision_date_localized_plugin.dates import get_date_formats, strftime_to_babel_format
99
import time
100
101
# Get current timestamp
102
timestamp = time.time()
103
104
# Format in different locales
105
english_dates = get_date_formats(timestamp, locale="en", time_zone="UTC")
106
french_dates = get_date_formats(timestamp, locale="fr", time_zone="Europe/Paris")
107
108
# Available format types
109
print(english_dates["date"]) # "January 15, 2023"
110
print(english_dates["datetime"]) # "January 15, 2023 14:30:25"
111
print(english_dates["iso_date"]) # "2023-01-15"
112
print(english_dates["iso_datetime"]) # "2023-01-15 14:30:25"
113
print(english_dates["timeago"]) # '<span class="timeago" datetime="2023-01-15T14:30:25+00:00" locale="en"></span>'
114
print(english_dates["custom"]) # "15. January 2023"
115
116
# Convert strftime to Babel format
117
babel_format = strftime_to_babel_format("%Y-%m-%d %H:%M") # Returns "yyyy-MM-dd HH:mm"
118
```
119
120
### Utility Date Formatting Methods
121
122
Instance methods for formatting dates with plugin configuration context.
123
124
```python { .api }
125
class Util:
126
def get_date_formats_for_timestamp(self, commit_timestamp: int, locale: str, add_spans: bool = True) -> Dict[str, str]:
127
"""
128
Get localized date formats for a timestamp using plugin configuration.
129
130
Parameters:
131
- commit_timestamp (int): Unix timestamp
132
- locale (str): Locale code
133
- add_spans (bool): Whether to wrap dates in HTML spans
134
135
Returns:
136
Dict[str, str]: Formatted date strings by type
137
"""
138
139
@staticmethod
140
def add_spans(date_formats: Dict[str, str]) -> Dict[str, str]:
141
"""
142
Wrap date strings in HTML spans with CSS classes.
143
144
Parameters:
145
- date_formats (Dict[str, str]): Date formats dictionary
146
147
Returns:
148
Dict[str, str]: Date formats wrapped in HTML spans
149
"""
150
```
151
152
**Usage:**
153
154
```python
155
# Using Util instance methods
156
util = Util(config, mkdocs_dir)
157
commit_hash, timestamp = util.get_git_commit_timestamp("file.md")
158
159
# Get formatted dates with spans
160
dates_with_spans = util.get_date_formats_for_timestamp(timestamp, "en", add_spans=True)
161
162
# Get raw date strings without spans
163
raw_dates = util.get_date_formats_for_timestamp(timestamp, "en", add_spans=False)
164
```
165
166
### Git Ignore Revisions
167
168
Utility for parsing and handling ignored commit lists.
169
170
```python { .api }
171
class Util:
172
@staticmethod
173
def parse_git_ignore_revs(filename: str) -> List[str]:
174
"""
175
Parse git blame ignore revisions file.
176
177
Parameters:
178
- filename (str): Path to ignore revisions file
179
180
Returns:
181
List[str]: List of commit hashes to ignore
182
"""
183
```
184
185
**Usage:**
186
187
```python
188
# Parse ignore file (same format as git's blame.ignoreRevsFile)
189
ignored_commits = Util.parse_git_ignore_revs(".git-blame-ignore-revs")
190
```
191
192
## Date Format Reference
193
194
The date formatting functions return dictionaries with these keys:
195
196
- **date**: Localized long date (e.g., "15 janvier 2023" in French)
197
- **datetime**: Date with time (e.g., "15 janvier 2023 14:30:25")
198
- **datetime-timezone**: Date with time and timezone (e.g., "15 janvier 2023 14:30:25 CET")
199
- **iso_date**: ISO date format (e.g., "2023-01-15")
200
- **iso_datetime**: ISO datetime format (e.g., "2023-01-15 14:30:25")
201
- **timeago**: HTML span for timeago.js (e.g., `<span class="timeago" datetime="..." locale="fr"></span>`)
202
- **custom**: Custom format using provided format string
203
204
## Error Handling
205
206
The git operations handle various error conditions:
207
208
- **InvalidGitRepositoryError**: When directory is not a git repository
209
- **GitCommandError**: When git commands fail
210
- **GitCommandNotFound**: When git is not installed
211
- **NoSuchPathError**: When file path doesn't exist
212
213
All errors can be handled gracefully using the `fallback_to_build_date` configuration option.