import type { RepositoryIdentity, SourceControlProviderError } from "@t3tools/contracts"; import { repositoryPathFromRemoteUrl } from "@t3tools/source-control-core/server/SourceControlProvider"; import { detectSourceControlProviderFromGitRemoteUrl, normalizeGitRemoteUrl, } from "@t3tools/shared/git"; import * as Cache from "effect/Cache"; import * as Context from "effect/Context"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Layer from "effect/Layer"; import * as ProcessRunner from "../processRunner.ts"; import { explicitBareRepositoryEnv } from "../vcs/VcsProcess.ts"; import * as HostProcess from "@t3tools/shared/HostProcess"; const DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY = 512; // Background sweeps resolve every project each minute. A long TTL keeps them // from spawning git each time. Clone, publish, and PR discovery (after a turn // and before it saves links) resolve with `refresh: true`. const DEFAULT_POSITIVE_CACHE_TTL = Duration.minutes(15); const DEFAULT_NEGATIVE_CACHE_TTL = Duration.minutes(1); export interface RepositoryIdentityResolverOptions { readonly cacheCapacity?: number; readonly positiveCacheTtl?: Duration.Input; readonly negativeCacheTtl?: Duration.Input; readonly refine?: ( identity: RepositoryIdentity, ) => Effect.Effect; } export class RepositoryIdentityResolver extends Context.Service< RepositoryIdentityResolver, { readonly resolve: ( cwd: string, options?: { readonly refresh?: boolean }, ) => Effect.Effect; } >()("t3/project/RepositoryIdentityResolver") {} // Local remotes (GitButler's `gb-local` is `.`) name a path on this machine, // not a repository, so unrelated repos would share one identity. function isLocalRemoteUrl(url: string): boolean { if (/^file:/i.test(url)) return true; if (/^[a-z][a-z0-9+.-]*:\/\//i.test(url)) return false; if (/^[a-z]:[\\/]/i.test(url)) return true; // Git treats `host:path` as scp-style only when the colon precedes any slash. const colonIndex = url.indexOf(":"); const slashIndex = url.search(/[\\/]/); return colonIndex === -1 || (slashIndex !== -1 && slashIndex < colonIndex); } function parseRemoteFetchUrls(stdout: string): Map { const remotes = new Map(); for (const line of stdout.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 [, remoteName = "", remoteUrl = "", direction = ""] = match; if ( direction !== "fetch" || remoteName.length === 0 || remoteUrl.length === 0 || isLocalRemoteUrl(remoteUrl) ) { continue; } remotes.set(remoteName, remoteUrl); } return remotes; } function pickPrimaryRemote( remotes: ReadonlyMap, ): { readonly remoteName: string; readonly remoteUrl: string } | null { for (const preferredRemoteName of ["upstream", "origin"] as const) { const remoteUrl = remotes.get(preferredRemoteName); if (remoteUrl) { return { remoteName: preferredRemoteName, remoteUrl }; } } const [remoteName, remoteUrl] = [...remotes.entries()].toSorted(([left], [right]) => left.localeCompare(right))[0] ?? []; return remoteName && remoteUrl ? { remoteName, remoteUrl } : null; } function repositoryPathOf(canonicalKey: string, remoteUrl: string): string { const canonicalPath = canonicalKey.split("/").slice(1).join("/"); const displayPath = repositoryPathFromRemoteUrl(remoteUrl); return displayPath?.toLowerCase() === canonicalPath ? displayPath : canonicalPath; } function buildRepositoryOrigin( originUrl: string | undefined, canonicalKey: string, ): RepositoryIdentity["origin"] { if (!originUrl) return undefined; const originKey = normalizeGitRemoteUrl(originUrl); if (originKey === canonicalKey) return undefined; const displayName = repositoryPathOf(originKey, originUrl); return { canonicalKey: originKey, ...(displayName ? { displayName } : {}) }; } function buildRepositoryIdentity(input: { readonly remoteName: string; readonly remoteUrl: string; readonly originUrl: string | undefined; readonly rootPath: string; }): RepositoryIdentity { const canonicalKey = normalizeGitRemoteUrl(input.remoteUrl); const sourceControlProvider = detectSourceControlProviderFromGitRemoteUrl(input.remoteUrl); const repositoryPath = repositoryPathOf(canonicalKey, input.remoteUrl); const repositoryPathSegments = repositoryPath.split("/").filter((segment) => segment.length > 0); const [owner] = repositoryPathSegments; const repositoryName = repositoryPathSegments.at(-1); const origin = buildRepositoryOrigin(input.originUrl, canonicalKey); return { canonicalKey, locator: { source: "git-remote", remoteName: input.remoteName, remoteUrl: input.remoteUrl, }, rootPath: input.rootPath, ...(repositoryPath ? { displayName: repositoryPath } : {}), ...(sourceControlProvider ? { provider: sourceControlProvider.kind } : {}), ...(owner ? { owner } : {}), ...(repositoryName ? { name: repositoryName } : {}), ...(origin ? { origin } : {}), }; } const resolveRepositoryIdentityCacheKey = Effect.fn("RepositoryIdentityResolver.resolveCacheKey")( function* (cwd: string) { const processRunner = yield* ProcessRunner.ProcessRunner; // git is a real executable on every platform — no cmd.exe shell mode, which // would split paths containing spaces during cmd's re-tokenization. const topLevelResult = yield* processRunner .run({ command: "git", args: ["-C", cwd, "rev-parse", "--show-toplevel"], env: explicitBareRepositoryEnv(process.env, yield* HostProcess.Platform), timeoutBehavior: "timedOutResult", }) .pipe(Effect.option); if (topLevelResult._tag === "None" || topLevelResult.value.code !== 0) { return null; } const candidate = topLevelResult.value.stdout.trim(); return candidate.length > 0 ? candidate : null; }, ); const resolveRepositoryIdentityFromCacheKey = Effect.fn( "RepositoryIdentityResolver.resolveFromCacheKey", )(function* ( cacheKey: string, ): Effect.fn.Return { const processRunner = yield* ProcessRunner.ProcessRunner; const remoteResult = yield* processRunner .run({ command: "git", args: ["-C", cacheKey, "remote", "-v"], env: explicitBareRepositoryEnv(process.env, yield* HostProcess.Platform), timeoutBehavior: "timedOutResult", }) .pipe(Effect.option); if (remoteResult._tag === "None" || remoteResult.value.code !== 0) { return null; } const remotes = parseRemoteFetchUrls(remoteResult.value.stdout); const remote = pickPrimaryRemote(remotes); return remote ? buildRepositoryIdentity({ ...remote, originUrl: remotes.get("origin"), rootPath: cacheKey }) : null; }); export const make = Effect.fn("RepositoryIdentityResolver.make")(function* ( options: RepositoryIdentityResolverOptions = {}, ) { const processRunner = yield* ProcessRunner.ProcessRunner; const cacheCapacity = options.cacheCapacity ?? DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY; const refine = options.refine ?? Effect.succeed; const timeToLive = (exit: Exit.Exit) => Exit.match(exit, { onSuccess: (value) => value === null ? (options.negativeCacheTtl ?? DEFAULT_NEGATIVE_CACHE_TTL) : (options.positiveCacheTtl ?? DEFAULT_POSITIVE_CACHE_TTL), onFailure: () => Duration.zero, }); const repositoryRootCache = yield* Cache.makeWith( (cwd) => resolveRepositoryIdentityCacheKey(cwd).pipe( Effect.provideService(ProcessRunner.ProcessRunner, processRunner), ), { capacity: cacheCapacity, timeToLive }, ); const repositoryIdentityCache = yield* Cache.makeWith( (cacheKey) => resolveRepositoryIdentityFromCacheKey(cacheKey).pipe( Effect.provideService(ProcessRunner.ProcessRunner, processRunner), Effect.filterOrElse( (identity): identity is null => identity === null, (identity) => refine(identity).pipe(Effect.orElseSucceed(() => identity)), ), ), { capacity: cacheCapacity, timeToLive }, ); const resolve: RepositoryIdentityResolver["Service"]["resolve"] = Effect.fnUntraced( function* (cwd, options) { if (options?.refresh) yield* Cache.invalidate(repositoryRootCache, cwd); const cacheKey = yield* Cache.get(repositoryRootCache, cwd); if (cacheKey === null) return null; if (options?.refresh) yield* Cache.invalidate(repositoryIdentityCache, cacheKey); return yield* Cache.get(repositoryIdentityCache, cacheKey); }, ); return RepositoryIdentityResolver.of({ resolve }); }); export const layer = Layer.effect(RepositoryIdentityResolver, make()).pipe( Layer.provide(ProcessRunner.layer), );