Skip to content
This repository was archived by the owner on Oct 23, 2026. It is now read-only.
Merged
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
72 changes: 59 additions & 13 deletions src/commands/release/set-commits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -35,6 +39,14 @@ const log = logger.withTag("release.set-commits");

const USAGE_HINT = "sentry release set-commits [<org>/]<version>";

/** Diagnostic note shared by --from validation errors. */
const FROM_RANGE_NOTE =
"Range is always <ref>..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.
*
Expand Down Expand Up @@ -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"
);
}
Expand Down Expand Up @@ -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
);
}

Expand Down Expand Up @@ -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"
);
}
Expand Down
89 changes: 85 additions & 4 deletions src/lib/argv-hoist.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}.
*
Expand Down Expand Up @@ -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;
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
}
}
Comment thread
sentry[bot] marked this conversation as resolved.
Resolved
}
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.
Expand All @@ -245,5 +326,5 @@ export function preprocessArgv(argv: readonly string[]): string[] {
if (isVersionRequest(argv)) {
return ["--version"];
}
return hoistGlobalFlags(argv);
return hoistGlobalFlags(rewriteDashedFlagValues(argv));
}
46 changes: 46 additions & 0 deletions src/lib/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
58 changes: 50 additions & 8 deletions src/lib/git.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -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)."
);
}

Expand All @@ -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 <org>/<version> --from v0.9.0",
],
"from",
"Range is always <ref>..HEAD — checkout the current release tag first."
);
}
throw error;
}

if (!raw) {
return [];
Expand Down
2 changes: 1 addition & 1 deletion test/commands/release/set-commits.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down
Loading
Loading