Commit c7614a0a by PLN (Algolia)

cli: real arg parsing — -h/--help/--version, score subcommand, safe walks

-h used to fall through as a lint target; unknown flags vanished silently;
the no-arg walk hit .Trash and died on EPERM. Now: flags parsed properly
(unknown = exit 2), dot-directories skipped (--hidden to include), directory
symlinks never followed, unreadable dirs warn instead of crashing, and the
score subcommand the header always advertised actually exists.
Co-Authored-By: 's avatarClaude Code <noreply@anthropic.com>
parent 96c1a969
......@@ -11,8 +11,10 @@ repo `git.nech.pl/pln/buvard` (visibility toggle is the owner's call).
structure -8, servile/meta -10; punctuation budgets (1 tiret cadratin/500w,
1 !/1000w). **Voice rule: hits are review candidates, never verdicts — the
author's voice always wins.** buvard is a style linter, never an AI detector.
- **`bin/buvard.js`** — CLI (`check`, `--json`), frontmatter stripped. Tests:
`npm test` (node:test, 6/6 passing).
- **`bin/buvard.js`** — CLI (`check`, `score`, `--json`, `--hidden`, `--help`,
`--version`), frontmatter stripped. Walks skip dot-directories and never
follow directory symlinks; unreadable dirs warn, never crash. Tests:
`npm test` (node:test, 24 passing).
- **`docs/research.md`** — the clustering study. **`docs/research-litreview.md`**
— literature review (2026-11-07): detection literature unreliable on short/
paraphrased text; 61.22% FP rate of commercial detectors on non-native essays
......
......@@ -2,14 +2,18 @@
/**
* buvard — l'anti-slop qui tache. Blotting paper for AI-flavored prose.
*
* buvard check <files|dirs> [--json] run the catalog over markdown/text
* buvard score <file> single-file score, machine-readable
* buvard check [files|dirs] [--json] [--hidden] run the catalog over markdown/text
* buvard score <file> [--json] single-file score, machine-readable
* buvard --help | --version
*
* Scoring starts at 100; each hit costs its weight (lexique 5, structure 8,
* servile 10; punctuation charges per occurrence past the budget: one tiret
* cadratin per 500 words, one exclamation per 1000). Every hit is a review
* candidate, not a verdict — the author's voice always wins.
*
* Walks skip dot-directories (--hidden to include) and never follow directory
* symlinks; unreadable directories are warned about, not fatal.
*
* Known gaps, deliberately manual: règle de trois, synonyme acrobatique and
* sentence-length variance need document-level analysis that regex fakes
* badly. Read the text too.
......@@ -20,26 +24,123 @@ import path from 'path';
import { CATALOG_VERSION, lint, bodyOf } from '../lib/index.mjs';
const TEXT_EXT = /\.(md|txt|mdx)$/i;
const PKG_VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
function collect(target, files) {
if (TEXT_EXT.test(target) && fs.existsSync(target)) return files.push(path.resolve(target));
if (fs.existsSync(target) && fs.statSync(target).isDirectory()) {
for (const f of fs.readdirSync(target)) {
const p = path.join(target, f);
if (fs.statSync(p).isDirectory()) collect(p, files);
else if (TEXT_EXT.test(f)) files.push(path.resolve(p));
}
const USAGE = `buvard — l'anti-slop qui tache. Blotting paper for AI-flavored prose.
Usage:
buvard check [files|dirs...] [--json] [--hidden] lint markdown/text files
buvard score <file> [--json] single-file score
buvard --help this help
buvard --version package version
Options:
--json machine-readable output
--hidden include dot-directories when walking (skipped by default)
Scoring: 100 base; each hit costs its weight (lexique -5, structure -8,
servile -10; punctuation past budget charges per occurrence: one tiret
cadratin per 500 words, one exclamation per 1000). Hits are review
candidates, never verdicts — the author's voice always wins.`;
/**
* Collect lintable files from a target path. Text files go straight in;
* directories are walked (skipping dot-entries unless `hidden`, and never
* following directory symlinks — readdir Dirents mark them as symlinks, not
* directories). Unresolvable targets and unreadable directories land in
* `errors` as warnings; they never throw.
*/
function collect(target, files, opts, errors) {
let st;
try {
st = fs.statSync(target);
} catch {
errors.push(`buvard: no file or directory for "${target}"`);
return;
}
if (st.isFile()) {
if (TEXT_EXT.test(target)) files.push(path.resolve(target));
else errors.push(`buvard: "${target}" is not .md, .txt or .mdx — skipped`);
return;
}
if (!st.isDirectory()) {
errors.push(`buvard: "${target}" is neither file nor directory — skipped`);
return;
}
let entries;
try {
entries = fs.readdirSync(target, { withFileTypes: true });
} catch (e) {
errors.push(`buvard: cannot read "${target}" (${e.code}) — skipped`);
return;
}
for (const ent of entries) {
if (!opts.hidden && ent.name.startsWith('.')) continue;
const p = path.join(target, ent.name);
if (ent.isDirectory()) collect(p, files, opts, errors);
else if (ent.isFile() && TEXT_EXT.test(ent.name)) files.push(path.resolve(p));
}
}
function scoreReport(file, json) {
const r = { file, ...lint(bodyOf(fs.readFileSync(file, 'utf8'))) };
if (json) {
console.log(JSON.stringify({ buvard: CATALOG_VERSION, ...r }, null, 1));
return;
}
console.error(`buvard: no file or directory for "${target}"`);
console.log(`${r.score}/100 ${path.relative(process.cwd(), r.file)} (${r.words} mots, ${r.hits.length} candidat${r.hits.length === 1 ? '' : 's'})`);
}
function main(argv) {
const json = argv.includes('--json');
const targets = argv.filter((a) => !a.startsWith('--'));
const flags = new Set();
const positional = [];
for (const a of argv) {
if (!a.startsWith('-')) {
positional.push(a);
continue;
}
if (a === '--json' || a === '--hidden') {
flags.add(a);
} else if (a === '-h' || a === '--help') {
console.log(USAGE);
return 0;
} else if (a === '--version') {
console.log(`buvard v${PKG_VERSION} (catalog v${CATALOG_VERSION})`);
return 0;
} else {
console.error(`buvard: unknown option "${a}"\n\n${USAGE}`);
return 2;
}
}
let cmd = 'check';
if (positional[0] === 'check' || positional[0] === 'score') cmd = positional.shift();
const json = flags.has('--json');
const opts = { hidden: flags.has('--hidden') };
const errors = [];
if (cmd === 'score') {
if (positional.length !== 1) {
console.error(`buvard score takes exactly one file\n\n${USAGE}`);
return 2;
}
const files = [];
collect(positional[0], files, opts, errors);
if (errors.length > 0 || files.length === 0) {
errors.forEach((e) => console.error(e));
return 2;
}
scoreReport(files[0], json);
return 0;
}
const files = [];
if (targets.length > 0) targets.forEach((t) => collect(t, files));
else collect('.', files);
if (positional.length > 0) positional.forEach((t) => collect(t, files, opts, errors));
else collect('.', files, opts, errors);
errors.forEach((e) => console.error(e));
if (files.length === 0 && positional.length > 0) return 2;
const results = files.map((file) => ({ file, ...lint(bodyOf(fs.readFileSync(file, 'utf8'))) }));
......
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
const BIN = new URL('../bin/buvard.js', import.meta.url).pathname;
const PKG = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
function run(args, cwd) {
return spawnSync(process.execPath, [BIN, ...args], { cwd, encoding: 'utf8' });
}
const SLOP = 'Soyons honnêtes : le montage cassait.';
function fixture() {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'buvard-cli-'));
fs.writeFileSync(path.join(dir, 'propre.txt'), 'Le montage marche.');
fs.writeFileSync(path.join(dir, 'slop.md'), SLOP);
fs.mkdirSync(path.join(dir, '.caché'));
fs.writeFileSync(path.join(dir, '.caché', 'slop.md'), SLOP);
return dir;
}
test('-h and --help exit 0 and print usage', () => {
for (const flag of ['-h', '--help']) {
const r = run([flag]);
assert.equal(r.status, 0, flag);
assert.match(r.stdout, /Usage:/);
assert.match(r.stdout, /buvard check/);
assert.match(r.stdout, /buvard score/);
assert.match(r.stdout, /--hidden/);
}
});
test('help documents every real option', () => {
const r = run(['--help']);
for (const opt of ['--json', '--hidden', '--version']) assert.ok(r.stdout.includes(opt), opt);
});
test('--version prints package and catalog version', () => {
const r = run(['--version']);
assert.equal(r.status, 0);
assert.match(r.stdout, new RegExp(`v${PKG.version}`));
});
test('unknown option exits 2 and points at --help', () => {
const r = run(['--nope']);
assert.equal(r.status, 2);
assert.match(r.stderr, /unknown option "--nope"/);
assert.match(r.stderr, /--help/);
});
test('-h is never treated as a lint target', () => {
const r = run(['-h']);
assert.equal(r.status, 0);
assert.ok(!r.stderr.includes('no file or directory'));
});
test('check on a file prints the score', () => {
const dir = fixture();
const r = run(['check', path.join(dir, 'slop.md')]);
assert.equal(r.status, 0);
assert.match(r.stdout, /95\/100/);
fs.rmSync(dir, { recursive: true, force: true });
});
test('check --json parses and carries catalog version', () => {
const dir = fixture();
const r = run(['check', '--json', path.join(dir, 'propre.txt')]);
assert.equal(r.status, 0);
const doc = JSON.parse(r.stdout);
assert.ok(doc.buvard);
assert.equal(doc.results.length, 1);
assert.equal(doc.results[0].score, 100);
fs.rmSync(dir, { recursive: true, force: true });
});
test('check skips dot-directories; --hidden includes them', () => {
const dir = fixture();
const plain = run(['check', dir]);
assert.equal(plain.status, 0);
assert.ok(!plain.stdout.includes('.caché'));
const deep = run(['check', '--hidden', dir]);
assert.equal(deep.status, 0);
assert.ok(deep.stdout.includes('.caché'));
fs.rmSync(dir, { recursive: true, force: true });
});
test('no-arg check survives hidden and unreadable directories', () => {
const dir = fixture();
// hidden dir: skipped outright — this is the old `.Trash` EPERM crash path
const trash = path.join(dir, '.Trash');
fs.mkdirSync(trash);
fs.writeFileSync(path.join(trash, 'secret.md'), SLOP);
// non-hidden unreadable dir: warned about, never fatal
const locked = path.join(dir, 'locked');
fs.mkdirSync(locked);
fs.writeFileSync(path.join(locked, 'inner.md'), SLOP);
fs.chmodSync(locked, 0o000);
try {
const r = run([], dir);
assert.equal(r.status, 0, `stderr: ${r.stderr}`);
assert.match(r.stderr, /cannot read/);
assert.ok(!r.stdout.includes('.Trash'));
assert.ok(!r.stdout.includes('secret.md'));
} finally {
fs.chmodSync(locked, 0o755);
fs.rmSync(dir, { recursive: true, force: true });
}
});
test('check on a missing target exits 2 with a message', () => {
const r = run(['check', '/pas/ici/nulle-part.md']);
assert.equal(r.status, 2);
assert.match(r.stderr, /no file or directory/);
});
test('check on a non-text file refuses politely', () => {
const dir = fixture();
fs.writeFileSync(path.join(dir, 'code.js'), 'const x = 1;');
const r = run(['check', path.join(dir, 'code.js')]);
assert.equal(r.status, 2);
assert.match(r.stderr, /not \.md, \.txt or \.mdx/);
fs.rmSync(dir, { recursive: true, force: true });
});
test('score prints one score; wrong arity exits 2', () => {
const dir = fixture();
const ok = run(['score', path.join(dir, 'slop.md')]);
assert.equal(ok.status, 0);
assert.match(ok.stdout, /95\/100/);
assert.equal(run(['score']).status, 2);
assert.equal(run(['score', path.join(dir, 'a.md'), path.join(dir, 'b.md')]).status, 2);
fs.rmSync(dir, { recursive: true, force: true });
});
test('check with no positional defaults to the working directory', () => {
const dir = fixture();
const r = run(['check'], dir);
assert.equal(r.status, 0);
assert.match(r.stdout, /propre\.txt/);
assert.match(r.stdout, /slop\.md/);
fs.rmSync(dir, { recursive: true, force: true });
});
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment