on-a-pip 0.1.0__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.
on_a_pip-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ryan Cotten / Ghost Developer Studio
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,93 @@
1
+ Metadata-Version: 2.4
2
+ Name: on-a-pip
3
+ Version: 0.1.0
4
+ Summary: PIP: your AI puts YOU on a Performance Improvement Plan. A local, private review of the programmer, generated from their own git history.
5
+ Author-email: Ryan Cotten <hello@ghostdeveloperstudio.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/littlestjames82-sys/pip-pip
8
+ Project-URL: Repository, https://github.com/littlestjames82-sys/pip-pip
9
+ Keywords: git,performance-review,developer-tools,fun,report-card
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Software Development :: Version Control :: Git
15
+ Requires-Python: >=3.9
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # PIP: the performance review where the AI reviews *you*
21
+
22
+ Every AI tool reviews your code. **PIP reviews the programmer.**
23
+
24
+ Every developer keeps a work diary without knowing it: their git history. Every change is in there, with a timestamp and a little note that was supposed to explain it. PIP reads that record, locally, on your own machine, and issues a formal manager-style performance review. With evidence.
25
+
26
+ ```
27
+ pip install on-a-pip
28
+ ```
29
+
30
+ Then, inside any git repository:
31
+
32
+ ```
33
+ on-a-pip
34
+ ```
35
+
36
+ ```
37
+ PERFORMANCE IMPROVEMENT PLAN - Dev Example
38
+ pip-sample | 8 commits reviewed | 2025-10-14 to 2026-11-08
39
+ --------------------------------------------------------------
40
+ Communication F 32.5 ######
41
+ Reliability C 64.4 ############
42
+ Follow-through B 84.3 ################
43
+ Judgment B 83.8 #################
44
+ Consistency D 43.0 ########
45
+ --------------------------------------------------------------
46
+ OVERALL C 61.6
47
+ Meets some expectations. There is a conversation to be had.
48
+ ```
49
+
50
+ (That is a real review of a deliberately terrible sample history. Yours will be different. Possibly worse.)
51
+
52
+ ## What it grades
53
+
54
+ - **Communication.** How many of your commit messages actually say anything. "stuff", "wip" and "asdf" are entered into the record, quoted back at you.
55
+ - **Reliability.** Commits between 10pm and 5am. Commits shipped Friday after 4pm. Reverts. Chains of commits that start with "fix".
56
+ - **Follow-through.** The TODOs still sitting in your code, and how old the oldest one is. A TODO that has been waiting 400 days has seniority.
57
+ - **Judgment.** The spots labelled "temporary", "hack" or "workaround", and how long the oldest one has been load-bearing.
58
+ - **Consistency.** Active days versus silent stretches, longest streak, longest disappearance.
59
+
60
+ Then it does what any good PIP does: it writes you a **30-day improvement plan**, generated from your three weakest categories, and signs off with the only appeal process that has ever worked: improve the record.
61
+
62
+ ## Outputs
63
+
64
+ ```
65
+ on-a-pip ~/some/repo --md review.md --html card.html
66
+ on-a-pip --author "your name" # review one author (default: the most prolific)
67
+ on-a-pip --json # machine-readable review
68
+ ```
69
+
70
+ - The terminal summary above.
71
+ - A full formal review in Markdown: per-category evidence, management notes, the plan, the sign-off.
72
+ - A shareable **report card** in HTML (see `examples/`), made for posting. Every card is different, because every history is different.
73
+
74
+ Sample outputs live in [`examples/`](examples/): a full sample review, a sample report card, and a real report card generated from the Decksmith repository.
75
+
76
+ ## Private by construction
77
+
78
+ PIP runs `git log`, `git grep` and `git blame` on your machine and nothing else. No network, no account, no API key, no telemetry, pure Python standard library. Your history is embarrassing enough without uploading it somewhere.
79
+
80
+ ## Requirements
81
+
82
+ - Python 3.9+
83
+ - git, on your PATH
84
+
85
+ ## Honest notes
86
+
87
+ - The package is called `on-a-pip` because PyPI rejected `pip-pip` as too similar to `pip` itself, which is fair: you do not get to out-pip pip. The tool was going to be `pip install pip-pip`. Now you install the news that you are on one.
88
+ - Grades are deterministic: same history, same review. The formulas are plain arithmetic in one file, `pip_pip.py`, if you want to argue with them.
89
+ - PIP reviews the most prolific author in the repo by default. Use `--author` in shared repos.
90
+
91
+ ## License
92
+
93
+ MIT. Built by [Ghost Developer Studio](https://ghostdeveloperstudio.com).
@@ -0,0 +1,74 @@
1
+ # PIP: the performance review where the AI reviews *you*
2
+
3
+ Every AI tool reviews your code. **PIP reviews the programmer.**
4
+
5
+ Every developer keeps a work diary without knowing it: their git history. Every change is in there, with a timestamp and a little note that was supposed to explain it. PIP reads that record, locally, on your own machine, and issues a formal manager-style performance review. With evidence.
6
+
7
+ ```
8
+ pip install on-a-pip
9
+ ```
10
+
11
+ Then, inside any git repository:
12
+
13
+ ```
14
+ on-a-pip
15
+ ```
16
+
17
+ ```
18
+ PERFORMANCE IMPROVEMENT PLAN - Dev Example
19
+ pip-sample | 8 commits reviewed | 2025-10-14 to 2026-11-08
20
+ --------------------------------------------------------------
21
+ Communication F 32.5 ######
22
+ Reliability C 64.4 ############
23
+ Follow-through B 84.3 ################
24
+ Judgment B 83.8 #################
25
+ Consistency D 43.0 ########
26
+ --------------------------------------------------------------
27
+ OVERALL C 61.6
28
+ Meets some expectations. There is a conversation to be had.
29
+ ```
30
+
31
+ (That is a real review of a deliberately terrible sample history. Yours will be different. Possibly worse.)
32
+
33
+ ## What it grades
34
+
35
+ - **Communication.** How many of your commit messages actually say anything. "stuff", "wip" and "asdf" are entered into the record, quoted back at you.
36
+ - **Reliability.** Commits between 10pm and 5am. Commits shipped Friday after 4pm. Reverts. Chains of commits that start with "fix".
37
+ - **Follow-through.** The TODOs still sitting in your code, and how old the oldest one is. A TODO that has been waiting 400 days has seniority.
38
+ - **Judgment.** The spots labelled "temporary", "hack" or "workaround", and how long the oldest one has been load-bearing.
39
+ - **Consistency.** Active days versus silent stretches, longest streak, longest disappearance.
40
+
41
+ Then it does what any good PIP does: it writes you a **30-day improvement plan**, generated from your three weakest categories, and signs off with the only appeal process that has ever worked: improve the record.
42
+
43
+ ## Outputs
44
+
45
+ ```
46
+ on-a-pip ~/some/repo --md review.md --html card.html
47
+ on-a-pip --author "your name" # review one author (default: the most prolific)
48
+ on-a-pip --json # machine-readable review
49
+ ```
50
+
51
+ - The terminal summary above.
52
+ - A full formal review in Markdown: per-category evidence, management notes, the plan, the sign-off.
53
+ - A shareable **report card** in HTML (see `examples/`), made for posting. Every card is different, because every history is different.
54
+
55
+ Sample outputs live in [`examples/`](examples/): a full sample review, a sample report card, and a real report card generated from the Decksmith repository.
56
+
57
+ ## Private by construction
58
+
59
+ PIP runs `git log`, `git grep` and `git blame` on your machine and nothing else. No network, no account, no API key, no telemetry, pure Python standard library. Your history is embarrassing enough without uploading it somewhere.
60
+
61
+ ## Requirements
62
+
63
+ - Python 3.9+
64
+ - git, on your PATH
65
+
66
+ ## Honest notes
67
+
68
+ - The package is called `on-a-pip` because PyPI rejected `pip-pip` as too similar to `pip` itself, which is fair: you do not get to out-pip pip. The tool was going to be `pip install pip-pip`. Now you install the news that you are on one.
69
+ - Grades are deterministic: same history, same review. The formulas are plain arithmetic in one file, `pip_pip.py`, if you want to argue with them.
70
+ - PIP reviews the most prolific author in the repo by default. Use `--author` in shared repos.
71
+
72
+ ## License
73
+
74
+ MIT. Built by [Ghost Developer Studio](https://ghostdeveloperstudio.com).
@@ -0,0 +1,93 @@
1
+ Metadata-Version: 2.4
2
+ Name: on-a-pip
3
+ Version: 0.1.0
4
+ Summary: PIP: your AI puts YOU on a Performance Improvement Plan. A local, private review of the programmer, generated from their own git history.
5
+ Author-email: Ryan Cotten <hello@ghostdeveloperstudio.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/littlestjames82-sys/pip-pip
8
+ Project-URL: Repository, https://github.com/littlestjames82-sys/pip-pip
9
+ Keywords: git,performance-review,developer-tools,fun,report-card
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Software Development :: Version Control :: Git
15
+ Requires-Python: >=3.9
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # PIP: the performance review where the AI reviews *you*
21
+
22
+ Every AI tool reviews your code. **PIP reviews the programmer.**
23
+
24
+ Every developer keeps a work diary without knowing it: their git history. Every change is in there, with a timestamp and a little note that was supposed to explain it. PIP reads that record, locally, on your own machine, and issues a formal manager-style performance review. With evidence.
25
+
26
+ ```
27
+ pip install on-a-pip
28
+ ```
29
+
30
+ Then, inside any git repository:
31
+
32
+ ```
33
+ on-a-pip
34
+ ```
35
+
36
+ ```
37
+ PERFORMANCE IMPROVEMENT PLAN - Dev Example
38
+ pip-sample | 8 commits reviewed | 2025-10-14 to 2026-11-08
39
+ --------------------------------------------------------------
40
+ Communication F 32.5 ######
41
+ Reliability C 64.4 ############
42
+ Follow-through B 84.3 ################
43
+ Judgment B 83.8 #################
44
+ Consistency D 43.0 ########
45
+ --------------------------------------------------------------
46
+ OVERALL C 61.6
47
+ Meets some expectations. There is a conversation to be had.
48
+ ```
49
+
50
+ (That is a real review of a deliberately terrible sample history. Yours will be different. Possibly worse.)
51
+
52
+ ## What it grades
53
+
54
+ - **Communication.** How many of your commit messages actually say anything. "stuff", "wip" and "asdf" are entered into the record, quoted back at you.
55
+ - **Reliability.** Commits between 10pm and 5am. Commits shipped Friday after 4pm. Reverts. Chains of commits that start with "fix".
56
+ - **Follow-through.** The TODOs still sitting in your code, and how old the oldest one is. A TODO that has been waiting 400 days has seniority.
57
+ - **Judgment.** The spots labelled "temporary", "hack" or "workaround", and how long the oldest one has been load-bearing.
58
+ - **Consistency.** Active days versus silent stretches, longest streak, longest disappearance.
59
+
60
+ Then it does what any good PIP does: it writes you a **30-day improvement plan**, generated from your three weakest categories, and signs off with the only appeal process that has ever worked: improve the record.
61
+
62
+ ## Outputs
63
+
64
+ ```
65
+ on-a-pip ~/some/repo --md review.md --html card.html
66
+ on-a-pip --author "your name" # review one author (default: the most prolific)
67
+ on-a-pip --json # machine-readable review
68
+ ```
69
+
70
+ - The terminal summary above.
71
+ - A full formal review in Markdown: per-category evidence, management notes, the plan, the sign-off.
72
+ - A shareable **report card** in HTML (see `examples/`), made for posting. Every card is different, because every history is different.
73
+
74
+ Sample outputs live in [`examples/`](examples/): a full sample review, a sample report card, and a real report card generated from the Decksmith repository.
75
+
76
+ ## Private by construction
77
+
78
+ PIP runs `git log`, `git grep` and `git blame` on your machine and nothing else. No network, no account, no API key, no telemetry, pure Python standard library. Your history is embarrassing enough without uploading it somewhere.
79
+
80
+ ## Requirements
81
+
82
+ - Python 3.9+
83
+ - git, on your PATH
84
+
85
+ ## Honest notes
86
+
87
+ - The package is called `on-a-pip` because PyPI rejected `pip-pip` as too similar to `pip` itself, which is fair: you do not get to out-pip pip. The tool was going to be `pip install pip-pip`. Now you install the news that you are on one.
88
+ - Grades are deterministic: same history, same review. The formulas are plain arithmetic in one file, `pip_pip.py`, if you want to argue with them.
89
+ - PIP reviews the most prolific author in the repo by default. Use `--author` in shared repos.
90
+
91
+ ## License
92
+
93
+ MIT. Built by [Ghost Developer Studio](https://ghostdeveloperstudio.com).
@@ -0,0 +1,10 @@
1
+ LICENSE
2
+ README.md
3
+ pip_pip.py
4
+ pyproject.toml
5
+ on_a_pip.egg-info/PKG-INFO
6
+ on_a_pip.egg-info/SOURCES.txt
7
+ on_a_pip.egg-info/dependency_links.txt
8
+ on_a_pip.egg-info/entry_points.txt
9
+ on_a_pip.egg-info/top_level.txt
10
+ tests/test_pip_pip.py
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ on-a-pip = pip_pip:main
3
+ pip-pip = pip_pip:main
@@ -0,0 +1 @@
1
+ pip_pip
@@ -0,0 +1,608 @@
1
+ #!/usr/bin/env python3
2
+ """PIP - the Performance Improvement Plan for programmers.
3
+
4
+ Every AI tool reviews your code. PIP reviews *you*.
5
+
6
+ PIP reads a developer's own git history (locally, read-only, nothing is
7
+ uploaded anywhere) and issues a formal, manager-style performance review
8
+ with evidence: commit-message quality, late-night and Friday-afternoon
9
+ habits, reverts, fix chains, TODOs left to grow old, and "temporary" hacks
10
+ that quietly became permanent.
11
+
12
+ Pure Python standard library. No dependencies, no accounts, no network.
13
+
14
+ pip install on-a-pip
15
+ on-a-pip # review the top author of the repo in cwd
16
+ on-a-pip ~/some/repo --md review.md --html card.html
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import argparse
22
+ import html
23
+ import json
24
+ import os
25
+ import re
26
+ import subprocess
27
+ import sys
28
+ from dataclasses import dataclass, field
29
+ from datetime import date, datetime, timedelta, timezone
30
+
31
+ __version__ = "0.1.0"
32
+
33
+ # --------------------------------------------------------------------------
34
+ # git collection (read-only)
35
+ # --------------------------------------------------------------------------
36
+
37
+ RS = "\x1e" # record separator
38
+ FS = "\x1f" # field separator
39
+
40
+
41
+ def _git(repo: str, args: list[str], check: bool = True) -> str:
42
+ proc = subprocess.run(
43
+ ["git", "-C", repo] + args,
44
+ capture_output=True, text=True, encoding="utf-8", errors="replace",
45
+ )
46
+ if check and proc.returncode != 0:
47
+ raise PipError(f"git {' '.join(args[:2])} failed: {proc.stderr.strip()[:200]}")
48
+ return proc.stdout
49
+
50
+
51
+ class PipError(Exception):
52
+ pass
53
+
54
+
55
+ @dataclass
56
+ class Commit:
57
+ sha: str
58
+ author: str
59
+ email: str
60
+ when: datetime # author date, tz-aware (commit's own offset)
61
+ subject: str
62
+ body: str
63
+ added: int = 0
64
+ deleted: int = 0
65
+ files: int = 0
66
+
67
+
68
+ @dataclass
69
+ class Marker:
70
+ kind: str # TODO / FIXME / HACK / TEMP ...
71
+ path: str
72
+ line: int
73
+ text: str
74
+ born: date | None # date the line was introduced (blame), if known
75
+
76
+
77
+ def collect_commits(repo: str, max_commits: int) -> list[Commit]:
78
+ fmt = FS.join(["%H", "%an", "%ae", "%aI", "%s", "%b"]) + RS
79
+ out = _git(repo, ["log", f"--max-count={max_commits}", f"--format={fmt}"])
80
+ commits: list[Commit] = []
81
+ for rec in out.split(RS):
82
+ rec = rec.strip("\n")
83
+ if not rec.strip():
84
+ continue
85
+ parts = rec.split(FS)
86
+ if len(parts) < 6:
87
+ continue
88
+ sha, author, email, iso, subject, body = parts[0], parts[1], parts[2], parts[3], parts[4], FS.join(parts[5:])
89
+ try:
90
+ when = datetime.fromisoformat(iso)
91
+ except ValueError:
92
+ continue
93
+ commits.append(Commit(sha=sha, author=author, email=email, when=when,
94
+ subject=subject.strip(), body=body.strip()))
95
+ return commits
96
+
97
+
98
+ def collect_numstat(repo: str, shas: set[str], cap: int = 5000) -> dict[str, tuple[int, int, int]]:
99
+ """Map sha -> (added, deleted, files). Capped for very large histories."""
100
+ out = _git(repo, ["log", f"--max-count={cap}", "--numstat", "--format=%H"])
101
+ stats: dict[str, tuple[int, int, int]] = {}
102
+ current: str | None = None
103
+ for line in out.splitlines():
104
+ line = line.strip()
105
+ if not line:
106
+ continue
107
+ if re.fullmatch(r"[0-9a-f]{40}", line):
108
+ current = line
109
+ if current in shas:
110
+ stats.setdefault(current, (0, 0, 0))
111
+ continue
112
+ if current is None or current not in shas:
113
+ continue
114
+ parts = line.split("\t")
115
+ if len(parts) >= 3:
116
+ a, d = parts[0], parts[1]
117
+ added = int(a) if a.isdigit() else 0
118
+ deleted = int(d) if d.isdigit() else 0
119
+ pa, pd, pf = stats[current]
120
+ stats[current] = (pa + added, pd + deleted, pf + 1)
121
+ return stats
122
+
123
+
124
+ MARKER_RE = re.compile(r"\b(TODO|FIXME|HACK|XXX|TEMPORARY|TEMP|WORKAROUND)\b[:\s]?(.*)", re.IGNORECASE)
125
+ TEMP_RE = re.compile(r"\b(temp|temporary|hack|workaround|for now|quick fix)\b", re.IGNORECASE)
126
+
127
+
128
+ def collect_markers(repo: str, cap: int = 300, blame_cap: int = 80) -> list[Marker]:
129
+ out = _git(repo, ["grep", "-n", "-I", "-i", "-E",
130
+ r"TODO|FIXME|HACK|XXX|TEMPORARY|WORKAROUND",
131
+ "--", "."], check=False)
132
+ markers: list[Marker] = []
133
+ for line in out.splitlines():
134
+ # path:line:content
135
+ m = re.match(r"(.+?):(\d+):(.*)$", line)
136
+ if not m:
137
+ continue
138
+ path, lno, content = m.group(1), int(m.group(2)), m.group(3).strip()
139
+ km = MARKER_RE.search(content)
140
+ if not km:
141
+ continue
142
+ kind = km.group(1).upper()
143
+ if kind in ("TEMP",):
144
+ kind = "TEMPORARY"
145
+ markers.append(Marker(kind=kind, path=path, line=lno,
146
+ text=content[:140], born=None))
147
+ if len(markers) >= cap:
148
+ break
149
+ # Age the oldest-looking markers first: blame a bounded sample.
150
+ for mk in markers[:blame_cap]:
151
+ bout = _git(repo, ["blame", "-L", f"{mk.line},{mk.line}", "--porcelain",
152
+ "--", mk.path], check=False)
153
+ dm = re.search(r"^author-time (\d+)$", bout, re.MULTILINE)
154
+ if dm:
155
+ mk.born = datetime.fromtimestamp(int(dm.group(1)), tz=timezone.utc).date()
156
+ return markers
157
+
158
+
159
+ # --------------------------------------------------------------------------
160
+ # analysis
161
+ # --------------------------------------------------------------------------
162
+
163
+ VAGUE_WORDS = {
164
+ "stuff", "wip", "fix", "fixes", "fixed", "fixing", "misc", "changes",
165
+ "change", "update", "updates", "updated", "asdf", "tmp", "temp", "test",
166
+ "testing", "work", "working", "more", "minor", "small", "quick", "oops",
167
+ "ugh", "idk", "whatever", "things", "code", "commit", "save", "checkpoint",
168
+ "progress", "done", "final", "finalfix", "realfix", "actualfix", "ok",
169
+ "yes", "no", "a", "aa", "aaa", ".", "..", "...", "lol", "pls", "please",
170
+ }
171
+ FIX_RE = re.compile(r"^(fix|fixes|fixed|fixup|hotfix|bugfix)\b", re.IGNORECASE)
172
+ REVERT_RE = re.compile(r"^revert\b", re.IGNORECASE)
173
+ WIP_RE = re.compile(r"\bwip\b|work in progress", re.IGNORECASE)
174
+
175
+
176
+ def _is_vague(subject: str) -> bool:
177
+ s = subject.strip().lower()
178
+ if len(s) < 8:
179
+ return True
180
+ words = re.findall(r"[a-z0-9]+", s)
181
+ if not words:
182
+ return True
183
+ meaningful = [w for w in words if w not in VAGUE_WORDS]
184
+ return len(meaningful) == 0 or (len(words) <= 2 and len(meaningful) <= 1 and len(s) < 16)
185
+
186
+
187
+ def grade_letter(score: float) -> str:
188
+ if score >= 88:
189
+ return "A"
190
+ if score >= 74:
191
+ return "B"
192
+ if score >= 58:
193
+ return "C"
194
+ if score >= 42:
195
+ return "D"
196
+ return "F"
197
+
198
+
199
+ @dataclass
200
+ class Category:
201
+ name: str
202
+ score: float
203
+ evidence: list[str] = field(default_factory=list)
204
+ praise: str = ""
205
+ concern: str = ""
206
+
207
+ @property
208
+ def letter(self) -> str:
209
+ return grade_letter(self.score)
210
+
211
+
212
+ @dataclass
213
+ class Review:
214
+ repo_name: str
215
+ author: str
216
+ review_date: date
217
+ span_start: date
218
+ span_end: date
219
+ total_commits: int
220
+ categories: list[Category]
221
+ highlights: dict[str, object]
222
+
223
+ @property
224
+ def overall_score(self) -> float:
225
+ return sum(c.score for c in self.categories) / max(1, len(self.categories))
226
+
227
+ @property
228
+ def overall_letter(self) -> str:
229
+ return grade_letter(self.overall_score)
230
+
231
+
232
+ VERDICTS = {
233
+ "A": "Exceeds expectations. Management is as surprised as you are.",
234
+ "B": "Meets and often exceeds expectations. Keep doing most of this.",
235
+ "C": "Meets some expectations. There is a conversation to be had.",
236
+ "D": "Partially meets expectations. This plan exists for a reason.",
237
+ "F": "Does not yet meet expectations. The plan below is not optional.",
238
+ }
239
+
240
+
241
+ def analyze(repo: str, commits_in: list[Commit], markers: list[Marker],
242
+ author_filter: str | None, today: date) -> Review:
243
+ # Pick the employee: explicit filter, else the most prolific author.
244
+ by_author: dict[str, list[Commit]] = {}
245
+ for c in commits_in:
246
+ by_author.setdefault(c.author, []).append(c)
247
+ if author_filter:
248
+ matches = {a: cs for a, cs in by_author.items()
249
+ if author_filter.lower() in a.lower()}
250
+ if not matches:
251
+ raise PipError(f"no commits found for author matching '{author_filter}'")
252
+ author, commits = max(matches.items(), key=lambda kv: len(kv[1]))
253
+ else:
254
+ author, commits = max(by_author.items(), key=lambda kv: len(kv[1]))
255
+ commits = sorted(commits, key=lambda c: c.when)
256
+ total = len(commits)
257
+ if total == 0:
258
+ raise PipError("no commits to review")
259
+
260
+ subjects = [c.subject for c in commits]
261
+ vague = [s for s in subjects if _is_vague(s)]
262
+ with_body = sum(1 for c in commits if len(c.body) >= 3)
263
+ avg_len = sum(len(s) for s in subjects) / total
264
+ night = [c for c in commits if c.when.hour >= 22 or c.when.hour < 5]
265
+ friday_late = [c for c in commits if c.when.weekday() == 4 and c.when.hour >= 16]
266
+ reverts = [c for c in commits if REVERT_RE.match(c.subject)]
267
+ fixes = [c for c in commits if FIX_RE.match(c.subject)]
268
+ wips = [c for c in commits if WIP_RE.search(c.subject)]
269
+ active_days = sorted({c.when.date() for c in commits})
270
+ span_days = max(1, (active_days[-1] - active_days[0]).days + 1)
271
+ # longest streak / gap
272
+ streak = longest = 1
273
+ gap = longest_gap = 0
274
+ for prev, cur in zip(active_days, active_days[1:]):
275
+ d = (cur - prev).days
276
+ if d == 1:
277
+ streak += 1
278
+ else:
279
+ longest = max(longest, streak)
280
+ streak = 1
281
+ gap = d - 1
282
+ longest_gap = max(longest_gap, gap)
283
+ longest = max(longest, streak)
284
+
285
+ # --- Communication -------------------------------------------------
286
+ vague_ratio = len(vague) / total
287
+ body_ratio = with_body / total
288
+ comm_score = 100 - vague_ratio * 110 - (18 if avg_len < 14 else 0) + body_ratio * 10
289
+ comm = Category("Communication", max(0.0, min(100.0, comm_score)))
290
+ comm.evidence.append(
291
+ f"{len(vague)} of {total} commit messages ({vague_ratio:.0%}) say almost nothing "
292
+ f"(average message length: {avg_len:.0f} characters).")
293
+ if vague:
294
+ examples = ", ".join(f'"{v}"' for v in vague[:3])
295
+ comm.evidence.append(f"Entered into the record: {examples}.")
296
+ comm.evidence.append(f"{with_body} of {total} commits ({body_ratio:.0%}) include any explanation beyond the subject line.")
297
+ comm.concern = "Commit messages are the only explanation future maintainers get."
298
+ comm.praise = "When you write a real message, it tends to be a genuinely useful one."
299
+
300
+ # --- Reliability ----------------------------------------------------
301
+ night_ratio = len(night) / total
302
+ revert_ratio = len(reverts) / total
303
+ fix_ratio = len(fixes) / total
304
+ rel_score = 100 - night_ratio * 45 - revert_ratio * 160 - fix_ratio * 35
305
+ rel = Category("Reliability", max(0.0, min(100.0, rel_score)))
306
+ rel.evidence.append(
307
+ f"{len(night)} of {total} commits ({night_ratio:.0%}) were made between 10pm and 5am.")
308
+ rel.evidence.append(
309
+ f"{len(friday_late)} commits landed on a Friday at or after 4pm, the industry's most dangerous hour.")
310
+ rel.evidence.append(
311
+ f"{len(reverts)} commits are reverts ({revert_ratio:.0%}) and {len(fixes)} ({fix_ratio:.0%}) begin with the word 'fix'.")
312
+ rel.concern = "Work shipped tired, or shipped twice, costs the team twice."
313
+ rel.praise = "A low revert habit, where present, is the mark of someone who checks before they ship."
314
+
315
+ # --- Follow-through ---------------------------------------------------
316
+ todos = [m for m in markers if m.kind in ("TODO", "FIXME", "XXX")]
317
+ aged = [m for m in todos if m.born is not None]
318
+ oldest_todo_days = max(((today - m.born).days for m in aged), default=None)
319
+ ft_score = 100 - min(45, len(todos) * 2.5)
320
+ if oldest_todo_days is not None:
321
+ ft_score -= min(35, oldest_todo_days / 365 * 12)
322
+ ft = Category("Follow-through", max(0.0, min(100.0, ft_score)))
323
+ ft.evidence.append(f"{len(todos)} TODO/FIXME notes are still open in the current code.")
324
+ if oldest_todo_days is not None:
325
+ yrs = oldest_todo_days / 365
326
+ ft.evidence.append(
327
+ f"The oldest surviving TODO has been waiting {oldest_todo_days} days ({yrs:.1f} years). It has seniority now.")
328
+ oldest_mk = max(aged, key=lambda m: (today - m.born).days)
329
+ ft.evidence.append(f"Senior TODO on file: {oldest_mk.path}:{oldest_mk.line} - \"{oldest_mk.text[:90]}\"")
330
+ ft.concern = "A TODO is a promise. Old TODOs are promises in default."
331
+ ft.praise = "Every TODO you do close is one the next person never has to meet."
332
+
333
+ # --- Judgment ---------------------------------------------------------
334
+ temps = [m for m in markers if m.kind in ("HACK", "TEMPORARY") or TEMP_RE.search(m.text)]
335
+ aged_temps = [m for m in temps if m.born is not None]
336
+ oldest_temp_days = max(((today - m.born).days for m in aged_temps), default=None)
337
+ jud_score = 92 - min(40, len(temps) * 4) - len(wips) * 1.5
338
+ if oldest_temp_days is not None:
339
+ jud_score -= min(30, oldest_temp_days / 365 * 10)
340
+ jud = Category("Judgment", max(0.0, min(100.0, jud_score)))
341
+ jud.evidence.append(f"{len(temps)} spots in the code are labelled temporary, a hack, or a workaround.")
342
+ if oldest_temp_days is not None:
343
+ jud.evidence.append(
344
+ f"The oldest 'temporary' measure has been in production {oldest_temp_days} days. It is not temporary. It is load-bearing.")
345
+ jud.evidence.append(f"{len(wips)} commits were checked in openly marked as work in progress.")
346
+ jud.concern = "Temporary is the most permanent word in software."
347
+ jud.praise = "Labelling a hack as a hack is honesty many developers skip entirely."
348
+
349
+ # --- Consistency --------------------------------------------------------
350
+ activity_ratio = len(active_days) / span_days
351
+ con_score = 45 + activity_ratio * 65 - min(25, longest_gap / 30)
352
+ con = Category("Consistency", max(0.0, min(100.0, con_score)))
353
+ con.evidence.append(
354
+ f"Active on {len(active_days)} of {span_days} days in the review period ({activity_ratio:.0%}).")
355
+ con.evidence.append(f"Longest streak: {longest} days. Longest disappearance: {longest_gap} days.")
356
+ con.evidence.append(f"Average output on an active day: {total / max(1, len(active_days)):.1f} commits.")
357
+ con.concern = "Bursts followed by silence are harder on a project than a steady pace."
358
+ con.praise = "Showing up regularly is most of the job, and it is the part nobody can automate."
359
+
360
+ highlights: dict[str, object] = {
361
+ "night_commits": len(night), "friday_late": len(friday_late),
362
+ "reverts": len(reverts), "fixes": len(fixes), "vague": len(vague),
363
+ "todos": len(todos), "oldest_todo_days": oldest_todo_days,
364
+ "temps": len(temps), "oldest_temp_days": oldest_temp_days,
365
+ "active_days": len(active_days), "span_days": span_days,
366
+ "longest_streak": longest, "longest_gap": longest_gap,
367
+ "added": sum(c.added for c in commits), "deleted": sum(c.deleted for c in commits),
368
+ }
369
+ return Review(
370
+ repo_name=os.path.basename(os.path.abspath(repo)) or repo,
371
+ author=author, review_date=today,
372
+ span_start=active_days[0], span_end=active_days[-1],
373
+ total_commits=total,
374
+ categories=[comm, rel, ft, jud, con],
375
+ highlights=highlights,
376
+ )
377
+
378
+
379
+ # --------------------------------------------------------------------------
380
+ # the improvement plan (generated from the weakest categories)
381
+ # --------------------------------------------------------------------------
382
+
383
+ PLAN_ACTIONS: dict[str, list[str]] = {
384
+ "Communication": [
385
+ "Every commit message must complete the sentence: 'This change will...' If it cannot, the commit is not ready.",
386
+ "The words 'stuff', 'wip', 'misc' and 'fix fix fix' are retired, effective immediately.",
387
+ "Commits touching more than one file get a body. Two lines minimum. Future you is the audience.",
388
+ ],
389
+ "Reliability": [
390
+ "No merges after 10pm without sleeping on it first. The code will keep. The bug you are about to write will too.",
391
+ "Friday after 4pm is for reading code, not shipping it.",
392
+ "Before any commit whose message starts with 'fix', write down what the first attempt missed.",
393
+ ],
394
+ "Follow-through": [
395
+ "Pick the five oldest TODOs. Close them, convert them to tracked issues, or delete them and own the decision.",
396
+ "New rule: a TODO without a date and a name is litter. Date and name, every time.",
397
+ "One TODO closed per week, minimum, until the backlog is younger than you are.",
398
+ ],
399
+ "Judgment": [
400
+ "Every 'temporary' fix gets an expiry date in the comment. When the date passes, it gets reviewed first, not last.",
401
+ "Count the hacks monthly. The number going down is the goal; the number existing is not the shame.",
402
+ "No new workaround merges without a note explaining what the real fix would take.",
403
+ ],
404
+ "Consistency": [
405
+ "Small and daily beats heroic and monthly. Protect the streak, shorten the silences.",
406
+ "End each session by leaving the next step written down, so returning is easy.",
407
+ "If a gap is coming (holiday, life), say so in a commit. Silence reads worse than absence.",
408
+ ],
409
+ }
410
+
411
+
412
+ def build_plan(review: Review) -> list[tuple[str, list[str]]]:
413
+ weakest = sorted(review.categories, key=lambda c: c.score)[:3]
414
+ return [(c.name, PLAN_ACTIONS[c.name]) for c in weakest]
415
+
416
+
417
+ # --------------------------------------------------------------------------
418
+ # renderers
419
+ # --------------------------------------------------------------------------
420
+
421
+ def render_terminal(review: Review) -> str:
422
+ lines = []
423
+ lines.append("")
424
+ lines.append(f" PERFORMANCE IMPROVEMENT PLAN - {review.author}")
425
+ lines.append(f" {review.repo_name} | {review.total_commits} commits reviewed | {review.span_start} to {review.span_end}")
426
+ lines.append(" " + "-" * 62)
427
+ for c in review.categories:
428
+ bar = "#" * int(c.score / 5)
429
+ lines.append(f" {c.name:<16} {c.letter} {c.score:5.1f} {bar}")
430
+ lines.append(" " + "-" * 62)
431
+ lines.append(f" OVERALL {review.overall_letter} {review.overall_score:5.1f}")
432
+ lines.append(f" {VERDICTS[review.overall_letter]}")
433
+ lines.append("")
434
+ lines.append(" This review was generated locally from your own git history.")
435
+ lines.append(" Nothing left this machine. Management has seen enough anyway.")
436
+ lines.append("")
437
+ return "\n".join(lines)
438
+
439
+
440
+ def render_markdown(review: Review) -> str:
441
+ out = []
442
+ out.append("# PERFORMANCE IMPROVEMENT PLAN")
443
+ out.append("")
444
+ out.append(f"**Employee:** {review.author} ")
445
+ out.append(f"**Project reviewed:** {review.repo_name} ")
446
+ out.append(f"**Review period:** {review.span_start.isoformat()} to {review.span_end.isoformat()} ")
447
+ out.append(f"**Commits examined:** {review.total_commits} ")
448
+ out.append(f"**Review date:** {review.review_date.isoformat()} ")
449
+ out.append("**Reviewer:** Management (PIP, running locally on the employee's own machine)")
450
+ out.append("")
451
+ out.append(f"## Overall assessment: {review.overall_letter} ({review.overall_score:.0f}/100)")
452
+ out.append("")
453
+ out.append(f"*{VERDICTS[review.overall_letter]}*")
454
+ out.append("")
455
+ out.append("This review is based entirely on the employee's own git history, "
456
+ "the work diary every programmer keeps without meaning to. "
457
+ "All findings below are drawn from that record. No code left this machine "
458
+ "in the preparation of this document; the evidence was already here.")
459
+ for c in review.categories:
460
+ out.append("")
461
+ out.append(f"## {c.name}: {c.letter} ({c.score:.0f}/100)")
462
+ out.append("")
463
+ for e in c.evidence:
464
+ out.append(f"- {e}")
465
+ out.append("")
466
+ out.append(f"**Management notes:** {c.concern} {c.praise}")
467
+ out.append("")
468
+ out.append("## 30-day improvement plan")
469
+ out.append("")
470
+ out.append("The following actions address the lowest-scoring areas. "
471
+ "Progress will be assessed by re-running this review, which is to say, "
472
+ "by the record itself.")
473
+ for name, actions in build_plan(review):
474
+ out.append("")
475
+ out.append(f"### {name}")
476
+ for i, a in enumerate(actions, 1):
477
+ out.append(f"{i}. {a}")
478
+ out.append("")
479
+ out.append("## Sign-off")
480
+ out.append("")
481
+ out.append("By continuing to commit, the employee acknowledges receipt of this plan. "
482
+ "Appeals may be filed by improving the record.")
483
+ out.append("")
484
+ out.append("Signed, ")
485
+ out.append("**Management** ")
486
+ out.append("*PIP - pip install on-a-pip*")
487
+ out.append("")
488
+ return "\n".join(out)
489
+
490
+
491
+ GRADE_COLORS = {"A": "#1d9e62", "B": "#5da423", "C": "#d9a400", "D": "#e07b24", "F": "#d43a2f"}
492
+
493
+
494
+ def render_html(review: Review) -> str:
495
+ rows = ""
496
+ for c in review.categories:
497
+ color = GRADE_COLORS[c.letter]
498
+ rows += (
499
+ f'<div class="row"><span class="cat">{html.escape(c.name)}</span>'
500
+ f'<span class="grade" style="background:{color}">{c.letter}</span>'
501
+ f'<span class="ev">{html.escape(c.evidence[0])}</span></div>\n'
502
+ )
503
+ overall_color = GRADE_COLORS[review.overall_letter]
504
+ return f"""<!DOCTYPE html>
505
+ <html lang="en"><head><meta charset="utf-8">
506
+ <title>PIP Report Card - {html.escape(review.author)}</title>
507
+ <style>
508
+ body {{ font-family: Georgia, 'Times New Roman', serif; background:#f2efe9; margin:0; padding:32px 16px; }}
509
+ .card {{ max-width:680px; margin:0 auto; background:#fffdf7; border:2px solid #222; padding:28px 32px; box-shadow:6px 6px 0 #222; }}
510
+ h1 {{ font-size:22px; letter-spacing:2px; margin:0 0 4px; text-transform:uppercase; }}
511
+ .sub {{ color:#555; font-size:13px; margin-bottom:18px; }}
512
+ .overall {{ display:flex; align-items:center; gap:18px; border-top:2px solid #222; border-bottom:2px solid #222; padding:14px 0; margin-bottom:14px; }}
513
+ .big {{ font-size:64px; font-weight:bold; color:#fff; width:96px; height:96px; display:flex; align-items:center; justify-content:center; background:{overall_color}; border-radius:8px; }}
514
+ .verdict {{ font-style:italic; font-size:16px; }}
515
+ .row {{ display:flex; align-items:flex-start; gap:12px; padding:9px 0; border-bottom:1px dotted #bbb; }}
516
+ .cat {{ width:130px; font-weight:bold; font-size:14px; padding-top:3px; }}
517
+ .grade {{ color:#fff; font-weight:bold; width:28px; height:28px; border-radius:50%; display:flex; align-items:center; justify-content:center; flex:none; }}
518
+ .ev {{ font-size:13px; color:#333; }}
519
+ .foot {{ margin-top:18px; font-size:12px; color:#777; text-align:center; }}
520
+ </style></head><body>
521
+ <div class="card">
522
+ <h1>Performance Improvement Plan</h1>
523
+ <div class="sub">Employee: {html.escape(review.author)} &nbsp;|&nbsp; Project: {html.escape(review.repo_name)} &nbsp;|&nbsp;
524
+ {review.total_commits} commits reviewed &nbsp;|&nbsp; {review.span_start.isoformat()} to {review.span_end.isoformat()}</div>
525
+ <div class="overall"><div class="big">{review.overall_letter}</div>
526
+ <div class="verdict">"{VERDICTS[review.overall_letter]}"</div></div>
527
+ {rows}
528
+ <div class="foot">Generated locally by PIP from the employee's own git history. Nothing was uploaded.<br>
529
+ pip install on-a-pip</div>
530
+ </div></body></html>
531
+ """
532
+
533
+
534
+ def review_to_json(review: Review) -> dict:
535
+ return {
536
+ "tool": "on-a-pip", "version": __version__,
537
+ "repo": review.repo_name, "author": review.author,
538
+ "review_date": review.review_date.isoformat(),
539
+ "period": [review.span_start.isoformat(), review.span_end.isoformat()],
540
+ "total_commits": review.total_commits,
541
+ "overall": {"letter": review.overall_letter, "score": round(review.overall_score, 1)},
542
+ "categories": [
543
+ {"name": c.name, "letter": c.letter, "score": round(c.score, 1), "evidence": c.evidence}
544
+ for c in review.categories
545
+ ],
546
+ "highlights": {k: v for k, v in review.highlights.items()},
547
+ }
548
+
549
+
550
+ # --------------------------------------------------------------------------
551
+ # main
552
+ # --------------------------------------------------------------------------
553
+
554
+ def main(argv: list[str] | None = None) -> int:
555
+ ap = argparse.ArgumentParser(
556
+ prog="on-a-pip",
557
+ description="PIP: a formal performance review of the programmer, "
558
+ "generated locally from their own git history.")
559
+ ap.add_argument("repo", nargs="?", default=".", help="path to a git repository (default: current directory)")
560
+ ap.add_argument("--author", help="review only commits by authors matching this text (default: most prolific author)")
561
+ ap.add_argument("--max-commits", type=int, default=10000, help="cap on commits examined (default 10000)")
562
+ ap.add_argument("--md", metavar="FILE", help="write the full review as Markdown")
563
+ ap.add_argument("--html", metavar="FILE", help="write the shareable report card as HTML")
564
+ ap.add_argument("--json", action="store_true", help="print the review as JSON instead of the summary")
565
+ ap.add_argument("--version", action="version", version=f"on-a-pip {__version__}")
566
+ args = ap.parse_args(argv)
567
+
568
+ repo = os.path.abspath(args.repo)
569
+ try:
570
+ inside = _git(repo, ["rev-parse", "--is-inside-work-tree"], check=False).strip()
571
+ if inside != "true":
572
+ raise PipError(f"{args.repo} is not a git repository")
573
+ commits = collect_commits(repo, args.max_commits)
574
+ if not commits:
575
+ raise PipError("this repository has no commits yet. Management cannot review potential.")
576
+ stats = collect_numstat(repo, {c.sha for c in commits})
577
+ for c in commits:
578
+ if c.sha in stats:
579
+ c.added, c.deleted, c.files = stats[c.sha]
580
+ markers = collect_markers(repo)
581
+ review = analyze(repo, commits, markers, args.author, date.today())
582
+ except PipError as e:
583
+ print(f"on-a-pip: {e}", file=sys.stderr)
584
+ return 2
585
+ except FileNotFoundError:
586
+ print("on-a-pip: git was not found on this machine", file=sys.stderr)
587
+ return 2
588
+
589
+ if args.json:
590
+ print(json.dumps(review_to_json(review), indent=2, default=str))
591
+ else:
592
+ print(render_terminal(review))
593
+ if args.md:
594
+ with open(args.md, "w", encoding="utf-8") as f:
595
+ f.write(render_markdown(review))
596
+ print(f"Full review written to {args.md}")
597
+ if args.html:
598
+ with open(args.html, "w", encoding="utf-8") as f:
599
+ f.write(render_html(review))
600
+ print(f"Report card written to {args.html}")
601
+ if review.total_commits < 10:
602
+ print("Note: fewer than 10 commits reviewed. Management is extrapolating, "
603
+ "the way management does.", file=sys.stderr)
604
+ return 0
605
+
606
+
607
+ if __name__ == "__main__":
608
+ raise SystemExit(main())
@@ -0,0 +1,32 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "on-a-pip"
7
+ version = "0.1.0"
8
+ description = "PIP: your AI puts YOU on a Performance Improvement Plan. A local, private review of the programmer, generated from their own git history."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "Ryan Cotten", email = "hello@ghostdeveloperstudio.com" }]
13
+ keywords = ["git", "performance-review", "developer-tools", "fun", "report-card"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Developers",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Programming Language :: Python :: 3",
19
+ "Topic :: Software Development :: Version Control :: Git",
20
+ ]
21
+ dependencies = []
22
+
23
+ [project.urls]
24
+ Homepage = "https://github.com/littlestjames82-sys/pip-pip"
25
+ Repository = "https://github.com/littlestjames82-sys/pip-pip"
26
+
27
+ [project.scripts]
28
+ on-a-pip = "pip_pip:main"
29
+ pip-pip = "pip_pip:main"
30
+
31
+ [tool.setuptools]
32
+ py-modules = ["pip_pip"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,177 @@
1
+ """Tests for pip-pip, built on synthetic git repos with scripted habits.
2
+
3
+ The repos are constructed with exact commit counts, hours, weekdays and
4
+ message quality, so the expected metrics are known answers, not guesses.
5
+ """
6
+ import json
7
+ import os
8
+ import subprocess
9
+ import sys
10
+ import tempfile
11
+ import unittest
12
+ from datetime import date, datetime, time, timedelta, timezone
13
+
14
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
15
+ import pip_pip # noqa: E402
16
+
17
+ UTC = timezone.utc
18
+
19
+
20
+ def _run(repo, *args, env_extra=None):
21
+ env = dict(os.environ)
22
+ if env_extra:
23
+ env.update(env_extra)
24
+ subprocess.run(["git", "-C", repo] + list(args), check=True,
25
+ capture_output=True, text=True, env=env)
26
+
27
+
28
+ def make_repo(path):
29
+ os.makedirs(path)
30
+ _run(path, "init", "-q")
31
+ _run(path, "config", "user.name", "Dev Example")
32
+ _run(path, "config", "user.email", "dev@example.com")
33
+ _run(path, "config", "commit.gpgsign", "false")
34
+
35
+
36
+ def commit(repo, when, subject, body="", files=None, append=None, author=None):
37
+ if files:
38
+ for name, content in files.items():
39
+ fp = os.path.join(repo, name)
40
+ os.makedirs(os.path.dirname(fp), exist_ok=True) if os.path.dirname(name) else None
41
+ with open(fp, "w") as f:
42
+ f.write(content)
43
+ if append:
44
+ for name, content in append.items():
45
+ with open(os.path.join(repo, name), "a") as f:
46
+ f.write(content)
47
+ _run(repo, "add", "-A")
48
+ iso = when.isoformat()
49
+ env = {"GIT_AUTHOR_DATE": iso, "GIT_COMMITTER_DATE": iso}
50
+ if author:
51
+ env["GIT_AUTHOR_NAME"] = author
52
+ args = ["commit", "-q", "-m", subject]
53
+ if body:
54
+ args += ["-m", body]
55
+ _run(repo, *args, env_extra=env)
56
+
57
+
58
+ def at(days_ago, hour, minute=0):
59
+ d = date.today() - timedelta(days=days_ago)
60
+ return datetime.combine(d, time(hour, minute), tzinfo=UTC)
61
+
62
+
63
+ def friday_at(days_ago, hour):
64
+ d = date.today() - timedelta(days=days_ago)
65
+ while d.weekday() != 4:
66
+ d -= timedelta(days=1)
67
+ return datetime.combine(d, time(hour, 30), tzinfo=UTC)
68
+
69
+
70
+ def review_of(repo):
71
+ commits = pip_pip.collect_commits(repo, 10000)
72
+ stats = pip_pip.collect_numstat(repo, {c.sha for c in commits})
73
+ for c in commits:
74
+ if c.sha in stats:
75
+ c.added, c.deleted, c.files = stats[c.sha]
76
+ markers = pip_pip.collect_markers(repo)
77
+ return pip_pip.analyze(repo, commits, markers, None, date.today())
78
+
79
+
80
+ class MessyDevTest(unittest.TestCase):
81
+ @classmethod
82
+ def setUpClass(cls):
83
+ cls.tmp = tempfile.mkdtemp()
84
+ cls.repo = os.path.join(cls.tmp, "messy")
85
+ make_repo(cls.repo)
86
+ commit(cls.repo, at(400, 10), "initial commit with project scaffold and readme",
87
+ files={"app.py": "# TODO: refactor this someday\nprint('v1')\n"})
88
+ commit(cls.repo, at(300, 23, 30), "stuff", append={"app.py": "print('more')\n"})
89
+ commit(cls.repo, at(299, 1, 15), "wip", append={"app.py": "print('even more')\n"})
90
+ commit(cls.repo, friday_at(200, 17), "fix", append={"app.py": "print('friday')\n"})
91
+ commit(cls.repo, at(198, 11), 'Revert "fix"', append={"app.py": "print('undo')\n"})
92
+ commit(cls.repo, at(100, 14), "add temporary workaround for api response parsing",
93
+ append={"app.py": "# temporary fix until the real API lands\nprint('parse')\n"})
94
+ commit(cls.repo, at(50, 9), "asdf", append={"app.py": "print('x')\n"})
95
+ commit(cls.repo, at(10, 15), "implement user settings page with validation and tests",
96
+ body="Adds the settings form, server validation, and tests.",
97
+ append={"app.py": "print('settings')\n"})
98
+ cls.review = review_of(cls.repo)
99
+
100
+ def test_known_counts(self):
101
+ h = self.review.highlights
102
+ self.assertEqual(self.review.total_commits, 8)
103
+ self.assertEqual(h["vague"], 5)
104
+ self.assertEqual(h["night_commits"], 2)
105
+ self.assertEqual(h["friday_late"], 1)
106
+ self.assertEqual(h["reverts"], 1)
107
+ self.assertEqual(h["fixes"], 1)
108
+
109
+ def test_todo_and_temp_ages(self):
110
+ h = self.review.highlights
111
+ self.assertGreaterEqual(h["todos"], 1)
112
+ self.assertGreaterEqual(h["oldest_todo_days"], 390)
113
+ self.assertGreaterEqual(h["temps"], 1)
114
+ self.assertGreaterEqual(h["oldest_temp_days"], 95)
115
+
116
+ def test_communication_is_poor(self):
117
+ comm = next(c for c in self.review.categories if c.name == "Communication")
118
+ self.assertLess(comm.score, 45)
119
+ self.assertIn(comm.letter, ("D", "F"))
120
+
121
+ def test_outputs_render(self):
122
+ md = pip_pip.render_markdown(self.review)
123
+ self.assertIn("PERFORMANCE IMPROVEMENT PLAN", md)
124
+ self.assertIn("30-day improvement plan", md)
125
+ card = pip_pip.render_html(self.review)
126
+ self.assertIn("Performance Improvement Plan", card)
127
+ data = pip_pip.review_to_json(self.review)
128
+ self.assertEqual(data["total_commits"], 8)
129
+
130
+
131
+ class ProfessionalDevTest(unittest.TestCase):
132
+ @classmethod
133
+ def setUpClass(cls):
134
+ cls.tmp = tempfile.mkdtemp()
135
+ cls.repo = os.path.join(cls.tmp, "pro")
136
+ make_repo(cls.repo)
137
+ topics = [
138
+ "add rate limiting to the public api endpoints",
139
+ "refactor invoice totals into a dedicated module",
140
+ "document the deployment rollback procedure",
141
+ "add integration tests for the checkout flow",
142
+ "remove the deprecated v1 search endpoint",
143
+ "improve error messages for failed payments",
144
+ ]
145
+ for i, subject in enumerate(topics):
146
+ commit(cls.repo, at(60 - i * 9, 11), subject,
147
+ body="Explains what changed and why, for the next reader." if i % 2 == 0 else "",
148
+ files={f"mod{i}.py": f"# module {i}\nVALUE = {i}\n"} if i == 0 else None,
149
+ append={"mod0.py": f"# line {i}\n"} if i > 0 else None)
150
+ cls.review = review_of(cls.repo)
151
+
152
+ def test_communication_is_strong(self):
153
+ comm = next(c for c in self.review.categories if c.name == "Communication")
154
+ self.assertEqual(comm.letter, "A")
155
+ self.assertEqual(self.review.highlights["vague"], 0)
156
+
157
+ def test_reliability_is_strong(self):
158
+ rel = next(c for c in self.review.categories if c.name == "Reliability")
159
+ self.assertEqual(rel.letter, "A")
160
+ self.assertEqual(self.review.highlights["night_commits"], 0)
161
+
162
+ def test_overall(self):
163
+ self.assertIn(self.review.overall_letter, ("A", "B"))
164
+
165
+
166
+ class CliTest(unittest.TestCase):
167
+ def test_not_a_repo(self):
168
+ with tempfile.TemporaryDirectory() as d:
169
+ proc = subprocess.run(
170
+ [sys.executable, os.path.join(os.path.dirname(__file__), "..", "pip_pip.py"), d],
171
+ capture_output=True, text=True)
172
+ self.assertEqual(proc.returncode, 2)
173
+ self.assertIn("not a git repository", proc.stderr)
174
+
175
+
176
+ if __name__ == "__main__":
177
+ unittest.main()