diff --git a/.changeset/import-exclude-as-ignore-rules.md b/.changeset/import-exclude-as-ignore-rules.md new file mode 100644 index 0000000..ca979a4 --- /dev/null +++ b/.changeset/import-exclude-as-ignore-rules.md @@ -0,0 +1,5 @@ +--- +"@codacy/codacy-cloud-cli": minor +--- + +`tools --import` now imports the config's `exclude` patterns, global and per tool, as ignore rules on Codacy, and lists every pattern it doesn't import with the reason. New `--dry-run` flag shows the whole import without changing anything. diff --git a/AGENTS.md b/AGENTS.md index 293303f..657d5ff 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -90,7 +90,7 @@ codacy-cloud-cli/ - **Proxy / TLS:** never hand-roll this. Outbound HTTP configuration is delegated to `configureProxy()` from `@codacy/tooling`, wrapped by `configureProxyFromEnv()` in `src/utils/proxy.ts` and called once at the top of `src/index.ts`. It installs a global `undici` dispatcher, so every `fetch` — the generated client and the CVE lookup alike — is covered without touching generated code. Keeping the implementation upstream is what keeps the environment contract identical to the Codacy Analysis CLI; a local reimplementation would drift. If proxy behavior needs to change, change it in `analysis-cli`'s `packages/tooling/src/proxy.ts` and bump the dependency here. - **Authentication — two token kinds.** Read `SPECS/repository-tokens.md` before touching auth or adding a command. - An **account token** (`api-token` header) reaches everything its owner can see. - - A **repository token** (`project-token` header) is scoped to one repository. It is accepted only on a fixed whitelist of 13 operations; everywhere else Codacy rejects it as if no token had been sent. + - A **repository token** (`project-token` header) is scoped to one repository. It is accepted only on a fixed whitelist of 19 operations; everywhere else Codacy rejects it as if no token had been sent. - Every command that calls the API resolves auth first, via `resolveAuth(this)` from `src/utils/auth.ts` (returns a `RemoteAuth` discriminated union), and declares `.addOption(repositoryTokenOption())` so `--repository-token` parses. - **New commands must decide their token scope**, using the whitelist in `SPECS/repository-tokens.md`: - account-only end to end → `resolveAccountAuth(this, "")` diff --git a/SPECS/README.md b/SPECS/README.md index efbfdd7..fbdf655 100644 --- a/SPECS/README.md +++ b/SPECS/README.md @@ -49,6 +49,7 @@ This is the single source of truth for all project tasks and specs. | Date | What was done | |---|---| +| 2026-12-02 | (OD-1268) **`tools --import` imports `exclude` as ignore rules.** The global `exclude` becomes rules for every tool and each tool's `exclude` rules for that tool, grouped so a pattern on several tools is one rule. Literal paths with a `/` go as `file` rules without their escapes, everything else as `glob`. Patterns of unknown tools and with a leading `/` are skipped by the CLI, everything else is judged by the API. The preview checks the rules with `dryRun` and lists every pattern not imported with its reason. New **`--dry-run`** (with `--import` only) prints the whole preview and writes nothing. A repository with a Codacy configuration file (409) gets one line and the tools are still imported. API client pinned to codacy-api 58.11.0, and the repository-token whitelist re-verified against it (19 operations, the 5 ignore rules ones added) (35 new tests, 889 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 | diff --git a/SPECS/commands/tools-and-patterns.md b/SPECS/commands/tools-and-patterns.md index efa4a49..7b5c190 100644 --- a/SPECS/commands/tools-and-patterns.md +++ b/SPECS/commands/tools-and-patterns.md @@ -34,6 +34,44 @@ Each group is a columnar table with columns: | Via Standard | Coding standard name(s), or `Overwritten by file` if config file is used, or `—` | | Notes | `Client-side tool` if applicable, otherwise `—` | +## Import (`--import [path]`) + +Applies a `codacy.config.json` (default `.codacy/codacy.config.json`) to the repository: its tools and patterns, and, +since OD-1268, its `exclude` patterns as ignore rules. `-y` skips the confirmation, `--force` unlinks coding standards +first, and `--dry-run` prints the whole preview (tools and ignore rules) and exits without asking or writing. `--dry-run` +is refused without `--import`. + +### `exclude` becomes ignore rules + +Code in `src/utils/import-ignore-rules.ts`. + +- The global `exclude` becomes rules for every tool. A tool's `exclude` becomes rules for that tool. The same pattern on + several tools becomes one rule with all of them, because the API refuses a second rule with the same path and type + whatever its tools. A tool pattern that is also global stays global only. +- A literal path with a `/` (no unescaped glob character, no leading `!`, `#` or `/`, no empty, `.` or `..` segment) is + sent as a `file` rule with its backslash escapes removed, so `pages/\[id\].tsx` becomes `pages/[id].tsx`, the way + stored single-file rules look. Everything else is sent as a `glob`, as written. A literal without `/`, like + `README.md`, stays a `glob`, because the Analysis CLI matches it in every folder. +- Rules go 100 per request, global rules first, in file order, with reason "Imported from " and + source `user`. +- The CLI skips two kinds of pattern itself. Patterns of a tool that isn't on Codacy, and patterns with a leading `/`, + which the API would strip (so `/vendor/**` would ignore the root `vendor` folder in the cloud) while the Analysis CLI + matches nothing for them. +- Everything else is judged by the API. The preview sends every batch with `dryRun=true` and prints how many rules + would be added, how many are already on Codacy, and a table of every pattern that won't be imported with its reason. + The import prints the same after the real request. +- A dry run checks each batch against the stored rules only, so with more than 100 patterns a limit can show up one + batch late. +- A 409 means the repository has a Codacy configuration file, which decides the ignores. The rules step stops with one + yellow line and the tools are still imported. +- A batch that fails otherwise counts as an import error, and the next batch is still sent. +- The import only adds. It never deletes a cloud rule the config doesn't list, and never changes the tools of an + existing rule (that comes back as already on Codacy). +- A config without `exclude` makes no ignore rules call and prints nothing about them. + +API: [`addRepositoryIgnoreRules`](https://api.codacy.com/api/api-docs#addrepositoryignorerules), with `dryRun` for the +preview. + ## Tests File: `src/commands/tools.test.ts` — 6 tests. diff --git a/SPECS/repository-tokens.md b/SPECS/repository-tokens.md index 7ff4844..273c770 100644 --- a/SPECS/repository-tokens.md +++ b/SPECS/repository-tokens.md @@ -46,7 +46,7 @@ depends on it). Both flag and env values are trimmed. > it. Source: Linear project *"Project token works in selected API v3 > (+expiration)"*. > -> **Last verified against API `57.4.17`** (2026-09-09). Since `57.4.x` the spec +> **Last verified against API `58.11.0`** (2026-12-02). Since `57.4.x` the spec > declares the `ProjectTokenAuth` security scheme (`project-token` header) on > each supported operation, so the whitelist is now machine-checkable: > @@ -64,7 +64,7 @@ depends on it). Both flag and env values are trimmed. > On `57.3.9` (the previously pinned build) the scheme was not declared > anywhere, which is why this table was maintained by hand. -Codacy accepts a repository token on **exactly** these 14 operations. Everywhere +Codacy accepts a repository token on **exactly** these 19 operations. Everywhere else it is rejected as if no token had been sent. | operationId | Method | Used by this CLI | @@ -78,11 +78,16 @@ else it is rejected as if no token had been sent. | `listRepositoryCommits` | GET | `repository`, `repository --reanalyze*` | | `configureTool` | PATCH | `tool`, `pattern`, `tools --import` | | `updateRepositoryToolPatterns` | PATCH | `patterns`, `tools --import` | +| `addRepositoryIgnoreRules` | POST | `tools --import` | | `reanalyzeCommitById` | POST | `repository --reanalyze*` | | `getRepositoryLanguages` | GET | — | | `getRepository` | GET | — | | `listIgnoredFiles` | GET | — | | `searchAiInventoryCategories` | POST | — | +| `listRepositoryIgnoreRules` | GET | — | +| `listRepositoryIgnoreRuleTools` | GET | — | +| `updateRepositoryIgnoreRule` | PATCH | — | +| `deleteRepositoryIgnoreRules` | POST | — | `ToolsService.listTools` / `listPatterns` / `getPattern` are declared `security: []` in the spec — unauthenticated, so they work with any token or diff --git a/package.json b/package.json index 36aa0d0..fe6a06e 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,7 @@ "prepublishOnly": "npm run update-api && npm run build", "start": "npx ts-node src/index.ts", "start:dist": "node dist/index.js", - "fetch-api": "curl https://artifacts.codacy.com/api/codacy-api/57.7.10/apiv3-bundled.yaml -o ./api-v3/api-swagger.yaml --create-dirs", + "fetch-api": "curl https://artifacts.codacy.com/api/codacy-api/58.11.0/apiv3-bundled.yaml -o ./api-v3/api-swagger.yaml --create-dirs", "generate-api": "rm -rf ./src/api/client && openapi --input ./api-v3/api-swagger.yaml --output ./src/api/client --useUnionTypes --indent 2 --client fetch", "update-api": "npm run fetch-api && npm run generate-api", "check-types": "tsc --noEmit" diff --git a/src/commands/tools.test.ts b/src/commands/tools.test.ts index e75aed6..5b1a3dc 100644 --- a/src/commands/tools.test.ts +++ b/src/commands/tools.test.ts @@ -5,12 +5,15 @@ import * as fs from "fs"; import { AnalysisService } from "../api/client/services/AnalysisService"; import { ToolsService } from "../api/client/services/ToolsService"; import { CodingStandardsService } from "../api/client/services/CodingStandardsService"; +import { RepositoryService } from "../api/client/services/RepositoryService"; +import { ApiError } from "../api/client/core/ApiError"; import * as importConfig from "../utils/import-config"; import * as prompt from "../utils/prompt"; vi.mock("../api/client/services/AnalysisService"); vi.mock("../api/client/services/CodingStandardsService"); vi.mock("../api/client/services/ToolsService"); +vi.mock("../api/client/services/RepositoryService"); vi.mock("../utils/credentials", () => ({ loadCredentials: vi.fn(() => null) })); vi.mock("../utils/git-remote", () => ({ detectRepoContext: vi.fn(() => ({ @@ -631,4 +634,210 @@ describe("tools command", () => { expect(output).not.toContain("Use --force to unlink them"); }); }); + + describe("--import with exclude patterns", () => { + const tmpConfigPath = "/tmp/test-import-exclude.json"; + const eslintTool = { + uuid: "uuid-eslint", + name: "ESLint", + shortName: "eslint", + prefix: "ESLint_", + languages: ["TypeScript"], + clientSide: false, + standalone: false, + configurable: true, + }; + + function writeConfig(exclude?: string[]) { + fs.writeFileSync( + tmpConfigPath, + JSON.stringify({ + version: 1, + exclude, + tools: [ + { + toolId: "ESLint", + patterns: [{ patternId: "no-unused-vars" }], + exclude: ["**/__tests__/**"], + }, + ], + }), + ); + } + + const addCalls = () => vi.mocked(RepositoryService.addRepositoryIgnoreRules).mock.calls; + + beforeEach(() => { + writeConfig(["src/generated/**", "/vendor/**"]); + vi.mocked(AnalysisService.updateRepositoryToolPatterns).mockResolvedValue(undefined as any); + vi.mocked(AnalysisService.configureTool).mockResolvedValue(undefined as any); + vi.mocked(RepositoryService.addRepositoryIgnoreRules).mockResolvedValue({ + successful: [], + failed: [], + }); + vi.spyOn(importConfig, "fetchAllTools").mockResolvedValue([eslintTool] as any); + vi.spyOn(importConfig, "getLocalSupportedToolIds").mockResolvedValue(["ESLint"]); + vi.mocked(AnalysisService.getRepositoryWithAnalysis).mockResolvedValue({ + data: { + repository: { + provider: "gh", + owner: "test-org", + name: "test-repo", + standards: [], + languages: [], + problems: [], + }, + }, + } as any); + }); + + afterEach(() => { + if (fs.existsSync(tmpConfigPath)) fs.unlinkSync(tmpConfigPath); + }); + + it("previews with dryRun, then adds the same rules with the import reason", async () => { + const program = createProgram(); + await program.parseAsync([ + "node", "test", "tools", "gh", "test-org", "test-repo", + "--import", tmpConfigPath, "-y", + ]); + + expect(addCalls().map((c) => c[4])).toEqual([true, false]); + expect(addCalls()[1][3].rules).toEqual([ + { path: "src/generated/**", type: "glob", tools: [], reason: "Imported from test-import-exclude.json" }, + { path: "**/__tests__/**", type: "glob", tools: ["uuid-eslint"], reason: "Imported from test-import-exclude.json" }, + ]); + const output = getAllOutput(); + expect(output).toContain("2 ignore rules would be added, 1 for every tool and 1 for specific tools."); + expect(output).toContain("2 ignore rules added, 1 for every tool and 1 for specific tools."); + expect(output).toContain("/vendor/**"); + expect(output).toContain("imported successfully"); + }); + + it("--dry-run shows the whole import, writes nothing and doesn't prompt", async () => { + const confirm = vi.spyOn(prompt, "confirmAction"); + + const program = createProgram(); + await program.parseAsync([ + "node", "test", "tools", "gh", "test-org", "test-repo", + "--import", tmpConfigPath, "--dry-run", + ]); + + expect(addCalls().map((c) => c[4])).toEqual([true]); + expect(AnalysisService.configureTool).not.toHaveBeenCalled(); + expect(AnalysisService.updateRepositoryToolPatterns).not.toHaveBeenCalled(); + expect(confirm).not.toHaveBeenCalled(); + const output = getAllOutput(); + expect(output).toContain("will be reconfigured: ESLint"); + expect(output).toContain("would be added"); + expect(output).toContain("Dry run, nothing was changed."); + }); + + it("refuses --dry-run without --import", async () => { + vi.spyOn(process, "exit").mockImplementation(() => { + throw new Error("process.exit called"); + }); + + const program = createProgram(); + await expect( + program.parseAsync(["node", "test", "tools", "gh", "test-org", "test-repo", "--dry-run"]), + ).rejects.toThrow("process.exit called"); + + expect(console.error).toHaveBeenCalledWith(expect.stringContaining("--dry-run only applies to --import.")); + expect(AnalysisService.listRepositoryTools).not.toHaveBeenCalled(); + }); + + it("lists the rules already on Codacy on a second run and adds nothing", async () => { + vi.mocked(RepositoryService.addRepositoryIgnoreRules).mockImplementation( + (_p, _o, _r, body) => + Promise.resolve({ + successful: [], + failed: body.rules.map((r) => ({ + path: r.path, + type: r.type, + error: "AlreadyExists", + message: "A rule for this path already exists.", + })), + }) as any, + ); + + const program = createProgram(); + await program.parseAsync([ + "node", "test", "tools", "gh", "test-org", "test-repo", + "--import", tmpConfigPath, "-y", + ]); + + const output = getAllOutput(); + expect(output).toContain("0 ignore rules added."); + expect(output).toContain("2 already on Codacy."); + expect(output).toContain("imported successfully"); + }); + + it("skips the rules with one line on a repository with a configuration file, and still imports the tools", async () => { + vi.mocked(RepositoryService.addRepositoryIgnoreRules).mockRejectedValue( + new ApiError( + { method: "POST", url: "/ignore-rules" } as any, + { url: "/ignore-rules", ok: false, status: 409, statusText: "Conflict", body: {} }, + "Conflict", + ), + ); + + const program = createProgram(); + await program.parseAsync([ + "node", "test", "tools", "gh", "test-org", "test-repo", + "--import", tmpConfigPath, "-y", + ]); + + expect(addCalls()).toHaveLength(1); + expect(AnalysisService.configureTool).toHaveBeenCalled(); + const output = getAllOutput(); + expect(output).toContain( + `test-repo has a Codacy configuration file, so Codacy reads ignores from it. The 2 exclude patterns in ${tmpConfigPath} won't be imported.`, + ); + expect(output).toContain("imported successfully"); + }); + + it("counts a failed batch as an import error", async () => { + vi.mocked(RepositoryService.addRepositoryIgnoreRules) + .mockResolvedValueOnce({ successful: [], failed: [] }) + .mockRejectedValueOnce(new Error("network down")); + + const program = createProgram(); + await program.parseAsync([ + "node", "test", "tools", "gh", "test-org", "test-repo", + "--import", tmpConfigPath, "-y", + ]); + + const output = getAllOutput(); + expect(output).toContain("Import completed with 1 error(s):"); + expect(output).toContain("2 ignore rules: network down"); + }); + + it("makes no ignore rules call for a config without exclude", async () => { + fs.writeFileSync( + tmpConfigPath, + JSON.stringify({ version: 1, tools: [{ toolId: "ESLint", patterns: [] }] }), + ); + + const program = createProgram(); + await program.parseAsync([ + "node", "test", "tools", "gh", "test-org", "test-repo", + "--import", tmpConfigPath, "-y", + ]); + + expect(RepositoryService.addRepositoryIgnoreRules).not.toHaveBeenCalled(); + expect(getAllOutput()).not.toContain("ignore rule"); + }); + + it("imports the rules with a repository token", async () => { + const program = createProgram(); + await program.parseAsync([ + "node", "test", "tools", "gh", "test-org", "test-repo", + "--import", tmpConfigPath, "-y", "--repository-token", "rt", + ]); + + expect(addCalls().map((c) => c[4])).toEqual([true, false]); + expect(getAllOutput()).toContain("2 ignore rules added"); + }); + }); }); diff --git a/src/commands/tools.ts b/src/commands/tools.ts index d679587..c101106 100644 --- a/src/commands/tools.ts +++ b/src/commands/tools.ts @@ -23,6 +23,12 @@ import { executeImport, ImportFailure, } from "../utils/import-config"; +import { + IgnoreRulesOutcome, + planIgnoreRules, + printIgnoreRulesOutcome, + sendIgnoreRules, +} from "../utils/import-ignore-rules"; import { confirmAction } from "../utils/prompt"; function configFileStatus(tool: AnalysisTool): string { @@ -128,6 +134,7 @@ export function registerToolsCommand(program: Command) { .option("--import [path]", "import tool configuration from a file (default: .codacy/codacy.config.json)") .option("-y, --skip-approval", "skip confirmation prompt during import") .option("--force", "unlink all coding standards before importing") + .option("--dry-run", "with --import: show what would change, change nothing") .addOption(repositoryTokenOption()) .addHelpText( "after", @@ -139,6 +146,7 @@ Examples: $ codacy-cloud-cli tools gh my-org my-repo --import $ codacy-cloud-cli tools gh my-org my-repo --import ./custom-config.json $ codacy-cloud-cli tools gh my-org my-repo --import -y + $ codacy-cloud-cli tools gh my-org my-repo --import --dry-run $ codacy-cloud-cli tools gh my-org my-repo --import --force -y`, ) .action(async function ( @@ -148,6 +156,10 @@ Examples: repositoryArg?: string, ) { try { + const opts = this.opts(); + if (opts.dryRun && opts.import === undefined) { + throw new Error("--dry-run only applies to --import."); + } const auth = resolveAuth(this); const { provider, organization, repository } = resolveRepoArgs( [providerArg, organizationArg, repositoryArg], @@ -155,7 +167,6 @@ Examples: "tools", [], ); - const opts = this.opts(); // ── Mode: import ──────────────────────────────────────────────── if (opts.import !== undefined) { @@ -205,6 +216,40 @@ Examples: canUnlinkStandards: auth.kind === "account-token", }); + const ignorePlan = planIgnoreRules(config, allTools); + const rulesReason = `Imported from ${path.basename(resolvedPath)}`; + const printRules = (outcome: IgnoreRulesOutcome, dryRun: boolean) => + printIgnoreRulesOutcome(ignorePlan.skipped, outcome, { + dryRun, + repository, + configPath, + plannedCount: ignorePlan.planned.length, + }); + let rulesPreview: IgnoreRulesOutcome | undefined; + if (ignorePlan.planned.length > 0 || ignorePlan.skipped.length > 0) { + const rulesSpinner = ora("Checking ignore rules...").start(); + rulesPreview = await sendIgnoreRules( + provider, + organization, + repository, + ignorePlan.planned, + rulesReason, + { dryRun: true, spinner: rulesSpinner }, + ); + rulesSpinner.stop(); + printRules(rulesPreview, true); + if (rulesPreview.errors.length > 0) { + console.log(ansis.yellow("⚠ Could not check every ignore rule with Codacy:")); + printImportErrors(rulesPreview.errors); + } + } + + if (opts.dryRun) { + console.log(); + console.log(ansis.dim("Dry run, nothing was changed.")); + return; + } + // Confirm if (!opts.skipApproval) { const confirmed = await confirmAction( @@ -246,17 +291,35 @@ Examples: ); } - if (result.failed.length === 0) { + let rulesErrors: ImportFailure[] = []; + if (ignorePlan.planned.length > 0 && !rulesPreview?.configurationFile) { + const rulesSpinner = ora("Adding ignore rules...").start(); + const rulesOutcome = await sendIgnoreRules( + provider, + organization, + repository, + ignorePlan.planned, + rulesReason, + { dryRun: false, spinner: rulesSpinner }, + ); + rulesSpinner.stop(); + printRules(rulesOutcome, false); + rulesErrors = rulesOutcome.errors; + console.log(); + } + + const failures = [...result.failed, ...rulesErrors]; + if (failures.length === 0) { console.log( `${ansis.green("✓")} Configuration imported successfully.`, ); } else { console.log( ansis.yellow( - `Import completed with ${result.failed.length} error(s):`, + `Import completed with ${failures.length} error(s):`, ), ); - printImportErrors(result.failed); + printImportErrors(failures); if (result.succeeded.length > 0) { console.log( ansis.green( diff --git a/src/utils/import-config.test.ts b/src/utils/import-config.test.ts index 631424a..5793bce 100644 --- a/src/utils/import-config.test.ts +++ b/src/utils/import-config.test.ts @@ -124,6 +124,17 @@ describe("readConfigFile", () => { expect(result.tools[0].patterns).toEqual([]); fs.unlinkSync(tmpPath); }); + + it.each([ + [{ version: 1, exclude: "dist/**", tools: [] }, "exclude must be an array of strings"], + [{ version: 1, exclude: [1], tools: [] }, "exclude must be an array of strings"], + [{ version: 1, tools: [{ toolId: "eslint", exclude: "dist/**" }] }, "tools[0].exclude must be an array of strings"], + ])("should refuse an exclude that isn't an array of strings (%j)", (content, message) => { + const tmpPath = "/tmp/test-bad-exclude.json"; + fs.writeFileSync(tmpPath, JSON.stringify(content)); + expect(() => readConfigFile(tmpPath)).toThrow(message); + fs.unlinkSync(tmpPath); + }); }); // ─── resolveToolId ──────────────────────────────────────────────────── diff --git a/src/utils/import-config.ts b/src/utils/import-config.ts index 5ba7655..bf14ad1 100644 --- a/src/utils/import-config.ts +++ b/src/utils/import-config.ts @@ -59,6 +59,9 @@ function extractErrorDetails(err: unknown): Pick + value === undefined || (Array.isArray(value) && value.every((v) => typeof v === "string")); + export function readConfigFile(filePath: string): CodacyConfig { if (!fs.existsSync(filePath)) { throw new Error(`Configuration file not found: ${filePath}`); @@ -69,6 +72,9 @@ export function readConfigFile(filePath: string): CodacyConfig { if (!config.version || !Array.isArray(config.tools)) { throw new Error("Invalid configuration file: missing 'version' or 'tools' fields."); } + if (!isOptionalStringArray(config.exclude)) { + throw new Error("Invalid configuration file: exclude must be an array of strings."); + } for (let i = 0; i < config.tools.length; i++) { const tool = config.tools[i]; if (!tool || typeof tool !== "object") { @@ -80,6 +86,9 @@ export function readConfigFile(filePath: string): CodacyConfig { if (!Array.isArray(tool.patterns)) { tool.patterns = []; } + if (!isOptionalStringArray(tool.exclude)) { + throw new Error(`Invalid configuration file: tools[${i}].exclude must be an array of strings.`); + } } return config; } catch (err) { @@ -348,7 +357,7 @@ export function printImportPreview( } } -function chunk(arr: T[], size: number): T[][] { +export function chunk(arr: T[], size: number): T[][] { const chunks: T[][] = []; for (let i = 0; i < arr.length; i += size) { chunks.push(arr.slice(i, i + size)); diff --git a/src/utils/import-ignore-rules.test.ts b/src/utils/import-ignore-rules.test.ts new file mode 100644 index 0000000..3316edb --- /dev/null +++ b/src/utils/import-ignore-rules.test.ts @@ -0,0 +1,255 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { + planIgnoreRules, + printIgnoreRulesOutcome, + sendIgnoreRules, + toRule, + PlannedRule, +} from "./import-ignore-rules"; +import { RepositoryService } from "../api/client/services/RepositoryService"; +import { ApiError } from "../api/client/core/ApiError"; +import { Tool } from "../api/client/models/Tool"; +import { CodacyConfig, CodacyToolConfig } from "../types/codacy-config"; + +vi.mock("../api/client/services/RepositoryService"); + +const eslint = { uuid: "uuid-eslint", name: "ESLint", shortName: "eslint", prefix: "ESLint_" } as Tool; +const pylint = { uuid: "uuid-pylint", name: "Pylint", shortName: "pylint", prefix: "PyLintPython3_" } as Tool; +const allTools = [eslint, pylint]; + +function config(exclude: string[] | undefined, tools: Partial[] = []): CodacyConfig { + return { + version: 1, + exclude, + tools: tools.map((t) => ({ patterns: [], ...t }) as CodacyToolConfig), + } as CodacyConfig; +} + +function apiError(status: number, body: unknown = {}) { + return new ApiError( + { method: "POST", url: "/ignore-rules" } as any, + { url: "/ignore-rules", ok: false, status, statusText: "", body }, + "Request failed", + ); +} + +function rule(path: string, tools: string[] = []): PlannedRule { + return { path, type: "glob", tools, toolNames: [], source: path }; +} + +describe("toRule", () => { + it.each([ + ["src/a.ts", "src/a.ts"], + ["pages/\\[id\\].tsx", "pages/[id].tsx"], + ])("sends the literal path %s as a file rule", (pattern, path) => { + expect(toRule(pattern)).toEqual({ path, type: "file" }); + }); + + it.each([ + "README.md", + "*.min.js", + "src/**", + "docs/", + "./src/a.ts", + "+(a|b).js", + "a/../b.ts", + "!src/a.ts", + "/src/a.ts", + ])("sends %s as a glob, as written", (pattern) => { + expect(toRule(pattern)).toEqual({ path: pattern, type: "glob" }); + }); +}); + +describe("planIgnoreRules", () => { + it("plans one rule for every tool per global pattern, in file order", () => { + const plan = planIgnoreRules(config(["src/generated/**", "src/a.ts"]), allTools); + expect(plan.planned).toEqual([ + { path: "src/generated/**", type: "glob", tools: [], toolNames: [], source: "src/generated/**" }, + { path: "src/a.ts", type: "file", tools: [], toolNames: [], source: "src/a.ts" }, + ]); + expect(plan.skipped).toEqual([]); + }); + + it("groups a pattern on several tools into one rule, after the global rules", () => { + const plan = planIgnoreRules( + config(["dist/**"], [ + { toolId: "ESLint", exclude: ["**/__tests__/**"] }, + { toolId: "pylint", exclude: ["**/__tests__/**"] }, + ]), + allTools, + ); + expect(plan.planned.map((r) => [r.path, r.tools])).toEqual([ + ["dist/**", []], + ["**/__tests__/**", ["uuid-eslint", "uuid-pylint"]], + ]); + expect(plan.planned[1].toolNames).toEqual(["ESLint", "Pylint"]); + }); + + it("keeps only the global rule for a pattern that is also global", () => { + const plan = planIgnoreRules( + config(["dist/**"], [{ toolId: "ESLint", exclude: ["dist/**"] }]), + allTools, + ); + expect(plan.planned).toHaveLength(1); + expect(plan.planned[0].tools).toEqual([]); + }); + + it("skips the patterns of a tool that isn't on Codacy", () => { + const plan = planIgnoreRules(config(undefined, [{ toolId: "nope", exclude: ["a/**"] }]), allTools); + expect(plan.planned).toEqual([]); + expect(plan.skipped).toEqual([ + { pattern: "a/**", toolNames: ["nope"], error: "UnknownTool", message: "Tool nope isn't on Codacy." }, + ]); + }); + + it("skips a leading / globally and per tool, and suggests the pattern without it", () => { + const plan = planIgnoreRules( + config(["/vendor/**"], [{ toolId: "ESLint", exclude: ["/build/**"] }]), + allTools, + ); + expect(plan.planned).toEqual([]); + expect(plan.skipped).toEqual([ + { + pattern: "/vendor/**", + toolNames: [], + error: "LeadingSlash", + message: "A leading / matches nothing in the Codacy Analysis CLI. Write vendor/** instead.", + }, + { + pattern: "/build/**", + toolNames: ["ESLint"], + error: "LeadingSlash", + message: "A leading / matches nothing in the Codacy Analysis CLI. Write build/** instead.", + }, + ]); + }); + + it("plans nothing for a config without exclude", () => { + expect(planIgnoreRules(config(undefined, [{ toolId: "ESLint" }]), allTools)).toEqual({ + planned: [], + skipped: [], + }); + }); +}); + +describe("sendIgnoreRules", () => { + beforeEach(() => { + vi.mocked(RepositoryService.addRepositoryIgnoreRules).mockReset(); + }); + + it("sends 250 rules in batches of 100, 100 and 50, in order, with the reason", async () => { + vi.mocked(RepositoryService.addRepositoryIgnoreRules).mockResolvedValue({ successful: [], failed: [] }); + const planned = Array.from({ length: 250 }, (_, i) => rule(`src/${i}/**`)); + + const outcome = await sendIgnoreRules("gh", "org", "repo", planned, "Imported from codacy.config.json", { + dryRun: true, + }); + + const calls = vi.mocked(RepositoryService.addRepositoryIgnoreRules).mock.calls; + expect(calls.map((c) => c[3].rules.length)).toEqual([100, 100, 50]); + expect(calls[1][3].rules[0]).toEqual({ + path: "src/100/**", + type: "glob", + tools: [], + reason: "Imported from codacy.config.json", + }); + expect(calls.every((c) => c[4] === true)).toBe(true); + expect(outcome.added).toHaveLength(250); + }); + + it("maps refused rules back to their patterns, with AlreadyExists apart", async () => { + vi.mocked(RepositoryService.addRepositoryIgnoreRules).mockResolvedValue({ + successful: [], + failed: [ + { path: "docs/", type: "glob", error: "InvalidPattern", message: "A trailing / matches nothing." }, + { path: "src/a.ts", type: "file", error: "AlreadyExists", message: "A rule for this path already exists." }, + ], + }); + const planned: PlannedRule[] = [ + rule("dist/**"), + { ...rule("docs/"), toolNames: ["ESLint"], tools: ["uuid-eslint"] }, + { path: "src/a.ts", type: "file", tools: [], toolNames: [], source: "src/a.ts" }, + ]; + + const outcome = await sendIgnoreRules("gh", "org", "repo", planned, "r", { dryRun: false }); + + expect(outcome.added.map((r) => r.path)).toEqual(["dist/**"]); + expect(outcome.alreadyExists.map((r) => r.path)).toEqual(["src/a.ts"]); + expect(outcome.refused).toEqual([ + { pattern: "docs/", toolNames: ["ESLint"], error: "InvalidPattern", message: "A trailing / matches nothing." }, + ]); + }); + + it("marks a batch that fails as an error and still sends the next one", async () => { + vi.mocked(RepositoryService.addRepositoryIgnoreRules) + .mockRejectedValueOnce(apiError(500, { message: "boom" })) + .mockResolvedValueOnce({ successful: [], failed: [] }); + const planned = Array.from({ length: 150 }, (_, i) => rule(`src/${i}/**`)); + + const outcome = await sendIgnoreRules("gh", "org", "repo", planned, "r", { dryRun: false }); + + expect(RepositoryService.addRepositoryIgnoreRules).toHaveBeenCalledTimes(2); + expect(outcome.errors).toEqual([ + expect.objectContaining({ tool: "100 ignore rules", error: "boom", status: 500 }), + ]); + expect(outcome.added).toHaveLength(50); + }); + + it("stops at a 409 and sends no other batch", async () => { + vi.mocked(RepositoryService.addRepositoryIgnoreRules).mockRejectedValue(apiError(409)); + const planned = Array.from({ length: 150 }, (_, i) => rule(`src/${i}/**`)); + + const outcome = await sendIgnoreRules("gh", "org", "repo", planned, "r", { dryRun: true }); + + expect(RepositoryService.addRepositoryIgnoreRules).toHaveBeenCalledTimes(1); + expect(outcome.configurationFile).toBe(true); + expect(outcome.errors).toEqual([]); + }); +}); + +describe("printIgnoreRulesOutcome", () => { + const output = () => + (console.log as ReturnType).mock.calls.map((c) => String(c[0] ?? "")).join("\n"); + const empty = { added: [], alreadyExists: [], refused: [], errors: [], configurationFile: false }; + const options = { dryRun: true, repository: "repo", configPath: ".codacy/codacy.config.json", plannedCount: 3 }; + + beforeEach(() => { + vi.spyOn(console, "log").mockImplementation(() => {}); + }); + + it("prints the summary, the rules already on Codacy and the patterns not imported", () => { + printIgnoreRulesOutcome( + [{ pattern: "/vendor/**", toolNames: [], error: "LeadingSlash", message: "Write vendor/** instead." }], + { ...empty, added: [rule("a/**"), rule("b/**", ["uuid-eslint"])], alreadyExists: [rule("c/**")] }, + options, + ); + const text = output(); + expect(text).toContain("2 ignore rules would be added, 1 for every tool and 1 for specific tools."); + expect(text).toContain("1 already on Codacy."); + expect(text).toContain("1 exclude pattern won't be imported:"); + expect(text).toContain("/vendor/**"); + expect(text).toContain("Write vendor/** instead."); + }); + + it("prints one line for a repository with a configuration file", () => { + printIgnoreRulesOutcome([], { ...empty, configurationFile: true }, options); + expect(output()).toContain( + "repo has a Codacy configuration file, so Codacy reads ignores from it. The 3 exclude patterns in .codacy/codacy.config.json won't be imported.", + ); + }); + + it("sanitizes patterns and messages", () => { + printIgnoreRulesOutcome( + [], + { + ...empty, + refused: [{ pattern: "a\x1b[2J", toolNames: [], error: "InvalidPattern", message: "bad\x1b]52;c;x\x07" }], + }, + options, + ); + const text = output(); + expect(text).not.toContain("\x1b[2J"); + expect(text).not.toContain("\x1b]52"); + expect(text).toContain("a^[[2J"); + }); +}); diff --git a/src/utils/import-ignore-rules.ts b/src/utils/import-ignore-rules.ts new file mode 100644 index 0000000..839b622 --- /dev/null +++ b/src/utils/import-ignore-rules.ts @@ -0,0 +1,250 @@ +import ansis from "ansis"; +import pluralize from "pluralize"; +import type ora from "ora"; +import { CodacyConfig } from "../types/codacy-config"; +import { Tool } from "../api/client/models/Tool"; +import { IgnoreRuleType } from "../api/client/models/IgnoreRuleType"; +import { ApiError } from "../api/client/core/ApiError"; +import { RepositoryService } from "../api/client/services/RepositoryService"; +import { chunk, ImportFailure, resolveToolId } from "./import-config"; +import { errorReason } from "./error"; +import { createTable } from "./output"; +import { sanitizeText } from "./sanitize"; + +export const MAX_RULES_PER_REQUEST = 100; + +export interface PlannedRule { + path: string; + type: IgnoreRuleType; + tools: string[]; + toolNames: string[]; + source: string; +} + +export interface SkippedRule { + pattern: string; + toolNames: string[]; + error: "InvalidPattern" | "LimitReached" | "UnknownTool" | "LeadingSlash"; + message: string; +} + +export interface IgnoreRulesPlan { + planned: PlannedRule[]; + skipped: SkippedRule[]; +} + +export interface IgnoreRulesOutcome { + added: PlannedRule[]; + alreadyExists: PlannedRule[]; + refused: SkippedRule[]; + errors: ImportFailure[]; + configurationFile: boolean; +} + +const GLOB_SPECIAL = /[*?[\]{}()]/; + +export function toRule(pattern: string): { path: string; type: IgnoreRuleType } { + const asGlob = { path: pattern, type: "glob" as const }; + if (/^[!#/]/.test(pattern)) return asGlob; + let literal = ""; + for (let i = 0; i < pattern.length; i++) { + const c = pattern[i]; + if (c === "\\" && i + 1 < pattern.length) { + literal += pattern[++i]; + continue; + } + if (GLOB_SPECIAL.test(c)) return asGlob; + literal += c; + } + const segments = literal.split("/"); + const isPath = + segments.length > 1 && segments.every((s) => s !== "" && s !== "." && s !== ".."); + return isPath ? { path: literal, type: "file" } : asGlob; +} + +const ruleKey = (rule: { path: string; type: IgnoreRuleType }) => `${rule.type}\0${rule.path}`; + +function skipMessage(skip: Omit): string { + if (skip.error === "LeadingSlash") { + return `A leading / matches nothing in the Codacy Analysis CLI. Write ${skip.pattern.replace(/^\/+/, "")} instead.`; + } + return skip.toolNames.length === 1 + ? `Tool ${skip.toolNames[0]} isn't on Codacy.` + : `Tools ${skip.toolNames.join(", ")} aren't on Codacy.`; +} + +export function planIgnoreRules(config: CodacyConfig, allTools: Tool[]): IgnoreRulesPlan { + const planned = new Map(); + const skipped = new Map>(); + + const skip = (pattern: string, error: "UnknownTool" | "LeadingSlash", toolName?: string) => { + const key = `${error}\0${pattern}`; + const existing = skipped.get(key); + if (!existing) { + skipped.set(key, { pattern, error, toolNames: toolName ? [toolName] : [] }); + } else if (toolName && !existing.toolNames.includes(toolName)) { + existing.toolNames.push(toolName); + } + }; + + const globalPatterns = new Set(config.exclude ?? []); + for (const pattern of globalPatterns) { + if (pattern.startsWith("/")) { + skip(pattern, "LeadingSlash"); + continue; + } + const rule = toRule(pattern); + if (!planned.has(ruleKey(rule))) { + planned.set(ruleKey(rule), { ...rule, tools: [], toolNames: [], source: pattern }); + } + } + const globalKeys = new Set(planned.keys()); + + for (const configTool of config.tools) { + const patterns = configTool.exclude ?? []; + if (patterns.length === 0) continue; + const tool = resolveToolId(configTool.toolId, allTools); + for (const pattern of patterns) { + if (globalPatterns.has(pattern)) continue; + if (!tool) { + skip(pattern, "UnknownTool", configTool.toolId); + continue; + } + if (pattern.startsWith("/")) { + skip(pattern, "LeadingSlash", tool.name); + continue; + } + const rule = toRule(pattern); + const key = ruleKey(rule); + if (globalKeys.has(key)) continue; + const existing = planned.get(key); + if (!existing) { + planned.set(key, { ...rule, tools: [tool.uuid], toolNames: [tool.name], source: pattern }); + } else if (!existing.tools.includes(tool.uuid)) { + existing.tools.push(tool.uuid); + existing.toolNames.push(tool.name); + } + } + } + + return { + planned: [...planned.values()], + skipped: [...skipped.values()].map((s) => ({ ...s, message: skipMessage(s) })), + }; +} + +export async function sendIgnoreRules( + provider: string, + organization: string, + repository: string, + planned: PlannedRule[], + reason: string, + options: { dryRun: boolean; spinner?: ReturnType }, +): Promise { + const outcome: IgnoreRulesOutcome = { + added: [], + alreadyExists: [], + refused: [], + errors: [], + configurationFile: false, + }; + const batches = chunk(planned, MAX_RULES_PER_REQUEST); + for (const [index, batch] of batches.entries()) { + if (options.spinner) { + const verb = options.dryRun ? "Checking" : "Adding"; + options.spinner.text = + batches.length > 1 + ? `${verb} ignore rules (batch ${index + 1} of ${batches.length})...` + : `${verb} ignore rules...`; + } + try { + const response = await RepositoryService.addRepositoryIgnoreRules( + provider, + organization, + repository, + { rules: batch.map((r) => ({ path: r.path, type: r.type, tools: r.tools, reason })) }, + options.dryRun, + ); + // Every rule comes back in `successful` or `failed`, with its path as sent. + const failed = new Map(response.failed.map((f) => [ruleKey(f), f])); + for (const rule of batch) { + const refusal = failed.get(ruleKey(rule)); + if (!refusal) { + outcome.added.push(rule); + } else if (refusal.error === "AlreadyExists") { + outcome.alreadyExists.push(rule); + } else { + outcome.refused.push({ + pattern: rule.source, + toolNames: rule.toolNames, + error: refusal.error, + message: refusal.message, + }); + } + } + } catch (err) { + if (err instanceof ApiError && err.status === 409) { + outcome.configurationFile = true; + break; + } + outcome.errors.push({ + tool: `${batch.length} ignore ${pluralize("rule", batch.length)}`, + error: errorReason(err), + status: err instanceof ApiError ? err.status : undefined, + details: [], + }); + } + } + return outcome; +} + +export function printIgnoreRulesOutcome( + skipped: SkippedRule[], + outcome: IgnoreRulesOutcome, + options: { dryRun: boolean; repository: string; configPath: string; plannedCount: number }, +): void { + console.log(); + if (outcome.configurationFile) { + console.log( + ansis.yellow( + `⚠ ${sanitizeText(options.repository)} has a Codacy configuration file, so Codacy reads ignores from it. ` + + `The ${options.plannedCount} exclude ${pluralize("pattern", options.plannedCount)} in ${sanitizeText(options.configPath)} ` + + `${options.dryRun ? "won't be" : "were not"} imported.`, + ), + ); + return; + } + + const added = outcome.added.length; + const forEveryTool = outcome.added.filter((r) => r.tools.length === 0).length; + const forSomeTools = added - forEveryTool; + const split = + forEveryTool > 0 && forSomeTools > 0 + ? `, ${forEveryTool} for every tool and ${forSomeTools} for specific tools` + : forSomeTools > 0 + ? " for specific tools" + : added > 0 + ? " for every tool" + : ""; + const summary = `${added} ignore ${pluralize("rule", added)} ${options.dryRun ? "would be added" : "added"}${split}.`; + console.log(!options.dryRun && added > 0 ? `${ansis.green("✓")} ${summary}` : summary); + + if (outcome.alreadyExists.length > 0) { + console.log(ansis.dim(`${outcome.alreadyExists.length} already on Codacy.`)); + } + + const notImported = [...skipped, ...outcome.refused]; + if (notImported.length === 0) return; + console.log( + `${notImported.length} exclude ${pluralize("pattern", notImported.length)} ${options.dryRun ? "won't be" : "weren't"} imported:`, + ); + const table = createTable({ head: ["Pattern", "Tools", "Reason"] }); + for (const s of notImported) { + table.push([ + sanitizeText(s.pattern), + s.toolNames.length === 0 ? "All" : s.toolNames.map((n) => sanitizeText(n)).join(", "), + sanitizeText(s.message), + ]); + } + console.log(table.toString()); +}