diff --git a/.changeset/import-autoconfig-source.md b/.changeset/import-autoconfig-source.md new file mode 100644 index 0000000..5cc4931 --- /dev/null +++ b/.changeset/import-autoconfig-source.md @@ -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. diff --git a/SPECS/README.md b/SPECS/README.md index fbdf655..cbd533b 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 | **`tools --import --source `** records the imported ignore rules as added by auto-configuration (source `autoconfig`, reason "Auto-configuration") instead of the default `user` and "Imported from ". 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) | | 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) | diff --git a/SPECS/commands/tools-and-patterns.md b/SPECS/commands/tools-and-patterns.md index 7b5c190..839009a 100644 --- a/SPECS/commands/tools-and-patterns.md +++ b/SPECS/commands/tools-and-patterns.md @@ -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 ` says who the ignore rules are recorded as added by. Both are refused without `--import`. ### `exclude` becomes ignore rules @@ -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 " 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 ". 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. diff --git a/src/commands/tools.test.ts b/src/commands/tools.test.ts index 5b1a3dc..4a6e799 100644 --- a/src/commands/tools.test.ts +++ b/src/commands/tools.test.ts @@ -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."); @@ -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"); diff --git a/src/commands/tools.ts b/src/commands/tools.ts index c101106..d12280c 100644 --- a/src/commands/tools.ts +++ b/src/commands/tools.ts @@ -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"; @@ -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, @@ -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"; @@ -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 ", + "with --import: record the ignore rules as added by user or autoconfig (default: user)", + parseIgnoreRuleSource, + ) .addOption(repositoryTokenOption()) .addHelpText( "after", @@ -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 ( @@ -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( @@ -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(); @@ -299,7 +321,7 @@ Examples: organization, repository, ignorePlan.planned, - rulesReason, + rulesOrigin, { dryRun: false, spinner: rulesSpinner }, ); rulesSpinner.stop(); diff --git a/src/utils/import-ignore-rules.test.ts b/src/utils/import-ignore-rules.test.ts index 3316edb..5ff416d 100644 --- a/src/utils/import-ignore-rules.test.ts +++ b/src/utils/import-ignore-rules.test.ts @@ -1,9 +1,11 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; import { + coveredByDefaults, planIgnoreRules, printIgnoreRulesOutcome, sendIgnoreRules, toRule, + IgnoreRulesPlan, PlannedRule, } from "./import-ignore-rules"; import { RepositoryService } from "../api/client/services/RepositoryService"; @@ -72,14 +74,14 @@ describe("planIgnoreRules", () => { it("groups a pattern on several tools into one rule, after the global rules", () => { const plan = planIgnoreRules( - config(["dist/**"], [ + config(["out/**"], [ { toolId: "ESLint", exclude: ["**/__tests__/**"] }, { toolId: "pylint", exclude: ["**/__tests__/**"] }, ]), allTools, ); expect(plan.planned.map((r) => [r.path, r.tools])).toEqual([ - ["dist/**", []], + ["out/**", []], ["**/__tests__/**", ["uuid-eslint", "uuid-pylint"]], ]); expect(plan.planned[1].toolNames).toEqual(["ESLint", "Pylint"]); @@ -87,7 +89,7 @@ describe("planIgnoreRules", () => { it("keeps only the global rule for a pattern that is also global", () => { const plan = planIgnoreRules( - config(["dist/**"], [{ toolId: "ESLint", exclude: ["dist/**"] }]), + config(["out/**"], [{ toolId: "ESLint", exclude: ["out/**"] }]), allTools, ); expect(plan.planned).toHaveLength(1); @@ -128,10 +130,53 @@ describe("planIgnoreRules", () => { expect(planIgnoreRules(config(undefined, [{ toolId: "ESLint" }]), allTools)).toEqual({ planned: [], skipped: [], + coveredByDefaults: [], }); }); }); +describe("coveredByDefaults", () => { + it.each([ + "node_modules/**", + "packages/app/node_modules/**", + "**/dist/**", + "src/vendor/**/*.ts", + "third_party/**", + "*.min.js", + "**/*-min.css", + "jquery.js", + "static/js/jquery.js", + "*.Designer.cs", + "libs/a\\[1\\].js", + ])("%s is already ignored by Codacy's defaults", (pattern) => { + expect(coveredByDefaults(pattern)).toBe(true); + }); + + it.each([ + "src/generated/**", + "Pods/**", + "**/__tests__/**", + "*.js", + "*.min.*", + "dist", + "**", + "!node_modules/**", + "{dist,out}/**", + "src/app.js", + ])("%s is not", (pattern) => { + expect(coveredByDefaults(pattern)).toBe(false); + }); + + it("leaves the patterns the defaults cover out of the plan, globally and per tool", () => { + const plan = planIgnoreRules( + config(["node_modules/**", "src/generated/**"], [{ toolId: "ESLint", exclude: ["*.min.js", "**/__tests__/**"] }]), + allTools, + ); + expect(plan.planned.map((r) => r.path)).toEqual(["src/generated/**", "**/__tests__/**"]); + expect(plan.coveredByDefaults).toEqual(["node_modules/**", "*.min.js"]); + }); +}); + describe("sendIgnoreRules", () => { beforeEach(() => { vi.mocked(RepositoryService.addRepositoryIgnoreRules).mockReset(); @@ -141,9 +186,14 @@ describe("sendIgnoreRules", () => { 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 outcome = await sendIgnoreRules( + "gh", + "org", + "repo", + planned, + { source: "user", reason: "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]); @@ -151,12 +201,31 @@ describe("sendIgnoreRules", () => { path: "src/100/**", type: "glob", tools: [], + source: "user", reason: "Imported from codacy.config.json", }); expect(calls.every((c) => c[4] === true)).toBe(true); expect(outcome.added).toHaveLength(250); }); + it("sends the source and reason it is given on every rule", async () => { + vi.mocked(RepositoryService.addRepositoryIgnoreRules).mockResolvedValue({ successful: [], failed: [] }); + + await sendIgnoreRules( + "gh", + "org", + "repo", + [rule("out/**")], + { source: "autoconfig", reason: "Auto-configuration" }, + { dryRun: false }, + ); + + expect(vi.mocked(RepositoryService.addRepositoryIgnoreRules).mock.calls[0][3].rules[0]).toMatchObject({ + source: "autoconfig", + reason: "Auto-configuration", + }); + }); + it("maps refused rules back to their patterns, with AlreadyExists apart", async () => { vi.mocked(RepositoryService.addRepositoryIgnoreRules).mockResolvedValue({ successful: [], @@ -171,7 +240,7 @@ describe("sendIgnoreRules", () => { { path: "src/a.ts", type: "file", tools: [], toolNames: [], source: "src/a.ts" }, ]; - const outcome = await sendIgnoreRules("gh", "org", "repo", planned, "r", { dryRun: false }); + const outcome = await sendIgnoreRules("gh", "org", "repo", planned, { source: "user", reason: "r" }, { dryRun: false }); expect(outcome.added.map((r) => r.path)).toEqual(["dist/**"]); expect(outcome.alreadyExists.map((r) => r.path)).toEqual(["src/a.ts"]); @@ -186,7 +255,7 @@ describe("sendIgnoreRules", () => { .mockResolvedValueOnce({ successful: [], failed: [] }); const planned = Array.from({ length: 150 }, (_, i) => rule(`src/${i}/**`)); - const outcome = await sendIgnoreRules("gh", "org", "repo", planned, "r", { dryRun: false }); + const outcome = await sendIgnoreRules("gh", "org", "repo", planned, { source: "user", reason: "r" }, { dryRun: false }); expect(RepositoryService.addRepositoryIgnoreRules).toHaveBeenCalledTimes(2); expect(outcome.errors).toEqual([ @@ -199,7 +268,7 @@ describe("sendIgnoreRules", () => { 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 }); + const outcome = await sendIgnoreRules("gh", "org", "repo", planned, { source: "user", reason: "r" }, { dryRun: true }); expect(RepositoryService.addRepositoryIgnoreRules).toHaveBeenCalledTimes(1); expect(outcome.configurationFile).toBe(true); @@ -211,7 +280,13 @@ 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 }; + const options = { dryRun: true, repository: "repo", configPath: ".codacy/codacy.config.json" }; + const plan = (overrides: Partial = {}): IgnoreRulesPlan => ({ + planned: [], + skipped: [], + coveredByDefaults: [], + ...overrides, + }); beforeEach(() => { vi.spyOn(console, "log").mockImplementation(() => {}); @@ -219,20 +294,28 @@ describe("printIgnoreRulesOutcome", () => { it("prints the summary, the rules already on Codacy and the patterns not imported", () => { printIgnoreRulesOutcome( - [{ pattern: "/vendor/**", toolNames: [], error: "LeadingSlash", message: "Write vendor/** instead." }], + plan({ + skipped: [{ pattern: "/vendor/**", toolNames: [], error: "LeadingSlash", message: "Write vendor/** instead." }], + coveredByDefaults: ["node_modules/**", "*.min.js"], + }), { ...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("2 already ignored by Codacy's defaults."); 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); + printIgnoreRulesOutcome( + plan({ planned: [rule("a/**"), rule("b/**"), rule("c/**")] }), + { ...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.", ); @@ -240,7 +323,7 @@ describe("printIgnoreRulesOutcome", () => { it("sanitizes patterns and messages", () => { printIgnoreRulesOutcome( - [], + plan(), { ...empty, refused: [{ pattern: "a\x1b[2J", toolNames: [], error: "InvalidPattern", message: "bad\x1b]52;c;x\x07" }], diff --git a/src/utils/import-ignore-rules.ts b/src/utils/import-ignore-rules.ts index 839b622..9d24902 100644 --- a/src/utils/import-ignore-rules.ts +++ b/src/utils/import-ignore-rules.ts @@ -4,6 +4,7 @@ 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 { NewIgnoreRuleSource } from "../api/client/models/NewIgnoreRuleSource"; import { ApiError } from "../api/client/core/ApiError"; import { RepositoryService } from "../api/client/services/RepositoryService"; import { chunk, ImportFailure, resolveToolId } from "./import-config"; @@ -31,6 +32,7 @@ export interface SkippedRule { export interface IgnoreRulesPlan { planned: PlannedRule[]; skipped: SkippedRule[]; + coveredByDefaults: string[]; } export interface IgnoreRulesOutcome { @@ -43,25 +45,93 @@ export interface IgnoreRulesOutcome { 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; +// Mirrors foundation's CodacyDefaultIgnores, which the server applies to every repository. +const DEFAULT_IGNORED_FOLDERS = [ + "node_modules", + "bower_components", + "vendor", + "thirdParty", + "thirdparty", + "third_Party", + "third_party", + "third-Party", + "third-party", + "sample", + "samples", + "release", + "releases", + "build", + "builds", + "dist", + "external", + "libs", +]; + +const DEFAULT_IGNORED_FILE_ENDINGS = [ + ".min.css", + "-min.css", + ".min.js", + "-min.js", + "d3.js", + "angular.js", + "angular-resource.js", + "select2.js", + "select2-resource.js", + "-ace.js", + "typeahead.js", + "jquery-ui.js", + "reveal.js", + "three.js", + "chart.js", + "jquery.js", + "underscore.js", + "lodash.js", + "bootstrap.js", + "bootstrap.css", + "font-awesome.css", + ".Designer.cs", + ".designer.cs", +]; + +function literalOf(text: string): string | undefined { let literal = ""; - for (let i = 0; i < pattern.length; i++) { - const c = pattern[i]; - if (c === "\\" && i + 1 < pattern.length) { - literal += pattern[++i]; + for (let i = 0; i < text.length; i++) { + const c = text[i]; + if (c === "\\" && i + 1 < text.length) { + literal += text[++i]; continue; } - if (GLOB_SPECIAL.test(c)) return asGlob; + if (GLOB_SPECIAL.test(c)) return undefined; literal += c; } + return literal; +} + +export function toRule(pattern: string): { path: string; type: IgnoreRuleType } { + const asGlob = { path: pattern, type: "glob" as const }; + if (/^[!#/]/.test(pattern)) return asGlob; + const literal = literalOf(pattern); + if (literal === undefined) return asGlob; const segments = literal.split("/"); const isPath = segments.length > 1 && segments.every((s) => s !== "" && s !== "." && s !== ".."); return isPath ? { path: literal, type: "file" } : asGlob; } +export function coveredByDefaults(pattern: string): boolean { + if (/^[!#/]/.test(pattern)) return false; + const segments = pattern.split("/"); + const last = segments[segments.length - 1]; + const ending = literalOf(last.startsWith("*") && !last.startsWith("**") ? last.slice(1) : last); + if (ending !== undefined && DEFAULT_IGNORED_FILE_ENDINGS.some((e) => ending.endsWith(e))) { + return true; + } + return segments.slice(0, -1).some((segment) => { + const folder = literalOf(segment); + return folder !== undefined && DEFAULT_IGNORED_FOLDERS.some((f) => folder.endsWith(f)); + }); +} + const ruleKey = (rule: { path: string; type: IgnoreRuleType }) => `${rule.type}\0${rule.path}`; function skipMessage(skip: Omit): string { @@ -76,6 +146,7 @@ function skipMessage(skip: Omit): string { export function planIgnoreRules(config: CodacyConfig, allTools: Tool[]): IgnoreRulesPlan { const planned = new Map(); const skipped = new Map>(); + const covered = new Set(); const skip = (pattern: string, error: "UnknownTool" | "LeadingSlash", toolName?: string) => { const key = `${error}\0${pattern}`; @@ -93,6 +164,10 @@ export function planIgnoreRules(config: CodacyConfig, allTools: Tool[]): IgnoreR skip(pattern, "LeadingSlash"); continue; } + if (coveredByDefaults(pattern)) { + covered.add(pattern); + continue; + } const rule = toRule(pattern); if (!planned.has(ruleKey(rule))) { planned.set(ruleKey(rule), { ...rule, tools: [], toolNames: [], source: pattern }); @@ -114,6 +189,10 @@ export function planIgnoreRules(config: CodacyConfig, allTools: Tool[]): IgnoreR skip(pattern, "LeadingSlash", tool.name); continue; } + if (coveredByDefaults(pattern)) { + covered.add(pattern); + continue; + } const rule = toRule(pattern); const key = ruleKey(rule); if (globalKeys.has(key)) continue; @@ -130,6 +209,7 @@ export function planIgnoreRules(config: CodacyConfig, allTools: Tool[]): IgnoreR return { planned: [...planned.values()], skipped: [...skipped.values()].map((s) => ({ ...s, message: skipMessage(s) })), + coveredByDefaults: [...covered], }; } @@ -138,7 +218,7 @@ export async function sendIgnoreRules( organization: string, repository: string, planned: PlannedRule[], - reason: string, + origin: { source: NewIgnoreRuleSource; reason: string }, options: { dryRun: boolean; spinner?: ReturnType }, ): Promise { const outcome: IgnoreRulesOutcome = { @@ -162,7 +242,7 @@ export async function sendIgnoreRules( provider, organization, repository, - { rules: batch.map((r) => ({ path: r.path, type: r.type, tools: r.tools, reason })) }, + { rules: batch.map((r) => ({ path: r.path, type: r.type, tools: r.tools, ...origin })) }, options.dryRun, ); // Every rule comes back in `successful` or `failed`, with its path as sent. @@ -199,16 +279,17 @@ export async function sendIgnoreRules( } export function printIgnoreRulesOutcome( - skipped: SkippedRule[], + plan: IgnoreRulesPlan, outcome: IgnoreRulesOutcome, - options: { dryRun: boolean; repository: string; configPath: string; plannedCount: number }, + options: { dryRun: boolean; repository: string; configPath: string }, ): void { console.log(); if (outcome.configurationFile) { + const count = plan.planned.length; 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)} ` + + `The ${count} exclude ${pluralize("pattern", count)} in ${sanitizeText(options.configPath)} ` + `${options.dryRun ? "won't be" : "were not"} imported.`, ), ); @@ -232,8 +313,11 @@ export function printIgnoreRulesOutcome( if (outcome.alreadyExists.length > 0) { console.log(ansis.dim(`${outcome.alreadyExists.length} already on Codacy.`)); } + if (plan.coveredByDefaults.length > 0) { + console.log(ansis.dim(`${plan.coveredByDefaults.length} already ignored by Codacy's defaults.`)); + } - const notImported = [...skipped, ...outcome.refused]; + const notImported = [...plan.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:`,