The best way to control Claude Code, Codex and more from any computer or phone
refactor(source-control): forges recognise their own remotes and repository keys (#23993)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 24, 2026 at 04:24 UTC
3d4c75370cd7d6ec91bb5c9763744125adc316ca
67 files changed
+981
-720
apps/mobile/src/features/pull-requests/pullRequestNavigation.test.ts
+2
-2
@@ -1,4 +1,4 @@
1
-import { EnvironmentId, ProjectId } from "@t3tools/contracts";
1
+import { EnvironmentId, ProjectId, SourceControlProviderKind } from "@t3tools/contracts";
2
import { describe, expect, it } from "vite-plus/test";
3
import { nativePullRequestDestination } from "../../lib/pullRequestNavigation";
4
@@ -10,7 +10,7 @@ const project = (id: string, canonicalKey: string, provider: string, remoteUrl:
10
canonicalKey,
11
locator: { source: "git-remote" as const, remoteName: "origin", remoteUrl },
12
displayName: canonicalKey.split("/").slice(1).join("/"),
13
- provider,
13
+ provider: SourceControlProviderKind.make(provider),
14
},
15
});
16
const projects = [
apps/server/src/git/GitManager.ts
+12
-11
@@ -49,15 +49,12 @@ import {
49
resolveProjectSettings,
50
} from "@t3tools/shared/projectSettings";
51
import {
52
- detectSourceControlProviderFromGitRemoteUrl,
52
mergeGitStatusParts,
54
- normalizeGitRemoteUrl,
53
resolveAutoFeatureBranchName,
54
sanitizeBranchFragment,
55
sanitizeFeatureBranchName,
56
} from "@t3tools/shared/git";
57
import {
60
- canonicalRepositoryKey,
58
getChangeRequestTerminologyForKind,
59
isSshRemoteUrl,
60
type ChangeRequestTerminology,
@@ -268,7 +265,7 @@ export function pullRequestRepositoryKey(value: string): string | null {
265
url.pathname = match[1];
266
url.search = "";
267
url.hash = "";
271
- return normalizeGitRemoteUrl(url.toString());
268
+ return sourceControlClients.repositoryKeyFromRemote(url.toString());
269
} catch {
270
return null;
271
}
@@ -1027,8 +1024,10 @@ export const make = Effect.gen(function* () {
1024
if (
1025
remoteUrl === null ||
1026
pullRequestKey === null ||
1030
- canonicalRepositoryKey(pullRequestKey) !==
1031
- canonicalRepositoryKey(normalizeGitRemoteUrl(remoteUrl))
1027
+ sourceControlClients.canonicalRepositoryKey(pullRequestKey) !==
1028
+ sourceControlClients.canonicalRepositoryKey(
1029
+ sourceControlClients.repositoryKeyFromRemote(remoteUrl),
1030
+ )
1031
) {
1032
return yield* cause;
1033
}
@@ -1451,7 +1450,7 @@ export const make = Effect.gen(function* () {
1450
const baseUrl =
1451
remote.remoteUrl === null
1452
? undefined
1454
- : detectSourceControlProviderFromGitRemoteUrl(remote.remoteUrl)?.baseUrl;
1453
+ : sourceControlClients.recognizeRemote(remote.remoteUrl)?.baseUrl;
1454
const host = baseUrl === undefined ? null : urlHost(baseUrl);
1455
const repository = remote.repositoryNameWithOwner?.toLowerCase();
1456
const fromEnvironment = parseGitHubRepositorySelector(environment.GH_REPO ?? "", host ?? "");
@@ -1485,7 +1484,7 @@ export const make = Effect.gen(function* () {
1484
(yield* readConfigValueNullable(cwd, `remote.${preferredRemoteName}.url`)) ??
1485
(yield* readConfigValueNullable(cwd, "remote.origin.url"));
1486
1488
- const provider = remoteUrl ? detectSourceControlProviderFromGitRemoteUrl(remoteUrl) : null;
1487
+ const provider = remoteUrl ? sourceControlClients.recognizeRemote(remoteUrl) : null;
1488
if (!remoteUrl || provider?.kind !== "unknown") return provider;
1489
const handle = yield* sourceControlProviders
1490
.resolveHandle({
@@ -1516,7 +1515,7 @@ export const make = Effect.gen(function* () {
1515
/^https?:\/\//iu.test(remoteUrl) &&
1516
(repositoryNameWithOwner?.split("/").length ?? 0) > 2
1517
) {
1519
- const kind = detectSourceControlProviderFromGitRemoteUrl(remoteUrl)?.kind;
1518
+ const kind = sourceControlClients.recognizeRemote(remoteUrl)?.kind;
1519
const provider =
1520
kind === undefined
1521
? undefined
@@ -1527,7 +1526,7 @@ export const make = Effect.gen(function* () {
1526
}
1527
return {
1528
remoteUrl,
1530
- remoteUrlKey: remoteUrl ? normalizeGitRemoteUrl(remoteUrl) : null,
1529
+ remoteUrlKey: remoteUrl ? sourceControlClients.repositoryKeyFromRemote(remoteUrl) : null,
1530
repositoryNameWithOwner,
1531
ownerLogin: parseRepositoryOwnerLogin(repositoryNameWithOwner),
1532
};
@@ -2486,7 +2485,9 @@ export const make = Effect.gen(function* () {
2485
remoteName === null
2486
? Effect.succeed(null)
2487
: readConfig(`remote.${remoteName}.url`).pipe(
2489
- Effect.map((remoteUrl) => (remoteUrl ? normalizeGitRemoteUrl(remoteUrl) : null)),
2488
+ Effect.map((remoteUrl) =>
2489
+ remoteUrl ? sourceControlClients.repositoryKeyFromRemote(remoteUrl) : null,
2490
+ ),
2491
);
2492
const remoteName = remoteNameOverride ?? (yield* readConfig(`branch.${branch}.remote`));
2493
const [headRemoteUrlKey, targetRemoteUrlKey] =
apps/server/src/git/linkCreatedPullRequest.test.ts
+2
-1
@@ -6,6 +6,7 @@ import {
6
type GitRunStackedActionResult,
7
type OrchestrationV2ServerCommand as OrchestrationCommand,
8
type OrchestrationProjectShell,
9
+ SourceControlProviderKind,
10
} from "@t3tools/contracts";
11
import { describe, expect, it } from "@effect/vitest";
12
import * as Effect from "effect/Effect";
@@ -40,7 +41,7 @@ const project: OrchestrationProjectShell = {
41
remoteName: "origin",
42
remoteUrl: "git@github.acme.test:Platform/API.git",
43
},
43
- provider: "github",
44
+ provider: SourceControlProviderKind.make("github"),
45
displayName: "Platform/API",
46
owner: "Platform",
47
name: "API",
apps/server/src/git/linkCreatedPullRequest.ts
+3
-6
@@ -1,10 +1,7 @@
1
-import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
1
import {
2
type CommandId,
4
- pullRequestHostOf,
3
type GitRunStackedActionResult,
4
type OrchestrationProjectShell,
7
- type SourceControlProviderKind,
5
type ThreadId,
6
} from "@t3tools/contracts";
7
import * as Cause from "effect/Cause";
@@ -35,11 +32,11 @@ export function createdPullRequestKey(
32
return { host: parsed.host, repository: parsed.repository, number: parsed.number, url };
33
}
34
const identity = project?.repositoryIdentity;
38
- const kind = identity?.provider as SourceControlProviderKind | undefined;
39
- const repository = sourceControlRepositorySelector(identity);
35
+ const kind = identity?.provider;
36
+ const repository = sourceControlClients.repositorySelector(identity);
37
if (!identity || kind === undefined || repository === null) return null;
38
return {
42
- host: pullRequestHostOf(identity, kind),
39
+ host: sourceControlClients.changeRequestHost(identity, kind),
40
repository: repository.toLowerCase(),
41
number,
42
url,
apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts
+6
-5
@@ -9,6 +9,7 @@ import {
9
type PullRequestRef,
10
type PullRequestReviewGuideResult,
11
type ThreadPullRequestLink,
12
+ SourceControlProviderKind,
13
} from "@t3tools/contracts";
14
import { describe, expect, it } from "@effect/vitest";
15
import * as Crypto from "effect/Crypto";
@@ -64,7 +65,7 @@ function makeProject(
65
remoteName: "origin",
66
remoteUrl: "git@github.com:T3Tools/T3Code.git",
67
},
67
- provider: "github",
68
+ provider: SourceControlProviderKind.make("github"),
69
displayName: "T3Tools/T3Code",
70
owner: "T3Tools",
71
name: "T3Code",
@@ -380,7 +381,7 @@ describe("pull request toolkit handlers", () => {
381
remoteName: "origin",
382
remoteUrl: "git@gitlab.com:group/sub/project.git",
383
},
383
- provider: "gitlab",
384
+ provider: SourceControlProviderKind.make("gitlab"),
385
displayName: "group/sub/project",
386
}),
387
});
@@ -415,7 +416,7 @@ describe("pull request toolkit handlers", () => {
416
remoteName: "origin",
417
remoteUrl: "http://dummy:secret@scm.example.test:8080/tfs/Collection/Project/_git/Repo",
418
},
418
- provider: "unknown",
419
+ provider: SourceControlProviderKind.make("unknown"),
420
displayName: "tfs/collection/project/_git/repo",
421
}),
422
});
@@ -592,7 +593,7 @@ describe("pull request guide tools", () => {
593
remoteName: "origin",
594
remoteUrl: "git@github.com:acme/web.git",
595
},
595
- provider: "github",
596
+ provider: SourceControlProviderKind.make("github"),
597
displayName: "acme/web",
598
owner: "acme",
599
name: "web",
@@ -651,7 +652,7 @@ describe("pull request guide tools", () => {
652
remoteName: "origin",
653
remoteUrl: "https://dev.azure.com/org/project/_git/web",
654
},
654
- provider: "azure-devops",
655
+ provider: SourceControlProviderKind.make("azure-devops"),
656
displayName: "org/project/_git/web",
657
owner: "org",
658
name: "web",
apps/server/src/mcp/toolkits/pullRequests/handlers.ts
+3
-5
@@ -1,13 +1,11 @@
1
import {
2
CommandId,
3
- pullRequestHostOf,
3
type OrchestrationProjectShell,
4
type OrchestrationV2ThreadShell,
5
type SourceControlProviderKind,
6
type ThreadId,
7
type ThreadPullRequestLink,
8
} from "@t3tools/contracts";
10
-import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
9
import * as Cause from "effect/Cause";
10
import * as Crypto from "effect/Crypto";
11
import * as Effect from "effect/Effect";
@@ -61,10 +59,10 @@ function projectHostAndProvider(project: OrchestrationProjectShell | undefined):
59
readonly kind: SourceControlProviderKind | null;
60
} {
61
const identity = project?.repositoryIdentity;
64
- const kind = (identity?.provider as SourceControlProviderKind | undefined) ?? null;
62
+ const kind = identity?.provider ?? null;
63
if (!identity || kind === null) return { host: null, kind: null };
64
return {
67
- host: pullRequestHostOf(identity, kind),
65
+ host: sourceControlClients.changeRequestHost(identity, kind),
66
kind,
67
};
68
}
@@ -173,7 +171,7 @@ function projectForPullRequest(
171
: pullRequestSyncKey(
172
{
173
projectId: project.id,
176
- repository: sourceControlRepositorySelector(project.repositoryIdentity) ?? "",
174
+ repository: sourceControlClients.repositorySelector(project.repositoryIdentity) ?? "",
175
number: 1,
176
},
177
project.repositoryIdentity,
apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts
+2
-2
@@ -137,7 +137,7 @@ describe("ThreadPullRequestServiceV2 reads", () => {
137
remoteName: "origin",
138
remoteUrl: "git@github.com:acme/project.git",
139
},
140
- provider: "github" as const,
140
+ provider: SourceControlProviderKind.make("github"),
141
owner: "acme",
142
name: "project",
143
}),
@@ -261,7 +261,7 @@ describe("ThreadPullRequestServiceV2 reads", () => {
261
remoteName: "origin",
262
remoteUrl: "git@github.com:acme/project.git",
263
},
264
- provider: "github" as const,
264
+ provider: SourceControlProviderKind.make("github"),
265
owner: "acme",
266
name: "project",
267
}),
apps/server/src/orchestration-v2/ThreadPullRequestService.ts
+4
-7
@@ -1,7 +1,3 @@
1
-import {
2
- canonicalRepositoryKey,
3
- sourceControlRepositorySelector,
4
-} from "@t3tools/shared/sourceControl";
1
import {
2
CommandId,
3
type OrchestrationProjectShell,
@@ -29,6 +25,7 @@ import * as ProjectStore from "./ProjectStore.ts";
25
import * as PullRequestService from "../pullRequest/PullRequestService.ts";
26
import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
27
import { forkParked } from "../serverActivation.ts";
28
+import { sourceControlClients } from "../sourceControl/sourceControlClients.ts";
29
import * as Orchestrator from "./Orchestrator.ts";
30
31
class ThreadPullRequestServiceV2 extends Context.Service<
@@ -59,8 +56,8 @@ function pullRequestMatchesProject(
56
return (
57
pullRequest.repositoryKey !== null &&
58
project.repositoryIdentity != null &&
62
- canonicalRepositoryKey(pullRequest.repositoryKey) ===
63
- canonicalRepositoryKey(project.repositoryIdentity.canonicalKey)
59
+ sourceControlClients.canonicalRepositoryKey(pullRequest.repositoryKey) ===
60
+ sourceControlClients.canonicalRepositoryKey(project.repositoryIdentity.canonicalKey)
61
);
62
}
63
@@ -78,7 +75,7 @@ const resolveProjectForPullRequestDiscovery = Effect.fn(
75
});
76
return {
77
project: { ...project, repositoryIdentity },
81
- repository: sourceControlRepositorySelector(repositoryIdentity),
78
+ repository: sourceControlClients.repositorySelector(repositoryIdentity),
79
};
80
});
81
apps/server/src/orchestration-v2/ThreadSettlementService.ts
+3
-14
@@ -26,6 +26,7 @@ import * as ServerSettings from "../serverSettings.ts";
26
import { forkParked } from "../serverActivation.ts";
27
import * as TerminalManager from "../terminal/Manager.ts";
28
import * as ProjectStore from "./ProjectStore.ts";
29
+import { sourceControlClients } from "../sourceControl/sourceControlClients.ts";
30
import * as Orchestrator from "./Orchestrator.ts";
31
import * as ProjectionStore from "./ProjectionStore.ts";
32
@@ -51,18 +52,6 @@ function latestMillis(values: ReadonlyArray<number | null>): number | null {
52
return latest;
53
}
54
54
-function canonicalRepositoryKey(key: string): string {
55
- return key
56
- .replace(
57
- /^(?:ssh\.dev\.azure\.com|vs-ssh\.visualstudio\.com)\/v3\/([^/]+)\/([^/]+)\/([^/]+)$/u,
58
- "dev.azure.com/$1/$2/_git/$3",
59
- )
60
- .replace(
61
- /^([^.]+)\.visualstudio\.com\/(?:defaultcollection\/)?([^/]+)\/_git\/([^/]+)$/u,
62
- "dev.azure.com/$1/$2/_git/$3",
63
- );
64
-}
65
-
55
function pullRequestMatchesProject(
56
pullRequest: GitManager.GitBranchPullRequest,
57
project: {
@@ -72,8 +61,8 @@ function pullRequestMatchesProject(
61
return (
62
pullRequest.repositoryKey !== null &&
63
project.repositoryIdentity != null &&
75
- canonicalRepositoryKey(pullRequest.repositoryKey) ===
76
- canonicalRepositoryKey(project.repositoryIdentity.canonicalKey)
64
+ sourceControlClients.canonicalRepositoryKey(pullRequest.repositoryKey) ===
65
+ sourceControlClients.canonicalRepositoryKey(project.repositoryIdentity.canonicalKey)
66
);
67
}
68
apps/server/src/project/AgentSessionScanner.test.ts
+5
-2
@@ -745,7 +745,7 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => {
745
yield* fileSystem.makeDirectory(submoduleGitDir, { recursive: true });
746
yield* fileSystem.writeFileString(
747
path.join(submoduleGitDir, "config"),
748
- '[remote "origin"]\n\turl = ssh://github.com/pingdotgg/vendor.git\n',
748
+ '[remote "origin"]\n\turl = ssh://gitlab.com/pingdotgg/libs/vendor.git\n',
749
);
750
yield* fileSystem.writeFileString(
751
path.join(submodule, ".git"),
@@ -767,7 +767,10 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => {
767
).toEqual([
768
{
769
path: submodule,
770
- git: { remoteKey: "github.com/pingdotgg/vendor", repository: "pingdotgg/vendor" },
770
+ git: {
771
+ remoteKey: "gitlab.com/pingdotgg/libs/vendor",
772
+ repository: "pingdotgg/libs/vendor",
773
+ },
774
},
775
{ path: noRemote, git: { remoteKey: null, repository: null } },
776
{ path: plain, git: null },
apps/server/src/project/AgentSessionScanner.ts
+6
-8
@@ -24,20 +24,17 @@ import * as Schema from "effect/Schema";
24
import * as Semaphore from "effect/Semaphore";
25
import * as Stream from "effect/Stream";
26
27
-import {
28
- normalizeGitRemoteUrl,
29
- isBareGitConfig,
30
- parseGitHubRepositoryNameWithOwnerFromRemoteUrl,
31
- parseOriginUrlFromGitConfig,
32
-} from "@t3tools/shared/git";
27
+import { isBareGitConfig, parseOriginUrlFromGitConfig } from "@t3tools/shared/git";
28
import * as HostProcess from "@t3tools/shared/HostProcess";
29
import { normalizeProjectPathForComparison } from "@t3tools/shared/path";
30
+import { repositoryPathFromRemoteUrl } from "@t3tools/source-control-core/server/SourceControlProvider";
31
32
import * as ServerConfig from "../config.ts";
33
import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
34
import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts";
35
import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
36
import * as ServerSettings from "../serverSettings.ts";
37
+import { sourceControlClients } from "../sourceControl/sourceControlClients.ts";
38
import {
39
createTranscriptJsonReader,
40
createTranscriptJsonSelector,
@@ -725,8 +722,9 @@ export const make = Effect.gen(function* () {
722
return {
723
_tag: "Repository",
724
git: {
728
- remoteKey: originUrl === null ? null : normalizeGitRemoteUrl(originUrl),
729
- repository: parseGitHubRepositoryNameWithOwnerFromRemoteUrl(originUrl),
725
+ remoteKey:
726
+ originUrl === null ? null : sourceControlClients.repositoryKeyFromRemote(originUrl),
727
+ repository: repositoryPathFromRemoteUrl(originUrl),
728
},
729
} as const;
730
});
apps/server/src/project/RepositoryIdentityResolver.ts
+4
-7
@@ -1,9 +1,5 @@
1
import type { RepositoryIdentity, SourceControlProviderError } from "@t3tools/contracts";
2
import { repositoryPathFromRemoteUrl } from "@t3tools/source-control-core/server/SourceControlProvider";
3
-import {
4
- detectSourceControlProviderFromGitRemoteUrl,
5
- normalizeGitRemoteUrl,
6
-} from "@t3tools/shared/git";
3
import * as Cache from "effect/Cache";
4
import * as Context from "effect/Context";
5
import * as Data from "effect/Data";
@@ -13,6 +9,7 @@ import * as Exit from "effect/Exit";
9
import * as Layer from "effect/Layer";
10
11
import * as ProcessRunner from "../processRunner.ts";
12
+import { sourceControlClients } from "../sourceControl/sourceControlClients.ts";
13
import { explicitBareRepositoryEnv } from "../vcs/VcsProcess.ts";
14
import * as HostProcess from "@t3tools/shared/HostProcess";
15
@@ -102,7 +99,7 @@ function buildRepositoryOrigin(
99
canonicalKey: string,
100
): RepositoryIdentity["origin"] {
101
if (!originUrl) return undefined;
105
- const originKey = normalizeGitRemoteUrl(originUrl);
102
+ const originKey = sourceControlClients.repositoryKeyFromRemote(originUrl);
103
if (originKey === canonicalKey) return undefined;
104
const displayName = repositoryPathOf(originKey, originUrl);
105
return { canonicalKey: originKey, remoteUrl: originUrl, ...(displayName ? { displayName } : {}) };
@@ -114,8 +111,8 @@ function buildRepositoryIdentity(input: {
111
readonly originUrl: string | undefined;
112
readonly rootPath: string;
113
}): RepositoryIdentity {
117
- const canonicalKey = normalizeGitRemoteUrl(input.remoteUrl);
118
- const sourceControlProvider = detectSourceControlProviderFromGitRemoteUrl(input.remoteUrl);
114
+ const canonicalKey = sourceControlClients.repositoryKeyFromRemote(input.remoteUrl);
115
+ const sourceControlProvider = sourceControlClients.recognizeRemote(input.remoteUrl);
116
const repositoryPath = repositoryPathOf(canonicalKey, input.remoteUrl);
117
const repositoryPathSegments = repositoryPath.split("/").filter((segment) => segment.length > 0);
118
const [owner] = repositoryPathSegments;
apps/server/src/pullRequest/PullRequestReviewGuideService.ts
+2
-2
@@ -24,7 +24,7 @@ import {
24
} from "@t3tools/contracts";
25
import type { ReviewGuideStackLayer } from "@t3tools/provider-core/server/textGeneration";
26
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
27
-import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
27
+import { sourceControlClients } from "../sourceControl/sourceControlClients.ts";
28
29
import * as ServerConfig from "../config.ts";
30
import * as PullRequestReviewGuides from "../persistence/PullRequestReviewGuides.ts";
@@ -104,7 +104,7 @@ const make = Effect.gen(function* () {
104
{
105
projectId: ProjectId.make("own"),
106
number: key.number,
107
- repository: sourceControlRepositorySelector(identity) ?? "",
107
+ repository: sourceControlClients.repositorySelector(identity) ?? "",
108
},
109
identity,
110
);
apps/server/src/pullRequest/PullRequestService.test.ts
+1
-1
@@ -77,7 +77,7 @@ function project(input: {
77
remoteName: "origin",
78
remoteUrl: input.remoteUrl ?? `https://${host}/${input.repository}.git`,
79
},
80
- provider: input.provider ?? "github",
80
+ provider: SourceControlProviderKind.make(input.provider ?? "github"),
81
displayName: input.repository,
82
},
83
}
apps/server/src/pullRequest/PullRequestService.ts
+64
-41
@@ -1,9 +1,4 @@
1
-import {
2
- canonicalRepositoryKey,
3
- isSshRemoteUrl,
4
- sourceControlRepositorySelector,
5
-} from "@t3tools/shared/sourceControl";
6
-import { normalizeGitRemoteUrl } from "@t3tools/shared/git";
1
+import { isSshRemoteUrl } from "@t3tools/shared/sourceControl";
2
import { parseDiffFilePaths } from "@t3tools/source-control-core/server/diffFileRevisions";
3
import * as Cache from "effect/Cache";
4
import * as Cause from "effect/Cause";
@@ -23,7 +18,6 @@ import * as SubscriptionRef from "effect/SubscriptionRef";
18
import {
19
PullRequestOperationError,
20
PullRequestUnavailableError,
26
- pullRequestHostOf,
21
pullRequestProviderRequirement,
22
resolvePullRequestAuthorFilter,
23
type OrchestrationProjectShell,
@@ -82,7 +76,7 @@ import {
76
type ThreadPullRequestKey,
77
} from "@t3tools/contracts";
78
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
85
-import { detectSourceControlProviderFromRemoteUrl } from "@t3tools/shared/sourceControl";
79
+import { sourceControlClients } from "../sourceControl/sourceControlClients.ts";
80
81
import * as ProjectService from "../project/ProjectService.ts";
82
import * as ServerSettings from "../serverSettings.ts";
@@ -500,6 +494,9 @@ function withRateLimitBackoff(
494
? {}
495
: { mergeMessageRewrite: api.mergeMessageRewrite }),
496
...(api.repositoryKey === undefined ? {} : { repositoryKey: api.repositoryKey }),
497
+ ...(api.readsPublicHostWithoutCheckout === undefined
498
+ ? {}
499
+ : { readsPublicHostWithoutCheckout: api.readsPublicHostWithoutCheckout }),
500
getViewer:
501
options?.viewerAllowsPause === true
502
? interactive("getViewer", api.getViewer)
@@ -648,6 +645,29 @@ function rankFilterOptions<A>(
645
};
646
}
647
648
+/** Whether the project's remote is SSH on a host whose SSH remotes do not name its web host. */
649
+function sshRemoteHidesWebHost(
650
+ identity: NonNullable<OrchestrationProjectShell["repositoryIdentity"]>,
651
+) {
652
+ return (
653
+ identity.provider !== undefined &&
654
+ sourceControlClients.find(identity.provider)?.sshRemoteHidesWebHost === true &&
655
+ isSshRemoteUrl(identity.locator.remoteUrl)
656
+ );
657
+}
658
+
659
+/** An HTTP remote names its server's web host, port included. */
660
+function httpRemoteHost(remoteUrl: string): string | null {
661
+ try {
662
+ const remote = new URL(remoteUrl);
663
+ return remote.protocol === "http:" || remote.protocol === "https:"
664
+ ? remote.host.toLowerCase()
665
+ : null;
666
+ } catch {
667
+ return null;
668
+ }
669
+}
670
+
671
// Capture before the provider read so a slow response keeps its original freshness through caches.
672
const observeRead = Effect.fnUntraced(function* <A, E, R>(read: Effect.Effect<A, E, R>) {
673
const observedAt = yield* Clock.currentTimeMillis;
@@ -682,24 +702,22 @@ export const make = Effect.gen(function* () {
702
if (filter.projectId !== undefined && project.id !== filter.projectId) continue;
703
const identity = project.repositoryIdentity;
704
if (
685
- (identity?.provider !== "unknown" &&
686
- !(identity?.provider === "forgejo" && isSshRemoteUrl(identity.locator.remoteUrl))) ||
687
- sourceControlRepositorySelector(project.repositoryIdentity) === null
705
+ (identity?.provider !== "unknown" && !(identity && sshRemoteHidesWebHost(identity))) ||
706
+ sourceControlClients.repositorySelector(project.repositoryIdentity) === null
707
)
708
continue;
690
- const host = pullRequestHostOf(identity, SourceControlProviderKind.make("unknown"));
709
+ const host = sourceControlClients.changeRequestHost(identity, "unknown");
710
if (
711
filter.host !== undefined &&
712
host !== "unknown" &&
713
host !== filter.host.toLowerCase() &&
695
- pullRequestHostOf(identity, SourceControlProviderKind.make("forgejo")) !==
696
- filter.host.toLowerCase() &&
714
+ httpRemoteHost(identity.locator.remoteUrl) !== filter.host.toLowerCase() &&
715
!isSshRemoteUrl(identity.locator.remoteUrl)
716
) {
717
continue;
718
}
719
const { remoteName, remoteUrl } = identity.locator;
702
- const provider = detectSourceControlProviderFromRemoteUrl(remoteUrl);
720
+ const provider = sourceControlClients.recognizeRemote(remoteUrl);
721
if (provider !== null) {
722
const candidates = refinements.get(provider.baseUrl);
723
const candidate = { project, provider, remoteName, remoteUrl };
@@ -717,10 +735,9 @@ export const make = Effect.gen(function* () {
735
sourceControlProviders.resolveHandle({
736
cwd: project.workspaceRoot,
737
context: {
720
- provider:
721
- provider.kind === "forgejo"
722
- ? { ...provider, kind: SourceControlProviderKind.make("unknown") }
723
- : provider,
738
+ provider: sourceControlClients.find(provider.kind)?.sshRemoteHidesWebHost
739
+ ? { ...provider, kind: SourceControlProviderKind.make("unknown") }
740
+ : provider,
741
remoteName,
742
remoteUrl,
743
...(filter.host !== undefined && isSshRemoteUrl(remoteUrl)
@@ -791,22 +808,20 @@ export const make = Effect.gen(function* () {
808
if (filter.projectId !== undefined && project.id !== filter.projectId) continue;
809
if (filter.projectIds !== undefined && !filter.projectIds.includes(project.id)) continue;
810
const identity = project.repositoryIdentity;
794
- let kind = identity?.provider as SourceControlProviderKind | undefined;
795
- const repository = sourceControlRepositorySelector(project.repositoryIdentity);
811
+ let kind = identity?.provider;
812
+ const repository = sourceControlClients.repositorySelector(project.repositoryIdentity);
813
if (!identity || kind === undefined || repository === null) continue;
814
let refinedProvider: SourceControlProviderInfo | null | undefined;
798
- if (
799
- kind === "unknown" ||
800
- (kind === "forgejo" && isSshRemoteUrl(identity.locator.remoteUrl))
801
- ) {
802
- const provider = detectSourceControlProviderFromRemoteUrl(identity.locator.remoteUrl);
815
+ if (kind === "unknown" || sshRemoteHidesWebHost(identity)) {
816
+ const provider = sourceControlClients.recognizeRemote(identity.locator.remoteUrl);
817
refinedProvider = provider === null ? null : refinedProviders.get(provider.baseUrl);
818
kind = refinedProvider?.kind ?? kind;
819
}
820
const host =
807
- refinedProvider?.kind === "forgejo"
821
+ refinedProvider &&
822
+ sourceControlClients.find(refinedProvider.kind)?.sshRemoteHidesWebHost
823
? new URL(refinedProvider.baseUrl).host.toLowerCase()
809
- : pullRequestHostOf(identity, kind);
824
+ : sourceControlClients.changeRequestHost(identity, kind);
825
if (filter.host !== undefined && host !== filter.host.toLowerCase()) {
826
continue;
827
}
@@ -833,9 +848,13 @@ export const make = Effect.gen(function* () {
848
api: withRateLimitBackoff(api, host, rateLimits),
849
repository,
850
host,
836
- remote: repositoryKey ?? normalizeGitRemoteUrl(`https://${host}/${repository}`),
851
+ remote:
852
+ repositoryKey ??
853
+ sourceControlClients.repositoryKeyFromRemote(`https://${host}/${repository}`),
854
repositoryKey:
838
- repositoryKey === null ? null : canonicalRepositoryKey(repositoryKey.toLowerCase()),
855
+ repositoryKey === null
856
+ ? null
857
+ : sourceControlClients.canonicalRepositoryKey(repositoryKey.toLowerCase()),
858
});
859
}
860
return { supported, unimplemented, viewerRoots };
@@ -866,11 +885,13 @@ export const make = Effect.gen(function* () {
885
}),
886
);
887
}
869
- const repositoryKey = canonicalRepositoryKey(`${host}/${repository}`.toLowerCase());
870
- // Azure SSH and legacy clone hosts differ from the browser URL's host. Compare
871
- // the complete repository identity before narrowing those checkouts by host.
888
+ const referenceKey = `${host}/${repository}`.toLowerCase();
889
+ const repositoryKey = sourceControlClients.canonicalRepositoryKey(referenceKey);
890
+ // A host that spells one repository several ways (Azure's SSH and legacy clone hosts)
891
+ // can differ from the browser URL's host. Compare the complete repository identity
892
+ // before narrowing those checkouts by host.
893
return listWorkspaceProjects(
873
- repositoryKey.startsWith("dev.azure.com/") ? {} : { host },
894
+ sourceControlClients.findByRepositoryKey(referenceKey) ? {} : { host },
895
).pipe(
896
Effect.flatMap(({ supported }) => {
897
const onHost = supported.filter((candidate) => candidate.host === host);
@@ -887,11 +908,9 @@ export const make = Effect.gen(function* () {
908
onHost.find((candidate) => candidate.repositoryKey === null);
909
if (route === undefined) {
910
return Effect.gen(function* () {
890
- const provider = ["github.com", "bitbucket.org", "codeberg.org"].includes(host)
891
- ? detectSourceControlProviderFromRemoteUrl(`https://${host}/${repository}.git`)
892
- : null;
893
- const api = provider === null ? null : registry.get(provider.kind);
894
- if (api !== null) {
911
+ const publicHost = sourceControlClients.findByPublicHost(host);
912
+ const api = publicHost === undefined ? null : registry.get(publicHost.kind);
913
+ if (api?.readsPublicHostWithoutCheckout) {
914
const selected = yield* projects.getShell(ref.projectId).pipe(
915
Effect.mapError(
916
(cause) =>
@@ -909,7 +928,9 @@ export const make = Effect.gen(function* () {
928
api: withRateLimitBackoff(api, host, rateLimits),
929
repository,
930
host,
912
- remote: normalizeGitRemoteUrl(`https://${host}/${repository}`),
931
+ remote: sourceControlClients.repositoryKeyFromRemote(
932
+ `https://${host}/${repository}`,
933
+ ),
934
repositoryKey: null,
935
};
936
}
@@ -924,7 +945,9 @@ export const make = Effect.gen(function* () {
945
: {
946
...route,
947
repository,
927
- remote: normalizeGitRemoteUrl(`https://${host}/${repository}`),
948
+ remote: sourceControlClients.repositoryKeyFromRemote(
949
+ `https://${host}/${repository}`,
950
+ ),
951
},
952
);
953
}),
apps/server/src/pullRequest/pullRequestSyncKey.test.ts
+2
-2
@@ -1,4 +1,4 @@
1
-import { ProjectId } from "@t3tools/contracts";
1
+import { ProjectId, SourceControlProviderKind } from "@t3tools/contracts";
2
import { describe, expect, it } from "vite-plus/test";
3
4
import { pullRequestSyncKey } from "./pullRequestSyncKey.ts";
@@ -13,7 +13,7 @@ describe("pullRequestSyncKey", () => {
13
])("resolves hostless and checkout-host Azure references for %s", (canonicalKey) => {
14
const identity = {
15
canonicalKey,
16
- provider: "azure-devops",
16
+ provider: SourceControlProviderKind.make("azure-devops"),
17
name: "web",
18
displayName: canonicalKey.split("/").slice(1).join("/"),
19
locator: {
apps/server/src/pullRequest/pullRequestSyncKey.ts
+17
-23
@@ -1,43 +1,37 @@
1
-import {
2
- pullRequestHostOf,
3
- type PullRequestRef,
4
- type RepositoryIdentity,
5
- SourceControlProviderKind,
6
- type ThreadPullRequestKey,
7
-} from "@t3tools/contracts";
8
-import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
1
+import type { PullRequestRef, RepositoryIdentity, ThreadPullRequestKey } from "@t3tools/contracts";
2
+import { sourceControlClients } from "../sourceControl/sourceControlClients.ts";
3
import { normalizeThreadPullRequestKey } from "../sourceControl/threadPullRequests.ts";
4
5
export function pullRequestSyncKey(
6
reference: PullRequestRef,
7
identity?: RepositoryIdentity | null,
8
): ThreadPullRequestKey | null {
15
- if (identity?.provider === "azure-devops" && !reference.repository.includes("/")) {
9
+ const host = identity
10
+ ? sourceControlClients.changeRequestHost(identity, identity.provider)
11
+ : undefined;
12
+ // A host whose tools select a repository by something other than its path (Azure DevOps takes
13
+ // the bare name) can only key such a reference through the project's own repository.
14
+ const definition = identity?.provider ? sourceControlClients.find(identity.provider) : undefined;
15
+ if (identity && definition?.repositorySelector && !reference.repository.includes("/")) {
16
if (
17
reference.repository.toLowerCase() !==
18
- sourceControlRepositorySelector(identity)?.toLowerCase() ||
19
- (reference.host !== undefined &&
20
- reference.host.toLowerCase() !==
21
- pullRequestHostOf(identity, SourceControlProviderKind.make("azure-devops")))
18
+ definition.repositorySelector(identity)?.toLowerCase() ||
19
+ (reference.host !== undefined && reference.host.toLowerCase() !== host)
20
)
21
return null;
24
- const [host, ...repository] = identity.canonicalKey.split("/");
25
- if (!host || repository.length === 0) return null;
22
+ const [projectHost, ...repository] = identity.canonicalKey.split("/");
23
+ if (!projectHost || repository.length === 0) return null;
24
return normalizeThreadPullRequestKey({
27
- host,
25
+ host: projectHost,
26
repository: repository.join("/"),
27
number: reference.number,
28
});
29
}
32
- const host =
33
- reference.host ??
34
- (identity
35
- ? pullRequestHostOf(identity, identity.provider as SourceControlProviderKind)
36
- : undefined);
37
- return host === undefined
30
+ const resolvedHost = reference.host ?? host;
31
+ return resolvedHost === undefined
32
? null
33
: normalizeThreadPullRequestKey({
40
- host,
34
+ host: resolvedHost,
35
repository: reference.repository,
36
number: reference.number,
37
});
apps/server/src/sourceControl/SourceControlProviderRegistry.ts
+3
-3
@@ -13,9 +13,9 @@ import {
13
type SourceControlProviderDiscoveryItem,
14
} from "@t3tools/contracts";
15
import type {} from "@t3tools/contracts";
16
-import { detectSourceControlProviderFromRemoteUrl } from "@t3tools/shared/sourceControl";
16
17
import * as BuiltInDrivers from "./builtInDrivers.ts";
18
+import { sourceControlClients } from "./sourceControlClients.ts";
19
import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
20
import {
21
probeSourceControlProvider,
@@ -144,7 +144,7 @@ function selectProviderContext(
144
): SourceControlProvider.SourceControlProviderContext | null {
145
const candidates: Array<SourceControlProvider.SourceControlProviderContext> = [];
146
for (const remote of remotes) {
147
- const provider = detectSourceControlProviderFromRemoteUrl(remote.url);
147
+ const provider = sourceControlClients.recognizeRemote(remote.url);
148
if (provider) {
149
candidates.push({
150
provider,
@@ -337,7 +337,7 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit
337
if (input.url.protocol !== "https:" || input.url.username || input.url.password) {
338
return undefined;
339
}
340
- const kind = detectSourceControlProviderFromRemoteUrl(input.url.href)?.kind;
340
+ const kind = sourceControlClients.recognizeRemote(input.url.href)?.kind;
341
return kind ? providers.get(kind)?.resolveLink?.(input) : undefined;
342
},
343
get,
apps/server/src/sourceControl/sourceControlClients.ts
+13
-2
@@ -10,7 +10,8 @@ import * as GitLabDriver from "@t3tools/source-control-gitlab/server/driver";
10
* The same order as the clients' registry in `@t3tools/client-runtime/source-control-clients`.
11
* A change request URL goes to the first host whose shape it has, so GitCafe, which claims
12
* `/pull/` and `/pulls/` only on its own hostnames, claims before GitHub and Forgejo, which
13
- * claim them everywhere.
13
+ * claim them everywhere. A remote goes to the first host that recognises it, and a hostname can
14
+ * carry more than one host's label (`gitea.github.example`), so recognition has its own order.
15
*/
16
export const BUILT_IN_SOURCE_CONTROL_DRIVER_LIST = [
17
GitHubDriver.driver,
@@ -23,5 +24,15 @@ export const BUILT_IN_SOURCE_CONTROL_DRIVER_LIST = [
24
25
export const sourceControlClients = makeSourceControlClientRegistry(
26
BUILT_IN_SOURCE_CONTROL_DRIVER_LIST.map((driver) => driver.definition),
26
- { claimChangeRequestUrlsFirst: [GitCafeDriver.driver.kind] },
27
+ {
28
+ claimChangeRequestUrlsFirst: [GitCafeDriver.driver.kind],
29
+ recognizeRemotesIn: [
30
+ GitCafeDriver.driver.kind,
31
+ ForgejoDriver.driver.kind,
32
+ GitHubDriver.driver.kind,
33
+ GitLabDriver.driver.kind,
34
+ AzureDevOpsDriver.driver.kind,
35
+ BitbucketDriver.driver.kind,
36
+ ],
37
+ },
38
);
apps/server/src/vcs/GitVcsDriverCore.ts
+4
-3
@@ -31,7 +31,7 @@ import {
31
type ReviewDiffPreviewSource,
32
type VcsRef,
33
} from "@t3tools/contracts";
34
-import { dedupeRemoteBranchesWithLocalMatches, normalizeGitRemoteUrl } from "@t3tools/shared/git";
34
+import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git";
35
import * as HostProcess from "@t3tools/shared/HostProcess";
36
import { compactTraceAttributes } from "@t3tools/shared/observability";
37
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
@@ -50,6 +50,7 @@ import {
50
parseRemoteRefWithRemoteNames,
51
} from "../git/remoteRefs.ts";
52
import * as ServerConfig from "../config.ts";
53
+import { sourceControlClients } from "../sourceControl/sourceControlClients.ts";
54
55
const DEFAULT_TIMEOUT_MS = 30_000;
56
const gitProcesses = Semaphore.makeUnsafe(8);
@@ -1727,7 +1728,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
1728
"ensureRemote",
1729
)(function* (input) {
1730
const preferredName = sanitizeRemoteName(input.preferredName);
1730
- const normalizedTargetUrl = normalizeGitRemoteUrl(input.url);
1731
+ const normalizedTargetUrl = sourceControlClients.repositoryKeyFromRemote(input.url);
1732
const remoteFetchUrls = yield* runGitStdout(
1733
"GitVcsDriver.ensureRemote.listRemoteUrls",
1734
input.cwd,
@@ -1735,7 +1736,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
1736
).pipe(Effect.map((stdout) => parseRemoteFetchUrls(stdout)));
1737
1738
for (const [remoteName, remoteUrl] of remoteFetchUrls.entries()) {
1738
- if (normalizeGitRemoteUrl(remoteUrl) === normalizedTargetUrl) {
1739
+ if (sourceControlClients.repositoryKeyFromRemote(remoteUrl) === normalizedTargetUrl) {
1740
return remoteName;
1741
}
1742
}
apps/web/src/components/ChatView.tsx
+2
-2
@@ -1,3 +1,4 @@
1
+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
2
import { ScrollToEndButton, WorkspaceFileDropOverlay } from "./chat/TimelineOverlays";
3
import { usePasteToFocusComposer } from "./chat/usePasteToFocusComposer";
4
import { announcedRun, isDetailBehindShell } from "./chat/threadActivityAnnouncement";
@@ -101,7 +102,6 @@ import {
102
import { formatModelSlugName, resolveSelectableModel } from "@t3tools/shared/model";
103
import { projectScriptCwd, resolveProjectScripts } from "@t3tools/shared/projectScripts";
104
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
104
-import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
105
import { resolveThreadReferenceCopyTarget } from "@t3tools/client-runtime/thread-reference";
106
import { resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";
107
import { useAtomValue } from "@effect/atom-react";
@@ -1911,7 +1911,7 @@ export default function ChatView(props: ChatViewProps) {
1911
});
1912
// The thread's own change request, placed against the project it belongs to. Without a
1913
// project there is nothing to resolve it against, so the caller falls back to the browser.
1914
- const activeProjectRepository = sourceControlRepositorySelector(
1914
+ const activeProjectRepository = sourceControlClients.repositorySelector(
1915
activeProject?.repositoryIdentity,
1916
);
1917
const {
apps/web/src/components/RightPanelTabs.tsx
+2
-2
@@ -1,4 +1,4 @@
1
-import { pullRequestHostOf, type SourceControlProviderKind } from "@t3tools/contracts";
1
+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
2
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
3
import { useProjects, useServerConfigs, useThreadShells } from "~/state/entities";
4
import {
@@ -715,7 +715,7 @@ function PullRequestSurfaceIcon({
715
const host =
716
surface.host ??
717
(identity?.provider
718
- ? pullRequestHostOf(identity, identity.provider as SourceControlProviderKind)
718
+ ? sourceControlClients.changeRequestHost(identity, identity.provider)
719
: null);
720
const configs = useServerConfigs();
721
const capabilities =
apps/web/src/components/chat/ThreadDetailsPrRow.tsx
+2
-2
@@ -1,10 +1,10 @@
1
+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
2
import { PullRequestChangeBreakdownRows } from "../pullRequest/PullRequestChangeBreakdownStat";
3
import { ThreadDetailsControl } from "./ThreadDetailsControl";
4
import { PullRequestGlyph } from "../pullRequest/pullRequestIcons";
5
import { selectEnvironmentQueryData } from "@t3tools/client-runtime/state/runtime";
6
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
7
import type { EnvironmentId, ProjectId, PullRequestRef } from "@t3tools/contracts";
7
-import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
8
import {
9
ArrowUpRightIcon,
10
EyeIcon,
@@ -106,7 +106,7 @@ export function ThreadDetailsPrRow({
106
const serverConfigs = useServerConfigs();
107
const supportsPullRequests =
108
serverConfigs.get(environmentId)?.environment.capabilities.pullRequests === true;
109
- const repository = sourceControlRepositorySelector(project?.repositoryIdentity);
109
+ const repository = sourceControlClients.repositorySelector(project?.repositoryIdentity);
110
const reference: PullRequestRef | null =
111
supportsPullRequests && project !== null
112
? linkedReference
apps/web/src/components/pullRequest/PullRequestsPage.tsx
+4
-4
@@ -1,3 +1,4 @@
1
+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
2
import { applyPullRequestDraftFilterChange } from "@t3tools/client-runtime/pull-request-query";
3
import { Spinner } from "~/components/ui/spinner";
4
import type { PullRequestSpeedActionResult } from "~/components/pullRequest/PullRequestSpeedActions";
@@ -5,7 +6,7 @@ import { usePullRequestCloseBatch } from "~/components/pullRequest/usePullReques
6
import { SidebarPointerSensor } from "~/components/Sidebar.pointer";
7
import { resolveSidebarSweepKeys } from "~/components/Sidebar.logic";
8
import { sortProjectsByGroupOrder } from "@t3tools/client-runtime/state/project-grouping";
8
-import { pullRequestHostOf, resolveEnvironmentMachineKind } from "@t3tools/contracts";
9
+import { resolveEnvironmentMachineKind } from "@t3tools/contracts";
10
import type {
11
EnvironmentId,
12
ProjectId,
@@ -15,7 +16,6 @@ import type {
16
PullRequestListInput,
17
PullRequestListResult,
18
PullRequestListState,
18
- SourceControlProviderKind,
19
} from "@t3tools/contracts";
20
import { useAtomValue } from "@effect/atom-react";
21
import { useNavigate, useSearch } from "@tanstack/react-router";
@@ -1014,9 +1014,9 @@ export function PullRequestsPage() {
1014
host:
1015
activePullRequestSurface.host ??
1016
(selectedProject?.repositoryIdentity
1017
- ? pullRequestHostOf(
1017
+ ? sourceControlClients.changeRequestHost(
1018
selectedProject.repositoryIdentity,
1019
- selectedProject.repositoryIdentity.provider as SourceControlProviderKind,
1019
+ selectedProject.repositoryIdentity.provider,
1020
)
1021
: undefined),
1022
}
apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts
+1
-1
@@ -85,7 +85,7 @@ describe("pull request checkout commands", () => {
85
remoteName: "origin",
86
remoteUrl: "git@github.com:acme/web.git",
87
},
88
- provider,
88
+ provider: SourceControlProviderKind.make(provider),
89
});
90
91
it("uses a matching enterprise identity and rejects an explicit host mismatch", () => {
apps/web/src/components/pullRequest/pullRequestDetail.logic.ts
+1
-2
@@ -5,7 +5,6 @@ import {
5
GitCommandError,
6
PullRequestDetail,
7
PullRequestOperationError,
8
- pullRequestHostOf,
8
type PullRequestAction,
9
type PullRequestActor,
10
type PullRequestBaseComparison,
@@ -135,7 +134,7 @@ export function loadingPullRequestCheckoutCommand(
134
if (
135
identity?.provider !== undefined &&
136
host &&
138
- pullRequestHostOf(identity, definition.kind) !== host
137
+ sourceControlClients.changeRequestHost(identity, definition.kind) !== host
138
) {
139
return null;
140
}
apps/web/src/components/pullRequest/pullRequestList.logic.test.ts
+3
-3
@@ -50,7 +50,7 @@ function entry(
50
) {
51
return {
52
environmentId: "env-1",
53
- provider: "github",
53
+ provider: SourceControlProviderKind.make("github"),
54
host: "github.com",
55
projectId: "project-1",
56
projectTitle: "t3code",
@@ -752,7 +752,7 @@ describe("findProjectForRepository", () => {
752
repositoryIdentity: {
753
canonicalKey: `dev.azure.com/${path}`,
754
locator: { source: "git-remote" as const, remoteName: "origin", remoteUrl: "" },
755
- provider: "azure-devops",
755
+ provider: SourceControlProviderKind.make("azure-devops"),
756
displayName: path,
757
owner: "contoso",
758
name: path.split("/").at(-1)!,
@@ -788,7 +788,7 @@ describe("findProjectForRepository", () => {
788
repositoryIdentity: {
789
canonicalKey: `github.com/${repository}`,
790
locator: { source: "git-remote" as const, remoteName: "origin", remoteUrl: "" },
791
- provider: "github",
791
+ provider: SourceControlProviderKind.make("github"),
792
displayName: repository,
793
},
794
});
apps/web/src/components/pullRequest/pullRequestList.logic.ts
+6
-6
@@ -1,3 +1,4 @@
1
+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
2
import * as Schema from "effect/Schema";
3
4
import {
@@ -5,13 +6,11 @@ import {
6
PullRequestListEntry,
7
PullRequestListProjectError,
8
PullRequestListResult,
8
- pullRequestHostOf,
9
resolvePullRequestAuthorFilter,
10
} from "@t3tools/contracts";
11
import type {
12
ProjectId,
13
RepositoryIdentity,
14
- SourceControlProviderKind,
14
PullRequestAction,
15
PullRequestActor,
16
PullRequestDiffStat,
@@ -23,8 +22,6 @@ import type {
22
PullRequestState,
23
} from "@t3tools/contracts";
24
26
-import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
27
-
25
import { toSortableTimestamp } from "../../lib/threadSort";
26
import type { PullRequestListSort } from "./pullRequestListPreferences";
27
@@ -1078,12 +1075,15 @@ export function findProjectForRepository<
1075
return false;
1076
}
1077
const identity = project.repositoryIdentity;
1081
- if (!identity || sourceControlRepositorySelector(identity)?.toLowerCase() !== repository) {
1078
+ if (
1079
+ !identity ||
1080
+ sourceControlClients.repositorySelector(identity)?.toLowerCase() !== repository
1081
+ ) {
1082
return false;
1083
}
1084
return (
1085
host === undefined ||
1086
- pullRequestHostOf(identity, identity.provider as SourceControlProviderKind) === host
1086
+ sourceControlClients.changeRequestHost(identity, identity.provider) === host
1087
);
1088
});
1089
// Azure repository names can collide across projects on the same host.
apps/web/src/components/pullRequest/usePullRequestListView.ts
+3
-4
@@ -1,13 +1,12 @@
1
+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
2
import { parsePullRequestQuery } from "@t3tools/client-runtime/pull-request-query";
3
import {
3
- pullRequestHostOf,
4
type EnvironmentId,
5
type ProjectId,
6
type PullRequestInvolvement,
7
type PullRequestListFilters,
8
type PullRequestListResult,
9
type PullRequestListState,
10
- type SourceControlProviderKind,
10
} from "@t3tools/contracts";
11
import { useState } from "react";
12
@@ -156,9 +155,9 @@ export function usePullRequestScope(search: PullRequestsSearch) {
155
const expectedHosts = (() => {
156
const byHost = new Map<string, PullRequestExpectedHost>();
157
for (const project of projects) {
159
- const kind = project.repositoryIdentity?.provider as SourceControlProviderKind | undefined;
158
+ const kind = project.repositoryIdentity?.provider;
159
if (kind === undefined) continue;
161
- const host = pullRequestHostOf(project.repositoryIdentity, kind);
160
+ const host = sourceControlClients.changeRequestHost(project.repositoryIdentity, kind);
161
if (!byHost.has(host)) byHost.set(host, { host, kind });
162
}
163
return [...byHost.values()];
apps/web/src/hooks/usePullRequestLinking.ts
+1
-2
@@ -1,4 +1,3 @@
1
-import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
1
import type {
2
EnvironmentId,
3
ScopedThreadRef,
@@ -101,7 +100,7 @@ export function usePullRequestLinking(environmentId: EnvironmentId | null | unde
100
reference: { ...parsed, url },
101
legacyProjectId: legacyProject?.id ?? null,
102
legacyRepository:
104
- sourceControlRepositorySelector(legacyProject?.repositoryIdentity) ?? undefined,
103
+ sourceControlClients.repositorySelector(legacyProject?.repositoryIdentity) ?? undefined,
104
linked,
105
});
106
if (mutation === null)
apps/web/src/lib/openPullRequestLink.ts
+2
-2
@@ -11,7 +11,6 @@ import {
11
sourceControlClients,
12
type ChangeRequestLink,
13
} from "@t3tools/client-runtime/source-control-clients";
14
-import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
14
15
import { useOpenLink } from "../browser/useOpenLink";
16
import { useClientSettings } from "../hooks/useSettings";
@@ -117,7 +116,8 @@ export function useOpenChangeRequestLink(
116
const repository =
117
serverConfigs.get(project.environmentId)?.environment.capabilities.threadPullRequests === true
118
? parsed.repository
120
- : (sourceControlRepositorySelector(project.repositoryIdentity) ?? parsed.repository);
119
+ : (sourceControlClients.repositorySelector(project.repositoryIdentity) ??
120
+ parsed.repository);
121
event.preventDefault();
122
event.stopPropagation();
123
if (resolvedPanelRef) {
packages/client-runtime/src/changeRequestLinks.test.ts
+27
-5
@@ -1,4 +1,9 @@
1
-import { EnvironmentId, ProjectId, type RepositoryIdentity } from "@t3tools/contracts";
1
+import {
2
+ EnvironmentId,
3
+ ProjectId,
4
+ type RepositoryIdentity,
5
+ SourceControlProviderKind,
6
+} from "@t3tools/contracts";
7
import { describe, expect, it } from "vite-plus/test";
8
9
import {
@@ -15,7 +20,7 @@ describe("findProjectForChangeRequest", () => {
20
const projects = [
21
project({
22
canonicalKey: "gitlab.com/t3tools/platform/t3code",
18
- provider: "gitlab",
23
+ provider: SourceControlProviderKind.make("gitlab"),
24
displayName: "t3tools/platform/t3code",
25
owner: "t3tools",
26
name: "t3code",
@@ -34,7 +39,7 @@ describe("findProjectForChangeRequest", () => {
39
const projects = [
40
project({
41
canonicalKey: "github.com/pingdotgg/t3code",
37
- provider: "github",
42
+ provider: SourceControlProviderKind.make("github"),
43
owner: "pingdotgg",
44
name: "t3code",
45
}),
@@ -56,7 +61,7 @@ describe("resolvePullRequestPreviewTarget", () => {
61
environmentId,
62
repositoryIdentity: {
63
canonicalKey: "github.com/acme/web",
59
- provider: "github",
64
+ provider: SourceControlProviderKind.make("github"),
65
displayName: "acme/web",
66
locator: { source: "git-remote", remoteName: "origin", remoteUrl: "git@github.com:acme/web" },
67
} satisfies RepositoryIdentity,
@@ -81,7 +86,7 @@ describe("resolvePullRequestPreviewTarget", () => {
86
describe("projectChangeRequestUrl", () => {
87
const identity = (provider: string): RepositoryIdentity => ({
88
canonicalKey: "github.com/acme/default",
84
- provider,
89
+ provider: SourceControlProviderKind.make(provider),
90
locator: {
91
source: "git-remote",
92
remoteName: "origin",
@@ -95,6 +100,23 @@ describe("projectChangeRequestUrl", () => {
100
);
101
});
102
103
+ it("builds the project's own Azure repository from its full path, not its short selector", () => {
104
+ const azure: RepositoryIdentity = {
105
+ canonicalKey: "dev.azure.com/org/project/_git/web",
106
+ provider: SourceControlProviderKind.make("azure-devops"),
107
+ owner: "org",
108
+ name: "web",
109
+ locator: {
110
+ source: "git-remote",
111
+ remoteName: "origin",
112
+ remoteUrl: "https://dev.azure.com/org/project/_git/web",
113
+ },
114
+ };
115
+ expect(projectChangeRequestUrl(azure, "web", 42)).toBe(
116
+ "https://dev.azure.com/org/project/_git/web/pullrequest/42",
117
+ );
118
+ });
119
+
120
it("builds nothing without a project host that knows its URL shape", () => {
121
expect(projectChangeRequestUrl(null, "acme/repository", 1)).toBeNull();
122
expect(projectChangeRequestUrl(identity("unknown"), "acme/repository", 1)).toBeNull();
packages/client-runtime/src/changeRequestLinks.ts
+8
-4
@@ -5,7 +5,6 @@ import type {
5
RepositoryIdentity,
6
} from "@t3tools/contracts";
7
import type { ChangeRequestLink } from "@t3tools/source-control-core/client/definition";
8
-import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
8
9
import { sourceControlClients } from "./sourceControlClients.ts";
10
@@ -53,7 +52,8 @@ export function resolvePullRequestPreviewTarget({
52
input: {
53
projectId: project.id,
54
host: parsed.authority ?? parsed.host,
56
- repository: sourceControlRepositorySelector(project.repositoryIdentity) ?? parsed.repository,
55
+ repository:
56
+ sourceControlClients.repositorySelector(project.repositoryIdentity) ?? parsed.repository,
57
number: parsed.number,
58
},
59
};
@@ -66,12 +66,16 @@ export function projectChangeRequestUrl(
66
number: number,
67
): string | null {
68
if (identity?.provider === undefined) return null;
69
- const host = identity.canonicalKey.split("/")[0];
69
+ const [host, ...path] = identity.canonicalKey.split("/");
70
if (!host) return null;
71
+ // The RPC selector can be shorter than the browser path (Azure's `web` for
72
+ // `org/project/_git/web`), so the project's own repository uses its full key.
73
+ const ownRepository = sourceControlClients.repositorySelector(identity) === repository;
74
return sourceControlClients.get(identity.provider).changeRequestUrl({
75
host,
73
- repository,
76
+ repository: ownRepository ? path.join("/") : repository,
77
number,
78
remoteUrl: identity.locator.remoteUrl.trim(),
79
+ ...(ownRepository && identity.webUrl !== undefined ? { webUrl: identity.webUrl } : {}),
80
});
81
}
packages/client-runtime/src/pullRequestLinkInput.ts
+2
-2
@@ -1,4 +1,4 @@
1
-import { pullRequestHostOf, type RepositoryIdentity } from "@t3tools/contracts";
1
+import type { RepositoryIdentity } from "@t3tools/contracts";
2
3
import { sourceControlClients } from "./sourceControlClients.ts";
4
@@ -42,7 +42,7 @@ export function pullRequestLinkProject(identity: RepositoryIdentity | null | und
42
(identity.owner && identity.name ? `${identity.owner}/${identity.name}` : null);
43
if (repository === null) return null;
44
const definition = sourceControlClients.get(identity.provider ?? "unknown");
45
- const host = pullRequestHostOf(identity, definition.kind);
45
+ const host = sourceControlClients.changeRequestHost(identity, definition.kind);
46
return {
47
host,
48
repository,
packages/client-runtime/src/sourceControlClients.test.ts
+113
-1
@@ -1,4 +1,4 @@
1
-import { ProjectId } from "@t3tools/contracts";
1
+import { ProjectId, SourceControlProviderKind } from "@t3tools/contracts";
2
import { describe, expect, it } from "vite-plus/test";
3
4
import { sourceControlClients } from "./sourceControlClients.ts";
@@ -238,3 +238,115 @@ describe("change request URLs built from a parsed link", () => {
238
});
239
});
240
});
241
+
242
+describe("sourceControlClients.recognizeRemote", () => {
243
+ const kindOfRemote = (url: string) => sourceControlClients.recognizeRemote(url)?.kind ?? null;
244
+
245
+ it("asks hosts in a fixed order when one hostname carries several hosts' labels", () => {
246
+ expect(kindOfRemote("https://gitea.github.example/o/r")).toBe("forgejo");
247
+ expect(kindOfRemote("https://forgejo.gitlab.example/o/r")).toBe("forgejo");
248
+ expect(kindOfRemote("https://gitlab.github.example/o/r")).toBe("github");
249
+ expect(kindOfRemote("https://bitbucket.gitlab.example/o/r")).toBe("gitlab");
250
+ expect(kindOfRemote("https://bitbucket.visualstudio.com/p/_git/r")).toBe("azure-devops");
251
+ expect(kindOfRemote("git@git.cafe:pingdotgg/t3code.git")).toBe("gitcafe");
252
+ });
253
+
254
+ it("reads a remote no host claims as an unknown host, and a local path as no host", () => {
255
+ expect(
256
+ sourceControlClients.recognizeRemote("https://self-hosted.example.test:8443/group/repo.git"),
257
+ ).toEqual({
258
+ kind: "unknown",
259
+ name: "self-hosted.example.test:8443",
260
+ baseUrl: "https://self-hosted.example.test:8443",
261
+ });
262
+ expect(sourceControlClients.recognizeRemote("git@github-work:owner/repo.git")).toEqual({
263
+ kind: "unknown",
264
+ name: "github-work",
265
+ baseUrl: "https://github-work",
266
+ });
267
+ for (const local of ["/srv/git/repo.git", "C:/repos/project", "file:///srv/git/repo.git", ""]) {
268
+ expect(sourceControlClients.recognizeRemote(local), local).toBeNull();
269
+ }
270
+ });
271
+});
272
+
273
+describe("sourceControlClients repository keys", () => {
274
+ // Persisted as `repositoryIdentity.canonicalKey` and in thread pull request keys.
275
+ it.each([
276
+ ["git@github.com:T3Tools/T3Code.git", "github.com/t3tools/t3code"],
277
+ ["ssh://git@gitlab.company.com:2222/team/project.git", "gitlab.company.com/team/project"],
278
+ [
279
+ "git@ssh.dev.azure.com:v3/T3Tools/Platform/T3Code",
280
+ "dev.azure.com/t3tools/platform/_git/t3code",
281
+ ],
282
+ [
283
+ "T3Tools@vs-ssh.visualstudio.com:v3/T3Tools/Platform/T3Code",
284
+ "t3tools.visualstudio.com/platform/_git/t3code",
285
+ ],
286
+ [
287
+ "https://T3Tools.visualstudio.com/DefaultCollection/Platform/_git/T3Code",
288
+ "t3tools.visualstudio.com/defaultcollection/platform/_git/t3code",
289
+ ],
290
+ ["git@ssh.dev.azure.com:v3/o/p", "ssh.dev.azure.com/v3/o/p"],
291
+ ["ssh.dev.azure.com/v3/o/p/r", "ssh.dev.azure.com/v3/o/p/r"],
292
+ ["C:/repos/project", "c:/repos/project"],
293
+ ])("keys %s as %s", (remote, key) => {
294
+ expect(sourceControlClients.repositoryKeyFromRemote(remote)).toBe(key);
295
+ });
296
+
297
+ it("compares Azure DevOps spellings on dev.azure.com and leaves other keys alone", () => {
298
+ expect(
299
+ sourceControlClients.canonicalRepositoryKey(
300
+ "org.visualstudio.com/defaultcollection/project/_git/repo",
301
+ ),
302
+ ).toBe("dev.azure.com/org/project/_git/repo");
303
+ expect(sourceControlClients.findByRepositoryKey("dev.azure.com/o/r")?.kind).toBe(
304
+ "azure-devops",
305
+ );
306
+ expect(sourceControlClients.canonicalRepositoryKey("tfs.corp.example/c/p/_git/r")).toBe(
307
+ "tfs.corp.example/c/p/_git/r",
308
+ );
309
+ expect(sourceControlClients.findByRepositoryKey("github.com/o/r")).toBeUndefined();
310
+ });
311
+});
312
+
313
+describe("sourceControlClients project hosts", () => {
314
+ const identity = {
315
+ canonicalKey: "forge.example/team/repo",
316
+ locator: { remoteUrl: "http://forge.example:3000/team/repo.git" },
317
+ };
318
+
319
+ it("keeps an HTTP remote's port for Forgejo only, and falls back to the kind without a key", () => {
320
+ expect(sourceControlClients.changeRequestHost(identity, "forgejo")).toBe("forge.example:3000");
321
+ expect(sourceControlClients.changeRequestHost(identity, "gitlab")).toBe("forge.example");
322
+ expect(sourceControlClients.changeRequestHost(identity, undefined)).toBe("forge.example");
323
+ expect(
324
+ sourceControlClients.changeRequestHost(
325
+ { locator: { remoteUrl: "https://x.example/a/b" } },
326
+ "github",
327
+ ),
328
+ ).toBe("github");
329
+ });
330
+
331
+ it("selects a repository by its path except where the host's tools take a name", () => {
332
+ const repository = {
333
+ displayName: "group/subgroup/service",
334
+ owner: "group",
335
+ name: "service",
336
+ };
337
+ expect(sourceControlClients.repositorySelector(repository)).toBe("group/subgroup/service");
338
+ expect(
339
+ sourceControlClients.repositorySelector({
340
+ ...repository,
341
+ provider: SourceControlProviderKind.make("gitlab"),
342
+ }),
343
+ ).toBe("group/subgroup/service");
344
+ expect(
345
+ sourceControlClients.repositorySelector({
346
+ ...repository,
347
+ provider: SourceControlProviderKind.make("azure-devops"),
348
+ }),
349
+ ).toBe("service");
350
+ expect(sourceControlClients.repositorySelector({ owner: "o", name: "r" })).toBe("o/r");
351
+ });
352
+});
packages/client-runtime/src/sourceControlClients.ts
+13
-2
@@ -22,7 +22,8 @@ import * as GitLab from "@t3tools/source-control-gitlab/client/definition";
22
* GitHub comes first because a repository that has not reported its host yet reads as GitHub,
23
* which is what clients have always shown there. A change request URL goes to the first host
24
* whose shape it has, so GitCafe, which claims `/pull/` and `/pulls/` only on its own hostnames,
25
- * claims before GitHub and Forgejo, which claim them everywhere. The server's
25
+ * claims before GitHub and Forgejo, which claim them everywhere. A hostname can carry more than
26
+ * one host's label (`gitea.github.example`), so remote recognition has its own order. The server's
27
* `sourceControl/sourceControlClients.ts` keeps the same order.
28
*/
29
const BUILT_IN_SOURCE_CONTROL_CLIENTS = [
@@ -36,7 +37,17 @@ const BUILT_IN_SOURCE_CONTROL_CLIENTS = [
37
38
export const sourceControlClients = makeSourceControlClientRegistry(
39
BUILT_IN_SOURCE_CONTROL_CLIENTS,
39
- { claimChangeRequestUrlsFirst: [GitCafe.definition.kind] },
40
+ {
41
+ claimChangeRequestUrlsFirst: [GitCafe.definition.kind],
42
+ recognizeRemotesIn: [
43
+ GitCafe.definition.kind,
44
+ Forgejo.definition.kind,
45
+ GitHub.definition.kind,
46
+ GitLab.definition.kind,
47
+ AzureDevOps.definition.kind,
48
+ Bitbucket.definition.kind,
49
+ ],
50
+ },
51
);
52
53
export type { GitHubSettings } from "@t3tools/source-control-github/client/definition";
packages/client-runtime/src/state/projectGrouping.test.ts
+2
-2
@@ -1,4 +1,4 @@
1
-import { EnvironmentId, ProjectId } from "@t3tools/contracts";
1
+import { EnvironmentId, ProjectId, SourceControlProviderKind } from "@t3tools/contracts";
2
import { describe, expect, it } from "vite-plus/test";
3
4
import type { EnvironmentProject } from "./models.ts";
@@ -84,7 +84,7 @@ const repositoryIdentity = {
84
remoteName: "upstream",
85
remoteUrl: "https://github.com/t3tools/t3code.git",
86
},
87
- provider: "github",
87
+ provider: SourceControlProviderKind.make("github"),
88
owner: "t3tools",
89
name: "t3code",
90
displayName: "T3 Code",
packages/contracts/src/environment.ts
+2
-1
@@ -8,6 +8,7 @@ import {
8
ThreadId,
9
TrimmedNonEmptyString,
10
} from "./baseSchemas.ts";
11
+import { SourceControlProviderKind } from "./sourceControl.ts";
12
13
export const ORCHESTRATION_PROTOCOL_VERSION = 2;
14
export const ORCHESTRATION_PROTOCOL_VERSION_TEXT = "2";
@@ -186,7 +187,7 @@ export const RepositoryIdentity = Schema.Struct({
187
/** Work tree root, or the git dir for a bare repository. */
188
rootPath: Schema.optionalKey(TrimmedNonEmptyString),
189
displayName: Schema.optionalKey(TrimmedNonEmptyString),
189
- provider: Schema.optionalKey(TrimmedNonEmptyString),
190
+ provider: Schema.optionalKey(SourceControlProviderKind),
191
owner: Schema.optionalKey(TrimmedNonEmptyString),
192
name: Schema.optionalKey(TrimmedNonEmptyString),
193
origin: Schema.optionalKey(RepositoryOrigin),
packages/contracts/src/pullRequest.test.ts
-19
@@ -5,7 +5,6 @@ import { describe, expect, it } from "vite-plus/test";
5
import {
6
PullRequestDetail,
7
PullRequestListResult,
8
- pullRequestHostOf,
8
resolvePullRequestAuthorFilter,
9
} from "./pullRequest.ts";
10
@@ -61,24 +60,6 @@ const LIST_RESULT: PullRequestListResult = {
60
};
61
62
describe("PullRequestListResult", () => {
64
- it("separates Forgejo HTTP ports while preserving other provider host identities", () => {
65
- const identity = {
66
- canonicalKey: "forge.example/team/repo",
67
- locator: { remoteUrl: "http://forge.example:3000/team/repo.git" },
68
- };
69
- expect(pullRequestHostOf(identity, SourceControlProviderKind.make("forgejo"))).toBe(
70
- "forge.example:3000",
71
- );
72
- expect(pullRequestHostOf(identity, SourceControlProviderKind.make("gitlab"))).toBe(
73
- "forge.example",
74
- );
75
- expect(
76
- pullRequestHostOf(
77
- { ...identity, locator: { remoteUrl: "ssh://git@forge.example:2222/team/repo.git" } },
78
- SourceControlProviderKind.make("forgejo"),
79
- ),
80
- ).toBe("forge.example");
81
- });
63
/**
64
* The RPC builds this codec at call time, so a shape it cannot lower — an open-keyed record
65
* with an optional value, for one — fails as an interrupted request rather than as a schema
packages/contracts/src/pullRequest.ts
-21
@@ -938,27 +938,6 @@ const PROVIDER_REQUIREMENT = new Map<
938
],
939
]);
940
941
-export function pullRequestHostOf(
942
- identity:
943
- | {
944
- readonly canonicalKey?: string | undefined;
945
- readonly locator?: { readonly remoteUrl: string } | undefined;
946
- }
947
- | null
948
- | undefined,
949
- kind: SourceControlProviderKind,
950
-): string {
951
- if (kind === "forgejo") {
952
- try {
953
- const remote = new URL(identity?.locator?.remoteUrl ?? "");
954
- if (remote.protocol === "http:" || remote.protocol === "https:")
955
- return remote.host.toLowerCase();
956
- } catch {}
957
- }
958
- const host = identity?.canonicalKey?.split("/")[0]?.trim();
959
- return host === undefined || host.length === 0 ? kind : host.toLowerCase();
960
-}
961
-
941
/**
942
* `author:me` names whoever is signed in to the host being read, GitHub's `@me` spelled either
943
* way. A host's own search would answer it, but the page and the server both re-check an author
packages/shared/src/git.test.ts
-21
@@ -62,27 +62,6 @@ describe("normalizeGitRemoteUrl", () => {
62
expect(normalizeGitRemoteUrl("C:/repos/project")).toBe("c:/repos/project");
63
expect(normalizeGitRemoteUrl("git@x:team/project.git")).toBe("x/team/project");
64
});
65
-
66
- it("gives an Azure DevOps repository the same key over SSH as over HTTPS", () => {
67
- expect(normalizeGitRemoteUrl("git@ssh.dev.azure.com:v3/T3Tools/Platform/T3Code")).toBe(
68
- "dev.azure.com/t3tools/platform/_git/t3code",
69
- );
70
- expect(normalizeGitRemoteUrl("ssh://git@ssh.dev.azure.com:22/v3/T3Tools/Platform/T3Code")).toBe(
71
- "dev.azure.com/t3tools/platform/_git/t3code",
72
- );
73
- expect(
74
- normalizeGitRemoteUrl("https://T3Tools@dev.azure.com/T3Tools/Platform/_git/T3Code"),
75
- ).toBe("dev.azure.com/t3tools/platform/_git/t3code");
76
- });
77
-
78
- it("puts the organization back in the host on the name dev.azure.com replaced", () => {
79
- expect(
80
- normalizeGitRemoteUrl("T3Tools@vs-ssh.visualstudio.com:v3/T3Tools/Platform/T3Code"),
81
- ).toBe("t3tools.visualstudio.com/platform/_git/t3code");
82
- expect(normalizeGitRemoteUrl("https://T3Tools.visualstudio.com/Platform/_git/T3Code")).toBe(
83
- "t3tools.visualstudio.com/platform/_git/t3code",
84
- );
85
- });
65
});
66
67
describe("parseOriginUrlFromGitConfig", () => {
packages/shared/src/git.ts
+24
-49
@@ -1,7 +1,6 @@
1
import type {
2
BranchNamingOptions,
3
VcsRef,
4
- SourceControlProviderInfo,
4
VcsStatusLocalResult,
5
VcsStatusRemoteResult,
6
VcsStatusResult,
@@ -9,7 +8,6 @@ import type {
8
} from "@t3tools/contracts";
9
import * as Arr from "effect/Array";
10
import * as Result from "effect/Result";
12
-import { detectSourceControlProviderFromRemoteUrl } from "./sourceControl.ts";
11
12
export const WORKTREE_BRANCH_PREFIX = "t3";
13
const TEMP_WORKTREE_HEX_TOKEN = "[0-9a-f]{8}";
@@ -125,41 +123,32 @@ export function isTemporaryWorktreeBranch(refName: string): boolean {
123
return TEMP_WORKTREE_BRANCH_PATTERN.test(refName.trim().toLowerCase());
124
}
125
128
-/**
129
- * Azure alone addresses one repository under two names that share no part: `ssh.dev.azure.com` and
130
- * `v3/{org}/{project}/{repo}` over SSH, against `dev.azure.com` and `{org}/{project}/_git/{repo}`
131
- * everywhere a person sees it. A project cloned over SSH would otherwise be a different repository
132
- * to every comparison made against a pull request URL, which arrives in the web spelling.
133
- */
134
-function azureDevOpsRepositoryKey(host: string, segments: ReadonlyArray<string>): string | null {
135
- if (host !== "ssh.dev.azure.com" && host !== "vs-ssh.visualstudio.com") return null;
136
- const [marker, organization, project, repository] = segments;
137
- if (segments.length !== 4 || marker !== "v3") return null;
138
- if (!organization || !project || !repository) return null;
139
- return host === "ssh.dev.azure.com"
140
- ? `dev.azure.com/${organization}/${project}/_git/${repository}`
141
- : `${organization}.visualstudio.com/${project}/_git/${repository}`;
142
-}
143
-
144
-export function normalizeGitRemoteUrl(value: string): string {
145
- const normalized = value
126
+function lowerCaseRemote(value: string): string {
127
+ return value
128
.trim()
129
.replace(/\/+$/g, "")
130
.replace(/\.git$/i, "")
131
.toLowerCase();
132
+}
133
+
134
+/**
135
+ * The host and repository path a remote names, lower case and without a port, or null for a
136
+ * remote that names no host, such as a local path.
137
+ */
138
+export function parseGitRemoteRepository(
139
+ value: string,
140
+): { readonly host: string; readonly path: string } | null {
141
+ const normalized = lowerCaseRemote(value);
142
143
if (/^(?:ssh|https?|git):\/\//i.test(normalized)) {
144
try {
145
const url = new URL(normalized);
146
const repositorySegments = url.pathname.split("/").filter((segment) => segment.length > 0);
147
if (url.hostname && repositorySegments.length > 1) {
156
- return (
157
- azureDevOpsRepositoryKey(url.hostname, repositorySegments) ??
158
- `${url.hostname}/${repositorySegments.join("/")}`
159
- );
148
+ return { host: url.hostname, path: repositorySegments.join("/") };
149
}
150
} catch {
162
- return normalized;
151
+ return null;
152
}
153
}
154
@@ -169,11 +158,17 @@ export function normalizeGitRemoteUrl(value: string): string {
158
: /^(?:[a-zA-Z0-9._-]+@)?([^@:/\\\s]+):\/?([^/\s]+(?:\/[^/\s]+)+)$/i.exec(normalized);
159
const scpHost = scpStyleHostAndPath?.[1];
160
const scpPath = scpStyleHostAndPath?.[2];
172
- if (scpHost && scpPath) {
173
- return azureDevOpsRepositoryKey(scpHost, scpPath.split("/")) ?? `${scpHost}/${scpPath}`;
174
- }
161
+ return scpHost && scpPath ? { host: scpHost, path: scpPath } : null;
162
+}
163
176
- return normalized;
164
+/**
165
+ * `host/path` for a remote that names a host, otherwise the remote itself, lower case. A host that
166
+ * spells repositories differently over SSH has its source control registry's
167
+ * `repositoryKeyFromRemote` rewrite this, so persisted keys come from that, not from here.
168
+ */
169
+export function normalizeGitRemoteUrl(value: string): string {
170
+ const repository = parseGitRemoteRepository(value);
171
+ return repository === null ? lowerCaseRemote(value) : `${repository.host}/${repository.path}`;
172
}
173
174
function parseGitConfigValue(raw: string): string {
@@ -251,20 +246,6 @@ export function parseOriginUrlFromGitConfig(configText: string): string | null {
246
return originUrl ?? firstRemoteUrl;
247
}
248
254
-export function parseGitHubRepositoryNameWithOwnerFromRemoteUrl(url: string | null): string | null {
255
- const trimmed = url?.trim() ?? "";
256
- if (trimmed.length === 0) {
257
- return null;
258
- }
259
-
260
- const match =
261
- /^(?:git@github\.com:|ssh:\/\/(?:git@)?github\.com\/|https:\/\/github\.com\/|git:\/\/github\.com\/)([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i.exec(
262
- trimmed,
263
- );
264
- const repositoryNameWithOwner = match?.[1]?.trim() ?? "";
265
- return repositoryNameWithOwner.length > 0 ? repositoryNameWithOwner : null;
266
-}
267
-
249
function deriveLocalBranchNameCandidatesFromRemoteRef(
250
branchName: string,
251
remoteName?: string,
@@ -318,12 +299,6 @@ export function dedupeRemoteBranchesWithLocalMatches(
299
});
300
}
301
321
-export function detectSourceControlProviderFromGitRemoteUrl(
322
- remoteUrl: string,
323
-): SourceControlProviderInfo | null {
324
- return detectSourceControlProviderFromRemoteUrl(remoteUrl);
325
-}
326
-
302
const EMPTY_GIT_STATUS_REMOTE: VcsStatusRemoteResult = {
303
hasUpstream: false,
304
aheadCount: 0,
packages/shared/src/sourceControl.test.ts
+6
-166
@@ -1,171 +1,11 @@
1
import { SourceControlProviderKind } from "@t3tools/contracts";
2
-import { describe, expect, it } from "vite-plus/test";
2
+import { expect, it } from "vite-plus/test";
3
4
-import {
5
- sourceControlRepositorySelector,
6
- detectSourceControlProviderFromRemoteUrl,
7
- getChangeRequestTerminologyForKind,
8
-} from "./sourceControl.ts";
4
+import { getChangeRequestTerminologyForKind } from "./sourceControl.ts";
5
10
-describe("detectSourceControlProviderFromRemoteUrl", () => {
11
- it("detects Forgejo and Gitea hosts while preserving HTTP origins", () => {
12
- for (const host of ["codeberg.org", "forgejo.example.test", "gitea.example.test"]) {
13
- expect(detectSourceControlProviderFromRemoteUrl(`http://${host}:3000/team/repo.git`)).toEqual(
14
- {
15
- kind: "forgejo",
16
- name: "Forgejo",
17
- baseUrl: `http://${host}:3000`,
18
- },
19
- );
20
- }
21
- expect(getChangeRequestTerminologyForKind(SourceControlProviderKind.make("forgejo"))).toEqual({
22
- shortLabel: "PR",
23
- singular: "pull request",
24
- });
6
+it("calls a Forgejo change request a pull request", () => {
7
+ expect(getChangeRequestTerminologyForKind(SourceControlProviderKind.make("forgejo"))).toEqual({
8
+ shortLabel: "PR",
9
+ singular: "pull request",
10
});
26
-
27
- it("detects Azure DevOps SSH remotes", () => {
28
- expect(
29
- detectSourceControlProviderFromRemoteUrl("git@ssh.dev.azure.com:v3/org/project/repo")?.kind,
30
- ).toBe("azure-devops");
31
- expect(
32
- detectSourceControlProviderFromRemoteUrl("ssh://git@ssh.dev.azure.com:22/v3/org/project/repo")
33
- ?.kind,
34
- ).toBe("azure-devops");
35
- expect(
36
- detectSourceControlProviderFromRemoteUrl("git@vs-ssh.visualstudio.com:v3/org/project/repo")
37
- ?.kind,
38
- ).toBe("azure-devops");
39
- });
40
-
41
- it("preserves ports while classifying by hostname", () => {
42
- expect(
43
- detectSourceControlProviderFromRemoteUrl("https://gitlab.com:8443/group/repo.git"),
44
- ).toEqual({
45
- kind: "gitlab",
46
- name: "GitLab",
47
- baseUrl: "https://gitlab.com:8443",
48
- });
49
- expect(
50
- detectSourceControlProviderFromRemoteUrl(
51
- "https://self-hosted.example.test:8443/group/repo.git",
52
- ),
53
- ).toEqual({
54
- kind: "unknown",
55
- name: "self-hosted.example.test:8443",
56
- baseUrl: "https://self-hosted.example.test:8443",
57
- });
58
- });
59
-
60
- it("does not reuse SSH ports for HTTPS provider URLs", () => {
61
- expect(
62
- detectSourceControlProviderFromRemoteUrl("ssh://git@gitlab.example.test:24/group/repo.git"),
63
- ).toEqual({
64
- kind: "gitlab",
65
- name: "GitLab Self-Hosted",
66
- baseUrl: "https://gitlab.example.test",
67
- });
68
- expect(
69
- detectSourceControlProviderFromRemoteUrl("ssh://git@code.example.test:24/team/project.git"),
70
- ).toEqual({
71
- kind: "unknown",
72
- name: "code.example.test",
73
- baseUrl: "https://code.example.test",
74
- });
75
- });
76
-
77
- it("matches self-hosted providers by complete DNS labels", () => {
78
- expect(
79
- detectSourceControlProviderFromRemoteUrl("https://github.example.com/owner/repo.git")?.kind,
80
- ).toBe("github");
81
- expect(
82
- detectSourceControlProviderFromRemoteUrl("https://gitlab.example.com/group/repo.git")?.kind,
83
- ).toBe("gitlab");
84
- expect(
85
- detectSourceControlProviderFromRemoteUrl("https://bitbucket.example.com/workspace/repo.git")
86
- ?.kind,
87
- ).toBe("bitbucket");
88
- });
89
-
90
- it("detects GitHub Enterprise Cloud data residency hosts on ghe.com", () => {
91
- expect(detectSourceControlProviderFromRemoteUrl("https://acme.ghe.com/owner/repo.git")).toEqual(
92
- {
93
- kind: "github",
94
- name: "GitHub Self-Hosted",
95
- baseUrl: "https://acme.ghe.com",
96
- },
97
- );
98
- expect(detectSourceControlProviderFromRemoteUrl("git@acme.ghe.com:owner/repo.git")?.kind).toBe(
99
- "github",
100
- );
101
- expect(detectSourceControlProviderFromRemoteUrl("https://ghe.com/owner/repo.git")?.kind).toBe(
102
- "unknown",
103
- );
104
- });
105
-
106
- it("does not match provider names embedded in unrelated DNS labels", () => {
107
- expect(
108
- detectSourceControlProviderFromRemoteUrl("https://notgithub.example.com/owner/repo.git")
109
- ?.kind,
110
- ).toBe("unknown");
111
- expect(
112
- detectSourceControlProviderFromRemoteUrl("https://notgitlab.example.com/group/repo.git")
113
- ?.kind,
114
- ).toBe("unknown");
115
- expect(
116
- detectSourceControlProviderFromRemoteUrl(
117
- "https://notbitbucket.example.com/workspace/repo.git",
118
- )?.kind,
119
- ).toBe("unknown");
120
- });
121
-
122
- it("detects SSH remotes with non-git SSH users (e.g. gitlab@, deploy@)", () => {
123
- expect(
124
- detectSourceControlProviderFromRemoteUrl("gitlab@gitlab.example.com:group/project.git")?.kind,
125
- ).toBe("gitlab");
126
- expect(
127
- detectSourceControlProviderFromRemoteUrl("gitlab@gitlab.example.com:group/project.git")
128
- ?.baseUrl,
129
- ).toBe("https://gitlab.example.com");
130
- expect(detectSourceControlProviderFromRemoteUrl("deploy@github.com:owner/repo.git")?.kind).toBe(
131
- "github",
132
- );
133
- expect(
134
- detectSourceControlProviderFromRemoteUrl("git@bitbucket.org:workspace/repo.git")?.kind,
135
- ).toBe("bitbucket");
136
- });
137
-});
138
-
139
-it("names an Azure DevOps repository by its own name, not its project path", () => {
140
- // `az repos pr list --repository` takes a name and detects the organisation and project from
141
- // the checkout; the recorded `org/project/_git/repo` path is refused, and the repository then
142
- // reads as unavailable on the page.
143
- const selector = sourceControlRepositorySelector({
144
- provider: "azure-devops",
145
- displayName: "contoso/payments/_git/checkout",
146
- owner: "contoso",
147
- name: "checkout",
148
- });
149
- expect(selector).toBe("checkout");
150
-});
151
-
152
-it("decodes an Azure DevOps repository name that the remote URL percent-encodes", () => {
153
- // A remote spells a space as `%20`, and `az repos pr list --repository` reads that literally.
154
- const selector = sourceControlRepositorySelector({
155
- provider: "azure-devops",
156
- displayName: "contoso/payments%20(eu)/_git/checkout%20(eu)",
157
- owner: "contoso",
158
- name: "checkout%20(eu)",
159
- });
160
- expect(selector).toBe("checkout (eu)");
161
-});
162
-
163
-it("keeps a GitLab identity's whole path, because a nested group is part of the name", () => {
164
- const selector = sourceControlRepositorySelector({
165
- provider: "gitlab",
166
- displayName: "group/subgroup/service",
167
- owner: "group",
168
- name: "service",
169
- });
170
- expect(selector).toBe("group/subgroup/service");
11
});
packages/shared/src/sourceControl.ts
+1
-180
@@ -1,5 +1,4 @@
1
-import { SourceControlProviderKind } from "@t3tools/contracts";
2
-import type { RepositoryIdentity, SourceControlProviderInfo } from "@t3tools/contracts";
1
+import type { SourceControlProviderInfo, SourceControlProviderKind } from "@t3tools/contracts";
2
3
export interface ChangeRequestPresentation {
4
readonly icon:
@@ -143,181 +142,3 @@ export function isSshRemoteUrl(remoteUrl: string): boolean {
142
const trimmed = remoteUrl.trim();
143
return SCP_SSH_REMOTE_PATTERN.test(trimmed) || trimmed.toLowerCase().startsWith("ssh://");
144
}
146
-
147
-function parseRemoteHost(remoteUrl: string): string | null {
148
- const trimmed = remoteUrl.trim();
149
- if (trimmed.length === 0) {
150
- return null;
151
- }
152
-
153
- const scpMatch = SCP_SSH_REMOTE_PATTERN.exec(trimmed);
154
- if (scpMatch?.[1]) {
155
- return scpMatch[1].toLowerCase();
156
- }
157
-
158
- try {
159
- const url = new URL(trimmed);
160
- return (url.protocol === "ssh:" ? url.hostname : url.host).toLowerCase();
161
- } catch {
162
- return null;
163
- }
164
-}
165
-
166
-function parseHostName(host: string): string {
167
- try {
168
- return new URL(`https://${host}`).hostname.toLowerCase();
169
- } catch {
170
- return host.replace(/:\d+$/u, "").toLowerCase();
171
- }
172
-}
173
-
174
-function toBaseUrl(host: string): string {
175
- return `https://${host}`;
176
-}
177
-
178
-function hasDnsLabel(host: string, label: string): boolean {
179
- return host.split(".").includes(label);
180
-}
181
-
182
-/** `*.ghe.com` is GitHub Enterprise Cloud with data residency, one subdomain per enterprise. */
183
-function isGitHubHost(host: string): boolean {
184
- return host === "github.com" || host.endsWith(".ghe.com") || hasDnsLabel(host, "github");
185
-}
186
-
187
-function isGitLabHost(host: string): boolean {
188
- return host === "gitlab.com" || hasDnsLabel(host, "gitlab");
189
-}
190
-
191
-function isAzureDevOpsHost(host: string): boolean {
192
- // `ssh.dev.azure.com` is the default Azure DevOps SSH clone host
193
- // (git@ssh.dev.azure.com:v3/org/project/repo), so match any `*.dev.azure.com`
194
- // subdomain, not just the bare `dev.azure.com`. Legacy hosts stay under
195
- // `.visualstudio.com` (including `vs-ssh.visualstudio.com`).
196
- return (
197
- host === "dev.azure.com" ||
198
- host.endsWith(".dev.azure.com") ||
199
- host.endsWith(".visualstudio.com")
200
- );
201
-}
202
-
203
-function isGitCafeHost(host: string): boolean {
204
- return host === "git.cafe" || host === "staging.git.cafe";
205
-}
206
-
207
-function isBitbucketHost(host: string): boolean {
208
- return host === "bitbucket.org" || hasDnsLabel(host, "bitbucket");
209
-}
210
-
211
-export function detectSourceControlProviderFromRemoteUrl(
212
- remoteUrl: string,
213
-): SourceControlProviderInfo | null {
214
- const host = parseRemoteHost(remoteUrl);
215
- if (!host) {
216
- return null;
217
- }
218
- const hostname = parseHostName(host);
219
-
220
- if (isGitCafeHost(hostname)) {
221
- return {
222
- kind: SourceControlProviderKind.make("gitcafe"),
223
- name: "GitCafe",
224
- baseUrl: toBaseUrl(hostname),
225
- };
226
- }
227
-
228
- if (
229
- hostname === "codeberg.org" ||
230
- hasDnsLabel(hostname, "forgejo") ||
231
- hasDnsLabel(hostname, "gitea")
232
- ) {
233
- return {
234
- kind: SourceControlProviderKind.make("forgejo"),
235
- name: "Forgejo",
236
- baseUrl: /^https?:/iu.test(remoteUrl.trim())
237
- ? new URL(remoteUrl.trim()).origin
238
- : toBaseUrl(host),
239
- };
240
- }
241
-
242
- if (isGitHubHost(hostname)) {
243
- return {
244
- kind: SourceControlProviderKind.make("github"),
245
- name: hostname === "github.com" ? "GitHub" : "GitHub Self-Hosted",
246
- baseUrl: toBaseUrl(host),
247
- };
248
- }
249
-
250
- if (isGitLabHost(hostname)) {
251
- return {
252
- kind: SourceControlProviderKind.make("gitlab"),
253
- name: hostname === "gitlab.com" ? "GitLab" : "GitLab Self-Hosted",
254
- baseUrl: toBaseUrl(host),
255
- };
256
- }
257
-
258
- if (isAzureDevOpsHost(hostname)) {
259
- return {
260
- kind: SourceControlProviderKind.make("azure-devops"),
261
- name: "Azure DevOps",
262
- baseUrl: toBaseUrl(host),
263
- };
264
- }
265
-
266
- if (isBitbucketHost(hostname)) {
267
- return {
268
- kind: SourceControlProviderKind.make("bitbucket"),
269
- name: hostname === "bitbucket.org" ? "Bitbucket" : "Bitbucket Self-Hosted",
270
- baseUrl: toBaseUrl(host),
271
- };
272
- }
273
-
274
- return {
275
- kind: SourceControlProviderKind.make("unknown"),
276
- name: host,
277
- baseUrl: toBaseUrl(host),
278
- };
279
-}
280
-
281
-function decodeUrlPathSegment(segment: string): string {
282
- try {
283
- return decodeURIComponent(segment);
284
- } catch {
285
- return segment;
286
- }
287
-}
288
-
289
-/**
290
- * Azure DevOps is the exception: `az repos pr list --repository` takes a repository name, and
291
- * takes the organisation and project from the checkout it detects — so the recorded
292
- * `org/project/_git/repo` path is refused outright and the whole repository reads as
293
- * unavailable. Its name is the last segment, which is what this hands over. The segment comes
294
- * from the remote URL, where a name with a space reads `my%20repo`; `az` looks that up literally
295
- * and answers 404, so it goes out decoded.
296
- */
297
-export function sourceControlRepositorySelector(
298
- identity:
299
- | Pick<RepositoryIdentity, "provider" | "displayName" | "owner" | "name">
300
- | null
301
- | undefined,
302
-): string | null {
303
- if (!identity) return null;
304
- if (identity.provider === "azure-devops") {
305
- const segments = (identity.displayName ?? "").split("/").filter((part) => part !== "_git");
306
- const name = identity.name || segments.at(-1);
307
- return name ? decodeUrlPathSegment(name) : null;
308
- }
309
- if (identity.displayName) return identity.displayName;
310
- return identity.owner && identity.name ? `${identity.owner}/${identity.name}` : null;
311
-}
312
-
313
-export function canonicalRepositoryKey(key: string): string {
314
- return key
315
- .replace(
316
- /^(?:ssh\.dev\.azure\.com|vs-ssh\.visualstudio\.com)\/v3\/([^/]+)\/([^/]+)\/([^/]+)$/u,
317
- "dev.azure.com/$1/$2/_git/$3",
318
- )
319
- .replace(
320
- /^([^.]+)\.visualstudio\.com\/(?:defaultcollection\/)?([^/]+)\/_git\/([^/]+)$/u,
321
- "dev.azure.com/$1/$2/_git/$3",
322
- );
323
-}
packages/source-control-azure-devops/src/client/definition.test.ts
+91
@@ -1,4 +1,9 @@
1
+import { SourceControlProviderKind } from "@t3tools/contracts";
2
import type { ChangeRequestProjectIdentity } from "@t3tools/source-control-core/client/definition";
3
+import {
4
+ makeSourceControlClientRegistry,
5
+ recognizeRemoteWith,
6
+} from "@t3tools/source-control-core/client/definition";
7
import { describe, expect, it } from "vite-plus/test";
8
9
import { definition } from "./definition.ts";
@@ -102,3 +107,89 @@ describe("Azure DevOps change request URLs", () => {
107
}
108
});
109
});
110
+
111
+describe("Azure DevOps remotes", () => {
112
+ it("recognises the SSH clone hosts as well as the web ones", () => {
113
+ for (const remote of [
114
+ "git@ssh.dev.azure.com:v3/org/project/repo",
115
+ "ssh://git@ssh.dev.azure.com:22/v3/org/project/repo",
116
+ "git@vs-ssh.visualstudio.com:v3/org/project/repo",
117
+ "https://org@dev.azure.com/org/project/_git/repo",
118
+ ]) {
119
+ expect(recognizeRemoteWith(definition, remote)?.kind, remote).toBe("azure-devops");
120
+ }
121
+ expect(recognizeRemoteWith(definition, "https://azure.example/o/p/_git/r")).toBeNull();
122
+ });
123
+});
124
+
125
+describe("Azure DevOps repository keys", () => {
126
+ const registry = makeSourceControlClientRegistry([definition]);
127
+
128
+ it("gives a repository the same key over SSH as over HTTPS", () => {
129
+ for (const remote of [
130
+ "git@ssh.dev.azure.com:v3/T3Tools/Platform/T3Code",
131
+ "ssh://git@ssh.dev.azure.com:22/v3/T3Tools/Platform/T3Code",
132
+ "https://T3Tools@dev.azure.com/T3Tools/Platform/_git/T3Code",
133
+ ]) {
134
+ expect(registry.repositoryKeyFromRemote(remote), remote).toBe(
135
+ "dev.azure.com/t3tools/platform/_git/t3code",
136
+ );
137
+ }
138
+ });
139
+
140
+ it("keeps the organization in the host for the legacy visualstudio.com remotes", () => {
141
+ for (const remote of [
142
+ "T3Tools@vs-ssh.visualstudio.com:v3/T3Tools/Platform/T3Code",
143
+ "https://T3Tools.visualstudio.com/Platform/_git/T3Code",
144
+ ]) {
145
+ expect(registry.repositoryKeyFromRemote(remote), remote).toBe(
146
+ "t3tools.visualstudio.com/platform/_git/t3code",
147
+ );
148
+ }
149
+ });
150
+
151
+ it("compares every spelling on dev.azure.com", () => {
152
+ for (const key of [
153
+ "ssh.dev.azure.com/v3/org/project/repo",
154
+ "vs-ssh.visualstudio.com/v3/org/project/repo",
155
+ "org.visualstudio.com/project/_git/repo",
156
+ "org.visualstudio.com/defaultcollection/project/_git/repo",
157
+ "dev.azure.com/org/project/_git/repo",
158
+ ]) {
159
+ expect(registry.canonicalRepositoryKey(key), key).toBe("dev.azure.com/org/project/_git/repo");
160
+ expect(registry.findByRepositoryKey(key), key).toBe(definition);
161
+ }
162
+ expect(registry.canonicalRepositoryKey("tfs.example/c/p/_git/r")).toBe(
163
+ "tfs.example/c/p/_git/r",
164
+ );
165
+ expect(registry.findByRepositoryKey("tfs.example/c/p/_git/r")).toBeUndefined();
166
+ });
167
+});
168
+
169
+describe("Azure DevOps repository selector", () => {
170
+ const registry = makeSourceControlClientRegistry([definition]);
171
+
172
+ it("names a repository by its own name, not its project path", () => {
173
+ // `az repos pr list --repository` takes a name and detects the organisation and project from
174
+ // the checkout; the recorded `org/project/_git/repo` path is refused.
175
+ expect(
176
+ registry.repositorySelector({
177
+ provider: SourceControlProviderKind.make("azure-devops"),
178
+ displayName: "contoso/payments/_git/checkout",
179
+ owner: "contoso",
180
+ name: "checkout",
181
+ }),
182
+ ).toBe("checkout");
183
+ });
184
+
185
+ it("decodes a name the remote URL percent-encodes", () => {
186
+ expect(
187
+ registry.repositorySelector({
188
+ provider: SourceControlProviderKind.make("azure-devops"),
189
+ displayName: "contoso/payments%20(eu)/_git/checkout%20(eu)",
190
+ owner: "contoso",
191
+ name: "checkout%20(eu)",
192
+ }),
193
+ ).toBe("checkout (eu)");
194
+ });
195
+});
packages/source-control-azure-devops/src/client/definition.ts
+75
-9
@@ -1,5 +1,4 @@
1
import { SourceControlProviderKind } from "@t3tools/contracts";
2
-import { canonicalRepositoryKey } from "@t3tools/shared/sourceControl";
2
import {
3
changeRequestUrlBelow,
4
defineSourceControlClient,
@@ -14,6 +13,44 @@ const CHECKOUT_COMMAND = /^az\s+repos\s+pr\s+checkout\s+(.+)$/i;
13
const CHANGE_REQUEST_REFERENCE =
14
/^https:\/\/(?:dev\.azure\.com\/[^/\s]+\/[^/\s]+|[^/\s]+\.visualstudio\.com\/[^/\s]+)\/_git\/[^/\s]+\/pullrequest\/(\d+)(?:[/?#].*)?$/i;
15
16
+/**
17
+ * Azure alone addresses one repository under two names that share no part: `ssh.dev.azure.com` and
18
+ * `v3/{org}/{project}/{repo}` over SSH, against `dev.azure.com` and `{org}/{project}/_git/{repo}`
19
+ * everywhere a person sees it. A project cloned over SSH would otherwise be a different repository
20
+ * to every comparison made against a pull request URL, which arrives in the web spelling.
21
+ */
22
+function repositoryKeyFromRemote(key: string): string | null {
23
+ const match =
24
+ /^(ssh\.dev\.azure\.com|vs-ssh\.visualstudio\.com)\/v3\/([^/]+)\/([^/]+)\/([^/]+)$/u.exec(key);
25
+ if (match === null) return null;
26
+ const [, host, organization, project, repository] = match;
27
+ return host === "ssh.dev.azure.com"
28
+ ? `dev.azure.com/${organization}/${project}/_git/${repository}`
29
+ : `${organization}.visualstudio.com/${project}/_git/${repository}`;
30
+}
31
+
32
+/** Every spelling of an Azure DevOps Services repository, on `dev.azure.com`. */
33
+function canonicalRepositoryKey(key: string): string | null {
34
+ const canonical = key
35
+ .replace(
36
+ /^(?:ssh\.dev\.azure\.com|vs-ssh\.visualstudio\.com)\/v3\/([^/]+)\/([^/]+)\/([^/]+)$/u,
37
+ "dev.azure.com/$1/$2/_git/$3",
38
+ )
39
+ .replace(
40
+ /^([^.]+)\.visualstudio\.com\/(?:defaultcollection\/)?([^/]+)\/_git\/([^/]+)$/u,
41
+ "dev.azure.com/$1/$2/_git/$3",
42
+ );
43
+ return canonical.startsWith("dev.azure.com/") ? canonical : null;
44
+}
45
+
46
+function decodeUrlPathSegment(segment: string): string {
47
+ try {
48
+ return decodeURIComponent(segment);
49
+ } catch {
50
+ return segment;
51
+ }
52
+}
53
+
54
function checkoutCommandId(args: string): string | null {
55
const parts = args.trim().split(/\s+/).filter(Boolean);
56
for (const [index, part] of parts.entries()) {
@@ -23,8 +60,10 @@ function checkoutCommandId(args: string): string | null {
60
return parts.find((part) => !part.startsWith("-")) ?? null;
61
}
62
63
+const KIND = SourceControlProviderKind.make("azure-devops");
64
+
65
export const definition = defineSourceControlClient({
27
- kind: SourceControlProviderKind.make("azure-devops"),
66
+ kind: KIND,
67
label: "Azure DevOps",
68
pickerLabel: "Azure DevOps",
69
icon: "azure-devops",
@@ -39,9 +78,8 @@ export const definition = defineSourceControlClient({
78
defaultCloneTransport: "ssh",
79
changeRequestUrl: ({ host, repository, number, remoteUrl, webUrl }) => {
80
if (webUrl) return changeRequestUrlBelow(webUrl, `pullrequest/${number}`);
42
- const [canonicalHost = host, ...path] = canonicalRepositoryKey(
43
- `${host}/${repository}`.toLowerCase(),
44
- ).split("/");
81
+ const key = `${host}/${repository}`.toLowerCase();
82
+ const [canonicalHost = host, ...path] = (canonicalRepositoryKey(key) ?? key).split("/");
83
return `${remoteWebOrigin(canonicalHost, remoteUrl)}/${path.join("/")}/pullrequest/${number}`;
84
},
85
// Servers on different ports are different servers, so a port stays in the link.
@@ -69,9 +107,37 @@ export const definition = defineSourceControlClient({
107
},
108
isChangeRequestReference: (url) => CHANGE_REQUEST_REFERENCE.test(url),
109
checkoutChangeRequestHost: () => null,
72
- isChangeRequestInRepository: (identity, link) =>
73
- isChangeRequestAuthorityOfProject(identity, link) &&
74
- canonicalRepositoryKey(identity.canonicalKey.toLowerCase()) ===
75
- canonicalRepositoryKey(`${link.host}/${link.repository}`.toLowerCase()),
110
+ // `ssh.dev.azure.com` is the default SSH clone host (git@ssh.dev.azure.com:v3/org/project/repo),
111
+ // so any `*.dev.azure.com` subdomain is Azure. Legacy hosts stay under `.visualstudio.com`,
112
+ // including `vs-ssh.visualstudio.com`.
113
+ recognizeRemote: ({ host, hostname }) =>
114
+ hostname === "dev.azure.com" ||
115
+ hostname.endsWith(".dev.azure.com") ||
116
+ hostname.endsWith(".visualstudio.com")
117
+ ? { kind: KIND, name: "Azure DevOps", baseUrl: `https://${host}` }
118
+ : null,
119
+ /**
120
+ * `az repos pr list --repository` takes a repository name, and takes the organisation and
121
+ * project from the checkout it detects, so the recorded `org/project/_git/repo` path is refused
122
+ * outright and the whole repository reads as unavailable. The segment comes from the remote URL,
123
+ * where a name with a space reads `my%20repo`; `az` looks that up literally and answers 404, so
124
+ * it goes out decoded.
125
+ */
126
+ repositorySelector: (identity) => {
127
+ const segments = (identity.displayName ?? "").split("/").filter((part) => part !== "_git");
128
+ const name = identity.name || segments.at(-1);
129
+ return name ? decodeUrlPathSegment(name) : null;
130
+ },
131
+ repositoryKeyFromRemote,
132
+ canonicalRepositoryKey,
133
+ isChangeRequestInRepository: (identity, link) => {
134
+ if (!isChangeRequestAuthorityOfProject(identity, link)) return false;
135
+ const projectKey = identity.canonicalKey.toLowerCase();
136
+ const linkKey = `${link.host}/${link.repository}`.toLowerCase();
137
+ return (
138
+ (canonicalRepositoryKey(projectKey) ?? projectKey) ===
139
+ (canonicalRepositoryKey(linkKey) ?? linkKey)
140
+ );
141
+ },
142
canReadChangeRequestOnHost: () => false,
143
});
packages/source-control-bitbucket/src/client/definition.test.ts
+17
@@ -1,3 +1,4 @@
1
+import { recognizeRemoteWith } from "@t3tools/source-control-core/client/definition";
2
import { describe, expect, it } from "vite-plus/test";
3
4
import { definition } from "./definition.ts";
@@ -36,3 +37,19 @@ describe("Bitbucket change request URLs", () => {
37
).toBe("https://bitbucket.org/w/repo/pull-requests/5");
38
});
39
});
40
+
41
+describe("Bitbucket remotes", () => {
42
+ const recognize = (url: string) => recognizeRemoteWith(definition, url);
43
+
44
+ it("recognises bitbucket.org and hosts with a bitbucket label", () => {
45
+ expect(recognize("git@bitbucket.org:workspace/repo.git")).toEqual({
46
+ kind: "bitbucket",
47
+ name: "Bitbucket",
48
+ baseUrl: "https://bitbucket.org",
49
+ });
50
+ expect(recognize("https://bitbucket.example.com/workspace/repo.git")?.name).toBe(
51
+ "Bitbucket Self-Hosted",
52
+ );
53
+ expect(recognize("https://notbitbucket.example.com/workspace/repo.git")).toBeNull();
54
+ });
55
+});
packages/source-control-bitbucket/src/client/definition.ts
+11
-2
@@ -11,6 +11,7 @@ import {
11
isChangeRequestInProjectRepository,
12
isChangeRequestOnProjectHost,
13
parseChangeRequestPath,
14
+ projectChangeRequestHost,
15
} from "@t3tools/source-control-core/client/definition";
16
17
const safeShellArgument = /^[A-Za-z0-9._/@+=,-]+$/;
@@ -97,9 +98,17 @@ export const definition = defineSourceControlClient({
98
checkoutCommandArgument: () => null,
99
isChangeRequestReference: () => false,
100
checkoutChangeRequestHost: () => null,
101
+ recognizeRemote: ({ host, hostname }) =>
102
+ hostname === "bitbucket.org" || hostname.split(".").includes("bitbucket")
103
+ ? {
104
+ kind: KIND,
105
+ name: hostname === "bitbucket.org" ? "Bitbucket" : "Bitbucket Self-Hosted",
106
+ baseUrl: `https://${host}`,
107
+ }
108
+ : null,
109
isChangeRequestInRepository: (identity, link) =>
101
- isChangeRequestInProjectRepository(KIND, identity, link),
110
+ isChangeRequestInProjectRepository(projectChangeRequestHost(identity, KIND), identity, link),
111
canReadChangeRequestOnHost: (identity, link) =>
103
- isChangeRequestOnProjectHost(KIND, identity, link),
112
+ isChangeRequestOnProjectHost(projectChangeRequestHost(identity, KIND), identity, link),
113
settings,
114
});
packages/source-control-bitbucket/src/server/BitbucketApi.ts
+4
-5
@@ -17,10 +17,9 @@ import {
17
} from "@t3tools/contracts";
18
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
19
import { sanitizeBranchFragment } from "@t3tools/shared/git";
20
-import {
21
- detectSourceControlProviderFromRemoteUrl,
22
- isSshRemoteUrl,
23
-} from "@t3tools/shared/sourceControl";
20
+import { isSshRemoteUrl } from "@t3tools/shared/sourceControl";
21
+import { recognizeRemoteWith } from "@t3tools/source-control-core/client/definition";
22
+import { definition } from "../client/definition.ts";
23
24
import {
25
BitbucketPullRequestListSchema,
@@ -791,7 +790,7 @@ export const make = Effect.gen(function* () {
790
);
791
792
for (const remote of remotes.remotes) {
794
- if (detectSourceControlProviderFromRemoteUrl(remote.url)?.kind !== "bitbucket") continue;
793
+ if (recognizeRemoteWith(definition, remote.url) === null) continue;
794
const parsed = parseBitbucketRemoteUrl(remote.url);
795
if (parsed) return parsed;
796
}
packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts
+1
@@ -147,6 +147,7 @@ export const make = Effect.gen(function* () {
147
const provider: PullRequestProviderApi = {
148
kind: SourceControlProviderKind.make("bitbucket"),
149
capabilities: CAPABILITIES,
150
+ readsPublicHostWithoutCheckout: true,
151
152
getViewer: () => api.getViewer().pipe(Effect.mapError(fail("getViewer"))),
153
packages/source-control-core/src/client/definition.ts
+199
-16
@@ -1,14 +1,15 @@
1
import {
2
type PullRequestAction,
3
- pullRequestHostOf,
3
type PullRequestReviewVerdict,
4
type RepositoryIdentity,
5
SourceControlProviderKind,
6
+ type SourceControlProviderInfo,
7
} from "@t3tools/contracts";
8
+import { normalizeGitRemoteUrl, parseGitRemoteRepository } from "@t3tools/shared/git";
9
import * as Schema from "effect/Schema";
10
11
/**
11
- * The two strings are what `pullRequestHostOf` and the project's `repositoryIdentity` produce
12
+ * The two strings are what `changeRequestHost` and the project's `repositoryIdentity` produce
13
* from a git remote — lower case, no port, the full path below the host — because links are
14
* matched against those. `authority` keeps the port for hosts whose identity includes it.
15
*/
@@ -43,6 +44,29 @@ export type ChangeRequestProjectIdentity = Pick<
44
"canonicalKey" | "locator" | "webUrl" | "displayName" | "owner" | "name"
45
>;
46
47
+export type ChangeRequestHostIdentity =
48
+ | {
49
+ readonly canonicalKey?: string | undefined;
50
+ readonly locator?: { readonly remoteUrl: string } | undefined;
51
+ }
52
+ | null
53
+ | undefined;
54
+
55
+export type RepositorySelectorIdentity = Pick<
56
+ RepositoryIdentity,
57
+ "provider" | "displayName" | "owner" | "name"
58
+>;
59
+
60
+/** A git remote's host, as `recognizeRemote` reads it. */
61
+export interface GitRemoteHost {
62
+ /** Trimmed. */
63
+ readonly remoteUrl: string;
64
+ /** Lower case. Keeps the port of an HTTP remote, never an SSH one. */
65
+ readonly host: string;
66
+ /** `host` without its port. */
67
+ readonly hostname: string;
68
+}
69
+
70
export interface ChangeRequestCheckoutInput {
71
readonly number: number;
72
readonly headBranch: string;
@@ -91,6 +115,32 @@ export interface SourceControlClientDefinition {
115
link: ChangeRequestLink,
116
) => boolean;
117
readonly checkoutChangeRequestHost: (identity: ChangeRequestProjectIdentity) => string | null;
118
+ /** Null when this host does not claim the remote. Asked in the registry's recognition order. */
119
+ readonly recognizeRemote: (remote: GitRemoteHost) => SourceControlProviderInfo | null;
120
+ /** The host change requests in the project are listed and keyed under. */
121
+ readonly changeRequestHost?: (identity: ChangeRequestHostIdentity) => string;
122
+ /**
123
+ * What the host's tools take to select the project's repository. Absent means the repository
124
+ * path, `owner/name`.
125
+ */
126
+ readonly repositorySelector?: (identity: RepositorySelectorIdentity) => string | null;
127
+ /**
128
+ * For a host that spells one repository differently over SSH and on the web: the web spelling
129
+ * of the `host/path` key `normalizeGitRemoteUrl` made from a remote that names a host. Null when
130
+ * the key is not this host's. Persisted repository keys are built with it, so its output must
131
+ * not change.
132
+ */
133
+ readonly repositoryKeyFromRemote?: (key: string) => string | null;
134
+ /**
135
+ * For a host with more than one spelling of a repository key: the one every spelling compares
136
+ * equal under. Null when the key is not this host's.
137
+ */
138
+ readonly canonicalRepositoryKey?: (key: string) => string | null;
139
+ /**
140
+ * An SSH remote names the SSH server only, so the web host, and its port, come from resolving
141
+ * the provider rather than from the remote.
142
+ */
143
+ readonly sshRemoteHidesWebHost?: boolean;
144
readonly settings?: SourceControlHostSettingsSchema;
145
}
146
@@ -160,14 +210,23 @@ export function isChangeRequestAuthorityOfProject(
210
return true;
211
}
212
213
+/** The host of the project's repository key, or `kind` when the key has none. */
214
+export function projectChangeRequestHost<const Kind extends string | undefined>(
215
+ identity: ChangeRequestHostIdentity,
216
+ kind: Kind,
217
+): string | Kind {
218
+ const host = identity?.canonicalKey?.split("/")[0]?.trim();
219
+ return host === undefined || host.length === 0 ? kind : host.toLowerCase();
220
+}
221
+
222
+/** `projectHost` is the project's `changeRequestHost`. */
223
export function isChangeRequestOnProjectHost(
164
- kind: SourceControlProviderKind,
224
+ projectHost: string,
225
identity: ChangeRequestProjectIdentity,
226
link: ChangeRequestLink,
227
): boolean {
228
if (!isChangeRequestAuthorityOfProject(identity, link)) return false;
169
- const host = pullRequestHostOf(identity, kind);
170
- return host === link.host.toLowerCase() || host === link.authority;
229
+ return projectHost === link.host.toLowerCase() || projectHost === link.authority;
230
}
231
232
function projectRepositoryPath(identity: ChangeRequestProjectIdentity): string | null {
@@ -178,7 +237,7 @@ function projectRepositoryPath(identity: ChangeRequestProjectIdentity): string |
237
}
238
239
export function isChangeRequestInProjectRepository(
181
- kind: SourceControlProviderKind,
240
+ projectHost: string,
241
identity: ChangeRequestProjectIdentity,
242
link: ChangeRequestLink,
243
): boolean {
@@ -186,10 +245,64 @@ export function isChangeRequestInProjectRepository(
245
return (
246
repository !== null &&
247
repository.toLowerCase() === link.repository.toLowerCase() &&
189
- isChangeRequestOnProjectHost(kind, identity, link)
248
+ isChangeRequestOnProjectHost(projectHost, identity, link)
249
);
250
}
251
252
+const SCP_REMOTE = /^[a-zA-Z0-9._-]+@([^:/]+):/;
253
+
254
+/** Null when the remote names no host, such as a local path. */
255
+export function parseGitRemoteHost(remoteUrl: string): GitRemoteHost | null {
256
+ const trimmed = remoteUrl.trim();
257
+ if (trimmed.length === 0) return null;
258
+ let host: string;
259
+ const scpHost = SCP_REMOTE.exec(trimmed)?.[1];
260
+ if (scpHost) {
261
+ host = scpHost.toLowerCase();
262
+ } else {
263
+ try {
264
+ const url = new URL(trimmed);
265
+ host = (url.protocol === "ssh:" ? url.hostname : url.host).toLowerCase();
266
+ } catch {
267
+ return null;
268
+ }
269
+ }
270
+ if (host.length === 0) return null;
271
+ let hostname: string;
272
+ try {
273
+ hostname = new URL(`https://${host}`).hostname.toLowerCase();
274
+ } catch {
275
+ hostname = host.replace(/:\d+$/u, "").toLowerCase();
276
+ }
277
+ return { remoteUrl: trimmed, host, hostname };
278
+}
279
+
280
+/** What a remote on a host no definition claims reads as. */
281
+export function unknownRemoteProvider(remote: GitRemoteHost): SourceControlProviderInfo {
282
+ return {
283
+ kind: SourceControlProviderKind.make("unknown"),
284
+ name: remote.host,
285
+ baseUrl: `https://${remote.host}`,
286
+ };
287
+}
288
+
289
+/** What `definition` alone makes of a remote, for a host's own code that asks only about itself. */
290
+export function recognizeRemoteWith(
291
+ definition: Pick<SourceControlClientDefinition, "recognizeRemote">,
292
+ remoteUrl: string,
293
+): SourceControlProviderInfo | null {
294
+ const remote = parseGitRemoteHost(remoteUrl);
295
+ return remote === null ? null : definition.recognizeRemote(remote);
296
+}
297
+
298
+function defaultRepositorySelector(
299
+ identity: RepositorySelectorIdentity | null | undefined,
300
+): string | null {
301
+ if (!identity) return null;
302
+ if (identity.displayName) return identity.displayName;
303
+ return identity.owner && identity.name ? `${identity.owner}/${identity.name}` : null;
304
+}
305
+
306
export const UNKNOWN_SOURCE_CONTROL_CLIENT: SourceControlClientDefinition = {
307
kind: SourceControlProviderKind.make("unknown"),
308
label: "source control",
@@ -213,10 +326,15 @@ export const UNKNOWN_SOURCE_CONTROL_CLIENT: SourceControlClientDefinition = {
326
checkoutCommandArgument: () => null,
327
isChangeRequestReference: () => false,
328
checkoutChangeRequestHost: () => null,
329
+ recognizeRemote: () => null,
330
isChangeRequestInRepository: (identity, link) =>
217
- isChangeRequestInProjectRepository(SourceControlProviderKind.make("unknown"), identity, link),
331
+ isChangeRequestInProjectRepository(
332
+ projectChangeRequestHost(identity, "unknown"),
333
+ identity,
334
+ link,
335
+ ),
336
canReadChangeRequestOnHost: (identity, link) =>
219
- isChangeRequestOnProjectHost(SourceControlProviderKind.make("unknown"), identity, link),
337
+ isChangeRequestOnProjectHost(projectChangeRequestHost(identity, "unknown"), identity, link),
338
};
339
340
export interface ParsedChangeRequest {
@@ -235,6 +353,23 @@ export interface SourceControlClientRegistry {
353
readonly hostLabelForChangeRequestUrl: (url: string) => string;
354
readonly isSameChangeRequest: (left: string, right: string) => boolean;
355
readonly changeRequestUrlFromReferenceAutolink: (url: string) => string | null;
356
+ /**
357
+ * The host a remote is on, from the first definition in recognition order that claims it, or an
358
+ * unknown host. Null when the remote names no host.
359
+ */
360
+ readonly recognizeRemote: (remoteUrl: string) => SourceControlProviderInfo | null;
361
+ /** `normalizeGitRemoteUrl`, in the spelling the remote's host uses on the web. */
362
+ readonly repositoryKeyFromRemote: (remoteUrl: string) => string;
363
+ readonly canonicalRepositoryKey: (key: string) => string;
364
+ /** The host that has more than one spelling of `key`, if any does. */
365
+ readonly findByRepositoryKey: (key: string) => SourceControlClientDefinition | undefined;
366
+ readonly repositorySelector: (
367
+ identity: RepositorySelectorIdentity | null | undefined,
368
+ ) => string | null;
369
+ readonly changeRequestHost: <const Kind extends string | undefined>(
370
+ identity: ChangeRequestHostIdentity,
371
+ kind: Kind,
372
+ ) => string | Kind;
373
}
374
375
function httpUrl(value: string): URL | null {
@@ -246,15 +381,30 @@ function httpUrl(value: string): URL | null {
381
}
382
}
383
384
+function inOrder(
385
+ definitions: ReadonlyArray<SourceControlClientDefinition>,
386
+ firstKinds: ReadonlyArray<SourceControlProviderKind> | undefined,
387
+): ReadonlyArray<SourceControlClientDefinition> {
388
+ const first = (firstKinds ?? []).flatMap(
389
+ (kind) => definitions.find((definition) => definition.kind === kind) ?? [],
390
+ );
391
+ return [...first, ...definitions.filter((definition) => !first.includes(definition))];
392
+}
393
+
394
/**
395
* `definitions` is display order, and its first entry is what `get` returns for a repository
396
* that has not reported its host yet. A change request URL goes to the first definition that
397
* reads it, trying `claimChangeRequestUrlsFirst` before the rest, so a host that claims a route
253
- * only on its own hostnames can precede one that claims the route everywhere.
398
+ * only on its own hostnames can precede one that claims the route everywhere. A remote likewise
399
+ * goes to the first that recognises it, in `recognizeRemotesIn` order and then the rest, because
400
+ * one hostname can carry several hosts' labels.
401
*/
402
export function makeSourceControlClientRegistry(
403
definitions: ReadonlyArray<SourceControlClientDefinition>,
257
- options?: { readonly claimChangeRequestUrlsFirst?: ReadonlyArray<SourceControlProviderKind> },
404
+ options?: {
405
+ readonly claimChangeRequestUrlsFirst?: ReadonlyArray<SourceControlProviderKind>;
406
+ readonly recognizeRemotesIn?: ReadonlyArray<SourceControlProviderKind>;
407
+ },
408
): SourceControlClientRegistry {
409
const byKind = new Map<string, SourceControlClientDefinition>();
410
for (const definition of definitions) {
@@ -263,11 +413,15 @@ export function makeSourceControlClientRegistry(
413
}
414
byKind.set(definition.kind, definition);
415
}
266
- const first = new Set(options?.claimChangeRequestUrlsFirst);
267
- const claimOrder = [
268
- ...definitions.filter((definition) => first.has(definition.kind)),
269
- ...definitions.filter((definition) => !first.has(definition.kind)),
270
- ];
416
+ const claimOrder = inOrder(definitions, options?.claimChangeRequestUrlsFirst);
417
+ const recognitionOrder = inOrder(definitions, options?.recognizeRemotesIn);
418
+ const repositoryKeyOwner = (key: string) => {
419
+ for (const definition of definitions) {
420
+ const canonical = definition.canonicalRepositoryKey?.(key);
421
+ if (canonical != null) return { definition, canonical };
422
+ }
423
+ return undefined;
424
+ };
425
const parseChangeRequestUrl = (value: string): ParsedChangeRequest | null => {
426
const url = httpUrl(value);
427
if (url === null) return null;
@@ -311,6 +465,35 @@ export function makeSourceControlClientRegistry(
465
}
466
return null;
467
},
468
+ recognizeRemote: (remoteUrl) => {
469
+ const remote = parseGitRemoteHost(remoteUrl);
470
+ if (remote === null) return null;
471
+ for (const definition of recognitionOrder) {
472
+ const provider = definition.recognizeRemote(remote);
473
+ if (provider !== null) return provider;
474
+ }
475
+ return unknownRemoteProvider(remote);
476
+ },
477
+ repositoryKeyFromRemote: (remoteUrl) => {
478
+ const key = normalizeGitRemoteUrl(remoteUrl);
479
+ if (parseGitRemoteRepository(remoteUrl) === null) return key;
480
+ for (const definition of definitions) {
481
+ const spelled = definition.repositoryKeyFromRemote?.(key);
482
+ if (spelled != null) return spelled;
483
+ }
484
+ return key;
485
+ },
486
+ canonicalRepositoryKey: (key) => repositoryKeyOwner(key)?.canonical ?? key,
487
+ findByRepositoryKey: (key) => repositoryKeyOwner(key)?.definition,
488
+ repositorySelector: (identity) =>
489
+ identity?.provider === undefined
490
+ ? defaultRepositorySelector(identity)
491
+ : (byKind.get(identity.provider)?.repositorySelector ?? defaultRepositorySelector)(
492
+ identity,
493
+ ),
494
+ changeRequestHost: (identity, kind) =>
495
+ (kind === undefined ? undefined : byKind.get(kind)?.changeRequestHost?.(identity)) ??
496
+ projectChangeRequestHost(identity, kind),
497
};
498
}
499
packages/source-control-core/src/client/threadPullRequests.ts
+9
-5
@@ -4,7 +4,6 @@ import type {
4
ThreadPullRequestKey,
5
ThreadPullRequestLink,
6
} from "@t3tools/contracts";
7
-import { canonicalRepositoryKey } from "@t3tools/shared/sourceControl";
7
import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests";
8
9
import type { SourceControlClientRegistry } from "./definition.ts";
@@ -63,7 +62,10 @@ export type ThreadPullRequestBadge = {
62
* binds these once to its own registry.
63
*/
64
export function makeThreadPullRequests(
66
- registry: Pick<SourceControlClientRegistry, "parseChangeRequestUrl">,
65
+ registry: Pick<
66
+ SourceControlClientRegistry,
67
+ "parseChangeRequestUrl" | "canonicalRepositoryKey" | "findByRepositoryKey"
68
+ >,
69
) {
70
const parse = (url: string) => registry.parseChangeRequestUrl(url)?.link ?? null;
71
@@ -74,7 +76,7 @@ export function makeThreadPullRequests(
76
(parsed?.repository === key.repository.trim().toLowerCase() && parsed.number === key.number
77
? parsed.authority
78
: undefined);
77
- const canonical = canonicalRepositoryKey(
79
+ const canonical = registry.canonicalRepositoryKey(
80
`${(authority ?? key.host).trim().toLowerCase()}/${key.repository.trim().toLowerCase()}`,
81
);
82
const separator = canonical.indexOf("/");
@@ -91,8 +93,10 @@ export function makeThreadPullRequests(
93
): ThreadPullRequestKey {
94
const parsed = parse(linked.url);
95
if (parsed !== null && parsed.number === linked.number) {
94
- const canonical = canonicalRepositoryKey(`${parsed.host}/${parsed.repository}`);
95
- if (parsed.authority !== undefined || canonical.startsWith("dev.azure.com/")) {
96
+ if (
97
+ parsed.authority !== undefined ||
98
+ registry.findByRepositoryKey(`${parsed.host}/${parsed.repository}`) !== undefined
99
+ ) {
100
return normalizeThreadPullRequestKey(parsed);
101
}
102
}
packages/source-control-core/src/server/PullRequestProvider.ts
+5
@@ -296,6 +296,11 @@ export interface PullRequestProviderApi {
296
* organization from the checkout, so only a checkout whose key matches the reference serves it.
297
*/
298
readonly repositoryKey?: (input: { readonly canonicalKey: string }) => string;
299
+ /**
300
+ * Names the repository in every request and authenticates by host, so a change request on the
301
+ * definition's `publicHost` can be read from a project with no checkout of its repository.
302
+ */
303
+ readonly readsPublicHostWithoutCheckout?: boolean;
304
305
readonly getViewer: (input: {
306
readonly cwd: string;
packages/source-control-forgejo/src/client/definition.test.ts
+27
@@ -1,4 +1,5 @@
1
import type { ChangeRequestProjectIdentity } from "@t3tools/source-control-core/client/definition";
2
+import { recognizeRemoteWith } from "@t3tools/source-control-core/client/definition";
3
import { describe, expect, it } from "vite-plus/test";
4
5
import { definition } from "./definition.ts";
@@ -102,3 +103,29 @@ describe("Forgejo change request URLs", () => {
103
}
104
});
105
});
106
+
107
+describe("Forgejo remotes", () => {
108
+ it("recognises Codeberg and Forgejo or Gitea hosts, keeping an HTTP remote's origin", () => {
109
+ for (const host of ["codeberg.org", "forgejo.example.test", "gitea.example.test"]) {
110
+ expect(recognizeRemoteWith(definition, `http://${host}:3000/team/repo.git`)).toEqual({
111
+ kind: "forgejo",
112
+ name: "Forgejo",
113
+ baseUrl: `http://${host}:3000`,
114
+ });
115
+ }
116
+ expect(
117
+ recognizeRemoteWith(definition, "ssh://git@forgejo.example.test:2222/team/repo.git")?.baseUrl,
118
+ ).toBe("https://forgejo.example.test");
119
+ expect(recognizeRemoteWith(definition, "https://git.example.test/team/repo")).toBeNull();
120
+ });
121
+});
122
+
123
+describe("Forgejo change request host", () => {
124
+ it("keeps an HTTP remote's port, because a server's identity includes it", () => {
125
+ const project = identity("http://forge.example:3000/git/team/repo.git");
126
+ expect(definition.changeRequestHost?.(project)).toBe("forge.example:3000");
127
+ expect(
128
+ definition.changeRequestHost?.(identity("ssh://git@forge.example:2222/git/team/repo.git")),
129
+ ).toBe("forge.example");
130
+ });
131
+});
packages/source-control-forgejo/src/client/definition.ts
+32
-4
@@ -1,12 +1,14 @@
1
import { SourceControlProviderKind } from "@t3tools/contracts";
2
import {
3
changeRequestUrlBelow,
4
+ type ChangeRequestHostIdentity,
5
type ChangeRequestProjectIdentity,
6
defineSourceControlClient,
7
isChangeRequestAuthorityOfProject,
8
isChangeRequestInProjectRepository,
9
isChangeRequestOnProjectHost,
10
parseChangeRequestPath,
11
+ projectChangeRequestHost,
12
remoteWebOrigin,
13
} from "@t3tools/source-control-core/client/definition";
14
@@ -33,6 +35,19 @@ function resolvedWebUrl(identity: ChangeRequestProjectIdentity): URL | null {
35
}
36
}
37
38
+/** A server's identity includes its port, which only an HTTP remote names. */
39
+function changeRequestHost(identity: ChangeRequestHostIdentity): string {
40
+ try {
41
+ const remote = new URL(identity?.locator?.remoteUrl ?? "");
42
+ if (remote.protocol === "http:" || remote.protocol === "https:") {
43
+ return remote.host.toLowerCase();
44
+ }
45
+ } catch {
46
+ // SSH remotes do not name the web server.
47
+ }
48
+ return projectChangeRequestHost(identity, KIND);
49
+}
50
+
51
export const definition = defineSourceControlClient({
52
kind: KIND,
53
label: "Forgejo",
@@ -40,8 +55,8 @@ export const definition = defineSourceControlClient({
55
icon: "forgejo",
56
changeRequest: { shortLabel: "PR", singular: "pull request" },
57
repositoryPathHint: "owner/repo",
43
- // Forgejo and Gitea are self-hosted, so no hostname names them.
44
- publicHost: null,
58
+ // Codeberg is the public Forgejo; any other server is self-hosted.
59
+ publicHost: "codeberg.org",
60
publishDescription: "Your signed-in server",
61
publishHost: (signedInHost) => signedInHost ?? "your server",
62
newRepositoryOwner: (account) => (account ? { owner: account } : null),
@@ -71,10 +86,23 @@ export const definition = defineSourceControlClient({
86
checkoutCommandArgument: (input) => CHECKOUT_COMMAND.exec(input)?.[1]?.trim() ?? null,
87
isChangeRequestReference: (url) => CHANGE_REQUEST_REFERENCE.test(url),
88
checkoutChangeRequestHost: () => null,
89
+ recognizeRemote: ({ remoteUrl, host, hostname }) =>
90
+ hostname === "codeberg.org" ||
91
+ hostname.split(".").includes("forgejo") ||
92
+ hostname.split(".").includes("gitea")
93
+ ? {
94
+ kind: KIND,
95
+ name: "Forgejo",
96
+ baseUrl: /^https?:/iu.test(remoteUrl) ? new URL(remoteUrl).origin : `https://${host}`,
97
+ }
98
+ : null,
99
+ changeRequestHost,
100
+ sshRemoteHidesWebHost: true,
101
isChangeRequestInRepository: (identity, link) => {
102
if (!isChangeRequestAuthorityOfProject(identity, link)) return false;
103
const web = resolvedWebUrl(identity);
77
- if (!web) return isChangeRequestInProjectRepository(KIND, identity, link);
104
+ if (!web)
105
+ return isChangeRequestInProjectRepository(changeRequestHost(identity), identity, link);
106
return (
107
web.host.toLowerCase() === (link.authority ?? link.host).toLowerCase() &&
108
web.pathname.replace(/^\/+|\/+$/g, "").toLowerCase() === link.repository.toLowerCase()
@@ -83,7 +111,7 @@ export const definition = defineSourceControlClient({
111
// A server mounted below a path serves only repositories under that mount.
112
canReadChangeRequestOnHost: (identity, link) => {
113
const web = resolvedWebUrl(identity);
86
- if (!web) return isChangeRequestOnProjectHost(KIND, identity, link);
114
+ if (!web) return isChangeRequestOnProjectHost(changeRequestHost(identity), identity, link);
115
const mount = web.pathname
116
.replace(/^\/+|\/+$/g, "")
117
.split("/")
packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts
+1
@@ -259,6 +259,7 @@ export const make = Effect.gen(function* () {
259
const provider: PullRequestProviderApi = {
260
kind: SourceControlProviderKind.make("forgejo"),
261
capabilities: CAPABILITIES,
262
+ readsPublicHostWithoutCheckout: true,
263
getViewer,
264
listChangeRequests: Effect.fn("ForgejoPullRequestProvider.listChangeRequests")(
265
function* (input) {
packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.ts
+1
-1
@@ -597,7 +597,7 @@ it.effect("gives Forgejo identities the browser URL of the login that serves the
597
canonicalKey: "forge.test/team/repo",
598
locator: { source: "git-remote" as const, remoteName: "origin", remoteUrl },
599
rootPath: "/repo",
600
- ...(provider === undefined ? {} : { provider }),
600
+ ...(provider === undefined ? {} : { provider: SourceControlProviderKind.make(provider) }),
601
});
602
const served = (baseUrl: string) => () =>
603
Effect.succeed({
packages/source-control-gitcafe/src/client/definition.test.ts
+15
@@ -1,3 +1,4 @@
1
+import { recognizeRemoteWith } from "@t3tools/source-control-core/client/definition";
2
import { describe, expect, it } from "vite-plus/test";
3
4
import { definition } from "./definition.ts";
@@ -47,3 +48,17 @@ describe("GitCafe change request URLs", () => {
48
).toBe("https://git.cafe/Team/Repo/pulls/8");
49
});
50
});
51
+
52
+describe("GitCafe remotes", () => {
53
+ it("recognises its own hosts only, without a port", () => {
54
+ expect(recognizeRemoteWith(definition, "https://git.cafe:8443/a/b")).toEqual({
55
+ kind: "gitcafe",
56
+ name: "GitCafe",
57
+ baseUrl: "https://git.cafe",
58
+ });
59
+ expect(recognizeRemoteWith(definition, "git@staging.git.cafe:team/repo.git")?.kind).toBe(
60
+ "gitcafe",
61
+ );
62
+ expect(recognizeRemoteWith(definition, "https://cafe.example/a/b")).toBeNull();
63
+ });
64
+});
packages/source-control-gitcafe/src/client/definition.ts
+7
-2
@@ -12,6 +12,7 @@ import {
12
isChangeRequestInProjectRepository,
13
isChangeRequestOnProjectHost,
14
parseChangeRequestPath,
15
+ projectChangeRequestHost,
16
} from "@t3tools/source-control-core/client/definition";
17
18
/** GitCafe has no self-hosted installs: production and staging are its only hosts. */
@@ -74,9 +75,13 @@ export const definition = defineSourceControlClient({
75
checkoutCommandArgument: () => null,
76
isChangeRequestReference: () => false,
77
checkoutChangeRequestHost: () => null,
78
+ recognizeRemote: ({ hostname }) =>
79
+ GITCAFE_HOSTS.has(hostname)
80
+ ? { kind: KIND, name: "GitCafe", baseUrl: `https://${hostname}` }
81
+ : null,
82
isChangeRequestInRepository: (identity, link) =>
78
- isChangeRequestInProjectRepository(KIND, identity, link),
83
+ isChangeRequestInProjectRepository(projectChangeRequestHost(identity, KIND), identity, link),
84
canReadChangeRequestOnHost: (identity, link) =>
80
- isChangeRequestOnProjectHost(KIND, identity, link),
85
+ isChangeRequestOnProjectHost(projectChangeRequestHost(identity, KIND), identity, link),
86
settings,
87
});
packages/source-control-github/src/client/definition.test.ts
+27
@@ -1,3 +1,4 @@
1
+import { recognizeRemoteWith } from "@t3tools/source-control-core/client/definition";
2
import { describe, expect, it } from "vite-plus/test";
3
4
import { definition } from "./definition.ts";
@@ -94,3 +95,29 @@ describe("GitHub change request URLs", () => {
95
expect(candidate("https://code.example.test/acme/web/issues/42")).toBeNull();
96
});
97
});
98
+
99
+describe("GitHub remotes", () => {
100
+ const recognize = (url: string) => recognizeRemoteWith(definition, url);
101
+
102
+ it("recognises github.com, ghe.com subdomains and hosts with a github label", () => {
103
+ expect(recognize("deploy@github.com:owner/repo.git")).toEqual({
104
+ kind: "github",
105
+ name: "GitHub",
106
+ baseUrl: "https://github.com",
107
+ });
108
+ expect(recognize("https://acme.ghe.com/owner/repo.git")).toEqual({
109
+ kind: "github",
110
+ name: "GitHub Self-Hosted",
111
+ baseUrl: "https://acme.ghe.com",
112
+ });
113
+ expect(recognize("git@acme.ghe.com:owner/repo.git")?.kind).toBe("github");
114
+ expect(recognize("https://github.example.com:8443/owner/repo.git")?.baseUrl).toBe(
115
+ "https://github.example.com:8443",
116
+ );
117
+ });
118
+
119
+ it("does not claim ghe.com itself or a label that only contains github", () => {
120
+ expect(recognize("https://ghe.com/owner/repo.git")).toBeNull();
121
+ expect(recognize("https://notgithub.example.com/owner/repo.git")).toBeNull();
122
+ });
123
+});
packages/source-control-github/src/client/definition.ts
+15
-4
@@ -2,7 +2,6 @@ import {
2
GitHubHost,
3
makeProviderSettingsSchema,
4
secretSetting,
5
- pullRequestHostOf,
5
SourceControlProviderKind,
6
TrimmedNonEmptyString,
7
TrimmedString,
@@ -15,6 +14,7 @@ import {
14
isChangeRequestInProjectRepository,
15
isChangeRequestOnProjectHost,
16
parseChangeRequestPath,
17
+ projectChangeRequestHost,
18
remoteWebOrigin,
19
} from "@t3tools/source-control-core/client/definition";
20
@@ -118,10 +118,21 @@ export const definition = defineSourceControlClient({
118
reviewSummaryRequired: () => false,
119
checkoutCommandArgument: (input) => CHECKOUT_COMMAND.exec(input)?.[1]?.trim() ?? null,
120
isChangeRequestReference: (url) => CHANGE_REQUEST_REFERENCE.test(url),
121
- checkoutChangeRequestHost: (identity) => pullRequestHostOf(identity, KIND),
121
+ checkoutChangeRequestHost: (identity) => projectChangeRequestHost(identity, KIND),
122
+ // `*.ghe.com` is GitHub Enterprise Cloud with data residency, one subdomain per enterprise.
123
+ recognizeRemote: ({ host, hostname }) =>
124
+ hostname === "github.com" ||
125
+ hostname.endsWith(".ghe.com") ||
126
+ hostname.split(".").includes("github")
127
+ ? {
128
+ kind: KIND,
129
+ name: hostname === "github.com" ? "GitHub" : "GitHub Self-Hosted",
130
+ baseUrl: `https://${host}`,
131
+ }
132
+ : null,
133
isChangeRequestInRepository: (identity, link) =>
123
- isChangeRequestInProjectRepository(KIND, identity, link),
134
+ isChangeRequestInProjectRepository(projectChangeRequestHost(identity, KIND), identity, link),
135
canReadChangeRequestOnHost: (identity, link) =>
125
- isChangeRequestOnProjectHost(KIND, identity, link),
136
+ isChangeRequestOnProjectHost(projectChangeRequestHost(identity, KIND), identity, link),
137
settings,
138
});
packages/source-control-github/src/server/GitHubPullRequestProvider.ts
+1
@@ -243,6 +243,7 @@ export const make = Effect.gen(function* () {
243
const provider: PullRequestProviderApi = {
244
kind: SourceControlProviderKind.make("github"),
245
capabilities: CAPABILITIES,
246
+ readsPublicHostWithoutCheckout: true,
247
mergeMessageRewrite: removeAgentCredits,
248
getRoutingIdentity: (input) =>
249
cli.getRoutingIdentity(input).pipe(Effect.mapError(fail("routeIdentity"))),
packages/source-control-github/src/server/gitHubRepositoryResolution.ts
+7
-8
@@ -1,8 +1,7 @@
1
import { normalizeGitRemoteUrl } from "@t3tools/shared/git";
2
-import {
3
- detectSourceControlProviderFromRemoteUrl,
4
- isSshRemoteUrl,
5
-} from "@t3tools/shared/sourceControl";
2
+import { isSshRemoteUrl } from "@t3tools/shared/sourceControl";
3
+import { parseGitRemoteHost } from "@t3tools/source-control-core/client/definition";
4
+import { definition } from "../client/definition.ts";
5
6
export interface GitHubRepositoryLocator {
7
readonly host: string;
@@ -163,13 +162,13 @@ export function parsePullRequestReference(
162
* #6198).
163
*/
164
export function gitHubApiHostForRemote(remoteUrl: string): string | null {
166
- const provider = detectSourceControlProviderFromRemoteUrl(remoteUrl);
167
- if (provider === null) return null;
168
- const host = new URL(provider.baseUrl).host.toLowerCase();
165
+ const remote = parseGitRemoteHost(remoteUrl);
166
+ if (remote === null) return null;
167
+ const host = new URL(`https://${remote.host}`).host.toLowerCase();
168
if (isSshRemoteUrl(remoteUrl) && !host.includes(".")) {
169
return host.includes("github") ? "github.com" : null;
170
}
172
- return provider.kind === "github" ? host : null;
171
+ return definition.recognizeRemote(remote) === null ? null : host;
172
}
173
174
function apiHostForHint(host: string): string {
packages/source-control-gitlab/src/client/definition.test.ts
+25
@@ -1,3 +1,4 @@
1
+import { recognizeRemoteWith } from "@t3tools/source-control-core/client/definition";
2
import { describe, expect, it } from "vite-plus/test";
3
4
import { definition } from "./definition.ts";
@@ -48,3 +49,27 @@ describe("GitLab change request URLs", () => {
49
).toBe("https://gitlab.com/group/sub/project/-/merge_requests/4");
50
});
51
});
52
+
53
+describe("GitLab remotes", () => {
54
+ const recognize = (url: string) => recognizeRemoteWith(definition, url);
55
+
56
+ it("keeps an HTTP port in the base URL and drops an SSH one", () => {
57
+ expect(recognize("https://gitlab.com:8443/group/repo.git")).toEqual({
58
+ kind: "gitlab",
59
+ name: "GitLab",
60
+ baseUrl: "https://gitlab.com:8443",
61
+ });
62
+ expect(recognize("ssh://git@gitlab.example.test:24/group/repo.git")).toEqual({
63
+ kind: "gitlab",
64
+ name: "GitLab Self-Hosted",
65
+ baseUrl: "https://gitlab.example.test",
66
+ });
67
+ expect(recognize("gitlab@gitlab.example.com:group/project.git")?.baseUrl).toBe(
68
+ "https://gitlab.example.com",
69
+ );
70
+ });
71
+
72
+ it("matches complete DNS labels only", () => {
73
+ expect(recognize("https://notgitlab.example.com/group/repo.git")).toBeNull();
74
+ });
75
+});
packages/source-control-gitlab/src/client/definition.ts
+11
-2
@@ -5,6 +5,7 @@ import {
5
isChangeRequestInProjectRepository,
6
isChangeRequestOnProjectHost,
7
parseChangeRequestPath,
8
+ projectChangeRequestHost,
9
} from "@t3tools/source-control-core/client/definition";
10
11
const CHECKOUT_COMMAND = /^glab\s+mr\s+checkout\s+(.+)$/i;
@@ -51,8 +52,16 @@ export const definition = defineSourceControlClient({
52
checkoutCommandArgument: (input) => CHECKOUT_COMMAND.exec(input)?.[1]?.trim() ?? null,
53
isChangeRequestReference: (url) => CHANGE_REQUEST_REFERENCE.test(url),
54
checkoutChangeRequestHost: () => null,
55
+ recognizeRemote: ({ host, hostname }) =>
56
+ hostname === "gitlab.com" || hostname.split(".").includes("gitlab")
57
+ ? {
58
+ kind: KIND,
59
+ name: hostname === "gitlab.com" ? "GitLab" : "GitLab Self-Hosted",
60
+ baseUrl: `https://${host}`,
61
+ }
62
+ : null,
63
isChangeRequestInRepository: (identity, link) =>
55
- isChangeRequestInProjectRepository(KIND, identity, link),
64
+ isChangeRequestInProjectRepository(projectChangeRequestHost(identity, KIND), identity, link),
65
canReadChangeRequestOnHost: (identity, link) =>
57
- isChangeRequestOnProjectHost(KIND, identity, link),
66
+ isChangeRequestOnProjectHost(projectChangeRequestHost(identity, KIND), identity, link),
67
});
packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts
+9
-6
@@ -1,8 +1,5 @@
1
import { SourceControlProviderKind } from "@t3tools/contracts";
2
-import {
3
- detectSourceControlProviderFromGitRemoteUrl,
4
- normalizeGitRemoteUrl,
5
-} from "@t3tools/shared/git";
2
+import { normalizeGitRemoteUrl } from "@t3tools/shared/git";
3
import { refineUnknownRemoteProvider } from "@t3tools/source-control-core/server/discovery";
4
import { processOutput } from "@t3tools/source-control-testing/TestSourceControlHost";
5
import { assert, it } from "@effect/vitest";
@@ -128,7 +125,10 @@ it.effect.each([
125
canonicalKey: normalizeGitRemoteUrl(remoteUrl),
126
locator: { source: "git-remote" as const, remoteName: "upstream", remoteUrl },
127
rootPath: "/repo",
131
- provider: detectSourceControlProviderFromGitRemoteUrl(remoteUrl)?.kind ?? "unknown",
128
+ // Only a remote no host recognised is left for glab to refine.
129
+ provider: SourceControlProviderKind.make(
130
+ expectedProvider === "github" ? "github" : "unknown",
131
+ ),
132
};
133
let authCalls = 0;
134
const refined = yield* (
@@ -177,7 +177,10 @@ it.effect.each([
177
"https://code.example.test/team/repo/-/merge_requests/42",
178
);
179
}
180
- assert.deepStrictEqual(refined, { ...identity, provider: expectedProvider });
180
+ assert.deepStrictEqual(refined, {
181
+ ...identity,
182
+ provider: SourceControlProviderKind.make(expectedProvider),
183
+ });
184
if (expectedProvider === "github") assert.strictEqual(authCalls, 0);
185
}),
186
);
packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts
+8
-6
@@ -3,7 +3,10 @@ import * as Schema from "effect/Schema";
3
import * as Effect from "effect/Effect";
4
import * as Option from "effect/Option";
5
import { SourceControlProviderError, type ChangeRequest } from "@t3tools/contracts";
6
-import { detectSourceControlProviderFromRemoteUrl } from "@t3tools/shared/sourceControl";
6
+import {
7
+ parseGitRemoteHost,
8
+ unknownRemoteProvider as unknownHostProvider,
9
+} from "@t3tools/source-control-core/client/definition";
10
11
import * as GitLabCli from "./GitLabCli.ts";
12
import * as GitLabChangeRequestTemplate from "./gitLabChangeRequestTemplate.ts";
@@ -105,13 +108,12 @@ function refineUnknownGitLabRemote(input: SourceControlUnknownRemoteRefinementIn
108
} as const;
109
}
110
111
+/** The caller refines only an identity no host recognised, so its remote is on an unknown host. */
112
function unknownRemoteProvider(remoteUrl: string) {
109
- // The shared detector does not recognize userless SCP remotes.
113
+ // Remote host parsing does not recognize userless SCP remotes.
114
const scpHost = /^([^@:/\\\s]{2,}):\/?[^/\s]+(?:\/[^/\s]+)+$/u.exec(remoteUrl.trim())?.[1];
111
- const provider = detectSourceControlProviderFromRemoteUrl(
112
- scpHost ? `ssh://${scpHost}` : remoteUrl,
113
- );
114
- return provider?.kind === "unknown" ? provider : null;
115
+ const remote = parseGitRemoteHost(scpHost ? `ssh://${scpHost}` : remoteUrl);
116
+ return remote === null ? null : unknownHostProvider(remote);
117
}
118
119
// A glab login confirms a self-hosted GitLab whose hostname does not identify its provider.