Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SourceControlRepositoryService.ts

348 lines12.5 KB

1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Layer from "effect/Layer";
5import * as Path from "effect/Path";
6import * as Schema from "effect/Schema";
7​
8import {
9 GitCommandError,
10 SourceControlRepositoryError,
11 type SourceControlCloneRepositoryInput,
12 type SourceControlCloneRepositoryResult,
13 type SourceControlCloneProtocol,
14 type SourceControlProviderKind,
15 type SourceControlPublishRepositoryInput,
16 type SourceControlPublishRepositoryResult,
17 type SourceControlRepositoryCloneUrls,
18 type SourceControlRepositoryInfo,
19 type SourceControlRepositoryLookupInput,
20} from "@t3tools/contracts";
21​
22import {
23 detectSourceControlProviderFromRemoteUrl,
24 isSshRemoteUrl,
25} from "@t3tools/shared/sourceControl";
26​
27import { ServerConfig } from "../config.ts";
28import { expandHomePathWith } from "../pathExpansion.ts";
29import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
30import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
31const isSourceControlRepositoryError = Schema.is(SourceControlRepositoryError);
32​
33function cloneFailureDetail(stderr: string, remoteUrl?: string | null): string {
34 if (/host key verification failed/iu.test(stderr)) {
35 return "SSH could not verify the source control host. Add its host key to known_hosts and try again.";
36 }
37 if (
38 /permission denied \(publickey(?:,[^)]+)?\)|public key authentication failed/iu.test(stderr)
39 ) {
40 return "SSH authentication failed. Add an SSH key to your source control account and try again.";
41 }
42 if (
43 /http basic: access denied|could not read username|terminal prompts disabled/iu.test(stderr)
44 ) {
45 return "HTTPS authentication failed. Configure Git credentials for the source control host and try again.";
46 }
47 if (/authentication failed/iu.test(stderr)) {
48 if (remoteUrl && isSshRemoteUrl(remoteUrl)) {
49 return "SSH authentication failed. Add an SSH key to your source control account and try again.";
50 }
51 if (remoteUrl && /^https?:\/\//iu.test(remoteUrl)) {
52 return "HTTPS authentication failed. Configure Git credentials for the source control host and try again.";
53 }
54 return "Git authentication failed. Check the credentials configured for this remote and try again.";
55 }
56 if (/could not resolve (?:host|hostname)/iu.test(stderr)) {
57 return "The source control host could not be resolved. Check your network or VPN connection and try again.";
58 }
59 if (/connection (?:timed out|refused)|operation timed out|failed to connect/iu.test(stderr)) {
60 return "Git could not connect to the source control host. Check your network or VPN connection and try again.";
61 }
62 if (/repository not found|could not read from remote repository/iu.test(stderr)) {
63 return "The repository could not be read. Check that it exists and that your Git credentials have access.";
64 }
65​
66 return "Git could not clone the repository. Verify that the remote works in a terminal and try again.";
68​
69export class SourceControlRepositoryService extends Context.Service<
70 SourceControlRepositoryService,
71 {
72 readonly lookupRepository: (
73 input: SourceControlRepositoryLookupInput,
74 ) => Effect.Effect<SourceControlRepositoryInfo, SourceControlRepositoryError>;
75 readonly cloneRepository: (
76 input: SourceControlCloneRepositoryInput,
77 ) => Effect.Effect<SourceControlCloneRepositoryResult, SourceControlRepositoryError>;
78 readonly publishRepository: (
79 input: SourceControlPublishRepositoryInput,
80 ) => Effect.Effect<SourceControlPublishRepositoryResult, SourceControlRepositoryError>;
81 }
82>()("t3/sourceControl/SourceControlRepositoryService") {}
83​
84function mapRepositoryError(operation: string, provider: SourceControlProviderKind) {
85 return Effect.mapError((cause: unknown) =>
86 isSourceControlRepositoryError(cause)
87 ? cause
88 : new SourceControlRepositoryError({
89 operation,
90 provider,
91 detail: "The source control operation could not be completed.",
92 cause,
93 }),
94 );
96​
97function toRepositoryInfo(
98 provider: SourceControlProviderKind,
99 urls: SourceControlRepositoryCloneUrls,
100): SourceControlRepositoryInfo {
101 return {
102 provider,
103 nameWithOwner: urls.nameWithOwner,
104 url: urls.url,
105 sshUrl: urls.sshUrl,
106 };
108​
109function selectRemoteUrl(
110 urls: SourceControlRepositoryCloneUrls,
111 protocol: SourceControlCloneProtocol | undefined,
112): string {
113 switch (protocol ?? "auto") {
114 case "https":
115 return urls.url;
116 case "ssh":
117 case "auto":
118 return urls.sshUrl;
119 }
121​
122/** @public Service construction is part of the canonical Effect module API. */
123export const make = Effect.gen(function* () {
124 const config = yield* ServerConfig;
125 const fileSystem = yield* FileSystem.FileSystem;
126 const git = yield* GitVcsDriver.GitVcsDriver;
127 const path = yield* Path.Path;
128 const providers = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;
129​
130 const ensureConcreteProvider = (input: {
131 readonly operation: string;
132 readonly provider: SourceControlProviderKind;
133 }) => {
134 if (input.provider !== "unknown") {
135 return Effect.succeed(input.provider);
136 }
137​
138 return Effect.fail(
139 new SourceControlRepositoryError({
140 operation: input.operation,
141 provider: input.provider,
142 detail: "Choose a source control provider before continuing.",
143 }),
144 );
145 };
146​
147 const lookupRepository = Effect.fn("SourceControlRepositoryService.lookupRepository")(function* (
148 input: SourceControlRepositoryLookupInput,
149 ) {
150 const providerKind = yield* ensureConcreteProvider({
151 operation: "lookupRepository",
152 provider: input.provider,
153 });
154 const provider = yield* providers.get(providerKind);
155 const urls = yield* provider.getRepositoryCloneUrls({
156 cwd: input.cwd ?? config.cwd,
157 repository: input.repository.trim(),
158 });
159 return toRepositoryInfo(providerKind, urls);
160 });
161​
162 const normalizeDestinationPath = Effect.fn("SourceControlRepositoryService.normalizeDestination")(
163 function* (destinationPath: string, provider: SourceControlProviderKind) {
164 const trimmed = destinationPath.trim();
165 if (trimmed.length === 0) {
166 return yield* new SourceControlRepositoryError({
167 operation: "cloneRepository",
168 provider,
169 detail: "Choose a destination path before cloning.",
170 });
171 }
172​
173 return path.resolve(expandHomePathWith(trimmed, path));
174 },
175 );
176​
177 const prepareDestination = Effect.fn("SourceControlRepositoryService.prepareDestination")(
178 function* (destinationPath: string, provider: SourceControlProviderKind) {
179 const normalizedDestination = yield* normalizeDestinationPath(destinationPath, provider);
180 if (yield* fileSystem.exists(normalizedDestination)) {
181 const entries = yield* fileSystem
182 .readDirectory(normalizedDestination, { recursive: false })
183 .pipe(
184 Effect.mapError(
185 (cause) =>
186 new SourceControlRepositoryError({
187 operation: "cloneRepository",
188 provider,
189 detail: "Destination path already exists and is not a directory.",
190 cause,
191 }),
192 ),
193 );
194 if (entries.length > 0) {
195 return yield* new SourceControlRepositoryError({
196 operation: "cloneRepository",
197 provider,
198 detail: "Destination path already exists and is not empty.",
199 });
200 }
201 } else {
202 yield* fileSystem.makeDirectory(path.dirname(normalizedDestination), { recursive: true });
203 }
204​
205 return {
206 destinationPath: normalizedDestination,
207 parentPath: path.dirname(normalizedDestination),
208 directoryName: path.basename(normalizedDestination),
209 };
210 },
211 );
212​
213 const cloneRepository = Effect.fn("SourceControlRepositoryService.cloneRepository")(function* (
214 input: SourceControlCloneRepositoryInput,
215 ) {
216 let repository: SourceControlRepositoryInfo | null = null;
217 let remoteUrl = input.remoteUrl?.trim() ?? null;
218 let provider: SourceControlProviderKind =
219 input.provider ??
220 (remoteUrl ? detectSourceControlProviderFromRemoteUrl(remoteUrl)?.kind : null) ??
221 "unknown";
222 const preparedDestination = yield* prepareDestination(input.destinationPath, provider).pipe(
223 mapRepositoryError("cloneRepository", provider),
224 );
225​
226 if (input.provider && input.repository) {
227 repository = yield* lookupRepository({
228 provider: input.provider,
229 repository: input.repository,
230 cwd: preparedDestination.parentPath,
231 });
232 remoteUrl = selectRemoteUrl(repository, input.protocol);
233 provider = input.provider;
234 }
235​
236 if (!remoteUrl) {
237 return yield* new SourceControlRepositoryError({
238 operation: "cloneRepository",
239 provider,
240 detail: "Enter a repository path or clone URL before cloning.",
241 });
242 }
243​
244 const cloneResult = yield* git.execute({
245 operation: "SourceControlRepositoryService.cloneRepository",
246 cwd: preparedDestination.parentPath,
247 args: ["clone", remoteUrl, preparedDestination.directoryName],
248 allowNonZeroExit: true,
249 timeoutMs: 120_000,
250 maxOutputBytes: 256 * 1024,
251 });
252​
253 if (cloneResult.exitCode !== 0) {
254 const detail = cloneFailureDetail(cloneResult.stderr, remoteUrl);
255 return yield* new SourceControlRepositoryError({
256 operation: "cloneRepository",
257 provider,
258 detail,
259 cause: new GitCommandError({
260 operation: "SourceControlRepositoryService.cloneRepository",
261 command: "git",
262 cwd: preparedDestination.parentPath,
263 argumentCount: 3,
264 exitCode: cloneResult.exitCode,
265 stdoutLength: cloneResult.stdout.length,
266 stderrLength: cloneResult.stderr.length,
267 detail: "git clone exited with a non-zero status.",
268 }),
269 });
270 }
271​
272 return {
273 cwd: preparedDestination.destinationPath,
274 remoteUrl,
275 repository,
276 };
277 });
278​
279 const publishRepository = Effect.fn("SourceControlRepositoryService.publishRepository")(
280 function* (input: SourceControlPublishRepositoryInput) {
281 const providerKind = yield* ensureConcreteProvider({
282 operation: "publishRepository",
283 provider: input.provider,
284 });
285 const provider = yield* providers.get(providerKind);
286 const urls = yield* provider.createRepository({
287 cwd: input.cwd,
288 repository: input.repository.trim(),
289 visibility: input.visibility,
290 });
291 const remoteUrl = selectRemoteUrl(urls, input.protocol);
292 const remoteName = yield* git.ensureRemote({
293 cwd: input.cwd,
294 preferredName: input.remoteName?.trim() || "origin",
295 url: remoteUrl,
296 });
297​
298 // An empty local repo (no commits) would make `git push HEAD:...` fail
299 // with an opaque "src refspec HEAD does not match any". Treat this as a
300 // partial success: the remote was created and wired up, but there is
301 // nothing to push yet.
302 const hasCommits = yield* git
303 .execute({
304 operation: "SourceControlRepositoryService.publishRepository.headCheck",
305 cwd: input.cwd,
306 args: ["rev-parse", "--verify", "HEAD"],
307 })
308 .pipe(
309 Effect.map(() => true),
310 Effect.orElseSucceed(() => false),
311 );
312 if (!hasCommits) {
313 const details = yield* git.statusDetails(input.cwd).pipe(Effect.orElseSucceed(() => null));
314 return {
315 repository: toRepositoryInfo(providerKind, urls),
316 remoteName,
317 remoteUrl,
318 branch: details?.branch ?? "main",
319 status: "remote_added" as const,
320 };
321 }
322​
323 const pushResult = yield* git.pushCurrentBranch(input.cwd, null, { remoteName });
324​
325 return {
326 repository: toRepositoryInfo(providerKind, urls),
327 remoteName,
328 remoteUrl,
329 branch: pushResult.branch,
330 ...(pushResult.upstreamBranch ? { upstreamBranch: pushResult.upstreamBranch } : {}),
331 status: "pushed" as const,
332 };
333 },
334 );
335​
336 return SourceControlRepositoryService.of({
337 lookupRepository: (input) =>
338 lookupRepository(input).pipe(mapRepositoryError("lookupRepository", input.provider)),
339 cloneRepository: (input) =>
340 cloneRepository(input).pipe(
341 mapRepositoryError("cloneRepository", input.provider ?? "unknown"),
342 ),
343 publishRepository: (input) =>
344 publishRepository(input).pipe(mapRepositoryError("publishRepository", input.provider)),
345 });
346});
347​
348export const layer = Layer.effect(SourceControlRepositoryService, make);