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