git-retro 0.2.0__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.
git_retro/__init__.py ADDED
@@ -0,0 +1,2 @@
1
+ """git-retro: your year in git, as an animated story page."""
2
+ __version__ = "0.2.0"
git_retro/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
git_retro/cli.py ADDED
@@ -0,0 +1,112 @@
1
+ """git retro: a sua retrospectiva do ano no git, gerada localmente."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import locale
6
+ import os
7
+ import sys
8
+ import webbrowser
9
+ from datetime import date
10
+ from pathlib import Path
11
+
12
+ from . import __version__
13
+ from .core import compute, summary, team, is_bot, config_emails, find_repos, read_commits, resolve_identity, top_authors
14
+ from .render import render
15
+
16
+
17
+ def _default_lang():
18
+ for v in (os.environ.get("LC_ALL"), os.environ.get("LANG"), (locale.getlocale()[0] or "")):
19
+ if v:
20
+ return "pt" if v.lower().startswith("pt") else "en"
21
+ return "en"
22
+
23
+
24
+ def main(argv=None):
25
+ ap = argparse.ArgumentParser(prog="git-retro", description="Your year in git, as an animated story page. Runs 100%% locally.")
26
+ ap.add_argument("paths", nargs="*", default=["."], help="folders to scan for git repositories (default: current folder)")
27
+ ap.add_argument("-y", "--year", type=int, default=None, help="year to look at (default: this year, or last year in January)")
28
+ ap.add_argument("-a", "--author", action="append", default=[], help="your e-mail or name; repeat for each identity you use")
29
+ ap.add_argument("-o", "--output", default=None, help="output HTML file (default: git-retro-YEAR.html)")
30
+ ap.add_argument("--name", default=None, help="name shown on the page (default: your git user.name)")
31
+ ap.add_argument("--lang", choices=["pt", "en"], default=None, help="page language (default: from your system)")
32
+ ap.add_argument("--no-messages", action="store_true", help="hide commit messages from the page")
33
+ ap.add_argument("--anonymize", action="store_true", help="replace repository names with projeto-A, projeto-B…")
34
+ ap.add_argument("--depth", type=int, default=4, help="how deep to look for repositories (default: 4)")
35
+ ap.add_argument("--team", action="store_true", help="the whole team instead of just you: leaderboard and awards")
36
+ ap.add_argument("--demo", action="store_true", help="use a made-up year instead of your repositories")
37
+ ap.add_argument("--no-open", action="store_true", help="do not open the page in the browser")
38
+ ap.add_argument("--version", action="version", version=f"git-retro {__version__}")
39
+ a = ap.parse_args(argv)
40
+
41
+ today = date.today()
42
+ year = a.year or (today.year - 1 if today.month == 1 else today.year)
43
+ lang = a.lang or _default_lang()
44
+ say = (lambda pt, en: print(pt if lang == "pt" else en, file=sys.stderr))
45
+
46
+ if a.demo:
47
+ from .demo import demo_commits
48
+ mine = demo_commits(year, lang=lang, team=a.team)
49
+ prev = demo_commits(year - 1, seed=3, lang=lang, scale=.7, team=a.team)
50
+ name = a.name or ("Acme" if a.team else ("Você" if lang == "pt" else "You"))
51
+ else:
52
+ repos = find_repos(a.paths, a.depth)
53
+ if not repos:
54
+ say("Nenhum repositório git encontrado aqui. Passe a pasta onde ficam seus projetos: git-retro ~/projetos",
55
+ "No git repositories found here. Point it at your projects folder: git-retro ~/code")
56
+ return 1
57
+ say(f"→ {len(repos)} repositórios encontrados, lendo commits de {year}…",
58
+ f"→ found {len(repos)} repositories, reading {year} commits…")
59
+ commits = [c for r in repos for c in read_commits(r, year)]
60
+ before = [c for r in repos for c in read_commits(r, year - 1)]
61
+ if not commits:
62
+ say(f"Nenhum commit em {year} nesses repositórios.", f"No commits in {year} in those repositories.")
63
+ return 1
64
+ if a.team:
65
+ mine = [c for c in commits if not is_bot(c)]
66
+ prev = [c for c in before if not is_bot(c)]
67
+ roots = {Path(p).expanduser().resolve() for p in a.paths}
68
+ name = a.name or (next(iter(roots)).name if len(roots) == 1 else "")
69
+ else:
70
+ seeds = {x for x in a.author if "@" in x} or config_emails(repos)
71
+ names = {x for x in a.author if "@" not in x}
72
+ if not seeds and not names:
73
+ (email, nm), _ = top_authors(commits, 1)[0]
74
+ seeds = {email}
75
+ say(f" (sem user.email configurado; usando quem mais commitou: {nm} <{email}>)",
76
+ f" (no user.email configured; using the top committer: {nm} <{email}>)")
77
+ emails, names = resolve_identity(commits + before, seeds, names)
78
+ mine = [c for c in commits if c.email in emails or c.name.lower() in names]
79
+ prev = [c for c in before if c.email in emails or c.name.lower() in names]
80
+ say(f" você = {', '.join(sorted(emails))}", f" you = {', '.join(sorted(emails))}")
81
+ if not mine:
82
+ say("Nenhum commit seu encontrado. Quem aparece nesses repositórios:",
83
+ "None of the commits are yours. Who shows up in these repositories:")
84
+ for (email, nm), n in top_authors(commits):
85
+ print(f" {n:5} {nm} <{email}>", file=sys.stderr)
86
+ say("Rode de novo com --author seu@email (pode repetir).", "Run again with --author you@email (repeatable).")
87
+ return 1
88
+ name = a.name or (mine[-1].name.split()[0] if mine[-1].name else "")
89
+
90
+ data = compute(mine, year, show_messages=not a.no_messages, anonymize=a.anonymize, name=name)
91
+ data["lang"] = lang
92
+ if a.team:
93
+ data["team"] = team(mine, year)
94
+ say(f" time: {data['team']['size']} pessoas", f" team: {data['team']['size']} people")
95
+ data["prev"] = summary(compute(prev, year - 1)) if prev else None
96
+ ign = data.pop("_ignored")
97
+ out = Path(a.output or f"git-retro-{year}.html")
98
+ out.write_text(render(data), encoding="utf-8")
99
+ t = data["totals"]
100
+ say(f"✓ {t['commits']} commits em {t['repos']} repositórios → {out}",
101
+ f"✓ {t['commits']} commits across {t['repos']} repositories → {out}")
102
+ if ign["lines"]:
103
+ n = f"{ign['lines']:,}".replace(",", "." if lang == "pt" else ",")
104
+ say(f" ({n} linhas de dependências, build e importações ficaram fora da conta; a maior parte em {ign['top']})",
105
+ f" ({n} lines of dependencies, build output and imports were left out; mostly {ign['top']})")
106
+ if not a.no_open:
107
+ webbrowser.open(out.resolve().as_uri())
108
+ return 0
109
+
110
+
111
+ if __name__ == "__main__":
112
+ sys.exit(main())
git_retro/core.py ADDED
@@ -0,0 +1,388 @@
1
+ """Coleta de commits nos repositórios locais e cálculo das estatísticas do ano.
2
+
3
+ Tudo roda localmente com o próprio `git`; nada é enviado para fora.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import os
8
+ import re
9
+ import subprocess
10
+ from collections import Counter, defaultdict
11
+ from dataclasses import dataclass, field
12
+ from datetime import date, datetime, timedelta
13
+ from pathlib import Path
14
+
15
+ SKIP_DIRS = {"node_modules", ".venv", "venv", "env", ".tox", "__pycache__", "dist", "build",
16
+ ".next", ".cache", "vendor", "target", ".gradle", ".dart_tool", "Pods"}
17
+
18
+ # pastas de dependência e de build: ninguém escreveu aquilo (mas alguém commitou)
19
+ VENDOR = re.compile(r"(^|/)(node_modules|bower_components|site-packages|\.?venv[^/]*|virtualenv|env|\.tox|vendor|Pods|"
20
+ r"\.dart_tool|staticfiles|collected_static|dist|build|out|target|coverage|htmlcov|\.next|\.nuxt|__pycache__|migrations|drizzle/meta)/")
21
+ # arquivos que inflam a contagem de linhas sem ninguém ter escrito nada
22
+ NOISE = re.compile(r"(^|/)(package-lock\.json|yarn\.lock|pnpm-lock\.yaml|poetry\.lock|Pipfile\.lock|uv\.lock|"
23
+ r"composer\.lock|Cargo\.lock|Gemfile\.lock|pubspec\.lock|go\.sum)$|"
24
+ r"\.min\.(js|css)$|\.map$|\.(svg|png|jpe?g|gif|webp|ico|pdf|zip|gz|woff2?|ttf|otf|mp4|mp3|lock|pyc)$")
25
+ DATA_EXT = re.compile(r"\.(json|csv|tsv|xml|sql|txt|ya?ml|geojson|ndjson)$", re.I)
26
+ GENERATED_LINES = 5000 # um arquivo só com mais que isso num commit é gerado/importado
27
+ DATA_LINES = 1500 # idem para arquivos de dados
28
+ IMPORT_LINES = 30000 # um commit inteiro maior que isso é código trazido de outro lugar
29
+
30
+ LANGS = {
31
+ "py": ("Python", "#3B82F6"), "js": ("JavaScript", "#F7DF1E"), "mjs": ("JavaScript", "#F7DF1E"),
32
+ "jsx": ("JavaScript", "#F7DF1E"), "ts": ("TypeScript", "#3178C6"), "tsx": ("TypeScript", "#3178C6"),
33
+ "html": ("HTML", "#E34F26"), "htm": ("HTML", "#E34F26"), "css": ("CSS", "#A855F7"),
34
+ "scss": ("CSS", "#A855F7"), "sass": ("CSS", "#A855F7"), "dart": ("Dart", "#00B4AB"),
35
+ "kt": ("Kotlin", "#A97BFF"), "kts": ("Kotlin", "#A97BFF"), "java": ("Java", "#F89820"),
36
+ "go": ("Go", "#00ADD8"), "rs": ("Rust", "#DEA584"), "rb": ("Ruby", "#CC342D"), "php": ("PHP", "#777BB4"),
37
+ "c": ("C", "#A8B9CC"), "h": ("C", "#A8B9CC"), "cpp": ("C++", "#F34B7D"), "cc": ("C++", "#F34B7D"),
38
+ "hpp": ("C++", "#F34B7D"), "cs": ("C#", "#68217A"), "swift": ("Swift", "#F05138"),
39
+ "sql": ("SQL", "#E38C00"), "sh": ("Shell", "#89E051"), "bash": ("Shell", "#89E051"),
40
+ "vue": ("Vue", "#41B883"), "svelte": ("Svelte", "#FF3E00"), "lua": ("Lua", "#000080"),
41
+ "md": ("Markdown", "#9CA3AF"), "json": ("JSON", "#6B7280"), "yml": ("YAML", "#CB171E"),
42
+ "yaml": ("YAML", "#CB171E"), "toml": ("TOML", "#9C4221"), "ex": ("Elixir", "#6E4A7E"),
43
+ "exs": ("Elixir", "#6E4A7E"), "scala": ("Scala", "#DC322F"), "r": ("R", "#198CE7"),
44
+ "ipynb": ("Jupyter", "#F37626"), "tf": ("Terraform", "#7B42BC"), "zig": ("Zig", "#F7A41D"),
45
+ }
46
+ SPECIAL_FILES = {"Dockerfile": ("Docker", "#2496ED"), "Makefile": ("Make", "#427819")}
47
+
48
+ STOP = set("""a o e é de da do das dos em no na nos nas um uma para pra por com sem que se ao à
49
+ as os mais e ou the a an and or to of in on for with from by at is it this that be as into
50
+ não nao sim mais fix fixes fixed feat chore refactor docs style test tests wip merge update updates updated add
51
+ added adds remove removed item itens items user users file files code page pages new novo nova novos novas
52
+ ajuste ajustes ajusta ajustar melhoria melhorias melhora versão versao version initial inicial commit
53
+ change changes changed alteração alterações altera small minor some more also now after before when""".split())
54
+
55
+ _SEP = "\x1e"
56
+ _FS = "\x1f"
57
+
58
+
59
+ @dataclass
60
+ class Commit:
61
+ hash: str
62
+ email: str
63
+ name: str
64
+ when: datetime
65
+ subject: str
66
+ repo: str
67
+ files: list = field(default_factory=list) # (added, removed, path)
68
+
69
+
70
+ def find_repos(roots, max_depth=4):
71
+ """Acha pastas com .git dentro das raízes dadas, sem descer em node_modules e afins."""
72
+ found = []
73
+ for root in roots:
74
+ root = Path(root).expanduser().resolve()
75
+ if (root / ".git").exists():
76
+ found.append(root)
77
+ base = len(root.parts)
78
+ for cur, dirs, _ in os.walk(root):
79
+ depth = len(Path(cur).parts) - base
80
+ if depth >= max_depth:
81
+ dirs[:] = []
82
+ continue
83
+ keep = []
84
+ for d in dirs:
85
+ if d in SKIP_DIRS or d.startswith(".") and d != ".git":
86
+ continue
87
+ p = Path(cur) / d
88
+ if d == ".git":
89
+ continue
90
+ if (p / ".git").exists():
91
+ found.append(p)
92
+ keep.append(d)
93
+ dirs[:] = keep
94
+ seen, out = set(), []
95
+ for r in found:
96
+ if r not in seen:
97
+ seen.add(r); out.append(r)
98
+ return out
99
+
100
+
101
+ def _git(repo, *args, stdin=None):
102
+ r = subprocess.run(["git", "-C", str(repo), *args], capture_output=True, text=True,
103
+ encoding="utf-8", errors="replace", input=stdin)
104
+ return r.stdout if r.returncode == 0 else ""
105
+
106
+
107
+ def config_emails(repos):
108
+ """E-mails configurados (global e em cada repositório): ponto de partida para achar 'você'."""
109
+ emails = set()
110
+ g = subprocess.run(["git", "config", "--global", "user.email"], capture_output=True, text=True).stdout.strip()
111
+ if g:
112
+ emails.add(g.lower())
113
+ for r in repos:
114
+ e = _git(r, "config", "--local", "user.email").strip()
115
+ if e:
116
+ emails.add(e.lower())
117
+ return emails
118
+
119
+
120
+ def read_commits(repo, year):
121
+ # 1) lista leve de datas; `--since` não serve: ele para no primeiro commit antigo do caminho
122
+ # (rebase, data alterada) e some com o resto do ano
123
+ hashes = [h for h, _, d in (l.partition(" ") for l in _git(repo, "log", "--all", "--no-merges", "--format=%H %aI").splitlines())
124
+ if d[:4] == str(year)]
125
+ if not hashes:
126
+ return []
127
+ # 2) detalhes só dos commits do ano
128
+ fmt = f"--pretty=format:{_SEP}%H{_FS}%ae{_FS}%an{_FS}%aI{_FS}%s"
129
+ out = _git(repo, "log", "--no-walk=unsorted", "--stdin", "--numstat", fmt, stdin="\n".join(hashes) + "\n")
130
+ commits = []
131
+ for block in out.split(_SEP):
132
+ if not block.strip():
133
+ continue
134
+ head, _, rest = block.partition("\n")
135
+ parts = head.split(_FS)
136
+ if len(parts) < 5:
137
+ continue
138
+ h, email, name, iso, subject = parts[:5]
139
+ try:
140
+ when = datetime.fromisoformat(iso.replace("Z", "+00:00"))
141
+ except ValueError:
142
+ continue
143
+ if when.year != year:
144
+ continue
145
+ c = Commit(h, email.lower(), name, when, subject.strip(), repo.name)
146
+ for line in rest.splitlines():
147
+ bits = line.split("\t")
148
+ if len(bits) != 3:
149
+ continue
150
+ a, d, path = bits
151
+ if " => " in path: # renomeado: fica o destino
152
+ path = re.sub(r"\{[^{}]* => ([^{}]*)\}", r"\1", path).split(" => ")[-1]
153
+ c.files.append((int(a) if a.isdigit() else 0, int(d) if d.isdigit() else 0, path))
154
+ commits.append(c)
155
+ return commits
156
+
157
+
158
+ def resolve_identity(commits, seeds, names=()):
159
+ """Junta os e-mails da mesma pessoa: quem usa um nome que algum e-mail-semente usa também é você."""
160
+ emails = {e.lower() for e in seeds}
161
+ names = {n.lower() for n in names}
162
+ for _ in range(3):
163
+ for c in commits:
164
+ if c.email in emails:
165
+ names.add(c.name.lower())
166
+ for c in commits:
167
+ if c.name.lower() in names:
168
+ emails.add(c.email)
169
+ return emails, names
170
+
171
+
172
+ BOT = re.compile(r"\[bot\]|dependabot|renovate|github-actions|actions-user|noreply@github\.com$", re.I)
173
+
174
+
175
+ def is_bot(c):
176
+ return bool(BOT.search(c.name) or BOT.search(c.email))
177
+
178
+
179
+ def group_people(commits):
180
+ """Junta e-mails e nomes que aparecem juntos: cada grupo é uma pessoa."""
181
+ parent = {}
182
+ def find(x):
183
+ parent.setdefault(x, x)
184
+ while parent[x] != x:
185
+ parent[x] = parent[parent[x]]; x = parent[x]
186
+ return x
187
+ for c in commits:
188
+ parent[find(("e", c.email))] = find(("n", c.name.strip().lower()))
189
+ groups = defaultdict(list)
190
+ for c in commits:
191
+ groups[find(("e", c.email))].append(c)
192
+ return list(groups.values())
193
+
194
+
195
+ def team(commits, year):
196
+ """Ranking e prêmios do time. Cada pessoa passa pelo mesmo cálculo da retrospectiva individual."""
197
+ people = []
198
+ for cs in group_people(commits):
199
+ d = compute(cs, year, show_messages=False)
200
+ name = Counter(c.name for c in cs).most_common(1)[0][0] or cs[0].email.split("@")[0]
201
+ night = d["night"]
202
+ people.append({
203
+ "name": name, "commits": d["totals"]["commits"], "added": d["totals"]["added"], "removed": d["totals"]["removed"],
204
+ "days": d["totals"]["active_days"], "streak": d["streak"]["length"], "persona": d["persona"],
205
+ "fixes": round(d["fix_pct"] * d["totals"]["commits"] / 100),
206
+ "night": night["time"] if night else None,
207
+ "_night_rank": _night_rank(datetime.strptime(night["time"], "%H:%M")) if night else -1,
208
+ })
209
+ people.sort(key=lambda p: -p["commits"])
210
+ awards = []
211
+ def award(key, field, fmt=None, minimum=1):
212
+ best = max(people, key=lambda p: p[field])
213
+ if best[field] >= minimum:
214
+ awards.append({"key": key, "name": best["name"], "value": fmt(best) if fmt else best[field]})
215
+ award("commits", "commits")
216
+ award("streak", "streak", minimum=2)
217
+ award("owl", "_night_rank", fmt=lambda p: p["night"], minimum=22)
218
+ award("cleaner", "removed", minimum=100)
219
+ award("fixer", "fixes", minimum=2)
220
+ for p in people:
221
+ p.pop("_night_rank")
222
+ return {"size": len(people), "members": people[:10], "awards": awards}
223
+
224
+
225
+ def top_authors(commits, n=8):
226
+ return Counter((c.email, c.name) for c in commits).most_common(n)
227
+
228
+
229
+ def lang_of(path):
230
+ base = path.rsplit("/", 1)[-1]
231
+ if base in SPECIAL_FILES:
232
+ return SPECIAL_FILES[base]
233
+ if "." not in base:
234
+ return None
235
+ return LANGS.get(base.rsplit(".", 1)[-1].lower())
236
+
237
+
238
+ def _night_rank(dt):
239
+ """Quanto mais perto das 5h, mais 'madrugada' é (0h=24, 4h59=28,99)."""
240
+ h = dt.hour + dt.minute / 60
241
+ return h + 24 if h < 5 else (h if h >= 22 else -1)
242
+
243
+
244
+ def compute(commits, year, *, show_messages=True, anonymize=False, name=""):
245
+ commits = sorted({c.hash: c for c in commits}.values(), key=lambda c: c.when)
246
+ if not commits:
247
+ return None
248
+
249
+ repo_alias = {}
250
+ def rname(r):
251
+ if not anonymize:
252
+ return r
253
+ if r not in repo_alias:
254
+ repo_alias[r] = f"projeto-{chr(65 + len(repo_alias) % 26)}"
255
+ return repo_alias[r]
256
+ msg = (lambda s: s) if show_messages else (lambda s: "")
257
+
258
+ days = Counter(c.when.date().isoformat() for c in commits)
259
+ hours = [0] * 24
260
+ weekdays = [0] * 7
261
+ months = [0] * 12
262
+ lang_lines = Counter()
263
+ lang_color = {}
264
+ per_repo = defaultdict(lambda: {"commits": 0, "added": 0, "removed": 0})
265
+ added = removed = 0
266
+ files = set()
267
+ ignored = 0
268
+ ignored_dirs = Counter()
269
+ words = Counter()
270
+ types = Counter()
271
+ biggest = None
272
+
273
+ for c in commits:
274
+ hours[c.when.hour] += 1
275
+ weekdays[c.when.weekday()] += 1
276
+ months[c.when.month - 1] += 1
277
+ pr = per_repo[c.repo]
278
+ pr["commits"] += 1
279
+ m = re.match(r"^(\w+)(\([^)]*\))?!?:", c.subject)
280
+ if m:
281
+ types[m.group(1).lower()] += 1
282
+ elif re.match(r"(?i)^(fix|corrig|conserta|ajust)", c.subject):
283
+ types["fix"] += 1
284
+ for w in re.findall(r"[a-zà-ú]{3,}", c.subject.lower()):
285
+ if w not in STOP:
286
+ words[w] += 1
287
+ size = 0
288
+ csize = sum(a + d for a, d, path in c.files if not NOISE.search(path) and not VENDOR.search(path))
289
+ if csize > IMPORT_LINES:
290
+ ignored += csize
291
+ ignored_dirs[f"{c.subject[:40]}"] += csize
292
+ continue
293
+ for a, d, path in c.files:
294
+ if NOISE.search(path):
295
+ continue
296
+ vm = VENDOR.search(path)
297
+ if vm or a + d > GENERATED_LINES or (DATA_EXT.search(path) and a + d > DATA_LINES):
298
+ ignored += a + d
299
+ ignored_dirs[path[:vm.end()] if vm else path] += a + d
300
+ continue
301
+ files.add((c.repo, path))
302
+ added += a; removed += d; size += a + d
303
+ pr["added"] += a; pr["removed"] += d
304
+ lg = lang_of(path)
305
+ if lg:
306
+ lang_lines[lg[0]] += a + d
307
+ lang_color[lg[0]] = lg[1]
308
+ if biggest is None or size > biggest[0]:
309
+ biggest = (size, c)
310
+
311
+ # sequência de dias seguidos
312
+ ds = sorted(date.fromisoformat(d) for d in days)
313
+ best = (1, ds[0], ds[0]); run_start = ds[0]
314
+ for prev, cur in zip(ds, ds[1:]):
315
+ if cur - prev != timedelta(days=1):
316
+ run_start = cur
317
+ ln = (cur - run_start).days + 1
318
+ if ln > best[0]:
319
+ best = (ln, run_start, cur)
320
+
321
+ busiest_day, busiest_n = max(days.items(), key=lambda kv: (kv[1], kv[0]))
322
+ night = max(commits, key=lambda c: _night_rank(c.when))
323
+ night = night if _night_rank(night.when) > 0 else None
324
+
325
+ total = len(commits)
326
+ late = sum(hours[0:5]); evening = sum(hours[18:24]); early = sum(hours[5:9])
327
+ weekend = weekdays[5] + weekdays[6]
328
+ fix_pct = round(types.get("fix", 0) * 100 / total)
329
+ tot_lang = sum(lang_lines.values()) or 1
330
+ big_langs = sum(1 for v in lang_lines.values() if v / tot_lang >= .05)
331
+ top_repo_share = max(v["commits"] for v in per_repo.values()) / total
332
+ by_day = sorted(days.values(), reverse=True)
333
+ burst = sum(by_day[:max(1, len(by_day) // 10)]) / total
334
+ pct = lambda x: round(x * 100 / total)
335
+ # cada traço vira uma razão "quanto passou do limite"; vence o mais forte, e o expediente comercial
336
+ # só aparece quando nada se destaca
337
+ rules = [ # (persona, valor medido / limite, número mostrado)
338
+ ("owl", late / total / .12, pct(late)),
339
+ ("weekend", weekend / total / .3, pct(weekend)),
340
+ ("marathon", best[0] / 21, best[0]),
341
+ ("cleaner", (removed / added / .6) if added > 1000 else 0, round(removed * 100 / max(added, 1))),
342
+ ("firefighter", fix_pct / 35, fix_pct),
343
+ ("polyglot", big_langs / 4, big_langs),
344
+ ("burst", (burst / .3) if len(days) >= 20 else 0, round(burst * 100)),
345
+ ("loyal", (top_repo_share / .8) if len(per_repo) > 1 else 0, round(top_repo_share * 100)),
346
+ ("early", early / total / .25, pct(early)),
347
+ ("night", evening / total / .35, pct(evening)),
348
+ ]
349
+ key, ratio, value = max(rules, key=lambda r: r[1])
350
+ persona, persona_value = (key, value) if ratio >= 1 else ("office", pct(sum(hours[9:18])))
351
+
352
+ ignored_top = ""
353
+ if ignored_dirs:
354
+ ignored_top = ignored_dirs.most_common(1)[0][0]
355
+ langs = [{"name": n, "lines": v, "pct": round(v * 100 / tot_lang, 1), "color": lang_color[n]}
356
+ for n, v in lang_lines.most_common(6)]
357
+ repos = sorted(({"name": rname(r), **v} for r, v in per_repo.items()), key=lambda x: -x["commits"])[:6]
358
+
359
+ return {
360
+ "year": year,
361
+ "name": name,
362
+ "totals": {"commits": total, "repos": len(per_repo), "active_days": len(days),
363
+ "added": added, "removed": removed, "files": len(files)},
364
+ "days": dict(days),
365
+ "hours": hours, "weekdays": weekdays, "months": months,
366
+ "langs": langs, "repos": repos,
367
+ "streak": {"length": best[0], "start": best[1].isoformat(), "end": best[2].isoformat()},
368
+ "busiest": {"date": busiest_day, "commits": busiest_n},
369
+ "night": night and {"time": night.when.strftime("%H:%M"), "date": night.when.date().isoformat(),
370
+ "message": msg(night.subject), "repo": rname(night.repo)},
371
+ "biggest": biggest and biggest[0] and {"lines": biggest[0], "message": msg(biggest[1].subject),
372
+ "repo": rname(biggest[1].repo), "date": biggest[1].when.date().isoformat()},
373
+ "words": words.most_common(8) if show_messages else [],
374
+ # fica só no terminal: a página não comenta o que foi tirado da conta
375
+ "_ignored": {"lines": ignored, "top": ignored_top},
376
+ "fix_pct": fix_pct,
377
+ "persona": persona, "persona_value": persona_value,
378
+ "weekend_pct": round(weekend * 100 / total),
379
+ }
380
+
381
+
382
+ def summary(data):
383
+ """O pouco do ano anterior que a comparação usa."""
384
+ if not data:
385
+ return None
386
+ t = data["totals"]
387
+ return {"year": data["year"], "commits": t["commits"], "active_days": t["active_days"], "added": t["added"],
388
+ "streak": data["streak"]["length"], "top_lang": data["langs"][0]["name"] if data["langs"] else ""}
git_retro/demo.py ADDED
@@ -0,0 +1,72 @@
1
+ """Um ano inventado, para ver a retrospectiva sem apontar para repositório nenhum."""
2
+ from __future__ import annotations
3
+
4
+ import random
5
+ from datetime import datetime, timedelta, timezone
6
+
7
+ from .core import Commit
8
+
9
+ REPOS = ["api-pagamentos", "app-entregas", "painel-admin", "site-institucional", "dotfiles", "cli-deploy"]
10
+ FILES = {
11
+ "api-pagamentos": ["app/models.py", "app/views.py", "app/services/pix.py", "tests/test_pix.py", "app/schema.sql"],
12
+ "app-entregas": ["lib/main.dart", "lib/screens/mapa.dart", "lib/api.dart", "android/app/build.gradle.kts"],
13
+ "painel-admin": ["src/App.tsx", "src/pages/Pedidos.tsx", "src/api.ts", "src/styles.css"],
14
+ "site-institucional": ["index.html", "css/site.css", "js/menu.js"],
15
+ "dotfiles": ["install.sh", ".zshrc.sh", "README.md"],
16
+ "cli-deploy": ["cmd/root.go", "internal/ssh.go", "Dockerfile", "README.md"],
17
+ }
18
+ MSGS = [
19
+ "feat: pagamento por pix com QR dinâmico", "fix: timezone no relatório mensal", "ajusta layout do checkout no celular",
20
+ "feat: tela de mapa com rota do entregador", "corrige cálculo de frete", "refactor: separa serviço de cobrança",
21
+ "fix: botão salvar duplicava pedido", "feat: exportar pedidos em csv", "deploy automático na main",
22
+ "testes do webhook do banco", "fix: fix do fix", "melhora performance da listagem", "feat: modo escuro",
23
+ "corrige migração quebrada", "atualiza dependências", "feat: login com código por e-mail", "por que isso funcionava antes",
24
+ "fix: cache do dashboard", "feat: filtros na tela de pedidos", "remove código morto",
25
+ ]
26
+ MSGS_EN = [
27
+ "feat: pix-style instant payments with dynamic QR", "fix: timezone in monthly report", "tweak checkout layout on mobile",
28
+ "feat: live map with courier route", "fix shipping cost rounding", "refactor: split billing service",
29
+ "fix: save button created duplicate orders", "feat: export orders as csv", "auto deploy on main",
30
+ "tests for bank webhook", "fix: fix the fix", "speed up order list", "feat: dark mode",
31
+ "fix broken migration", "bump dependencies", "feat: passwordless login by e-mail", "why did this ever work",
32
+ "fix: dashboard cache", "feat: filters on orders page", "remove dead code",
33
+ ]
34
+
35
+
36
+ TEAM = [("Ana Souza", "ana@exemplo.dev", 34, 0), ("Bruno Lima", "bruno@exemplo.dev", 24, 0), ("Carla Dias", "carla@exemplo.dev", 18, 0),
37
+ ("Diego Rocha", "diego@exemplo.dev", 14, 4), ("Eva Martins", "eva@exemplo.dev", 10, -3)]
38
+
39
+
40
+ def demo_commits(year: int, seed: int = 7, lang: str = "en", scale: float = 1.0, team: bool = False):
41
+ rnd = random.Random(seed)
42
+ tz = timezone(timedelta(hours=-3))
43
+ msgs = MSGS if lang == "pt" else MSGS_EN
44
+ you = "Você" if lang == "pt" else "You"
45
+ out = []
46
+ day = datetime(year, 1, 1, tzinfo=tz)
47
+ n = 0
48
+ while day.year == year:
49
+ busy = (.82 if day.weekday() < 5 else .35) * scale
50
+ if rnd.random() < busy:
51
+ for _ in range(rnd.choice([1, 1, 2, 2, 3, 4, 6])):
52
+ h = rnd.choices(range(24), weights=[3, 2, 1, .5, .2, .1, .3, 1, 3, 6, 8, 8, 4, 6, 8, 8, 7, 5, 3, 3, 4, 5, 5, 4])[0]
53
+ when = day.replace(hour=h, minute=rnd.randrange(60))
54
+ repo = rnd.choices(REPOS, weights=[30, 22, 18, 8, 4, 10])[0]
55
+ files = [(rnd.randrange(1, 140), rnd.randrange(0, 60), f) for f in rnd.sample(FILES[repo], rnd.randint(1, min(3, len(FILES[repo]))))]
56
+ n += 1
57
+ who, mail = you, "you@example.dev"
58
+ if team:
59
+ k = rnd.choices(range(len(TEAM)), weights=[t[2] for t in TEAM])[0]
60
+ who, mail, _, shift = TEAM[k]
61
+ if rnd.random() < .7: # cada pessoa tem o seu projeto preferido
62
+ repo = REPOS[k]
63
+ files = [(rnd.randrange(1, 140), rnd.randrange(0, 60), f) for f in rnd.sample(FILES[repo], rnd.randint(1, min(3, len(FILES[repo]))))]
64
+ when = when + timedelta(hours=shift) if 0 <= h + shift < 24 else when
65
+ out.append(Commit(f"{n:040x}", mail, who, when, rnd.choice(msgs), repo, files))
66
+ day += timedelta(days=1)
67
+ # um commit de madrugada que todo mundo já fez
68
+ who, mail = (TEAM[3][0], TEAM[3][1]) if team else (you, "you@example.dev")
69
+ out.append(Commit("f" * 40, mail, who, datetime(year, 9, 12, 4, 52, tzinfo=tz),
70
+ "hotfix: produção caiu, não me pergunte" if lang == "pt" else "hotfix: prod is down, don't ask",
71
+ "api-pagamentos", [(12, 3, "app/services/pix.py")]))
72
+ return out