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