Repository navigation
Expand file tree
/
Copy pathcli.ts
More file actions
364 lines (334 loc) · 11.2 KB
/
Copy pathcli.ts
File metadata and controls
364 lines (334 loc) · 11.2 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
352
353
354
355
356
357
358
359
360
361
362
363
364
#!/usr/bin/env node
import { mkdir, writeFile, stat } from "node:fs/promises";
import { listCleanableFiles, mapOutputPath } from "./batch.js";
import { cleanPath, cleanSource } from "./clean.js";
import { formatDiffHuman } from "./diff.js";
import { inspectBuffer, inspectPath } from "./inspect.js";
import { readInputSource } from "./io.js";
import {
formatBatchHuman,
formatBatchJson,
formatReportHuman,
formatReportJson,
} from "./report.js";
import {
rewritePath,
type RewriteBackend,
type RewriteStrength,
} from "./rewrite.js";
import { batchToSarif, toSarif } from "./sarif.js";
import {
TOOL_VERSION,
type BatchReport,
type MarkscrubReport,
} from "./types.js";
function usage(): string {
return `markscrub ${TOOL_VERSION}
Usage:
markscrub inspect <path|-> [--clipboard] [--json] [--sarif <file>] [--fail-on-findings]
markscrub clean <path|-> -o <out> [--clipboard] [--recursive] [--diff] [--dry-run] [--json] [--sarif <file>] [--fail-on-findings]
markscrub rewrite <path|-> [-o <out>] [--clipboard] [--backend print-prompt|openai|ollama|lmstudio]
[--strength paraphrase|strong] [--model <name>] [--json]
markscrub report <path> (alias of inspect --json)
markscrub help
Flags:
--recursive Clean/inspect directories recursively
--diff Show before/after summary for text cleans
--dry-run Preview clean without writing
--clipboard Read text from the system clipboard (and write back on clean if no -o)
--fail-on-findings Exit 1 when findings are present (CI)
--sarif <file> Write SARIF 2.1.0 report
--json Machine-readable output
Rewrite backends:
print-prompt Print paraphrase prompt (default, no API)
ollama http://127.0.0.1:11434/v1 (local)
lmstudio http://127.0.0.1:1234/v1 (local)
openai OpenAI-compatible API (needs API key)
Env:
MARKSCRUB_REWRITE_BACKEND / _MODEL / _BASE_URL / _API_KEY
OPENAI_API_KEY
Notes:
- clean = Unicode scrub + file metadata/C2PA strip (verifiable where possible)
- rewrite = best-effort statistical mark reduction (never a guarantee)
- PDF: exiftool when available, else best-effort XMP/Info scrub
`;
}
function argValue(args: string[], name: string): string | undefined {
const i = args.indexOf(name);
if (i < 0) return undefined;
return args[i + 1];
}
function hasFlag(args: string[], name: string): boolean {
return args.includes(name);
}
function positionalInput(args: string[]): string | undefined {
return args.find((a) => !a.startsWith("-") || a === "-");
}
async function writeSarifFile(
path: string,
reports: MarkscrubReport[],
): Promise<void> {
await writeFile(path, `${JSON.stringify(toSarif(reports), null, 2)}\n`);
}
function exitForFindings(
reports: MarkscrubReport[],
fail: boolean,
): void {
if (!fail) return;
if (reports.some((r) => r.findings.length > 0)) process.exitCode = 1;
}
async function main(): Promise<void> {
const argv = process.argv.slice(2);
const cmd = argv[0];
if (!cmd || cmd === "help" || cmd === "--help" || cmd === "-h") {
process.stdout.write(usage());
return;
}
if (cmd === "version" || cmd === "--version" || cmd === "-V") {
process.stdout.write(`${TOOL_VERSION}\n`);
return;
}
const rest = argv.slice(1);
const json = hasFlag(rest, "--json") || cmd === "report";
const clipboard = hasFlag(rest, "--clipboard");
const recursive = hasFlag(rest, "--recursive");
const diff = hasFlag(rest, "--diff");
const dryRun = hasFlag(rest, "--dry-run");
const failOnFindings = hasFlag(rest, "--fail-on-findings");
const sarifPath = argValue(rest, "--sarif");
const input = clipboard ? "--clipboard" : positionalInput(rest);
if (!input && !clipboard) {
process.stderr.write(`missing path\n\n${usage()}`);
process.exitCode = 1;
return;
}
if (cmd === "inspect" || cmd === "report") {
if (clipboard || input === "-") {
const src = await readInputSource(input ?? "-", { clipboard });
const report = await inspectBuffer(src.label, src.buffer, {
asText: true,
});
process.stdout.write(
json ? formatReportJson(report) : `${formatReportHuman(report)}\n`,
);
if (sarifPath) await writeSarifFile(sarifPath, [report]);
exitForFindings([report], failOnFindings);
return;
}
const st = await stat(input!);
if (st.isDirectory()) {
const files = await listCleanableFiles(input!, { recursive: true });
const reports: MarkscrubReport[] = [];
for (const file of files) reports.push(await inspectPath(file));
const batch: BatchReport = {
tool: "markscrub",
version: TOOL_VERSION,
action: "batch",
input: input!,
files: reports,
summary: {
total: reports.length,
withFindings: reports.filter((r) => r.findings.length > 0).length,
cleaned: 0,
failed: 0,
},
};
process.stdout.write(
json ? formatBatchJson(batch) : `${formatBatchHuman(batch)}\n`,
);
if (sarifPath) {
await writeFile(
sarifPath,
`${JSON.stringify(batchToSarif(batch), null, 2)}\n`,
);
}
exitForFindings(reports, failOnFindings);
return;
}
const report = await inspectPath(input!);
process.stdout.write(
json ? formatReportJson(report) : `${formatReportHuman(report)}\n`,
);
if (sarifPath) await writeSarifFile(sarifPath, [report]);
exitForFindings([report], failOnFindings);
return;
}
if (cmd === "clean") {
const out = argValue(rest, "-o") ?? argValue(rest, "--output");
if (clipboard || input === "-") {
const src = await readInputSource(input ?? "-", { clipboard });
const result = await cleanSource(src.label, src.buffer, {
dryRun,
diff,
asTextExt: "txt",
outputPath: out,
clipboardOut: clipboard && !out && !dryRun,
});
if (!dryRun && !out && !clipboard) {
process.stdout.write(result.buffer);
} else {
process.stdout.write(
json
? formatReportJson(result.report)
: `${formatReportHuman(result.report)}\n`,
);
if (!json && diff) {
const d = formatDiffHuman(result.report);
if (d) process.stderr.write(`${d}\n`);
}
}
if (sarifPath) await writeSarifFile(sarifPath, [result.report]);
exitForFindings([result.report], failOnFindings);
return;
}
const st = await stat(input!);
if (st.isDirectory()) {
if (!out && !dryRun) {
process.stderr.write("directory clean requires -o <out-dir>\n");
process.exitCode = 1;
return;
}
const files = await listCleanableFiles(input!, {
recursive: recursive || true,
});
const reports: MarkscrubReport[] = [];
let failed = 0;
for (const file of files) {
try {
const target = out
? mapOutputPath(input!, file, out)
: file + ".cleaned";
if (dryRun) {
const { cleanBuffer } = await import("./clean.js");
const { readFile } = await import("node:fs/promises");
const buf = await readFile(file);
const result = await cleanBuffer(file, buf, { dryRun: true, diff });
reports.push(result.report);
} else {
reports.push(await cleanPath(file, target, { diff }));
}
} catch (err) {
failed += 1;
reports.push({
tool: "markscrub",
version: TOOL_VERSION,
input: file,
action: "clean",
findings: [
{
kind: "metadata",
code: "clean_error",
message: err instanceof Error ? err.message : String(err),
verifiable: false,
},
],
actions: [],
residualRisk: { level: "medium", notes: ["clean failed"] },
});
}
}
const batch: BatchReport = {
tool: "markscrub",
version: TOOL_VERSION,
action: "batch",
input: input!,
output: out,
files: reports,
summary: {
total: reports.length,
withFindings: reports.filter((r) => r.findings.length > 0).length,
cleaned: reports.filter((r) => r.actions.length > 0).length,
failed,
},
};
process.stdout.write(
json ? formatBatchJson(batch) : `${formatBatchHuman(batch)}\n`,
);
if (sarifPath) {
await writeFile(
sarifPath,
`${JSON.stringify(batchToSarif(batch), null, 2)}\n`,
);
}
exitForFindings(reports, failOnFindings);
return;
}
if (!out && !dryRun) {
process.stderr.write("clean requires -o <out> (or --dry-run)\n");
process.exitCode = 1;
return;
}
const report = await cleanPath(input!, out ?? input! + ".cleaned", {
dryRun,
diff,
});
process.stdout.write(
json ? formatReportJson(report) : `${formatReportHuman(report)}\n`,
);
if (!json && diff) {
const d = formatDiffHuman(report);
if (d) process.stderr.write(`${d}\n`);
}
if (sarifPath) await writeSarifFile(sarifPath, [report]);
exitForFindings([report], failOnFindings);
return;
}
if (cmd === "rewrite") {
const out = argValue(rest, "-o") ?? argValue(rest, "--output");
const backend = (argValue(rest, "--backend") ??
process.env.MARKSCRUB_REWRITE_BACKEND ??
"print-prompt") as RewriteBackend;
const strength = (argValue(rest, "--strength") ??
"paraphrase") as RewriteStrength;
const model = argValue(rest, "--model");
let result;
if (clipboard || input === "-") {
const src = await readInputSource(input ?? "-", { clipboard });
result = await rewritePath(src.label, {
backend,
strength,
model,
outputPath: out,
text: src.buffer.toString("utf8"),
inputLabel: src.label,
});
} else {
result = await rewritePath(input!, {
backend,
strength,
model,
outputPath: out,
});
}
if (result.prompt && backend === "print-prompt") {
if (out) {
await mkdir((await import("node:path")).dirname(out), {
recursive: true,
});
await writeFile(out, result.prompt, "utf8");
}
process.stdout.write(result.prompt);
if (!result.prompt.endsWith("\n")) process.stdout.write("\n");
if (json) process.stderr.write(formatReportJson(result.report));
else process.stderr.write(`\n${formatReportHuman(result.report)}\n`);
return;
}
if (clipboard && result.text && !out) {
const { writeClipboard } = await import("./io.js");
await writeClipboard(result.text);
result.report.output = "<clipboard>";
}
process.stdout.write(
json
? formatReportJson(result.report)
: `${formatReportHuman(result.report)}\n`,
);
return;
}
process.stderr.write(`unknown command: ${cmd}\n\n${usage()}`);
process.exitCode = 1;
}
main().catch((err: unknown) => {
process.stderr.write(`${err instanceof Error ? err.message : String(err)}\n`);
process.exitCode = 1;
});