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

sync-reference-repos.ts

332 lines10.1 KB

1#!/usr/bin/env node
2​
3import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import * as Console from "effect/Console";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Option from "effect/Option";
9import * as Path from "effect/Path";
10import * as Schema from "effect/Schema";
11import * as Stream from "effect/Stream";
12import { Command, Flag } from "effect/unstable/cli";
13import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
14import { fromYaml } from "@v12/shared/schemaYaml";
15​
16import { referenceRepos, type ReferenceRepo } from "./lib/reference-repos.ts";
17​
18export type ReferenceRepoSyncAction = "add" | "pull";
19​
20export interface ReferenceRepoSyncOptions {
21 readonly rootDir?: string | undefined;
22 readonly repoId?: string | undefined;
23 readonly latest?: boolean | undefined;
24 readonly dryRun?: boolean | undefined;
26​
27export interface ReferenceRepoSyncPlan {
28 readonly repo: ReferenceRepo;
29 readonly action: ReferenceRepoSyncAction;
30 readonly ref: string;
31 readonly args: ReadonlyArray<string>;
33​
34export class ReferenceRepoSelectionError extends Schema.TaggedErrorClass<ReferenceRepoSelectionError>()(
35 "ReferenceRepoSelectionError",
36 {
37 repoId: Schema.String,
38 expectedRepoIds: Schema.Array(Schema.String),
39 },
40) {
41 override get message(): string {
42 return `Unknown reference repo "${this.repoId}". Expected one of: ${this.expectedRepoIds.join(", ")}.`;
43 }
45​
46export class ReferenceRepoVersionSourceError extends Schema.TaggedErrorClass<ReferenceRepoVersionSourceError>()(
47 "ReferenceRepoVersionSourceError",
48 {
49 operation: Schema.Literals(["read", "parse"]),
50 repoId: Schema.String,
51 sourcePath: Schema.String,
52 cause: Schema.Defect(),
53 },
54) {
55 override get message(): string {
56 return `Reference repo "${this.repoId}" version source operation "${this.operation}" failed for ${this.sourcePath}.`;
57 }
59​
60export class ReferenceRepoVersionResolutionError extends Schema.TaggedErrorClass<ReferenceRepoVersionResolutionError>()(
61 "ReferenceRepoVersionResolutionError",
62 {
63 repoId: Schema.String,
64 sourcePath: Schema.String,
65 packageVersionPath: Schema.Array(Schema.String),
66 },
67) {
68 override get message(): string {
69 return `No version was found for reference repo "${this.repoId}" at ${this.sourcePath}:${this.packageVersionPath.join(".")}.`;
70 }
72​
73export class ReferenceRepoGitSubtreeError extends Schema.TaggedErrorClass<ReferenceRepoGitSubtreeError>()(
74 "ReferenceRepoGitSubtreeError",
75 {
76 operation: Schema.Literals(["spawn", "communicate", "exit"]),
77 repoId: Schema.String,
78 action: Schema.Literals(["add", "pull"]),
79 repository: Schema.String,
80 ref: Schema.String,
81 rootDir: Schema.String,
82 argumentCount: Schema.Number,
83 exitCode: Schema.optional(Schema.Number),
84 stdoutLength: Schema.optional(Schema.Number),
85 stderrLength: Schema.optional(Schema.Number),
86 cause: Schema.optional(Schema.Defect()),
87 },
88) {
89 override get message(): string {
90 return `Git subtree ${this.action} for reference repo "${this.repoId}" failed during "${this.operation}".`;
91 }
93​
94export const ReferenceRepoSyncError = Schema.Union([
95 ReferenceRepoSelectionError,
96 ReferenceRepoVersionSourceError,
97 ReferenceRepoVersionResolutionError,
98 ReferenceRepoGitSubtreeError,
99]);
100export type ReferenceRepoSyncError = typeof ReferenceRepoSyncError.Type;
101export const isReferenceRepoSyncError = Schema.is(ReferenceRepoSyncError);
102​
103const decodeJsonSource = Schema.decodeUnknownEffect(Schema.UnknownFromJsonString);
104const decodeYamlSource = Schema.decodeEffect(fromYaml(Schema.Unknown));
105​
106const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
107 stream.pipe(
108 Stream.decodeText(),
109 Stream.runFold(
110 () => "",
111 (acc, chunk) => acc + chunk,
112 ),
113 );
114​
115function readNestedString(input: unknown, keys: ReadonlyArray<string>): string | undefined {
116 let value = input;
117 for (const key of keys) {
118 if (typeof value !== "object" || value === null || !(key in value)) {
119 return undefined;
120 }
121 value = (value as Record<string, unknown>)[key];
122 }
123 return typeof value === "string" && value.length > 0 ? value : undefined;
125​
126function decodeVersionSource(
127 repo: ReferenceRepo,
128 sourcePath: string,
129 content: string,
130): Effect.Effect<unknown, ReferenceRepoSyncError> {
131 const decode =
132 repo.versionSourcePath.endsWith(".yaml") || repo.versionSourcePath.endsWith(".yml")
133 ? decodeYamlSource
134 : decodeJsonSource;
135 return decode(content).pipe(
136 Effect.mapError(
137 (cause) =>
138 new ReferenceRepoVersionSourceError({
139 operation: "parse",
140 repoId: repo.id,
141 sourcePath,
142 cause,
143 }),
144 ),
145 );
147​
148function getSelectedRepos(
149 repoId: string | undefined,
150): Effect.Effect<ReadonlyArray<ReferenceRepo>, ReferenceRepoSyncError> {
151 if (!repoId) {
152 return Effect.succeed(referenceRepos);
153 }
154​
155 const repo = referenceRepos.find((candidate) => candidate.id === repoId);
156 return repo
157 ? Effect.succeed([repo])
158 : Effect.fail(
159 new ReferenceRepoSelectionError({
160 repoId,
161 expectedRepoIds: referenceRepos.map((candidate) => candidate.id),
162 }),
163 );
165​
166export const resolveReferenceRepoRef = Effect.fn("resolveReferenceRepoRef")(function* (
167 repo: ReferenceRepo,
168 rootDir: string,
169 latest: boolean,
170) {
171 if (latest) {
172 return repo.latestRef;
173 }
174​
175 const fs = yield* FileSystem.FileSystem;
176 const path = yield* Path.Path;
177 const versionSourcePath = path.join(rootDir, repo.versionSourcePath);
178 const versionSourceContent = yield* fs.readFileString(versionSourcePath).pipe(
179 Effect.mapError(
180 (cause) =>
181 new ReferenceRepoVersionSourceError({
182 operation: "read",
183 repoId: repo.id,
184 sourcePath: versionSourcePath,
185 cause,
186 }),
187 ),
188 );
189 const versionSource = yield* decodeVersionSource(repo, versionSourcePath, versionSourceContent);
190 const version = readNestedString(versionSource, repo.packageVersionPath);
191​
192 if (!version) {
193 return yield* new ReferenceRepoVersionResolutionError({
194 repoId: repo.id,
195 sourcePath: versionSourcePath,
196 packageVersionPath: repo.packageVersionPath,
197 });
198 }
199​
200 return `${repo.versionTagPrefix}${version}`;
201});
202​
203export const planReferenceRepoSync = Effect.fn("planReferenceRepoSync")(function* (
204 repo: ReferenceRepo,
205 rootDir: string,
206 latest: boolean,
207) {
208 const fs = yield* FileSystem.FileSystem;
209 const path = yield* Path.Path;
210 const action: ReferenceRepoSyncAction = (yield* fs.exists(path.join(rootDir, repo.prefix)))
211 ? "pull"
212 : "add";
213 const ref = yield* resolveReferenceRepoRef(repo, rootDir, latest);
214​
215 return {
216 repo,
217 action,
218 ref,
219 args: ["subtree", action, `--prefix=${repo.prefix}`, repo.repository, ref, "--squash"],
220 } satisfies ReferenceRepoSyncPlan;
221});
222​
223const runGit = Effect.fn("runGit")(function* (rootDir: string, plan: ReferenceRepoSyncPlan) {
224 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
225 const errorContext = {
226 repoId: plan.repo.id,
227 action: plan.action,
228 repository: plan.repo.repository,
229 ref: plan.ref,
230 rootDir,
231 argumentCount: plan.args.length,
232 } as const;
233 const child = yield* spawner.spawn(ChildProcess.make("git", plan.args, { cwd: rootDir })).pipe(
234 Effect.mapError(
235 (cause) =>
236 new ReferenceRepoGitSubtreeError({
237 ...errorContext,
238 operation: "spawn",
239 cause,
240 }),
241 ),
242 );
243 const [stdout, stderr, exitCode] = yield* Effect.all(
244 [
245 collectStreamAsString(child.stdout),
246 collectStreamAsString(child.stderr),
247 child.exitCode.pipe(Effect.map(Number)),
248 ],
249 { concurrency: "unbounded" },
250 ).pipe(
251 Effect.mapError(
252 (cause) =>
253 new ReferenceRepoGitSubtreeError({
254 ...errorContext,
255 operation: "communicate",
256 cause,
257 }),
258 ),
259 );
260​
261 if (exitCode !== 0) {
262 return yield* new ReferenceRepoGitSubtreeError({
263 ...errorContext,
264 operation: "exit",
265 exitCode,
266 stdoutLength: stdout.length,
267 stderrLength: stderr.length,
268 });
269 }
270​
271 if (stdout.trim().length > 0) {
272 yield* Console.log(stdout.trim());
273 }
274});
275​
276export const syncReferenceRepos = Effect.fn("syncReferenceRepos")(function* (
277 options: ReferenceRepoSyncOptions = {},
278) {
279 const path = yield* Path.Path;
280 const rootDir = path.resolve(options.rootDir ?? process.cwd());
281 const repos = yield* getSelectedRepos(options.repoId);
282 const plans: Array<ReferenceRepoSyncPlan> = [];
283​
284 for (const repo of repos) {
285 const plan = yield* planReferenceRepoSync(repo, rootDir, options.latest ?? false);
286 plans.push(plan);
287 yield* Console.log(`Syncing ${repo.id} from ${plan.ref} with git subtree ${plan.action}.`);
288 if (!(options.dryRun ?? false)) {
289 yield* runGit(rootDir, plan).pipe(Effect.scoped);
290 }
291 }
292​
293 return plans;
294});
295​
296export const syncReferenceReposCommand = Command.make(
297 "sync-reference-repos",
298 {
299 repo: Flag.string("repo").pipe(
300 Flag.withDescription("Sync only the named reference repo. Defaults to all configured repos."),
301 Flag.optional,
302 ),
303 latest: Flag.boolean("latest").pipe(
304 Flag.withDescription(
305 "Sync each repo from its latest branch instead of the installed version.",
306 ),
307 Flag.withDefault(false),
308 ),
309 root: Flag.string("root").pipe(
310 Flag.withDescription("Workspace root used to resolve versions and subtree prefixes."),
311 Flag.optional,
312 ),
313 dryRun: Flag.boolean("dry-run").pipe(
314 Flag.withDescription("Print planned subtree operations without running git."),
315 Flag.withDefault(false),
316 ),
317 },
318 ({ repo, latest, root, dryRun }) =>
319 syncReferenceRepos({
320 repoId: Option.getOrUndefined(repo),
321 rootDir: Option.getOrUndefined(root),
322 latest,
323 dryRun,
324 }),
325).pipe(Command.withDescription("Sync vendored reference repositories under .repos/."));
326​
327if (import.meta.main) {
328 Command.run(syncReferenceReposCommand, { version: "0.0.0" }).pipe(
329 Effect.provide(NodeServices.layer),
330 NodeRuntime.runMain,
331 );