diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index dedf2d19f54ed..4b23f8cd6c66f 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -66,7 +66,11 @@ import { } from "../sourceControl/threadPullRequests.ts"; import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; -import { GitManagerError, GitPullRequestMaterializationError } from "@t3tools/contracts"; +import { + GitManagerError, + GitPullRequestMaterializationError, + trimAsciiWhitespace, +} from "@t3tools/contracts"; import { historicalMessage, renderHistory, @@ -278,7 +282,7 @@ const prLookupGitReads = Context.Reference( function parseRemoteNames(stdout: string): ReadonlyArray { return stdout .split("\n") - .map((name) => name.trim()) + .map(trimAsciiWhitespace) .filter((name) => name.length > 0); } @@ -2012,7 +2016,7 @@ export const make = Effect.gen(function* () { timeoutMs: 5_000, })).stdout .split("\n") - .map((ref) => ref.trim()) + .map(trimAsciiWhitespace) .filter((ref) => ref.length > 0), ); const matching = remoteNames.filter((name) => refs.has(`refs/remotes/${name}/${branch}`)); @@ -2049,7 +2053,7 @@ export const make = Effect.gen(function* () { const oidByRef = new Map( refs.stdout .split("\n") - .map((line) => line.trim().split("\u0000")) + .map((line) => trimAsciiWhitespace(line).split("\u0000")) .filter((entry): entry is [string, string] => entry.length === 2), ); const localOid = oidByRef.get(localRef); @@ -3354,7 +3358,7 @@ export const make = Effect.gen(function* () { const refNames = new Set( trackingRefs.stdout .split("\n") - .map((remoteRef) => remoteRef.trim()) + .map(trimAsciiWhitespace) .filter((remoteRef) => remoteRef.length > 0), ); return remoteNames diff --git a/apps/server/src/git/GitWorkflowService.ts b/apps/server/src/git/GitWorkflowService.ts index 4cf3e62d9a93f..ca7c0b03c13d4 100644 --- a/apps/server/src/git/GitWorkflowService.ts +++ b/apps/server/src/git/GitWorkflowService.ts @@ -29,6 +29,7 @@ import { type VcsStatusResult, } from "@t3tools/contracts"; +import { trimAsciiWhitespace } from "@t3tools/contracts"; import * as GitManager from "./GitManager.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; @@ -365,7 +366,7 @@ export const make = Effect.gen(function* () { timeoutMs: 5_000, }); if (result.exitCode === 0) { - return result.stdout.trim().replace(/^refs\/heads\//, "") || null; + return trimAsciiWhitespace(result.stdout).replace(/^refs\/heads\//, "") || null; } if (result.exitCode === 1) return null; return yield* new GitCommandError({ diff --git a/apps/server/src/git/remoteRefs.ts b/apps/server/src/git/remoteRefs.ts index e3873effe475e..c5be08c165676 100644 --- a/apps/server/src/git/remoteRefs.ts +++ b/apps/server/src/git/remoteRefs.ts @@ -1,7 +1,9 @@ +import { trimAsciiWhitespace } from "@t3tools/contracts"; + export function parseRemoteNamesInGitOrder(stdout: string): ReadonlyArray { const remoteNames: Array = []; for (const line of stdout.split("\n")) { - const remoteName = line.trim(); + const remoteName = trimAsciiWhitespace(line); if (remoteName.length > 0) { remoteNames.push(remoteName); } @@ -17,7 +19,7 @@ export function parseRemoteRefWithRemoteNames( ref: string, remoteNames: ReadonlyArray, ): { remoteRef: string; remoteName: string; branchName: string } | null { - const trimmedRef = ref.trim(); + const trimmedRef = trimAsciiWhitespace(ref); if (trimmedRef.length === 0) { return null; } @@ -27,7 +29,7 @@ export function parseRemoteRefWithRemoteNames( if (!trimmedRef.startsWith(remotePrefix)) { continue; } - const branchName = trimmedRef.slice(remotePrefix.length).trim(); + const branchName = trimmedRef.slice(remotePrefix.length); if (branchName.length === 0) { return null; } @@ -48,7 +50,7 @@ export function extractBranchNameFromRemoteRef( remoteNames?: ReadonlyArray; }, ): string { - const normalized = ref.trim(); + const normalized = trimAsciiWhitespace(ref); if (normalized.length === 0) { return ""; } @@ -67,5 +69,5 @@ export function extractBranchNameFromRemoteRef( if (firstSlash === -1) { return normalized; } - return normalized.slice(firstSlash + 1).trim(); + return normalized.slice(firstSlash + 1); } diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index d64c0ec5cbb5b..b7125614c0ef7 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -6485,24 +6485,36 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("marks the origin default ref as default when no local copy exists", () => - Effect.gen(function* () { - const cwd = yield* makeTmpDir(); - const remote = yield* makeTmpDir("git-vcs-driver-remote-"); - const { initialBranch } = yield* initRepoWithCommit(cwd); - yield* git(remote, ["init", "--bare"]); - yield* git(cwd, ["remote", "add", "origin", remote]); - yield* git(cwd, ["push", "-u", "origin", initialBranch]); - yield* git(cwd, ["remote", "set-head", "origin", initialBranch]); - yield* git(cwd, ["checkout", "-b", "feature/only-local"]); - yield* git(cwd, ["branch", "-D", initialBranch]); - const driver = yield* GitVcsDriver.GitVcsDriver; + it.effect.each(["trunk", "feature/memo\u3000", "\u00a0release"])( + "marks the origin default ref %s as default when no local copy exists", + (defaultBranch) => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const remote = yield* makeTmpDir("git-vcs-driver-remote-"); + yield* initRepoWithCommit(cwd); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["branch", "-M", defaultBranch]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "-u", "origin", defaultBranch]); + yield* git(cwd, ["remote", "set-head", "origin", defaultBranch]); + const driver = yield* GitVcsDriver.GitVcsDriver; - const refs = yield* driver.listRefs({ cwd }); - const remoteDefault = refs.refs.find((ref) => ref.name === `origin/${initialBranch}`); - assert.equal(remoteDefault?.isRemote, true); - assert.equal(remoteDefault?.isDefault, true); - }), + const localStatus = yield* driver.statusDetails(cwd); + const remoteStatus = yield* driver.statusDetailsRemote(cwd); + for (const status of [localStatus, remoteStatus]) { + assert.equal(status.branch, defaultBranch); + assert.equal(status.upstreamRef, `origin/${defaultBranch}`); + assert.isTrue(status.isDefaultBranch); + } + + yield* git(cwd, ["checkout", "-b", "feature/only-local"]); + yield* git(cwd, ["branch", "-D", defaultBranch]); + + const refs = yield* driver.listRefs({ cwd }); + const remoteDefault = refs.refs.find((ref) => ref.name === `origin/${defaultBranch}`); + assert.equal(remoteDefault?.isRemote, true); + assert.equal(remoteDefault?.isDefault, true); + }), ); it.effect("preserves exact custom names and refuses collisions without a suffix", () => @@ -7444,37 +7456,42 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect.each(["release/v2", "origin/release/v2", "refs/remotes/origin/release/v2"])( - "records a remote-only PR base when creating a worktree from %s", - (baseRef) => - Effect.gen(function* () { - const cwd = yield* makeTmpDir(); - yield* initRepoWithCommit(cwd); - const remote = yield* makeTmpDir("git-remote-"); - yield* git(remote, ["init", "--bare"]); - yield* git(cwd, ["remote", "add", "origin", remote]); - yield* git(cwd, ["push", "origin", "HEAD:refs/heads/release/v2"]); - const commit = yield* git(cwd, ["rev-parse", "origin/release/v2"]); - const path = yield* Path.Path; - const driver = yield* GitVcsDriver.GitVcsDriver; - const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "remote"); - yield* driver.createWorktree({ - cwd, - path: worktreePath, - refName: commit, - newRefName: "feature/remote", - baseRefName: baseRef, - }); + it.effect.each([ + "release/v2", + "origin/release/v2", + "refs/remotes/origin/release/v2", + "origin/release/v2\u3000", + ])("records a remote-only PR base when creating a worktree from %s", (baseRef) => + Effect.gen(function* () { + const branch = baseRef.replace(/^(refs\/remotes\/)?origin\//, ""); + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const remote = yield* makeTmpDir("git-remote-"); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "origin", `HEAD:refs/heads/${branch}`]); + const commit = yield* git(cwd, ["rev-parse", `origin/${branch}`]); + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.GitVcsDriver; + const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "remote"); + yield* driver.createWorktree({ + cwd, + path: worktreePath, + refName: commit, + newRefName: "feature/remote", + baseRefName: baseRef, + }); - const preview = yield* driver.getReviewDiffPreview({ cwd: worktreePath }); - const comparisonBase = preview.sources.find( - (source) => source.kind === "branch-range", - )!.baseRef; - assert.equal( - yield* git(worktreePath, ["rev-parse", `${comparisonBase}^{commit}`]), - commit, - ); - }), + assert.equal( + yield* driver.readConfigValue(cwd, "branch.feature/remote.t3-merge-base"), + branch, + ); + const preview = yield* driver.getReviewDiffPreview({ cwd: worktreePath }); + const comparisonBase = preview.sources.find( + (source) => source.kind === "branch-range", + )!.baseRef; + assert.equal(yield* git(worktreePath, ["rev-parse", `${comparisonBase}^{commit}`]), commit); + }), ); it("parses checkout progress lines from git's stderr", () => { diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 9ee53e4e90ac3..4981ece0979e4 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -34,6 +34,7 @@ import { type ReviewDiffPreviewInput, type ReviewDiffFileStat, type ReviewDiffPreviewSource, + trimAsciiWhitespace, type VcsRef, } from "@t3tools/contracts"; import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git"; @@ -452,8 +453,8 @@ function parseUpstreamRefByFirstSeparator( return null; } - const remoteName = upstreamRef.slice(0, separatorIndex).trim(); - const branchName = upstreamRef.slice(separatorIndex + 1).trim(); + const remoteName = upstreamRef.slice(0, separatorIndex); + const branchName = upstreamRef.slice(separatorIndex + 1); if (remoteName.length === 0 || branchName.length === 0) { return null; } @@ -467,13 +468,13 @@ function parseUpstreamRefByFirstSeparator( function parseTrackingBranchByUpstreamRef(stdout: string, upstreamRef: string): string | null { for (const line of stdout.split("\n")) { - const trimmedLine = line.trim(); + const trimmedLine = trimAsciiWhitespace(line); if (trimmedLine.length === 0) { continue; } const [branchNameRaw, upstreamBranchRaw = ""] = trimmedLine.split("\t"); - const branchName = branchNameRaw?.trim() ?? ""; - const candidateUpstreamRef = upstreamBranchRaw.trim(); + const branchName = branchNameRaw ?? ""; + const candidateUpstreamRef = upstreamBranchRaw; if (branchName.length === 0 || candidateUpstreamRef.length === 0) { continue; } @@ -490,7 +491,7 @@ function deriveLocalBranchNameFromRemoteRef(branchName: string): string | null { if (separatorIndex <= 0 || separatorIndex === branchName.length - 1) { return null; } - const localBranch = branchName.slice(separatorIndex + 1).trim(); + const localBranch = branchName.slice(separatorIndex + 1); return localBranch.length > 0 ? localBranch : null; } @@ -592,19 +593,19 @@ function classifyGitFailure(stderr: string): GitCommandFailureReason | null { // `--short` and `--abbrev-ref` print `heads/` when a tag shares the branch's name, so // branch reads take the full ref and strip the prefix themselves. function branchNameFromHeadRef(value: string): string | null { - const ref = value.trim(); + const ref = trimAsciiWhitespace(value); return ref.startsWith("refs/heads/") && ref.length > "refs/heads/".length ? ref.slice("refs/heads/".length) : null; } function parseDefaultBranchFromRemoteHeadRef(value: string, remoteName: string): string | null { - const trimmed = value.trim(); + const trimmed = trimAsciiWhitespace(value); const prefix = `refs/remotes/${remoteName}/`; if (!trimmed.startsWith(prefix)) { return null; } - const refName = trimmed.slice(prefix.length).trim(); + const refName = trimmed.slice(prefix.length); return refName.length > 0 && refName !== "HEAD" ? refName : null; } @@ -1472,7 +1473,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd, ["rev-parse", "--symbolic-full-name", "@{upstream}"], true, - ).pipe(Effect.map((stdout) => stdout.trim().replace(/^refs\/(?:remotes|heads)\//, ""))); + ).pipe( + Effect.map((stdout) => trimAsciiWhitespace(stdout).replace(/^refs\/(?:remotes|heads)\//, "")), + ); if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") { return null; @@ -2056,7 +2059,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd, ["symbolic-ref", "--quiet", "HEAD"], true, - ).pipe(Effect.map((stdout) => stdout.trim()))); + ).pipe(Effect.map(trimAsciiWhitespace))); if (headRef.length === 0) return undefined; const upstreamRemote = yield* executeGit( "GitVcsDriver.refreshStatusUpstreamIfStale.upstreamRemote", @@ -2065,7 +2068,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* { allowNonZeroExit: true }, ); if (upstreamRemote.exitCode !== 0) return undefined; - const remoteName = upstreamRemote.stdout.trim(); + const remoteName = trimAsciiWhitespace(upstreamRemote.stdout); // Empty means no upstream; `.` means the upstream is a local branch. if (remoteName.length === 0 || remoteName === ".") return remoteName; const gitCommonDir = yield* resolveGitCommonDir(cwd); @@ -2202,7 +2205,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd, ["config", "--get", `branch.${refName}.pushRemote`], true, - ).pipe(Effect.map((stdout) => stdout.trim())); + ).pipe(Effect.map(trimAsciiWhitespace)); if (branchPushRemote.length > 0) { return branchPushRemote; } @@ -2212,7 +2215,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd, ["config", "--get", "remote.pushDefault"], true, - ).pipe(Effect.map((stdout) => stdout.trim())); + ).pipe(Effect.map(trimAsciiWhitespace)); return pushDefaultRemote.length > 0 ? pushDefaultRemote : null; }); @@ -2351,7 +2354,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ["rev-parse", "--symbolic-full-name", `${refName}@{upstream}`], { allowNonZeroExit: true }, ); - const comparisonRef = upstream.stdout.trim(); + const comparisonRef = trimAsciiWhitespace(upstream.stdout); if (upstream.exitCode !== 0 || !comparisonRef.startsWith("refs/remotes/")) return null; return { baseRef: comparisonRef.slice("refs/remotes/".length), comparisonRef }; }); @@ -2665,7 +2668,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* headRef = ""; } else { branch = branchNameFromHeadRef(branchResult.stdout); - headRef = branchResult.stdout.trim(); + headRef = trimAsciiWhitespace(branchResult.stdout); } let upstreamRemoteName: string | undefined; if (refreshUpstream) { @@ -2945,13 +2948,13 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* continue; } if (line.startsWith("# branch.head ")) { - const value = line.slice("# branch.head ".length).trim(); + const value = trimAsciiWhitespace(line.slice("# branch.head ".length)); // `(unknown)` is printed while HEAD names no resolvable branch, e.g. mid-`git clone`. refName = value === "(detached)" || value === "(unknown)" ? null : value; continue; } if (line.startsWith("# branch.upstream ")) { - const value = line.slice("# branch.upstream ".length).trim(); + const value = trimAsciiWhitespace(line.slice("# branch.upstream ".length)); upstreamRef = value.length > 0 ? value : null; continue; } @@ -4031,7 +4034,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd, ["config", "--get-all", `branch.${refName}.merge`], true, - ).pipe(Effect.map((stdout) => stdout.trim().split("\n").filter(Boolean))), + ).pipe(Effect.map((stdout) => trimAsciiWhitespace(stdout).split("\n").filter(Boolean))), runGitStdout( "GitVcsDriver.pullCurrentBranch.currentBranch", cwd, @@ -5233,7 +5236,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const readConfigValue: GitVcsDriver.GitVcsDriver["Service"]["readConfigValue"] = (cwd, key) => runGitStdout("GitVcsDriver.readConfigValue", cwd, ["config", "--get", key], true).pipe( - Effect.map((stdout) => stdout.trim()), + Effect.map(trimAsciiWhitespace), Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)), ); @@ -5279,7 +5282,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* input.cwd, ["rev-parse", "--symbolic-full-name", startPoint], { allowNonZeroExit: true }, - ).pipe(Effect.map((result) => (result.exitCode === 0 ? result.stdout.trim() : ""))); + ).pipe( + Effect.map((result) => (result.exitCode === 0 ? trimAsciiWhitespace(result.stdout) : "")), + ); if (!startRef.startsWith("refs/remotes/")) return; yield* executeGitWithStableDiagnostics( `${operation}.track`, @@ -5326,7 +5331,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ? { baseRef: `refs/remotes/${remoteName}/${refName}`, branchName: refName } : null; } - const ref = result.stdout.trim(); + const ref = trimAsciiWhitespace(result.stdout); if (ref.startsWith("refs/heads/")) { const branchName = ref.slice("refs/heads/".length); return { baseRef: ref, branchName }; @@ -6897,7 +6902,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const refName = yield* runGitStdout("GitVcsDriver.switchRef.currentBranch", input.cwd, [ "branch", "--show-current", - ]).pipe(Effect.map((stdout) => stdout.trim() || null)); + ]).pipe(Effect.map((stdout) => trimAsciiWhitespace(stdout) || null)); return { refName }; }, @@ -6937,7 +6942,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* Effect.map((stdout) => { const branchNames: Array = []; for (const line of stdout.split("\n")) { - const branchName = line.trim(); + const branchName = trimAsciiWhitespace(line); if (branchName.length > 0) { branchNames.push(branchName); } diff --git a/packages/contracts/src/baseSchemas.ts b/packages/contracts/src/baseSchemas.ts index d8137fc8ca9ec..be27f15c58753 100644 --- a/packages/contracts/src/baseSchemas.ts +++ b/packages/contracts/src/baseSchemas.ts @@ -28,6 +28,39 @@ const isNonBlank = Schema.makeFilter((value: string) => value.trim().length > 0, }); export const TrimmedNonEmptyString = TrimmedString.check(isNonBlank); +// Git forbids ASCII space and control characters in ref names but allows Unicode whitespace such +// as U+00A0 and U+3000, which `String.prototype.trim` would strip from a name's edges. +export function trimAsciiWhitespace(value: string): string { + let start = 0; + let end = value.length; + while (start < end && isAsciiWhitespace(value.charCodeAt(start))) start++; + while (end > start && isAsciiWhitespace(value.charCodeAt(end - 1))) end--; + return end - start === value.length ? value : value.slice(start, end); +} + +function isAsciiWhitespace(code: number): boolean { + return code === 0x20 || (code >= 0x09 && code <= 0x0d); +} + +const isNonBlankGitRefName = Schema.makeFilter( + (value: string) => trimAsciiWhitespace(value).length > 0, + { + expected: "a non-blank string", + toJsonSchema: () => [{ minLength: 1 }, true], + arbitraryConstraint: { minLength: 1 }, + }, +); +/** A branch, ref or remote name. Unlike `TrimmedNonEmptyString`, it keeps Unicode whitespace. */ +export const GitRefName = Schema.String.pipe( + Schema.decodeTo( + Schema.String, + SchemaTransformation.transformEffect({ + decode: (value) => Effect.succeed(trimAsciiWhitespace(value)), + encode: (value) => Effect.succeed(trimAsciiWhitespace(value)), + }), + ), +).check(isNonBlankGitRefName); + export const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)); export const PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)); export const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 })); diff --git a/packages/contracts/src/git.test.ts b/packages/contracts/src/git.test.ts index ae7b260c368f9..8802b445e53ac 100644 --- a/packages/contracts/src/git.test.ts +++ b/packages/contracts/src/git.test.ts @@ -5,10 +5,18 @@ import { GitCommandError, GitPreparePullRequestThreadResult, GitRunStackedActionInput, + VcsCreateWorktreeInput, + VcsRef, } from "./git.ts"; +import { WorktreeMcpHandoffInput } from "./worktreeMcp.ts"; import { PullRequestDiffFileContentsInput } from "./pullRequest.ts"; import { ReviewDiffFileContentsInput } from "./review.ts"; +const encodeVcsRef = Schema.encodeUnknownSync(VcsRef); +const decodeVcsRef = Schema.decodeUnknownSync(VcsRef); +const encodeCreateWorktreeInput = Schema.encodeUnknownSync(VcsCreateWorktreeInput); +const decodeCreateWorktreeInput = Schema.decodeUnknownSync(VcsCreateWorktreeInput); +const decodeWorktreeHandoffInput = Schema.decodeUnknownSync(WorktreeMcpHandoffInput); const decodeGitCommandError = Schema.decodeUnknownSync(Schema.toCodecJson(GitCommandError)); const decodePreparePullRequestThreadResult = Schema.decodeUnknownSync( GitPreparePullRequestThreadResult, @@ -106,3 +114,28 @@ describe("Git file paths", () => { expect(encode(input)).toEqual(input); }); }); + +describe("Git ref names", () => { + it.each(["origin/release/v2\u3000", "\u00a0release", "\u3000"])( + "keeps Unicode whitespace at the edges of %j across the wire", + (name) => { + const ref = { name, upstreamRef: `refs/remotes/${name}`, current: false, isDefault: false }; + const wireRef = encodeVcsRef({ ...ref, worktreePath: null }); + expect(decodeVcsRef(wireRef)).toMatchObject(ref); + + const input = { cwd: "/repo", refName: name, newRefName: name, baseRefName: name }; + const wireInput = encodeCreateWorktreeInput({ ...input, path: null }); + expect(decodeCreateWorktreeInput(wireInput)).toMatchObject(input); + + const handoff = { branch: name, baseRef: name, startFromOrigin: true }; + expect(decodeWorktreeHandoffInput(handoff)).toEqual(handoff); + }, + ); + + it("still trims ASCII whitespace and rejects a blank name", () => { + expect( + decodeCreateWorktreeInput({ cwd: "/repo", refName: " \tmain\n", path: null }).refName, + ).toBe("main"); + expect(() => decodeCreateWorktreeInput({ cwd: "/repo", refName: " \t", path: null })).toThrow(); + }); +}); diff --git a/packages/contracts/src/git.ts b/packages/contracts/src/git.ts index 751f240f0709e..2faf0ffb8c248 100644 --- a/packages/contracts/src/git.ts +++ b/packages/contracts/src/git.ts @@ -1,6 +1,7 @@ import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import { + GitRefName, ForwardCompatibleOptional, NonNegativeInt, PositiveInt, @@ -81,11 +82,11 @@ const GitRunStackedActionToast = Schema.Struct({ export type GitRunStackedActionToast = typeof GitRunStackedActionToast.Type; export const VcsRef = Schema.Struct({ - name: TrimmedNonEmptyStringSchema, + name: GitRefName, isRemote: Schema.optional(Schema.Boolean), - remoteName: Schema.optional(TrimmedNonEmptyStringSchema), + remoteName: Schema.optional(GitRefName), // Full Git ref, for example refs/remotes/origin/feature. - upstreamRef: Schema.optional(TrimmedNonEmptyStringSchema), + upstreamRef: Schema.optional(GitRefName), current: Schema.Boolean, isDefault: Schema.Boolean, worktreePath: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr), @@ -94,14 +95,14 @@ export type VcsRef = typeof VcsRef.Type; const VcsWorktree = Schema.Struct({ path: TrimmedNonEmptyStringSchema, - refName: TrimmedNonEmptyStringSchema, + refName: GitRefName, }); const GitResolvedPullRequest = Schema.Struct({ number: PositiveInt, title: TrimmedNonEmptyStringSchema, url: Schema.String, - baseBranch: TrimmedNonEmptyStringSchema, - headBranch: TrimmedNonEmptyStringSchema, + baseBranch: GitRefName, + headBranch: GitRefName, state: GitPullRequestState, }); export type GitResolvedPullRequest = typeof GitResolvedPullRequest.Type; @@ -157,9 +158,9 @@ export type VcsListRefsInput = typeof VcsListRefsInput.Type; export const VcsCreateWorktreeInput = Schema.Struct({ cwd: TrimmedNonEmptyStringSchema, - refName: TrimmedNonEmptyStringSchema, - newRefName: Schema.optional(TrimmedNonEmptyStringSchema), - baseRefName: Schema.optional(TrimmedNonEmptyStringSchema), + refName: GitRefName, + newRefName: Schema.optional(GitRefName), + baseRefName: Schema.optional(GitRefName), path: Schema.NullOr(TrimmedNonEmptyStringSchema), }); export type VcsCreateWorktreeInput = typeof VcsCreateWorktreeInput.Type; @@ -187,19 +188,19 @@ export type VcsRemoveWorktreeInput = typeof VcsRemoveWorktreeInput.Type; export const VcsCreateRefInput = Schema.Struct({ cwd: TrimmedNonEmptyStringSchema, - refName: TrimmedNonEmptyStringSchema, + refName: GitRefName, switchRef: Schema.optional(Schema.Boolean), }); export type VcsCreateRefInput = typeof VcsCreateRefInput.Type; export const VcsCreateRefResult = Schema.Struct({ - refName: TrimmedNonEmptyStringSchema, + refName: GitRefName, }); export type VcsCreateRefResult = typeof VcsCreateRefResult.Type; export const VcsSwitchRefInput = Schema.Struct({ cwd: TrimmedNonEmptyStringSchema, - refName: TrimmedNonEmptyStringSchema, + refName: GitRefName, }); export type VcsSwitchRefInput = typeof VcsSwitchRefInput.Type; @@ -213,8 +214,8 @@ const VcsStatusChangeRequest = Schema.Struct({ number: PositiveInt, title: TrimmedNonEmptyStringSchema, url: Schema.String, - baseRef: TrimmedNonEmptyStringSchema, - headRef: TrimmedNonEmptyStringSchema, + baseRef: GitRefName, + headRef: GitRefName, state: VcsStatusChangeRequestState, isDraft: Schema.optional(Schema.Boolean), updatedAt: Schema.optional(Schema.NullOr(Schema.String)), @@ -225,7 +226,7 @@ const VcsStatusLocalShape = { sourceControlProvider: Schema.optional(SourceControlProviderInfo), hasPrimaryRemote: Schema.Boolean, isDefaultRef: Schema.Boolean, - refName: Schema.NullOr(TrimmedNonEmptyStringSchema), + refName: Schema.NullOr(GitRefName), hasWorkingTreeChanges: Schema.Boolean, workingTree: Schema.Struct({ // Absolute worktree root on the environment that every files[].path is @@ -243,7 +244,7 @@ const VcsStatusLocalShape = { }), branchChanges: Schema.optional( Schema.Struct({ - baseRef: Schema.NullOr(TrimmedNonEmptyStringSchema), + baseRef: Schema.NullOr(GitRefName), insertions: NonNegativeInt, deletions: NonNegativeInt, }), @@ -313,7 +314,7 @@ export type GitResolvePullRequestResult = typeof GitResolvePullRequestResult.Typ export const GitPreparePullRequestThreadResult = Schema.Struct({ pullRequest: GitResolvedPullRequest, - branch: TrimmedNonEmptyStringSchema, + branch: GitRefName, worktreePath: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr), /** False when local commits or edits prevented a reused worktree from reaching the PR head. */ isOnPullRequestHead: Schema.Boolean.pipe(Schema.withDecodingDefaultKey(Effect.succeed(true))), @@ -321,7 +322,7 @@ export const GitPreparePullRequestThreadResult = Schema.Struct({ export type GitPreparePullRequestThreadResult = typeof GitPreparePullRequestThreadResult.Type; export const VcsSwitchRefResult = Schema.Struct({ - refName: Schema.NullOr(TrimmedNonEmptyStringSchema), + refName: Schema.NullOr(GitRefName), }); export type VcsSwitchRefResult = typeof VcsSwitchRefResult.Type; @@ -329,7 +330,7 @@ export const GitRunStackedActionResult = Schema.Struct({ action: GitStackedAction, branch: Schema.Struct({ status: GitBranchStepStatus, - name: Schema.optional(TrimmedNonEmptyStringSchema), + name: Schema.optional(GitRefName), }), commit: Schema.Struct({ status: GitCommitStepStatus, @@ -338,16 +339,16 @@ export const GitRunStackedActionResult = Schema.Struct({ }), push: Schema.Struct({ status: GitPushStepStatus, - branch: Schema.optional(TrimmedNonEmptyStringSchema), - upstreamBranch: Schema.optional(TrimmedNonEmptyStringSchema), + branch: Schema.optional(GitRefName), + upstreamBranch: Schema.optional(GitRefName), setUpstream: Schema.optional(Schema.Boolean), }), pr: Schema.Struct({ status: GitPrStepStatus, url: Schema.optional(Schema.String), number: Schema.optional(PositiveInt), - baseBranch: Schema.optional(TrimmedNonEmptyStringSchema), - headBranch: Schema.optional(TrimmedNonEmptyStringSchema), + baseBranch: Schema.optional(GitRefName), + headBranch: Schema.optional(GitRefName), title: Schema.optional(TrimmedNonEmptyStringSchema), }), toast: GitRunStackedActionToast, @@ -356,8 +357,8 @@ export type GitRunStackedActionResult = typeof GitRunStackedActionResult.Type; export const VcsPullResult = Schema.Struct({ status: Schema.Literals(["pulled", "skipped_up_to_date"]), - refName: TrimmedNonEmptyStringSchema, - upstreamRef: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr), + refName: GitRefName, + upstreamRef: GitRefName.pipe(Schema.NullOr), }); export type VcsPullResult = typeof VcsPullResult.Type; @@ -430,8 +431,8 @@ export class GitPullRequestMaterializationError extends Schema.TaggedError