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