8000 #59 dogfood: switch root knip.json to production-marked config by devill · Pull Request #61 · habit-hooks/habit-hooks · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
c0ac857
#59 dogfood: switch root knip.json to production-marked config
claude Jun 21, 2026
18c00b1
#59 clear test-only export: demote requiresNodeRuntime to private helper
claude Jun 21, 2026
ab2a55f
#59 clear test-only export: demote fallbackNotice to private helper
claude Jun 21, 2026
80e6a33
#59 clear test-only export: demote resolveFix, drive tests via mapIssues
claude Jun 21, 2026
37778fe
#59 clear test-only export: demote getMergeBase, test via getChangedV…
claude Jun 21, 2026
501115d
#59 clear test-only export: demote GitScopeError to private class
claude Jun 21, 2026
e91de5f
#59 clear test-only export: extract seed catalogue, drop listPrompts
claude Jun 21, 2026
ae5642c
#59 clear dead-in-production export: delete buildPresetSensors adapter
claude Jun 21, 2026
8401216
#59 clear test-only exports: demote BaselineVersionError/BaselinePars…
claude Jun 21, 2026
da04453
#59 clear test-only exports: demote singleSmellFor/catalogueSmell
claude Jun 21, 2026
0b1a142
#59 clear test-only exports: demote buildInstallCommand/packagesFor
claude Jun 21, 2026
49c3260
#59 clear test-only export: demote detectLanguage to private helper
claude Jun 21, 2026
69c68ad
#59 clear test-only exports: drop knip-wrap re-export, un-export cons…
claude Jun 21, 2026
946309c
#59 clear test-only exports: extract jscpd-resolve, un-export jscpd i…
claude Jun 21, 2026
0ad0fae
#59 clear dead-in-production file: delete superseded python-preset wr…
claude Jun 21, 2026
dd81573
#59 clear unused exports: demote autoPruneFullRepo/autoPruneNotice
claude Jun 21, 2026
aabd63c
#59 clear unused export: demote reportSkillResult to private helper
claude Jun 21, 2026
17734d4
#59 clear unused export/type: demote globsFor and DiscoverOptions
claude Jun 21, 2026
f666256
#59 clear unused export: drop gratuitous BaselineFile re-export
claude Jun 21, 2026
c9d195c
#59 clear unused type: demote ReapResult
claude Jun 21, 2026
c98b955
#59 clear unused type: demote DetectedLanguage
claude Jun 21, 2026
caa071d
#59 clear unused types: demote GuideResult and GuideInput
claude Jun 21, 2026
cd31ffb
#59 clear unused type: demote SensorFactory
claude Jun 21, 2026
f96b96a
#59 clear unused type: demote SensorRunInput
claude Jun 21, 2026
e5301d8
#59 clear unused type: demote WrapperSpec
claude Jun 21, 2026
eaf3761
#59 clear unused exports/type: demote LeafSpec, trim preset re-exports
claude Jun 21, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions knip.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"$schema": "https://unpkg.com/knip@5/schema.json",
"entry": ["src/cli.ts", "src/index.ts"],
"project": ["src/**/*.ts"],
"ignore": ["tests/**", "dist/**"]
"entry": ["src/cli.ts!", "src/index.ts!", "src/**/*.test.ts"],
"project": ["src/**/*.ts!"],
"ignore": ["dist/**", "tests/**"]
}
4 changes: 2 additions & 2 deletions src/baseline/auto-prune.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { reapBaseline } from './reap.js';
// configPath must match the one used for the main run so the re-scan sees the
// same rules — using a different (or default-discovered) config could wrongly
// mark a still-snoozed file as clean and prune it.
export async function autoPruneFullRepo(cwd: string, configPath?: string): Promise<string[]> {
async function autoPruneFullRepo(cwd: string, configPath?: string): Promise<string[]> {
const baseline = loadBaseline(cwd);
if (Object.keys(baseline.files).length === 0) return [];
const scan = await run(cwd, { configPath, scopeFlags: { all: true }, applyBaseline: false });
Expand All @@ -19,7 +19,7 @@ export async function autoPruneFullRepo(cwd: string, configPath?: string): Promi
return pruned;
}

export function autoPruneNotice(pruned: string[]): string {
function autoPruneNotice(pruned: string[]): string {
const entries = pruned.length === 1 ? 'entry' : 'entries';
return `🧹 Auto-pruned ${String(pruned.length)} fixed baseline ${entries}: ${pruned.join(', ')}\n`;
}
Expand Down
3 changes: 0 additions & 3 deletions src/baseline/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import {
loadBaseline,
saveBaseline,
type BaselineEntry,
type BaselineFile,
} from './store.js';
import { toRepoRelative } from './filter.js';
import { reapBaseline } from './reap.js';
Expand Down Expand Up @@ -152,5 +151,3 @@ export function baselineStatus(cwd: string): CommandResult {
if (entries.length === 0) return ok('Baseline file is empty.\n');
return ok(`${renderStatusLines(cwd, entries).join('\n')}\n`);
}

export type { BaselineFile };
2 changes: 1 addition & 1 deletion src/baseline/reap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { existsSync } from 'node:fs';
import { join } from 'node:path';
import type { BaselineEntry, BaselineFile } from './store.js';

export interface ReapResult {
interface ReapResult {
files: Record<string, BaselineEntry>;
pruned: string[];
}
Expand Down
5 changes: 0 additions & 5 deletions src/baseline/store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ import { join } from 'node:path';
import { createGitRepo, type GitRepo } from '../../tests/helpers/git.js';
import {
BASELINE_FILENAME,
BaselineParseError,
BaselineVersionError,
loadBaseline,
saveBaseline,
} from './store.js';
Expand Down Expand Up @@ -73,7 +71,6 @@ describe('baseline store', () => {
it('throws BaselineVersionError on a future version', () => {
repo = createGitRepo();
repo.writeFile(BASELINE_FILENAME, JSON.stringify({ version: 3, files: {} }));
expect(() => loadBaseline(repo.cwd)).toThrow(BaselineVersionError);
expect(() => loadBaseline(repo.cwd)).toThrow(/unsupported baseline version 3; expected 1 or 2/);
});

Expand Down Expand Up @@ -148,7 +145,6 @@ describe('baseline store', () => {
files: { 'a.ts': { snoozedAt: 'aaa' } },
}),
);
expect(() => loadBaseline(repo.cwd)).toThrow(BaselineParseError);
expect(() => loadBaseline(repo.cwd)).toThrow(/missing 'snoozedAtCommit' string/);
});

Expand All @@ -161,7 +157,6 @@ describe('baseline store', () => {
files: { 'a.ts': { snoozedAtCommit: 'aaa' } },
}),
);
expect(() => loadBaseline(repo.cwd)).toThrow(BaselineParseError);
expect(() => loadBaseline(repo.cwd)).toThrow(/missing 'snoozedAt' string/);
});
});
4 changes: 2 additions & 2 deletions src/baseline/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@ export interface BaselineFile {
files: Record<string, BaselineEntry>;
}

export class BaselineVersionError extends Error {
class BaselineVersionError extends Error {
constructor(version: number) {
super(`unsupported baseline version ${String(version)}; expected 1 or 2`);
this.name = 'BaselineVersionError';
}
}

export class BaselineParseError extends Error {
class BaselineParseError extends Error {
constructor(message: string) {
super(`failed to parse baseline: ${message}`);
this.name = 'BaselineParseError';
Expand Down
40 changes: 40 additions & 0 deletions src/checks/jscpd-resolve.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { createRequire } from 'node:module';
import { existsSync, readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { detectTool } from '../detect/tool.js';
import { type BinResolution } from '../wrap/notices.js';

const require = createRequire(import.meta.url);

function findPackageRoot(start: string): string {
let dir = start;
while (dir !== dirname(dir)) {
if (existsSync(join(dir, 'package.json'))) return dir;
dir = dirname(dir);
}
throw new Error(`Could not find package.json from ${start}`);
}

function bundledJscpdBin(): string {
const main = require.resolve('jscpd');
const pkgRoot = findPackageRoot(dirname(main));
const pkg = JSON.parse(readFileSync(join(pkgRoot, 'package.json'), 'utf8')) as { bin?: { jscpd?: string } | string };
const binRel = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.jscpd ?? 'bin/jscpd';
return join(pkgRoot, binRel);
}

function tryBundledJscpdBin(resolver: () => string): string | null {
try {
return resolver();
} catch {
return null;
}
}

export function resolveJscpdBin(cwd: string, fallbackResolver: () => string = bundledJscpdBin): BinResolution | null {
const detected = detectTool(cwd, 'jscpd');
if (detected !== null) return { binPath: detected.binPath, isFallback: false };
const fallback = tryBundledJscpdBin(fallbackResolver);
if (fallback === null) return null;
return { binPath: fallback, isFallback: true };
}
66 changes: 37 additions & 29 deletions src/checks/jscpd-wrap.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import { chmodSync, mkdtempSync, mkdirSync, readdirSync, rmSync, symlinkSync, wr
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { jscpdWrap, resolveJscpdBin, runJscpdWrap, tryBundledJscpdBin } from './jscpd-wrap.js';
import { jscpdWrap } from './jscpd-wrap.js';
import { resolveJscpdBin } from './jscpd-resolve.js';
import type { CheckOutcome, Rule } from '../types.js';

const here = dirname(fileURLToPath(import.meta.url));
Expand Down Expand Up @@ -50,12 +51,22 @@ async function runWrap(cwd: string, files: string[]): Promise<CheckOutcome> {
return asOutcome(await jscpdWrap.run(files, RULES, cwd));
}

async function runWrapWithTmpRoot(cwd: string, files: string[], tmpRoot: string): Promise<CheckOutcome> {
return runJscpdWrap(files, cwd, { resolution: resolveJscpdBin(cwd), tmpRoot });
}

function jscpdEntries(dir: string): string[] {
return readdirSync(dir).filter((n) => n.startsWith('hh-jscpd-'));
// jscpdWrap.run creates its scratch report dir under os.tmpdir() (makeReportDir).
// os.tmpdir() honours TMPDIR per call, so pointing TMPDIR at a private dir lets us
// observe the wrap's own scratch cleanup race-free against parallel tests. Returns
// the scratch dirs the wrap left behind in that private root.
async function runWrapWithPrivateTmp(cwd: string, files: string[]): Promise<string[]> {
const tmpRoot = mkdtempSync(join(tmpdir(), 'hh-jscpd-root-'));
const original = process.env.TMPDIR;
process.env.TMPDIR = tmpRoot;
try {
await runWrap(cwd, files);
return readdirSync(tmpRoot);
} finally {
if (original === undefined) delete process.env.TMPDIR;
else process.env.TMPDIR = original;
rmSync(tmpRoot, { recursive: true, force: true });
}
}

describe('jscpdWrap', () => {
Expand Down Expand Up @@ -131,12 +142,10 @@ describe('jscpdWrap', () => {
writeJscpdConfig(cwd);
const a = writeFile(cwd, 'a.ts', DUPLICATE);
const b = writeFile(cwd, 'b.ts', DUPLICATE);
const tmpRoot = mkdtempSync(join(tmpdir(), 'hh-jscpd-root-'));

await runWrapWithTmpRoot(cwd, [a, b], tmpRoot);
const leftover = await runWrapWithPrivateTmp(cwd, [a, b]);

expect(jscpdEntries(tmpRoot)).toEqual([]);
rmSync(tmpRoot, { recursive: true, force: true });
expect(leftover).toEqual([]);
}, 30_000);

it('cleans up the tmpdir even when the report is missing', async () => {
Expand All @@ -146,12 +155,10 @@ describe('jscpdWrap', () => {
const stub = writeFile(cwd, 'node_modules/jscpd/stub.js', '#!/usr/bin/env node\nprocess.exit(0);\n');
chmodSync(stub, 0o755);
writeFileSync(join(jscpdDir, 'package.json'), JSON.stringify({ bin: { jscpd: 'stub.js' } }));
const tmpRoot = mkdtempSync(join(tmpdir(), 'hh-jscpd-root-'));

await runWrapWithTmpRoot(cwd, [writeFile(cwd, 'a.ts', 'x')], tmpRoot);
const leftover = await runWrapWithPrivateTmp(cwd, [writeFile(cwd, 'a.ts', 'x')]);

expect(jscpdEntries(tmpRoot)).toEqual([]);
rmSync(tmpRoot, { recursive: true, force: true });
expect(leftover).toEqual([]);
});

it('emits a spawn-failure stderr notice when the jscpd binary cannot be executed', async () => {
Expand Down Expand Up @@ -192,28 +199,29 @@ describe('jscpdWrap', () => {
expect(outcome.violations.every((v) => v.ruleId === 'duplicated-code')).toBe(true);
}, 30_000);

it('tryBundledJscpdBin returns null when the resolver throws', () => {
expect(
tryBundledJscpdBin(() => {
throw new Error('synthetic');
}),
).toBeNull();
});

it('resolveJscpdBin returns null when no detection and bundled resolver throws', () => {
it('resolveJscpdBin returns null when no consumer jscpd and the bundled fallback throws', () => {
// No consumer node_modules in cwd, so detection fails; the injected bundled
// resolver throws, so tryBundledJscpdBin swallows it and resolution is null.
// This null is exactly what makes jscpdWrap.run emit the "could not locate
// bundled bin" notice in production.
expect(
resolveJscpdBin(cwd, () => {
throw new Error('synthetic');
}),
).toBeNull();
});

it('runJscpdWrap returns a notice and zero violations when no bin can be resolved', async () => {
const file = writeFile(cwd, 'a.ts', 'export const a = 1;\n');
it('resolveJscpdBin prefers a consumer-detected bin over the bundled fallback', () => {
const jscpdDir = join(cwd, 'node_modules', 'jscpd');
mkdirSync(jscpdDir, { recursive: true });
const stub = writeFile(cwd, 'node_modules/jscpd/stub.js', '#!/usr/bin/env node\n');
chmodSync(stub, 0o755);
writeFileSync(join(jscpdDir, 'package.json'), JSON.stringify({ bin: { jscpd: 'stub.js' } }));

const outcome = await runJscpdWrap([file], cwd, { resolution: null });
const resolution = resolveJscpdBin(cwd, () => {
throw new Error('bundled fallback must not be consulted');
});

expect(outcome.violations).toEqual([]);
expect(outcome.stderr?.some((s) => s.includes('could not locate bundled bin'))).toBe(true);
expect(resolution).toEqual({ binPath: stub, isFallback: false });
});
});
59 changes: 10 additions & 49 deletions src/checks/jscpd-wrap.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
import { createRequire } from 'node:module';
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { join } from 'node:path';
import { type ShellResult } from '../wrap/shell.js';
import { detectTool, TOOL_CONFIG_FILENAMES } from '../detect/tool.js';
import { TOOL_CONFIG_FILENAMES } from '../detect/tool.js';
import { hasPackageJsonKey } from '../detect/package-json.js';
import { absolutize, emptyOutcome, firstLine, noticesFor, type BinResolution } from '../wrap/notices.js';
import { isSpawnSkip, skipOutcome, spawnWrapped } from '../wrap/run.js';
import { resolveJscpdBin } from './jscpd-resolve.js';
import { JSCPD_SMELL } from '../config/tool-smells.js';
import type { Check, CheckOutcome, Violation } from '../types.js';

const require = createRequire(import.meta.url);

const REPORT_FILENAME = 'jscpd-report.json';

interface JscpdLocation {
Expand All @@ -29,39 +27,6 @@ interface JscpdReport {
duplicates?: JscpdClone[];
}

function findPackageRoot(start: string): string {
let dir = start;
while (dir !== dirname(dir)) {
if (existsSync(join(dir, 'package.json'))) return dir;
dir = dirname(dir);
}
throw new Error(`Could not find package.json from ${start}`);
}

function bundledJscpdBin(): string {
const main = require.resolve('jscpd');
const pkgRoot = findPackageRoot(dirname(main));
const pkg = JSON.parse(readFileSync(join(pkgRoot, 'package.json'), 'utf8')) as { bin?: { jscpd?: string } | string };
const binRel = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.jscpd ?? 'bin/jscpd';
return join(pkgRoot, binRel);
}

export function tryBundledJscpdBin(resolver: () => string = bundledJscpdBin): string | null {
try {
return resolver();
} catch {
return null;
}
}

export function resolveJscpdBin(cwd: string, fallbackResolver: () => string = bundledJscpdBin): BinResolution | null {
const detected = detectTool(cwd, 'jscpd');
if (detected !== null) return { binPath: detected.binPath, isFallback: false };
const fallback = tryBundledJscpdBin(fallbackResolver);
if (fallback === null) return null;
return { binPath: fallback, isFallback: true };
}

function reportMissingWarning(cwd: string, code: number, stderr: string): string {
const detail = firstLine(stderr);
const suffix = detail.length > 0 ? `: ${detail}` : '';
Expand Down Expand Up @@ -124,8 +89,8 @@ function buildArgs(reportDir: string): string[] {
return ['-r', 'json', '-o', reportDir, '--silent', '--noTips', '-n', '.'];
}

function makeReportDir(tmpRoot: string = tmpdir()): string {
return mkdtempSync(join(tmpRoot, 'hh-jscpd-'));
function makeReportDir(): string {
return mkdtempSync(join(tmpdir(), 'hh-jscpd-'));
}

function removeReportDir(reportDir: string): void {
Expand Down Expand Up @@ -155,8 +120,8 @@ async function runOnce(inputs: RunInputs, reportDir: string): Promise<CheckOutco
return { violations: reportToViolations(report, inputs.scope, inputs.cwd), stderr: inputs.notices };
}

async function runJscpd(inputs: RunInputs, tmpRoot?: string): Promise<CheckOutcome> {
const reportDir = makeReportDir(tmpRoot);
async function runJscpd(inputs: RunInputs): Promise<CheckOutcome> {
const reportDir = makeReportDir();
try {
return await runOnce(inputs, reportDir);
} finally {
Expand All @@ -177,22 +142,18 @@ function noBinOutcome(cwd: string): CheckOutcome {
return emptyOutcome([unresolvedBinWarning(cwd)]);
}

export async function runJscpdWrap(
files: string[],
cwd: string,
{ resolution, tmpRoot }: { resolution: BinResolution | null; tmpRoot?: string },
): Promise<CheckOutcome> {
async function runJscpdWrap(files: string[], cwd: string, resolution: BinResolution | null): Promise<CheckOutcome> {
if (files.length === 0) return { violations: [], stderr: [] };
if (resolution === null) return noBinOutcome(cwd);
const notices = noticesFor('jscpd', resolution, cwd);
if (!hasJscpdConfig(cwd)) return noConfigOutcome(cwd, notices);
return runJscpd({ resolution, cwd, scope: new Set(files), notices }, tmpRoot);
return runJscpd({ resolution, cwd, scope: new Set(files), notices });
}

export const jscpdWrap: Check = {
id: 'jscpd',
async run(files, _rules, cwd) {
const runCwd = cwd ?? process.cwd();
return runJscpdWrap(files, runCwd, { resolution: resolveJscpdBin(runCwd) });
return runJscpdWrap(files, runCwd, resolveJscpdBin(runCwd));
},
};
2 changes: 1 addition & 1 deletion src/checks/knip-resolve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ function readMajorFromPackageJson(path: string): number | null {
}
}

export function consumerKnipMajor(cwd: string): number | null {
function consumerKnipMajor(cwd: string): number | null {
return readMajorFromPackageJson(join(cwd, 'node_modules', 'knip', 'package.json'));
}

Expand Down
Loading
0