Add generic source control provider routing core

This commit is contained in:
Julius Marminge authored and Julius Marminge committed 2026-05-02 14:22:14 -07:00
1 parent 66640c6c27
commit 25058ddfe5
13 files changed
+441 -166

No files matched your search

+1
View File
@@ -660,6 +660,7 @@ function makeManager(input?: {
GitHubSourceControlProvider.make().pipe(
Effect.map((provider) =>
SourceControlProviderRegistry.SourceControlProviderRegistry.of({
resolveHandle: () => Effect.succeed({ provider, context: null }),
resolve: () => Effect.succeed(provider),
}),
),
+10
View File
@@ -382,6 +382,7 @@ const buildAppUnderTest = (options?: {
supportsBookmarks: false,
supportsAtomicSnapshot: false,
supportsPushDefaultRemote: true,
ignoreClassifier: "native",
},
execute: () =>
Effect.succeed({
@@ -403,6 +404,15 @@ const buildAppUnderTest = (options?: {
expiresAt: Option.none(),
},
}),
listRemotes: () =>
Effect.succeed({
remotes: [],
freshness: {
source: "live-local",
observedAt: TEST_EPOCH,
expiresAt: Option.none(),
},
}),
filterIgnoredPaths: (_cwd, relativePaths) => Effect.succeed(relativePaths),
...options?.layers?.vcsDriver,
};
+10 -5
View File
@@ -155,10 +155,19 @@ const ProviderLayerLive = ProviderServiceLive.pipe(
const PersistenceLayerLive = Layer.empty.pipe(Layer.provideMerge(SqlitePersistenceLayerLive));
const VcsDriverRegistryLayerLive = VcsDriverRegistry.layer.pipe(
Layer.provide(VcsProjectConfig.layer),
);
const GitManagerLayerLive = GitManager.layer.pipe(
Layer.provideMerge(ProjectSetupScriptRunnerLive),
Layer.provideMerge(GitVcsDriver.layer),
Layer.provideMerge(SourceControlProviderRegistry.layer.pipe(Layer.provide(GitHubCli.layer))),
Layer.provideMerge(
SourceControlProviderRegistry.layer.pipe(
Layer.provide(GitHubCli.layer),
Layer.provideMerge(VcsDriverRegistryLayerLive),
),
),
Layer.provideMerge(TextGeneration.layer),
);
@@ -167,10 +176,6 @@ const GitLayerLive = Layer.empty.pipe(
Layer.provideMerge(GitVcsDriver.layer),
);
const VcsDriverRegistryLayerLive = VcsDriverRegistry.layer.pipe(
Layer.provide(VcsProjectConfig.layer),
);
const GitWorkflowLayerLive = GitWorkflowService.layer.pipe(
Layer.provideMerge(VcsDriverRegistryLayerLive),
Layer.provideMerge(GitLayerLive),
@@ -3,24 +3,43 @@ import type {
ChangeRequest,
ChangeRequestState,
SourceControlProviderError,
SourceControlProviderInfo,
SourceControlProviderKind,
SourceControlRepositoryCloneUrls,
} from "@t3tools/contracts";
export interface SourceControlProviderContext {
readonly provider: SourceControlProviderInfo;
readonly remoteName: string;
readonly remoteUrl: string;
}
export interface SourceControlRefSelector {
readonly refName: string;
readonly owner?: string;
readonly repository?: string;
}
export interface SourceControlProviderShape {
readonly kind: SourceControlProviderKind;
readonly listChangeRequests: (input: {
readonly cwd: string;
readonly context?: SourceControlProviderContext;
readonly source?: SourceControlRefSelector;
readonly headSelector: string;
readonly state: ChangeRequestState | "all";
readonly limit?: number;
}) => Effect.Effect<ReadonlyArray<ChangeRequest>, SourceControlProviderError>;
readonly getChangeRequest: (input: {
readonly cwd: string;
readonly context?: SourceControlProviderContext;
readonly reference: string;
}) => Effect.Effect<ChangeRequest, SourceControlProviderError>;
readonly createChangeRequest: (input: {
readonly cwd: string;
readonly context?: SourceControlProviderContext;
readonly source?: SourceControlRefSelector;
readonly target?: SourceControlRefSelector;
readonly baseRefName: string;
readonly headSelector: string;
readonly title: string;
@@ -28,13 +47,16 @@ export interface SourceControlProviderShape {
}) => Effect.Effect<void, SourceControlProviderError>;
readonly getRepositoryCloneUrls: (input: {
readonly cwd: string;
readonly context?: SourceControlProviderContext;
readonly repository: string;
}) => Effect.Effect<SourceControlRepositoryCloneUrls, SourceControlProviderError>;
readonly getDefaultBranch: (input: {
readonly cwd: string;
readonly context?: SourceControlProviderContext;
}) => Effect.Effect<string | null, SourceControlProviderError>;
readonly checkoutChangeRequest: (input: {
readonly cwd: string;
readonly context?: SourceControlProviderContext;
readonly reference: string;
readonly force?: boolean;
}) => Effect.Effect<void, SourceControlProviderError>;
@@ -1,38 +1,62 @@
import { assert, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { DateTime, Effect, Layer, Option } from "effect";
import { GitHubCli } from "./GitHubCli.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
import { VcsDriverRegistry } from "../vcs/VcsDriverRegistry.ts";
import type { VcsDriverShape } from "../vcs/VcsDriver.ts";
const processResult = (stdout: string) => ({
stdout,
stderr: "",
exitCode: ChildProcessSpawner.ExitCode(0),
stdoutTruncated: false,
stderrTruncated: false,
});
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
function makeRegistry(input: {
readonly originUrl?: string | null;
readonly remoteVerboseOutput?: string;
readonly remotes: ReadonlyArray<{
readonly name: string;
readonly url: string;
}>;
}) {
const gitLayer = Layer.mock(GitVcsDriver.GitVcsDriver)({
readConfigValue: (_cwd, key) =>
key === "remote.origin.url" ? Effect.succeed(input.originUrl ?? null) : Effect.succeed(null),
execute: () => Effect.succeed(processResult(input.remoteVerboseOutput ?? "")),
const driver = {
listRemotes: () =>
Effect.succeed({
remotes: input.remotes.map((remote) => ({
...remote,
pushUrl: Option.none(),
isPrimary: remote.name === "origin",
})),
freshness: {
source: "live-local" as const,
observedAt: TEST_EPOCH,
expiresAt: Option.none(),
},
}),
} satisfies Partial<VcsDriverShape>;
const registryLayer = Layer.mock(VcsDriverRegistry)({
resolve: () =>
Effect.succeed({
kind: "git",
repository: {
kind: "git",
rootPath: "/repo",
metadataPath: null,
freshness: {
source: "live-local" as const,
observedAt: TEST_EPOCH,
expiresAt: Option.none(),
},
},
driver: driver as unknown as VcsDriverShape,
}),
});
return SourceControlProviderRegistry.make().pipe(
Effect.provide(Layer.mergeAll(gitLayer, Layer.mock(GitHubCli)({}))),
Effect.provide(Layer.mergeAll(registryLayer, Layer.mock(GitHubCli)({}))),
);
}
it.effect("routes GitHub remotes to the GitHub provider", () =>
Effect.gen(function* () {
const registry = yield* makeRegistry({
originUrl: "[email protected]:pingdotgg/t3code.git",
remotes: [{ name: "origin", url: "[email protected]:pingdotgg/t3code.git" }],
});
const provider = yield* registry.resolve({ cwd: "/repo" });
@@ -46,7 +70,7 @@ it.effect(
() =>
Effect.gen(function* () {
const registry = yield* makeRegistry({
originUrl: "[email protected]:group/project.git",
remotes: [{ name: "origin", url: "[email protected]:group/project.git" }],
});
const provider = yield* registry.resolve({ cwd: "/repo" });
@@ -64,14 +88,10 @@ it.effect(
}),
);
it.effect("falls back to remote verbose output when origin is not configured", () =>
it.effect("falls back to a non-origin remote when origin is not configured", () =>
Effect.gen(function* () {
const registry = yield* makeRegistry({
originUrl: null,
remoteVerboseOutput: [
"upstream\thttps://dev.azure.com/acme/project/_git/repo (fetch)",
"upstream\thttps://dev.azure.com/acme/project/_git/repo (push)",
].join("\n"),
remotes: [{ name: "upstream", url: "https://dev.azure.com/acme/project/_git/repo" }],
});
const provider = yield* registry.resolve({ cwd: "/repo" });
@@ -1,16 +1,33 @@
import { Cache, Context, Duration, Effect, Exit, Layer } from "effect";
import { SourceControlProviderError } from "@t3tools/contracts";
import type { SourceControlProviderKind } from "@t3tools/contracts";
import { detectSourceControlProviderFromGitRemoteUrl } from "@t3tools/shared/git";
import { detectSourceControlProviderFromRemoteUrl } from "@t3tools/shared/sourceControl";
import { SourceControlProvider, type SourceControlProviderShape } from "./SourceControlProvider.ts";
import {
SourceControlProvider,
type SourceControlProviderContext,
type SourceControlProviderShape,
} from "./SourceControlProvider.ts";
import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import { VcsDriverRegistry } from "../vcs/VcsDriverRegistry.ts";
const PROVIDER_DETECTION_CACHE_CAPACITY = 2_048;
const PROVIDER_DETECTION_CACHE_TTL = Duration.seconds(5);
export interface SourceControlProviderRegistration {
readonly kind: SourceControlProviderKind;
readonly provider: SourceControlProviderShape;
}
export interface SourceControlProviderHandle {
readonly provider: SourceControlProviderShape;
readonly context: SourceControlProviderContext | null;
}
export interface SourceControlProviderRegistryShape {
readonly resolveHandle: (input: {
readonly cwd: string;
}) => Effect.Effect<SourceControlProviderHandle, SourceControlProviderError>;
readonly resolve: (input: {
readonly cwd: string;
}) => Effect.Effect<SourceControlProviderShape, SourceControlProviderError>;
@@ -51,72 +68,88 @@ function providerDetectionError(operation: string, cwd: string, cause: unknown)
});
}
function firstRemoteUrlFromVerboseOutput(output: string): string | null {
for (const line of output.split("\n")) {
const trimmed = line.trim();
if (trimmed.length === 0) {
continue;
}
const match = /^\S+\s+(\S+)\s+\((?:fetch|push)\)$/.exec(trimmed);
const remoteUrl = match?.[1]?.trim() ?? "";
if (remoteUrl.length > 0) {
return remoteUrl;
}
}
return null;
function selectProviderContext(
remotes: ReadonlyArray<{
readonly name: string;
readonly url: string;
}>,
): SourceControlProviderContext | null {
const candidates = remotes
.map((remote) => {
const provider = detectSourceControlProviderFromRemoteUrl(remote.url);
return provider
? {
provider,
remoteName: remote.name,
remoteUrl: remote.url,
}
: null;
})
.filter((value): value is SourceControlProviderContext => value !== null);
return (
candidates.find((candidate) => candidate.remoteName === "origin") ??
candidates.find((candidate) => candidate.provider.kind !== "unknown") ??
candidates[0] ??
null
);
}
export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWithProviders")(
function* (registrations: ReadonlyArray<SourceControlProviderRegistration>) {
const vcsRegistry = yield* VcsDriverRegistry;
const providers = new Map<SourceControlProviderKind, SourceControlProviderShape>(
registrations.map((registration) => [registration.kind, registration.provider]),
);
const detectProviderContext = Effect.fn("SourceControlProviderRegistry.detectProviderContext")(
function* (cwd: string) {
const handle = yield* vcsRegistry
.resolve({ cwd })
.pipe(Effect.mapError((error) => providerDetectionError("detectProvider", cwd, error)));
const remotes = yield* handle.driver
.listRemotes(cwd)
.pipe(Effect.mapError((error) => providerDetectionError("detectProvider", cwd, error)));
return selectProviderContext(remotes.remotes);
},
);
const providerContextCache = yield* Cache.makeWith<
string,
SourceControlProviderContext | null,
SourceControlProviderError
>(detectProviderContext, {
capacity: PROVIDER_DETECTION_CACHE_CAPACITY,
timeToLive: (exit) => (Exit.isSuccess(exit) ? PROVIDER_DETECTION_CACHE_TTL : Duration.zero),
});
const resolveHandle: SourceControlProviderRegistryShape["resolveHandle"] = (input) =>
Cache.get(providerContextCache, input.cwd).pipe(
Effect.map((context) => {
const kind = context?.provider.kind ?? "unknown";
return {
provider: providers.get(kind) ?? unsupportedProvider(kind),
context,
} satisfies SourceControlProviderHandle;
}),
);
return SourceControlProviderRegistry.of({
resolveHandle,
resolve: (input) => resolveHandle(input).pipe(Effect.map((handle) => handle.provider)),
});
},
);
export const make = Effect.fn("makeSourceControlProviderRegistry")(function* () {
const github = yield* GitHubSourceControlProvider.make();
const git = yield* GitVcsDriver.GitVcsDriver;
const providers: Partial<Record<SourceControlProviderKind, SourceControlProviderShape>> = {
github,
};
const detectProviderKind = Effect.fn("SourceControlProviderRegistry.detectProviderKind")(
function* (cwd: string) {
const originUrl = yield* git
.readConfigValue(cwd, "remote.origin.url")
.pipe(Effect.catch(() => Effect.succeed(null)));
const remoteUrl =
originUrl ??
(yield* git
.execute({
operation: "SourceControlProviderRegistry.detectProvider.remoteVerbose",
cwd,
args: ["remote", "-v"],
allowNonZeroExit: true,
})
.pipe(
Effect.map((result) =>
result.exitCode === 0 ? firstRemoteUrlFromVerboseOutput(result.stdout) : null,
),
Effect.mapError((error) => providerDetectionError("detectProvider", cwd, error)),
));
if (!remoteUrl) {
return "unknown" as const;
}
return detectSourceControlProviderFromGitRemoteUrl(remoteUrl)?.kind ?? "unknown";
return yield* makeWithProviders([
{
kind: "github",
provider: github,
},
);
const providerKindCache = yield* Cache.makeWith<
string,
SourceControlProviderKind,
SourceControlProviderError
>(detectProviderKind, {
capacity: PROVIDER_DETECTION_CACHE_CAPACITY,
timeToLive: (exit) => (Exit.isSuccess(exit) ? PROVIDER_DETECTION_CACHE_TTL : Duration.zero),
});
return SourceControlProviderRegistry.of({
resolve: (input) =>
Cache.get(providerKindCache, input.cwd).pipe(
Effect.map((kind) => providers[kind] ?? unsupportedProvider(kind)),
),
});
]);
});
export const layer = Layer.effect(SourceControlProviderRegistry, make());
+72
View File
@@ -259,6 +259,38 @@ function chunkPathsForGitCheckIgnore(relativePaths: ReadonlyArray<string>): stri
return chunks;
}
function parseGitRemoteVerboseOutput(
output: string,
): Map<string, { url?: string; pushUrl?: string }> {
const remotes = new Map<string, { url?: string; pushUrl?: string }>();
for (const line of output.split("\n")) {
const trimmed = line.trim();
if (trimmed.length === 0) {
continue;
}
const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)$/.exec(trimmed);
if (!match) {
continue;
}
const name = match[1];
const url = match[2];
const direction = match[3];
if (!name || !url || !direction) {
continue;
}
const remote = remotes.get(name) ?? {};
if (direction === "fetch") {
remote.url = url;
} else {
remote.pushUrl = url;
}
remotes.set(name, remote);
}
return remotes;
}
const gitCommand = (
process: VcsProcessShape,
operation: string,
@@ -298,6 +330,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
supportsBookmarks: false,
supportsAtomicSnapshot: false,
supportsPushDefaultRemote: true,
ignoreClassifier: "native" as const,
};
const isInsideWorkTree: VcsDriverShape["isInsideWorkTree"] = (cwd) =>
@@ -393,6 +426,44 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
),
);
const listRemotes: VcsDriverShape["listRemotes"] = Effect.fn("listRemotes")(function* (cwd) {
const result = yield* gitCommand(process, "GitVcsDriver.listRemotes", cwd, ["remote", "-v"], {
allowNonZeroExit: true,
timeoutMs: 5_000,
maxOutputBytes: 64 * 1024,
});
if (result.exitCode !== 0) {
return yield* new VcsProcessExitError({
operation: "GitVcsDriver.listRemotes",
command: "git remote -v",
cwd,
exitCode: result.exitCode,
detail: result.stderr.trim() || "git remote -v failed",
});
}
const parsed = parseGitRemoteVerboseOutput(result.stdout);
const remotes = Array.from(parsed.entries()).flatMap(([name, remote]) => {
if (!remote.url) {
return [];
}
return [
{
name,
url: remote.url,
pushUrl: remote.pushUrl ? Option.some(remote.pushUrl) : Option.none(),
isPrimary: name === "origin",
},
];
});
return {
remotes,
freshness: yield* nowFreshness(),
};
});
const filterIgnoredPaths: VcsDriverShape["filterIgnoredPaths"] = Effect.fn("filterIgnoredPaths")(
function* (cwd, relativePaths) {
if (relativePaths.length === 0) {
@@ -446,6 +517,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
detectRepository,
isInsideWorkTree,
listWorkspaceFiles,
listRemotes,
filterIgnoredPaths,
} satisfies VcsDriverShape;
});
+2
View File
@@ -3,6 +3,7 @@ import { Context, type Effect } from "effect";
import type {
VcsDriverCapabilities,
VcsError,
VcsListRemotesResult,
VcsListWorkspaceFilesResult,
VcsRepositoryIdentity,
} from "@t3tools/contracts";
@@ -18,6 +19,7 @@ export interface VcsDriverShape {
readonly listWorkspaceFiles: (
cwd: string,
) => Effect.Effect<VcsListWorkspaceFilesResult, VcsError>;
readonly listRemotes: (cwd: string) => Effect.Effect<VcsListRemotesResult, VcsError>;
readonly filterIgnoredPaths: (
cwd: string,
relativePaths: ReadonlyArray<string>,
+83
View File
@@ -0,0 +1,83 @@
import type { SourceControlProviderInfo } from "@t3tools/contracts";
export interface ChangeRequestPresentation {
readonly icon: "github" | "gitlab" | "azure-devops" | "change-request";
readonly providerName: string;
readonly shortName: string;
readonly longName: string;
readonly pluralLongName: string;
readonly providerLongName: string;
readonly checkoutCommandExample: string;
readonly urlExample: string;
}
const GITHUB_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
icon: "github",
providerName: "GitHub",
shortName: "PR",
longName: "pull request",
pluralLongName: "pull requests",
providerLongName: "GitHub pull request",
checkoutCommandExample: "gh pr checkout 123",
urlExample: "https://github.com/owner/repo/pull/42",
};
const GITLAB_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
icon: "gitlab",
providerName: "GitLab",
shortName: "MR",
longName: "merge request",
pluralLongName: "merge requests",
providerLongName: "GitLab merge request",
checkoutCommandExample: "glab mr checkout 123",
urlExample: "https://gitlab.com/group/project/-/merge_requests/42",
};
const AZURE_DEVOPS_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
icon: "azure-devops",
providerName: "Azure DevOps",
shortName: "PR",
longName: "pull request",
pluralLongName: "pull requests",
providerLongName: "Azure DevOps pull request",
checkoutCommandExample: "az repos pr checkout --id 123",
urlExample: "https://dev.azure.com/org/project/_git/repo/pullrequest/42",
};
const GENERIC_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
icon: "change-request",
providerName: "source control",
shortName: "change request",
longName: "change request",
pluralLongName: "change requests",
providerLongName: "change request",
checkoutCommandExample: "123",
urlExample: "#42",
};
export function resolveChangeRequestPresentation(
provider: SourceControlProviderInfo | null | undefined,
): ChangeRequestPresentation {
switch (provider?.kind) {
case "github":
case undefined:
return GITHUB_CHANGE_REQUEST_PRESENTATION;
case "gitlab":
return GITLAB_CHANGE_REQUEST_PRESENTATION;
case "azure-devops":
return AZURE_DEVOPS_CHANGE_REQUEST_PRESENTATION;
case "unknown":
return GENERIC_CHANGE_REQUEST_PRESENTATION;
}
}
export function formatChangeRequestAction(
verb: "View" | "Create",
presentation: ChangeRequestPresentation,
): string {
return `${verb} ${presentation.shortName}`;
}
export function formatCreateChangeRequestPhrase(presentation: ChangeRequestPresentation): string {
return `create ${presentation.shortName}`;
}
+15
View File
@@ -25,6 +25,7 @@ export const VcsDriverCapabilities = Schema.Struct({
supportsBookmarks: Schema.Boolean,
supportsAtomicSnapshot: Schema.Boolean,
supportsPushDefaultRemote: Schema.Boolean,
ignoreClassifier: Schema.Literals(["native", "git-compatible-fallback"]),
});
export type VcsDriverCapabilities = typeof VcsDriverCapabilities.Type;
@@ -43,6 +44,20 @@ export const VcsListWorkspaceFilesResult = Schema.Struct({
});
export type VcsListWorkspaceFilesResult = typeof VcsListWorkspaceFilesResult.Type;
export const VcsRemote = Schema.Struct({
name: TrimmedNonEmptyString,
url: TrimmedNonEmptyString,
pushUrl: Schema.Option(TrimmedNonEmptyString),
isPrimary: Schema.Boolean,
});
export type VcsRemote = typeof VcsRemote.Type;
export const VcsListRemotesResult = Schema.Struct({
remotes: Schema.Array(VcsRemote),
freshness: VcsFreshness,
});
export type VcsListRemotesResult = typeof VcsListRemotesResult.Type;
export class VcsProcessSpawnError extends Schema.TaggedErrorClass<VcsProcessSpawnError>()(
"VcsProcessSpawnError",
{
+4
View File
@@ -12,6 +12,10 @@
"types": "./src/git.ts",
"import": "./src/git.ts"
},
"./sourceControl": {
"types": "./src/sourceControl.ts",
"import": "./src/sourceControl.ts"
},
"./logging": {
"types": "./src/logging.ts",
"import": "./src/logging.ts"
+2 -72
View File
@@ -8,6 +8,7 @@ import type {
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Random from "effect/Random";
import { detectSourceControlProviderFromRemoteUrl } from "./sourceControl.ts";
export const WORKTREE_BRANCH_PREFIX = "t3code";
const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);
@@ -191,81 +192,10 @@ export function dedupeRemoteBranchesWithLocalMatches(
});
}
function parseGitRemoteHost(remoteUrl: string): string | null {
const trimmed = remoteUrl.trim();
if (trimmed.length === 0) {
return null;
}
if (trimmed.startsWith("git@")) {
const hostWithPath = trimmed.slice("git@".length);
const separatorIndex = hostWithPath.search(/[:/]/);
if (separatorIndex <= 0) {
return null;
}
return hostWithPath.slice(0, separatorIndex).toLowerCase();
}
try {
return new URL(trimmed).hostname.toLowerCase();
} catch {
return null;
}
}
function toBaseUrl(host: string): string {
return `https://${host}`;
}
function isGitHubHost(host: string): boolean {
return host === "github.com" || host.includes("github");
}
function isGitLabHost(host: string): boolean {
return host === "gitlab.com" || host.includes("gitlab");
}
function isAzureDevOpsHost(host: string): boolean {
return host === "dev.azure.com" || host.endsWith(".visualstudio.com");
}
export function detectSourceControlProviderFromGitRemoteUrl(
remoteUrl: string,
): SourceControlProviderInfo | null {
const host = parseGitRemoteHost(remoteUrl);
if (!host) {
return null;
}
if (isGitHubHost(host)) {
return {
kind: "github",
name: host === "github.com" ? "GitHub" : "GitHub Self-Hosted",
baseUrl: toBaseUrl(host),
};
}
if (isGitLabHost(host)) {
return {
kind: "gitlab",
name: host === "gitlab.com" ? "GitLab" : "GitLab Self-Hosted",
baseUrl: toBaseUrl(host),
};
}
if (isAzureDevOpsHost(host)) {
return {
kind: "azure-devops",
name: "Azure DevOps",
baseUrl: toBaseUrl(host),
};
}
return {
kind: "unknown",
name: host,
baseUrl: toBaseUrl(host),
};
return detectSourceControlProviderFromRemoteUrl(remoteUrl);
}
const EMPTY_GIT_STATUS_REMOTE: VcsStatusRemoteResult = {
+78
View File
@@ -0,0 +1,78 @@
import type { SourceControlProviderInfo } from "@t3tools/contracts";
function parseRemoteHost(remoteUrl: string): string | null {
const trimmed = remoteUrl.trim();
if (trimmed.length === 0) {
return null;
}
if (trimmed.startsWith("git@")) {
const hostWithPath = trimmed.slice("git@".length);
const separatorIndex = hostWithPath.search(/[:/]/);
if (separatorIndex <= 0) {
return null;
}
return hostWithPath.slice(0, separatorIndex).toLowerCase();
}
try {
return new URL(trimmed).hostname.toLowerCase();
} catch {
return null;
}
}
function toBaseUrl(host: string): string {
return `https://${host}`;
}
function isGitHubHost(host: string): boolean {
return host === "github.com" || host.includes("github");
}
function isGitLabHost(host: string): boolean {
return host === "gitlab.com" || host.includes("gitlab");
}
function isAzureDevOpsHost(host: string): boolean {
return host === "dev.azure.com" || host.endsWith(".visualstudio.com");
}
export function detectSourceControlProviderFromRemoteUrl(
remoteUrl: string,
): SourceControlProviderInfo | null {
const host = parseRemoteHost(remoteUrl);
if (!host) {
return null;
}
if (isGitHubHost(host)) {
return {
kind: "github",
name: host === "github.com" ? "GitHub" : "GitHub Self-Hosted",
baseUrl: toBaseUrl(host),
};
}
if (isGitLabHost(host)) {
return {
kind: "gitlab",
name: host === "gitlab.com" ? "GitLab" : "GitLab Self-Hosted",
baseUrl: toBaseUrl(host),
};
}
if (isAzureDevOpsHost(host)) {
return {
kind: "azure-devops",
name: "Azure DevOps",
baseUrl: toBaseUrl(host),
};
}
return {
kind: "unknown",
name: host,
baseUrl: toBaseUrl(host),
};
}