Skip to content

Commit 43f6de2

Browse files
committed
feat: update plugin
1 parent 3766c90 commit 43f6de2

File tree

1 file changed

+30
-13
lines changed

1 file changed

+30
-13
lines changed

hooks/committer.py

+30-13
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
"""
2-
hooks/committer.py – 使用源码文件 git 时间增量缓存
2+
hooks/committer.py – 使用源码文件 git 时间增量缓存(时间戳版)
33
支持 URL 编码字符(Two%20Sum → Two Sum)
44
"""
55

@@ -26,7 +26,13 @@ def _log(msg: str, level: str = "INFO"):
2626
print(f"{_now()} [{level}] {msg}")
2727

2828

29-
# ───────────────────────── 工具函数 ───────────────────────── #
29+
# ───────────────────────── 时间工具 ───────────────────────── #
30+
def _ts(dt: datetime) -> int:
31+
"""datetime → Unix 时间戳(秒,UTC)"""
32+
return int(dt.timestamp())
33+
34+
35+
# ───────────────────────── 其他工具函数 ───────────────────────── #
3036
def _exclude(src_path: str, globs: List[str]) -> bool:
3137
for g in globs:
3238
if fnmatch.fnmatchcase(src_path, g):
@@ -51,7 +57,7 @@ def _file_git_datetime(repo_path: str) -> datetime:
5157
执行前后都打印完整命令与结果,便于排查。
5258
"""
5359
cmd = ["git", "log", "-1", "--format=%ct", "--", repo_path]
54-
cmd_str = " ".join(shlex.quote(c) for c in cmd) # 可粘贴到终端复现
60+
cmd_str = " ".join(shlex.quote(c) for c in cmd)
5561
_log(f"_file_git_datetime: run → {cmd_str}")
5662

5763
try:
@@ -67,7 +73,6 @@ def _file_git_datetime(repo_path: str) -> datetime:
6773
_log(f"_file_git_datetime: success stdout='{ts}'")
6874
return datetime.fromtimestamp(int(ts), tz=timezone.utc)
6975

70-
# 非 0 或无输出,打印全部信息
7176
_log(
7277
f"_file_git_datetime: git log failed "
7378
f"(code={result.returncode}) "
@@ -96,22 +101,36 @@ def __init__(self):
96101
def on_pre_build(self, _cfg):
97102
if self.cache_path.exists():
98103
try:
99-
self.page_authors = json.loads(self.cache_path.read_text())["page_authors"]
104+
raw = json.loads(self.cache_path.read_text())["page_authors"]
105+
# 过滤旧式错误键;并对 retrieved 做向下兼容
106+
for k, v in list(raw.items()):
107+
if k.startswith("https://"):
108+
continue # 丢弃早期错误的 “全 URL” 键
109+
rt = v.get("retrieved")
110+
if isinstance(rt, str):
111+
try:
112+
raw[k]["retrieved"] = _ts(datetime.fromisoformat(rt))
113+
except Exception:
114+
raw[k].pop("retrieved", None)
115+
self.page_authors = raw
100116
_log(f"Loaded committer cache from {self.cache_path}")
101117
except Exception as e:
102118
_log(f"Failed to read cache, ignore: {e}", "WARN")
103119

104120
def on_post_build(self, _cfg):
105121
out = {
106-
"cache_date": datetime.now(tz=timezone.utc).isoformat(),
122+
"cache_date": _ts(datetime.now(tz=timezone.utc)),
107123
"page_authors": self.page_authors,
108124
}
109125
self.cache_path.write_text(json.dumps(out, ensure_ascii=False, indent=2))
110126
_log(f"Saved committer cache to {self.cache_path}")
111127

112128
_log("========= Committer Summary =========")
113129
for k, v in sorted(self.page_authors.items()):
114-
_log(f"[SUMMARY] {k} | retrieved: {v.get('retrieved', 'N/A')}")
130+
rt = v.get("retrieved", "N/A")
131+
if isinstance(rt, int):
132+
rt = datetime.fromtimestamp(rt, tz=timezone.utc).isoformat()
133+
_log(f"[SUMMARY] {k} | retrieved: {rt}")
115134
_log("=====================================")
116135

117136
def on_page_context(self, context, page, _cfg, _nav):
@@ -130,26 +149,24 @@ def on_page_context(self, context, page, _cfg, _nav):
130149
@staticmethod
131150
def _repo_path_from_edit_url(edit_url: str) -> str:
132151
"""
152+
把 GitHub edit URL 转成 repo 内部相对路径。
133153
例:
134-
edit_url =
135154
https://github.com/doocs/leetcode/edit/main/solution/0000-0099/0001.Two%20Sum/README.md
136-
返回:
137-
solution/0000-0099/0001.Two Sum/README.md
155+
→ solution/0000-0099/0001.Two Sum/README.md
138156
"""
139157
raw_path = edit_url.split("/edit/main/")[-1]
140158
return urllib.parse.unquote(raw_path)
141159

142160
@staticmethod
143161
def _api_url_from_repo_path(repo_path: str) -> str:
144-
# 重新进行 URL 编码,确保空格等字符合法
145162
quoted = urllib.parse.quote(repo_path)
146163
return (
147164
"https://api.github.com/repos/doocs/leetcode/commits"
148165
f"?path={quoted}&sha=main&per_page=100"
149166
)
150167

151168
def _get_authors_with_cache(self, api_url: str, repo_path: str) -> List[Dict]:
152-
git_mtime = _file_git_datetime(repo_path).isoformat()
169+
git_mtime = _ts(_file_git_datetime(repo_path)) # int
153170

154171
cached = self.page_authors.get(repo_path)
155172
cached_time = cached.get("retrieved") if cached else None
@@ -195,7 +212,7 @@ def _get_authors_with_cache(self, api_url: str, repo_path: str) -> List[Dict]:
195212

196213
self.page_authors[repo_path] = {
197214
"authors": authors,
198-
"retrieved": datetime.now(tz=timezone.utc).isoformat(),
215+
"retrieved": _ts(datetime.now(tz=timezone.utc)), # int
199216
}
200217
_log(f"[CACHE UPDATE] {repo_path} new authors: {len(authors)}")
201218
return authors

0 commit comments

Comments
 (0)