Repository navigation
Expand file tree
/
Copy pathRepositoryIdentityResolver.ts
More file actions
331 lines (304 loc) · 12.4 KB
/
Copy pathRepositoryIdentityResolver.ts
File metadata and controls
331 lines (304 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
import type { RepositoryIdentity, SourceControlProviderError } from "@t3tools/contracts";
import { repositoryPathFromRemoteUrl } from "@t3tools/source-control-core/server/SourceControlProvider";
import * as Cache from "effect/Cache";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as ProcessRunner from "../processRunner.ts";
import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
import { explicitBareRepositoryEnv } from "../vcs/VcsProcess.ts";
import * as HostProcess from "@t3tools/shared/HostProcess";
const DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY = 512;
// Minute-by-minute sweeps need cached hits; clone, publish and PR discovery force refresh.
const DEFAULT_POSITIVE_CACHE_TTL = Duration.minutes(15);
const DEFAULT_NEGATIVE_CACHE_TTL = Duration.minutes(1);
export interface RepositoryIdentityResolverOptions {
readonly cacheCapacity?: number;
readonly refine?: (
identity: RepositoryIdentity,
) => Effect.Effect<RepositoryIdentity, SourceControlProviderError>;
}
export class RepositoryIdentityResolver extends Context.Service<
RepositoryIdentityResolver,
{
readonly resolve: (
cwd: string,
options?: { readonly refresh?: boolean },
) => Effect.Effect<RepositoryIdentity | null>;
}
>()("t3/project/RepositoryIdentityResolver") {}
// Local paths such as GitButler's gb-local=. would give unrelated repos the same 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<string, string> {
const remotes = new Map<string, string>();
for (const line of stdout.split("\n")) {
const trimmed = line.trim();
if (trimmed.length === 0) continue;
// Partial clones append the promisor filter, e.g. `(fetch) [blob:none]`.
const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)(?:\s+\[[^\]]+\])?$/.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;
}
/** The remote `gh repo set-default` chose, when exactly one is marked. */
function parseGhDefaultRemote(stdout: string): string | null {
const marked = stdout
.split("\n")
.map((line) => /^remote\.(.+)\.gh-resolved\s+base$/.exec(line.trim())?.[1])
.filter((name) => name !== undefined);
return marked.length === 1 ? (marked[0] ?? null) : null;
}
function pickPrimaryRemote(
remotes: ReadonlyMap<string, string>,
ghDefaultRemote: string | null,
): { readonly remoteName: string; readonly remoteUrl: string } | null {
// Pull requests, `#123` and the PR list follow gh's choice; otherwise upstream outranks a fork.
for (const preferredRemoteName of [ghDefaultRemote, "upstream", "origin"]) {
if (preferredRemoteName === null) continue;
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 = sourceControlDefinitions.repositoryKeyFromRemote(originUrl);
if (originKey === canonicalKey) return undefined;
const displayName = repositoryPathOf(originKey, originUrl);
return { canonicalKey: originKey, remoteUrl: originUrl, ...(displayName ? { displayName } : {}) };
}
function buildRepositoryIdentity(input: {
readonly remoteName: string;
readonly remoteUrl: string;
readonly originUrl: string | undefined;
readonly rootPath: string;
}): RepositoryIdentity {
const canonicalKey = sourceControlDefinitions.repositoryKeyFromRemote(input.remoteUrl);
const sourceControlProvider = sourceControlDefinitions.recognizeRemote(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 } : {}),
};
}
class RepositoryIdentityCacheKey extends Data.Class<{
readonly rootPath: string;
readonly isBare: boolean;
}> {}
const resolveRepositoryIdentityCacheKey = Effect.fn("RepositoryIdentityResolver.resolveCacheKey")(
function* (cwd: string) {
const processRunner = yield* ProcessRunner.ProcessRunner;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const env = explicitBareRepositoryEnv(process.env, yield* HostProcess.Platform);
// `git -C` cannot enter a missing folder or a file, so every probe below would fail.
const isFolder = yield* fileSystem.stat(cwd).pipe(
Effect.map((info) => info.type === "Directory"),
Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed(false)),
Effect.orElseSucceed(() => true),
);
if (!isFolder) return null;
// git is always a real executable; cmd shell mode would split spaced paths on re-tokenization.
const topLevelResult = yield* processRunner
.run({
command: "git",
args: ["-C", cwd, "rev-parse", "--show-toplevel"],
env,
timeoutBehavior: "timedOutResult",
})
.pipe(Effect.option);
if (topLevelResult._tag === "None" || topLevelResult.value.timedOut) {
return null;
}
if (topLevelResult.value.code === 0) {
const rootPath = topLevelResult.value.stdout.trim();
return rootPath.length > 0
? new RepositoryIdentityCacheKey({ rootPath, isBare: false })
: null;
}
// Explicit Git directories preserve safe.bareRepository=explicit for both layouts.
for (const [gitDir, entry] of [
[".", "HEAD"],
[".git", ".git"],
] as const) {
// An explicit --git-dir fails unless the folder has this entry; a symlink counts even
// when its target is missing, as git reads a symlinked HEAD's target text.
const target = path.join(cwd, entry);
const hasEntry = yield* fileSystem.exists(target).pipe(
Effect.flatMap((exists) =>
exists
? Effect.succeed(true)
: fileSystem.readLink(target).pipe(
Effect.as(true),
Effect.orElseSucceed(() => false),
),
),
Effect.orElseSucceed(() => true),
);
if (!hasEntry) continue;
const bareResult = yield* processRunner
.run({
command: "git",
args: [
"-C",
cwd,
`--git-dir=${gitDir}`,
"rev-parse",
"--is-bare-repository",
"--absolute-git-dir",
],
env,
timeoutBehavior: "timedOutResult",
})
.pipe(Effect.option);
if (bareResult._tag === "None" || bareResult.value.timedOut) return null;
if (bareResult.value.code !== 0) continue;
const [isBare, rootPath = ""] = bareResult.value.stdout
.split("\n")
.map((line) => line.trim());
// A checkout's .git directory contains remotes but is not a project root.
return isBare === "true" && rootPath.length > 0
? new RepositoryIdentityCacheKey({ rootPath, isBare: true })
: null;
}
return null;
},
);
const resolveRepositoryIdentityFromCacheKey = Effect.fn(
"RepositoryIdentityResolver.resolveFromCacheKey",
)(function* (
cacheKey: RepositoryIdentityCacheKey,
): Effect.fn.Return<RepositoryIdentity | null, never, ProcessRunner.ProcessRunner> {
const processRunner = yield* ProcessRunner.ProcessRunner;
const env = explicitBareRepositoryEnv(process.env, yield* HostProcess.Platform);
const runGit = (args: ReadonlyArray<string>) =>
processRunner
.run({
command: "git",
args: ["-C", cacheKey.rootPath, ...(cacheKey.isBare ? ["--git-dir=."] : []), ...args],
env,
timeoutBehavior: "timedOutResult",
})
.pipe(Effect.option);
const [remoteResult, ghResolvedResult] = yield* Effect.all(
[runGit(["remote", "-v"]), runGit(["config", "--get-regexp", "^remote\\..*\\.gh-resolved$"])],
{ concurrency: 2 },
);
if (remoteResult._tag === "None" || remoteResult.value.code !== 0) {
return null;
}
const remotes = parseRemoteFetchUrls(remoteResult.value.stdout);
const remote = pickPrimaryRemote(
remotes,
ghResolvedResult._tag === "Some" && ghResolvedResult.value.code === 0
? parseGhDefaultRemote(ghResolvedResult.value.stdout)
: null,
);
return remote
? buildRepositoryIdentity({
...remote,
originUrl: remotes.get("origin"),
rootPath: cacheKey.rootPath,
})
: null;
});
export const make = Effect.fn("RepositoryIdentityResolver.make")(function* (
options: RepositoryIdentityResolverOptions = {},
) {
const processRunner = yield* ProcessRunner.ProcessRunner;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const cacheCapacity = options.cacheCapacity ?? DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY;
const refine = options.refine ?? Effect.succeed;
const timeToLive = (exit: Exit.Exit<unknown>) =>
Exit.match(exit, {
onSuccess: (value) =>
value === null ? DEFAULT_NEGATIVE_CACHE_TTL : DEFAULT_POSITIVE_CACHE_TTL,
onFailure: () => Duration.zero,
});
const repositoryRootCache = yield* Cache.makeWith<string, RepositoryIdentityCacheKey | null>(
(cwd) =>
resolveRepositoryIdentityCacheKey(cwd).pipe(
Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
),
{ capacity: cacheCapacity, timeToLive },
);
const repositoryIdentityCache = yield* Cache.makeWith<
RepositoryIdentityCacheKey,
RepositoryIdentity | null
>(
(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),
);