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

SourceControlRepositoryService.ts

281 lines9.6 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 SourceControlRepositoryError,
10 type SourceControlCloneRepositoryInput,
11 type SourceControlCloneRepositoryResult,
12 type SourceControlCloneProtocol,
13 type SourceControlProviderKind,
14 type SourceControlPublishRepositoryInput,
15 type SourceControlPublishRepositoryResult,
16 type SourceControlRepositoryCloneUrls,
17 type SourceControlRepositoryInfo,
18 type SourceControlRepositoryLookupInput,
19} from "@t3tools/contracts";
20​
21import { ServerConfig } from "../config.ts";
22import { expandHomePathWith } from "../pathExpansion.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 );
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 };
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 }
79​
80/** @public Service construction is part of the canonical Effect module API. */
81export const make = Effect.gen(function* () {
82 const config = yield* ServerConfig;
83 const fileSystem = yield* FileSystem.FileSystem;
84 const git = yield* GitVcsDriver.GitVcsDriver;
85 const path = yield* Path.Path;
86 const providers = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;
87​
88 const ensureConcreteProvider = (input: {
89 readonly operation: string;
90 readonly provider: SourceControlProviderKind;
91 }) => {
92 if (input.provider !== "unknown") {
93 return Effect.succeed(input.provider);
94 }
95​
96 return Effect.fail(
97 new SourceControlRepositoryError({
98 operation: input.operation,
99 provider: input.provider,
100 detail: "Choose a source control provider before continuing.",
101 }),
102 );
103 };
104​
105 const lookupRepository = Effect.fn("SourceControlRepositoryService.lookupRepository")(function* (
106 input: SourceControlRepositoryLookupInput,
107 ) {
108 const providerKind = yield* ensureConcreteProvider({
109 operation: "lookupRepository",
110 provider: input.provider,
111 });
112 const provider = yield* providers.get(providerKind);
113 const urls = yield* provider.getRepositoryCloneUrls({
114 cwd: input.cwd ?? config.cwd,
115 repository: input.repository.trim(),
116 });
117 return toRepositoryInfo(providerKind, urls);
118 });
119​
120 const normalizeDestinationPath = Effect.fn("SourceControlRepositoryService.normalizeDestination")(
121 function* (destinationPath: string) {
122 const trimmed = destinationPath.trim();
123 if (trimmed.length === 0) {
124 return yield* new SourceControlRepositoryError({
125 operation: "cloneRepository",
126 provider: "unknown",
127 detail: "Choose a destination path before cloning.",
128 });
129 }
130​
131 return path.resolve(expandHomePathWith(trimmed, path));
132 },
133 );
134​
135 const prepareDestination = Effect.fn("SourceControlRepositoryService.prepareDestination")(
136 function* (destinationPath: string) {
137 const normalizedDestination = yield* normalizeDestinationPath(destinationPath);
138 if (yield* fileSystem.exists(normalizedDestination)) {
139 const entries = yield* fileSystem
140 .readDirectory(normalizedDestination, { recursive: false })
141 .pipe(
142 Effect.mapError(
143 (cause) =>
144 new SourceControlRepositoryError({
145 operation: "cloneRepository",
146 provider: "unknown",
147 detail: "Destination path already exists and is not a directory.",
148 cause,
149 }),
150 ),
151 );
152 if (entries.length > 0) {
153 return yield* new SourceControlRepositoryError({
154 operation: "cloneRepository",
155 provider: "unknown",
156 detail: "Destination path already exists and is not empty.",
157 });
158 }
159 } else {
160 yield* fileSystem.makeDirectory(path.dirname(normalizedDestination), { recursive: true });
161 }
162​
163 return {
164 destinationPath: normalizedDestination,
165 parentPath: path.dirname(normalizedDestination),
166 directoryName: path.basename(normalizedDestination),
167 };
168 },
169 );
170​
171 const cloneRepository = Effect.fn("SourceControlRepositoryService.cloneRepository")(function* (
172 input: SourceControlCloneRepositoryInput,
173 ) {
174 const preparedDestination = yield* prepareDestination(input.destinationPath);
175 let repository: SourceControlRepositoryInfo | null = null;
176 let remoteUrl = input.remoteUrl?.trim() ?? null;
177 let provider: SourceControlProviderKind = input.provider ?? "unknown";
178​
179 if (input.provider && input.repository) {
180 repository = yield* lookupRepository({
181 provider: input.provider,
182 repository: input.repository,
183 cwd: preparedDestination.parentPath,
184 });
185 remoteUrl = selectRemoteUrl(repository, input.protocol);
186 provider = input.provider;
187 }
188​
189 if (!remoteUrl) {
190 return yield* new SourceControlRepositoryError({
191 operation: "cloneRepository",
192 provider,
193 detail: "Enter a repository path or clone URL before cloning.",
194 });
195 }
196​
197 yield* git.execute({
198 operation: "SourceControlRepositoryService.cloneRepository",
199 cwd: preparedDestination.parentPath,
200 args: ["clone", remoteUrl, preparedDestination.directoryName],
201 timeoutMs: 120_000,
202 maxOutputBytes: 256 * 1024,
203 });
204​
205 return {
206 cwd: preparedDestination.destinationPath,
207 remoteUrl,
208 repository,
209 };
210 });
211​
212 const publishRepository = Effect.fn("SourceControlRepositoryService.publishRepository")(
213 function* (input: SourceControlPublishRepositoryInput) {
214 const providerKind = yield* ensureConcreteProvider({
215 operation: "publishRepository",
216 provider: input.provider,
217 });
218 const provider = yield* providers.get(providerKind);
219 const urls = yield* provider.createRepository({
220 cwd: input.cwd,
221 repository: input.repository.trim(),
222 visibility: input.visibility,
223 });
224 const remoteUrl = selectRemoteUrl(urls, input.protocol);
225 const remoteName = yield* git.ensureRemote({
226 cwd: input.cwd,
227 preferredName: input.remoteName?.trim() || "origin",
228 url: remoteUrl,
229 });
230​
231 // An empty local repo (no commits) would make `git push HEAD:...` fail
232 // with an opaque "src refspec HEAD does not match any". Treat this as a
233 // partial success: the remote was created and wired up, but there is
234 // nothing to push yet.
235 const hasCommits = yield* git
236 .execute({
237 operation: "SourceControlRepositoryService.publishRepository.headCheck",
238 cwd: input.cwd,
239 args: ["rev-parse", "--verify", "HEAD"],
240 })
241 .pipe(
242 Effect.map(() => true),
243 Effect.orElseSucceed(() => false),
244 );
245 if (!hasCommits) {
246 const details = yield* git.statusDetails(input.cwd).pipe(Effect.orElseSucceed(() => null));
247 return {
248 repository: toRepositoryInfo(providerKind, urls),
249 remoteName,
250 remoteUrl,
251 branch: details?.branch ?? "main",
252 status: "remote_added" as const,
253 };
254 }
255​
256 const pushResult = yield* git.pushCurrentBranch(input.cwd, null, { remoteName });
257​
258 return {
259 repository: toRepositoryInfo(providerKind, urls),
260 remoteName,
261 remoteUrl,
262 branch: pushResult.branch,
263 ...(pushResult.upstreamBranch ? { upstreamBranch: pushResult.upstreamBranch } : {}),
264 status: "pushed" as const,
265 };
266 },
267 );
268​
269 return SourceControlRepositoryService.of({
270 lookupRepository: (input) =>
271 lookupRepository(input).pipe(mapRepositoryError("lookupRepository", input.provider)),
272 cloneRepository: (input) =>
273 cloneRepository(input).pipe(
274 mapRepositoryError("cloneRepository", input.provider ?? "unknown"),
275 ),
276 publishRepository: (input) =>
277 publishRepository(input).pipe(mapRepositoryError("publishRepository", input.provider)),
278 });
279});
280​
281export const layer = Layer.effect(SourceControlRepositoryService, make);