diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 28353df265..bd6eb8e6e8 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -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), }), ), diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts index 9e13ad999a..961911aa47 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -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, }; diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 1c31d6de74..55e7689e97 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -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), diff --git a/apps/server/src/sourceControl/SourceControlProvider.ts b/apps/server/src/sourceControl/SourceControlProvider.ts index 022a88dd48..baa18cb9c4 100644 --- a/apps/server/src/sourceControl/SourceControlProvider.ts +++ b/apps/server/src/sourceControl/SourceControlProvider.ts @@ -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, SourceControlProviderError>; readonly getChangeRequest: (input: { readonly cwd: string; + readonly context?: SourceControlProviderContext; readonly reference: string; }) => Effect.Effect; 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; readonly getRepositoryCloneUrls: (input: { readonly cwd: string; + readonly context?: SourceControlProviderContext; readonly repository: string; }) => Effect.Effect; readonly getDefaultBranch: (input: { readonly cwd: string; + readonly context?: SourceControlProviderContext; }) => Effect.Effect; readonly checkoutChangeRequest: (input: { readonly cwd: string; + readonly context?: SourceControlProviderContext; readonly reference: string; readonly force?: boolean; }) => Effect.Effect; diff --git a/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts b/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts index 7c130ab1ed..ab820a461c 100644 --- a/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts +++ b/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts @@ -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; + + 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: "git@github.com:pingdotgg/t3code.git", + remotes: [{ name: "origin", url: "git@github.com:pingdotgg/t3code.git" }], }); const provider = yield* registry.resolve({ cwd: "/repo" }); @@ -46,7 +70,7 @@ it.effect( () => Effect.gen(function* () { const registry = yield* makeRegistry({ - originUrl: "git@gitlab.com:group/project.git", + remotes: [{ name: "origin", url: "git@gitlab.com: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" }); diff --git a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts b/apps/server/src/sourceControl/SourceControlProviderRegistry.ts index 52a863808f..915365c945 100644 --- a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts +++ b/apps/server/src/sourceControl/SourceControlProviderRegistry.ts @@ -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; readonly resolve: (input: { readonly cwd: string; }) => Effect.Effect; @@ -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) { + const vcsRegistry = yield* VcsDriverRegistry; + const providers = new Map( + 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> = { - 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()); diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index 605242427f..8575c1d55a 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -259,6 +259,38 @@ function chunkPathsForGitCheckIgnore(relativePaths: ReadonlyArray): stri return chunks; } +function parseGitRemoteVerboseOutput( + output: string, +): Map { + const remotes = new Map(); + 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; }); diff --git a/apps/server/src/vcs/VcsDriver.ts b/apps/server/src/vcs/VcsDriver.ts index 7dfa3b707a..b04dd1333e 100644 --- a/apps/server/src/vcs/VcsDriver.ts +++ b/apps/server/src/vcs/VcsDriver.ts @@ -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; + readonly listRemotes: (cwd: string) => Effect.Effect; readonly filterIgnoredPaths: ( cwd: string, relativePaths: ReadonlyArray, diff --git a/apps/web/src/sourceControlPresentation.ts b/apps/web/src/sourceControlPresentation.ts new file mode 100644 index 0000000000..f007513520 --- /dev/null +++ b/apps/web/src/sourceControlPresentation.ts @@ -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}`; +} diff --git a/packages/contracts/src/vcs.ts b/packages/contracts/src/vcs.ts index bd9a81f7e2..72ba544147 100644 --- a/packages/contracts/src/vcs.ts +++ b/packages/contracts/src/vcs.ts @@ -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", { diff --git a/packages/shared/package.json b/packages/shared/package.json index 82085dfcaf..da0f24b77a 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -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" diff --git a/packages/shared/src/git.ts b/packages/shared/src/git.ts index 411e68a815..02d9c61d6a 100644 --- a/packages/shared/src/git.ts +++ b/packages/shared/src/git.ts @@ -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 = { diff --git a/packages/shared/src/sourceControl.ts b/packages/shared/src/sourceControl.ts new file mode 100644 index 0000000000..2e7b292832 --- /dev/null +++ b/packages/shared/src/sourceControl.ts @@ -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), + }; +}