codeyear 0.2.14__py3-none-any.whl

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.
codeyear/profile.py ADDED
@@ -0,0 +1,180 @@
1
+ """Optionally write the GitHub profile card into a local profile repo.
2
+
3
+ No network access happens unless ``push=True``. Even then, only the card
4
+ SVGs and the profile README are committed; the report and raw JSON stay
5
+ on this machine.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import re
12
+ import shutil
13
+ import subprocess
14
+ import time
15
+ from pathlib import Path
16
+
17
+ _NO_WINDOW = subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0
18
+
19
+
20
+ def _git(repo: Path, *args: str) -> subprocess.CompletedProcess:
21
+ return subprocess.run(
22
+ ["git", "-C", str(repo), *args],
23
+ capture_output=True,
24
+ text=True,
25
+ encoding="utf-8",
26
+ errors="replace",
27
+ check=False,
28
+ creationflags=_NO_WINDOW,
29
+ )
30
+
31
+
32
+ def _push(repo: Path) -> None:
33
+ """Push, rebasing once if another workflow committed in the meantime."""
34
+ last: subprocess.CompletedProcess | None = None
35
+ for attempt in range(3):
36
+ result = _git(repo, "push")
37
+ if result.returncode == 0:
38
+ return
39
+ last = result
40
+ if attempt < 2:
41
+ _git(repo, "pull", "--rebase")
42
+ time.sleep(2)
43
+ raise RuntimeError(((last.stderr if last else "") or "git push failed").strip())
44
+
45
+
46
+ def _latest_version(directory: Path, year: int) -> tuple[int, Path | None]:
47
+ pattern = re.compile(rf"^codeyear-{year}-card-v(\d+)\.svg$")
48
+ found: list[tuple[int, Path]] = []
49
+ for path in directory.iterdir():
50
+ match = pattern.match(path.name)
51
+ if match:
52
+ found.append((int(match.group(1)), path))
53
+ if not found:
54
+ return 0, None
55
+ return max(found, key=lambda item: item[0])
56
+
57
+
58
+ def _card_dir(text: str) -> str:
59
+ """Directory used by the existing README card reference, if any."""
60
+ match = re.search(
61
+ r'(?:src|srcset)="(?:\./)?([^"]*/)?codeyear-\d{4}-card[^"]*\.svg[^"]*"',
62
+ text,
63
+ )
64
+ if not match:
65
+ return ""
66
+ prefix = (match.group(1) or "").strip("/")
67
+ if not prefix or prefix.startswith(("http:", "https:")):
68
+ return ""
69
+ return prefix
70
+
71
+
72
+ def update_profile(
73
+ repo_path: str | Path,
74
+ year: int,
75
+ light_card: str | Path,
76
+ dark_card: str | Path,
77
+ *,
78
+ push: bool = False,
79
+ ) -> tuple[Path, bool, bool]:
80
+ """Update a local profile repo.
81
+
82
+ Returns ``(repo, changed, pushed)``. Without ``push=True`` the working
83
+ tree is updated but nothing is committed or sent anywhere.
84
+ """
85
+
86
+ repo = Path(repo_path).expanduser().resolve()
87
+ if not (repo / ".git").exists():
88
+ raise FileNotFoundError(f"不是 git 仓库: {repo}")
89
+
90
+ light = Path(light_card)
91
+ dark = Path(dark_card)
92
+ if not light.exists() or not dark.exists():
93
+ raise FileNotFoundError("找不到卡片文件,请先生成卡片")
94
+
95
+ readme = repo / "README.md"
96
+ text = readme.read_text(encoding="utf-8") if readme.exists() else ""
97
+ rel_dir = _card_dir(text)
98
+ target = repo
99
+ if rel_dir:
100
+ candidate = (repo / rel_dir).resolve()
101
+ try:
102
+ candidate.relative_to(repo)
103
+ target = candidate
104
+ except ValueError: # README path escapes the repo; stay at the root
105
+ target = repo
106
+ target.mkdir(parents=True, exist_ok=True)
107
+
108
+ version, latest_light = _latest_version(target, year)
109
+ if latest_light is not None:
110
+ latest_dark = target / f"codeyear-{year}-card-v{version}-dark.svg"
111
+ if (
112
+ latest_dark.exists()
113
+ and latest_light.read_bytes() == light.read_bytes()
114
+ and latest_dark.read_bytes() == dark.read_bytes()
115
+ ):
116
+ return repo, False, False
117
+
118
+ version += 1
119
+ light_name = f"codeyear-{year}-card-v{version}.svg"
120
+ dark_name = f"codeyear-{year}-card-v{version}-dark.svg"
121
+ shutil.copy2(light, target / light_name)
122
+ shutil.copy2(dark, target / dark_name)
123
+ # Only the newest version stays referenced; drop older versioned files so
124
+ # a daily/weekly Action does not accumulate one SVG pair per run. Also
125
+ # remove unversioned cards left by the old fixed-filename workflow.
126
+ keep = {target / light_name, target / dark_name}
127
+ for directory in {repo, target}:
128
+ for pattern in ("codeyear-*-card-v*.svg", "codeyear-*-card.svg",
129
+ "codeyear-*-card-dark.svg",
130
+ "codeyear-*-card-en-v*.svg",
131
+ "codeyear-*-card-en.svg",
132
+ "codeyear-*-card-en-dark.svg"):
133
+ for old in directory.glob(pattern):
134
+ if old not in keep:
135
+ old.unlink(missing_ok=True)
136
+
137
+ # Replace any year's card reference so a new year also takes over the
138
+ # README instead of appending a second card block. The path prefix (e.g.
139
+ # "./assets/") is left intact, so subdirectory layouts keep working.
140
+ # English filenames are handled too, so switching --lang does not append
141
+ # a second card block next to the old one.
142
+ text = re.sub(r"codeyear-\d{4}-card-en-v\d+-dark\.svg", dark_name, text)
143
+ text = re.sub(r"codeyear-\d{4}-card-en-v\d+\.svg", light_name, text)
144
+ text = re.sub(r"codeyear-\d{4}-card-en-dark\.svg", dark_name, text)
145
+ text = re.sub(r"codeyear-\d{4}-card-en\.svg", light_name, text)
146
+ text = re.sub(r"codeyear-\d{4}-card-v\d+-dark\.svg", dark_name, text)
147
+ text = re.sub(r"codeyear-\d{4}-card-v\d+\.svg", light_name, text)
148
+ text = re.sub(r"codeyear-\d{4}-card-dark\.svg", dark_name, text)
149
+ text = re.sub(r"codeyear-\d{4}-card\.svg", light_name, text)
150
+ text = re.sub(r'alt="CodeYear \d{4}"', f'alt="CodeYear {year}"', text)
151
+ if light_name not in text:
152
+ prefix = f"./{rel_dir}/" if rel_dir else "./"
153
+ block = (
154
+ '<p align="center">\n'
155
+ " <picture>\n"
156
+ f' <source media="(prefers-color-scheme: dark)" '
157
+ f'srcset="{prefix}{dark_name}">\n'
158
+ f' <img src="{prefix}{light_name}" width="640" '
159
+ f'alt="CodeYear {year}">\n'
160
+ " </picture>\n"
161
+ "</p>\n"
162
+ )
163
+ text = text.rstrip() + "\n\n" + block
164
+ readme.write_text(text, encoding="utf-8")
165
+
166
+ pushed = False
167
+ if push:
168
+ # -A is required so the old versioned files removed above are staged
169
+ # as deletions too; glob magic covers cards in nested asset folders.
170
+ _git(repo, "add", "-A", "README.md", ":(glob)**/codeyear-*.svg")
171
+ staged = _git(repo, "diff", "--cached", "--name-only")
172
+ if staged.stdout.strip():
173
+ commit = _git(
174
+ repo, "commit", "-m", f"Update CodeYear {year} card to v{version}"
175
+ )
176
+ if commit.returncode != 0:
177
+ raise RuntimeError((commit.stderr or "git commit failed").strip())
178
+ _push(repo)
179
+ pushed = True
180
+ return repo, True, pushed