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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/import-autoconfig-source.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@codacy/codacy-cloud-cli": minor
---

`tools --import --source autoconfig` records the imported ignore rules as added by auto-configuration. The import also skips `exclude` patterns that Codacy's default ignores already cover, instead of adding them as duplicate rules.
1 change: 1 addition & 0 deletions SPECS/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@

| Date | What was done |
|---|---|
| 2026-12-02 | **`tools --import --source <user\|autoconfig>`** records the imported ignore rules as added by auto-configuration (source `autoconfig`, reason "Auto-configuration") instead of the default `user` and "Imported from <file>". Refused without `--import`. **Patterns Codacy's default ignores already cover are no longer imported** (they would be stored as duplicate rules, since defaults aren't stored and the API can't report them as existing). The check is on what a pattern matches, mirroring foundation's `CodacyDefaultIgnores`, and the skipped patterns are counted in one dim line (25 new tests, 914 total) |

Check notice on line 52 in SPECS/README.md

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

SPECS/README.md#L52

Element: file
| 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 <from-to>` narrows the source, `-N, --no-source` hides it. The path is resolved to a `fileId` by listing the parent folder and matching exactly (not `search`, which matches substrings); with an auto-detected repository it is relative to the cwd (an absolute path is resolved against the git root, and a path outside the repository is refused). Source is fetched at the analysed `commitSha` so line numbers match issues and coverage. `--output json` carries no source code (the content endpoint isn't called): `{ file, issues, clones, coverage }`, with per-line `coverage.lines` `{ line, hits }`. Account token only — none of the file endpoints are whitelisted (29 new tests, 854 total) |
| 2026-11-09 | (OD-1049) `findings` can narrow to container scanning. **`--scan-types` accepts `ContainerSCA`**, the API value (as the `SearchSRMItems.scanTypes` example in the spec lists it), not `ContainerScanning` as the ticket named it; `ContainerScanning` and `Container` are accepted as aliases, normalized like the other scan types. The normalized list is now de-duplicated, since several aliases resolve to one value. **`-i, --image <name>` and `-t, --image-tag <tag>`** map to the body's `containerImage` (`ContainerImageFilter`), through `parseImageFilter`: values are trimmed, `--image name:tag` is split (a registry port stays in the name), and empty values, a tag without a name, a digest reference or two different tags are refused before any request. An empty `--image` would otherwise be dropped by a truthiness check and silently widen the result to the whole org. **Container findings show `image:tag` in place of the repository** on the `findings` card (also in the single-repository view) and on the `finding` header, through the shared `formatImageReference`; both commands' JSON gains `imageName`/`imageTag` (25 new tests, 823 total) |
Expand Down
16 changes: 12 additions & 4 deletions SPECS/commands/tools-and-patterns.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ Each group is a columnar table with columns:

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`.
first, and `--dry-run` prints the whole preview (tools and ignore rules) and exits without asking or writing, and
`--source <user|autoconfig>` says who the ignore rules are recorded as added by. Both are refused without `--import`.

### `exclude` becomes ignore rules

Expand All @@ -52,8 +52,16 @@ Code in `src/utils/import-ignore-rules.ts`.
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 <config file name>" and
source `user`.
- Rules go 100 per request, global rules first, in file order. By default they are recorded with source `user` and
reason "Imported from <config file name>". With `--source autoconfig` they get source `autoconfig` and reason
"Auto-configuration". The auto-configuration skill passes it wherever it runs, and the source says who picked the
paths, not where the command ran.
- Patterns that Codacy's default ignores already cover aren't sent, because defaults aren't stored and the API would
add them as duplicates. `init --auto` writes the defaults into `exclude` as ordinary globs (`node_modules/**`,
`**/dist/**`, `*.min.js`, escaped literal paths), so the check is on what a pattern matches, not on its text. A
pattern is covered when a literal folder segment ends with a default folder name, or its basename (`*S` or a literal
`S`) ends with a default file ending. The lists mirror foundation's `CodacyDefaultIgnores`. They're counted in one
dim line, "N already ignored by Codacy's defaults".
- 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.
Expand Down
37 changes: 35 additions & 2 deletions src/commands/tools.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -704,8 +704,8 @@ describe("tools command", () => {

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" },
{ path: "src/generated/**", type: "glob", tools: [], source: "user", reason: "Imported from test-import-exclude.json" },
{ path: "**/__tests__/**", type: "glob", tools: ["uuid-eslint"], source: "user", 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.");
Expand Down Expand Up @@ -733,6 +733,39 @@ describe("tools command", () => {
expect(output).toContain("Dry run, nothing was changed.");
});

it("--source autoconfig records the rules as added by auto-configuration", async () => {
const program = createProgram();
await program.parseAsync([
"node", "test", "tools", "gh", "test-org", "test-repo",
"--import", tmpConfigPath, "--source", "autoconfig", "-y",
]);

for (const call of addCalls()) {
expect(call[3].rules.every((r) => r.source === "autoconfig" && r.reason === "Auto-configuration")).toBe(true);
}
});

it("refuses --source without --import, and a source other than user or autoconfig", async () => {
vi.spyOn(process, "exit").mockImplementation(() => {
throw new Error("process.exit called");
});

await expect(
createProgram().parseAsync(["node", "test", "tools", "gh", "test-org", "test-repo", "--source", "autoconfig"]),
).rejects.toThrow("process.exit called");
expect(console.error).toHaveBeenCalledWith(expect.stringContaining("--source only applies to --import."));

const program = createProgram();
program.exitOverride();
program.commands[0].exitOverride();
await expect(
program.parseAsync([
"node", "test", "tools", "gh", "test-org", "test-repo", "--import", tmpConfigPath, "--source", "default",
]),
).rejects.toThrow("Use user or autoconfig.");
expect(RepositoryService.addRepositoryIgnoreRules).not.toHaveBeenCalled();
});

it("refuses --dry-run without --import", async () => {
vi.spyOn(process, "exit").mockImplementation(() => {
throw new Error("process.exit called");
Expand Down
48 changes: 35 additions & 13 deletions src/commands/tools.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as path from "path";
import { Command } from "commander";
import { Command, InvalidArgumentError } from "commander";
import ora from "ora";
import ansis from "ansis";
import pluralize from "pluralize";
Expand All @@ -14,6 +14,7 @@ import { resolveRepoArgs } from "../utils/resolve-repo-args";
import { createTable, getOutputFormat, pickDeep, printJson } from "../utils/output";
import { AnalysisService } from "../api/client/services/AnalysisService";
import { AnalysisTool } from "../api/client/models/AnalysisTool";
import { NewIgnoreRuleSource } from "../api/client/models/NewIgnoreRuleSource";
import {
readConfigFile,
fetchAllTools,
Expand All @@ -31,6 +32,15 @@ import {
} from "../utils/import-ignore-rules";
import { confirmAction } from "../utils/prompt";

const IGNORE_RULE_SOURCES: NewIgnoreRuleSource[] = ["user", "autoconfig"];

function parseIgnoreRuleSource(value: string): NewIgnoreRuleSource {
if (!IGNORE_RULE_SOURCES.includes(value as NewIgnoreRuleSource)) {
throw new InvalidArgumentError(`Use ${IGNORE_RULE_SOURCES.join(" or ")}.`);
}
return value as NewIgnoreRuleSource;
}

function configFileStatus(tool: AnalysisTool): string {
if (tool.settings.usesConfigurationFile) return "Applied";
if (tool.settings.hasConfigurationFile) return "Available";
Expand Down Expand Up @@ -135,6 +145,11 @@ export function registerToolsCommand(program: Command) {
.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")
.option(
"--source <source>",
"with --import: record the ignore rules as added by user or autoconfig (default: user)",
parseIgnoreRuleSource,
)
.addOption(repositoryTokenOption())
.addHelpText(
"after",
Expand All @@ -147,6 +162,7 @@ Examples:
$ 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 .codacy/auto.config.json --source autoconfig -y
$ codacy-cloud-cli tools gh my-org my-repo --import --force -y`,
)
.action(async function (
Expand All @@ -157,8 +173,8 @@ Examples:
) {
try {
const opts = this.opts();
if (opts.dryRun && opts.import === undefined) {
throw new Error("--dry-run only applies to --import.");
if (opts.import === undefined && (opts.dryRun || opts.source)) {
throw new Error(`${opts.dryRun ? "--dry-run" : "--source"} only applies to --import.`);
}
const auth = resolveAuth(this);
const { provider, organization, repository } = resolveRepoArgs(
Expand Down Expand Up @@ -217,23 +233,29 @@ Examples:
});

const ignorePlan = planIgnoreRules(config, allTools);
const rulesReason = `Imported from ${path.basename(resolvedPath)}`;
const source: NewIgnoreRuleSource = opts.source ?? "user";
const rulesOrigin = {
source,
reason:
source === "autoconfig"
? "Auto-configuration"
: `Imported from ${path.basename(resolvedPath)}`,
};
const printRules = (outcome: IgnoreRulesOutcome, dryRun: boolean) =>
printIgnoreRulesOutcome(ignorePlan.skipped, outcome, {
dryRun,
repository,
configPath,
plannedCount: ignorePlan.planned.length,
});
printIgnoreRulesOutcome(ignorePlan, outcome, { dryRun, repository, configPath });
let rulesPreview: IgnoreRulesOutcome | undefined;
if (ignorePlan.planned.length > 0 || ignorePlan.skipped.length > 0) {
if (
ignorePlan.planned.length > 0 ||
ignorePlan.skipped.length > 0 ||
ignorePlan.coveredByDefaults.length > 0
) {
const rulesSpinner = ora("Checking ignore rules...").start();
rulesPreview = await sendIgnoreRules(
provider,
organization,
repository,
ignorePlan.planned,
rulesReason,
rulesOrigin,
{ dryRun: true, spinner: rulesSpinner },
);
rulesSpinner.stop();
Expand Down Expand Up @@ -299,7 +321,7 @@ Examples:
organization,
repository,
ignorePlan.planned,
rulesReason,
rulesOrigin,
{ dryRun: false, spinner: rulesSpinner },
);
rulesSpinner.stop();
Expand Down
Loading
Loading