-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommit-crimes.js
More file actions
351 lines (317 loc) · 11.1 KB
/
Copy pathcommit-crimes.js
File metadata and controls
351 lines (317 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
#!/usr/bin/env node
/**
* commit-crimes — every repo hides crimes. expose yours.
* Zero dependencies. Nothing leaves your machine. No AI, no API keys.
*/
'use strict';
const { execFileSync } = require('child_process');
const VERSION = '1.0.0';
/* ---------------------------------- args --------------------------------- */
const argv = process.argv.slice(2);
const has = (f) => argv.includes(f);
const optVal = (f) => {
const i = argv.indexOf(f);
return i !== -1 && argv[i + 1] ? argv[i + 1] : null;
};
if (has('-h') || has('--help')) {
console.log(`
commit-crimes v${VERSION} — every repo hides crimes. expose yours.
Usage: run it inside any git repository
npx commit-crimes [options]
Options
--last <n> only judge the last n commits
--author <s> only judge commits whose author matches s
--no-anim skip the courtroom drama, print instantly
--no-color plain output
-v, --version print version
-h, --help this file, exhibit A
`);
process.exit(0);
}
if (has('-v') || has('--version')) {
console.log(VERSION);
process.exit(0);
}
const ANIM = !has('--no-anim') && process.stdout.isTTY;
const COLOR =
!has('--no-color') &&
!process.env.NO_COLOR &&
(process.stdout.isTTY || process.env.FORCE_COLOR);
/* --------------------------------- style --------------------------------- */
const paint = (code) => (s) => (COLOR ? `\x1b[${code}m${s}\x1b[0m` : String(s));
const red = paint('31;1');
const yellow = paint('33;1');
const green = paint('32;1');
const cyan = paint('36');
const gray = paint('90');
const bold = paint('1');
const dim = paint('2');
const invRed = paint('41;97;1');
const sleep = (ms) => (ANIM ? new Promise((r) => setTimeout(r, ms)) : Promise.resolve());
/* ---------------------------------- git ---------------------------------- */
function git(args) {
return execFileSync('git', args, {
encoding: 'utf8',
maxBuffer: 1024 * 1024 * 128,
stdio: ['ignore', 'pipe', 'ignore'],
});
}
function loadCommits() {
try {
git(['rev-parse', '--is-inside-work-tree']);
} catch {
console.error(red(' ✖ Not a git repository.') + gray(' Your crimes are elsewhere.'));
process.exit(1);
}
const logArgs = ['log', '--no-merges', '--pretty=format:%H%x1f%an%x1f%at%x1f%s%x1e'];
const last = optVal('--last');
if (last && /^\d+$/.test(last)) logArgs.splice(1, 0, `-${last}`);
const author = optVal('--author');
if (author) logArgs.push(`--author=${author}`);
let raw = '';
try {
raw = git(logArgs);
} catch {
/* empty repo — handled by caller */
}
return raw
.split('\x1e')
.map((r) => r.trim())
.filter(Boolean)
.map((r) => {
const [hash, an, at, subject = ''] = r.split('\x1f');
return { hash, author: an, date: new Date(Number(at) * 1000), subject };
});
}
/* --------------------------------- crimes -------------------------------- */
const RX = {
fix: /(^|[^a-z])fix(es|ed|ing|up)?([^a-z]|$)/i,
wip: /(^|[^a-z])wip([^a-z]|$)/i,
lazy: /^(update[sd]?|changes?|stuff|misc|minor|edits?|tweaks?|more|cleanup|\.{1,3})$/i,
scream: /^[^a-z]*$/,
swear: /(^|[^a-z])(damn|hell|crap|wtf|ffs|sh[i1]t|f[u*]ck\w*)/i,
desperate:
/^(please work|it works?|finally|works now|why|no+|yes|help|test|testing|idk|whatever|ugh+)[.!?]*$/i,
mash: /^[asdfghjkl;]{4,}$/i,
};
const CRIMES = [
{
id: 'fixer',
title: 'The Serial Fixer',
match: (c) => RX.fix.test(c.subject),
quip: (n, t) => `${n} of ${t} commits claim to "fix" something. The bug remains at large.`,
weight: 1,
},
{
id: 'wip',
title: 'Work-In-Progress Convict',
match: (c) => RX.wip.test(c.subject),
quip: (n) => `"wip" ×${n}. The progress was never finished. It never is.`,
weight: 2,
},
{
id: 'lazy',
title: 'The Minimalist',
match: (c) => RX.lazy.test(c.subject.trim()) || c.subject.trim().length <= 2,
quip: (n) => `${n} commit messages written with the passion of a wet napkin.`,
weight: 2,
},
{
id: 'night',
title: 'The Night Crawler',
match: (c) => c.date.getHours() < 5,
quip: (n) => `${n} commits between midnight and 5am. Sleep is for the merged.`,
weight: 1,
},
{
id: 'friday',
title: 'The Friday Gambler',
match: (c) => c.date.getDay() === 5 && c.date.getHours() >= 16,
quip: (n) => `${n} late-Friday commits. Bold. Reckless. Someone's weekend paid for it.`,
weight: 3,
},
{
id: 'scream',
title: 'The Screamer',
match: (c) =>
c.subject.length >= 5 &&
/[A-Z].*[A-Z]/.test(c.subject) &&
RX.scream.test(c.subject),
quip: (n) => `${n} ALL-CAPS messages. WE HEARD YOU THE FIRST TIME.`,
weight: 2,
},
{
id: 'swear',
title: 'The Potty Mouth',
match: (c) => RX.swear.test(c.subject),
quip: (n) => `${n} messages that need a swear jar. The jar is full.`,
weight: 2,
},
{
id: 'novelist',
title: 'The Novelist',
match: (c) => c.subject.length > 80,
quip: (n) => `${n} subject lines over 80 chars. Save it for the memoir.`,
weight: 1,
},
{
id: 'desperate',
title: 'The Desperado',
match: (c) => RX.desperate.test(c.subject.trim()) || RX.mash.test(c.subject.trim()),
quip: (n) => `${n} commits begging the compiler for mercy. It felt nothing.`,
weight: 3,
},
];
function findGroundhog(commits) {
const seen = new Map();
for (const c of commits) {
const k = c.subject.trim().toLowerCase();
if (!k) continue;
seen.set(k, (seen.get(k) || 0) + 1);
}
let msg = null;
let n = 0;
for (const [k, v] of seen) {
if (v > n) {
n = v;
msg = k;
}
}
return n >= 3 ? { msg, n } : null;
}
/* --------------------------------- layout -------------------------------- */
const W = 60;
const stripAnsi = (s) => s.replace(/\x1b\[[0-9;]*m/g, '');
const boxTop = () => `╔${'═'.repeat(W)}╗`;
const boxMid = () => `╠${'═'.repeat(W)}╣`;
const boxBot = () => `╚${'═'.repeat(W)}╝`;
const row = (s = '') => {
const pad = Math.max(0, W - 2 - stripAnsi(s).length);
return `║ ${s}${' '.repeat(pad)} ║`;
};
const center = (s) => {
const total = W - 2 - stripAnsi(s).length;
const l = Math.max(0, Math.floor(total / 2));
const r = Math.max(0, total - l);
return `║ ${' '.repeat(l)}${s}${' '.repeat(r)} ║`;
};
function grade(ratio) {
if (ratio === 0) return ['S', green, 'Suspiciously clean. We are watching you.'];
if (ratio < 0.08) return ['A', green, 'A few misdemeanors. Probation granted.'];
if (ratio < 0.2) return ['B', cyan, 'Petty crimes. The jury smirked.'];
if (ratio < 0.38) return ['C', yellow, 'Habitual offender. Your keyboard testified against you.'];
if (ratio < 0.6) return ['D', red, 'The evidence rack collapsed under the weight.'];
return ['F', red, 'A career criminal. Museums will study this repo.'];
}
/* ---------------------------------- main ---------------------------------- */
(async function main() {
const commits = loadCommits();
if (commits.length === 0) {
console.log(gray('\n 0 commits found. The perfect crime… is committing nothing at all.\n'));
return;
}
let repoName = 'this repository';
try {
repoName = git(['rev-parse', '--show-toplevel']).trim().split(/[\\/]/).pop();
} catch {}
const byHash = new Map(commits.map((c) => [c.hash, c]));
const authors = new Set(commits.map((c) => c.author));
const days = Math.max(
1,
Math.round((commits[0].date - commits[commits.length - 1].date) / 864e5)
);
console.log('');
console.log(bold(` ⚖ COMMIT CRIMES — case file: ${cyan(repoName)}`));
console.log(
gray(
` ${commits.length} commits · ${authors.size} suspect${authors.size > 1 ? 's' : ''} · ${days} day${days > 1 ? 's' : ''} of activity`
)
);
console.log(gray(' nothing leaves your machine. the shame stays local.\n'));
await sleep(700);
/* detect */
const guiltySet = new Set();
const verdicts = [];
for (const crime of CRIMES) {
const hits = commits.filter(crime.match);
if (hits.length === 0) continue;
hits.forEach((c) => guiltySet.add(c.hash));
const worst = hits[Math.floor(Math.random() * hits.length)];
verdicts.push({ crime, hits, worst });
}
const groundhog = findGroundhog(commits);
if (verdicts.length === 0 && !groundhog) {
console.log(green(' ✔ ACQUITTED. ') + 'Not a single charge sticks.');
console.log(gray(' Frankly, nobody will believe you. Screenshot it anyway.\n'));
return;
}
/* read the charges */
verdicts.sort((a, b) => b.hits.length * b.crime.weight - a.hits.length * a.crime.weight);
for (const v of verdicts) {
const dashes = '─'.repeat(Math.max(1, 34 - v.crime.title.length));
console.log(
` ${invRed(' GUILTY ')} ${bold(v.crime.title)} ${gray(dashes)} ${red(
v.hits.length + ' count' + (v.hits.length > 1 ? 's' : '')
)}`
);
console.log(
gray(` exhibit: ${JSON.stringify(v.worst.subject.slice(0, 46))} — ${v.worst.author}`)
);
console.log(dim(` ${v.crime.quip(v.hits.length, commits.length)}`));
console.log('');
await sleep(650);
}
if (groundhog) {
console.log(
` ${invRed(' GUILTY ')} ${bold('Groundhog Day')} ${gray('─'.repeat(21))} ${red(
groundhog.n + ' counts'
)}`
);
console.log(
gray(
` exhibit: ${JSON.stringify(groundhog.msg.slice(0, 46))} — committed ${groundhog.n} separate times`
)
);
console.log(dim(' Same message. Same hope. Same result.'));
console.log('');
await sleep(650);
}
/* verdict card */
const crimeScore = verdicts.reduce((s, v) => s + v.hits.length * v.crime.weight, 0);
const ratio = Math.min(1, crimeScore / (commits.length * 2));
const [g, gColor, gLine] = grade(ratio);
const byAuthor = new Map();
for (const v of verdicts)
for (const c of v.hits) byAuthor.set(c.author, (byAuthor.get(c.author) || 0) + 1);
const prime = [...byAuthor.entries()].sort((a, b) => b[1] - a[1])[0];
const byHour = new Array(24).fill(0);
for (const h of guiltySet) {
const c = byHash.get(h);
if (c) byHour[c.date.getHours()]++;
}
const worstHour = byHour.indexOf(Math.max(...byHour));
await sleep(400);
console.log(gray(' the jury deliberates…'));
await sleep(1100);
const totalCharges = verdicts.length + (groundhog ? 1 : 0);
console.log('');
console.log(' ' + boxTop());
console.log(' ' + center(bold('CRIMINAL RECORD')));
console.log(' ' + center(gray(repoName)));
console.log(' ' + boxMid());
console.log(' ' + center(`GRADE: ${gColor(g)}`));
console.log(' ' + center(dim(gLine)));
console.log(' ' + boxMid());
console.log(' ' + row(`charges ${bold(String(totalCharges))}`));
console.log(' ' + row(`guilty commits ${bold(String(guiltySet.size))} of ${commits.length}`));
if (prime && authors.size > 1)
console.log(' ' + row(`prime suspect ${bold(prime[0].slice(0, 30))} (${prime[1]} offenses)`));
if (guiltySet.size > 0)
console.log(
' ' + row(`crime hour ${bold(String(worstHour).padStart(2, '0') + ':00')} — most offenses`)
);
console.log(' ' + boxMid());
console.log(' ' + center(gray('expose a friend: npx commit-crimes')));
console.log(' ' + boxBot());
console.log('');
})();