Open History to see the last commit
1import type { RepositoryIdentity } from "@t3tools/contracts";
2import { Cache, Duration, Effect, Exit, Layer } from "effect";
3import { detectGitHostingProviderFromRemoteUrl, normalizeGitRemoteUrl } from "@t3tools/shared/git";
4
5import { runProcess } from "../../processRunner.ts";
6import {
7 RepositoryIdentityResolver,
8 type RepositoryIdentityResolverShape,
9} from "../Services/RepositoryIdentityResolver.ts";
10
11function parseRemoteFetchUrls(stdout: string): Map<string, string> {
12 const remotes = new Map<string, string>();
13 for (const line of stdout.split("\n")) {
14 const trimmed = line.trim();
15 if (trimmed.length === 0) continue;
16 const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)$/.exec(trimmed);
17 if (!match) continue;
18 const [, remoteName = "", remoteUrl = "", direction = ""] = match;
19 if (direction !== "fetch" || remoteName.length === 0 || remoteUrl.length === 0) {
20 continue;
21 }
22 remotes.set(remoteName, remoteUrl);
23 }
24 return remotes;
25}
26
27function pickPrimaryRemote(
28 remotes: ReadonlyMap<string, string>,
29): { readonly remoteName: string; readonly remoteUrl: string } | null {
30 for (const preferredRemoteName of ["upstream", "origin"] as const) {
31 const remoteUrl = remotes.get(preferredRemoteName);
32 if (remoteUrl) {
33 return { remoteName: preferredRemoteName, remoteUrl };
34 }
35 }
36
37 const [remoteName, remoteUrl] =
38 [...remotes.entries()].toSorted(([left], [right]) => left.localeCompare(right))[0] ?? [];
39 return remoteName && remoteUrl ? { remoteName, remoteUrl } : null;
40}
41
42function buildRepositoryIdentity(input: {
43 readonly remoteName: string;
44 readonly remoteUrl: string;
45 readonly rootPath: string;
46}): RepositoryIdentity {
47 const canonicalKey = normalizeGitRemoteUrl(input.remoteUrl);
48 const hostingProvider = detectGitHostingProviderFromRemoteUrl(input.remoteUrl);
49 const repositoryPath = canonicalKey.split("/").slice(1).join("/");
50 const repositoryPathSegments = repositoryPath.split("/").filter((segment) => segment.length > 0);
51 const [owner] = repositoryPathSegments;
52 const repositoryName = repositoryPathSegments.at(-1);
53
54 return {
55 canonicalKey,
56 locator: {
57 source: "git-remote",
58 remoteName: input.remoteName,
59 remoteUrl: input.remoteUrl,
60 },
61 rootPath: input.rootPath,
62 ...(repositoryPath ? { displayName: repositoryPath } : {}),
63 ...(hostingProvider ? { provider: hostingProvider.kind } : {}),
64 ...(owner ? { owner } : {}),
65 ...(repositoryName ? { name: repositoryName } : {}),
66 };
67}
68
69const DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY = 512;
70const DEFAULT_POSITIVE_CACHE_TTL = Duration.minutes(1);
71const DEFAULT_NEGATIVE_CACHE_TTL = Duration.minutes(1);
72
73interface RepositoryIdentityResolverOptions {
74 readonly cacheCapacity?: number;
75 readonly positiveCacheTtl?: Duration.Input;
76 readonly negativeCacheTtl?: Duration.Input;
77}
78
79async function resolveRepositoryIdentityCacheKey(cwd: string): Promise<string> {
80 let cacheKey = cwd;
81
82 try {
83 const topLevelResult = await runProcess("git", ["-C", cwd, "rev-parse", "--show-toplevel"], {
84 allowNonZeroExit: true,
85 });
86 if (topLevelResult.code !== 0) {
87 return cacheKey;
88 }
89
90 const candidate = topLevelResult.stdout.trim();
91 if (candidate.length > 0) {
92 cacheKey = candidate;
93 }
94 } catch {
95 return cacheKey;
96 }
97
98 return cacheKey;
99}
100
101async function resolveRepositoryIdentityFromCacheKey(
102 cacheKey: string,
103): Promise<RepositoryIdentity | null> {
104 try {
105 const remoteResult = await runProcess("git", ["-C", cacheKey, "remote", "-v"], {
106 allowNonZeroExit: true,
107 });
108 if (remoteResult.code !== 0) {
109 return null;
110 }
111
112 const remote = pickPrimaryRemote(parseRemoteFetchUrls(remoteResult.stdout));
113 return remote ? buildRepositoryIdentity({ ...remote, rootPath: cacheKey }) : null;
114 } catch {
115 return null;
116 }
117}
118
119export const makeRepositoryIdentityResolver = Effect.fn("makeRepositoryIdentityResolver")(
120 function* (options: RepositoryIdentityResolverOptions = {}) {
121 const repositoryIdentityCache = yield* Cache.makeWith<string, RepositoryIdentity | null>(
122 (cacheKey) => Effect.promise(() => resolveRepositoryIdentityFromCacheKey(cacheKey)),
123 {
124 capacity: options.cacheCapacity ?? DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY,
125 timeToLive: Exit.match({
126 onSuccess: (value) =>
127 value === null
128 ? (options.negativeCacheTtl ?? DEFAULT_NEGATIVE_CACHE_TTL)
129 : (options.positiveCacheTtl ?? DEFAULT_POSITIVE_CACHE_TTL),
130 onFailure: () => Duration.zero,
131 }),
132 },
133 );
134
135 const resolve: RepositoryIdentityResolverShape["resolve"] = Effect.fn(
136 "RepositoryIdentityResolver.resolve",
137 )(function* (cwd) {
138 const cacheKey = yield* Effect.promise(() => resolveRepositoryIdentityCacheKey(cwd));
139 return yield* Cache.get(repositoryIdentityCache, cacheKey);
140 });
141
142 return {
143 resolve,
144 } satisfies RepositoryIdentityResolverShape;
145 },
146);
147
148export const RepositoryIdentityResolverLive = Layer.effect(
149 RepositoryIdentityResolver,
150 makeRepositoryIdentityResolver(),
151);