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