diff --git a/.changeset/file-command.md b/.changeset/file-command.md new file mode 100644 index 0000000..27f3d61 --- /dev/null +++ b/.changeset/file-command.md @@ -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 ` to narrow the source or `--no-source` to hide it. diff --git a/README.md b/README.md index 7365a9f..af10d28 100644 --- a/README.md +++ b/README.md @@ -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. @@ -144,6 +144,7 @@ Supported providers: GitHub (`gh`), GitLab (`gl`), Bitbucket (`bb`). | `repositories ` | 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] ` | 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] ` | Show details for a single issue, or ignore/unignore it | diff --git a/SPECS/README.md b/SPECS/README.md index 0cdfacc..bbcc26b 100644 --- a/SPECS/README.md +++ b/SPECS/README.md @@ -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) | @@ -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 ` 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 ` 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 new file mode 100644 index 0000000..bce9515 --- /dev/null +++ b/SPECS/commands/file.md @@ -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 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 ` | `-b` | Branch (defaults to the main branch) | +| `--lines ` | `-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 ` (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 ()` 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`. diff --git a/SPECS/repository-tokens.md b/SPECS/repository-tokens.md index a5750f2..7ff4844 100644 --- a/SPECS/repository-tokens.md +++ b/SPECS/repository-tokens.md @@ -100,7 +100,7 @@ none. `issues -T ` 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 | diff --git a/src/commands/AGENTS.md b/src/commands/AGENTS.md index 81d23be..059665d 100644 --- a/src/commands/AGENTS.md +++ b/src/commands/AGENTS.md @@ -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`: diff --git a/src/commands/file.test.ts b/src/commands/file.test.ts new file mode 100644 index 0000000..e665ce1 --- /dev/null +++ b/src/commands/file.test.ts @@ -0,0 +1,447 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { Command } from "commander"; +import { + registerFileCommand, + parseLineRange, + resolveFilePath, + renderSource, + coverageGutter, +} from "./file"; +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 { ApiError } from "../api/client/core/ApiError"; +import { encodePathSegment } from "../utils/api-path"; + +function apiError(status: number, statusText: string): ApiError { + return new ApiError( + { method: "GET", url: "/x" } as any, + { url: "/x", ok: false, status, statusText, body: { message: statusText } } as any, + statusText, + ); +} + +vi.mock("../api/client/services/RepositoryService"); +vi.mock("../api/client/services/FileService"); +vi.mock("../utils/credentials", () => ({ loadCredentials: vi.fn(() => null) })); +vi.mock("../utils/git-remote", () => ({ + detectRepoContext: vi.fn(() => ({ + provider: "gh", + organization: "auto-org", + repository: "auto-repo", + })), +})); +vi.mock("../utils/repo-tree", async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, getCwdRepoRelativePath: vi.fn(() => "") }; +}); +vi.spyOn(console, "log").mockImplementation(() => {}); +vi.spyOn(console, "error").mockImplementation(() => {}); + +function createProgram(): Command { + const program = new Command(); + program.option("-o, --output ", "output format", "table"); + registerFileCommand(program); + return program; +} + +const FILE_PATH = "src/app.ts"; +const FILE_ID = 42; + +const fileInfo = { + file: { + fileId: FILE_ID, + fileDataId: 7, + commitId: 1, + commitSha: "abcdef1234567890", + path: FILE_PATH, + language: "TypeScript", + gitProviderUrl: "https://example.com", + ignored: false, + }, + quality: { + totalIssues: 1, + complexity: 12, + grade: 80, + gradeLetter: "B", + duplication: 1, + duplicatedLinesOfCode: 6, + }, + coverage: { coverage: 66.67, coverableLines: 3, coveredLines: 2 }, +}; + +const issue = { + issueId: "uuid", + resultDataId: 1001, + filePath: FILE_PATH, + lineNumber: 2, + lineText: "eval(input);", + message: "Avoid eval", + falsePositiveThreshold: 80, + patternInfo: { + id: "no-eval", + category: "Security", + severityLevel: "Error", + }, + toolInfo: { uuid: "t", name: "ESLint" }, + commitInfo: { sha: "abc" }, + language: "TypeScript", +}; + +const clone = { + id: 9, + occurrences: [ + { path: FILE_PATH, fileId: FILE_ID, fileDataId: 7, fromLine: 10, toLine: 15 }, + { path: "src/other.ts", fileId: 99, fileDataId: 8, fromLine: 3, toLine: 8 }, + ], +}; + +const source = [ + { number: 1, content: "const a = 1;" }, + { number: 2, content: "eval(input);" }, + { number: 3, content: "// comment" }, + { number: 4, content: "return a;" }, +]; + +function mockApi(overrides: { files?: unknown[]; coverage?: unknown; content?: unknown } = {}) { + vi.mocked(RepositoryService.listFiles).mockResolvedValue({ + data: overrides.files ?? [ + { fileId: 1, path: "src/app.test.ts" }, + { fileId: FILE_ID, path: FILE_PATH }, + ], + } as any); + vi.mocked(RepositoryService.getFileWithAnalysis).mockResolvedValue(fileInfo as any); + vi.mocked(RepositoryService.getFileIssues).mockResolvedValue({ data: [issue] } as any); + vi.mocked(RepositoryService.getFileClones).mockResolvedValue({ data: [clone] } as any); + if (overrides.coverage instanceof Error) { + vi.mocked(RepositoryService.getFileCoverage).mockRejectedValue(overrides.coverage); + } else { + vi.mocked(RepositoryService.getFileCoverage).mockResolvedValue( + (overrides.coverage ?? { + data: [ + { line: 1, hits: 3 }, + { line: 2, hits: 0 }, + { line: 4, hits: 1 }, + ], + }) as any, + ); + } + if (overrides.content instanceof Error) { + vi.mocked(FileService.getFileContent).mockRejectedValue(overrides.content); + } else { + vi.mocked(FileService.getFileContent).mockResolvedValue( + (overrides.content ?? { data: source }) as any, + ); + } +} + +async function run(...args: string[]) { + await createProgram().parseAsync(["node", "test", "file", ...args]); +} + +describe("parseLineRange", () => { + it("parses from-to, open-ended and single-line ranges", () => { + expect(parseLineRange("40-120")).toEqual({ from: 40, to: 120 }); + expect(parseLineRange("40-")).toEqual({ from: 40, to: undefined }); + expect(parseLineRange("7")).toEqual({ from: 7, to: 7 }); + }); + + it("rejects malformed or inverted ranges", () => { + expect(() => parseLineRange("abc")).toThrow("Invalid --lines"); + expect(() => parseLineRange("0-3")).toThrow("lines start at 1"); + expect(() => parseLineRange("10-5")).toThrow("must not exceed"); + expect(() => parseLineRange("-5")).toThrow("Invalid --lines"); + }); +}); + +describe("resolveFilePath", () => { + beforeEach(() => vi.clearAllMocks()); + + it("joins the cwd when the repository is auto-detected", () => { + vi.mocked(getCwdRepoRelativePath).mockReturnValueOnce("src/utils"); + expect(resolveFilePath("../app.ts", true)).toBe("src/app.ts"); + }); + + 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(); + }); +}); + +describe("coverageGutter", () => { + // Colors are off under the test env (NO_COLOR), so this checks the glyph + // placement; green vs red was verified against a live repository. + it("marks coverable lines (covered or not) and leaves the rest blank", () => { + const coverage = new Map([ + [1, 3], + [2, 0], + ]); + expect(coverageGutter(1, coverage)).toContain("▌"); + expect(coverageGutter(2, coverage)).toContain("▌"); + expect(coverageGutter(3, coverage)).toBe(" "); + expect(coverageGutter(1, null)).toBe(" "); + }); +}); + +describe("renderSource", () => { + it("neutralizes control characters in inline issue messages", () => { + const out = renderSource( + [{ number: 2, content: "x" }], + null, + [{ ...issue, message: "bad\x1b[2Jmsg" } as any], + ).join("\n"); + expect(out).not.toContain("\x1b[2J"); + }); + + it("handles a very long file without overflowing Math.max", () => { + const many = Array.from({ length: 200_000 }, (_, i) => ({ number: i + 1, content: "x" })); + const out = renderSource(many, null); + expect(out).toHaveLength(200_000); + expect(out[0]).toMatch(/^ {5}1 /); + }); + + it("neutralizes control characters in file content", () => { + const [line] = renderSource([{ number: 1, content: "evil\x1b]52;c;aGk=\x07" }], null); + expect(line).not.toContain("\x1b]52"); + expect(line).not.toContain("\x07"); + }); +}); + +describe("file command", () => { + beforeEach(() => { + vi.clearAllMocks(); + process.env.CODACY_API_TOKEN = "test-token"; + delete process.env.CODACY_PROJECT_TOKEN; + }); + + it("resolves the fileId by listing the parent folder and matching exactly", async () => { + mockApi(); + await run("gh", "org", "repo", FILE_PATH); + + const listCall = vi.mocked(RepositoryService.listFiles).mock.calls[0]; + expect(listCall.slice(0, 5)).toEqual(["gh", "org", "repo", undefined, "src"]); + expect(vi.mocked(RepositoryService.getFileWithAnalysis).mock.calls[0][3]).toBe(FILE_ID); + }); + + it("lists the repository root for a top-level file", async () => { + mockApi({ files: [{ fileId: FILE_ID, path: "README.md" }] }); + await run("gh", "org", "repo", "README.md"); + expect(vi.mocked(RepositoryService.listFiles).mock.calls[0][4]).toBe(""); + }); + + it("resolves the repository from the git remote with a single argument", async () => { + mockApi(); + await run(FILE_PATH); + expect(vi.mocked(RepositoryService.listFiles).mock.calls[0].slice(0, 3)).toEqual([ + "gh", + "auto-org", + "auto-repo", + ]); + }); + + it("errors when the file is not on Codacy", async () => { + mockApi({ files: [{ fileId: 1, path: "src/other.ts" }] }); + const exit = vi.spyOn(process, "exit").mockImplementation(() => { + throw new Error("process.exit called"); + }); + await expect(run("gh", "org", "repo", FILE_PATH)).rejects.toThrow("process.exit called"); + const err = vi.mocked(console.error).mock.calls.flat().join("\n"); + expect(err).toContain("not found on Codacy"); + expect(RepositoryService.getFileWithAnalysis).not.toHaveBeenCalled(); + exit.mockRestore(); + }); + + it("renders the summary, clones and source with issues inline", async () => { + mockApi(); + await run("gh", "org", "repo", FILE_PATH); + const out = consoleOutput(); + + // Summary + expect(out).toContain(FILE_PATH); + expect(out).toContain("TypeScript · commit abcdef1"); + expect(out).toContain("1 clone · 6 duplicated lines"); + expect(out).toContain("66.7% (2/3 lines)"); + // With source, the issue is inline — no top Issues section + expect(out).not.toContain("Issues —"); + expect(out).not.toContain("Issues outside"); + // Clones + expect(out).toContain("Clones — Found 1 clone"); + expect(out).toContain("10-15"); + expect(out).toContain("src/other.ts:3-8"); + // Source + expect(out).toContain("covered"); + expect(out).toMatch(/1 ▌ │ const a = 1;/); + expect(out).toMatch(/3 │ \/\/ comment/); + // Inline card right under line 2, before line 3 + const lines = out.split("\n"); + const at = lines.findIndex((l) => /^2 . │ eval\(input\);/.test(l)); + expect(lines[at + 1]).toBe("↳ • Critical | Security #1001"); + expect(lines[at + 2]).toBe(" Avoid eval"); + expect(lines[at + 3]).toMatch(/^─+$/); + expect(lines[at + 4]).toMatch(/^3 │/); + }); + + it("lists issues outside --lines at the top and the rest inline", async () => { + mockApi({ content: { data: source.slice(0, 1) } }); + vi.mocked(RepositoryService.getFileIssues).mockResolvedValue({ + data: [ + { ...issue, resultDataId: 2001, lineNumber: 1, message: "Inline one" }, + issue, + ], + } as any); + await run("gh", "org", "repo", FILE_PATH, "--lines", "1"); + const out = consoleOutput(); + expect(out).toContain("Issues outside the shown lines — Found 1 issue"); + // Full card (with file:line) for the outside issue + expect(out).toContain(`${FILE_PATH}:2`); + expect(out).toContain("↳ • Critical | Security #2001"); + expect(out.indexOf("Avoid eval")).toBeLessThan(out.indexOf("Inline one")); + }); + + it("renders the inline false-positive note", async () => { + mockApi(); + vi.mocked(RepositoryService.getFileIssues).mockResolvedValue({ + data: [{ ...issue, falsePositiveProbability: 90, falsePositiveReason: "test code" }], + } as any); + await run("gh", "org", "repo", FILE_PATH); + expect(consoleOutput()).toContain(" Potential false positive: test code"); + }); + + it("pins the source to the analysed commit and passes --lines", async () => { + mockApi(); + await run("gh", "org", "repo", FILE_PATH, "--lines", "2-3"); + expect(vi.mocked(FileService.getFileContent).mock.calls[0]).toEqual([ + "gh", + "org", + "repo", + FILE_PATH, + 2, + 3, + "abcdef1234567890", + ]); + }); + + it("validates --lines before any request", async () => { + mockApi(); + const exit = vi.spyOn(process, "exit").mockImplementation(() => { + throw new Error("process.exit called"); + }); + await expect(run("gh", "org", "repo", FILE_PATH, "--lines", "9-1")).rejects.toThrow( + "process.exit called", + ); + expect(RepositoryService.listFiles).not.toHaveBeenCalled(); + exit.mockRestore(); + }); + + it("skips the source with --no-source and lists issues at the top", async () => { + mockApi(); + await run("gh", "org", "repo", FILE_PATH, "--no-source"); + expect(FileService.getFileContent).not.toHaveBeenCalled(); + expect(consoleOutput()).not.toContain("Source"); + expect(consoleOutput()).toContain("Issues — Found 1 issue"); + }); + + it("shows the source without a gutter legend when there is no coverage", async () => { + mockApi({ coverage: apiError(404, "Not Found") }); + await run("gh", "org", "repo", FILE_PATH); + const out = consoleOutput(); + expect(out).not.toContain("not covered"); + expect(out).toMatch(/1 │ const a = 1;/); + }); + + it("surfaces a coverage failure other than 404 instead of hiding it", async () => { + mockApi({ coverage: apiError(500, "Internal Server Error") }); + const exit = vi.spyOn(process, "exit").mockImplementation(() => { + throw new Error("process.exit called"); + }); + await expect(run("gh", "org", "repo", FILE_PATH)).rejects.toThrow("process.exit called"); + expect(vi.mocked(console.error).mock.calls.flat().join("\n")).toContain("Error:"); + exit.mockRestore(); + }); + + it("passes the raw path so the client's encoder escapes it exactly once", async () => { + const odd = "src/my dir/file #1%.ts"; + mockApi({ files: [{ fileId: FILE_ID, path: odd }] }); + await run("gh", "org", "repo", odd); + const sent = vi.mocked(FileService.getFileContent).mock.calls[0][3]; + expect(sent).toBe(odd); + // What the generated client puts in the URL (OpenAPI.ENCODE_PATH, set in index.ts) + 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") }); + await run("gh", "org", "repo", FILE_PATH); + const out = consoleOutput(); + expect(out).toContain("Source not available (Payload Too Large)"); + // 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`); + expect(out).not.toContain("↳"); + }); + + it("follows pagination for issues and clones", async () => { + mockApi(); + vi.mocked(RepositoryService.getFileIssues) + .mockResolvedValueOnce({ data: [issue], pagination: { cursor: "c1", limit: 100 } } as any) + .mockResolvedValueOnce({ data: [{ ...issue, resultDataId: 1002, lineNumber: 1 }] } as any); + await run("gh", "org", "repo", FILE_PATH, "-o", "json"); + expect(RepositoryService.getFileIssues).toHaveBeenCalledTimes(2); + expect(vi.mocked(RepositoryService.getFileIssues).mock.calls[1][4]).toBe("c1"); + }); + + it("prints issues, clones and coverage as JSON, without source code", async () => { + mockApi(); + await createProgram().parseAsync([ + "node", "test", "--output", "json", "file", "gh", "org", "repo", FILE_PATH, + ]); + // JSON carries no code, so the content endpoint isn't called at all. + expect(FileService.getFileContent).not.toHaveBeenCalled(); + const json = JSON.parse(vi.mocked(console.log).mock.calls[0][0] as string); + expect(Object.keys(json)).toEqual(["file", "issues", "clones", "coverage"]); + expect(json.file).toMatchObject({ + path: FILE_PATH, + fileId: FILE_ID, + commitSha: "abcdef1234567890", + quality: { gradeLetter: "B" }, + }); + expect(json.issues[0]).toMatchObject({ resultDataId: 1001, message: "Avoid eval" }); + expect(json.issues[0].toolInfo).toBeUndefined(); + expect(json.clones).toHaveLength(1); + expect(json.coverage).toEqual({ + coverage: 66.67, + coverableLines: 3, + coveredLines: 2, + lines: [ + { line: 1, hits: 3 }, + { line: 2, hits: 0 }, + { line: 4, hits: 1 }, + ], + }); + expect(JSON.stringify(json)).not.toContain("const a = 1;"); + }); + + it("prints coverage as null in JSON when the file has none", async () => { + mockApi({ coverage: apiError(404, "Not Found") }); + vi.mocked(RepositoryService.getFileWithAnalysis).mockResolvedValue({ + ...fileInfo, + coverage: undefined, + } as any); + await run("gh", "org", "repo", FILE_PATH, "-o", "json"); + const json = JSON.parse(vi.mocked(console.log).mock.calls[0][0] as string); + expect(json.coverage).toBeNull(); + }); + + it("sanitizes a crafted file path in the human output", async () => { + const evil = "src/\x1b[2Jevil.ts"; + mockApi({ files: [{ fileId: FILE_ID, path: evil }] }); + vi.mocked(RepositoryService.getFileWithAnalysis).mockResolvedValue({ + ...fileInfo, + file: { ...fileInfo.file, path: evil }, + } as any); + await run("gh", "org", "repo", evil); + const raw = vi.mocked(console.log).mock.calls.map((c) => String(c[0])).join("\n"); + expect(raw).not.toContain("\x1b[2J"); + }); +}); diff --git a/src/commands/file.ts b/src/commands/file.ts new file mode 100644 index 0000000..1e723bd --- /dev/null +++ b/src/commands/file.ts @@ -0,0 +1,579 @@ +import * as path from "path"; +import { Command } from "commander"; +import ora from "ora"; +import ansis from "ansis"; +import pluralize from "pluralize"; +import { repositoryTokenOption, resolveAccountAuth } from "../utils/auth"; +import { 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, + normalizeRepoPath, +} from "../utils/repo-tree"; +import { + colorSeverity, + formatDependencyChainsLine, + formatCount, + formatCountCell, + formatCoverageCell, + formatGrade, + printIssueCard, + printSection, +} from "../utils/formatting"; +import { RepositoryService } from "../api/client/services/RepositoryService"; +import { FileService } from "../api/client/services/FileService"; +import { CodeBlockLine } from "../api/client/models/CodeBlockLine"; +import { CommitIssue } from "../api/client/models/CommitIssue"; +import { FileClone } from "../api/client/models/FileClone"; +import { FileInformationWithAnalysis } from "../api/client/models/FileInformationWithAnalysis"; +import { PaginationInfo } from "../api/client/models/PaginationInfo"; +import { ApiError } from "../api/client/core/ApiError"; + +/** + * `codacy file` — the CLI counterpart of the file view in the Codacy UI: + * summary metrics, the file's issues and clones, and its source code with a + * coverage gutter. See SPECS/commands/file.md. + */ + +interface FileOptions { + branch?: string; + lines?: string; + /** Commander's `--no-source` negation: true unless the flag is passed. */ + source: boolean; +} + +export interface LineRange { + from?: number; + to?: number; +} + +/** Glyph for the coverage gutter; colored green (covered) or red (not covered). */ +const COVERAGE_BAR = "▌"; + +/** + * Parse `--lines`: `40-120`, `40-` (to the end) or `40` (one line). + * Throws on anything else so the command fails before any request. + */ +export function parseLineRange(value: string): LineRange { + const match = /^\s*(\d+)\s*(?:(-)\s*(\d*)\s*)?$/.exec(value); + if (!match) { + throw new Error( + `Invalid --lines value "${value}". Use FROM-TO, FROM- or a single LINE (e.g. 40-120, 40-, 40).`, + ); + } + const from = parseInt(match[1], 10); + const hasDash = match[2] !== undefined; + const to = match[3] ? parseInt(match[3], 10) : hasDash ? undefined : from; + if (from < 1 || (to !== undefined && to < from)) { + throw new Error( + `Invalid --lines value "${value}": lines start at 1 and the start must not exceed the end.`, + ); + } + return { from, to }; +} + +/** + * 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. + */ +export function resolveFilePath(input: string, autoDetected: boolean): string { + const joined = autoDetected + ? path.posix.join(getCwdRepoRelativePath(), input.trim()) + : input; + return normalizeRepoPath(joined); +} + +/** Fetch every page of a cursor-paginated endpoint. */ +async function fetchAllPages( + fetchPage: ( + cursor: string | undefined, + ) => Promise<{ data: T[]; pagination?: PaginationInfo }>, +): Promise { + const all: T[] = []; + let cursor: string | undefined; + do { + const response = await fetchPage(cursor); + all.push(...response.data); + cursor = response.pagination?.cursor; + } while (cursor); + return all; +} + +/** + * Resolve a path to its Codacy `fileId` by listing the parent folder + * (non-recursive) and matching the path exactly. Listing the parent instead of + * using `search` avoids its substring/wildcard matching. + */ +async function resolveFileId( + provider: string, + organization: string, + repository: string, + branch: string | undefined, + filePath: string, +): Promise { + const dir = path.posix.dirname(filePath); + const files = await fetchAllFiles( + provider, + organization, + repository, + branch, + dir === "." ? "" : dir, + ); + const match = files.find((f) => f.path === filePath); + if (!match) { + throw new Error( + `File '${sanitizeText(filePath)}' not found on Codacy. It may be ignored, not analyzed yet, ` + + `or not on this branch${branch ? "" : " (try --branch)"}.`, + ); + } + return match.fileId; +} + +interface RepoRef { + provider: string; + organization: string; + repository: string; +} + +interface FileData { + info: FileInformationWithAnalysis; + issues: CommitIssue[]; + clones: FileClone[]; + /** line number → hits; null when the file has no coverage data. */ + coverage: Map | null; + /** null when the source was not requested or could not be fetched. */ + source: CodeBlockLine[] | null; + sourceError?: string; +} + +async function fetchFileData( + { provider, organization, repository }: RepoRef, + filePath: string, + fileId: number, + fetchSource: boolean, + range: LineRange, +): Promise { + const [info, issues, clones, coverageResponse] = await Promise.all([ + RepositoryService.getFileWithAnalysis(provider, organization, repository, fileId), + fetchAllPages((cursor) => + RepositoryService.getFileIssues(provider, organization, repository, fileId, cursor, 100), + ), + fetchAllPages((cursor) => + RepositoryService.getFileClones(provider, organization, repository, fileId, cursor, 100), + ), + // Coverage is optional: a file without coverage data answers 404 ("No + // coverage data for file …"). Any other failure is a real error. + RepositoryService.getFileCoverage(provider, organization, repository, fileId).catch( + (err: unknown) => { + if (err instanceof ApiError && err.status === 404) return null; + throw err; + }, + ), + ]); + + const coverage = + coverageResponse && coverageResponse.data.length > 0 + ? new Map(coverageResponse.data.map((c) => [c.line, c.hits])) + : null; + + let source: CodeBlockLine[] | null = null; + let sourceError: string | undefined; + if (fetchSource) { + try { + // Pinned to the analysed commit so line numbers match issues and coverage. + // The raw path is passed: the client's global encoder (`encodePathSegment`, + // installed in index.ts) escapes it once, `/` included. + const content = await FileService.getFileContent( + provider, + organization, + repository, + filePath, + range.from, + range.to, + info.file.commitSha, + ); + source = content.data; + } catch (err) { + sourceError = err instanceof Error ? err.message : String(err); + } + } + + // Issues ordered by line, as they appear in the file. + issues.sort((a, b) => a.lineNumber - b.lineNumber); + return { info, issues, clones, coverage, source, sourceError }; +} + +// ── Rendering ──────────────────────────────────────────────────────────────── + +/** The coverage gutter cell for one line: green/red bar, or blank when not coverable. */ +export function coverageGutter( + line: number, + coverage: Map | null, +): string { + if (!coverage) return " "; + const hits = coverage.get(line); + if (hits === undefined) return " "; + return hits > 0 ? ansis.green(COVERAGE_BAR) : ansis.red(COVERAGE_BAR); +} + +/** Width of the separator under an inline issue card. */ +const INLINE_SEPARATOR_WIDTH = 78; + +/** + * A compact issue card printed under its source line: + * + * ↳ • Medium | Complexity #131497158287 + * Method printFindingDetail has 81 lines of code (limit is 60) + * ────────────────────────────────────────── + * + * The `↳` sits in the line-number column and the body aligns past the gutter. + * The file path and line text of the full card are dropped: the line is right + * above it. + */ +export function renderInlineIssue(issue: CommitIssue, width: number): string[] { + const p = issue.patternInfo; + const arrow = ansis.dim("↳".padStart(width, " ")); + const indent = " ".repeat(width + 5); + const subCat = p.subCategory ? ` ${sanitizeText(p.subCategory)}` : ""; + const id = ansis.hex("#555555")(`#${issue.resultDataId}`); + const out = [ + `${arrow} • ${colorSeverity(p.severityLevel)} ${ansis.dim("|")} ${sanitizeText(p.category)}${subCat} ${id}`, + `${indent}${sanitizeText(issue.message)}`, + ]; + if ( + issue.falsePositiveProbability !== undefined && + issue.falsePositiveProbability >= issue.falsePositiveThreshold + ) { + const reason = issue.falsePositiveReason || "No reason provided"; + out.push(`${indent}${ansis.yellow(`Potential false positive: ${sanitizeText(reason)}`)}`); + } + if (issue.dependencyChains?.length) { + // Already sanitized by the helper. + const chain = formatDependencyChainsLine(issue.dependencyChains, issue.fixedVersion); + if (chain) out.push(`${indent}${ansis.dim(chain)}`); + } + out.push(ansis.dim(`${" ".repeat(Math.max(0, width - 1))}${"─".repeat(INLINE_SEPARATOR_WIDTH)}`)); + return out; +} + +/** + * Source lines as `NNN ▌ │ content`, with the coverage gutter, and each line's + * issues rendered inline right under it. + */ +export function renderSource( + lines: CodeBlockLine[], + coverage: Map | null, + issues: CommitIssue[] = [], +): string[] { + // A reduce, not Math.max(...lines): spreading ~150k lines overflows the stack. + const maxLine = lines.reduce((max, l) => (l.number > max ? l.number : max), 0); + const width = String(maxLine).length; + const byLine = new Map(); + for (const issue of issues) { + byLine.set(issue.lineNumber, [...(byLine.get(issue.lineNumber) ?? []), issue]); + } + return lines.flatMap((l) => { + const num = ansis.dim(String(l.number).padStart(width, " ")); + // File content is attacker-controllable — neutralize before printing. + const line = `${num} ${coverageGutter(l.number, coverage)} ${ansis.dim("│")} ${sanitizeText(l.content)}`; + const inline = (byLine.get(l.number) ?? []).flatMap((i) => renderInlineIssue(i, width)); + return [line, ...inline]; + }); +} + +/** + * Issues that won't appear inline: all of them without source, otherwise those + * whose line isn't among the fetched source lines (outside `--lines`, or a line + * the content endpoint didn't return). + */ +export function issuesNotInline( + issues: CommitIssue[], + source: CodeBlockLine[] | null, +): CommitIssue[] { + if (!source || source.length === 0) return issues; + const shown = new Set(source.map((l) => l.number)); + return issues.filter((i) => !shown.has(i.lineNumber)); +} + +function printSummary(data: FileData, branch: string | undefined): void { + const { file, quality, coverage } = data.info; + console.log(ansis.bold(`\n${sanitizeText(file.path)}`)); + const meta = [ + file.language ? sanitizeText(file.language) : undefined, + branch ? `branch ${sanitizeText(branch)}` : undefined, + file.commitSha ? `commit ${sanitizeText(file.commitSha.substring(0, 7))}` : undefined, + ].filter(Boolean); + if (meta.length) console.log(ansis.dim(meta.join(" · "))); + if (file.ignored) { + console.log(ansis.yellow("This file is ignored on Codacy and excluded from analysis.")); + } + console.log(); + + const clonesCount = quality?.duplication ?? data.clones.length; + const duplication = + quality?.duplicatedLinesOfCode !== undefined && quality?.duplicatedLinesOfCode !== null + ? `${formatCount(clonesCount)} ${pluralize("clone", clonesCount)} · ` + + `${formatCount(quality.duplicatedLinesOfCode)} duplicated ${pluralize("line", quality.duplicatedLinesOfCode)}` + : `${formatCount(clonesCount)} ${pluralize("clone", clonesCount)}`; + const coverageCell = coverage + ? `${formatCoverageCell(coverage.coverage)} ${ansis.dim( + `(${coverage.coveredLines}/${coverage.coverableLines} lines)`, + )}` + : formatCoverageCell(undefined); + + const table = createTable({ + head: ["Grade", "Issues", "Complexity", "Duplication", "Coverage"], + }); + table.push([ + formatGrade(quality?.gradeLetter), + formatCountCell(quality?.totalIssues ?? data.issues.length), + formatCountCell(quality?.complexity), + duplication, + coverageCell, + ]); + console.log(table.toString()); +} + +/** + * The top Issues section. Without source it lists every issue; with source the + * issues are inline, so it only lists the ones that aren't (and is skipped when + * there are none). + */ +function printIssues(data: FileData): void { + const inlineMode = !!data.source && data.source.length > 0; + const issues = issuesNotInline(data.issues, data.source); + if (inlineMode) { + if (issues.length === 0) return; + printSection("Issues outside the shown lines", issues.length, "issue"); + } else { + printSection("Issues", issues.length, "issue"); + if (issues.length === 0) { + console.log(ansis.dim("No issues.")); + return; + } + } + for (const issue of issues) printIssueCard(issue); +} + +function formatBlock(from: number, to: number): string { + return from === to ? `${from}` : `${from}-${to}`; +} + +function printClones(clones: FileClone[], fileId: number, filePath: string): void { + printSection("Clones", clones.length, "clone"); + if (clones.length === 0) { + console.log(ansis.dim("No clones.")); + return; + } + const isHere = (o: FileClone["occurrences"][number]) => + o.fileId === fileId || o.path === filePath; + // Ordered by where each clone starts in this file, like the issues. + const firstLineHere = (c: FileClone) => + Math.min(...c.occurrences.filter(isHere).map((o) => o.fromLine), Infinity); + const sorted = [...clones].sort((a, b) => firstLineHere(a) - firstLineHere(b)); + const table = createTable({ head: ["Lines", "Also in"] }); + for (const clone of sorted) { + const here = clone.occurrences.filter(isHere); + const elsewhere = clone.occurrences.filter((o) => !isHere(o)); + // Same-file clones: every occurrence beyond the first is also "elsewhere". + const shownHere = here.slice(0, 1); + const others = [...here.slice(1), ...elsewhere]; + table.push([ + shownHere.map((o) => formatBlock(o.fromLine, o.toLine)).join(", ") || ansis.dim("-"), + others + .map((o) => `${sanitizeText(o.path)}:${formatBlock(o.fromLine, o.toLine)}`) + .join("\n") || ansis.dim("-"), + ]); + } + console.log(table.toString()); +} + +function printSource(data: FileData): void { + printSection("Source"); + if (!data.source) { + console.log( + ansis.dim( + `Source not available${data.sourceError ? ` (${sanitizeText(data.sourceError)})` : ""}.`, + ), + ); + return; + } + if (data.source.length === 0) { + console.log(ansis.dim("No lines in this range.")); + return; + } + if (data.coverage) { + console.log( + ansis.dim(`${ansis.green(COVERAGE_BAR)} covered ${ansis.red(COVERAGE_BAR)} not covered\n`), + ); + } + for (const line of renderSource(data.source, data.coverage, data.issues)) console.log(line); +} + +/** Issue fields in the JSON output — the same projection `issues` uses. */ +const ISSUE_JSON_FIELDS = [ + "patternInfo.id", + "patternInfo.severityLevel", + "patternInfo.category", + "patternInfo.subCategory", + "message", + "filePath", + "lineNumber", + "lineText", + "resultDataId", + "falsePositiveProbability", + "falsePositiveThreshold", + "falsePositiveReason", + "advisoryInformation.advisoryId", + "advisoryInformation.vulnerableFunctions", + "advisoryInformation.publishedAt", + "dependencyChains", + "fixedVersion", +]; + +/** + * The `--output json` projection: metadata, issues, clones and coverage — no + * source code. `--lines` and `--no-source` only affect the source section, so + * they don't change it. `coverage` is null when the file has no coverage data; + * `coverage.lines` lists the coverable lines only (`hits: 0` = not covered). + */ +export function fileJson(data: FileData): Record { + const { file, quality, coverage } = data.info; + return { + file: { + path: file.path, + fileId: file.fileId, + branchId: file.branchId, + language: file.language, + commitSha: file.commitSha, + ignored: file.ignored, + quality: quality ?? null, + }, + issues: data.issues.map((issue) => pickDeep(issue, ISSUE_JSON_FIELDS)), + clones: data.clones, + coverage: + coverage || data.coverage + ? { + coverage: coverage?.coverage ?? null, + coverableLines: coverage?.coverableLines ?? null, + coveredLines: coverage?.coveredLines ?? null, + lines: data.coverage + ? [...data.coverage] + .map(([line, hits]) => ({ line, hits })) + .sort((a, b) => a.line - b.line) + : [], + } + : null, + }; +} + +/** The human-readable view: summary, issues, clones, source. */ +function printFileView(data: FileData, options: FileOptions): void { + printSummary(data, options.branch); + printIssues(data); + printClones(data.clones, data.info.file.fileId, data.info.file.path); + if (options.source) printSource(data); +} + +export function registerFileCommand(program: Command) { + program + .command("file") + .alias("fl") + .description( + "Show a file's metrics, issues, clones, and source code with coverage", + ) + .argument( + "[provider]", + "git provider (gh, gl, or bb) — auto-detected from git remote if omitted", + ) + .argument("[organization]", "organization name") + .argument("[repository]", "repository name") + .argument( + "[path]", + "file path (relative to the current directory when the repository is auto-detected, otherwise to the repository root)", + ) + .option("-b, --branch ", "branch name (defaults to the main branch)") + .option( + "-l, --lines ", + "only show this range of the source: -, - or ", + ) + .option("-N, --no-source", "hide the source code section") + // Declared per command so `--repository-token` parses in the test harnesses. + .addOption(repositoryTokenOption()) + .addHelpText( + "after", + ` +Examples: + $ codacy file src/index.ts # auto-detect repo; path relative to cwd + $ codacy file gh my-org my-repo src/index.ts + $ codacy file src/index.ts --lines 40-120 + $ codacy file src/index.ts --no-source # summary, issues and clones only + $ codacy file src/index.ts --branch develop + $ codacy file src/index.ts --output json`, + ) + .action(async function ( + this: Command, + providerArg: string | undefined, + organizationArg: string | undefined, + repositoryArg: string | undefined, + pathArg: string | undefined, + options: FileOptions, + ) { + try { + resolveAccountAuth( + this, + "Codacy does not accept repository tokens on the file endpoints", + ); + const format = getOutputFormat(this); + // Validate --lines before any git call or request. + const range = options.lines ? parseLineRange(options.lines) : {}; + + const defined = [providerArg, organizationArg, repositoryArg, pathArg].filter( + (v) => v !== undefined, + ); + const autoDetected = defined.length === 1; + const { provider, organization, repository, trailingArgs } = resolveRepoArgs( + [providerArg, organizationArg, repositoryArg, pathArg], + 1, + "file", + ["path"], + ); + const filePath = resolveFilePath(trailingArgs[0], autoDetected); + if (!filePath) { + throw new Error("A file path is required."); + } + + const spinner = ora(`Loading ${filePath}...`).start(); + let data: FileData; + try { + const fileId = await resolveFileId( + provider, + organization, + repository, + options.branch, + filePath, + ); + // JSON carries no source code, so the content is never fetched for it. + const fetchSource = options.source && format !== "json"; + data = await fetchFileData( + { provider, organization, repository }, + filePath, + fileId, + fetchSource, + range, + ); + } finally { + spinner.stop(); + } + + if (format === "json") printJson(fileJson(data)); + else printFileView(data, options); + } catch (err) { + handleError(err); + } + }); +} diff --git a/src/commands/repository-token-refusals.test.ts b/src/commands/repository-token-refusals.test.ts index 6bb743f..f2c8818 100644 --- a/src/commands/repository-token-refusals.test.ts +++ b/src/commands/repository-token-refusals.test.ts @@ -13,6 +13,7 @@ import { Command } from "commander"; import { registerInfoCommand } from "./info"; import { registerRepositoriesCommand } from "./repositories"; import { registerLsCommand } from "./ls"; +import { registerFileCommand } from "./file"; import { registerDirectoriesCommand } from "./directories"; import { registerPullRequestCommand } from "./pull-request"; import { registerPullRequestsCommand } from "./pull-requests"; @@ -68,6 +69,12 @@ const ACCOUNT_ONLY_COMMANDS = [ argv: ["ls"], neverCalled: () => RepositoryService.listDirectories, }, + { + name: "file", + register: registerFileCommand, + argv: ["file", "src/index.ts"], + neverCalled: () => RepositoryService.listFiles, + }, { name: "directories", register: registerDirectoriesCommand, diff --git a/src/index.ts b/src/index.ts index 204e7d3..63c8c2c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -11,6 +11,7 @@ import { registerInfoCommand } from "./commands/info"; import { registerRepositoriesCommand } from "./commands/repositories"; import { registerRepositoryCommand } from "./commands/repository"; import { registerLsCommand } from "./commands/ls"; +import { registerFileCommand } from "./commands/file"; import { registerDirectoriesCommand } from "./commands/directories"; import { registerPullRequestCommand } from "./commands/pull-request"; import { registerPullRequestsCommand } from "./commands/pull-requests"; @@ -75,6 +76,7 @@ registerInfoCommand(program); registerRepositoriesCommand(program); registerRepositoryCommand(program); registerLsCommand(program); +registerFileCommand(program); registerDirectoriesCommand(program); registerPullRequestCommand(program); registerPullRequestsCommand(program);