diff --git a/src/commands/release/set-commits.ts b/src/commands/release/set-commits.ts index d4072ae615..f5044dd804 100644 --- a/src/commands/release/set-commits.ts +++ b/src/commands/release/set-commits.ts @@ -14,7 +14,11 @@ import { import { buildCommand, numberParser } from "../../lib/command.js"; import { getDatabase } from "../../lib/db/index.js"; import { clearMetadata, getMetadata, setMetadata } from "../../lib/db/utils.js"; -import { ApiError, ValidationError } from "../../lib/errors.js"; +import { + ApiError, + ValidationError, + validationError, +} from "../../lib/errors.js"; import { escapeMarkdownInline, mdKvTable, @@ -35,6 +39,14 @@ const log = logger.withTag("release.set-commits"); const USAGE_HINT = "sentry release set-commits [/]"; +/** Diagnostic note shared by --from validation errors. */ +const FROM_RANGE_NOTE = + "Range is always ..HEAD — checkout the current release before running."; + +/** Note when --from receives a CLI-flag-like value (git refs cannot start with '-'). */ +const FROM_DASHED_REF_NOTE = + "Git refs cannot start with '-'. Tokens like '--format=x' are CLI flags, not refs — use a tag or commit (e.g. v0.9.0)."; + /** * Read commits from local git history and send to the Sentry API. * @@ -204,8 +216,12 @@ function parseCommitRefs( const trimmed = pair.trim(); const atIdx = trimmed.lastIndexOf("@"); if (atIdx <= 0) { - throw new ValidationError( + throw validationError( `Invalid commit format '${trimmed}'. Expected REPO@SHA or REPO@PREV..SHA.`, + [ + "sentry release set-commits 1.0.0 --commit owner/repo@abc123", + "sentry release set-commits 1.0.0 --commit owner/repo@prev..abc123", + ], "commit" ); } @@ -252,35 +268,60 @@ function parseLocalScope(flags: { .map((p) => p.trim()) .filter(Boolean); if (flags.path !== undefined && paths.length === 0) { - throw new ValidationError( + throw validationError( "--path requires at least one non-empty path.", + ["sentry release set-commits 1.0.0 --path apps/mobile,packages/shared"], "path" ); } if (paths.length > 0 && serverExpanded) { - throw new ValidationError( - "--path cannot be combined with --auto or --commit (their commit ranges are expanded server-side). Use --path with local mode.", + throw validationError( + "--path cannot be combined with --auto or --commit. Those modes expand commit ranges on the server; --path filters local git history only.", + flags.commit + ? [ + "sentry release set-commits 1.0.0 --from v0.9.0 --path apps/mobile", + "sentry release set-commits 1.0.0 --local --path apps/mobile", + ] + : [ + "sentry release set-commits 1.0.0 --local --path apps/mobile", + "sentry release set-commits 1.0.0 --from v0.9.0 --path apps/mobile", + ], "path" ); } const from = flags.from?.trim(); if (flags.from !== undefined && !from) { - throw new ValidationError("--from requires a non-empty git ref.", "from"); + throw validationError( + "--from requires a non-empty git ref (tag, branch, or commit).", + ["sentry release set-commits 1.0.0 --from v0.9.0"], + "from", + FROM_RANGE_NOTE + ); } // Reject option-like refs. Otherwise `--from=--format=x` would become the // argv element `--format=x..HEAD`, which git parses as a `--format` override // (arg injection). Git ref names cannot start with "-" anyway. if (from?.startsWith("-")) { - throw new ValidationError( - "--from must be a git ref, not an option (must not start with '-').", - "from" + throw validationError( + `--from must be a git ref, not a CLI flag (received '${from}').`, + [ + "sentry release set-commits 1.0.0 --from v0.9.0", + "sentry release set-commits 1.0.0 --from v0.9.0 --path apps/mobile", + ], + "from", + FROM_DASHED_REF_NOTE ); } if (from && serverExpanded) { - throw new ValidationError( - "--from cannot be combined with --auto or --commit (their commit ranges are expanded server-side). Use --from with local mode.", - "from" + throw validationError( + "--from cannot be combined with --auto or --commit. Those modes expand commit ranges on the server; --from reads local git history.", + [ + "sentry release set-commits 1.0.0 --from v0.9.0 --path apps/mobile", + "sentry release set-commits 1.0.0 --local --initial-depth 50", + ], + "from", + FROM_RANGE_NOTE ); } @@ -423,8 +464,13 @@ export const setCommitsCommand = buildCommand({ // Validate mutual exclusivity of commit source flags const modeFlags = [flags.auto, flags.local, !!flags.commit].filter(Boolean); if (modeFlags.length > 1) { - throw new ValidationError( + throw validationError( "Only one of --auto, --local, or --commit can be used at a time.", + [ + "sentry release set-commits 1.0.0 --auto", + "sentry release set-commits 1.0.0 --from v0.9.0 --path apps/mobile", + "sentry release set-commits 1.0.0 --commit owner/repo@abc123..def456", + ], "commit" ); } diff --git a/src/lib/argv-hoist.ts b/src/lib/argv-hoist.ts index 1daa77192a..aea3af5b3e 100644 --- a/src/lib/argv-hoist.ts +++ b/src/lib/argv-hoist.ts @@ -49,6 +49,42 @@ const NEGATABLE_NAMES = new Set( HOISTABLE_FLAGS.filter((f) => f.negatable).map((f) => f.name) ); +/** + * Flags whose values may start with `-`. + * + * Stricli treats a following token like `--format=x` as a separate flag, not + * as the value of `--from`. Rewriting `--from --format=x` → `--from=--format=x` + * lets the leaf parser pass the ref through to validation. + */ +const DASHED_VALUE_FLAGS = new Set(["from"]); + +/** + * Leaf flags on `release set-commits` that must not be swallowed as a `--from` + * value when rewrite runs (only `--from` uses {@link DASHED_VALUE_FLAGS} today). + */ +const SET_COMMITS_FROM_NEIGHBOR_FLAGS = new Set([ + "auto", + "local", + "clear", + "commit", + "path", + "from", + "initial-depth", +]); + +/** True when `token` is a registered global or set-commits leaf flag. */ +function isRegisteredFlagToken(token: string): boolean { + if (matchHoistable(token) !== null) { + return true; + } + if (!token.startsWith("--")) { + return false; + } + const eqIdx = token.indexOf("="); + const name = eqIdx === -1 ? token.slice(2) : token.slice(2, eqIdx); + return SET_COMMITS_FROM_NEIGHBOR_FLAGS.has(name); +} + /** * Match result from {@link matchHoistable}. * @@ -225,15 +261,60 @@ export function hoistGlobalFlags(argv: readonly string[]): string[] { return [...remaining, ...hoisted, ...positionalTail]; } +/** + * Rewrite `--flag VALUE` as `--flag=VALUE` when `VALUE` looks like a long flag. + * + * Stricli's parser treats dashed tokens as flags, so `--from --format=x` fails + * before the command sees the ref. Only unregistered `--`-prefixed tokens are + * merged — registered global flags (`--json`) and set-commits leaf flags + * (`--auto`) are left separate; short flags like `-v` are never merged. Git refs cannot start with `-` anyway; merged injection + * attempts still reach our validation guard. + * + * Tokens after `--` are never touched. + * + * @param argv - Raw CLI arguments (e.g., `process.argv.slice(2)`) + * @returns New array with eligible flag/value pairs collapsed to `--flag=value` + */ +export function rewriteDashedFlagValues(argv: readonly string[]): string[] { + const result: string[] = []; + let i = 0; + while (i < argv.length) { + const token = argv[i] ?? ""; + if (token === "--") { + result.push(...argv.slice(i)); + break; + } + if (token.startsWith("--") && !token.includes("=")) { + const name = token.slice(2); + if (DASHED_VALUE_FLAGS.has(name)) { + const next = argv[i + 1]; + if ( + next?.startsWith("--") && + next !== "--" && + !isRegisteredFlagToken(next) + ) { + result.push(`${token}=${next}`); + i += 2; + continue; + } + } + } + result.push(token); + i += 1; + } + return result; +} + /** * Preprocess raw CLI argv before Stricli dispatch. * - * Composes the two argv transforms applied on every invocation: + * Composes the argv transforms applied on every invocation: * 1. A top-level `--version` (see {@link isVersionRequest}) is normalized to a * plain `["--version"]` so the application-level version handler prints it * regardless of how deep in the route tree it appeared. - * 2. Otherwise, global flags are hoisted to the tail (see - * {@link hoistGlobalFlags}). + * 2. Otherwise, dashed flag values are rewritten (see + * {@link rewriteDashedFlagValues}), then global flags are hoisted to the + * tail (see {@link hoistGlobalFlags}). * * Kept as a single entry point so callers apply one transform and stay under * the cognitive-complexity budget. @@ -245,5 +326,5 @@ export function preprocessArgv(argv: readonly string[]): string[] { if (isVersionRequest(argv)) { return ["--version"]; } - return hoistGlobalFlags(argv); + return hoistGlobalFlags(rewriteDashedFlagValues(argv)); } diff --git a/src/lib/errors.ts b/src/lib/errors.ts index 001ab80ea6..7ef84fe621 100644 --- a/src/lib/errors.ts +++ b/src/lib/errors.ts @@ -503,6 +503,52 @@ export class ResolutionError extends CliError { } } +/** + * Build a {@link ValidationError} message with Try: examples and optional Note: section. + * + * Matches {@link buildResolutionMessage} / {@link buildContextMessage} formatting so + * agent consumers get actionable recovery commands plus diagnostic context in a + * predictable shape. Always pass `field` when constructing the error — unfielded + * validation errors collapse into one Sentry fingerprint. + * + * @param headline - What failed validation + * @param examples - CLI commands or steps shown under "Try:" + * @param note - Optional diagnostic context rendered as "Note:" (not actionable) + */ +export function buildValidationMessage( + headline: string, + examples: string[], + note?: string +): string { + const lines = [headline]; + if (examples.length > 0) { + lines.push("", "Try:"); + for (const example of examples) { + lines.push(` ${example}`); + } + } + if (note) { + lines.push("", `Note: ${note}`); + } + return lines.join("\n"); +} + +/** + * Convenience wrapper around {@link buildValidationMessage} that returns a + * {@link ValidationError} with the given field name. + */ +export function validationError( + headline: string, + examples: string[], + field?: string, + note?: string +): ValidationError { + return new ValidationError( + buildValidationMessage(headline, examples, note), + field + ); +} + /** * Input validation errors. * diff --git a/src/lib/git.ts b/src/lib/git.ts index 1d44c49016..a029e01a67 100644 --- a/src/lib/git.ts +++ b/src/lib/git.ts @@ -13,7 +13,31 @@ import { execFileSync } from "node:child_process"; -import { ValidationError } from "./errors.js"; +import { ValidationError, validationError } from "./errors.js"; + +/** `execFileSync` failure shape when git exits non-zero. */ +type ExecFileSyncError = Error & { + stderr?: string | Buffer; + stdout?: string | Buffer; +}; + +/** + * Return true when git stderr indicates an unknown or invalid revision ref. + * + * Used to surface friendly {@link ValidationError}s instead of raw git output. + */ +function isUnknownGitRefError(error: unknown): boolean { + if (typeof error !== "object" || error === null || !("stderr" in error)) { + return false; + } + const stderr = String((error as ExecFileSyncError).stderr ?? ""); + return ( + stderr.includes("unknown revision") || + stderr.includes("bad revision") || + stderr.includes("ambiguous argument") || + stderr.includes("Invalid revision range") + ); +} /** Commit data structure matching the Sentry releases API */ export type GitCommit = { @@ -168,9 +192,11 @@ export function getCommitLog( // This is version-independent, unlike `--end-of-options` (git >= 2.24). // Mirrors the guard in getMergeBase. if (from?.startsWith("-")) { - throw new ValidationError( - `Invalid git ref '${from}': must not start with '-'.`, - "from" + throw validationError( + `--from must be a git ref, not a CLI flag (received '${from}').`, + ["sentry release set-commits 1.0.0 --from v0.9.0"], + "from", + "Git refs cannot start with '-'. Tokens like '--format=x' are CLI flags, not refs — use a tag or commit (e.g. v0.9.0)." ); } @@ -192,10 +218,26 @@ export function getCommitLog( // Pathspecs go after `--`; each path is a discrete argv entry (no shell), so // there is no escaping/injection concern. const pathspec = paths && paths.length > 0 ? ["--", ...paths] : []; - const raw = git( - ["log", `--format=${format}`, ...maxCount, range, ...pathspec], - cwd - ); + let raw: string; + try { + raw = git( + ["log", `--format=${format}`, ...maxCount, range, ...pathspec], + cwd + ); + } catch (error) { + if (from && isUnknownGitRefError(error)) { + throw validationError( + `Unknown git ref '${from}': not found in this repository.`, + [ + `git rev-parse ${from}`, + "sentry release set-commits / --from v0.9.0", + ], + "from", + "Range is always ..HEAD — checkout the current release tag first." + ); + } + throw error; + } if (!raw) { return []; diff --git a/test/commands/release/set-commits.test.ts b/test/commands/release/set-commits.test.ts index 3cebb0b391..b3330378f8 100644 --- a/test/commands/release/set-commits.test.ts +++ b/test/commands/release/set-commits.test.ts @@ -664,7 +664,7 @@ describe("release set-commits --from", () => { }, "1.0.0" ) - ).rejects.toThrow("--from must be a git ref, not an option"); + ).rejects.toThrow("--from must be a git ref, not a CLI flag"); }); test("throws when --from is empty/whitespace", async () => { diff --git a/test/lib/argv-hoist.test.ts b/test/lib/argv-hoist.test.ts index e107b671e0..d884c126ab 100644 --- a/test/lib/argv-hoist.test.ts +++ b/test/lib/argv-hoist.test.ts @@ -11,6 +11,7 @@ import { hoistGlobalFlags, isVersionRequest, preprocessArgv, + rewriteDashedFlagValues, } from "../../src/lib/argv-hoist.js"; describe("hoistGlobalFlags", () => { @@ -380,6 +381,75 @@ describe("isVersionRequest", () => { }); }); +describe("rewriteDashedFlagValues", () => { + test("rewrites --from followed by a dashed token to equals form", () => { + expect( + rewriteDashedFlagValues([ + "release", + "set-commits", + "1.0.0", + "--from", + "--format=x", + ]) + ).toEqual(["release", "set-commits", "1.0.0", "--from=--format=x"]); + }); + + test("does not rewrite --from followed by a single-dash token", () => { + expect( + rewriteDashedFlagValues([ + "release", + "set-commits", + "1.0.0", + "--from", + "-v1.0", + ]) + ).toEqual(["release", "set-commits", "1.0.0", "--from", "-v1.0"]); + }); + + test("does not rewrite --from followed by a global flag", () => { + expect( + rewriteDashedFlagValues([ + "release", + "set-commits", + "1.0.0", + "--from", + "--json", + ]) + ).toEqual(["release", "set-commits", "1.0.0", "--from", "--json"]); + }); + + test("leaves --from= already in equals form unchanged", () => { + expect( + rewriteDashedFlagValues([ + "release", + "set-commits", + "1.0.0", + "--from=-format=x", + ]) + ).toEqual(["release", "set-commits", "1.0.0", "--from=-format=x"]); + }); + + test("does not rewrite tokens after --", () => { + expect( + rewriteDashedFlagValues([ + "release", + "set-commits", + "1.0.0", + "--", + "--from", + "--format=x", + ]) + ).toEqual([ + "release", + "set-commits", + "1.0.0", + "--", + "--from", + "--format=x", + ]); + }); +}); + describe("preprocessArgv", () => { test("normalizes a route-scoped --version to a plain --version", () => { expect(preprocessArgv(["cli", "--version"])).toEqual(["--version"]); @@ -401,4 +471,41 @@ describe("preprocessArgv", () => { preprocessArgv(["monitor", "run", "job", "--", "tool", "--version"]) ).toEqual(["monitor", "run", "job", "--", "tool", "--version"]); }); + + test("rewrites dashed --from values before hoisting global flags", () => { + expect( + preprocessArgv([ + "--verbose", + "release", + "set-commits", + "1.0.0", + "--from", + "--format=x", + ]) + ).toEqual([ + "release", + "set-commits", + "1.0.0", + "--from=--format=x", + "--verbose", + ]); + }); + + test("preserves --json when it follows --from without a ref", () => { + expect( + preprocessArgv(["release", "set-commits", "1.0.0", "--from", "--json"]) + ).toEqual(["release", "set-commits", "1.0.0", "--from", "--json"]); + }); + + test("does not rewrite --from followed by another set-commits flag", () => { + expect( + rewriteDashedFlagValues([ + "release", + "set-commits", + "1.0.0", + "--from", + "--auto", + ]) + ).toEqual(["release", "set-commits", "1.0.0", "--from", "--auto"]); + }); }); diff --git a/test/lib/errors.test.ts b/test/lib/errors.test.ts index 485235419b..485ffbb724 100644 --- a/test/lib/errors.test.ts +++ b/test/lib/errors.test.ts @@ -3,6 +3,7 @@ import { AbortError, ApiError, AuthError, + buildValidationMessage, CliError, ConfigError, ContextError, @@ -21,6 +22,7 @@ import { TimeoutError, UpgradeError, ValidationError, + validationError, WizardError, withAuthGuard, } from "../../src/lib/errors.js"; @@ -276,6 +278,34 @@ describe("ValidationError", () => { }); }); +describe("buildValidationMessage", () => { + test("formats Try examples and Note section", () => { + expect( + buildValidationMessage( + "Invalid flag.", + ["sentry release set-commits 1.0.0 --from v0.9.0"], + "Range is always ..HEAD." + ) + ).toBe( + [ + "Invalid flag.", + "", + "Try:", + " sentry release set-commits 1.0.0 --from v0.9.0", + "", + "Note: Range is always ..HEAD.", + ].join("\n") + ); + }); + + test("validationError wrapper preserves field", () => { + const err = validationError("Bad ref.", ["git rev-parse v0.9.0"], "from"); + expect(err).toBeInstanceOf(ValidationError); + expect(err.field).toBe("from"); + expect(err.message).toContain("Try:"); + }); +}); + describe("DeviceFlowError", () => { test("stores error code", () => { const err = new DeviceFlowError("slow_down", "Polling too fast"); diff --git a/test/lib/git-commit-log.test.ts b/test/lib/git-commit-log.test.ts index 1d9dd4b6d3..c0b6b91afb 100644 --- a/test/lib/git-commit-log.test.ts +++ b/test/lib/git-commit-log.test.ts @@ -78,11 +78,34 @@ describe("getCommitLog pathspec argv", () => { // (no reliance on --end-of-options, which requires git >= 2.24). test("throws on an option-like `from` ref", () => { expect(() => getCommitLog("/repo", { from: "--format=%H" })).toThrow( - "must not start with '-'" + "must be a git ref, not a CLI flag" + ); + expect(() => getCommitLog("/repo", { from: "--format=%H" })).toThrow( + "Git refs cannot start with '-'" + ); + expect(() => getCommitLog("/repo", { from: "--format=%H" })).not.toThrow( + "use the equals form" ); expect(execFileSyncMock).not.toHaveBeenCalled(); }); + test("throws ValidationError when the from ref is unknown", () => { + const gitError = Object.assign(new Error("Command failed"), { + stderr: + "fatal: ambiguous argument 'bogus-ref..HEAD': unknown revision or path not in the working tree.\n", + }); + execFileSyncMock.mockImplementation(() => { + throw gitError; + }); + + expect(() => getCommitLog("/repo", { from: "bogus-ref" })).toThrow( + "Unknown git ref 'bogus-ref': not found in this repository." + ); + expect(() => getCommitLog("/repo", { from: "bogus-ref" })).toThrow( + "git rev-parse bogus-ref" + ); + }); + // Uncapped `--from` ranges can emit >1 MB, so git() must raise maxBuffer // above execFileSync's 1 MB default to avoid crashing on large histories. test("passes a large maxBuffer to execFileSync", () => {