8000 Add ruff BLE001 as a swallowed-exception smell by LiinaSuoniemi · Pull Request #62 · 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
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
9 changes: 9 additions & 0 deletions docs/DECISIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,15 @@ Each is labelled _agent decision_ per the working agreement.
`oversized-file` for Python** — no clean ruff rule (GOAL says best-effort or
defer). deptry's `/dev/stdout` JSON is POSIX-only, fine for the Linux e2e.

- **Added ruff `BLE001` -> `swallowed-exception` (new smell).** A broad `except`
that catches and discards the error is a silent-failure risk and has no clean
TypeScript twin, so `swallowed-exception` is the first catalogue smell to carry
`source: 'ruff'` (added to `RuleSource` in `types.ts` and to config validation,
mirroring how `knip` is a spec-driven source). Severity `suggested`: blind-except
has legitimate top-level uses (a request handler, a worker loop), so it coaches
rather than failing the run. Exercised only when ruff is on PATH, skipped on CI
like the other Python sensors.

- The live-ruff preset test skips when ruff is not on PATH (CI without the Python
toolchain) so the suite stays green everywhere; it runs in the provisioned env.

Expand Down
5 changes: 5 additions & 0 deletions docs/smell-vocabulary.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,15 @@ exits 0. The mapper config can override it per project.
| `unused-export` | Unused export | enforced |
| `unused-dependency` | Unused dependency | enforced |
| `unused-import` | Unused import | enforced |
| `swallowed-exception` | Swallowed exception | suggested |
| `parse-error` | Parse / config error | enforced |

`unused-import` was added as a general smell (agent decision) so ruff `F401`
has a canonical home; see `DECISIONS.md`.

`swallowed-exception` is the first smell sourced only from ruff (`BLE001`), with
no TypeScript twin; it carries `source: 'ruff'`. See `DECISIONS.md`.

## TypeScript/JavaScript preset translation

The raw rule IDs the TS/JS preset sensors emit, and the smell key each maps
Expand Down Expand Up @@ -91,6 +95,7 @@ to (the rest of the catalogue is shared — only the sensor layer differs).
| `ruff:PLR0915` | `oversized-function` |
| `ruff:F841` | `unused-variable` |
| `ruff:F401` | `unused-import` |
| `ruff:BLE001` 10BC8 | `swallowed-exception` |
| `jscpd:duplication` | `duplicated-code` |
| `deptry:DEP002` | `unused-dependency` |
| `line-count:max-module-lines` | `oversized-file` |
Expand Down
13 changes: 13 additions & 0 deletions src/config/catalogue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,11 +160,24 @@ const jscpdRules: Rule[] = [
},
];

// ruff-only smells: no TypeScript-tool twin, so they carry source 'ruff'.
const ruffRules: Rule[] = [
{
id: 'swallowed-exception',
source: 'ruff',
severity: 'suggested',
changedFilesOnly: true,
title: 'Swallowed exception',
description: 'A broad except that catches and discards the error hides failures; catch the specific exception and handle or re-raise it.',
},
];

export const defaultRules: Rule[] = [
...tier1Rules,
...tier2Rules,
...tier3Rules,
...customRules,
...jscpdRules,
...ruffRules,
...unusedRules,
];
5 changes: 3 additions & 2 deletions src/config/tool-smells.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@ export const KNIP_PRODUCES = Object.values(KNIP_SMELL_MAP);
// Python tool specs (the generalized AdapterSpec model): ruff + deptry.
export const RUFF_SPEC: DeclarativeSensorSpec = {
id: 'ruff',
produces: ['high-complexity', 'too-many-parameters', 'oversized-function', 'unused-variable', 'unused-import'],
command: 'ruff check --output-format=json --select=C901,PLR0913,PLR0915,F841,F401 ${files}',
produces: ['high-complexity', 'too-many-parameters', 'oversized-function', 'unused-variable', 'unused-import', 'swallowed-exception'],
command: 'ruff check --output-format=json --select=C901,PLR0913,PLR0915,F841,F401,BLE001 ${files}',
items: '[]',
fields: { smell: 'code', file: 'filename', line: 'location.row', column: 'location.column', message: 'message' },
map: {
Expand All @@ -68,6 +68,7 @@ export const RUFF_SPEC: DeclarativeSensorSpec = {
PLR0915: 'oversized-function',
F841: 'unused-variable',
F401: 'unused-import',
BLE001: 'swallowed-exception',
},
};

Expand Down
4 changes: 2 additions & 2 deletions src/config/validate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
import { validateFiles, validateSensors } from './validate-sensors.js';

const SEVERITIES: readonly Severity[] = ['enforced', 'suggested'];
const SOURCES: readonly RuleSource[] = ['eslint', 'jscpd', 'knip', 'custom'];
const SOURCES: readonly RuleSource[] = ['eslint', 'jscpd', 'knip', 'ruff', 'custom'];

function validateOptionalBoolean(value: unknown, path: string): void {
if (value === undefined) return;
Expand All @@ -32,7 +32,7 @@ function validateSeverity(value: unknown, path: string): void {

function validateSource(value: unknown, path: string): void {
if (typeof value !== 'string' || !SOURCES.includes(value as RuleSource)) {
fail(path, `one of 'eslint', 'jscpd', 'knip', 'custom'`);
fail(path, `one of 'eslint', 'jscpd', 'knip', 'ruff', 'custom'`);
}
}

Expand Down
9 changes: 9 additions & 0 deletions src/prompts/swallowed-exception.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
A broad `except` (`except:`, `except Exception`, `except BaseException`) that swallows the error is hiding a failure you have not understood, not handling one you planned for. Before writing it, name the specific error you expect here and why. That sentence is usually the fix.

Catch only the exception you actually expect: `ValueError`, `KeyError`, `TimeoutError`, whatever the call can really raise. If you cannot name it, you are guessing, and every other error should stay free to surface where it can be seen.

Then do something real: recover, or add context and re-raise (`raise ... from err`), or let it propagate. Catching broadly and then `pass`, logging-and-continuing, or returning a default is the swallow. The bug does not disappear. It resurfaces later, far from here, where it costs the most.

Narrowing the type or adding `# noqa` only to quiet the checker is not a fix if the error is still discarded. The smell is the silent swallow, not the width of the catch.

One legitimate case: a top-level boundary that must stay alive (a request handler, a worker loop, a CLI entry point). Even there, catch as narrow as you can, log the full traceback, and never discard the error silently. If unsure, check with a human first.
34 changes: 34 additions & 0 deletions src/python-acceptance.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const pythonProject = join(here, '..', 'tests', 'fixtures', 'python-project');
// toolchain is absent (CI without it) so the suite stays green everywhere.
const PY_TOOLS =
spawnSync('ruff', ['--version']).status === 0 && spawnSync('deptry', ['--version']).status === 0;
const RUFF = spawnSync('ruff', ['--version']).status === 0;

interface ExpectedCount {
ruleId: string;
Expand Down Expand Up @@ -135,3 +136,36 @@ describe('python needs-extraction (composite sensor)', () => {
expect(violations.filter((v) => v.ruleId === 'duplicated-code')).toEqual([]);
}, 30_000);
});

// ruff BLE001 -> swallowed-exception. Needs only ruff on PATH (no deptry), so it
// gates on RUFF alone and asserts on violations, not exit code.
describe.skipIf(!RUFF)('python swallowed-exception (ruff BLE001)', () => {
let dir = '';

afterEach(() => {
if (dir) rmSync(dir, { recursive: true, force: true });
dir = '';
});

function pythonFile(body: string): void {
dir = mkdtempSync(join(tmpdir(), 'hh-py-swallowed-'));
writeFileSync(join(dir, 'habit-hooks.config.json'), JSON.stringify({ language: 'python' }));
writeFileSync(join(dir, 'risky.py'), body);
}

it('fires for a broad except that swallows the error', async () => {
pythonFile('def risky(x):\n try:\n return int(x)\n except Exception:\n return None\n');

const result = await run(dir);

expect(result.violations.some((v) => v.ruleId === 'swallowed-exception')).toBe(true);
}, 30_000);

it('does not fire for a specific, named except', async () => {
pythonFile('def risky(x):\n try:\n return int(x)\n except ValueError:\n return None\n');

const result = await run(dir);

expect(result.violations.some((v) => v.ruleId === 'swallowed-exception')).toBe(false);
}, 30_000);
});
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export type Severity = 'enforced' | 'suggested';
export type RuleSource = 'eslint' | 'jscpd' | 'knip' | 'custom';
export type RuleSource = 'eslint' | 'jscpd' | 'knip' | 'ruff' | 'custom';

export interface CommentCheckThresholds {
maxSingleLineChars: number;
Expand Down
0