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
5 changes: 5 additions & 0 deletions .changeset/file-command.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@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.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ Codacy accepts repository tokens on a **limited set of repository-scoped operati
| `tools`, `tool`, `patterns`, `pattern` | `info`, `repositories` |
| `issues` (including `--overview`) | `issues --ignore`, `issues --ignored`, `issue` |
| `repository`, `repository --reanalyze` | `repository --add`/`--remove`/`--follow`/`--unfollow`/`--link-standard`/`--unlink-standard` |
| | `pull-request`, `pull-requests`, `ls`, `directories`, `findings`, `finding` |
| | `pull-request`, `pull-requests`, `ls`, `file`, `directories`, `findings`, `finding` |
| | `images`, `image` |

`codacy repository` works, but omits the pull request section — that endpoint doesn't accept repository tokens. In `--output json` it marks it as `"unavailable": ["pullRequests"]`, so a consumer can tell "none" apart from "couldn't look". Everything else, including the coverage status, is available.
Expand Down Expand Up @@ -144,6 +144,7 @@ Supported providers: GitHub (`gh`), GitLab (`gl`), Bitbucket (`bb`).
| `repositories <provider> <org>` | List repositories for an organization |
| `repository [provider] [org] [repo]` | Show metrics for a repository, or add/remove/follow/unfollow/reanalyze it (optionally waiting for results) |
| `ls [provider] [org] [repo]` | List (or search) directories and files at a path in a repository, with quality metrics and sorting |
| `file [provider] [org] [repo] <path>` | Show a file's metrics, issues, clones, and source code with coverage |
| `directories [provider] [org] [repo]` | List directories at a path in a repository (optionally one level of sub-directories), with quality metrics |
| `issues [provider] [org] [repo]` | Search issues in a repository with filters |
| `issue [provider] [org] [repo] <id>` | Show details for a single issue, or ignore/unignore it |
Expand Down
2 changes: 2 additions & 0 deletions SPECS/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ This is the single source of truth for all project tasks and specs.
| `repositories` | `repos` | ✅ Done (coverage status added) | [repositories.md](commands/repositories.md) |
| `repository` | `repo` | ✅ Done (actions + coverage status added) | [repository.md](commands/repository.md) |
| `ls` | N/A | ✅ Done | [ls.md](commands/ls.md) |
| `file` | `fl` | ✅ Done | [file.md](commands/file.md) |
| `directories` | `dirs` | ✅ Done | [directories.md](commands/directories.md) |
| `pull-request` | `pr` | ✅ Done (--diff + Diff Coverage Summary added) | [pull-request.md](commands/pull-request.md) |
| `pull-requests` | `prs` | ✅ Done | [pull-requests.md](commands/pull-requests.md) |
Expand Down Expand Up @@ -48,6 +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-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
71 changes: 71 additions & 0 deletions SPECS/commands/file.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# `file` Command Spec

**Status:** ✅ Done (2026-11-10)

## Purpose

The CLI counterpart of the Codacy UI's file view for a single file: a summary of its metrics, its issues and clones, and its source code with coverage marks.

## Usage

```
codacy file src/index.ts # auto-detect repo; path relative to cwd
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
codacy file src/index.ts --branch develop
codacy file src/index.ts --output json
```

Alias: `fl`.

## API Endpoints

| Step | Operation | Notes |
|---|---|---|
| Resolve `fileId` | `RepositoryService.listFiles(…, branch, <parent dir>)` | Parent folder listing, all pages, exact `path` match |
| Metadata + metrics | `RepositoryService.getFileWithAnalysis(fileId)` | `file`, `quality`, `coverage` |
| Issues | `RepositoryService.getFileIssues(fileId)` | All pages |
| Clones | `RepositoryService.getFileClones(fileId)` | All pages |
| Line coverage | `RepositoryService.getFileCoverage(fileId)` | `{line, hits}[]`; a 404 (no coverage data for the file) means "no coverage", any other error fails the command |
| Source | `FileService.getFileContent(path, from, to, commitSha)` | Pinned to the analysed commit; skipped with `--no-source` and with `--output json` |

None of these are on the repository-token whitelist, so the command requires an account token (`resolveAccountAuth`).

## Options

| Option | Short | Description |
|---|---|---|
| `--branch <branch>` | `-b` | Branch (defaults to the main branch) |
| `--lines <range>` | `-l` | Source range: `40-120`, `40-` (to end) or `40`. Validated before any request |
| `--no-source` | `-N` | Hide the source section (and skip the content request) |

## Output

1. **Header**: path (bold), `language · branch · commit <sha7>` (dim), a yellow note if the file is ignored, then a table: Grade, Issues, Complexity, Duplication (`N clones · M duplicated lines`), Coverage (`66.7% (2/3 lines)` or `-`).
2. **Issues** — where they show depends on whether there is source:
- **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).

All repository-derived values (paths, content, clone paths) go through `sanitizeText`.

## JSON

`--output json` carries **no source code** — the content endpoint isn't called — only metadata, issues, clones and coverage. `--lines` and `--no-source` affect the source section only, so they don't change the JSON.

```json
{
"file": { "path", "fileId", "branchId", "language", "commitSha", "ignored", "quality" },
"issues": [ /* same projection as `issues --output json` */ ],
"clones": [ { "id", "occurrences": [ { "path", "fileId", "fileDataId", "fromLine", "toLine" } ] } ],
"coverage": { "coverage", "coverableLines", "coveredLines", "lines": [ { "line", "hits" } ] } | null
}
```

`coverage.lines` lists coverable lines only, ordered by line (`hits: 0` = not covered). `coverage` is `null` when the file has no coverage data.

## Tests

`src/commands/file.test.ts` (26 tests) + a refusal case in `repository-token-refusals.test.ts`.
2 changes: 1 addition & 1 deletion SPECS/repository-tokens.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ none. `issues -T <name>` and the `issues -O` noise suggestions rely on this.
| `repository` (dashboard) | ⚠️ partial — pull requests + coverage reports skipped |
| `repository --reanalyze` / `--reanalyze-and-wait` | ✅ |
| `repository --add/--remove/--follow/--unfollow/--link-standard/--unlink-standard` | ❌ refused |
| `info`, `repositories`, `ls`, `directories`, `pull-request`, `pull-requests`, `issue`, `findings`, `finding` | ❌ refused |
| `info`, `repositories`, `ls`, `file`, `directories`, `pull-request`, `pull-requests`, `issue`, `findings`, `finding` | ❌ refused |
| `images`, `image` (all modes) | ❌ refused — organization-level SBOM operations, none whitelisted |
| `login`, `logout` | Warn that the flag is ignored |

Expand Down
38 changes: 38 additions & 0 deletions src/commands/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,44 @@ also pull each folder's immediate sub-folders (one extra level).
form).
- JSON: `ls` → `{ path, directories, files }`; `directories` → `{ path, directories: [{…, children?}] }`, each item projected via `pickDeep`.

## file command (`file.ts`)

Single-file view: summary, issues, clones, source with coverage. Spec in
[`SPECS/commands/file.md`](../../SPECS/commands/file.md).

- **Path → `fileId` via the parent folder.** Every file endpoint takes a
`fileId`, which only `listFiles` returns. The command lists the parent folder
(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.
- **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
`encodeURIComponent`; the API happens to accept the double-encoded form for
ordinary paths, but single encoding is the correct one.
- **Source is pinned to `info.file.commitSha`.** The content endpoint defaults to
the branch HEAD, which can be ahead of the last analysis, and then issue and
coverage line numbers would point at the wrong lines.
- **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.
- **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
under its line via `renderInlineIssue` (compact card, `↳` in the line-number
column). `issuesNotInline` decides what the top section lists: everything
without source, otherwise only issues whose line wasn't fetched (outside
`--lines`) — so `--lines` never hides an issue. Those, and the no-source list,
use the full `printIssueCard`.
- **JSON has no source code.** `--output json` skips the content request and
prints `{ file, issues, clones, coverage }`; per-line data is
`coverage.lines` (`{ line, hits }`, coverable lines only). The issue
projection matches `issues`'.

## Shared Formatting Utilities (`utils/formatting.ts`)

Several helpers are shared between `repository.ts` and `pull-request.ts` via `utils/formatting.ts`:
Expand Down
Loading
Loading