diff --git a/.changeset/check-diff-scope.md b/.changeset/check-diff-scope.md new file mode 100644 index 000000000..bad21a5ce --- /dev/null +++ b/.changeset/check-diff-scope.md @@ -0,0 +1,5 @@ +--- +"@taskless/cli": patch +--- + +`check --diff` scopes a check to the files a unified diff changes. Pipe one in (`git diff --staged | taskless check --diff`), or name a file with `--diff=`; the value only ever follows `=`, so `check --diff src/a.ts` reads `src/a.ts` as a path and refuses the pair. Every file the diff adds or modifies is checked whole, including lines it did not change. Deleted files are skipped, and files under `.taskless/` or `.git/` are never checked from a diff, so a change that only adds a rule no longer fails on the rule's own `tests/fail` fixtures. An empty diff exits 0 having checked nothing; input that is not a unified diff, a terminal on stdin, and a diff combined with paths are refused with `INVALID_INPUT`. The CLI runs no git: the `ci` and `hooks` recipes give the command that produces the diff (`git diff --no-ext-diff --no-color --relative ...`), replacing the `$(git diff --name-only ...)` expansion they used before. diff --git a/openspec/changes/archive/2026-12-05-check-diff-scope/.openspec.yaml b/openspec/changes/archive/2026-12-05-check-diff-scope/.openspec.yaml new file mode 100644 index 000000000..35a260cfb --- /dev/null +++ b/openspec/changes/archive/2026-12-05-check-diff-scope/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-12-05 diff --git a/openspec/changes/archive/2026-12-05-check-diff-scope/design.md b/openspec/changes/archive/2026-12-05-check-diff-scope/design.md new file mode 100644 index 000000000..27b2b9301 --- /dev/null +++ b/openspec/changes/archive/2026-12-05-check-diff-scope/design.md @@ -0,0 +1,40 @@ +## Context + +`check` takes positional paths (`classifyPaths` in `commands/check.ts`): missing paths are skipped with a notice, paths outside the project are refused, and the surviving list goes to all three engines through `scanProject`. ast-grep and Vale apply the `.taskless/**` and `.git/**` exclusions only on a whole-project walk (`isWholeProjectWalk`), on the principle that a path the caller named is a request. The runtime engine narrows with ast-grep over the same list. Engines read the working tree; the run snapshot holds only `.taskless/rules/`. + +## Goals / Non-Goals + +**Goals:** + +- A diff in, the set of files it changes checked whole, with one exit code meaning the same as any other `check`. +- No git invocation, configuration, or repository assumption inside the CLI. +- Every way the input can fail to describe a change is an error or a named notice, never a silent clean run. + +**Non-Goals:** + +- Filtering findings to changed lines. Decided against: it would report a file clean that is not. +- Checking staged content when it differs from the working tree. The engines read the working tree; see Risks. +- Prefix styles other than one leading path component (`a/`, `b/`, `i/`, `w/`, `c/`). Producing a conforming diff is the integration's job, and the recipes give the canonical command. + +## Decisions + +**Read a diff, never run git.** The alternative, `--staged` and `--diff ` flags that shell out to git, bakes one VCS's commands, configuration (`diff.external`, `color.ui`, `diff.noprefix`) and repository-shape assumptions (merge bases on shallow clones) into the deterministic side. A diff on stdin is the same text whatever produced it, and the parser is testable with fixture files and no repository. The Taskless service already holds each PR's diff, so the upkeep path needs no checkout to compute one. + +**Parse file headers only.** With whole-file scope the hunks carry nothing `check` uses, so the parser reads only the per-file headers: `diff --git a/X b/Y`, `---`/`+++` lines, `rename to`, `new file mode`, `deleted file mode`, and `Binary files ... differ`. The changed path is the `+++` path with its first component stripped, falling back to the `diff --git` new-side path when there is no `+++` (binary, mode-only, pure rename). `+++ /dev/null` is a deletion and contributes no path. C-quoted paths (`"a/caf\303\251.md"`) are unquoted. A hand-written parser over a few line shapes, rather than a dependency: the existing parsers on npm parse hunks we would discard, and this repository's guidance is not to add a dependency for one call site. + +**Unrecognized input is an error.** Input that is non-empty after trimming but contains no file header is refused with `INVALID_INPUT`. This is the case where a user's `diff.external` (difftastic, say) or forced color produced something that is not a unified diff; reading it as "no files changed" would be a green run that checked nothing, the defect #475 fixed for paths. Empty input is legitimate (nothing staged) and exits 0 with a notice. + +**Diff paths go through the existing path pipeline, then the exclusions.** Parsed paths are classified exactly like positional paths (missing skipped and named, outside refused), then paths under `.taskless/` or `.git/` at any depth are dropped and named in one notice. The exclusion reuses the directory list ast-grep and Vale already use for a whole-project walk, so the three definitions of "not the user's code" cannot drift. Applying it here and not to positional paths keeps the existing rule intact: the caller did not name these paths, the diff did. If nothing survives, the run exits 0 like an all-missing path list does today, with the notices saying why. + +**One flag whose value comes only from `=`.** `--diff` reads stdin; `--diff=` reads a file. A flag with an optional value that could also take the next token would make `check --diff src/a.ts` ambiguous between a diff file and a positional path, since positional paths are how lint-staged, lefthook, pre-commit and existing CI pass files and cannot move behind a flag. Taking the value only from `=` is git's convention for optional values (`--color[=]`, `--abbrev[=]`) and removes the ambiguity: `--diff src/a.ts` is stdin plus a path, which is refused, so a caller who meant a file gets an error rather than a misreading. The shared argv scanner gains an optional-value class for this: it records `--diff=` as a value and never consumes the token after a bare `--diff`. The alternative, two flags (`--diff` and `--diff-file `), also works but spends a second name on one input. Required-value flags (`--rule`, `--timeout`, `--dir`) keep accepting both `--flag value` and `--flag=value`: they are never ambiguous, because they always take a value. + +**Refuse a terminal stdin.** `--diff` with `process.stdin.isTTY` set is refused with `INVALID_INPUT` naming the piped form, instead of blocking on a read nobody will satisfy. + +**Refuse `--diff` with positional paths.** Their intersection is a plausible feature, but nobody has asked for it, and silently preferring one source would check something other than what one of the two arguments said. + +## Risks / Trade-offs + +- [A partially staged file is checked as it is in the working tree] → The diff decides which files, the working tree decides their content, as with positional paths today. A commit can pass on an unstaged fix, or fail on an unstaged mistake. The `hooks` recipe keeps lint-staged (which hides unstaged changes) as the preferred route and states this for the piped form. +- [A monorepo diff is repo-root-relative while `check` runs in a package] → Without `--relative`, every path resolves under the package and is skipped as missing, giving exit 0 with a notice listing them. The recipes use `git diff --relative` from the package directory. The notice names every skipped path, so it is visible, but it does not fail the run, because an all-deletions diff produces the same input legitimately. +- [The upkeep PR's new rule is never exercised by its own diff check] → Intended: the PR changes no source file. The rule meets pre-existing code on the first full scan after merge, which is a policy question for upkeep itself (fix in the same PR, ship as a warning, or accept it), outside this change. The exclusion notice names the rule files, and `verify` remains the test of the rule. +- [Whole-file scope surfaces old findings in a touched file] → Intended, by decision: a changed file must be clean. diff --git a/openspec/changes/archive/2026-12-05-check-diff-scope/proposal.md b/openspec/changes/archive/2026-12-05-check-diff-scope/proposal.md new file mode 100644 index 000000000..31f7ba9eb --- /dev/null +++ b/openspec/changes/archive/2026-12-05-check-diff-scope/proposal.md @@ -0,0 +1,38 @@ +## Why + +`check` can already scan a list of files, but a caller has to build that list with `$(git diff --name-only ...)`, which splits filenames on whitespace, turns an empty list into a full scan unless guarded, and passes every path as an explicit request. Explicit paths skip the whole-project exclusions, so a diff that touches `.taskless/` scans the rules' own `tests/fail/` fixtures. Measured on this repository: the files of `sg/no-eval` and `vale/no-em-dashes`, passed the way the CI recipe passes a diff, report 6 errors and exit 1, every one from a fixture written to fail. That is exactly the diff a Taskless upkeep PR produces (it adds a rule and nothing else), so the repository's own diff-scoped check goes red on the rule being added. + +Three callers need "check what this change touches": a pre-commit hook over staged files, CI that judges incoming code, and the upkeep PRs. All three already hold a unified diff, or can produce one with a single command, so `check` should read one. + +## What Changes + +- `check --diff` reads a unified diff from stdin and checks every file the diff adds or modifies, **whole file**. Findings anywhere in a changed file are reported, including ones on lines the diff did not touch: a changed file must be clean to pass. There is no changed-lines mode, by decision: a narrowed result would report a file as clean when it is not. +- `check --diff=` reads the diff from a file instead. The value is taken only from the `=` form, the way git spells its optional-value flags (`--color[=]`), so `check --diff src/a.ts` is never read as a diff file. +- The CLI never runs git. The diff is plain text the caller supplies, so any tool that emits a unified diff with `a/`/`b/` prefixes works (git, jj, Mercurial, `gh pr diff`, a diff the Taskless service fetched from GitHub). +- Paths from a diff are chosen by the CLI rather than named by the caller, so the whole-project exclusions apply: paths under `.taskless/` and `.git/` are not checked, and are named in a notice. +- An empty diff exits 0 with a notice and checks nothing. Non-empty input that names no file is refused with `INVALID_INPUT` rather than reported clean. `--diff` with stdin attached to a terminal is refused rather than waiting for input. `--diff` combined with positional paths is refused. +- The `ci` and `hooks` recipes pipe a canonical diff command into `check --diff` (`git diff --no-ext-diff --no-color --relative ...`) instead of expanding a file list into the command line. +- Positional paths are unchanged: a path the caller names is still checked as named. + +## Capabilities + +### New Capabilities + +(none) + +### Modified Capabilities + +- `cli-check`: adds diff-scoped checking (`--diff[=]`), its input errors, and the exclusions a diff-derived file list is subject to. +- `cli-agent`: the `ci` recipe's diff scan becomes a piped `check --diff`; the `hooks` recipe gains the piped form for hook tools that do not supply a file list themselves. + +## Delivery shape + +**Single PR.** The parser, the flags, the recipes, and their tests are one reviewable diff, well under the stacking threshold, and none of it is correct without the rest: the recipes name a flag that only exists with the CLI change. + +## Impact + +- `packages/cli/src/commands/check.ts`: one new flag; the diff-derived path list feeds the existing path classification and scan. +- A new unified-diff file-list parser under `packages/cli/src/util/` (no new dependency). +- `packages/cli/src/agent/ci.md`, `packages/cli/src/agent/hooks.md`: recipe text and examples; topic versions bump. +- Tests for the parser, the command's input handling, and the fixture-exclusion case above. +- A `patch` changeset (the package is `0.y.z`; this adds surface and changes nothing a consumer must react to). diff --git a/openspec/changes/archive/2026-12-05-check-diff-scope/specs/cli-agent/spec.md b/openspec/changes/archive/2026-12-05-check-diff-scope/specs/cli-agent/spec.md new file mode 100644 index 000000000..6a00109b7 --- /dev/null +++ b/openspec/changes/archive/2026-12-05-check-diff-scope/specs/cli-agent/spec.md @@ -0,0 +1,45 @@ +## MODIFIED Requirements + +### Requirement: The ci recipe runs the launcher with Node supplied by the job + +The `ci` recipe SHALL generate CI configuration that runs `node .taskless/bin/cli.mjs check`, for a full scan, and, for a diff scan, pipes the pull request's diff into `node .taskless/bin/cli.mjs check --diff`, from the repository root. The diff command SHALL be `git diff --no-ext-diff --no-color --relative ...HEAD`, and the recipe SHALL NOT expand a file list into the `check` command line. It SHALL NOT generate a `npx`, `pnpm dlx`, `yarn dlx`, or `bunx` call to the CLI, and SHALL NOT ask the reader to choose a package manager launcher. It SHALL use `node ` rather than `./`, since a CI checkout can lose the executable bit and a Windows runner does not honour a shebang. + +The recipe SHALL require that the generated job make Node available itself, through the CI system's Node setup step or a Node container image, and SHALL say that the job does not need the project's own language toolchain or a `package.json`. It SHALL name the launcher's version source, `.taskless/taskless.json`, as what decides which CLI version CI runs, so an upgrade reaches CI through the same commit that updates `.taskless/`. + +The recipe SHALL have the generated job cache `.taskless/.cache` between runs where the CI system supports a cache, with a key that includes the runner's operating system and a hash of `.taskless/bin/cli.lock.json`, so a restored cache never crosses platforms and an upgrade starts a fresh one. + +#### Scenario: GitHub Actions template + +- **WHEN** the `ci` recipe is rendered +- **THEN** its GitHub Actions template SHALL contain `node .taskless/bin/cli.mjs check` +- **AND** SHALL contain a Node setup step +- **AND** SHALL NOT contain `%(PACKAGE_MANAGER_DLX)s` + +#### Scenario: A repository without package.json + +- **WHEN** the `ci` recipe is followed in a repository with no `package.json` +- **THEN** the recipe SHALL direct the job to supply Node itself, and SHALL NOT tell the reader to add a `package.json` + +#### Scenario: The launcher cache is restored between runs + +- **WHEN** the `ci` recipe is rendered +- **THEN** its GitHub Actions template SHALL cache the path `.taskless/.cache` +- **AND** the cache key SHALL include `runner.os` and `hashFiles('.taskless/bin/cli.lock.json')` + +#### Scenario: The diff scan pipes a diff + +- **WHEN** the `ci` recipe is rendered +- **THEN** its diff scan SHALL pipe `git diff --no-ext-diff --no-color --relative` into `node .taskless/bin/cli.mjs check --diff` +- **AND** SHALL NOT contain `$(git diff` inside a `check` command line + +## ADDED Requirements + +### Requirement: The hooks recipe pipes the staged diff where the tool supplies no file list + +For hook tools that do not pass staged filenames themselves (husky or simple-git-hooks without lint-staged), the `hooks` recipe SHALL generate `git diff --staged --no-ext-diff --no-color --relative | node .taskless/bin/cli.mjs check --diff`, and SHALL NOT build a file list in a shell variable. It SHALL state that `check` reads the working tree, so a file with unstaged edits is checked as it is on disk rather than as staged, and SHALL keep lint-staged as the recommended route where that matters. + +#### Scenario: husky example + +- **WHEN** the `hooks` recipe is rendered +- **THEN** its husky example SHALL pipe `git diff --staged` into `node .taskless/bin/cli.mjs check --diff` +- **AND** SHALL NOT contain `FILES=$(` diff --git a/openspec/changes/archive/2026-12-05-check-diff-scope/specs/cli-check/spec.md b/openspec/changes/archive/2026-12-05-check-diff-scope/specs/cli-check/spec.md new file mode 100644 index 000000000..3f08015c5 --- /dev/null +++ b/openspec/changes/archive/2026-12-05-check-diff-scope/specs/cli-check/spec.md @@ -0,0 +1,109 @@ +## ADDED Requirements + +### Requirement: Check scopes a run to the files a unified diff changes + +`check --diff` SHALL read a unified diff from stdin, and `check --diff=` SHALL read one from the named file. The flag SHALL take a value only from the `=` form: the token after a bare `--diff` SHALL NOT be read as its value. The CLI SHALL derive the run's paths from the diff's file headers and SHALL NOT invoke a version-control tool to do so. + +Each file the diff adds, modifies, renames, or copies SHALL contribute its new-side path, taken from the `+++` header with its first path component removed, or from the `diff --git` header when the file has no `+++` header (a binary, mode-only, or pure-rename change). A file the diff deletes (`+++ /dev/null`) SHALL contribute no path. C-quoted paths SHALL be unquoted before use. + +The derived paths SHALL then be handled as positional paths are: a path that does not exist is skipped and named in a notice, and a path outside the project is refused with `INVALID_INPUT`. + +Every derived file SHALL be checked in full. The CLI SHALL report every finding in a checked file whether or not the diff changed the finding's line, and SHALL NOT offer a mode that reports only findings on changed lines. + +#### Scenario: Piped diff scopes the check + +- **WHEN** a user runs `git diff --staged | taskless check --diff` +- **AND** the diff modifies `src/a.ts` and adds `src/b.ts` +- **THEN** the check SHALL run over `src/a.ts` and `src/b.ts` only + +#### Scenario: A finding on an unchanged line of a changed file is reported + +- **WHEN** a diff changes line 3 of `src/a.ts` +- **AND** a rule matches line 900 of `src/a.ts`, which the diff did not change +- **THEN** the finding on line 900 SHALL be reported +- **AND** SHALL count toward the exit code as any finding does + +#### Scenario: Deleted files contribute nothing + +- **WHEN** the diff deletes `src/old.ts` and modifies `src/a.ts` +- **THEN** the check SHALL run over `src/a.ts` only +- **AND** SHALL NOT name `src/old.ts` as a skipped path + +#### Scenario: A rename checks the new path + +- **WHEN** the diff renames `src/old.ts` to `src/new.ts` +- **THEN** the check SHALL run over `src/new.ts` + +#### Scenario: The diff is read from a file + +- **WHEN** a user runs `taskless check --diff=change.patch` +- **THEN** the check SHALL be scoped to the files `change.patch` changes +- **AND** `change.patch` SHALL NOT itself be treated as a path to check + +#### Scenario: Prefixes other than a/ and b/ are stripped the same way + +- **WHEN** the diff's headers read `--- i/src/a.ts` and `+++ w/src/a.ts` +- **THEN** the check SHALL run over `src/a.ts` + +### Requirement: A diff-scoped check excludes Taskless and VCS directories + +Paths a diff contributes that lie under a `.taskless/` or `.git/` directory, at any depth, SHALL NOT be checked. The CLI SHALL name the excluded paths in one notice. This exclusion SHALL apply only to paths derived from a diff; a positional path the caller names SHALL be checked as named, as before. + +When no path survives the exclusions and existence filtering, the CLI SHALL exit 0 with no findings and with the notices that explain why. + +#### Scenario: A diff that adds a rule checks none of the rule's files + +- **WHEN** a diff adds `.taskless/rules/sg/no-eval/rule.yml` and `.taskless/rules/sg/no-eval/tests/fail/case/handler.ts` +- **AND** `handler.ts` contains code the rule matches +- **THEN** `taskless check --diff` SHALL exit 0 with no findings +- **AND** a notice SHALL name the two excluded paths + +#### Scenario: Positional paths keep their meaning + +- **WHEN** a user runs `taskless check .taskless/rules/sg/no-eval` +- **THEN** the named directory SHALL be checked as it is today + +#### Scenario: A nested Taskless directory is excluded + +- **WHEN** a diff changes `packages/app/.taskless/rules/vale/x/tests/fail/c/README.md` and `packages/app/src/a.ts` +- **THEN** only `packages/app/src/a.ts` SHALL be checked + +### Requirement: Check refuses diff input that cannot describe a change + +The CLI SHALL distinguish a diff that changes nothing from input that is not a diff: + +- Input that is empty or only whitespace SHALL exit 0 with no findings and a notice saying the diff changed no files. +- Input that is not empty and contains no file header SHALL be refused with `INVALID_INPUT`, and nothing SHALL be checked. +- `--diff` while stdin is a terminal SHALL be refused with `INVALID_INPUT` naming the piped form, rather than waiting for input. +- `--diff`, in either form, together with positional paths SHALL be refused with `INVALID_INPUT`. +- `--diff=` naming a file that cannot be read SHALL be refused with `INVALID_INPUT`. + +Each refusal SHALL use the standard error envelope under `--json` and exit 1. + +#### Scenario: Nothing staged + +- **WHEN** a user runs `git diff --staged | taskless check --diff` with nothing staged +- **THEN** the CLI SHALL exit 0 +- **AND** SHALL NOT scan the whole project + +#### Scenario: Output that is not a unified diff + +- **WHEN** a user pipes the output of a structural diff tool that prints no `diff --git`, `---`, or `+++` headers into `taskless check --diff` +- **THEN** the CLI SHALL exit 1 with `INVALID_INPUT` +- **AND** SHALL NOT report the run as clean + +#### Scenario: Interactive stdin + +- **WHEN** a user runs `taskless check --diff` in a terminal with nothing piped +- **THEN** the CLI SHALL exit 1 with `INVALID_INPUT` without reading stdin + +#### Scenario: Diff and positional paths together + +- **WHEN** a user runs `git diff | taskless check --diff src/a.ts` +- **THEN** the CLI SHALL exit 1 with `INVALID_INPUT` + +#### Scenario: The token after a bare --diff is a path, not a diff file + +- **WHEN** a user runs `taskless check --diff change.patch` with a diff piped on stdin +- **THEN** `change.patch` SHALL be read as a positional path, not as the diff +- **AND** the CLI SHALL exit 1 with `INVALID_INPUT` because a diff and positional paths were given together diff --git a/openspec/changes/archive/2026-12-05-check-diff-scope/tasks.md b/openspec/changes/archive/2026-12-05-check-diff-scope/tasks.md new file mode 100644 index 000000000..fec4cff9f --- /dev/null +++ b/openspec/changes/archive/2026-12-05-check-diff-scope/tasks.md @@ -0,0 +1,21 @@ +## 1. Diff parser + +- [x] 1.1 Add a unified-diff file-list parser under `packages/cli/src/util/` returning `{ paths, recognized }`: `+++` path with one component stripped, `diff --git` fallback for binary, mode-only and pure-rename entries, `/dev/null` deletions dropped, C-quoted paths unquoted, duplicates collapsed; verify with unit tests over fixture diffs from git (default `a/`/`b/`, mnemonic `i/`/`w/`, rename, binary, delete, quoted path) and a non-diff input that yields `recognized: false` + +## 2. check --diff[=] + +- [x] 2.0 Teach the shared argv scanner (`util/argv.ts`) a class of optional-value flags that take a value only from `--flag=value` and never consume the next token; verify with unit tests that `--diff x` leaves `x` positional and `--diff=x` yields the value +- [x] 2.1 Add `--diff[=]` to `check` (bare reads stdin, `=` form reads the file), read from raw argv through the scanner, and refuse: terminal stdin on the bare form, positional paths alongside either form, unreadable file, non-empty input with no file header; verify each refusal exits 1 with `INVALID_INPUT` in text and `--json` +- [x] 2.2 Feed parsed paths through `classifyPaths`, then drop paths under `.taskless/` or `.git/` at any depth using the same directory list the whole-project walk excludes, and name them in one notice; verify a test where a diff adding a rule and its `tests/fail` fixture exits 0 with the notice, and a positional path to the same directory still reports findings +- [x] 2.3 Empty input exits 0 with a "diff changed no files" notice and scans nothing; verify by test that no engine is spawned +- [x] 2.4 End-to-end test: a temp git repo with a file holding a pre-existing violation far from the edited line, `git diff` piped to the built CLI with `--diff`, asserting the old finding is reported and the exit code is 1 + +## 3. Recipes + +- [x] 3.1 Update `packages/cli/src/agent/ci.md`: diff scan pipes `git diff --no-ext-diff --no-color --relative origin/...HEAD` into `check --diff`, the GitHub Actions template and scan-patterns section follow, the empty-list guard and its explanation go; bump the topic version; verify recipe tests and the rendered template +- [x] 3.2 Update `packages/cli/src/agent/hooks.md`: the husky / simple-git-hooks example pipes the staged diff into `check --diff`, the whitespace caveat is replaced by the working-tree caveat; bump the topic version; verify recipe tests +- [x] 3.3 Update `packages/cli/src/agent/check.md` to document `--diff[=]`, the exclusions, and the refusals, keeping the existing one-command-per-call path-list guidance for agents; verify recipe tests + +## 4. Release and checks + +- [x] 4.1 Add a `patch` changeset describing `--diff[=]`; run `pnpm typecheck`, `pnpm lint`, and the test suite, all passing diff --git a/openspec/specs/cli-agent/spec.md b/openspec/specs/cli-agent/spec.md index 33cc34a8a..4e047f127 100644 --- a/openspec/specs/cli-agent/spec.md +++ b/openspec/specs/cli-agent/spec.md @@ -609,7 +609,7 @@ When rendered with `mechanics: false`, the paragraph SHALL name no invocation an #### Scenario: A diff-scoped check is not a command substitution - **WHEN** the `check` recipe describes scanning the files a branch changed -- **THEN** it SHALL tell the agent to run `git diff --name-only` as its own call and pass the paths it printed +- **THEN** it SHALL tell the agent to run `git diff` as its own call, save its output to a file, and pass that file as `check --diff=` - **AND** SHALL NOT show `$(git diff ...)` inside a Taskless command line ### Requirement: Recipes fetched through a launcher name the launcher @@ -641,7 +641,7 @@ The `@taskless/cli/prompts` export SHALL NOT read this variable, since a host th ### Requirement: The ci recipe runs the launcher with Node supplied by the job -The `ci` recipe SHALL generate CI configuration that runs `node .taskless/bin/cli.mjs check`, for a full scan, and `node .taskless/bin/cli.mjs check `, for a diff scan, from the repository root. It SHALL NOT generate a `npx`, `pnpm dlx`, `yarn dlx`, or `bunx` call to the CLI, and SHALL NOT ask the reader to choose a package manager launcher. It SHALL use `node ` rather than `./`, since a CI checkout can lose the executable bit and a Windows runner does not honour a shebang. +The `ci` recipe SHALL generate CI configuration that runs `node .taskless/bin/cli.mjs check`, for a full scan, and, for a diff scan, pipes the pull request's diff into `node .taskless/bin/cli.mjs check --diff`, from the repository root. The diff command SHALL be `git diff --no-ext-diff --no-color --relative ...HEAD`, and the recipe SHALL NOT expand a file list into the `check` command line. It SHALL NOT generate a `npx`, `pnpm dlx`, `yarn dlx`, or `bunx` call to the CLI, and SHALL NOT ask the reader to choose a package manager launcher. It SHALL use `node ` rather than `./`, since a CI checkout can lose the executable bit and a Windows runner does not honour a shebang. The recipe SHALL require that the generated job make Node available itself, through the CI system's Node setup step or a Node container image, and SHALL say that the job does not need the project's own language toolchain or a `package.json`. It SHALL name the launcher's version source, `.taskless/taskless.json`, as what decides which CLI version CI runs, so an upgrade reaches CI through the same commit that updates `.taskless/`. @@ -665,6 +665,12 @@ The recipe SHALL have the generated job cache `.taskless/.cache` between runs wh - **THEN** its GitHub Actions template SHALL cache the path `.taskless/.cache` - **AND** the cache key SHALL include `runner.os` and `hashFiles('.taskless/bin/cli.lock.json')` +#### Scenario: The diff scan pipes a diff + +- **WHEN** the `ci` recipe is rendered +- **THEN** its diff scan SHALL pipe `git diff --no-ext-diff --no-color --relative` into `node .taskless/bin/cli.mjs check --diff` +- **AND** SHALL NOT contain `$(git diff` inside a `check` command line + ### Requirement: The hooks recipe runs the launcher The `hooks` recipe SHALL generate pre-commit commands that run `node .taskless/bin/cli.mjs`, for every hook tool it covers. It SHALL NOT tell the reader to add `@taskless/cli` as a dev dependency for the hook, SHALL NOT resolve a binary from `node_modules/.bin`, and SHALL NOT call `npx`, `pnpm dlx`, `yarn dlx`, or `bunx`, since the launcher already runs the version recorded in `.taskless/taskless.json`. It SHALL require that `.taskless/bin/cli.mjs` exists and is committed, and SHALL say what to do when `.taskless/` is not at the repository root, where git runs hooks. @@ -749,3 +755,13 @@ A section fetch SHALL capture `cli_agent` with `topic` and `section`, and SHALL - **WHEN** a user runs `taskless agent create-sg-rule --section quirks` - **THEN** PostHog SHALL receive `cli_agent` with `topic: "create-sg-rule"` and `section: "quirks"` - **AND** stdout SHALL NOT carry the feedback invite + +### Requirement: The hooks recipe pipes the staged diff where the tool supplies no file list + +For hook tools that do not pass staged filenames themselves (husky or simple-git-hooks without lint-staged), the `hooks` recipe SHALL generate `git diff --staged --no-ext-diff --no-color --relative | node .taskless/bin/cli.mjs check --diff`, and SHALL NOT build a file list in a shell variable. It SHALL state that `check` reads the working tree, so a file with unstaged edits is checked as it is on disk rather than as staged, and SHALL keep lint-staged as the recommended route where that matters. + +#### Scenario: husky example + +- **WHEN** the `hooks` recipe is rendered +- **THEN** its husky example SHALL pipe `git diff --staged` into `node .taskless/bin/cli.mjs check --diff` +- **AND** SHALL NOT contain `FILES=$(` diff --git a/openspec/specs/cli-check/spec.md b/openspec/specs/cli-check/spec.md index 97cab5705..d6ef6ff6a 100644 --- a/openspec/specs/cli-check/spec.md +++ b/openspec/specs/cli-check/spec.md @@ -949,3 +949,111 @@ A finding in `check --json`'s `results` and a finding in `verify --json`'s `rule - **WHEN** `check --json` and `verify --json` run against a project whose rule fires in both the code and the rule's `fail/` fixture - **THEN** a finding from each SHALL parse against the published `findingSchema` + +### Requirement: Check scopes a run to the files a unified diff changes + +`check --diff` SHALL read a unified diff from stdin, and `check --diff=` SHALL read one from the named file. The flag SHALL take a value only from the `=` form: the token after a bare `--diff` SHALL NOT be read as its value. The CLI SHALL derive the run's paths from the diff's file headers and SHALL NOT invoke a version-control tool to do so. + +Each file the diff adds, modifies, renames, or copies SHALL contribute its new-side path, taken from the `+++` header with its first path component removed, or from the `diff --git` header when the file has no `+++` header (a binary, mode-only, or pure-rename change). A file the diff deletes (`+++ /dev/null`) SHALL contribute no path. C-quoted paths SHALL be unquoted before use. + +The derived paths SHALL then be handled as positional paths are: a path that does not exist is skipped and named in a notice, and a path outside the project is refused with `INVALID_INPUT`. + +Every derived file SHALL be checked in full. The CLI SHALL report every finding in a checked file whether or not the diff changed the finding's line, and SHALL NOT offer a mode that reports only findings on changed lines. + +#### Scenario: Piped diff scopes the check + +- **WHEN** a user runs `git diff --staged | taskless check --diff` +- **AND** the diff modifies `src/a.ts` and adds `src/b.ts` +- **THEN** the check SHALL run over `src/a.ts` and `src/b.ts` only + +#### Scenario: A finding on an unchanged line of a changed file is reported + +- **WHEN** a diff changes line 3 of `src/a.ts` +- **AND** a rule matches line 900 of `src/a.ts`, which the diff did not change +- **THEN** the finding on line 900 SHALL be reported +- **AND** SHALL count toward the exit code as any finding does + +#### Scenario: Deleted files contribute nothing + +- **WHEN** the diff deletes `src/old.ts` and modifies `src/a.ts` +- **THEN** the check SHALL run over `src/a.ts` only +- **AND** SHALL NOT name `src/old.ts` as a skipped path + +#### Scenario: A rename checks the new path + +- **WHEN** the diff renames `src/old.ts` to `src/new.ts` +- **THEN** the check SHALL run over `src/new.ts` + +#### Scenario: The diff is read from a file + +- **WHEN** a user runs `taskless check --diff=change.patch` +- **THEN** the check SHALL be scoped to the files `change.patch` changes +- **AND** `change.patch` SHALL NOT itself be treated as a path to check + +#### Scenario: Prefixes other than a/ and b/ are stripped the same way + +- **WHEN** the diff's headers read `--- i/src/a.ts` and `+++ w/src/a.ts` +- **THEN** the check SHALL run over `src/a.ts` + +### Requirement: A diff-scoped check excludes Taskless and VCS directories + +Paths a diff contributes that lie under a `.taskless/` or `.git/` directory, at any depth, SHALL NOT be checked. The CLI SHALL name the excluded paths in one notice. This exclusion SHALL apply only to paths derived from a diff; a positional path the caller names SHALL be checked as named, as before. + +When no path survives the exclusions and existence filtering, the CLI SHALL exit 0 with no findings and with the notices that explain why. + +#### Scenario: A diff that adds a rule checks none of the rule's files + +- **WHEN** a diff adds `.taskless/rules/sg/no-eval/rule.yml` and `.taskless/rules/sg/no-eval/tests/fail/case/handler.ts` +- **AND** `handler.ts` contains code the rule matches +- **THEN** `taskless check --diff` SHALL exit 0 with no findings +- **AND** a notice SHALL name the two excluded paths + +#### Scenario: Positional paths keep their meaning + +- **WHEN** a user runs `taskless check .taskless/rules/sg/no-eval` +- **THEN** the named directory SHALL be checked as it is today + +#### Scenario: A nested Taskless directory is excluded + +- **WHEN** a diff changes `packages/app/.taskless/rules/vale/x/tests/fail/c/README.md` and `packages/app/src/a.ts` +- **THEN** only `packages/app/src/a.ts` SHALL be checked + +### Requirement: Check refuses diff input that cannot describe a change + +The CLI SHALL distinguish a diff that changes nothing from input that is not a diff: + +- Input that is empty or only whitespace SHALL exit 0 with no findings and a notice saying the diff changed no files. +- Input that is not empty and contains no file header SHALL be refused with `INVALID_INPUT`, and nothing SHALL be checked. +- `--diff` while stdin is a terminal SHALL be refused with `INVALID_INPUT` naming the piped form, rather than waiting for input. +- `--diff`, in either form, together with positional paths SHALL be refused with `INVALID_INPUT`. +- `--diff=` naming a file that cannot be read SHALL be refused with `INVALID_INPUT`. + +Each refusal SHALL use the standard error envelope under `--json` and exit 1. + +#### Scenario: Nothing staged + +- **WHEN** a user runs `git diff --staged | taskless check --diff` with nothing staged +- **THEN** the CLI SHALL exit 0 +- **AND** SHALL NOT scan the whole project + +#### Scenario: Output that is not a unified diff + +- **WHEN** a user pipes the output of a structural diff tool that prints no `diff --git`, `---`, or `+++` headers into `taskless check --diff` +- **THEN** the CLI SHALL exit 1 with `INVALID_INPUT` +- **AND** SHALL NOT report the run as clean + +#### Scenario: Interactive stdin + +- **WHEN** a user runs `taskless check --diff` in a terminal with nothing piped +- **THEN** the CLI SHALL exit 1 with `INVALID_INPUT` without reading stdin + +#### Scenario: Diff and positional paths together + +- **WHEN** a user runs `git diff | taskless check --diff src/a.ts` +- **THEN** the CLI SHALL exit 1 with `INVALID_INPUT` + +#### Scenario: The token after a bare --diff is a path, not a diff file + +- **WHEN** a user runs `taskless check --diff change.patch` with a diff piped on stdin +- **THEN** `change.patch` SHALL be read as a positional path, not as the diff +- **AND** the CLI SHALL exit 1 with `INVALID_INPUT` because a diff and positional paths were given together diff --git a/packages/cli/README.md b/packages/cli/README.md index 99bbe9f64..47c5992c9 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -51,13 +51,15 @@ pipeline: ```bash ./.taskless/bin/cli.mjs check # scan everything -./.taskless/bin/cli.mjs check $(git diff --name-only main...HEAD) # PR-only scan +git diff --no-ext-diff --no-color main...HEAD \ + | ./.taskless/bin/cli.mjs check --diff # PR-only scan ./.taskless/bin/cli.mjs check --json # machine-readable ./.taskless/bin/cli.mjs check --json --summary # per-rule counts only ``` -Paths that no longer exist are dropped silently, so raw `git diff` output can be -piped in without pre-filtering. Static rules need no login and make no network +`--diff` reads a unified diff on stdin (or `--diff=`) and checks every file +it adds or modifies, whole. Deleted files and files under `.taskless/` are +skipped, and an empty diff checks nothing. Static rules need no login and make no network calls, so CI needs no secrets. Runtime rules (which execute code) only run once the server has verified their signature; otherwise they are reported as skipped and never change the exit code. diff --git a/packages/cli/src/agent/check.md b/packages/cli/src/agent/check.md index b0973b99c..686f00ca7 100644 --- a/packages/cli/src/agent/check.md +++ b/packages/cli/src/agent/check.md @@ -1,4 +1,4 @@ -# Topic: check (CLI v%(CLI_VERSION)s / topic v12) +# Topic: check (CLI v%(CLI_VERSION)s / topic v13) %(ONE_COMMAND_PER_CALL)s @@ -24,6 +24,7 @@ in CI (diff-only scan), or after rule create/improve to validate. any repository. Use it when the question is "how many", not "where". - `--rule `: run only the named rule (its directory name); repeatable. Works with `--json` and `--summary`. +- `--diff[=]`: scope to a diff ([Diff scope](#diff-scope)). - `--local`: run only static rules; skip runtime rules. - `--dangerously-run-scripts`: run runtime `check.ts` unverified. - `--timeout `: per-runtime-check wall-clock bound (default 10). @@ -40,8 +41,7 @@ in CI (diff-only scan), or after rule create/improve to validate. ## Steps 1. **Decide scope.** Default is a full project scan. If the user - specified files (or you're in a CI context with a known diff), - pass them as positional arguments. + specified files, pass them as positional arguments. 2. **Invoke the CLI.** Either: ``` @@ -51,14 +51,14 @@ in CI (diff-only scan), or after rule create/improve to validate. ``` %(TASKLESS_CLI)s check --json src/foo.ts src/bar.ts ``` - or, against a git diff: run `git diff --name-only main...HEAD` as - its own call, then pass the paths it printed: + or, against a git diff: run `git diff --no-ext-diff --no-color + main...HEAD` as its own call, save its output to + `.taskless/.tmp-diff.patch` with your file tools, then: ``` - %(TASKLESS_CLI)s check --json src/foo.ts src/deleted.ts + %(TASKLESS_CLI)s check --json --diff=.taskless/.tmp-diff.patch ``` - Paths that don't exist on disk are skipped, so you can pass every - path `git diff` printed without pre-filtering. Skipped paths are - named in `notices`, so a mistyped path does not read as clean. + Delete it afterwards. Unlike a path list, `--diff` skips + `.taskless/`. A missing named path is skipped and named in `notices`. A path outside the project (the working directory, or `--dir`), existing or not, is refused with `INVALID_INPUT` and nothing is @@ -324,6 +324,25 @@ delete the rules to make `check` pass, and do not suggest `--dangerously-run-scripts` as a fix. Show the `upgradeUrl`. An `entitlement` with an empty `withheld` does not fail the run. + +## Diff scope + +`check --diff` reads a unified diff on stdin; `check --diff=` +reads one from a file. The value only ever comes after `=`, so in +`check --diff src/a.ts` the path is a path, and the pair is refused. + +Every file the diff adds or modifies is checked whole, including lines +the diff did not change: a changed file has to be clean. Deleted files +are skipped. Files under `.taskless/` or `.git/` are never checked from +a diff and are named in `notices`. An empty diff exits 0 having checked +nothing. + +Refused with `INVALID_INPUT`, nothing checked: input with no file +headers (an external diff tool or colored output; produce the diff +with `git diff --no-ext-diff --no-color`), `--diff` while stdin is a +terminal, `--diff` together with paths, and a `--diff=` that +cannot be read. + ## See Also diff --git a/packages/cli/src/agent/ci.md b/packages/cli/src/agent/ci.md index cf74d5466..455430308 100644 --- a/packages/cli/src/agent/ci.md +++ b/packages/cli/src/agent/ci.md @@ -1,4 +1,4 @@ -# Topic: ci (CLI v%(CLI_VERSION)s / topic v12) +# Topic: ci (CLI v%(CLI_VERSION)s / topic v13) %(ONE_COMMAND_PER_CALL)s @@ -48,8 +48,10 @@ which CI they use. If multiple match, ask which should run Taskless. - **Full scan**: `%(TASKLESS_CLI)s check`. Scans everything. Best for runs on the main/default branch. -- **Diff scan**: `%(TASKLESS_CLI)s check $(git diff --name-only ...)`. - Faster for PR builds. +- **Diff scan**: pipe the pull request's diff into + `%(TASKLESS_CLI)s check --diff`. Checks every file the PR changes, + whole: a changed file must be clean, including lines the PR did not + touch. Faster for PR builds. **Recommended default:** diff scan on PRs, full scan on pushes to main. Read [Scan patterns](#scan-patterns) for each CI's target branch @@ -120,8 +122,14 @@ Show: ## Scan patterns -A diff scan, `%(TASKLESS_CLI)s check $(git diff --name-only ...)`, diffs -against the pull request's target branch. Per-CI diff target var: +A diff scan pipes the diff against the pull request's target branch +into `check --diff`: + +``` +git diff --no-ext-diff --no-color --relative "origin/...HEAD" | %(TASKLESS_CLI)s check --diff +``` + +Per-CI diff target var: | CI | Target branch variable | |---------------------|-----------------------------------------------| @@ -132,10 +140,21 @@ against the pull request's target branch. Per-CI diff target var: | Azure Pipelines | `System.PullRequest.TargetBranch` | | Bitbucket Pipelines | `BITBUCKET_PR_DESTINATION_BRANCH` | -`%(TASKLESS_CLI)s check` skips paths that don't exist (naming them in a -notice), so raw `git diff --name-only` output can pipe in directly. -Run it from the repository root: `git diff` paths are relative to the -root, and a path outside the project is refused. +`check --diff` reads the diff's file headers and checks each file the +diff adds or modifies, in full. Deleted files are skipped. Files under +`.taskless/` or `.git/` are never checked from a diff, and are named in +a notice, so a PR that only adds a rule checks no code and passes; the +rule meets existing code on the next full scan. An empty diff exits 0 +having checked nothing, so the job needs no empty-diff guard. Input +that is not a unified diff is refused rather than read as "no +changes", which is why the command carries `--no-ext-diff` and +`--no-color`: either setting in a user's git config would otherwise +change what git prints. + +Run it from the directory that contains `.taskless/`. `--relative` +makes git print paths relative to that directory and leaves out files +outside it, which matters when `.taskless/` belongs to one package of a +monorepo. ## Local check outcomes @@ -224,13 +243,9 @@ jobs: - name: Taskless check run: | if [ "${{ github.event_name }}" = "pull_request" ]; then - git fetch origin "${{ github.base_ref }}" --depth=1 - FILES=$(git diff --name-only "origin/${{ github.base_ref }}...HEAD") - if [ -z "$FILES" ]; then - echo "No changed files." - exit 0 - fi - node .taskless/bin/cli.mjs check $FILES + git fetch origin "${{ github.base_ref }}" + git diff --no-ext-diff --no-color --relative "origin/${{ github.base_ref }}...HEAD" \ + | node .taskless/bin/cli.mjs check --diff else node .taskless/bin/cli.mjs check fi @@ -256,10 +271,10 @@ The six universal steps: key built from the runner's operating system and the hash of `.taskless/bin/cli.lock.json`. 3. Fetch the target branch. -4. Compute changed files with `git diff --name-only "origin/...HEAD"`. -5. Exit early if the diff is empty. -6. Call `node .taskless/bin/cli.mjs check $FILES` for PR builds, or - `node .taskless/bin/cli.mjs check` for main-branch builds. +4. For PR builds, pipe `git diff --no-ext-diff --no-color --relative + "origin/...HEAD"` into `node .taskless/bin/cli.mjs check --diff`. +5. For main-branch builds, run `node .taskless/bin/cli.mjs check`. +6. Let `check`'s exit code fail the job; an empty diff already exits 0. YAML for GitHub/GitLab/Azure/Bitbucket; Groovy for Jenkins; different structure for CircleCI. The six steps stay the same. diff --git a/packages/cli/src/agent/hooks.md b/packages/cli/src/agent/hooks.md index 940e12b8a..589d8d380 100644 --- a/packages/cli/src/agent/hooks.md +++ b/packages/cli/src/agent/hooks.md @@ -1,4 +1,4 @@ -# Topic: hooks (CLI v%(CLI_VERSION)s / topic v7) +# Topic: hooks (CLI v%(CLI_VERSION)s / topic v8) %(ONE_COMMAND_PER_CALL)s @@ -74,10 +74,12 @@ without the network. ### 3. Write the pre-commit command -`check` accepts file paths and skips any that do not exist, so a staged -list that includes deleted files can go straight in. Called with no -paths at all it scans the whole project, so a hook that builds the list -itself has to exit early when the list is empty. +Where the hook tool passes the staged filenames itself, `check` takes +them as paths and skips any that do not exist. Where it does not, +pipe the staged diff into `check --diff`, which checks every file the +diff adds or modifies and exits 0 when nothing is staged. Either way a +staged file is checked whole: findings on lines the commit did not +touch still block it, since the file being committed has to be clean. Copy the command for the tool from [Hook commands](#hook-commands), which also covers paths with spaces and simple-git-hooks' installer. Tell the @@ -164,23 +166,24 @@ repos: pass_filenames: true ``` -**husky or simple-git-hooks without lint-staged.** Build the list -with git: +**husky or simple-git-hooks without lint-staged.** Pipe the staged +diff into `check --diff`: ```sh -FILES=$(git diff --cached --name-only --diff-filter=ACMR) -[ -z "$FILES" ] && exit 0 -node .taskless/bin/cli.mjs check $FILES +git diff --staged --no-ext-diff --no-color --relative | node .taskless/bin/cli.mjs check --diff ``` -`--diff-filter=ACMR` drops deleted files up front. `check` would skip -them anyway; the filter keeps a commit that only deletes files from -reaching `check` at all. - -`$FILES` splits on whitespace, so a staged path containing a space -reaches `check` as two paths that do not exist, and is skipped. The -`ci` recipe has the same limitation. If the repository has paths -like that, prefer lint-staged. +Copy the git flags as they are. `--no-ext-diff` and `--no-color` keep +a user's git config from changing what git prints, which `check` +refuses rather than reading as "nothing staged". `--relative` keeps +paths relative to the directory the hook runs in. Deleted files, an +empty commit, and files under `.taskless/` or `.git/` are handled by +`check` itself. + +`check` reads the files as they are on disk. A file with both staged +and unstaged edits is checked with the unstaged ones included, so a +commit can pass on a fix it does not contain. lint-staged hides +unstaged edits while it runs; if that matters to the user, prefer it. For simple-git-hooks, rerun its installer after editing the config (` simple-git-hooks`), or the change does not reach diff --git a/packages/cli/src/commands/check.ts b/packages/cli/src/commands/check.ts index d30e789c7..595cadf05 100644 --- a/packages/cli/src/commands/check.ts +++ b/packages/cli/src/commands/check.ts @@ -6,7 +6,7 @@ import { relative, resolve, } from "node:path"; -import { realpath, stat } from "node:fs/promises"; +import { readFile, realpath, stat } from "node:fs/promises"; import process from "node:process"; import { defineCommand } from "citty"; @@ -14,6 +14,7 @@ import { hasValeRules } from "../rules/dispatch"; import { splitRawArguments } from "../util/argv"; import { formatSummaryText, formatText } from "../util/format"; import { listRuleIds, planEngineDispatch } from "../rules/engines"; +import { EXCLUDED_DIRECTORIES } from "../rules/scan"; import { getTelemetry } from "../telemetry"; import { outputSchema as checkOutputSchema } from "../schemas/check"; import { makeErrorEnvelope, writeJsonError } from "../types/errors"; @@ -26,6 +27,7 @@ import { scanProject } from "../rules/scan-project"; import { summarizeFindings } from "../rules/summarize-findings"; import type { CheckResult } from "../types/check"; import { isCiEnvironment } from "../util/interactive"; +import { parseDiffFiles } from "../util/unified-diff"; import { markNotice } from "../util/notices"; import { detectLauncherCommand, @@ -161,7 +163,78 @@ function missingPathsNotice(missing: string[]): string { * value-taking flag, so it is named here rather than in the shared set. */ function extractPositionalPaths(rawArguments: string[]): string[] { - return splitRawArguments(rawArguments, VALUE_FLAGS).positionals; + return splitRawArguments(rawArguments, VALUE_FLAGS, OPTIONAL_VALUE_FLAGS) + .positionals; +} + +/** + * `check`'s flags whose value is optional, and so is read only from the + * `--flag=value` spelling: `--diff` reads stdin, `--diff=` reads a file, + * and the token after a bare `--diff` stays a positional path. + */ +const OPTIONAL_VALUE_FLAGS = ["--diff"] as const; + +/** Where `check --diff` reads its diff from. */ +type DiffSource = + | { kind: "stdin" } + | { kind: "file"; path: string } + | { kind: "invalid"; message: string }; + +/** + * The diff `check` was asked to read, or `undefined` when `--diff` was not + * given. Read through the same scanner as the positionals, so `--diff` after + * `--` is a path and a `--timeout --diff` value is a timeout. + */ +function extractDiffSource(rawArguments: string[]): DiffSource | undefined { + const { flags, values } = splitRawArguments( + rawArguments, + VALUE_FLAGS, + OPTIONAL_VALUE_FLAGS + ); + const occurrences = flags.filter( + (flag) => flag === "--diff" || flag.startsWith("--diff=") + ); + if (occurrences.length === 0) return undefined; + if (occurrences.length > 1) { + return { kind: "invalid", message: "`--diff` was given more than once." }; + } + const value = values.find((entry) => entry.flag === "--diff")?.value; + if (value === undefined) return { kind: "stdin" }; + if (value === "") { + return { + kind: "invalid", + message: + "`--diff=` names no file. Pipe the diff into `check --diff`, or pass `--diff=`.", + }; + } + return { kind: "file", path: value }; +} + +/** All of stdin, as UTF-8. */ +async function readStdin(): Promise { + const chunks: Buffer[] = []; + for await (const chunk of process.stdin as AsyncIterable) { + chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk); + } + return Buffer.concat(chunks).toString("utf8"); +} + +/** Whether `path` lies under a directory a diff-scoped check never checks. */ +function isExcludedFromDiff(path: string): boolean { + const segments = path.split(/[/\\]/); + return segments.some((segment) => + (EXCLUDED_DIRECTORIES as readonly string[]).includes(segment) + ); +} + +/** + * The notice for diff paths left out because they lie under `.taskless/` or + * `.git/`. Named, so a diff that only touched rules reads as "the rules were + * not checked here" rather than as a clean check of them. + */ +function excludedPathsNotice(excluded: string[]): string { + const noun = excluded.length === 1 ? "path" : "paths"; + return `Not checked: ${excluded.length} changed ${noun} under .taskless/ or .git/, which \`check --diff\` never checks: ${excluded.join(", ")}`; } /** @@ -262,6 +335,12 @@ export const checkCommand = defineCommand({ type: "string", description: "Run only the named rule; repeatable (--rule a --rule b)", }, + diff: { + type: "boolean", + description: + "Check the files a unified diff changes, whole: reads stdin, or --diff=", + default: false, + }, summary: { type: "boolean", description: @@ -336,9 +415,91 @@ export const checkCommand = defineCommand({ ruleCount: number; } | undefined; + /** Refuse the command line: nothing is scanned, exit 1. */ + const refuse = (message: string) => { + if (args.json) { + writeJsonError("INVALID_INPUT", message); + } else { + console.error(`Error: ${message}`); + } + process.exitCode = 1; + }; + try { - const positionalPaths = extractPositionalPaths(rawArgs); - const hadExplicitPaths = positionalPaths.length > 0; + const namedPaths = extractPositionalPaths(rawArgs); + const diffSource = extractDiffSource(rawArgs); + + // Paths from a diff, and the notices that say what the diff named but + // this run will not check. `undefined` when no diff was given. + let diffScope: { paths: string[]; notices: string[] } | undefined; + if (diffSource !== undefined) { + if (diffSource.kind === "invalid") { + refuse(diffSource.message); + return; + } + // Two sources for one list would check what only one of them said. + if (namedPaths.length > 0) { + refuse( + `\`--diff\` cannot be combined with paths (${namedPaths.join(", ")}). A diff's file is passed as \`--diff=\`, with \`=\`.` + ); + return; + } + if (diffSource.kind === "stdin" && process.stdin.isTTY === true) { + refuse( + "`--diff` reads a diff from stdin, and stdin is a terminal. Pipe one in (`git diff --staged | taskless check --diff`), or pass `--diff=`." + ); + return; + } + let text: string; + try { + text = + diffSource.kind === "stdin" + ? await readStdin() + : // Against the project, as `--from` is elsewhere: with + // `--dir`, a relative diff file names one in that project. + await readFile(resolve(cwd, diffSource.path), "utf8"); + } catch (error) { + refuse( + `Could not read the diff from ${diffSource.kind === "stdin" ? "stdin" : diffSource.path}: ${error instanceof Error ? error.message : String(error)}` + ); + return; + } + if (text.trim() === "") { + diffScope = { + paths: [], + notices: ["The diff changes no files; nothing was checked."], + }; + } else { + const parsed = parseDiffFiles(text); + // Text with no file header is not "no changes": it is output this + // command cannot read (an external diff tool, colored output), and + // reporting it clean would be a green run that checked nothing. + if (!parsed.recognized) { + refuse( + "The input is not a unified diff: it has no `diff --git`, `---` or `+++` file headers. Produce it with `git diff --no-ext-diff --no-color`." + ); + return; + } + const excluded = parsed.paths.filter((path) => + isExcludedFromDiff(path) + ); + diffScope = { + paths: parsed.paths.filter((path) => !isExcludedFromDiff(path)), + notices: excluded.length > 0 ? [excludedPathsNotice(excluded)] : [], + }; + if (parsed.paths.length === 0) { + diffScope.notices.push( + "The diff only deletes files; nothing was checked." + ); + } + } + } + + const positionalPaths = diffScope?.paths ?? namedPaths; + // A diff is an explicit scope even when it leaves nothing to check: + // falling back to a whole-project scan would check what nobody asked. + const hadExplicitPaths = + diffScope !== undefined || positionalPaths.length > 0; const { kept: existingPaths, missing, @@ -359,8 +520,10 @@ export const checkCommand = defineCommand({ return; } - const pathNotices = - missing.length > 0 ? [missingPathsNotice(missing)] : []; + const pathNotices = [ + ...(diffScope?.notices ?? []), + ...(missing.length > 0 ? [missingPathsNotice(missing)] : []), + ]; // If the user passed paths but none exist (e.g. all-deleted diff), // exit cleanly with empty results rather than falling back to a full diff --git a/packages/cli/src/rules/scan.ts b/packages/cli/src/rules/scan.ts index 20acade49..9a9d87bfb 100644 --- a/packages/cli/src/rules/scan.ts +++ b/packages/cli/src/rules/scan.ts @@ -225,7 +225,10 @@ const GIT_DIRECTORY = ".git"; * exclusions both apply, unlike Vale's `--glob`, where the last one silently * wins. So this is a list rather than one combined brace pattern. */ -const EXCLUDED_DIRECTORIES = [TASKLESS_DIRECTORY, GIT_DIRECTORY] as const; +export const EXCLUDED_DIRECTORIES = [ + TASKLESS_DIRECTORY, + GIT_DIRECTORY, +] as const; /** * How every `sg scan` we spawn is told to walk the project. diff --git a/packages/cli/src/util/argv.ts b/packages/cli/src/util/argv.ts index 47d6a8c72..28a9a4d03 100644 --- a/packages/cli/src/util/argv.ts +++ b/packages/cli/src/util/argv.ts @@ -55,10 +55,18 @@ export interface FlagValue { * Split raw argv into positionals and flags, skipping flag values and honoring * `--`. `valueFlags` names flags beyond `-d`/`--dir` that consume the next * token (e.g. `check`'s `--timeout`). + * + * `optionalValueFlags` names flags whose value is optional and therefore comes + * only from the `--flag=value` spelling, the way git spells them + * (`--color[=]`). Such a flag never consumes the next token: in + * `check --diff src/a.ts`, `src/a.ts` is a positional, because reading it as + * the flag's value would make the same tokens mean two different things + * depending on what the caller intended. */ export function splitRawArguments( rawArguments: string[], - valueFlags: readonly string[] = [] + valueFlags: readonly string[] = [], + optionalValueFlags: readonly string[] = [] ): SplitArguments { const consumesValue = valueFlags.length > 0 ? new Set([...DIR_FLAGS, ...valueFlags]) : DIR_FLAGS; @@ -79,7 +87,7 @@ export function splitRawArguments( const equals = argument.indexOf("="); if (equals > 0) { const flag = argument.slice(0, equals); - if (consumesValue.has(flag)) + if (consumesValue.has(flag) || optionalValueFlags.includes(flag)) values.push({ flag, value: argument.slice(equals + 1) }); continue; } diff --git a/packages/cli/src/util/unified-diff.ts b/packages/cli/src/util/unified-diff.ts new file mode 100644 index 000000000..573f9d113 --- /dev/null +++ b/packages/cli/src/util/unified-diff.ts @@ -0,0 +1,223 @@ +/** + * The files a unified diff changes, read from its file headers alone. + * + * `check --diff` scopes a run to whole files, so the hunks carry nothing it + * uses. They still have to be walked, though, and not skipped by pattern: a + * hunk line that adds the text `++ b/x` reads `+++ b/x`, exactly a header. The + * hunk header's line counts say where each hunk ends, so the walk consumes a + * hunk's lines by count and only reads headers between hunks. + * + * No git is run and no git configuration is consulted. Whatever produced the + * diff (git, jj, Mercurial, a diff fetched from a forge) is the caller's + * concern; this reads the text. Paths are taken with their first component + * removed, as `patch -p1` does, so `a/`/`b/` and git's mnemonic `i/`/`w/`/`c/` + * prefixes all resolve to the same path. + */ + +export interface DiffFiles { + /** New-side paths of every file added, modified, renamed or copied. In order, without duplicates. */ + paths: string[]; + /** + * Whether the input held at least one file header. False on text that is + * not a unified diff at all, which a caller must not read as "no files + * changed": the two produce the same empty `paths`. + */ + recognized: boolean; +} + +const DEV_NULL = "/dev/null"; +const HUNK_HEADER = /^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/; + +/** Escape sequences git writes inside a C-quoted path, other than octal bytes. */ +const ESCAPES: Readonly> = { + a: 0x07, + b: 0x08, + f: 0x0c, + n: 0x0a, + r: 0x0d, + t: 0x09, + v: 0x0b, + '"': 0x22, + "\\": 0x5c, +}; + +/** + * Read one C-quoted string starting at `text[0] === '"'`. + * + * git quotes a path holding a byte it considers unusual (non-ASCII under the + * default `core.quotePath`, a quote, a backslash, a control character) and + * writes non-ASCII as octal escapes of its UTF-8 bytes, so the bytes are + * collected and decoded once at the end rather than per escape. + */ +function readQuoted(text: string): { value: string; rest: string } | undefined { + const bytes: number[] = []; + let index = 1; + while (index < text.length) { + const character = text[index]!; + if (character === '"') { + return { + value: Buffer.from(bytes).toString("utf8"), + rest: text.slice(index + 1), + }; + } + if (character === "\\") { + const next = text[index + 1] ?? ""; + const octal = /^[0-7]{3}/.exec(text.slice(index + 1)); + if (octal !== null) { + bytes.push(Number.parseInt(octal[0], 8)); + index += 4; + continue; + } + const escaped = ESCAPES[next]; + if (escaped === undefined) return undefined; + bytes.push(escaped); + index += 2; + continue; + } + bytes.push(...Buffer.from(character, "utf8")); + index += 1; + } + return undefined; +} + +/** A header path as written: unquoted, without a trailing timestamp. */ +function headerPath(raw: string): string | undefined { + if (raw.startsWith('"')) return readQuoted(raw)?.value; + // A plain `diff -u` appends a tab and a timestamp; git never writes a tab + // into an unquoted path, so everything after one is not the path. + const tab = raw.indexOf("\t"); + return tab === -1 ? raw : raw.slice(0, tab); +} + +/** `path` with its first component removed, as `patch -p1` does. */ +function stripPrefix(path: string): string { + const slash = path.indexOf("/"); + return slash === -1 ? path : path.slice(slash + 1); +} + +/** + * The new-side path from `diff --git `, when it can be known from + * that line alone. + * + * Quoted halves are unambiguous. Unquoted halves are separated by a space that + * a path can also contain, so the line is split only where both halves name + * the same path after their prefixes are removed, which is every change but a + * rename or copy. Those carry `rename to`/`copy to` lines, read separately. + */ +function gitHeaderNewPath(rest: string): string | undefined { + if (rest.startsWith('"')) { + const old = readQuoted(rest); + if (old === undefined) return undefined; + const tail = old.rest.trimStart(); + const next = tail.startsWith('"') ? readQuoted(tail)?.value : tail; + return next === undefined ? undefined : stripPrefix(next); + } + const lastQuote = rest.lastIndexOf(' "'); + if (lastQuote !== -1 && rest.endsWith('"')) { + const next = readQuoted(rest.slice(lastQuote + 1)); + return next === undefined ? undefined : stripPrefix(next.value); + } + if (rest.length % 2 === 1) { + const middle = (rest.length - 1) / 2; + const left = rest.slice(0, middle); + const right = rest.slice(middle + 1); + if (rest[middle] === " " && stripPrefix(left) === stripPrefix(right)) { + return stripPrefix(right); + } + } + return undefined; +} + +interface FileEntry { + /** From `diff --git`, `rename to` or `copy to`: a fallback for a file with no `+++`. */ + headerPath?: string; + /** From `+++` or `deleted file mode`; `null` when the file was deleted. */ + newPath?: string | null; + /** Whether this entry's `---`/`+++` pair has been read. */ + hasLineHeaders?: boolean; +} + +function entryPath(entry: FileEntry): string | undefined { + if (entry.newPath === null) return undefined; + return entry.newPath ?? entry.headerPath; +} + +/** Parse the files a unified diff changes. */ +export function parseDiffFiles(text: string): DiffFiles { + const lines = text.split(/\r?\n/); + const entries: FileEntry[] = []; + let current: FileEntry | undefined; + let oldRemaining = 0; + let newRemaining = 0; + + for (let index = 0; index < lines.length; index++) { + const line = lines[index]!; + + // Inside a hunk: consume by count. A `\ No newline at end of file` + // marker belongs to neither side. + if (oldRemaining > 0 || newRemaining > 0) { + if (line.startsWith("\\")) continue; + const marker = line[0]; + if (marker === "-") oldRemaining--; + else if (marker === "+") newRemaining--; + else { + oldRemaining--; + newRemaining--; + } + continue; + } + + if (line.startsWith("diff --git ")) { + const path = gitHeaderNewPath(line.slice("diff --git ".length)); + current = path === undefined ? {} : { headerPath: path }; + entries.push(current); + continue; + } + + if (line.startsWith("rename to ") || line.startsWith("copy to ")) { + const raw = line.slice(line.indexOf(" to ") + 4); + const path = headerPath(raw); + if (current !== undefined && path !== undefined) { + current.headerPath = path; + } + continue; + } + + if (line.startsWith("deleted file mode ")) { + if (current !== undefined) current.newPath = null; + continue; + } + + if (line.startsWith("--- ") && lines[index + 1]?.startsWith("+++ ")) { + // A diff without `diff --git` lines (plain `diff -u`, some forges) + // starts each file here instead. + if (current === undefined || current.hasLineHeaders === true) { + current = {}; + entries.push(current); + } + const raw = lines[index + 1]!.slice(4); + const path = headerPath(raw); + current.hasLineHeaders = true; + if (path === DEV_NULL) current.newPath = null; + else if (path !== undefined) current.newPath = stripPrefix(path); + index++; + continue; + } + + const hunk = HUNK_HEADER.exec(line); + if (hunk !== null) { + oldRemaining = hunk[1] === undefined ? 1 : Number(hunk[1]); + newRemaining = hunk[2] === undefined ? 1 : Number(hunk[2]); + } + } + + const seen = new Set(); + const paths: string[] = []; + for (const entry of entries) { + const path = entryPath(entry); + if (path === undefined || path === "" || seen.has(path)) continue; + seen.add(path); + paths.push(path); + } + return { paths, recognized: entries.length > 0 }; +} diff --git a/packages/cli/test/check-diff.test.ts b/packages/cli/test/check-diff.test.ts new file mode 100644 index 000000000..9a84d4fef --- /dev/null +++ b/packages/cli/test/check-diff.test.ts @@ -0,0 +1,301 @@ +import { execFileSync, spawn } from "node:child_process"; +import { + appendFile, + cp, + mkdir, + mkdtemp, + rm, + writeFile, +} from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; + +import { splitRawArguments } from "../src/util/argv"; +import { builtCli } from "./support/built-cli"; +import { migrateFixture } from "./support/current-project"; + +const binPath = builtCli(); +const fixturesDirectory = resolve( + import.meta.dirname, + "fixtures/taskless-project" +); + +interface Run { + stdout: string; + stderr: string; + exitCode: number; +} + +/** Run the built CLI with `input` on stdin. */ +async function runCli(args: string[], input: string): Promise { + await migrateFixture(args); + return new Promise((resolvePromise, reject) => { + const child = spawn("node", [binPath, ...args], { + stdio: ["pipe", "pipe", "pipe"], + }); + let stdout = ""; + let stderr = ""; + child.stdout.on("data", (chunk: Buffer) => (stdout += chunk.toString())); + child.stderr.on("data", (chunk: Buffer) => (stderr += chunk.toString())); + child.on("error", reject); + child.on("close", (code) => + resolvePromise({ stdout, stderr, exitCode: code ?? 1 }) + ); + child.stdin.end(input); + }); +} + +interface Envelope { + success: boolean; + results?: Array<{ + file: string; + ruleId: string; + range: { start: { line: number } }; + }>; + notices?: string[]; + code?: string; +} + +function parse(run: Run): Envelope { + return JSON.parse(run.stdout.trim()) as Envelope; +} + +/** A git-style diff that modifies each of `files` on one line. */ +function modifies(...files: string[]): string { + return files + .map((file) => + [ + `diff --git a/${file} b/${file}`, + "index 1111111..2222222 100644", + `--- a/${file}`, + `+++ b/${file}`, + "@@ -4 +4 @@", + '-console.log("this is fine");', + '+console.log("this is still fine");', + "", + ].join("\n") + ) + .join(""); +} + +describe("splitRawArguments with optional-value flags", () => { + it("never takes the token after a bare optional-value flag", () => { + const split = splitRawArguments(["--diff", "src/a.ts"], [], ["--diff"]); + expect(split.positionals).toEqual(["src/a.ts"]); + expect(split.values).toEqual([]); + }); + + it("reads the value from the = spelling", () => { + const split = splitRawArguments(["--diff=change.patch"], [], ["--diff"]); + expect(split.positionals).toEqual([]); + expect(split.values).toEqual([{ flag: "--diff", value: "change.patch" }]); + }); +}); + +describe("check --diff", () => { + let directory: string; + + beforeEach(async () => { + directory = await mkdtemp(join(tmpdir(), "taskless-check-diff-")); + await cp(fixturesDirectory, directory, { recursive: true }); + // A violation in a file no diff below names: reported only if the scope leaks. + await writeFile(join(directory, "other.js"), 'eval("not in the diff");\n'); + }); + + afterEach(async () => { + await rm(directory, { recursive: true, force: true }); + }); + + it("checks only the files the diff changes", async () => { + const run = await runCli( + ["check", "-d", directory, "--json", "--diff"], + modifies("sample.js") + ); + expect(run.exitCode).toBe(1); + const files = new Set(parse(run).results?.map((result) => result.file)); + expect([...files]).toEqual(["sample.js"]); + }); + + it("reports a finding on a line the diff did not change", async () => { + // The diff changes line 4; `eval` sits on line 2. + const run = await runCli( + ["check", "-d", directory, "--json", "--diff"], + modifies("sample.js") + ); + const evalFinding = parse(run).results?.find( + (result) => result.ruleId === "no-eval" + ); + expect(evalFinding?.range.start.line).toBe(1); + expect(run.exitCode).toBe(1); + }); + + it("checks none of a rule's own files when a diff adds the rule", async () => { + const fixture = join( + directory, + ".taskless/rules/sg/no-eval/tests/fail/case" + ); + await mkdir(fixture, { recursive: true }); + await writeFile(join(fixture, "handler.js"), 'eval("fixture");\n'); + + const run = await runCli( + ["check", "-d", directory, "--json", "--diff"], + modifies( + ".taskless/rules/sg/no-eval/no-eval.yml", + ".taskless/rules/sg/no-eval/tests/fail/case/handler.js" + ) + ); + expect(run.exitCode).toBe(0); + const envelope = parse(run); + expect(envelope.results).toEqual([]); + expect(envelope.notices).toContainEqual( + expect.stringContaining( + ".taskless/rules/sg/no-eval/tests/fail/case/handler.js" + ) + ); + }); + + it("checks nothing, and says so, when the diff is empty", async () => { + const run = await runCli( + ["check", "-d", directory, "--json", "--diff"], + "" + ); + expect(run.exitCode).toBe(0); + const envelope = parse(run); + expect(envelope.results).toEqual([]); + expect(envelope.notices).toContainEqual( + expect.stringContaining("changes no files") + ); + }); + + it("checks nothing when the diff only deletes files", async () => { + const run = await runCli( + ["check", "-d", directory, "--json", "--diff"], + [ + "diff --git a/gone.js b/gone.js", + "deleted file mode 100644", + "--- a/gone.js", + "+++ /dev/null", + "@@ -1 +0,0 @@", + "-x", + "", + ].join("\n") + ); + expect(run.exitCode).toBe(0); + expect(parse(run).results).toEqual([]); + }); + + it("refuses input that is not a unified diff", async () => { + const run = await runCli( + ["check", "-d", directory, "--json", "--diff"], + "sample.js --- 1/1 --- JavaScript\n2 const result = eval();\n" + ); + expect(run.exitCode).toBe(1); + expect(parse(run).code).toBe("INVALID_INPUT"); + }); + + it("reads the token after a bare --diff as a path, and refuses the pair", async () => { + const run = await runCli( + ["check", "-d", directory, "--json", "--diff", "other.js"], + modifies("sample.js") + ); + expect(run.exitCode).toBe(1); + expect(parse(run).code).toBe("INVALID_INPUT"); + }); + + it("reads the diff from --diff= without checking the file itself", async () => { + const patch = join(directory, "change.patch"); + await writeFile(patch, modifies("sample.js")); + const run = await runCli( + ["check", "-d", directory, "--json", `--diff=${patch}`], + "" + ); + expect(run.exitCode).toBe(1); + const files = new Set(parse(run).results?.map((result) => result.file)); + expect([...files]).toEqual(["sample.js"]); + }); + + it("resolves a relative --diff= against --dir, as --from does", async () => { + await writeFile(join(directory, "change.patch"), modifies("sample.js")); + // Spawned from elsewhere, so only resolving against `-d` finds the file. + const run = await runCli( + ["check", "-d", directory, "--json", "--diff=change.patch"], + "" + ); + expect(run.exitCode).toBe(1); + const files = new Set(parse(run).results?.map((result) => result.file)); + expect([...files]).toEqual(["sample.js"]); + }); + + it("refuses a --diff file that cannot be read", async () => { + const run = await runCli( + [ + "check", + "-d", + directory, + "--json", + `--diff=${join(directory, "nope.patch")}`, + ], + "" + ); + expect(run.exitCode).toBe(1); + expect(parse(run).code).toBe("INVALID_INPUT"); + }); + + it("reads what git diff --staged writes, and reports a pre-existing finding", async () => { + await migrateFixture(["-d", directory]); + const git = (...args: string[]) => + execFileSync("git", args, { cwd: directory, encoding: "utf8" }); + git("init", "-q"); + git("-c", "user.email=t@t", "-c", "user.name=t", "add", "-A"); + git( + "-c", + "user.email=t@t", + "-c", + "user.name=t", + "-c", + "commit.gpgsign=false", + "commit", + "-qm", + "init" + ); + // Append far from the `eval` on line 2, which predates this change. + await appendFile(join(directory, "sample.js"), 'console.log("new");\n'); + git("add", "sample.js"); + const diff = git( + "diff", + "--staged", + "--no-ext-diff", + "--no-color", + "--relative" + ); + + const run = await runCli( + ["check", "-d", directory, "--json", "--diff"], + diff + ); + expect(run.exitCode).toBe(1); + const envelope = parse(run); + expect(envelope.results?.map((result) => result.ruleId)).toContain( + "no-eval" + ); + expect(new Set(envelope.results?.map((result) => result.file))).toEqual( + new Set(["sample.js"]) + ); + }); + + it("keeps a positional .taskless path a request", async () => { + // The exclusion is for paths a diff contributes; a named path is unchanged. + const fixture = join( + directory, + ".taskless/rules/sg/no-eval/tests/fail/case" + ); + await mkdir(fixture, { recursive: true }); + await writeFile(join(fixture, "handler.js"), 'eval("fixture");\n'); + const run = await runCli( + ["check", "-d", directory, "--json", ".taskless/rules/sg/no-eval/tests"], + "" + ); + expect(run.exitCode).toBe(1); + }); +}); diff --git a/packages/cli/test/check-recipe.test.ts b/packages/cli/test/check-recipe.test.ts index cc16f1098..142719a44 100644 --- a/packages/cli/test/check-recipe.test.ts +++ b/packages/cli/test/check-recipe.test.ts @@ -6,8 +6,8 @@ const check = getRecipe("check"); if (check === undefined) throw new Error("no recipe for check"); describe("the check recipe", () => { - it("is topic v12", () => { - expect(check).toMatch(/^# Topic: check {5}\(CLI v.+ \/ topic v12\)/m); + it("is topic v13", () => { + expect(check).toMatch(/^# Topic: check {5}\(CLI v.+ \/ topic v13\)/m); }); it("lists --rule among its flags", () => { diff --git a/packages/cli/test/fixtures/diffs/git-default.diff b/packages/cli/test/fixtures/diffs/git-default.diff new file mode 100644 index 000000000..4fe236f31 --- /dev/null +++ b/packages/cli/test/fixtures/diffs/git-default.diff @@ -0,0 +1,53 @@ +diff --git a/added.ts b/added.ts +new file mode 100644 +index 0000000..3e75765 +--- /dev/null ++++ b/added.ts +@@ -0,0 +1 @@ ++new +diff --git "a/caf\303\251.md" "b/caf\303\251.md" +index 4ae8ef0..967e095 100644 +--- "a/caf\303\251.md" ++++ "b/caf\303\251.md" +@@ -1 +1 @@ +-u ++u2 +diff --git a/del.ts b/del.ts +deleted file mode 100644 +index 286c5f5..0000000 +--- a/del.ts ++++ /dev/null +@@ -1 +0,0 @@ +-gone +diff --git a/img.bin b/img.bin +index bdc955b..8835708 100644 +Binary files a/img.bin and b/img.bin differ +diff --git a/mod.ts b/mod.ts +index de98044..93e5cdc 100644 +--- a/mod.ts ++++ b/mod.ts +@@ -1,3 +1,3 @@ + a +-b ++++ b/fake.ts + c +diff --git a/old-name.ts b/new-name.ts +similarity index 88% +rename from old-name.ts +rename to new-name.ts +index a470291..2fab172 100644 +--- a/old-name.ts ++++ b/new-name.ts +@@ -2,3 +2,4 @@ x + y + z + w ++n +\ No newline at end of file +diff --git a/sp ace/f.ts b/sp ace/f.ts +index bca70f3..d169a2f 100644 +--- a/sp ace/f.ts ++++ b/sp ace/f.ts +@@ -1 +1 @@ +-q ++q2 diff --git a/packages/cli/test/fixtures/diffs/git-mnemonic.diff b/packages/cli/test/fixtures/diffs/git-mnemonic.diff new file mode 100644 index 000000000..71179ca22 --- /dev/null +++ b/packages/cli/test/fixtures/diffs/git-mnemonic.diff @@ -0,0 +1,53 @@ +diff --git c/added.ts i/added.ts +new file mode 100644 +index 0000000..3e75765 +--- /dev/null ++++ i/added.ts +@@ -0,0 +1 @@ ++new +diff --git "c/caf\303\251.md" "i/caf\303\251.md" +index 4ae8ef0..967e095 100644 +--- "c/caf\303\251.md" ++++ "i/caf\303\251.md" +@@ -1 +1 @@ +-u ++u2 +diff --git c/del.ts i/del.ts +deleted file mode 100644 +index 286c5f5..0000000 +--- c/del.ts ++++ /dev/null +@@ -1 +0,0 @@ +-gone +diff --git c/img.bin i/img.bin +index bdc955b..8835708 100644 +Binary files c/img.bin and i/img.bin differ +diff --git c/mod.ts i/mod.ts +index de98044..93e5cdc 100644 +--- c/mod.ts ++++ i/mod.ts +@@ -1,3 +1,3 @@ + a +-b ++++ b/fake.ts + c +diff --git c/old-name.ts i/new-name.ts +similarity index 88% +rename from old-name.ts +rename to new-name.ts +index a470291..2fab172 100644 +--- c/old-name.ts ++++ i/new-name.ts +@@ -2,3 +2,4 @@ x + y + z + w ++n +\ No newline at end of file +diff --git c/sp ace/f.ts i/sp ace/f.ts +index bca70f3..d169a2f 100644 +--- c/sp ace/f.ts ++++ i/sp ace/f.ts +@@ -1 +1 @@ +-q ++q2 diff --git a/packages/cli/test/fixtures/diffs/plain-unified.diff b/packages/cli/test/fixtures/diffs/plain-unified.diff new file mode 100644 index 000000000..e61c249bc --- /dev/null +++ b/packages/cli/test/fixtures/diffs/plain-unified.diff @@ -0,0 +1,5 @@ +--- old/x.txt 2026-01-01 00:00:00 ++++ new/x.txt 2026-01-02 00:00:00 +@@ -1 +1 @@ +-a ++b diff --git a/packages/cli/test/unified-diff.test.ts b/packages/cli/test/unified-diff.test.ts new file mode 100644 index 000000000..6454084cb --- /dev/null +++ b/packages/cli/test/unified-diff.test.ts @@ -0,0 +1,104 @@ +import { readFile } from "node:fs/promises"; +import { resolve } from "node:path"; +import { describe, expect, it } from "vitest"; + +import { parseDiffFiles } from "../src/util/unified-diff"; + +const fixtures = resolve(import.meta.dirname, "fixtures/diffs"); + +async function fixture(name: string): Promise { + return readFile(resolve(fixtures, name), "utf8"); +} + +/** + * Every new-side path in `git-default.diff`, which `git diff --staged` wrote + * over one staged change of each kind: an added file, a modified file whose + * hunk adds the text `++ b/fake.ts` (a line that reads as a `+++` header), a + * deletion, a binary change, a rename with an edit, a path with a space (git + * appends a tab to its headers), and a non-ASCII path (git C-quotes it). + */ +const EXPECTED = [ + "added.ts", + "café.md", + "img.bin", + "mod.ts", + "new-name.ts", + "sp ace/f.ts", +]; + +describe("parseDiffFiles", () => { + it("reads every changed file from git's default output", async () => { + const parsed = parseDiffFiles(await fixture("git-default.diff")); + expect(parsed.recognized).toBe(true); + expect(parsed.paths).toEqual(EXPECTED); + }); + + it("strips git's mnemonic prefixes the same way", async () => { + const parsed = parseDiffFiles(await fixture("git-mnemonic.diff")); + expect(parsed.paths).toEqual(EXPECTED); + }); + + it("never reads a hunk line as a file header", async () => { + const parsed = parseDiffFiles(await fixture("git-default.diff")); + expect(parsed.paths).not.toContain("fake.ts"); + }); + + it("drops a deleted file", async () => { + const parsed = parseDiffFiles(await fixture("git-default.diff")); + expect(parsed.paths).not.toContain("del.ts"); + }); + + it("reads a plain diff -u without git headers", async () => { + const parsed = parseDiffFiles(await fixture("plain-unified.diff")); + expect(parsed).toEqual({ paths: ["x.txt"], recognized: true }); + }); + + it("takes a pure rename's path from its rename line", () => { + const parsed = parseDiffFiles( + [ + "diff --git a/src/old.ts b/src/new.ts", + "similarity index 100%", + "rename from src/old.ts", + "rename to src/new.ts", + "", + ].join("\n") + ); + expect(parsed.paths).toEqual(["src/new.ts"]); + }); + + it("drops a deleted binary file, which has no +++ line", () => { + const parsed = parseDiffFiles( + [ + "diff --git a/logo.png b/logo.png", + "deleted file mode 100644", + "index 1234567..0000000", + "Binary files a/logo.png and /dev/null differ", + "", + ].join("\n") + ); + expect(parsed).toEqual({ paths: [], recognized: true }); + }); + + it("reads CRLF line endings", () => { + const parsed = parseDiffFiles( + "--- a/x.ts\r\n+++ b/x.ts\r\n@@ -1 +1 @@\r\n-a\r\n+b\r\n" + ); + expect(parsed.paths).toEqual(["x.ts"]); + }); + + it("collapses a file named twice", () => { + const one = "--- a/x.ts\n+++ b/x.ts\n@@ -1 +1 @@\n-a\n+b\n"; + expect(parseDiffFiles(one + one).paths).toEqual(["x.ts"]); + }); + + it("does not recognize text that is not a unified diff", () => { + const parsed = parseDiffFiles( + "src/a.ts --- 1/2 --- TypeScript\n 1 const a = 1;\n" + ); + expect(parsed).toEqual({ paths: [], recognized: false }); + }); + + it("reports empty input as recognized nothing", () => { + expect(parseDiffFiles("")).toEqual({ paths: [], recognized: false }); + }); +});