From 92aa1c088f2a0b4c83820ab405d01354e08de012 Mon Sep 17 00:00:00 2001 From: Alejandro Rizzo Date: Wed, 11 Nov 2026 15:02:08 +0000 Subject: [PATCH] fix(file): accept absolute paths and show the server's reason for missing source - Resolve an absolute path against the git root when the repository is auto-detected; refuse a path outside the repository before any request. - "Source not available (...)" now shows the server's message via errorReason() instead of the client's static status name. - These were review-round-2 fixes left uncommitted when #68 merged. Co-Authored-By: Claude Opus 5.5 --- .changeset/file-command.md | 2 +- SPECS/README.md | 2 +- SPECS/commands/file.md | 6 +++--- src/commands/AGENTS.md | 11 +++++++---- src/commands/file.test.ts | 32 +++++++++++++++++++++++++------- src/commands/file.ts | 29 ++++++++++++++++++++++------- 6 files changed, 59 insertions(+), 23 deletions(-) diff --git a/.changeset/file-command.md b/.changeset/file-command.md index 27f3d61..e9430ce 100644 --- a/.changeset/file-command.md +++ b/.changeset/file-command.md @@ -2,4 +2,4 @@ "@codacy/codacy-cloud-cli": minor --- -New `file` command (alias `fl`): shows a file's grade, issues, complexity, duplication and coverage, its issues and clones, and its source code with a covered/not-covered gutter. Use `--lines ` to narrow the source or `--no-source` to hide it. +New `file` command (alias `fl`): shows a file's grade, issues, complexity, duplication and coverage, its issues and clones, and its source code with a covered/not-covered gutter. Use `--lines ` to narrow the source or `--no-source` to hide it. With an auto-detected repository, the path can be relative to the current directory or absolute; a path outside the repository is refused. diff --git a/SPECS/README.md b/SPECS/README.md index bbcc26b..efbfdd7 100644 --- a/SPECS/README.md +++ b/SPECS/README.md @@ -49,7 +49,7 @@ This is the single source of truth for all project tasks and specs. | Date | What was done | |---|---| -| 2026-11-10 | New **`file`** command (alias `fl`): the CLI counterpart of the UI's file view. Summary (grade, issues, complexity, clones + duplicated lines, coverage with covered/coverable lines), its clones (lines here → other occurrences), and its source with a green/red coverage gutter and each issue inline under its line. Without source, the issues are listed at the top as the same cards `issues` prints; with `--lines`, issues outside the range are listed at the top. `--lines ` narrows the source, `-N, --no-source` hides it. The path is resolved to a `fileId` by listing the parent folder and matching exactly (not `search`, which matches substrings); with an auto-detected repository it is relative to the cwd. Source is fetched at the analysed `commitSha` so line numbers match issues and coverage. `--output json` carries no source code (the content endpoint isn't called): `{ file, issues, clones, coverage }`, with per-line `coverage.lines` `{ line, hits }`. Account token only — none of the file endpoints are whitelisted (27 new tests, 852 total) | +| 2026-11-10 | New **`file`** command (alias `fl`): the CLI counterpart of the UI's file view. Summary (grade, issues, complexity, clones + duplicated lines, coverage with covered/coverable lines), its clones (lines here → other occurrences), and its source with a green/red coverage gutter and each issue inline under its line. Without source, the issues are listed at the top as the same cards `issues` prints; with `--lines`, issues outside the range are listed at the top. `--lines ` narrows the source, `-N, --no-source` hides it. The path is resolved to a `fileId` by listing the parent folder and matching exactly (not `search`, which matches substrings); with an auto-detected repository it is relative to the cwd (an absolute path is resolved against the git root, and a path outside the repository is refused). Source is fetched at the analysed `commitSha` so line numbers match issues and coverage. `--output json` carries no source code (the content endpoint isn't called): `{ file, issues, clones, coverage }`, with per-line `coverage.lines` `{ line, hits }`. Account token only — none of the file endpoints are whitelisted (29 new tests, 854 total) | | 2026-11-09 | (OD-1049) `findings` can narrow to container scanning. **`--scan-types` accepts `ContainerSCA`**, the API value (as the `SearchSRMItems.scanTypes` example in the spec lists it), not `ContainerScanning` as the ticket named it; `ContainerScanning` and `Container` are accepted as aliases, normalized like the other scan types. The normalized list is now de-duplicated, since several aliases resolve to one value. **`-i, --image ` and `-t, --image-tag `** map to the body's `containerImage` (`ContainerImageFilter`), through `parseImageFilter`: values are trimmed, `--image name:tag` is split (a registry port stays in the name), and empty values, a tag without a name, a digest reference or two different tags are refused before any request. An empty `--image` would otherwise be dropped by a truthiness check and silently widen the result to the whole org. **Container findings show `image:tag` in place of the repository** on the `findings` card (also in the single-repository view) and on the `finding` header, through the shared `formatImageReference`; both commands' JSON gains `imageName`/`imageTag` (25 new tests, 823 total) | | 2026-11-03 | **Node.js engines raised for CVE-2026-111497** (Brotli decoder OOB write, bundled in Node). `engines` `>=20` → `^22.23.4 \|\| ^24.22.1 \|\| >=26.12.1`, the first patched release of each line; Node 20 is EOL and unpatched, so it is dropped. CI matrix `[20, 22]` → `[22, 24]`. No dependency change: the repo ships no Brotli package, but `fetch` (undici) decompresses `Content-Encoding: br` responses with Node's bundled decoder, so the runtime is the exposure. `engines` only warns on install; no runtime version check was added | | 2026-09-30 | (OD-590, OD-784) `fixedVersion` surfaced on `issue`/`issues`/`pull-request --issue`, now that `CommitIssue` carries it (first in API `57.7.9`; counterpart of `codacy-spa` #3145). **API bump: pinned `57.6.4` → `57.7.10`** — a diff of both bundled specs shows only `CommitIssue.fixedVersion` added, the organization webhook operations retagged `organization` → `webhooks` (the CLI uses none of them) and a `hasWebhooksEnabled` field on an organization schema; no operation signatures shifted, so `SPECS/repository-tokens.md`'s whitelist needed no changes. `57.7.9` and `57.7.10` bundle identical specs. `printIssueCard` (list) and `printIssueCodeContext` (detail, shared with `pull-request --issue` and `finding`'s linked-issue block) now pass `issue.fixedVersion` to the existing `formatDependencyChainsLine`/`formatDependencyChainsBlock`, so a direct dependency reads `Direct - Update to ` and a transitive one ends `(Fixed in )`, as on `finding`/`findings`. The param `finding` passes (`SrmItem.fixedVersion`) still wins when non-empty. An empty array (no fix available) renders as before — no version text — rather than adding a "no fix" phrase the other commands don't use. `fixedVersion` added to all three JSON projections (issue.test.ts 24→28, issues.test.ts 76→78, pull-request.test.ts +2) | diff --git a/SPECS/commands/file.md b/SPECS/commands/file.md index bce9515..50223c0 100644 --- a/SPECS/commands/file.md +++ b/SPECS/commands/file.md @@ -9,7 +9,7 @@ The CLI counterpart of the Codacy UI's file view for a single file: a summary of ## Usage ``` -codacy file src/index.ts # auto-detect repo; path relative to cwd +codacy file src/index.ts # auto-detect repo; path relative to cwd (or absolute; must be inside the repo) codacy file gh my-org my-repo src/index.ts # explicit repo; path relative to repo root codacy file src/index.ts --lines 40-120 codacy file src/index.ts --no-source @@ -47,7 +47,7 @@ None of these are on the repository-token whitelist, so the command requires an - **With source**, each issue is printed **inline** under its line as a compact card (`↳ • Severity | Category #id`, the message, a false-positive note / dependency chain when present, a separator); no file path or line text, since the line is right above. A top section **Issues outside the shown lines — Found N issues** lists, as full `printIssueCard` cards, only the issues whose line isn't among the fetched lines (outside `--lines`); it is omitted when there are none. - **Without source** (`--no-source`, or the content request failed), **Issues — Found N issues** lists every issue as a full `printIssueCard`, ordered by line. `No issues.` when empty. 3. **Clones — Found N clones**: table of `Lines` (the block in this file) and `Also in` (`path:from-to` per other occurrence, including a second block in the same file), ordered by line. -4. **Source** (with issues inline, see 2): `NNN ▌ │ content`. The gutter bar is green for covered lines (`hits > 0`), red for uncovered (`hits = 0`), blank for lines that can't be covered or when the file has no coverage. A legend line is printed only when there is coverage. `Source not available ()` if the content request fails (e.g. over 1MB). +4. **Source** (with issues inline, see 2): `NNN ▌ │ content`. The gutter bar is green for covered lines (`hits > 0`), red for uncovered (`hits = 0`), blank for lines that can't be covered or when the file has no coverage. A legend line is printed only when there is coverage. `Source not available ()` if the content request fails (e.g. over 1MB); the reason is the server's message. All repository-derived values (paths, content, clone paths) go through `sanitizeText`. @@ -68,4 +68,4 @@ All repository-derived values (paths, content, clone paths) go through `sanitize ## Tests -`src/commands/file.test.ts` (26 tests) + a refusal case in `repository-token-refusals.test.ts`. +`src/commands/file.test.ts` (28 tests) + a refusal case in `repository-token-refusals.test.ts`. diff --git a/src/commands/AGENTS.md b/src/commands/AGENTS.md index 059665d..a0319e7 100644 --- a/src/commands/AGENTS.md +++ b/src/commands/AGENTS.md @@ -262,8 +262,10 @@ Single-file view: summary, issues, clones, source with coverage. Spec in (non-recursive, `""` for the root) and matches `path` exactly. Don't switch to `search`: it matches substrings, so `app.ts` would also hit `myapp.ts`. - **Path is cwd-relative only when the repository is auto-detected** (one - positional), so `codacy file ../x.ts` behaves like a local path; with an - explicit repository it is repo-relative. + positional), so `codacy file ../x.ts` behaves like a local path. An absolute + path (shell completion, editors) is resolved against the git root, and a local + path that lands outside the repository is refused before any request. With an + explicit repository the path is repo-relative. - **Pass the raw path to `getFileContent`.** `OpenAPI.ENCODE_PATH` (`encodePathSegment`, set in `index.ts`) already escapes it once, `/` included. `issue`/`finding`/`pull-request` still pre-encode with @@ -275,8 +277,9 @@ Single-file view: summary, issues, clones, source with coverage. Spec in - **Coverage and source are optional.** `getFileCoverage` answers **404** for a file without coverage data; only that becomes "no gutter". Any other error propagates, so an outage isn't reported as "no coverage". A failed content - fetch (e.g. over 1MB → 413) prints `Source not available (…)` and the rest of - the view still renders. + fetch (e.g. over 1MB → 413) prints `Source not available ()`, with the + reason from `errorReason(err)` (the server's message, not the client's static + status name), and the rest of the view still renders. - **Issues and clones fetch every page**, like `ls`. The view is one file, and the lists are bounded by it, so no pagination warning is shown. - **Issues go inline when there is source.** `renderSource` prints each issue diff --git a/src/commands/file.test.ts b/src/commands/file.test.ts index e665ce1..bad0d3a 100644 --- a/src/commands/file.test.ts +++ b/src/commands/file.test.ts @@ -10,14 +10,14 @@ import { import { RepositoryService } from "../api/client/services/RepositoryService"; import { FileService } from "../api/client/services/FileService"; import { consoleOutput } from "../test-support"; -import { getCwdRepoRelativePath } from "../utils/repo-tree"; +import { getCwdRepoRelativePath, getGitRepoRoot } from "../utils/repo-tree"; import { ApiError } from "../api/client/core/ApiError"; import { encodePathSegment } from "../utils/api-path"; -function apiError(status: number, statusText: string): ApiError { +function apiError(status: number, statusText: string, message = statusText): ApiError { return new ApiError( { method: "GET", url: "/x" } as any, - { url: "/x", ok: false, status, statusText, body: { message: statusText } } as any, + { url: "/x", ok: false, status, statusText, body: { message } } as any, statusText, ); } @@ -34,7 +34,11 @@ vi.mock("../utils/git-remote", () => ({ })); vi.mock("../utils/repo-tree", async (importOriginal) => { const actual = await importOriginal(); - return { ...actual, getCwdRepoRelativePath: vi.fn(() => "") }; + return { + ...actual, + getCwdRepoRelativePath: vi.fn(() => ""), + getGitRepoRoot: vi.fn(() => "/home/me/repo"), + }; }); vi.spyOn(console, "log").mockImplementation(() => {}); vi.spyOn(console, "error").mockImplementation(() => {}); @@ -163,6 +167,20 @@ describe("resolveFilePath", () => { expect(resolveFilePath("../app.ts", true)).toBe("src/app.ts"); }); + it("resolves an absolute path against the git root", () => { + expect(resolveFilePath("/home/me/repo/src/a.ts", true)).toBe("src/a.ts"); + expect(getGitRepoRoot).toHaveBeenCalled(); + expect(getCwdRepoRelativePath).not.toHaveBeenCalled(); + }); + + it("refuses a path outside the repository", () => { + vi.mocked(getCwdRepoRelativePath).mockReturnValueOnce("src"); + expect(() => resolveFilePath("../../x.ts", true)).toThrow( + "Path '../../x.ts' is outside the repository.", + ); + expect(() => resolveFilePath("/etc/passwd", true)).toThrow("outside the repository"); + }); + it("treats the path as repo-relative when the repository is explicit", () => { expect(resolveFilePath("./src/app.ts", false)).toBe("src/app.ts"); expect(getCwdRepoRelativePath).not.toHaveBeenCalled(); @@ -370,11 +388,11 @@ describe("file command", () => { expect(encodePathSegment(sent)).toBe("src%2Fmy%20dir%2Ffile%20%231%25.ts"); }); - it("notes when the source cannot be fetched", async () => { - mockApi({ content: new Error("Payload Too Large") }); + it("notes when the source cannot be fetched, with the server's reason", async () => { + mockApi({ content: apiError(413, "Payload Too Large", "File is too large to display") }); await run("gh", "org", "repo", FILE_PATH); const out = consoleOutput(); - expect(out).toContain("Source not available (Payload Too Large)"); + expect(out).toContain("Source not available (File is too large to display)"); // No source → the issues are listed at the top as full cards expect(out).toContain("Issues — Found 1 issue"); expect(out).toContain(`${FILE_PATH}:2`); diff --git a/src/commands/file.ts b/src/commands/file.ts index 1e723bd..e7da5f1 100644 --- a/src/commands/file.ts +++ b/src/commands/file.ts @@ -4,13 +4,14 @@ import ora from "ora"; import ansis from "ansis"; import pluralize from "pluralize"; import { repositoryTokenOption, resolveAccountAuth } from "../utils/auth"; -import { handleError } from "../utils/error"; +import { errorReason, handleError } from "../utils/error"; import { createTable, getOutputFormat, pickDeep, printJson } from "../utils/output"; import { sanitizeText } from "../utils/sanitize"; import { resolveRepoArgs } from "../utils/resolve-repo-args"; import { fetchAllFiles, getCwdRepoRelativePath, + getGitRepoRoot, normalizeRepoPath, } from "../utils/repo-tree"; import { @@ -77,13 +78,25 @@ export function parseLineRange(value: string): LineRange { /** * Turn the user's path argument into a repository-relative path. With an - * auto-detected repository the path is relative to the current directory (like - * a local file path); with an explicit repository it is relative to the root. + * auto-detected repository the path is a local one: relative to the current + * directory, or absolute (what shell completion and editors hand over), which is + * resolved against the git root. With an explicit repository it is relative to + * the repository root. A local path that lands outside the repository is + * refused before any request is made. */ export function resolveFilePath(input: string, autoDetected: boolean): string { - const joined = autoDetected - ? path.posix.join(getCwdRepoRelativePath(), input.trim()) - : input; + if (!autoDetected) return normalizeRepoPath(input); + const trimmed = input.trim(); + let joined: string; + if (path.isAbsolute(trimmed)) { + const root = getGitRepoRoot(); + joined = root ? path.relative(root, trimmed).split(path.sep).join("/") : ".."; + } else { + joined = path.posix.join(getCwdRepoRelativePath(), trimmed); + } + if (joined === ".." || joined.startsWith("../")) { + throw new Error(`Path '${trimmed}' is outside the repository.`); + } return normalizeRepoPath(joined); } @@ -198,7 +211,9 @@ async function fetchFileData( ); source = content.data; } catch (err) { - sourceError = err instanceof Error ? err.message : String(err); + // errorReason, not err.message: for an ApiError the latter is the generated + // client's static status name, which hides the server's explanation. + sourceError = errorReason(err); } }