unslop-design 1.11.0 → 1.13.0
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.
- package/README.md +44 -5
- package/bin/unslop.mjs +74 -0
- package/hooks/unslop-hook.mjs +69 -28
- package/package.json +1 -1
- package/scripts/unslop-score.py +55 -4
package/README.md
CHANGED
|
@@ -212,6 +212,18 @@ python3 scripts/unslop-score.py examples/swiftui/after # 100/100
|
|
|
212
212
|
The SwiftUI folders also hold the HTML mock of each state at iPhone size,
|
|
213
213
|
the way quick mode shows a native before/after when there's no simulator.
|
|
214
214
|
|
|
215
|
+
## Scores in the wild
|
|
216
|
+
|
|
217
|
+
Ran it on your own app or site? [Share the before/after and the
|
|
218
|
+
score](https://github.com/marcosnovo/unslop-design/issues/new?template=score-report.yml),
|
|
219
|
+
and it goes here with your permission: what the app is, the two numbers,
|
|
220
|
+
one image. What it missed is just as useful: that's how rules get added.
|
|
221
|
+
|
|
222
|
+
| App | Platform | Score | |
|
|
223
|
+
|---|---|---|---|
|
|
224
|
+
| [Refil](https://refil.app) (the author's) | iOS, Android | before/after above | [screens](#one-fix-at-a-time) |
|
|
225
|
+
| *Yours?* | | | [share it](https://github.com/marcosnovo/unslop-design/issues/new?template=score-report.yml) |
|
|
226
|
+
|
|
215
227
|
## Use it
|
|
216
228
|
|
|
217
229
|
Type `/unslop-design` (or `$unslop-design` in Codex), or just ask in plain
|
|
@@ -288,24 +300,51 @@ edit just added, with the fix number. It says nothing when the edit is
|
|
|
288
300
|
clean, never changes code itself, and turns off with `UNSLOP_HOOK=off` or
|
|
289
301
|
`hook: off` in `.unslop/context.md`.
|
|
290
302
|
|
|
303
|
+
**While other agents write.** The same hook works wherever an agent's hooks
|
|
304
|
+
can hand a note back to the model. One command sets it up in the project:
|
|
305
|
+
|
|
306
|
+
```bash
|
|
307
|
+
npx unslop-design hooks gemini --write # .gemini/settings.json, AfterTool
|
|
308
|
+
npx unslop-design hooks copilot --write # .github/hooks/unslop-design.json, postToolUse (preview)
|
|
309
|
+
npx unslop-design hooks codex # prints the ~/.codex/config.toml block, PostToolUse
|
|
310
|
+
```
|
|
311
|
+
|
|
312
|
+
Each runs `npx -y unslop-design hook` after a write or edit, reads the
|
|
313
|
+
agent's event (Gemini's `write_file`/`replace`, Codex's `apply_patch`,
|
|
314
|
+
Copilot's tool arguments) and answers in the format they share. Cursor's and
|
|
315
|
+
Windsurf's post-edit hooks can't send anything back to the agent yet, so
|
|
316
|
+
there is no hook for them; the scanner and the CI work there as anywhere.
|
|
317
|
+
|
|
291
318
|
**On every pull request (GitHub Actions).** Each hit becomes an annotation
|
|
292
|
-
on its line,
|
|
293
|
-
|
|
319
|
+
on its line, and one comment on the PR keeps the score and the change
|
|
320
|
+
against the base branch, updated on every push:
|
|
321
|
+
|
|
322
|
+
> ### unslop score: 88/100 (+7 vs main)
|
|
323
|
+
> **Worse** · [#68] Border and shadow on one card: 0 → 2 (-2)
|
|
324
|
+
> **Better** · [#32] Colored glows: 3 → 0 (+8) · [#33] Emoji in the UI: 4 → 0 (+8)
|
|
325
|
+
|
|
326
|
+
The job fails under your minimum, if you set one:
|
|
294
327
|
|
|
295
328
|
```yaml
|
|
296
329
|
# .github/workflows/unslop.yml
|
|
297
330
|
on: pull_request
|
|
331
|
+
permissions:
|
|
332
|
+
contents: read
|
|
333
|
+
pull-requests: write # for the comment
|
|
298
334
|
jobs:
|
|
299
335
|
unslop:
|
|
300
336
|
runs-on: ubuntu-latest
|
|
301
337
|
steps:
|
|
302
|
-
- uses: actions/checkout@
|
|
303
|
-
- uses: marcosnovo/unslop-design@v1.
|
|
338
|
+
- uses: actions/checkout@v5
|
|
339
|
+
- uses: marcosnovo/unslop-design@v1.13.0
|
|
304
340
|
with:
|
|
305
341
|
paths: src
|
|
306
|
-
min: 80 # optional; also: allow, scale, type-scale
|
|
342
|
+
min: 80 # optional; also: allow, scale, type-scale, comment: false
|
|
307
343
|
```
|
|
308
344
|
|
|
345
|
+
Locally, `unslop-score.py --json > main.json` on one branch and
|
|
346
|
+
`--baseline main.json` on another gives the same comparison.
|
|
347
|
+
|
|
309
348
|
**Anywhere else.** `python3 scripts/slop-scan.py src --github` prints the
|
|
310
349
|
same annotations, `--json` every hit for other tools, and `--list-rules`
|
|
311
350
|
every rule id. All of them read `.unslop/context.md`, so your scale and your
|
package/bin/unslop.mjs
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// npx unslop-design <command>: one entry point for the installer and the scripts.
|
|
3
3
|
// No dependencies. scan and score need Python 3; audit needs Playwright.
|
|
4
4
|
import { spawnSync } from "node:child_process";
|
|
5
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
5
6
|
import { dirname, join } from "node:path";
|
|
6
7
|
import { fileURLToPath } from "node:url";
|
|
7
8
|
|
|
@@ -20,6 +21,8 @@ const HELP = `unslop-design: make your app or site stop looking AI-generated
|
|
|
20
21
|
the rendered page at 390/768/1280 px (needs Playwright)
|
|
21
22
|
npx unslop-design rules
|
|
22
23
|
every rule id with its fix number
|
|
24
|
+
npx unslop-design hooks <gemini|codex|copilot|claude> [--write]
|
|
25
|
+
the post-edit hook for that agent: prints its config, --write adds it to this project
|
|
23
26
|
|
|
24
27
|
Then, in your agent: "unslop this screen". Docs: https://github.com/marcosnovo/unslop-design`;
|
|
25
28
|
|
|
@@ -38,6 +41,72 @@ function python(script, args) {
|
|
|
38
41
|
process.exit(2);
|
|
39
42
|
}
|
|
40
43
|
|
|
44
|
+
// The same hook for every agent: `npx -y unslop-design hook` reads the agent's event on stdin.
|
|
45
|
+
const HOOK = "npx -y unslop-design hook";
|
|
46
|
+
const HOOKS = {
|
|
47
|
+
gemini: {
|
|
48
|
+
file: ".gemini/settings.json",
|
|
49
|
+
note: "Gemini CLI: AfterTool on write_file and replace. Project hooks ask for approval the first time.",
|
|
50
|
+
merge: (cfg) => {
|
|
51
|
+
cfg.hooks ??= {};
|
|
52
|
+
cfg.hooks.AfterTool = withOurHook(cfg.hooks.AfterTool,
|
|
53
|
+
{ matcher: "write_file|replace", hooks: [{ name: "unslop-design", type: "command", command: HOOK, timeout: 30000 }] });
|
|
54
|
+
return cfg;
|
|
55
|
+
},
|
|
56
|
+
},
|
|
57
|
+
copilot: {
|
|
58
|
+
file: ".github/hooks/unslop-design.json",
|
|
59
|
+
note: "GitHub Copilot (VS Code agent, Copilot CLI, cloud agent): postToolUse. Agent hooks are in preview; commit the file for cloud sessions.",
|
|
60
|
+
merge: () => ({ version: 1, hooks: { postToolUse: [{ type: "command", command: HOOK, timeoutSec: 30 }] } }),
|
|
61
|
+
},
|
|
62
|
+
claude: {
|
|
63
|
+
file: ".claude/settings.json",
|
|
64
|
+
note: "Claude Code: the plugin already ships this hook (/plugin install unslop-design@unslop). Use this only without the plugin.",
|
|
65
|
+
merge: (cfg) => {
|
|
66
|
+
cfg.hooks ??= {};
|
|
67
|
+
cfg.hooks.PostToolUse = withOurHook(cfg.hooks.PostToolUse,
|
|
68
|
+
{ matcher: "Write|Edit|MultiEdit", hooks: [{ type: "command", command: HOOK, timeout: 30 }] });
|
|
69
|
+
return cfg;
|
|
70
|
+
},
|
|
71
|
+
},
|
|
72
|
+
codex: {
|
|
73
|
+
file: null,
|
|
74
|
+
note: "Codex CLI: PostToolUse on apply_patch. Add this to ~/.codex/config.toml (hooks may need enabling in your version, and some versions don't fire it for apply_patch).",
|
|
75
|
+
text: `[[hooks.PostToolUse]]\nmatcher = "apply_patch"\n\n[[hooks.PostToolUse.hooks]]\ntype = "command"\ncommand = "${HOOK}"\n`,
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
// Replace only our own handler in a list of hook groups: other commands in the same group stay.
|
|
80
|
+
function withOurHook(groups, group) {
|
|
81
|
+
const ours = (h) => typeof h?.command === "string" && h.command.includes("unslop-design");
|
|
82
|
+
const kept = (groups || []).map(g => ({ ...g, hooks: (g.hooks || []).filter(h => !ours(h)) })).filter(g => g.hooks.length);
|
|
83
|
+
return [...kept, group];
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function hooks([agent, ...flags]) {
|
|
87
|
+
const h = HOOKS[agent];
|
|
88
|
+
if (!h) {
|
|
89
|
+
console.error(`usage: npx unslop-design hooks <${Object.keys(HOOKS).join("|")}> [--write]\n` +
|
|
90
|
+
"Cursor and Windsurf hooks can't send a note back to the agent yet, so there is no hook for them.");
|
|
91
|
+
process.exit(2);
|
|
92
|
+
}
|
|
93
|
+
console.log(h.note + "\n");
|
|
94
|
+
if (!h.file) { console.log(h.text); return; }
|
|
95
|
+
let cfg = {};
|
|
96
|
+
if (existsSync(h.file)) {
|
|
97
|
+
try { cfg = JSON.parse(readFileSync(h.file, "utf8")); }
|
|
98
|
+
catch { console.error(`${h.file} isn't valid JSON: fix it or add the hook by hand.`); process.exit(2); }
|
|
99
|
+
}
|
|
100
|
+
const next = JSON.stringify(h.merge(cfg), null, 2) + "\n";
|
|
101
|
+
if (flags.includes("--write")) {
|
|
102
|
+
mkdirSync(dirname(h.file), { recursive: true });
|
|
103
|
+
writeFileSync(h.file, next);
|
|
104
|
+
console.log(`Wrote ${h.file}. The hook runs after each UI edit and is silent when it's clean.`);
|
|
105
|
+
} else {
|
|
106
|
+
console.log(`${h.file}:\n${next}\nRun again with --write to save it.`);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
41
110
|
switch (cmd) {
|
|
42
111
|
case "install": {
|
|
43
112
|
const code = run("bash", [join(ROOT, "install.sh"), ...rest]);
|
|
@@ -50,6 +119,11 @@ switch (cmd) {
|
|
|
50
119
|
case "scan": python("slop-scan.py", rest); break;
|
|
51
120
|
case "score": python("unslop-score.py", rest); break;
|
|
52
121
|
case "rules": python("slop-scan.py", ["--list-rules"]); break;
|
|
122
|
+
case "hook": {
|
|
123
|
+
const r = spawnSync(process.execPath, [join(ROOT, "hooks", "unslop-hook.mjs")], { stdio: "inherit" });
|
|
124
|
+
process.exit(r.status ?? 0);
|
|
125
|
+
}
|
|
126
|
+
case "hooks": hooks(rest); break;
|
|
53
127
|
case "audit": process.exit(run(process.execPath, [join(ROOT, "scripts", "web-audit.mjs"), ...rest]) ?? 1);
|
|
54
128
|
case undefined: case "help": case "-h": case "--help": console.log(HELP); break;
|
|
55
129
|
default:
|
package/hooks/unslop-hook.mjs
CHANGED
|
@@ -1,17 +1,27 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
//
|
|
2
|
+
// Post-edit hook: scan the UI files the agent just wrote or edited with
|
|
3
3
|
// scripts/slop-scan.py and hand the new hits back to the agent as context.
|
|
4
|
-
//
|
|
5
|
-
//
|
|
4
|
+
//
|
|
5
|
+
// One script for every agent whose hooks can talk back to the model:
|
|
6
|
+
// Claude Code PostToolUse Write, Edit, MultiEdit: tool_input.file_path
|
|
7
|
+
// Gemini CLI AfterTool write_file, replace: tool_input.file_path
|
|
8
|
+
// Codex CLI PostToolUse apply_patch: the paths inside the patch text
|
|
9
|
+
// Copilot / VS Code agents PostToolUse: a file path in tool_input or toolArgs
|
|
10
|
+
// All of them read {"hookSpecificOutput": {"additionalContext": "…"}} on stdout.
|
|
11
|
+
//
|
|
12
|
+
// Silent when clean, when no UI file was touched, when Python is missing, or
|
|
13
|
+
// when turned off (UNSLOP_HOOK=off, or a line "hook: off" in .unslop/context.md).
|
|
6
14
|
// It never edits anything: the agent decides, the user approves.
|
|
7
15
|
import { spawnSync } from "node:child_process";
|
|
8
16
|
import { existsSync, readFileSync } from "node:fs";
|
|
9
|
-
import { dirname, join, relative, extname } from "node:path";
|
|
17
|
+
import { dirname, join, relative, resolve, extname } from "node:path";
|
|
10
18
|
import { fileURLToPath } from "node:url";
|
|
11
19
|
|
|
12
20
|
const UI = new Set([".css", ".scss", ".sass", ".less", ".html", ".htm", ".jsx", ".tsx", ".vue", ".svelte", ".astro", ".mdx", ".swift", ".kt"]);
|
|
13
21
|
const SCAN = join(dirname(fileURLToPath(import.meta.url)), "..", "scripts", "slop-scan.py");
|
|
14
22
|
const MAX = 8;
|
|
23
|
+
const PATH_KEYS = ["file_path", "filePath", "path", "absolute_path", "absolutePath", "target_file", "filename"];
|
|
24
|
+
const WRITE_TOOLS = /^(Write|write_file|create_file|createFile|create)$/;
|
|
15
25
|
|
|
16
26
|
function quit() { process.exit(0); }
|
|
17
27
|
|
|
@@ -21,12 +31,38 @@ let ev;
|
|
|
21
31
|
try { ev = JSON.parse(input); } catch { quit(); }
|
|
22
32
|
if (/^(off|0|false|no)$/i.test(process.env.UNSLOP_HOOK || "")) quit();
|
|
23
33
|
|
|
24
|
-
const
|
|
25
|
-
|
|
26
|
-
if (
|
|
34
|
+
const cwd = ev.cwd || process.cwd();
|
|
35
|
+
let tool = ev.tool_input ?? ev.toolArgs ?? ev.tool_args ?? {};
|
|
36
|
+
if (typeof tool === "string") { try { tool = JSON.parse(tool); } catch { tool = { input: tool }; } }
|
|
37
|
+
const toolName = ev.tool_name || ev.toolName || "";
|
|
38
|
+
|
|
39
|
+
// The files this edit touched -> the text it brought in (null: the whole file is new).
|
|
40
|
+
const files = new Map();
|
|
41
|
+
const fresh = [tool.new_string, tool.newString, ...(Array.isArray(tool.edits) ? tool.edits : [])
|
|
42
|
+
.map(e => e && (e.new_string ?? e.newString))].filter(s => typeof s === "string" && s);
|
|
43
|
+
const whole = WRITE_TOOLS.test(toolName) || !fresh.length;
|
|
44
|
+
for (const key of PATH_KEYS) {
|
|
45
|
+
if (typeof tool[key] === "string" && tool[key]) files.set(resolve(cwd, tool[key]), whole ? null : fresh.join("\n"));
|
|
46
|
+
}
|
|
47
|
+
// Codex apply_patch: "*** Update File: src/Card.tsx" then "+added line" rows.
|
|
48
|
+
const strings = [];
|
|
49
|
+
(function walk(v) {
|
|
50
|
+
if (typeof v === "string") strings.push(v);
|
|
51
|
+
else if (Array.isArray(v)) v.forEach(walk);
|
|
52
|
+
else if (v && typeof v === "object") Object.values(v).forEach(walk);
|
|
53
|
+
})(tool);
|
|
54
|
+
for (const s of strings) {
|
|
55
|
+
for (const block of s.split(/^(?=\*\*\* (?:Add|Update|Delete) File: )/m)) {
|
|
56
|
+
const m = block.match(/^\*\*\* (Add|Update) File: (.+)$/m);
|
|
57
|
+
if (!m) continue;
|
|
58
|
+
const added = block.split("\n").filter(l => l.startsWith("+") && !l.startsWith("+++")).map(l => l.slice(1));
|
|
59
|
+
files.set(resolve(cwd, m[2].trim()), m[1] === "Add" ? null : added.join("\n"));
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
const targets = [...files].filter(([f]) => UI.has(extname(f).toLowerCase()) && existsSync(f));
|
|
63
|
+
if (!targets.length) quit();
|
|
27
64
|
|
|
28
65
|
// Project context (written by "init"): slop-scan reads its scales and allowed rules itself.
|
|
29
|
-
const cwd = ev.cwd || process.cwd();
|
|
30
66
|
const opts = [];
|
|
31
67
|
const ctxPath = join(cwd, ".unslop", "context.md");
|
|
32
68
|
if (existsSync(ctxPath)) {
|
|
@@ -35,8 +71,8 @@ if (existsSync(ctxPath)) {
|
|
|
35
71
|
}
|
|
36
72
|
|
|
37
73
|
let out = null;
|
|
38
|
-
for (const py of ["python3", "python"]) {
|
|
39
|
-
const r = spawnSync(py, [SCAN,
|
|
74
|
+
for (const py of process.platform === "win32" ? ["py", "python", "python3"] : ["python3", "python"]) {
|
|
75
|
+
const r = spawnSync(py, [SCAN, ...targets.map(([f]) => f), "--json", ...opts], { encoding: "utf8", timeout: 15000 });
|
|
40
76
|
if (r.error) continue; // not installed under this name
|
|
41
77
|
if (r.status !== 0) quit(); // a bad --allow in context.md, etc.: stay out of the way
|
|
42
78
|
out = r.stdout;
|
|
@@ -46,29 +82,34 @@ if (!out) quit();
|
|
|
46
82
|
|
|
47
83
|
let hits;
|
|
48
84
|
try { hits = JSON.parse(out).hits; } catch { quit(); }
|
|
49
|
-
|
|
50
|
-
// (a partial-line edit counts its whole line).
|
|
51
|
-
const
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
const
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
85
|
+
|
|
86
|
+
// After an edit, only the lines its new text now sits on (a partial-line edit counts its whole line).
|
|
87
|
+
const touched = new Map();
|
|
88
|
+
for (const [f, text] of targets) {
|
|
89
|
+
if (text === null) continue;
|
|
90
|
+
const body = readFileSync(f, "utf8");
|
|
91
|
+
const lines = new Set();
|
|
92
|
+
// Every non-empty piece counts, even "3": a short value is a common UI edit. A short piece may
|
|
93
|
+
// also match other lines; reporting a few extra beats missing what the edit added.
|
|
94
|
+
for (const piece of text.split("\n").map(l => l.trim()).filter(Boolean)) {
|
|
95
|
+
for (let at = body.indexOf(piece); at !== -1; at = body.indexOf(piece, at + piece.length)) {
|
|
96
|
+
lines.add(body.slice(0, at).split("\n").length);
|
|
60
97
|
}
|
|
61
98
|
}
|
|
62
|
-
|
|
99
|
+
touched.set(f, lines);
|
|
63
100
|
}
|
|
101
|
+
hits = hits.filter(h => {
|
|
102
|
+
const lines = touched.get(resolve(h.file));
|
|
103
|
+
return !lines || lines.has(h.line);
|
|
104
|
+
});
|
|
64
105
|
if (!hits.length) quit();
|
|
65
|
-
hits.sort((a, b) => a.line - b.line);
|
|
106
|
+
hits.sort((a, b) => (a.file === b.file ? a.line - b.line : a.file < b.file ? -1 : 1));
|
|
66
107
|
|
|
67
|
-
const
|
|
68
|
-
const
|
|
69
|
-
const
|
|
70
|
-
const note = `unslop-design found ${hits.length} slop pattern${hits.length === 1 ? "" : "s"} in what you just wrote to ${rel}:\n` +
|
|
108
|
+
const shown = hits.slice(0, MAX).map(h => `- ${relative(cwd, resolve(h.file)) || h.file}:${h.line}: ${h.ref} ${h.rule} — ${h.description}`);
|
|
109
|
+
const more = hits.length > MAX ? `\n- … ${hits.length - MAX} more (run scripts/slop-scan.py on the same files)` : "";
|
|
110
|
+
const note = `unslop-design found ${hits.length} slop pattern${hits.length === 1 ? "" : "s"} in what you just wrote:\n` +
|
|
71
111
|
shown.join("\n") + more +
|
|
72
112
|
"\nFix them by changing the value or the token (checklist.md has each fix), not by hiding them. " +
|
|
73
113
|
"If one is a written project decision, it belongs in .unslop/context.md under allow:, not in an unslop-ignore.";
|
|
74
|
-
|
|
114
|
+
const event = ev.hook_event_name || ev.hookEventName || "PostToolUse";
|
|
115
|
+
process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: event, additionalContext: note } }));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "unslop-design",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.13.0",
|
|
4
4
|
"description": "Make your app or site stop looking AI-generated: install the agent skill, scan UI code for slop and score it 0-100.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Marcos Novo (https://github.com/marcosnovo)",
|
package/scripts/unslop-score.py
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
|
|
4
4
|
python3 scripts/unslop-score.py [paths…] [--audit unslop-audit/report.json]
|
|
5
5
|
[--scale …] [--json | --markdown] [--min 80]
|
|
6
|
-
[--save [.unslop]]
|
|
6
|
+
[--save [.unslop]] [--baseline base.json]
|
|
7
7
|
|
|
8
8
|
Scores the source with the same rules as `slop-scan.py` and, if you pass a
|
|
9
9
|
`web-audit.mjs` report, the rendered page too (scroll, contrast, focus,
|
|
@@ -13,7 +13,9 @@ are left more than how big the codebase is. Prints the breakdown and a
|
|
|
13
13
|
README badge. With --min it exits 1 below that score (pre-commit hook).
|
|
14
14
|
With --save it appends the run to .unslop/history.json and prints the
|
|
15
15
|
trend ("score 41 → 88 → 91"); --markdown prints a table for a PR comment or
|
|
16
|
-
a GitHub Actions job summary.
|
|
16
|
+
a GitHub Actions job summary. --baseline compares with an earlier --json
|
|
17
|
+
run (the base branch in a PR): "score 72 → 81 (+9)", what got better and what
|
|
18
|
+
got worse.
|
|
17
19
|
|
|
18
20
|
It is a smoke alarm, not a judge: a 95 can still have a flat hierarchy,
|
|
19
21
|
and a gradient you chose on purpose costs points anyway (silence that line
|
|
@@ -179,6 +181,26 @@ def save_run(folder, run):
|
|
|
179
181
|
return [h["score"] for h in history]
|
|
180
182
|
|
|
181
183
|
|
|
184
|
+
def compare(base, score, lines):
|
|
185
|
+
"""Score delta and per-row changes against an earlier --json output."""
|
|
186
|
+
before = {r["rule"]: (r["count"], r["points"]) for r in base.get("penalties", [])}
|
|
187
|
+
now = {r: (n, p) for p, r, n in lines}
|
|
188
|
+
better, worse = [], []
|
|
189
|
+
for rule in sorted(set(before) | set(now)):
|
|
190
|
+
(bn, bp), (nn, np_) = before.get(rule, (0, 0)), now.get(rule, (0, 0))
|
|
191
|
+
if np_ < bp:
|
|
192
|
+
better.append({"rule": rule, "from": bn, "to": nn, "points": round(bp - np_, 1)})
|
|
193
|
+
elif np_ > bp:
|
|
194
|
+
worse.append({"rule": rule, "from": bn, "to": nn, "points": round(np_ - bp, 1)})
|
|
195
|
+
better.sort(key=lambda x: -x["points"])
|
|
196
|
+
worse.sort(key=lambda x: -x["points"])
|
|
197
|
+
return {"score": base["score"], "delta": score - base["score"], "better": better, "worse": worse}
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def signed(n):
|
|
201
|
+
return f"+{n:g}" if n > 0 else f"{n:g}" if n < 0 else "±0"
|
|
202
|
+
|
|
203
|
+
|
|
182
204
|
def main():
|
|
183
205
|
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
184
206
|
ap.add_argument("paths", nargs="*", help="source to scan (default: . unless only --audit is given)")
|
|
@@ -189,6 +211,8 @@ def main():
|
|
|
189
211
|
ap.add_argument("--save", nargs="?", const=".unslop", metavar="DIR",
|
|
190
212
|
help="append this run to DIR/history.json (default .unslop) and show the trend")
|
|
191
213
|
ap.add_argument("--min", type=float, help="exit 1 below this score")
|
|
214
|
+
ap.add_argument("--baseline", metavar="JSON", help="an earlier --json output to compare with (e.g. the base branch)")
|
|
215
|
+
ap.add_argument("--baseline-label", default="baseline", metavar="NAME", help="what to call it (e.g. main)")
|
|
192
216
|
ap.add_argument("--type-scale", help="allowed font sizes in px (default: the project context, else slop-scan's)")
|
|
193
217
|
ap.add_argument("--context", metavar="FILE", help="project context to read (default .unslop/context.md if present)")
|
|
194
218
|
ap.add_argument("--no-context", action="store_true", help="ignore .unslop/context.md")
|
|
@@ -255,12 +279,34 @@ def main():
|
|
|
255
279
|
scores = save_run(a.save, {"score": score, "files": files, "audit": bool(a.audit), "allowed": allowed,
|
|
256
280
|
"penalties": [{"rule": r, "count": n, "points": p} for p, r, n in lines]})
|
|
257
281
|
trend = " → ".join(str(s) for s in scores[-5:])
|
|
282
|
+
cmp_ = None
|
|
283
|
+
if a.baseline:
|
|
284
|
+
try:
|
|
285
|
+
with open(a.baseline, encoding="utf-8") as fh:
|
|
286
|
+
cmp_ = compare(json.load(fh), score, lines)
|
|
287
|
+
except (OSError, ValueError, KeyError) as e:
|
|
288
|
+
sys.exit(f"can't read the baseline {a.baseline}: {e}. It is the --json output of an earlier run.")
|
|
258
289
|
if a.markdown:
|
|
259
|
-
|
|
290
|
+
if cmp_:
|
|
291
|
+
out = [f"### unslop score: {score}/100 ({signed(cmp_['delta'])} vs {a.baseline_label})", "",
|
|
292
|
+
f"{a.baseline_label} {cmp_['score']} → this change {score}", ""]
|
|
293
|
+
for title, rows, sign in (("Worse", cmp_["worse"], "-"), ("Better", cmp_["better"], "+")):
|
|
294
|
+
if rows:
|
|
295
|
+
out.append(f"**{title}**")
|
|
296
|
+
out += [f"- {r['rule']}: {r['from']} → {r['to']} ({sign}{r['points']:g})" for r in rows]
|
|
297
|
+
out.append("")
|
|
298
|
+
if not cmp_["better"] and not cmp_["worse"]:
|
|
299
|
+
out += ["No change in any row.", ""]
|
|
300
|
+
if lines:
|
|
301
|
+
out += ["<details><summary>Every row now</summary>", ""]
|
|
302
|
+
else:
|
|
303
|
+
out = [f"### unslop score: {score}/100 ({word})", ""]
|
|
260
304
|
if trend and "→" in trend:
|
|
261
305
|
out += [f"Trend: {trend}", ""]
|
|
262
306
|
if lines:
|
|
263
307
|
out += ["| Points | Fix | Hits |", "|---:|---|---:|"] + [f"| -{p:g} | {r} | {n} |" for p, r, n in lines]
|
|
308
|
+
if cmp_:
|
|
309
|
+
out += ["", "</details>"]
|
|
264
310
|
else:
|
|
265
311
|
out.append("Nothing found.")
|
|
266
312
|
if allowed:
|
|
@@ -270,7 +316,7 @@ def main():
|
|
|
270
316
|
elif a.json:
|
|
271
317
|
print(json.dumps({"score": score, "verdict": word, "files": files, "audit": bool(a.audit), "badge": badge,
|
|
272
318
|
"penalties": [{"rule": r, "count": n, "points": p} for p, r, n in lines],
|
|
273
|
-
"allowed": allowed, "trend": trend}, indent=2))
|
|
319
|
+
"allowed": allowed, "trend": trend, "baseline": cmp_}, indent=2))
|
|
274
320
|
else:
|
|
275
321
|
src = []
|
|
276
322
|
if paths:
|
|
@@ -282,6 +328,11 @@ def main():
|
|
|
282
328
|
print(f"unslop score: {score}/100 — {word} ({' + '.join(src)})")
|
|
283
329
|
if trend and "→" in trend:
|
|
284
330
|
print(f"trend: {trend} ({os.path.join(a.save, 'history.json')})")
|
|
331
|
+
if cmp_:
|
|
332
|
+
print(f"vs {a.baseline_label}: {cmp_['score']} → {score} ({signed(cmp_['delta'])})")
|
|
333
|
+
for title, rows, sign in (("worse", cmp_["worse"], "-"), ("better", cmp_["better"], "+")):
|
|
334
|
+
for r in rows:
|
|
335
|
+
print(f" {title}: {r['rule']} {r['from']} → {r['to']} ({sign}{r['points']:g})")
|
|
285
336
|
if allowed:
|
|
286
337
|
print("allowed by the project (--allow, not scored): " + ", ".join(allowed))
|
|
287
338
|
if lines:
|