Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .changeset/file-command.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <from-to>` 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 <from-to>` 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.
2 changes: 1 addition & 1 deletion SPECS/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <from-to>` 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 <from-to>` 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 <name>` and `-t, --image-tag <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 <pkg> to <version>` and a transitive one ends `(Fixed in <version>)`, 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) |
Expand Down
6 changes: 3 additions & 3 deletions SPECS/commands/file.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 (<reason>)` 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 (<reason>)` 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`.

Expand All @@ -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`.
11 changes: 7 additions & 4 deletions src/commands/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 (<reason>)`, 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
Expand Down
32 changes: 25 additions & 7 deletions src/commands/file.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
);
}
Expand All @@ -34,7 +34,11 @@ vi.mock("../utils/git-remote", () => ({
}));
vi.mock("../utils/repo-tree", async (importOriginal) => {
const actual = await importOriginal<typeof import("../utils/repo-tree")>();
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(() => {});
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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`);
Expand Down
29 changes: 22 additions & 7 deletions src/commands/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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("/") : "..";

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟑 MEDIUM RISK

An absolute path through a symlink to the repository is rejected even when it names a file inside the repository. Consider resolving symlink aliases before comparing the path with the git root.

TIP React πŸ‘ if this review is right, or reply with what's wrong and how it could be better to help improve the reviewer.

} else {
joined = path.posix.join(getCwdRepoRelativePath(), trimmed);
}
if (joined === ".." || joined.startsWith("../")) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟑 MEDIUM RISK

On Windows, an absolute path on another drive is not rejected as outside the repository because path.relative returns an absolute path rather than ../.... Consider rejecting an absolute joined result as well.

TIP React πŸ‘ if this review is right, or reply with what's wrong and how it could be better to help improve the reviewer.

throw new Error(`Path '${trimmed}' is outside the repository.`);
}
return normalizeRepoPath(joined);
}

Expand Down Expand Up @@ -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);
}
}

Expand Down
Loading