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 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 { ServerConfig } from "../config.ts";
23import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
24import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
25const isSourceControlRepositoryError = Schema.is(SourceControlRepositoryError);
26
27export interface SourceControlRepositoryServiceShape {
28 readonly lookupRepository: (
29 input: SourceControlRepositoryLookupInput,
30 ) => Effect.Effect<SourceControlRepositoryInfo, SourceControlRepositoryError>;
31 readonly cloneRepository: (
32 input: SourceControlCloneRepositoryInput,
33 ) => Effect.Effect<SourceControlCloneRepositoryResult, SourceControlRepositoryError>;
34 readonly publishRepository: (
35 input: SourceControlPublishRepositoryInput,
36 ) => Effect.Effect<SourceControlPublishRepositoryResult, SourceControlRepositoryError>;
37}
38
39export class SourceControlRepositoryService extends Context.Service<
40 SourceControlRepositoryService,
41 SourceControlRepositoryServiceShape
42>()("t3/source-control/SourceControlRepositoryService") {}
43
44function detailFromUnknown(cause: unknown): string {
45 if (typeof cause === "object" && cause !== null) {
46 if ("detail" in cause && typeof cause.detail === "string" && cause.detail.length > 0) {
47 return cause.detail;
48 }
49 if ("message" in cause && typeof cause.message === "string" && cause.message.length > 0) {
50 return cause.message;
51 }
52 }
53
54 return "An unexpected source control error occurred.";
55}
56
57function repositoryError(input: {
58 readonly operation: string;
59 readonly provider: SourceControlProviderKind;
60 readonly detail: string;
61 readonly cause?: unknown;
62}): SourceControlRepositoryError {
63 return new SourceControlRepositoryError({
64 provider: input.provider,
65 operation: input.operation,
66 detail: input.detail,
67 ...(input.cause === undefined ? {} : { cause: input.cause }),
68 });
69}
70
71function mapRepositoryError(operation: string, provider: SourceControlProviderKind) {
72 return Effect.mapError((cause: unknown) =>
73 isSourceControlRepositoryError(cause)
74 ? cause
75 : repositoryError({
76 operation,
77 provider,
78 detail: detailFromUnknown(cause),
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.fn("makeSourceControlRepositoryService")(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 repositoryError({
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* repositoryError({
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).pipe(Effect.orElseSucceed(() => false))) {
177 const entries = yield* fileSystem
178 .readDirectory(normalizedDestination, { recursive: false })
179 .pipe(
180 Effect.mapError((cause) =>
181 repositoryError({
182 operation: "cloneRepository",
183 provider: "unknown",
184 detail: "Destination path already exists and is not a directory.",
185 cause,
186 }),
187 ),
188 );
189 if (entries.length > 0) {
190 return yield* repositoryError({
191 operation: "cloneRepository",
192 provider: "unknown",
193 detail: "Destination path already exists and is not empty.",
194 });
195 }
196 } else {
197 yield* fileSystem.makeDirectory(path.dirname(normalizedDestination), { recursive: true });
198 }
199
200 return {
201 destinationPath: normalizedDestination,
202 parentPath: path.dirname(normalizedDestination),
203 directoryName: path.basename(normalizedDestination),
204 };
205 },
206 );
207
208 const cloneRepository = Effect.fn("SourceControlRepositoryService.cloneRepository")(function* (
209 input: SourceControlCloneRepositoryInput,
210 ) {
211 const preparedDestination = yield* prepareDestination(input.destinationPath);
212 let repository: SourceControlRepositoryInfo | null = null;
213 let remoteUrl = input.remoteUrl?.trim() ?? null;
214 let provider: SourceControlProviderKind = input.provider ?? "unknown";
215
216 if (input.provider && input.repository) {
217 repository = yield* lookupRepository({
218 provider: input.provider,
219 repository: input.repository,
220 cwd: preparedDestination.parentPath,
221 });
222 remoteUrl = selectRemoteUrl(repository, input.protocol);
223 provider = input.provider;
224 }
225
226 if (!remoteUrl) {
227 return yield* repositoryError({
228 operation: "cloneRepository",
229 provider,
230 detail: "Enter a repository path or clone URL before cloning.",
231 });
232 }
233
234 yield* git.execute({
235 operation: "SourceControlRepositoryService.cloneRepository",
236 cwd: preparedDestination.parentPath,
237 args: ["clone", remoteUrl, preparedDestination.directoryName],
238 timeoutMs: 120_000,
239 maxOutputBytes: 256 * 1024,
240 });
241
242 return {
243 cwd: preparedDestination.destinationPath,
244 remoteUrl,
245 repository,
246 };
247 });
248
249 const publishRepository = Effect.fn("SourceControlRepositoryService.publishRepository")(
250 function* (input: SourceControlPublishRepositoryInput) {
251 const providerKind = yield* ensureConcreteProvider({
252 operation: "publishRepository",
253 provider: input.provider,
254 });
255 const provider = yield* providers.get(providerKind);
256 const urls = yield* provider.createRepository({
257 cwd: input.cwd,
258 repository: input.repository.trim(),
259 visibility: input.visibility,
260 });
261 const remoteUrl = selectRemoteUrl(urls, input.protocol);
262 const remoteName = yield* git.ensureRemote({
263 cwd: input.cwd,
264 preferredName: input.remoteName?.trim() || "origin",
265 url: remoteUrl,
266 });
267
268 // An empty local repo (no commits) would make `git push HEAD:...` fail
269 // with an opaque "src refspec HEAD does not match any". Treat this as a
270 // partial success: the remote was created and wired up, but there is
271 // nothing to push yet.
272 const hasCommits = yield* git
273 .execute({
274 operation: "SourceControlRepositoryService.publishRepository.headCheck",
275 cwd: input.cwd,
276 args: ["rev-parse", "--verify", "HEAD"],
277 })
278 .pipe(
279 Effect.map(() => true),
280 Effect.catch(() => Effect.succeed(false)),
281 );
282 if (!hasCommits) {
283 const details = yield* git
284 .statusDetails(input.cwd)
285 .pipe(Effect.catch(() => Effect.succeed(null)));
286 return {
287 repository: toRepositoryInfo(providerKind, urls),
288 remoteName,
289 remoteUrl,
290 branch: details?.branch ?? "main",
291 status: "remote_added" as const,
292 };
293 }
294
295 const pushResult = yield* git.pushCurrentBranch(input.cwd, null, { remoteName });
296
297 return {
298 repository: toRepositoryInfo(providerKind, urls),
299 remoteName,
300 remoteUrl,
301 branch: pushResult.branch,
302 ...(pushResult.upstreamBranch ? { upstreamBranch: pushResult.upstreamBranch } : {}),
303 status: "pushed" as const,
304 };
305 },
306 );
307
308 return SourceControlRepositoryService.of({
309 lookupRepository: (input) =>
310 lookupRepository(input).pipe(mapRepositoryError("lookupRepository", input.provider)),
311 cloneRepository: (input) =>
312 cloneRepository(input).pipe(
313 mapRepositoryError("cloneRepository", input.provider ?? "unknown"),
314 ),
315 publishRepository: (input) =>
316 publishRepository(input).pipe(mapRepositoryError("publishRepository", input.provider)),
317 });
318});
319
320export const layer = Layer.effect(SourceControlRepositoryService, make());