Open History to see the last commit
1import type { RepositoryIdentity } from "@t3tools/contracts";
2import {
3 detectSourceControlProviderFromGitRemoteUrl,
4 normalizeGitRemoteUrl,
5} from "@t3tools/shared/git";
6import { parseSshResolveOutput } from "@t3tools/ssh/command";
7import * as Cache from "effect/Cache";
8import * as Context from "effect/Context";
9import * as Duration from "effect/Duration";
10import * as Effect from "effect/Effect";
11import * as Exit from "effect/Exit";
12import * as Layer from "effect/Layer";
13
14import * as ProcessRunner from "../processRunner.ts";
15import { resolveGitRemoteForSourceControl } from "../sourceControl/resolveGitRemoteForSourceControl.ts";
16
17const DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY = 512;
18const DEFAULT_POSITIVE_CACHE_TTL = Duration.minutes(1);
19const DEFAULT_NEGATIVE_CACHE_TTL = Duration.minutes(1);
20
21export interface RepositoryIdentityResolverOptions {
22 readonly cacheCapacity?: number;
23 readonly positiveCacheTtl?: Duration.Input;
24 readonly negativeCacheTtl?: Duration.Input;
25}
26
27export class RepositoryIdentityResolver extends Context.Service<
28 RepositoryIdentityResolver,
29 {
30 readonly resolve: (cwd: string) => Effect.Effect<RepositoryIdentity | null>;
31 }
32>()("t3/project/RepositoryIdentityResolver") {}
33
34function parseRemoteFetchUrls(stdout: string): Map<string, string> {
35 const remotes = new Map<string, string>();
36 for (const line of stdout.split("\n")) {
37 const trimmed = line.trim();
38 if (trimmed.length === 0) continue;
39 const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)$/.exec(trimmed);
40 if (!match) continue;
41 const [, remoteName = "", remoteUrl = "", direction = ""] = match;
42 if (direction !== "fetch" || remoteName.length === 0 || remoteUrl.length === 0) {
43 continue;
44 }
45 remotes.set(remoteName, remoteUrl);
46 }
47 return remotes;
48}
49
50function pickPrimaryRemote(
51 remotes: ReadonlyMap<string, string>,
52): { readonly remoteName: string; readonly remoteUrl: string } | null {
53 for (const preferredRemoteName of ["upstream", "origin"] as const) {
54 const remoteUrl = remotes.get(preferredRemoteName);
55 if (remoteUrl) {
56 return { remoteName: preferredRemoteName, remoteUrl };
57 }
58 }
59
60 const [remoteName, remoteUrl] =
61 [...remotes.entries()].toSorted(([left], [right]) => left.localeCompare(right))[0] ?? [];
62 return remoteName && remoteUrl ? { remoteName, remoteUrl } : null;
63}
64
65// This layer is provided in many tests without NodeServices. Resolve HostName
66// through ProcessRunner so SSH Effect services do not leak onto the service.
67function resolveSshHostnameWithProcessRunner(
68 processRunner: ProcessRunner.ProcessRunner["Service"],
69): (alias: string) => Effect.Effect<string | null> {
70 return (alias) =>
71 processRunner
72 .run({
73 command: "ssh",
74 args: ["-G", alias],
75 timeout: Duration.seconds(5),
76 timeoutBehavior: "timedOutResult",
77 })
78 .pipe(
79 Effect.map((result) => {
80 if (result.timedOut || result.code !== 0) {
81 return null;
82 }
83 const hostname = parseSshResolveOutput(alias, result.stdout).hostname.trim();
84 return hostname.length > 0 ? hostname : null;
85 }),
86 Effect.orElseSucceed(() => null),
87 );
88}
89
90function buildRepositoryIdentity(input: {
91 readonly remoteName: string;
92 readonly remoteUrl: string;
93 readonly detectionUrl: string;
94 readonly rootPath: string;
95}): RepositoryIdentity {
96 const canonicalKey = normalizeGitRemoteUrl(input.detectionUrl);
97 const sourceControlProvider = detectSourceControlProviderFromGitRemoteUrl(input.detectionUrl);
98 const repositoryPath = canonicalKey.split("/").slice(1).join("/");
99 const repositoryPathSegments = repositoryPath.split("/").filter((segment) => segment.length > 0);
100 const [owner] = repositoryPathSegments;
101 const repositoryName = repositoryPathSegments.at(-1);
102
103 return {
104 canonicalKey,
105 locator: {
106 source: "git-remote",
107 remoteName: input.remoteName,
108 remoteUrl: input.remoteUrl,
109 },
110 rootPath: input.rootPath,
111 ...(repositoryPath ? { displayName: repositoryPath } : {}),
112 ...(sourceControlProvider ? { provider: sourceControlProvider.kind } : {}),
113 ...(owner ? { owner } : {}),
114 ...(repositoryName ? { name: repositoryName } : {}),
115 };
116}
117
118const resolveRepositoryIdentityCacheKey = Effect.fn("RepositoryIdentityResolver.resolveCacheKey")(
119 function* (cwd: string) {
120 const processRunner = yield* ProcessRunner.ProcessRunner;
121 let cacheKey = cwd;
122
123 // git is a real executable on every platform — no cmd.exe shell mode, which
124 // would split paths containing spaces during cmd's re-tokenization.
125 const topLevelResult = yield* processRunner
126 .run({
127 command: "git",
128 args: ["-C", cwd, "rev-parse", "--show-toplevel"],
129 timeoutBehavior: "timedOutResult",
130 })
131 .pipe(Effect.option);
132 if (topLevelResult._tag === "None" || topLevelResult.value.code !== 0) {
133 return cacheKey;
134 }
135
136 const candidate = topLevelResult.value.stdout.trim();
137 if (candidate.length > 0) {
138 cacheKey = candidate;
139 }
140
141 return cacheKey;
142 },
143);
144
145const resolveRepositoryIdentityFromCacheKey = Effect.fn(
146 "RepositoryIdentityResolver.resolveFromCacheKey",
147)(function* (
148 cacheKey: string,
149 resolveDetectionUrl: (remoteUrl: string) => Effect.Effect<string>,
150): Effect.fn.Return<RepositoryIdentity | null, never, ProcessRunner.ProcessRunner> {
151 const processRunner = yield* ProcessRunner.ProcessRunner;
152 const remoteResult = yield* processRunner
153 .run({
154 command: "git",
155 args: ["-C", cacheKey, "remote", "-v"],
156 timeoutBehavior: "timedOutResult",
157 })
158 .pipe(Effect.option);
159 if (remoteResult._tag === "None" || remoteResult.value.code !== 0) {
160 return null;
161 }
162
163 const remote = pickPrimaryRemote(parseRemoteFetchUrls(remoteResult.value.stdout));
164 if (!remote) {
165 return null;
166 }
167
168 const detectionUrl = yield* resolveDetectionUrl(remote.remoteUrl);
169 return buildRepositoryIdentity({ ...remote, detectionUrl, rootPath: cacheKey });
170});
171
172export const make = Effect.fn("RepositoryIdentityResolver.make")(function* (
173 options: RepositoryIdentityResolverOptions = {},
174) {
175 const processRunner = yield* ProcessRunner.ProcessRunner;
176 const resolveDetectionUrl = (remoteUrl: string) =>
177 resolveGitRemoteForSourceControl(remoteUrl, resolveSshHostnameWithProcessRunner(processRunner));
178
179 const repositoryIdentityCache = yield* Cache.makeWith<string, RepositoryIdentity | null>(
180 (cacheKey) =>
181 resolveRepositoryIdentityFromCacheKey(cacheKey, resolveDetectionUrl).pipe(
182 Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
183 ),
184 {
185 capacity: options.cacheCapacity ?? DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY,
186 timeToLive: Exit.match({
187 onSuccess: (value) =>
188 value === null
189 ? (options.negativeCacheTtl ?? DEFAULT_NEGATIVE_CACHE_TTL)
190 : (options.positiveCacheTtl ?? DEFAULT_POSITIVE_CACHE_TTL),
191 onFailure: () => Duration.zero,
192 }),
193 },
194 );
195
196 const resolve: RepositoryIdentityResolver["Service"]["resolve"] = Effect.fn(
197 "RepositoryIdentityResolver.resolve",
198 )(function* (cwd) {
199 const cacheKey = yield* resolveRepositoryIdentityCacheKey(cwd).pipe(
200 Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
201 );
202 return yield* Cache.get(repositoryIdentityCache, cacheKey);
203 });
204
205 return RepositoryIdentityResolver.of({ resolve });
206});
207
208export const layer = Layer.effect(RepositoryIdentityResolver, make()).pipe(
209 Layer.provide(ProcessRunner.layer),
210);