Skip to content
TypeScript

refactor(source-control): git and process behaviour comes from forge hooks (#23995)

Julius Marminge39f6e2b2a226
diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts
index 660e2de9cbd..d3ebc2daa1f 100644
--- a/apps/server/src/git/GitManager.test.ts
+++ b/apps/server/src/git/GitManager.test.ts
@@ -3053,6 +3053,47 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
}),
);
+ it.effect("hands the branch base to the host when a failed first push is retried", () =>
+ Effect.gen(function* () {
+ const repoDir = yield* makeTempDir("t3code-git-manager-");
+ yield* initRepo(repoDir);
+ const remoteDir = yield* createBareRemote();
+ yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
+ yield* runGit(repoDir, ["push", "-u", "origin", "HEAD:main"]);
+ yield* runGit(repoDir, ["checkout", "-b", "feature/retried-push", "--track", "origin/main"]);
+ NodeFS.writeFileSync(NodePath.join(repoDir, "retried.txt"), "retried\n");
+ yield* runGit(repoDir, ["add", "retried.txt"]);
+ yield* runGit(repoDir, ["commit", "-m", "Retried push"]);
+ const rejectOnce = NodePath.join(remoteDir, "reject-once");
+ NodeFS.writeFileSync(rejectOnce, "");
+ NodeFS.writeFileSync(
+ NodePath.join(remoteDir, "hooks", "pre-receive"),
+ `#!/bin/sh\nif [ -f "${rejectOnce}" ]; then rm "${rejectOnce}"; exit 1; fi\n`,
+ { mode: 0o755 },
+ );
+
+ const recorded: Array<{ branch: string; baseBranch: string }> = [];
+ const { service } = createGitHubProviderWithFakeGh();
+ const { manager } = yield* makeManager({
+ sourceControlProvider: {
+ ...service,
+ recordBranchBase: ({ branch, baseBranch }) =>
+ Effect.sync(() => {
+ recorded.push({ branch, baseBranch });
+ }),
+ },
+ });
+ const failed = yield* runStackedAction(manager, { cwd: repoDir, action: "push" }).pipe(
+ Effect.flip,
+ );
+ expect(failed).toBeDefined();
+ const result = yield* runStackedAction(manager, { cwd: repoDir, action: "push" });
+
+ expect(result.push.status).toBe("pushed");
+ expect(recorded).toEqual([{ branch: "feature/retried-push", baseBranch: "main" }]);
+ }),
+ );
+
it.effect("create_pr targets the remote default branch when it is not main", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -4576,63 +4617,6 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
}),
);
- it.effect("derives fork repository identity from PR URL when GitHub omits nameWithOwner", () =>
- Effect.gen(function* () {
- const repoDir = yield* makeTempDir("t3code-git-manager-");
- yield* initRepo(repoDir);
- const originDir = yield* createBareRemote();
- const forkDir = yield* createBareRemote();
- yield* runGit(repoDir, ["remote", "add", "origin", originDir]);
- yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
- yield* runGit(repoDir, ["remote", "add", "binbandit-seed", forkDir]);
- yield* runGit(repoDir, ["checkout", "-b", "fix/git-action-default-without-origin"]);
- NodeFS.writeFileSync(NodePath.join(repoDir, "derived-fork.txt"), "derived fork\n");
- yield* runGit(repoDir, ["add", "derived-fork.txt"]);
- yield* runGit(repoDir, ["commit", "-m", "Derived fork PR branch"]);
- yield* runGit(repoDir, [
- "push",
- "-u",
- "binbandit-seed",
- "fix/git-action-default-without-origin",
- ]);
- yield* runGit(repoDir, ["checkout", "main"]);
- yield* runGit(repoDir, ["branch", "-D", "fix/git-action-default-without-origin"]);
-
- const { manager } = yield* makeManager({
- ghScenario: {
- pullRequest: {
- number: 642,
- title: "fix: use commit as the default git action without origin",
- url: "https://github.com/pingdotgg/t3code/pull/642",
- baseRefName: "main",
- headRefName: "fix/git-action-default-without-origin",
- state: "open",
- isCrossRepository: true,
- headRepositoryOwnerLogin: "binbandit",
- },
- repositoryCloneUrls: {
- "binbandit/t3code": {
- url: forkDir,
- sshUrl: forkDir,
- },
- },
- },
- });
-
- const result = yield* preparePullRequestThread(manager, {
- cwd: repoDir,
- reference: "642",
- mode: "local",
- });
-
- expect(result.branch).toBe("fix/git-action-default-without-origin");
- expect(result.worktreePath).toBeNull();
- expect(
- (yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"])).stdout.trim(),
- ).toBe("binbandit-seed/fix/git-action-default-without-origin");
- }),
- );
-
it.effect("refreshes a reused PR worktree onto the updated pull request head", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -5058,6 +5042,49 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
}),
);
+ it.effect("creates a merge request worktree from the host's own head ref", () =>
+ Effect.gen(function* () {
+ const repoDir = yield* makeTempDir("t3code-git-manager-");
+ yield* initRepo(repoDir);
+ const remoteDir = yield* createBareRemote();
+ yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
+ yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
+ yield* runGit(repoDir, ["checkout", "-b", "feature/mr-ref-only"]);
+ NodeFS.writeFileSync(NodePath.join(repoDir, "mr.txt"), "merge request\n");
+ yield* runGit(repoDir, ["add", "mr.txt"]);
+ yield* runGit(repoDir, ["commit", "-m", "Merge request ref only"]);
+ const head = (yield* runGit(repoDir, ["rev-parse", "HEAD"])).stdout.trim();
+ yield* runGit(repoDir, ["push", "origin", "HEAD:refs/merge-requests/93/head"]);
+ yield* runGit(repoDir, ["checkout", "main"]);
+ yield* runGit(repoDir, ["branch", "-D", "feature/mr-ref-only"]);
+
+ const { service } = createGitHubProviderWithFakeGh({
+ pullRequest: {
+ number: 93,
+ title: "Merge request ref only",
+ url: "https://gitlab.com/pingdotgg/codething-mvp/-/merge_requests/93",
+ baseRefName: "main",
+ headRefName: "feature/mr-ref-only",
+ state: "open",
+ },
+ });
+ const { manager } = yield* makeManager({
+ sourceControlProvider: { ...service, kind: SourceControlProviderKind.make("gitlab") },
+ });
+
+ const result = yield* preparePullRequestThread(manager, {
+ cwd: repoDir,
+ reference: "93",
+ mode: "worktree",
+ });
+
+ expect(result.isOnPullRequestHead).toBe(true);
+ expect(
+ (yield* runGit(result.worktreePath as string, ["rev-parse", "HEAD"])).stdout.trim(),
+ ).toBe(head);
+ }),
+ );
+
it.effect("preserves an unrelated local branch and upstream that share the fork head name", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts
index 0e517a53ae9..6902e84777b 100644
--- a/apps/server/src/git/GitManager.ts
+++ b/apps/server/src/git/GitManager.ts
@@ -1,4 +1,3 @@
-import { SourceControlProviderKind } from "@t3tools/contracts";
import * as Arr from "effect/Array";
import * as Cache from "effect/Cache";
import * as Clock from "effect/Clock";
@@ -54,16 +53,11 @@ import {
sanitizeBranchFragment,
sanitizeFeatureBranchName,
} from "@t3tools/shared/git";
+import { isSshRemoteUrl } from "@t3tools/shared/sourceControl";
import {
- getChangeRequestTerminologyForKind,
- isSshRemoteUrl,
type ChangeRequestTerminology,
-} from "@t3tools/shared/sourceControl";
-import * as HostProcess from "@t3tools/shared/HostProcess";
-import {
- parseGitHubRepositorySelector,
- resolveGitHubRepository,
-} from "@t3tools/source-control-github/server/gitHubRepositoryResolution";
+ UNKNOWN_SOURCE_CONTROL_CLIENT,
+} from "@t3tools/source-control-core/client/definition";
import {
normalizeThreadPullRequestKey,
threadPullRequestKeyOf,
@@ -255,48 +249,15 @@ interface BranchHeadContext {
}
export function pullRequestRepositoryKey(value: string): string | null {
- try {
- const url = new URL(value);
- const match =
- /^(.*)(?:\/pulls?\/|\/-\/merge_requests\/|\/pull-requests\/|\/pullrequest\/)\d+(?:\/.*)?$/iu.exec(
- url.pathname,
- );
- if (match?.[1] === undefined) return null;
- url.pathname = match[1];
- url.search = "";
- url.hash = "";
- return sourceControlClients.repositoryKeyFromRemote(url.toString());
- } catch {
- return null;
- }
+ const repositoryUrl = sourceControlClients.parseChangeRequestUrl(value)?.link.repositoryUrl;
+ return repositoryUrl === undefined
+ ? null
+ : sourceControlClients.repositoryKeyFromRemote(repositoryUrl);
}
-function parseRepositoryNameFromPullRequestUrl(url: string): string | null {
- const trimmed = url.trim();
- const match = /^https?:\/\/[^/]+\/[^/]+\/([^/]+)\/pull\/\d+(?:\/.*)?$/i.exec(trimmed);
- const repositoryName = match?.[1]?.trim() ?? "";
- return repositoryName.length > 0 ? repositoryName : null;
-}
-
-function resolveHeadRepositoryNameWithOwner(
- pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,
-): string | null {
- const explicitRepository = pullRequest.headRepositoryNameWithOwner?.trim() ?? "";
- if (explicitRepository.length > 0) {
- return explicitRepository;
- }
-
- if (!pullRequest.isCrossRepository) {
- return null;
- }
-
- const ownerLogin = pullRequest.headRepositoryOwnerLogin?.trim() ?? "";
- const repositoryName = parseRepositoryNameFromPullRequestUrl(pullRequest.url);
- if (ownerLogin.length === 0 || !repositoryName) {
- return null;
- }
-
- return `${ownerLogin}/${repositoryName}`;
+/** Null when the host did not name the repository the head lives in. */
+function resolveHeadRepositoryNameWithOwner(pullRequest: PullRequestHeadRemoteInfo): string | null {
+ return normalizeOptionalString(pullRequest.headRepositoryNameWithOwner);
}
function resolvePullRequestWorktreeLocalBranchName(
@@ -331,7 +292,8 @@ function parseRepositoryOwnerLogin(nameWithOwner: string | null): string | null
if (trimmed.length === 0) {
return null;
}
- // GitLab reports the top-level group as owner. The full path distinguishes subgroups.
+ // The first segment only: a nested path's owner is its top-level group. The full path
+ // distinguishes subgroups.
const [ownerLogin] = trimmed.split("/");
const normalizedOwnerLogin = ownerLogin?.trim() ?? "";
return normalizedOwnerLogin.length > 0 ? normalizedOwnerLogin : null;
@@ -352,27 +314,6 @@ function normalizeOptionalOwnerLogin(value: string | null | undefined): string |
return normalized ? normalized.toLowerCase() : null;
}
-function resolvePullRequestHeadRepositoryNameWithOwner(
- pr: PullRequestHeadRemoteInfo & { url: string },
-) {
- const explicitRepository = normalizeOptionalString(pr.headRepositoryNameWithOwner);
- if (explicitRepository) {
- return explicitRepository;
- }
-
- if (!pr.isCrossRepository) {
- return null;
- }
-
- const ownerLogin = normalizeOptionalString(pr.headRepositoryOwnerLogin);
- const repositoryName = parseRepositoryNameFromPullRequestUrl(pr.url);
- if (!ownerLogin || !repositoryName) {
- return null;
- }
-
- return `${ownerLogin}/${repositoryName}`;
-}
-
interface PullRequestHeadIdentity {
readonly repositoryNameWithOwner: string | null;
readonly ownerLogin: string | null;
@@ -394,7 +335,7 @@ function resolveExpectedHeadIdentity(
function resolvePullRequestHeadIdentity(pr: PullRequestInfo): PullRequestHeadIdentity {
const repositoryNameWithOwner = normalizeOptionalRepositoryNameWithOwner(
- resolvePullRequestHeadRepositoryNameWithOwner(pr),
+ resolveHeadRepositoryNameWithOwner(pr),
);
return {
repositoryNameWithOwner,
@@ -634,11 +575,6 @@ function headBranchProbe(
);
}
-/** A URL's host as `new URL` reads it: lowercased, any non-default port kept, `:443` dropped. */
-function urlHost(url: string): string | null {
- return URL.canParse(url) ? new URL(url).host : null;
-}
-
function appendUnique(values: string[], next: string | null | undefined): void {
const trimmed = next?.trim() ?? "";
if (trimmed.length === 0 || values.includes(trimmed)) {
@@ -726,9 +662,16 @@ export const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
- const environment = yield* HostProcess.Environment;
const sourceControlProvider = (cwd: string) => sourceControlProviders.resolve({ cwd });
+ const changeRequestTermsFor = Effect.fn("GitManager.changeRequestTermsFor")(function* (
+ cwd: string,
+ ) {
+ return yield* sourceControlProvider(cwd).pipe(
+ Effect.map((provider) => sourceControlClients.get(provider.kind).changeRequest),
+ Effect.orElseSucceed(() => UNKNOWN_SOURCE_CONTROL_CLIENT.changeRequest),
+ );
+ });
const serverSettingsService = yield* ServerSettings.ServerSettingsService;
const threads = yield* ProjectionStore.ProjectionStoreV2;
const projects = yield* ProjectStore.ProjectStoreV2;
@@ -775,6 +718,31 @@ export const make = Effect.gen(function* () {
),
),
);
+ // Hands the base T3 recorded for a branch to the host, whose own tools may keep it elsewhere.
+ // Best-effort: nothing T3 does reads it back from there.
+ const shareBranchBase = Effect.fn("GitManager.shareBranchBase")(function* (
+ cwd: string,
+ branch: string,
+ ) {
+ const baseBranch = yield* gitCore
+ .readBranchBase(cwd, branch)
+ .pipe(Effect.orElseSucceed(() => null));
+ if (baseBranch === null) return;
+ const provider = yield* sourceControlProvider(cwd).pipe(Effect.orElseSucceed(() => null));
+ yield* provider?.recordBranchBase?.({ cwd, branch, baseBranch }) ?? Effect.void;
+ });
+ // Publishing a branch that tracks its base records that base first, even when the push then
+ // fails, so the host hears of it after every successful push rather than the first attempt.
+ const pushCurrentBranch = Effect.fn("GitManager.pushCurrentBranch")(function* (
+ cwd: string,
+ branch: string | null,
+ ) {
+ const result = yield* gitCore.pushCurrentBranch(cwd, branch);
+ if (result.status === "pushed" && result.branch) {
+ yield* shareBranchBase(cwd, result.branch);
+ }
+ return result;
+ });
const readWorktreesDirectory = serverSettingsService.getSettings.pipe(
Effect.map((settings) => settings.worktreesDirectory),
Effect.orElseSucceed(() => ""),
@@ -790,7 +758,15 @@ export const make = Effect.gen(function* () {
Effect.orElseSucceed(() => null),
);
const worktreesDirectory = yield* readWorktreesDirectory;
- return yield* gitCore.createWorktree(input, { worktreesDirectory, ...options, submodules });
+ const result = yield* gitCore.createWorktree(input, {
+ worktreesDirectory,
+ ...options,
+ submodules,
+ });
+ if (input.newRefName && input.baseRefName) {
+ yield* shareBranchBase(input.cwd, input.newRefName);
+ }
+ return result;
});
const readRepositoryInstructions = Effect.fn("GitManager.readRepositoryInstructions")(
@@ -990,6 +966,31 @@ export const make = Effect.gen(function* () {
),
);
+ // The kind comes from the provider, not the remote alone: an unrecognised remote can resolve
+ // to a known host.
+ const changeRequestHeadRef = Effect.fn("GitManager.changeRequestHeadRef")(function* (
+ cwd: string,
+ number: number,
+ ) {
+ const provider = yield* sourceControlProvider(cwd);
+ const ref = sourceControlClients.get(provider.kind).changeRequestHeadRef?.(number);
+ if (ref === undefined) {
+ return yield* new GitManagerError({
+ operation: "changeRequestHeadRef",
+ cwd,
+ detail: "This host publishes no ref for a change request's head.",
+ });
+ }
+ return ref;
+ });
+
+ const fetchChangeRequestHeadIntoBranch = Effect.fn("GitManager.fetchChangeRequestHeadIntoBranch")(
+ function* (cwd: string, number: number, branch: string) {
+ const ref = yield* changeRequestHeadRef(cwd, number);
+ yield* gitCore.fetchRefIntoBranch({ cwd, ref, branch });
+ },
+ );
+
const materializePullRequestHeadBranchBase = Effect.fn("materializePullRequestHeadBranch")(
function* (
cwd: string,
@@ -999,47 +1000,38 @@ export const make = Effect.gen(function* () {
const repositoryNameWithOwner = resolveHeadRepositoryNameWithOwner(pullRequest) ?? "";
if (repositoryNameWithOwner.length === 0) {
- yield* gitCore
- .fetchPullRequestBranch({
- cwd,
- prNumber: pullRequest.number,
- branch: localBranch,
- })
- .pipe(
- // Azure DevOps, GitLab and Bitbucket publish no `refs/pull/<n>/head`. A head in the
- // same repository is a branch on the primary remote, so it is fetched by name instead,
- // but only when that remote is the pull request's own repository: Azure finds a pull
- // request by number anywhere in the organization. Only while it is open, too: the
- // branch of a closed one may have moved on past the head it was closed with.
- Effect.catch((cause) =>
- pullRequest.isCrossRepository === true || pullRequest.state !== "open"
- ? Effect.fail(cause)
- : Effect.gen(function* () {
- const remoteName = yield* gitCore.resolvePrimaryRemoteName(cwd);
- const remoteUrl = yield* gitCore.readConfigValue(
- cwd,
- `remote.${remoteName}.url`,
- );
- const pullRequestKey = pullRequestRepositoryKey(pullRequest.url);
- if (
- remoteUrl === null ||
- pullRequestKey === null ||
- sourceControlClients.canonicalRepositoryKey(pullRequestKey) !==
- sourceControlClients.canonicalRepositoryKey(
- sourceControlClients.repositoryKeyFromRemote(remoteUrl),
- )
- ) {
- return yield* cause;
- }
- yield* gitCore.fetchRemoteBranch({
- cwd,
- remoteName,
- remoteBranch: pullRequest.headBranch,
- localBranch,
- });
- }),
- ),
- );
+ yield* fetchChangeRequestHeadIntoBranch(cwd, pullRequest.number, localBranch).pipe(
+ // Without the host's head ref, a head in the same repository is a branch on the
+ // primary remote, so it is fetched by name instead, but only when that remote is the
+ // pull request's own repository: a host can find a change request by number outside
+ // the checkout's repository. Only while it is open, too: the branch of a closed one
+ // may have moved on past the head it was closed with.
+ Effect.catch((cause) =>
+ pullRequest.isCrossRepository === true || pullRequest.state !== "open"
+ ? Effect.fail(cause)
+ : Effect.gen(function* () {
+ const remoteName = yield* gitCore.resolvePrimaryRemoteName(cwd);
+ const remoteUrl = yield* gitCore.readConfigValue(cwd, `remote.${remoteName}.url`);
+ const pullRequestKey = pullRequestRepositoryKey(pullRequest.url);
+ if (
+ remoteUrl === null ||
+ pullRequestKey === null ||
+ sourceControlClients.canonicalRepositoryKey(pullRequestKey) !==
+ sourceControlClients.canonicalRepositoryKey(
+ sourceControlClients.repositoryKeyFromRemote(remoteUrl),
+ )
+ ) {
+ return yield* cause;
+ }
+ yield* gitCore.fetchRemoteBranch({
+ cwd,
+ remoteName,
+ remoteBranch: pullRequest.headBranch,
+ localBranch,
+ });
+ }),
+ ),
+ );
return;
}
@@ -1081,29 +1073,23 @@ export const make = Effect.gen(function* () {
) =>
materializePullRequestHeadBranchBase(cwd, pullRequest, localBranch).pipe(
Effect.catch((primaryCause) =>
- gitCore
- .fetchPullRequestBranch({
- cwd,
- prNumber: pullRequest.number,
- branch: localBranch,
- })
- .pipe(
- Effect.mapError(
- (fallbackCause) =>
- new GitPullRequestMaterializationError({
- cwd,
- pullRequestNumber: pullRequest.number,
- headRepository: resolveHeadRepositoryNameWithOwner(pullRequest),
- headBranch: pullRequest.headBranch,
- localBranch,
- cause: new AggregateError(
- [primaryCause, fallbackCause],
- `Repository-head and pull-request-ref fetches both failed for pull request #${pullRequest.number}.`,
- { cause: primaryCause },
- ),
- }),
- ),
+ fetchChangeRequestHeadIntoBranch(cwd, pullRequest.number, localBranch).pipe(
+ Effect.mapError(
+ (fallbackCause) =>
+ new GitPullRequestMaterializationError({
+ cwd,
+ pullRequestNumber: pullRequest.number,
+ headRepository: resolveHeadRepositoryNameWithOwner(pullRequest),
+ headBranch: pullRequest.headBranch,
+ localBranch,
+ cause: new AggregateError(
+ [primaryCause, fallbackCause],
+ `Repository-head and pull-request-ref fetches both failed for pull request #${pullRequest.number}.`,
+ { cause: primaryCause },
+ ),
+ }),
),
+ ),
),
);
const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
@@ -1437,39 +1423,27 @@ export const make = Effect.gen(function* () {
const readConfigValueNullable = (cwd: string, key: string) =>
gitCore.readConfigValue(cwd, key).pipe(Effect.orElseSucceed(() => null));
- // Whether the GitHub provider creates PRs in the only remote. It picks GH_REPO when that
- // parses, else what resolveGitHubRepository makes of the remote and its gh-resolved mark from
- // `gh repo set-default`, given the host the provider's context gets from the remote URL. An
- // HTTPS remote keeps a non-default port there, and the provider then ignores the mark. With no
- // answer at all, the provider falls back to the remote itself.
+ // Whether the remote's host creates change requests in the only remote. A host's tools can let
+ // configuration outside the remotes name another repository; the remote itself otherwise.
const targetsOnlyRemote = Effect.fn("targetsOnlyRemote")(function* (
cwd: string,
remoteName: string,
remote: { readonly remoteUrl: string | null; readonly repositoryNameWithOwner: string | null },
) {
- const baseUrl =
- remote.remoteUrl === null
- ? undefined
- : sourceControlClients.recognizeRemote(remote.remoteUrl)?.baseUrl;
- const host = baseUrl === undefined ? null : urlHost(baseUrl);
- const repository = remote.repositoryNameWithOwner?.toLowerCase();
- const fromEnvironment = parseGitHubRepositorySelector(environment.GH_REPO ?? "", host ?? "");
- if (fromEnvironment !== null) {
- const { host: targetHost, owner, name } = fromEnvironment;
- return (
- host !== null &&
- urlHost(`https://${targetHost}`) === host &&
- `${owner}/${name}`.toLowerCase() === repository
- );
- }
- const mark = yield* readConfigValueNullable(cwd, `remote.${remoteName}.gh-resolved`);
- const { locator } = resolveGitHubRepository({
- remotes: remote.remoteUrl === null ? "" : `${remoteName}\t${remote.remoteUrl} (fetch)`,
- resolved: mark === null ? "" : `remote.${remoteName}.gh-resolved ${mark}`,
- hostHint: host ?? undefined,
- defaultHost: host ?? "github.com",
+ const provider =
+ remote.remoteUrl === null ? null : sourceControlClients.recognizeRemote(remote.remoteUrl);
+ if (remote.remoteUrl === null || provider === null) return true;
+ const context = { provider, remoteName, remoteUrl: remote.remoteUrl };
+ const handle = yield* sourceControlProviders
+ .resolveHandle({ cwd, context })
+ .pipe(Effect.orElseSucceed(() => null));
+ const createsChangeRequestsIn = handle?.provider.createsChangeRequestsIn;
+ if (createsChangeRequestsIn === undefined) return true;
+ return yield* createsChangeRequestsIn({
+ cwd,
+ context: handle?.context ?? context,
+ repository: remote.repositoryNameWithOwner,
});
- return locator === null || `${locator.owner}/${locator.name}`.toLowerCase() === repository;
});
const resolveHostingProvider = Effect.fn("resolveHostingProvider")(function* (
@@ -1564,9 +1538,9 @@ export const make = Effect.gen(function* () {
remoteName,
);
- // With no origin to compare against, the only remote is the repository gh targets
- // unless GH_REPO or `gh repo set-default` (gh-resolved) names another, so a branch on it
- // is not a fork. With several remotes, or with that other target, it may still be a fork.
+ // With no origin to compare against, the only remote is the repository change requests
+ // are created in unless the host's own configuration names another, so a branch on it is
+ // not a fork. With several remotes, or with that other target, it may still be a fork.
const isOnlyRemote =
remoteName !== null &&
remoteName !== "origin" &&
@@ -1928,12 +1902,7 @@ export const make = Effect.gen(function* () {
cwd: string,
result: Pick<GitRunStackedActionResult, "action" | "branch" | "commit" | "push" | "pr">,
) {
- const terms = yield* sourceControlProvider(cwd).pipe(
- Effect.map((provider) => getChangeRequestTerminologyForKind(provider.kind)),
- Effect.orElseSucceed(() =>
- getChangeRequestTerminologyForKind(SourceControlProviderKind.make("unknown")),
- ),
- );
+ const terms = yield* changeRequestTermsFor(cwd);
const summary = summarizeGitActionResult(result, terms);
let latestOpenPr: PullRequestInfo | null = null;
let currentBranchIsDefault = false;
@@ -2032,7 +2001,7 @@ export const make = Effect.gen(function* () {
if (configuredBranch) return { baseBranch: configuredBranch, baseRef: configuredRef };
}
- const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`);
+ const configured = yield* gitCore.readBranchBase(cwd, branch);
if (configured) {
const localRef = configured.startsWith("refs/") ? configured : `refs/heads/${configured}`;
const localBranch = yield* gitCore.resolveBranchName(cwd, localRef);
@@ -2278,7 +2247,7 @@ export const make = Effect.gen(function* () {
emit: GitActionProgressEmitter,
) {
const provider = yield* sourceControlProvider(cwd);
- const terms = getChangeRequestTerminologyForKind(provider.kind);
+ const terms = sourceControlClients.get(provider.kind).changeRequest;
const details = yield* gitCore.statusDetails(cwd);
const branch = details.branch ?? fallbackBranch;
if (!branch) {
@@ -2871,53 +2840,52 @@ export const make = Effect.gen(function* () {
yield* ensureExistingWorktreeUpstream(worktreePath);
- const refreshed = yield* gitCore
- // The pull request's own ref, because it is the only thing that certainly names its
- // head. The branch's upstream does not: configuring it is best-effort, so a branch cut
- // from `origin/main` whose head branch has since been deleted still resolves — and
- // following it would move the checkout onto main and call that the pull request.
- .fetchPullRequestHeadCommit({ cwd: worktreePath, prNumber: pullRequest.number })
- .pipe(
- // A host that publishes no `refs/pull/<n>/head` leaves the remote-tracking branch,
- // taken only where it is the head branch's own rather than whatever the checkout
- // happened to be cut from.
- Effect.catch(() =>
- Effect.gen(function* () {
- const details = yield* gitCore.statusDetails(worktreePath);
- if (
- details.upstreamRef === null ||
- !details.upstreamRef.endsWith(`/${pullRequest.headBranch}`)
- ) {
- return yield* new GitManagerError({
- operation: "preparePullRequestThread",
- cwd: worktreePath,
- detail: "The pull request head could not be resolved for this checkout.",
- });
- }
- return yield* gitCore.resolveCommit({
+ // The pull request's own ref, because it is the only thing that certainly names its
+ // head. The branch's upstream does not: configuring it is best-effort, so a branch cut
+ // from `origin/main` whose head branch has since been deleted still resolves — and
+ // following it would move the checkout onto main and call that the pull request.
+ const refreshed = yield* changeRequestHeadRef(worktreePath, pullRequest.number).pipe(
+ Effect.flatMap((ref) => gitCore.fetchRefCommit({ cwd: worktreePath, ref })),
+ // A host that publishes no head ref leaves the remote-tracking branch,
+ // taken only where it is the head branch's own rather than whatever the checkout
+ // happened to be cut from.
+ Effect.catch(() =>
+ Effect.gen(function* () {
+ const details = yield* gitCore.statusDetails(worktreePath);
+ if (
+ details.upstreamRef === null ||
+ !details.upstreamRef.endsWith(`/${pullRequest.headBranch}`)
+ ) {
+ return yield* new GitManagerError({
+ operation: "preparePullRequestThread",
cwd: worktreePath,
- revision: details.upstreamRef,
+ detail: "The pull request head could not be resolved for this checkout.",
});
- }),
- ),
- Effect.flatMap((target) =>
- gitCore.refreshCheckedOutBranch({
+ }
+ return yield* gitCore.resolveCommit({
cwd: worktreePath,
- targetCommit: target.commitSha,
- resetWhenHeadCommit: upstreamCommitBeforeFetch,
- }),
- ),
- Effect.catch((error) =>
- Effect.logWarning(
- "GitManager.preparePullRequestThread reused worktree refresh failed",
- {
- worktreePath,
- localBranch: localPullRequestBranch,
- cause: error,
- },
- ).pipe(Effect.as({ moved: false, onTarget: false })),
- ),
- );
+ revision: details.upstreamRef,
+ });
+ }),
+ ),
+ Effect.flatMap((target) =>
+ gitCore.refreshCheckedOutBranch({
+ cwd: worktreePath,
+ targetCommit: target.commitSha,
+ resetWhenHeadCommit: upstreamCommitBeforeFetch,
+ }),
+ ),
+ Effect.catch((error) =>
+ Effect.logWarning(
+ "GitManager.preparePullRequestThread reused worktree refresh failed",
+ {
+ worktreePath,
+ localBranch: localPullRequestBranch,
+ cause: error,
+ },
+ ).pipe(Effect.as({ moved: false, onTarget: false })),
+ ),
+ );
// Only when the checkout actually moved: another thread may be running in this worktree,
// and re-running the setup script under it buys nothing when the code did not change.
@@ -3189,14 +3157,7 @@ export const make = Effect.gen(function* () {
const currentBranch = branchStep.name ?? initialStatus.branch;
const commitAction = isCommitAction(input.action) ? input.action : null;
- const changeRequestTerms = wantsPr
- ? yield* sourceControlProvider(input.cwd).pipe(
- Effect.map((provider) => getChangeRequestTerminologyForKind(provider.kind)),
- Effect.orElseSucceed(() =>
- getChangeRequestTerminologyForKind(SourceControlProviderKind.make("unknown")),
- ),
- )
- : null;
+ const changeRequestTerms = wantsPr ? yield* changeRequestTermsFor(input.cwd) : null;
const commit = commitAction
? yield* Ref.set(currentPhase, Option.some("commit")).pipe(
@@ -3225,7 +3186,7 @@ export const make = Effect.gen(function* () {
})
.pipe(
Effect.tap(() => Ref.set(currentPhase, Option.some("push"))),
- Effect.flatMap(() => gitCore.pushCurrentBranch(input.cwd, currentBranch)),
+ Effect.flatMap(() => pushCurrentBranch(input.cwd, currentBranch)),
)
: { status: "skipped_not_requested" as const };
diff --git a/apps/server/src/pullRequest/PullRequestReviewGuideService.test.ts b/apps/server/src/pullRequest/PullRequestReviewGuideService.test.ts
index 76f703123c2..b4dd965570a 100644
--- a/apps/server/src/pullRequest/PullRequestReviewGuideService.test.ts
+++ b/apps/server/src/pullRequest/PullRequestReviewGuideService.test.ts
@@ -94,6 +94,7 @@ const makeRepositories = Effect.gen(function* () {
const detail = (workspaceRoot: string, headSha: string): PullRequestDetail =>
({
+ provider: "github",
number: 7,
title: "Add the feature",
body: "Adds the feature.",
@@ -385,13 +386,7 @@ it.layer(layerBase, { excludeTestServices: true })("PullRequestReviewGuideServic
name: "a head no source has",
reportedHead: () => "e".repeat(40),
shadow: "none",
- expected: [
- "local objects:",
- "the commit:",
- "branch feature:",
- "refs/pull/7/head:",
- "refs/merge-requests/7/head:",
- ],
+ expected: ["local objects:", "the commit:", "branch feature:", "refs/pull/7/head:"],
},
])("refuses to write a guide for $name", ({ reportedHead, shadow, expected }) =>
Effect.scoped(
@@ -415,6 +410,8 @@ it.layer(layerBase, { excludeTestServices: true })("PullRequestReviewGuideServic
assert.strictEqual(result.run?._tag, "Failed");
const detail = result.run?._tag === "Failed" ? result.run.detail : "";
for (const part of expected) assert.include(detail, part);
+ // Only the host's own head ref is tried.
+ assert.notInclude(detail, "refs/merge-requests/");
assert.deepStrictEqual(run.observed, []);
assert.isFalse(run.fetchedRefs.some((ref) => ref.startsWith("-")));
const fs = yield* FileSystem.FileSystem;
diff --git a/apps/server/src/pullRequest/PullRequestReviewGuideService.ts b/apps/server/src/pullRequest/PullRequestReviewGuideService.ts
index e78d850d683..5ae93c8827b 100644
--- a/apps/server/src/pullRequest/PullRequestReviewGuideService.ts
+++ b/apps/server/src/pullRequest/PullRequestReviewGuideService.ts
@@ -251,6 +251,7 @@ const make = Effect.gen(function* () {
),
);
const fetchAndResolve = (ref: string) => fetch([ref]).pipe(Effect.andThen(resolveHead));
+ const headRef = sourceControlClients.get(detail.provider).changeRequestHeadRef?.(number);
const branchRef = `refs/heads/${branch}`;
const checkBranch = git.execute({
operation: "PullRequestReviewGuideService.checkHeadBranch",
@@ -266,11 +267,7 @@ const make = Effect.gen(function* () {
source: `branch ${branch}`,
head: checkBranch.pipe(Effect.andThen(fetchAndResolve(branchRef))),
},
- { source: `refs/pull/${number}/head`, head: fetchAndResolve(`refs/pull/${number}/head`) },
- {
- source: `refs/merge-requests/${number}/head`,
- head: fetchAndResolve(`refs/merge-requests/${number}/head`),
- },
+ ...(headRef === undefined ? [] : [{ source: headRef, head: fetchAndResolve(headRef) }]),
];
const failures: Array<string> = [];
for (const { source, head } of sources) {
diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts
index 3f839643086..0599b0caf24 100644
--- a/apps/server/src/vcs/GitVcsDriver.ts
+++ b/apps/server/src/vcs/GitVcsDriver.ts
@@ -201,15 +201,10 @@ export interface GitRenameBranchResult {
branch: string;
}
-export interface GitFetchPullRequestBranchInput {
+export interface GitFetchRefInput {
cwd: string;
- prNumber: number;
- branch: string;
-}
-
-export interface GitFetchPullRequestHeadCommitInput {
- cwd: string;
- prNumber: number;
+ /** A ref on the primary remote, such as a host's change request head ref. */
+ ref: string;
}
export interface GitResolveCommitInput {
@@ -342,6 +337,14 @@ export class GitVcsDriver extends Context.Service<
cwd: string,
key: string,
) => Effect.Effect<string | null, GitCommandError>;
+ /**
+ * The branch, named as on the host, that T3 recorded `branch` was cut from. Null when none
+ * was recorded.
+ */
+ readonly readBranchBase: (
+ cwd: string,
+ branch: string,
+ ) => Effect.Effect<string | null, GitCommandError>;
readonly resolveBranchName: (
cwd: string,
refName: string,
@@ -354,11 +357,12 @@ export class GitVcsDriver extends Context.Service<
input: VcsCreateWorktreeInput,
options?: CreateWorktreeOptions,
) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
- readonly fetchPullRequestBranch: (
- input: GitFetchPullRequestBranchInput,
+ /** Force-updates local `branch` to the primary remote's `ref`. */
+ readonly fetchRefIntoBranch: (
+ input: GitFetchRefInput & { readonly branch: string },
) => Effect.Effect<void, GitCommandError>;
- readonly fetchPullRequestHeadCommit: (
- input: GitFetchPullRequestHeadCommitInput,
+ readonly fetchRefCommit: (
+ input: GitFetchRefInput,
) => Effect.Effect<GitResolveCommitResult, GitCommandError>;
readonly resolveCommit: (
input: GitResolveCommitInput,
diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts
index 6bd0137154d..fc0ee47223f 100644
--- a/apps/server/src/vcs/GitVcsDriverCore.test.ts
+++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts
@@ -3066,7 +3066,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
yield* git(cwd, ["rev-parse", "HEAD"]),
);
assert.equal(
- yield* git(cwd, ["config", "branch.feature/parallel.gh-merge-base"]),
+ yield* git(cwd, ["config", "branch.feature/parallel.t3-merge-base"]),
initialBranch,
);
for (const [configured, expected] of [
@@ -3117,7 +3117,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
assert.equal(yield* git(worktreePath, ["rev-parse", "HEAD"]), commit);
assert.equal(
- yield* driver.readConfigValue(cwd, "branch.feature/revision.gh-merge-base"),
+ yield* driver.readConfigValue(cwd, "branch.feature/revision.t3-merge-base"),
null,
);
}),
@@ -3142,7 +3142,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
});
assert.equal(
- yield* driver.readConfigValue(cwd, "branch.feature/branch.gh-merge-base"),
+ yield* driver.readConfigValue(cwd, "branch.feature/branch.t3-merge-base"),
baseBranch,
);
}),
@@ -3465,7 +3465,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
"# test\n",
);
assert.equal(
- yield* driver.readConfigValue(worktreePath, "branch.feature/locked-config.gh-merge-base"),
+ yield* driver.readConfigValue(worktreePath, "branch.feature/locked-config.t3-merge-base"),
null,
);
assert.equal(yield* fileSystem.exists(pathService.join(cwd, ".git/config.lock")), true);
@@ -3737,7 +3737,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
assert.equal(yield* driver.resolvePrimaryRemoteName(cwd), remoteName);
yield* driver.fetchRemoteTrackingBranch({ cwd, remoteName, remoteBranch: initialBranch });
yield* driver.fetchRemote({ cwd, remoteName });
- const head = yield* driver.fetchPullRequestHeadCommit({ cwd, prNumber: 7 });
+ const head = yield* driver.fetchRefCommit({ cwd, ref: "refs/pull/7/head" });
assert.isFalse(yield* fileSystem.exists((yield* Path.Path).join(cwd, "t3-marker")));
assert.equal(head.commitSha, yield* git(cwd, ["rev-parse", "HEAD"]));
@@ -4133,7 +4133,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
assert.strictEqual(status.branchChanges?.deletions, 0);
// gh pr create consumes this setting verbatim as the hosted target branch.
assert.equal(
- yield* driver.readConfigValue(worktreePath, "branch.feature/from-upstream.gh-merge-base"),
+ yield* driver.readConfigValue(worktreePath, "branch.feature/from-upstream.t3-merge-base"),
"release",
);
assert.equal(changes.baseRef, "upstream/release");
@@ -4362,7 +4362,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
yield* git(cwd, ["rev-parse", "--abbrev-ref", "@{upstream}"]),
"origin/feature/x",
);
- assert.equal(yield* driver.readConfigValue(cwd, "branch.feature/x.gh-merge-base"), "dev");
+ assert.equal(yield* driver.readConfigValue(cwd, "branch.feature/x.t3-merge-base"), "dev");
const preview = yield* driver.getReviewDiffPreview({ cwd });
const changes = preview.sources.find((source) => source.kind === "branch-range")!;
diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts
index 2bc11cdb045..78c88d3c790 100644
--- a/apps/server/src/vcs/GitVcsDriverCore.ts
+++ b/apps/server/src/vcs/GitVcsDriverCore.ts
@@ -53,6 +53,13 @@ import * as ServerConfig from "../config.ts";
import { sourceControlClients } from "../sourceControl/sourceControlClients.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
+/** T3's record of the branch, named as on the host, that a branch was cut from. */
+const branchBaseConfigKey = (branch: string) => `branch.${branch}.t3-merge-base`;
+/**
+ * Where T3 kept that record before it had a key of its own, for every host alike: the GitHub
+ * CLI's key, which branches cut before then still carry instead.
+ */
+const legacyBranchBaseConfigKey = (branch: string) => `branch.${branch}.gh-merge-base`;
const gitProcesses = Semaphore.makeUnsafe(8);
const WORKTREE_ADD_TIMEOUT_MS = 300_000;
const WORKTREE_REMOVE_TIMEOUT_MS = Duration.toMillis(Duration.minutes(5));
@@ -1818,8 +1825,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
}
}
- const configuredBaseBranch =
- (yield* readConfigValue(cwd, `branch.${refName}.gh-merge-base`)) ?? "";
+ const configuredBaseBranch = (yield* readBranchBase(cwd, refName)) ?? "";
const configuredBase = yield* resolveComparisonBaseRef(cwd, configuredBaseBranch);
if (
configuredBase !== null &&
@@ -2638,16 +2644,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
const remoteName = publishRemoteName ?? currentUpstream.remoteName;
const publishBranch = yield* resolvePublishBranchName(cwd, branch);
// Publishing retargets the upstream, so preserve its comparison base first.
- const configuredMergeBase = yield* runGitStdout(
- "GitVcsDriver.pushCurrentBranch.readMergeBase",
- cwd,
- ["config", "--get", `branch.${branch}.gh-merge-base`],
- true,
- ).pipe(Effect.map((stdout) => stdout.trim()));
- if (configuredMergeBase.length === 0) {
+ if ((yield* readBranchBase(cwd, branch)) === null) {
yield* runGit("GitVcsDriver.pushCurrentBranch.recordMergeBase", cwd, [
"config",
- `branch.${branch}.gh-merge-base`,
+ branchBaseConfigKey(branch),
currentUpstream.branchName,
]);
if (!(yield* readConfigValue(cwd, `branch.${branch}.t3-merge-base-ref`))) {
@@ -3369,6 +3369,13 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)),
);
+ const readBranchBase: GitVcsDriver.GitVcsDriver["Service"]["readBranchBase"] = Effect.fn(
+ "GitVcsDriver.readBranchBase",
+ )(function* (cwd, branch) {
+ const base = yield* readConfigValue(cwd, branchBaseConfigKey(branch));
+ return base ?? (yield* readConfigValue(cwd, legacyBranchBaseConfigKey(branch)));
+ });
+
const resolveBranchBase = Effect.fn("GitVcsDriver.resolveBranchBase")(function* (
cwd: string,
refName: string,
@@ -3842,17 +3849,18 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
);
}
- if (input.newRefName && input.baseRefName) {
+ const newRefName = input.newRefName;
+ if (newRefName && input.baseRefName) {
const base = yield* resolveBranchBase(input.cwd, input.baseRefName);
if (base) {
yield* Effect.gen(function* () {
yield* runGit("GitVcsDriver.createWorktree.configureBaseRef", input.cwd, [
"config",
- `branch.${input.newRefName}.gh-merge-base`,
+ branchBaseConfigKey(newRefName),
base.branchName,
]);
if (base.baseRef.startsWith("refs/remotes/")) {
- // gh consumes its key as a provider branch; T3 also needs the selected remote.
+ // The base key names a branch on the host; this one keeps the remote it came from.
yield* runGit("GitVcsDriver.createWorktree.configureComparisonRef", input.cwd, [
"config",
`branch.${input.newRefName}.t3-merge-base-ref`,
@@ -3878,25 +3886,26 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
};
});
- const fetchPullRequestBranch: GitVcsDriver.GitVcsDriver["Service"]["fetchPullRequestBranch"] =
- Effect.fn("fetchPullRequestBranch")(function* (input) {
- const remoteName = yield* resolvePrimaryRemoteName(input.cwd);
- yield* executeGit(
- "GitVcsDriver.fetchPullRequestBranch",
- input.cwd,
- [
- "fetch",
- "--quiet",
- "--no-tags",
- "--",
- remoteName,
- `+refs/pull/${input.prNumber}/head:refs/heads/${input.branch}`,
- ],
- {
- fallbackErrorDetail: "git fetch pull request branch failed",
- },
- );
- });
+ const fetchRefIntoBranch: GitVcsDriver.GitVcsDriver["Service"]["fetchRefIntoBranch"] = Effect.fn(
+ "GitVcsDriver.fetchRefIntoBranch",
+ )(function* (input) {
+ const remoteName = yield* resolvePrimaryRemoteName(input.cwd);
+ yield* executeGit(
+ "GitVcsDriver.fetchRefIntoBranch",
+ input.cwd,
+ [
+ "fetch",
+ "--quiet",
+ "--no-tags",
+ "--",
+ remoteName,
+ `+${input.ref}:refs/heads/${input.branch}`,
+ ],
+ {
+ fallbackErrorDetail: "git fetch ref into branch failed",
+ },
+ );
+ });
const resolveCommit: GitVcsDriver.GitVcsDriver["Service"]["resolveCommit"] = Effect.fn(
"resolveCommit",
@@ -3910,22 +3919,23 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
return { commitSha };
});
- const fetchPullRequestHeadCommit: GitVcsDriver.GitVcsDriver["Service"]["fetchPullRequestHeadCommit"] =
- Effect.fn("fetchPullRequestHeadCommit")(function* (input) {
- const remoteName = yield* resolvePrimaryRemoteName(input.cwd);
- // No refspec destination: the pull head lands in FETCH_HEAD (per worktree) instead of a
- // branch, which is the only way to read it while that branch is checked out somewhere.
- yield* executeGit(
- "GitVcsDriver.fetchPullRequestHeadCommit",
- input.cwd,
- ["fetch", "--quiet", "--no-tags", "--", remoteName, `refs/pull/${input.prNumber}/head`],
- {
- fallbackErrorDetail: "git fetch pull request head failed",
- },
- );
+ const fetchRefCommit: GitVcsDriver.GitVcsDriver["Service"]["fetchRefCommit"] = Effect.fn(
+ "GitVcsDriver.fetchRefCommit",
+ )(function* (input) {
+ const remoteName = yield* resolvePrimaryRemoteName(input.cwd);
+ // No refspec destination: the ref lands in FETCH_HEAD (per worktree) instead of a branch,
+ // which is the only way to read it while that branch is checked out somewhere.
+ yield* executeGit(
+ "GitVcsDriver.fetchRefCommit",
+ input.cwd,
+ ["fetch", "--quiet", "--no-tags", "--", remoteName, input.ref],
+ {
+ fallbackErrorDetail: "git fetch ref failed",
+ },
+ );
- return yield* resolveCommit({ cwd: input.cwd, revision: "FETCH_HEAD" });
- });
+ return yield* resolveCommit({ cwd: input.cwd, revision: "FETCH_HEAD" });
+ });
const refreshCheckedOutBranch: GitVcsDriver.GitVcsDriver["Service"]["refreshCheckedOutBranch"] =
Effect.fn("refreshCheckedOutBranch")(function* (input) {
@@ -4507,13 +4517,13 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
getReviewDiffPreview,
getReviewDiffFileContents,
readConfigValue,
+ readBranchBase,
resolveBranchName,
listRefs,
createWorktree: (input, options) =>
withListRefsInvalidation(input.cwd, createWorktree(input, options)),
- fetchPullRequestBranch: (input) =>
- withListRefsInvalidation(input.cwd, fetchPullRequestBranch(input)),
- fetchPullRequestHeadCommit,
+ fetchRefIntoBranch: (input) => withListRefsInvalidation(input.cwd, fetchRefIntoBranch(input)),
+ fetchRefCommit,
resolveCommit,
refreshCheckedOutBranch: (input) =>
withListRefsInvalidation(input.cwd, refreshCheckedOutBranch(input)),
diff --git a/apps/server/src/vcs/VcsProcess.test.ts b/apps/server/src/vcs/VcsProcess.test.ts
index 03d274fdd82..212415171bd 100644
--- a/apps/server/src/vcs/VcsProcess.test.ts
+++ b/apps/server/src/vcs/VcsProcess.test.ts
@@ -258,7 +258,7 @@ describe("VcsProcess.run", () => {
}),
);
- it.effect("bounds a synthetic burst of GitHub API processes", () =>
+ it.effect("bounds a burst of processes that share a concurrency key", () =>
Effect.gen(function* () {
const gate = yield* Deferred.make<void>();
const starts = yield* Queue.unbounded<number>();
@@ -294,10 +294,11 @@ describe("VcsProcess.run", () => {
const burst = yield* Effect.all(
Array.from({ length: 32 }, (_, index) =>
service.run({
- operation: `synthetic.github.${index}`,
- command: "gh",
+ operation: `synthetic.cli.${index}`,
+ command: "host-cli",
args: ["api", "user"],
cwd: "/workspace",
+ concurrency: { key: "host-cli", limit: 4 },
}),
),
{ concurrency: "unbounded" },
@@ -391,6 +392,30 @@ describe("VcsProcess.run", () => {
}).pipe(provideLive),
);
+ it.effect("reads a failure with the command's own classifier and names it in its terms", () =>
+ Effect.gen(function* () {
+ const fail = (input: Partial<VcsProcess.VcsProcessInput>) =>
+ run({
+ operation: "test.classify",
+ command: "node",
+ args: ["-e", "process.stderr.write('HTTP 404: 404 Not Found'); process.exit(1)"],
+ cwd: process.cwd(),
+ ...input,
+ }).pipe(Effect.flip);
+
+ expect(yield* fail({})).toMatchObject({
+ failureKind: "command-failed",
+ detail: "Process exited with a non-zero status.",
+ });
+ expect(
+ yield* fail({
+ classifyFailure: (stderr) => (stderr.includes("404") ? "not-found" : null),
+ notFoundDetail: "Merge request not found.",
+ }),
+ ).toMatchObject({ failureKind: "not-found", detail: "Merge request not found." });
+ }).pipe(provideLive),
+ );
+
it.effect("retains spawn causes without exposing process arguments in the error message", () =>
Effect.gen(function* () {
const secretArgument = "--token=super-secret-token";
diff --git a/apps/server/src/vcs/VcsProcess.ts b/apps/server/src/vcs/VcsProcess.ts
index 2a62c6fb1ac..980f4c7e674 100644
--- a/apps/server/src/vcs/VcsProcess.ts
+++ b/apps/server/src/vcs/VcsProcess.ts
@@ -20,6 +20,7 @@ import {
VcsProcessTimeoutError,
} from "@t3tools/contracts";
import * as HostProcess from "@t3tools/shared/HostProcess";
+import type { SourceControlProcessInput } from "@t3tools/source-control-core/server/SourceControlHost";
import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../observability/Metrics.ts";
import * as ProcessRunner from "../processRunner.ts";
@@ -38,6 +39,9 @@ export interface VcsProcessInput {
readonly maxOutputBytes?: number;
readonly outputMode?: ProcessRunner.ProcessRunInput["outputMode"];
readonly appendTruncationMarker?: boolean;
+ readonly classifyFailure?: SourceControlProcessInput["classifyFailure"];
+ readonly notFoundDetail?: string;
+ readonly concurrency?: SourceControlProcessInput["concurrency"];
}
export interface VcsProcessOutput {
@@ -61,7 +65,6 @@ const DEFAULT_TIMEOUT_MS = 30_000;
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
const OUTPUT_TRUNCATED_MARKER = "\n\n[truncated]";
const VCS_PROCESS_CONCURRENCY = 8;
-const GITHUB_PROCESS_CONCURRENCY = 4;
/** Shown to users when a Git command fails because another process holds the index lock. */
export const GIT_INDEX_LOCKED_DETAIL =
@@ -132,22 +135,23 @@ export const gitConfigEnv = (
* Git otherwise opens any folder holding `HEAD`, `objects/` and `refs/` as a
* bare repository and applies its `config`, including commands such as
* `core.fsmonitor`. Files saved in a project or checked out from a clone can
- * form one, so git started by T3 (or by gh and friends) only opens a bare
+ * form one, so git started by T3 (or by a host CLI) only opens a bare
* repository named with `--git-dir` or `GIT_DIR`. Git before 2.38 ignores it.
*/
export const explicitBareRepositoryEnv = (env: NodeJS.ProcessEnv, platform: NodeJS.Platform) =>
gitConfigEnv(env, "safe.bareRepository", "explicit", platform);
-const classifyNonZeroExit = (command: string, stderr: string): VcsProcessExitFailureKind => {
+const classifyNonZeroExit = (
+ stderr: string,
+ classifyFailure: VcsProcessInput["classifyFailure"],
+): VcsProcessExitFailureKind => {
const normalized = stderr.toLowerCase();
+ const commandKind = classifyFailure?.(stderr) ?? null;
if (
+ commandKind === "authentication" ||
normalized.includes("authentication failed") ||
normalized.includes("not logged in") ||
- normalized.includes("gh auth login") ||
- normalized.includes("glab auth login") ||
- normalized.includes("az devops login") ||
- normalized.includes("please run az login") ||
normalized.includes("no oauth token") ||
normalized.includes("unauthorized")
) {
@@ -155,6 +159,7 @@ const classifyNonZeroExit = (command: string, stderr: string): VcsProcessExitFai
}
if (
+ commandKind === "rate-limited" ||
normalized.includes("api rate limit") ||
normalized.includes("rate limit exceeded") ||
normalized.includes("secondary rate limit") ||
@@ -164,24 +169,7 @@ const classifyNonZeroExit = (command: string, stderr: string): VcsProcessExitFai
return "rate-limited";
}
- if (
- (command === "gh" &&
- (normalized.includes("could not resolve to a pullrequest") ||
- normalized.includes("repository.pullrequest") ||
- normalized.includes("no pull requests found for branch") ||
- normalized.includes("pull request not found"))) ||
- (command === "glab" &&
- (normalized.includes("merge request not found") ||
- normalized.includes("not found") ||
- normalized.includes("404"))) ||
- (command === "az" &&
- normalized.includes("pull request") &&
- (normalized.includes("not found") || normalized.includes("does not exist")))
- ) {
- return "not-found";
- }
-
- return "command-failed";
+ return commandKind ?? "command-failed";
};
// Classify before discarding stderr; keep paths and process output out of errors.
@@ -204,7 +192,15 @@ export const make = Effect.gen(function* () {
const processRunner = yield* ProcessRunner.ProcessRunner;
const hostPlatform = yield* HostProcess.Platform;
const vcsProcesses = yield* Semaphore.make(VCS_PROCESS_CONCURRENCY);
- const githubProcesses = yield* Semaphore.make(GITHUB_PROCESS_CONCURRENCY);
+ const keyedProcesses = new Map<string, Semaphore.Semaphore>();
+ const keyedPermit = (concurrency: NonNullable<VcsProcessInput["concurrency"]>) => {
+ let semaphore = keyedProcesses.get(concurrency.key);
+ if (semaphore === undefined) {
+ semaphore = Semaphore.makeUnsafe(concurrency.limit);
+ keyedProcesses.set(concurrency.key, semaphore);
+ }
+ return semaphore.withPermits(1);
+ };
const spawn = Effect.fn("VcsProcess.spawn")(function* (
input: VcsProcessInput,
@@ -315,7 +311,7 @@ export const make = Effect.gen(function* () {
}
if (!input.allowNonZeroExit && result.code !== 0) {
- const failureKind = classifyNonZeroExit(input.command, result.stderr);
+ const failureKind = classifyNonZeroExit(result.stderr, input.classifyFailure);
const error = VcsProcessExitError.fromProcessExit(
baseError,
{
@@ -324,9 +320,13 @@ export const make = Effect.gen(function* () {
stderrTruncated: result.stderrTruncated,
},
failureKind,
- input.command === "git" &&
- failureKind === "command-failed" &&
- isTransientGitExit(result.stderr),
+ {
+ retryable:
+ input.command === "git" &&
+ failureKind === "command-failed" &&
+ isTransientGitExit(result.stderr),
+ ...(input.notFoundDetail === undefined ? {} : { notFoundDetail: input.notFoundDetail }),
+ },
);
if (
input.command === "git" &&
@@ -374,7 +374,9 @@ export const make = Effect.gen(function* () {
}),
);
}
- return yield* input.command === "gh" ? githubProcesses.withPermits(1)(bounded) : bounded;
+ return yield* input.concurrency === undefined
+ ? bounded
+ : keyedPermit(input.concurrency)(bounded);
});
return VcsProcess.of({ run });
diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.ts
index 41859b9dd90..71427713e5b 100644
--- a/apps/server/src/vcs/VcsStatusBroadcaster.ts
+++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts
@@ -243,7 +243,7 @@ export const make = Effect.gen(function* () {
);
const cacheRef = yield* Ref.make(new Map<string, CachedVcsStatus>());
// One permit per cwd for remote reads that write the cache. Without it a
- // periodic poll that started before `gh pr create` can finish after the
+ // periodic poll that started before an agent creates a PR can finish after the
// turn-end refresh and overwrite the fresh PR with its stale `pr: null`.
const remoteWriteLocks = yield* KeyedLock.make<string>();
const withRemoteWriteLock = <A, E, R>(cwd: string, effect: Effect.Effect<A, E, R>) =>
diff --git a/packages/contracts/src/vcs.ts b/packages/contracts/src/vcs.ts
index f92e4fc1d5c..3d59d61c7aa 100644
--- a/packages/contracts/src/vcs.ts
+++ b/packages/contracts/src/vcs.ts
@@ -132,7 +132,7 @@ export class VcsProcessExitError extends Schema.TaggedError<VcsProcessExitError>
context: VcsProcessErrorContext,
error: VcsProcessExitFailure,
failureKind: VcsProcessExitFailureKind,
- retryable?: boolean,
+ options?: { readonly retryable?: boolean; readonly notFoundDetail?: string },
) {
const detail =
failureKind === "authentication"
@@ -140,11 +140,7 @@ export class VcsProcessExitError extends Schema.TaggedError<VcsProcessExitError>
: failureKind === "rate-limited"
? "API rate limit exceeded."
: failureKind === "not-found"
- ? context.command === "glab"
- ? "Merge request not found."
- : context.command === "gh" || context.command === "az"
- ? "Pull request not found."
- : "VCS resource not found."
+ ? (options?.notFoundDetail ?? "VCS resource not found.")
: "Process exited with a non-zero status.";
return new VcsProcessExitError({
@@ -152,7 +148,7 @@ export class VcsProcessExitError extends Schema.TaggedError<VcsProcessExitError>
exitCode: error.exitCode,
detail,
failureKind,
- ...(retryable === true ? { retryable: true } : {}),
+ ...(options?.retryable === true ? { retryable: true } : {}),
stderrLength: error.stderr.length,
stderrTruncated: error.stderrTruncated,
});
diff --git a/packages/shared/src/sourceControl.test.ts b/packages/shared/src/sourceControl.test.ts
deleted file mode 100644
index bb3ad5716fd..00000000000
--- a/packages/shared/src/sourceControl.test.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { SourceControlProviderKind } from "@t3tools/contracts";
-import { expect, it } from "vite-plus/test";
-
-import { getChangeRequestTerminologyForKind } from "./sourceControl.ts";
-
-it("calls a Forgejo change request a pull request", () => {
- expect(getChangeRequestTerminologyForKind(SourceControlProviderKind.make("forgejo"))).toEqual({
- shortLabel: "PR",
- singular: "pull request",
- });
-});
diff --git a/packages/shared/src/sourceControl.ts b/packages/shared/src/sourceControl.ts
index f7039961f97..31fba958776 100644
--- a/packages/shared/src/sourceControl.ts
+++ b/packages/shared/src/sourceControl.ts
@@ -1,141 +1,3 @@
-import type { SourceControlProviderInfo, SourceControlProviderKind } from "@t3tools/contracts";
-
-export interface ChangeRequestPresentation {
- readonly icon:
- | "github"
- | "gitlab"
- | "forgejo"
- | "azure-devops"
- | "bitbucket"
- | "gitcafe"
- | "change-request";
- readonly providerName: string;
- readonly shortName: string;
- readonly longName: string;
- readonly pluralLongName: string;
- readonly providerLongName: string;
- readonly checkoutCommandExample?: string;
- readonly urlExample: string;
-}
-
-export interface ChangeRequestTerminology {
- readonly shortLabel: string;
- readonly singular: string;
-}
-
-const GITHUB_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
- icon: "github",
- providerName: "GitHub",
- shortName: "PR",
- longName: "pull request",
- pluralLongName: "pull requests",
- providerLongName: "GitHub pull request",
- checkoutCommandExample: "gh pr checkout 123",
- urlExample: "https://github.com/owner/repo/pull/42",
-};
-
-const GITLAB_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
- icon: "gitlab",
- providerName: "GitLab",
- shortName: "MR",
- longName: "merge request",
- pluralLongName: "merge requests",
- providerLongName: "GitLab merge request",
- checkoutCommandExample: "glab mr checkout 123",
- urlExample: "https://gitlab.com/group/project/-/merge_requests/42",
-};
-
-const FORGEJO_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
- icon: "forgejo",
- providerName: "Forgejo",
- shortName: "PR",
- longName: "pull request",
- pluralLongName: "pull requests",
- providerLongName: "Forgejo pull request",
- checkoutCommandExample: "tea pr checkout 123",
- urlExample: "https://codeberg.org/owner/repo/pulls/42",
-};
-
-const AZURE_DEVOPS_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
- icon: "azure-devops",
- providerName: "Azure DevOps",
- shortName: "PR",
- longName: "pull request",
- pluralLongName: "pull requests",
- providerLongName: "Azure DevOps pull request",
- checkoutCommandExample: "az repos pr checkout --id 123",
- urlExample: "https://dev.azure.com/org/project/_git/repo/pullrequest/42",
-};
-
-const BITBUCKET_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
- icon: "bitbucket",
- providerName: "Bitbucket",
- shortName: "PR",
- longName: "pull request",
- pluralLongName: "pull requests",
- providerLongName: "Bitbucket pull request",
- urlExample: "https://bitbucket.org/workspace/repo/pull-requests/42",
-};
-
-const GITCAFE_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
- icon: "gitcafe",
- providerName: "GitCafe",
- shortName: "PR",
- longName: "pull request",
- pluralLongName: "pull requests",
- providerLongName: "GitCafe pull request",
- checkoutCommandExample: "cafe pr checkout 123",
- urlExample: "https://git.cafe/owner/repo/pulls/42",
-};
-
-const GENERIC_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
- icon: "change-request",
- providerName: "source control",
- shortName: "change request",
- longName: "change request",
- pluralLongName: "change requests",
- providerLongName: "change request",
- urlExample: "#42",
-};
-
-function resolveChangeRequestPresentation(
- provider: SourceControlProviderInfo | null | undefined,
-): ChangeRequestPresentation {
- switch (provider?.kind) {
- case "github":
- case undefined:
- return GITHUB_CHANGE_REQUEST_PRESENTATION;
- case "gitlab":
- return GITLAB_CHANGE_REQUEST_PRESENTATION;
- case "forgejo":
- return FORGEJO_CHANGE_REQUEST_PRESENTATION;
- case "azure-devops":
- return AZURE_DEVOPS_CHANGE_REQUEST_PRESENTATION;
- case "bitbucket":
- return BITBUCKET_CHANGE_REQUEST_PRESENTATION;
- case "gitcafe":
- return GITCAFE_CHANGE_REQUEST_PRESENTATION;
- default:
- return GENERIC_CHANGE_REQUEST_PRESENTATION;
- }
-}
-
-function resolveChangeRequestPresentationForKind(
- kind: SourceControlProviderKind,
-): ChangeRequestPresentation {
- return resolveChangeRequestPresentation({ kind, name: "", baseUrl: "" });
-}
-
-export function getChangeRequestTerminologyForKind(
- kind: SourceControlProviderKind,
-): ChangeRequestTerminology {
- const presentation = resolveChangeRequestPresentationForKind(kind);
- return {
- shortLabel: presentation.shortName,
- singular: presentation.longName,
- };
-}
-
const SCP_SSH_REMOTE_PATTERN = /^[a-zA-Z0-9._-]+@([^:/]+):/;
export function isSshRemoteUrl(remoteUrl: string): boolean {
diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.test.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.test.ts
index 9a39f74d290..ff2ddd03399 100644
--- a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.test.ts
+++ b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.test.ts
@@ -70,7 +70,20 @@ describe("AzureDevOpsCli.layer", () => {
assert.strictEqual(result.headSha, "a".repeat(40));
assert.strictEqual(result.state, "open");
assert.deepStrictEqual(result.updatedAt._tag, Option.some(1)._tag);
- assert.deepStrictEqual(mockRun.mock.calls.at(-1)?.[0], {
+ const { classifyFailure, ...call } = mockRun.mock.calls.at(-1)?.[0] ?? {};
+ assert.strictEqual(
+ classifyFailure?.("Please run az login to setup account."),
+ "authentication",
+ );
+ assert.strictEqual(
+ classifyFailure?.("Please run 'az login' to setup account."),
+ "authentication",
+ );
+ assert.strictEqual(
+ classifyFailure?.("TF401180: The requested pull request was not found."),
+ "not-found",
+ );
+ assert.deepStrictEqual(call, {
operation: "AzureDevOpsCli.execute",
command: "az",
args: [
@@ -86,6 +99,7 @@ describe("AzureDevOpsCli.layer", () => {
"json",
],
cwd: "/repo",
+ notFoundDetail: "Pull request not found.",
timeoutMs: 30_000,
});
assert.strictEqual(result.isCrossRepository, false);
diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts
index c333a220c6d..b12901d6ace 100644
--- a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts
+++ b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts
@@ -9,6 +9,7 @@ import {
TrimmedNonEmptyString,
type SourceControlRepositoryVisibility,
type VcsError,
+ type VcsProcessExitFailureKind,
} from "@t3tools/contracts";
import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
@@ -350,6 +351,17 @@ function decodeAzureDevOpsJson<S extends Schema.Top>(
);
}
+const classifyAzFailure = (stderr: string): VcsProcessExitFailureKind | null => {
+ const normalized = stderr.toLowerCase();
+ if (normalized.includes("az devops login") || /please run '?az login'?/.test(normalized)) {
+ return "authentication";
+ }
+ return normalized.includes("pull request") &&
+ (normalized.includes("not found") || normalized.includes("does not exist"))
+ ? "not-found"
+ : null;
+};
+
/** @public Service construction is part of the canonical Effect module API. */
export const make = Effect.gen(function* () {
const { process } = yield* SourceControlHost.SourceControlHost;
@@ -361,6 +373,8 @@ export const make = Effect.gen(function* () {
command: "az",
args: input.args,
cwd: input.cwd,
+ classifyFailure: classifyAzFailure,
+ notFoundDetail: "Pull request not found.",
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),
})
diff --git a/packages/source-control-core/src/client/definition.ts b/packages/source-control-core/src/client/definition.ts
index 35cc5ddaeba..a253780a6a3 100644
--- a/packages/source-control-core/src/client/definition.ts
+++ b/packages/source-control-core/src/client/definition.ts
@@ -125,6 +125,11 @@ export interface SourceControlClientDefinition {
link: ChangeRequestLink,
) => boolean;
readonly checkoutChangeRequestHost: (identity: ChangeRequestProjectIdentity) => string | null;
+ /**
+ * The ref the target repository publishes change request `number`'s head under, which names the
+ * head even when it lives in a fork. Absent for a host that publishes none.
+ */
+ readonly changeRequestHeadRef?: (number: number) => string;
/** Null when this host does not claim the remote. Asked in the registry's recognition order. */
readonly recognizeRemote: (remote: GitRemoteHost) => SourceControlProviderInfo | null;
/** The host change requests in the project are listed and keyed under. */
diff --git a/packages/source-control-core/src/server/SourceControlHost.ts b/packages/source-control-core/src/server/SourceControlHost.ts
index 330fea4bbfa..711538d0aa7 100644
--- a/packages/source-control-core/src/server/SourceControlHost.ts
+++ b/packages/source-control-core/src/server/SourceControlHost.ts
@@ -4,6 +4,7 @@ import type {
ServerSettingsError,
VcsError,
VcsListRemotesResult,
+ VcsProcessExitFailureKind,
VcsSwitchRefInput,
VcsSwitchRefResult,
} from "@t3tools/contracts";
@@ -25,6 +26,18 @@ export interface SourceControlProcessInput {
readonly maxOutputBytes?: number;
readonly outputMode?: "error" | "truncate" | undefined;
readonly appendTruncationMarker?: boolean;
+ /**
+ * Reads a failure the generic rules cannot, such as a host CLI's sign-in hint, from its stderr.
+ * Null leaves it to them.
+ */
+ readonly classifyFailure?: (stderr: string) => VcsProcessExitFailureKind | null;
+ /** The error's detail when the command reports something it was asked for as missing. */
+ readonly notFoundDetail?: string;
+ /**
+ * Runs sharing a key run at most `limit` at a time, for a host that throttles bursts of its CLI.
+ * The first run of a key fixes its limit.
+ */
+ readonly concurrency?: { readonly key: string; readonly limit: number };
}
export interface SourceControlProcessOutput {
diff --git a/packages/source-control-core/src/server/SourceControlProvider.ts b/packages/source-control-core/src/server/SourceControlProvider.ts
index 23e26dcf0d7..90e9acfcb25 100644
--- a/packages/source-control-core/src/server/SourceControlProvider.ts
+++ b/packages/source-control-core/src/server/SourceControlProvider.ts
@@ -142,6 +142,25 @@ export class SourceControlProvider extends Context.Service<
}) => Effect.Effect<SourceControlProviderContext | null, SourceControlProviderError>;
}) => Effect.Effect<RepositoryIdentity, SourceControlProviderError>;
readonly resolveLink?: ResolveSourceControlLink;
+ /**
+ * Whether `createChangeRequest` from `cwd` targets `repository`, the `owner/name` of the
+ * context's remote, for a host whose tools let configuration outside the remotes name another
+ * repository. Absent means it does.
+ */
+ readonly createsChangeRequestsIn?: (input: {
+ readonly cwd: string;
+ readonly context: SourceControlProviderContext;
+ readonly repository: string | null;
+ }) => Effect.Effect<boolean>;
+ /**
+ * Told when T3 records `baseBranch`, a branch name on the host, as the base `branch` was cut
+ * from, for a host whose own tools keep that in git config of their own.
+ */
+ readonly recordBranchBase?: (input: {
+ readonly cwd: string;
+ readonly branch: string;
+ readonly baseBranch: string;
+ }) => Effect.Effect<void>;
readonly listChangeRequests: (input: {
readonly cwd: string;
readonly context?: SourceControlProviderContext;
diff --git a/packages/source-control-forgejo/src/client/definition.ts b/packages/source-control-forgejo/src/client/definition.ts
index 1411a42c1e2..f11e7f58aaa 100644
--- a/packages/source-control-forgejo/src/client/definition.ts
+++ b/packages/source-control-forgejo/src/client/definition.ts
@@ -21,6 +21,8 @@ const CHANGE_REQUEST_PATH = /^\/([^/]+(?:\/[^/]+)+)\/pulls\/(\d+)(?:\/|$)/u;
const KIND = SourceControlProviderKind.make("forgejo");
+const changeRequestHeadRef = (number: number) => `refs/pull/${number}/head`;
+
/**
* The repository's browser URL the server resolved from the signed-in account, which is the
* only place a Forgejo mounted below a path says so.
@@ -77,7 +79,7 @@ export const definition = defineSourceControlClient({
// Neither `fj` nor `tea` checks out by number, so fetch the pull ref from the repository itself.
checkoutCommand: ({ number, repositoryUrl }) =>
repositoryUrl
- ? `git fetch '${repositoryUrl.replaceAll("'", "'\\''")}' refs/pull/${number}/head && git checkout -B pulls/${number} FETCH_HEAD`
+ ? `git fetch '${repositoryUrl.replaceAll("'", "'\\''")}' ${changeRequestHeadRef(number)} && git checkout -B pulls/${number} FETCH_HEAD`
: null,
authorProfileUrl: () => null,
// Forgejo refuses a change request review without a summary, even with inline comments.
@@ -86,6 +88,7 @@ export const definition = defineSourceControlClient({
checkoutCommandArgument: (input) => CHECKOUT_COMMAND.exec(input)?.[1]?.trim() ?? null,
isChangeRequestReference: (url) => CHANGE_REQUEST_REFERENCE.test(url),
checkoutChangeRequestHost: () => null,
+ changeRequestHeadRef,
recognizeRemote: ({ remoteUrl, host, hostname }) =>
hostname === "codeberg.org" ||
hostname.split(".").includes("forgejo") ||
diff --git a/packages/source-control-github/src/client/definition.ts b/packages/source-control-github/src/client/definition.ts
index 86268f29d40..f60f10e7238 100644
--- a/packages/source-control-github/src/client/definition.ts
+++ b/packages/source-control-github/src/client/definition.ts
@@ -121,6 +121,7 @@ export const definition = defineSourceControlClient({
checkoutCommandArgument: (input) => CHECKOUT_COMMAND.exec(input)?.[1]?.trim() ?? null,
isChangeRequestReference: (url) => CHANGE_REQUEST_REFERENCE.test(url),
checkoutChangeRequestHost: (identity) => projectChangeRequestHost(identity, KIND),
+ changeRequestHeadRef: (number) => `refs/pull/${number}/head`,
// `*.ghe.com` is GitHub Enterprise Cloud with data residency, one subdomain per enterprise.
recognizeRemote: ({ host, hostname }) =>
hostname === "github.com" ||
diff --git a/packages/source-control-github/src/server/GitHubCredentials.ts b/packages/source-control-github/src/server/GitHubCredentials.ts
index b2d0b7d0ea3..58aed003e3b 100644
--- a/packages/source-control-github/src/server/GitHubCredentials.ts
+++ b/packages/source-control-github/src/server/GitHubCredentials.ts
@@ -19,6 +19,12 @@ import type { ServerSettings } from "@t3tools/contracts";
import * as GitHubClient from "../client/definition.ts";
+/**
+ * Every gh run on the server shares this. A burst of them (a status poll across many checkouts)
+ * otherwise starts enough at once to trip GitHub's secondary rate limit.
+ */
+export const GH_PROCESS_CONCURRENCY = { key: "gh", limit: 4 } as const;
+
const TOKEN_TTL = Duration.minutes(5);
const MISSING_TTL = Duration.seconds(10);
@@ -146,6 +152,7 @@ export const make = Effect.gen(function* () {
// Never let gh print the token into a debug log.
env: { GH_DEBUG: "", GH_PROMPT_DISABLED: "1" },
timeoutMs: 10_000,
+ concurrency: GH_PROCESS_CONCURRENCY,
})
.pipe(
Effect.mapError((error) =>
diff --git a/packages/source-control-github/src/server/GitHubSourceControlProvider.test.ts b/packages/source-control-github/src/server/GitHubSourceControlProvider.test.ts
index a8dfbabf7d2..2c2293efb65 100644
--- a/packages/source-control-github/src/server/GitHubSourceControlProvider.test.ts
+++ b/packages/source-control-github/src/server/GitHubSourceControlProvider.test.ts
@@ -1051,3 +1051,31 @@ it.effect.each([
);
},
);
+
+it.effect("says a GH_REPO naming an unparseable host targets no remote rather than failing", () => {
+ const { layer } = harness({
+ remotes: remotesOutput(["upstream", "[email protected]:acme/web.git"]),
+ resolved: "",
+ api: {},
+ });
+ return Effect.gen(function* () {
+ const provider = yield* GitHubSourceControlProvider.make;
+ const targets = yield* provider.createsChangeRequestsIn!({
+ cwd: "/repo",
+ context: {
+ provider: {
+ kind: SourceControlProviderKind.make("github"),
+ name: "GitHub",
+ baseUrl: "https://github.com",
+ },
+ remoteName: "upstream",
+ remoteUrl: "[email protected]:acme/web.git",
+ },
+ repository: "acme/web",
+ });
+ assert.isFalse(targets);
+ }).pipe(
+ Effect.provide(layer),
+ Effect.provideService(HostProcess.Environment, { GH_REPO: "bad host/acme/web" }),
+ );
+});
diff --git a/packages/source-control-github/src/server/GitHubSourceControlProvider.ts b/packages/source-control-github/src/server/GitHubSourceControlProvider.ts
index b4c2b5107fe..22bbf99f2ab 100644
--- a/packages/source-control-github/src/server/GitHubSourceControlProvider.ts
+++ b/packages/source-control-github/src/server/GitHubSourceControlProvider.ts
@@ -26,6 +26,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
import { isSshRemoteUrl } from "@t3tools/shared/sourceControl";
+import { GH_PROCESS_CONCURRENCY } from "./GitHubCredentials.ts";
import * as GitHubRest from "./GitHubRest.ts";
import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
import * as GitHubChangeRequestTemplate from "./gitHubChangeRequestTemplate.ts";
@@ -235,7 +236,9 @@ export const makeDiscovery = Effect.gen(function* () {
);
const cli = yield* probeSourceControlProvider({
cwd,
- process,
+ process: {
+ run: (input) => process.run({ ...input, concurrency: GH_PROCESS_CONCURRENCY }),
+ },
spec: { ...discovery, parseAuth: (input) => parseGitHubAuth(input, settings) },
});
const savedToken = (settings.tokens["github.com"] ?? "").trim() !== "";
@@ -893,6 +896,55 @@ export const make = Effect.gen(function* () {
}),
readChangeRequestTemplate: ({ cwd, treeish }) =>
GitHubChangeRequestTemplate.detect(cwd, treeish, git.execute),
+ // `createChangeRequest` targets what `resolveRepository` picks: GH_REPO when it parses, else
+ // the remote `gh repo set-default` marked (`gh-resolved`). An HTTPS remote keeps a
+ // non-default port in the context's host, and the mark is then ignored.
+ createsChangeRequestsIn: Effect.fn("GitHubSourceControlProvider.createsChangeRequestsIn")(
+ function* ({ cwd, context, repository }) {
+ const host = URL.canParse(context.provider.baseUrl)
+ ? new URL(context.provider.baseUrl).host
+ : null;
+ const target = repository?.toLowerCase();
+ const fromEnvironment = parseGitHubRepositorySelector(
+ environment.GH_REPO ?? "",
+ host ?? "",
+ );
+ if (fromEnvironment !== null) {
+ const { host: targetHost, owner, name } = fromEnvironment;
+ return (
+ host !== null &&
+ URL.canParse(`https://${targetHost}`) &&
+ new URL(`https://${targetHost}`).host === host &&
+ `${owner}/${name}`.toLowerCase() === target
+ );
+ }
+ const mark = yield* git
+ .readConfigValue(cwd, `remote.${context.remoteName}.gh-resolved`)
+ .pipe(Effect.orElseSucceed(() => null));
+ const { locator } = resolveGitHubRepository({
+ remotes: `${context.remoteName}\t${context.remoteUrl} (fetch)`,
+ resolved: mark === null ? "" : `remote.${context.remoteName}.gh-resolved ${mark}`,
+ hostHint: host ?? undefined,
+ defaultHost: host ?? "github.com",
+ });
+ return locator === null || `${locator.owner}/${locator.name}`.toLowerCase() === target;
+ },
+ ),
+ // `gh pr create` run in the checkout, as an agent in a T3 worktree often does, takes its base
+ // from this key.
+ recordBranchBase: ({ cwd, branch, baseBranch }) =>
+ git
+ .execute({
+ operation: "GitHubSourceControlProvider.recordBranchBase",
+ cwd,
+ args: ["config", `branch.${branch}.gh-merge-base`, baseBranch],
+ })
+ .pipe(
+ Effect.asVoid,
+ Effect.catch((cause) =>
+ Effect.logWarning("Could not record the branch base for gh", { cause }),
+ ),
+ ),
resolveLink: (input) => {
// Automatic enrichment must not send ambient CLI credentials to a host from message text.
if (input.url.host !== "github.com") return undefined;
diff --git a/packages/source-control-github/src/server/gitHubPullRequests.test.ts b/packages/source-control-github/src/server/gitHubPullRequests.test.ts
new file mode 100644
index 00000000000..59e8fffa418
--- /dev/null
+++ b/packages/source-control-github/src/server/gitHubPullRequests.test.ts
@@ -0,0 +1,27 @@
+import * as Result from "effect/Result";
+import { expect, it } from "vite-plus/test";
+
+import { decodeGitHubPullRequestListJson } from "./gitHubPullRequests.ts";
+
+// gh before 2.47 names the head repository without its owner, and a fork's checkout needs both.
+it("names a fork's head repository from its owner when gh leaves nameWithOwner out", () => {
+ const decoded = decodeGitHubPullRequestListJson(
+ JSON.stringify([
+ {
+ number: 642,
+ title: "fix: use commit as the default git action without origin",
+ url: "https://github.com/pingdotgg/t3code/pull/642",
+ baseRefName: "main",
+ headRefName: "fix/git-action-default-without-origin",
+ isCrossRepository: true,
+ headRepository: { id: "R_1", name: "t3code" },
+ headRepositoryOwner: { login: "binbandit" },
+ },
+ ]),
+ );
+
+ expect(Result.getOrThrow(decoded)[0]).toMatchObject({
+ headRepositoryNameWithOwner: "binbandit/t3code",
+ headRepositoryOwnerLogin: "binbandit",
+ });
+});
diff --git a/packages/source-control-gitlab/src/client/definition.ts b/packages/source-control-gitlab/src/client/definition.ts
index e944270a94e..d9262f5abf7 100644
--- a/packages/source-control-gitlab/src/client/definition.ts
+++ b/packages/source-control-gitlab/src/client/definition.ts
@@ -52,6 +52,7 @@ export const definition = defineSourceControlClient({
checkoutCommandArgument: (input) => CHECKOUT_COMMAND.exec(input)?.[1]?.trim() ?? null,
isChangeRequestReference: (url) => CHANGE_REQUEST_REFERENCE.test(url),
checkoutChangeRequestHost: () => null,
+ changeRequestHeadRef: (number) => `refs/merge-requests/${number}/head`,
recognizeRemote: ({ host, hostname }) =>
hostname === "gitlab.com" || hostname.split(".").includes("gitlab")
? {
diff --git a/packages/source-control-gitlab/src/server/GitLabCli.ts b/packages/source-control-gitlab/src/server/GitLabCli.ts
index aea251144e8..405c6a52004 100644
--- a/packages/source-control-gitlab/src/server/GitLabCli.ts
+++ b/packages/source-control-gitlab/src/server/GitLabCli.ts
@@ -11,6 +11,7 @@ import {
TrimmedNonEmptyString,
type SourceControlRepositoryVisibility,
type VcsError,
+ type VcsProcessExitFailureKind,
} from "@t3tools/contracts";
import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
@@ -409,6 +410,14 @@ function parseRepositoryPath(repository: string): {
return { namespacePath, projectPath };
}
+// glab prints a missing project or merge request as a bare 404.
+const classifyGlabFailure = (stderr: string): VcsProcessExitFailureKind | null => {
+ const normalized = stderr.toLowerCase();
+ if (normalized.includes("glab auth login")) return "authentication";
+ if (normalized.includes("not found") || normalized.includes("404")) return "not-found";
+ return null;
+};
+
/** @public Service construction is part of the canonical Effect module API. */
export const make = Effect.gen(function* () {
const { process } = yield* SourceControlHost.SourceControlHost;
@@ -423,6 +432,8 @@ export const make = Effect.gen(function* () {
command: "glab",
args: input.args,
cwd: input.cwd,
+ classifyFailure: classifyGlabFailure,
+ notFoundDetail: "Merge request not found.",
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
...(input.stdin === undefined ? {} : { stdin: input.stdin }),
...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),