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