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

sync-reference-repos.ts

230 lines7.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 Data from "effect/Data";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Option from "effect/Option";
10import * as Path from "effect/Path";
11import * as Schema from "effect/Schema";
12import * as Stream from "effect/Stream";
13import { Command, Flag } from "effect/unstable/cli";
14import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
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 ReferenceRepoSyncError extends Data.TaggedError("ReferenceRepoSyncError")<{
35 readonly message: string;
36 readonly cause?: unknown;
37}> {}
38​
39const decodePackageJson = Schema.decodeUnknownEffect(Schema.UnknownFromJsonString);
40​
41const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
42 stream.pipe(
43 Stream.decodeText(),
44 Stream.runFold(
45 () => "",
46 (acc, chunk) => acc + chunk,
47 ),
48 );
49​
50function readNestedString(input: unknown, keys: ReadonlyArray<string>): string | undefined {
51 let value = input;
52 for (const key of keys) {
53 if (typeof value !== "object" || value === null || !(key in value)) {
54 return undefined;
55 }
56 value = (value as Record<string, unknown>)[key];
57 }
58 return typeof value === "string" && value.length > 0 ? value : undefined;
60​
61function getSelectedRepos(
62 repoId: string | undefined,
63): Effect.Effect<ReadonlyArray<ReferenceRepo>, ReferenceRepoSyncError> {
64 if (!repoId) {
65 return Effect.succeed(referenceRepos);
66 }
67​
68 const repo = referenceRepos.find((candidate) => candidate.id === repoId);
69 return repo
70 ? Effect.succeed([repo])
71 : Effect.fail(
72 new ReferenceRepoSyncError({
73 message: `Unknown reference repo '${repoId}'. Expected one of: ${referenceRepos
74 .map((candidate) => candidate.id)
75 .join(", ")}.`,
76 }),
77 );
79​
80export const resolveReferenceRepoRef = Effect.fn("resolveReferenceRepoRef")(function* (
81 repo: ReferenceRepo,
82 rootDir: string,
83 latest: boolean,
84) {
85 if (latest) {
86 return repo.latestRef;
87 }
88​
89 const fs = yield* FileSystem.FileSystem;
90 const path = yield* Path.Path;
91 const packageJsonPath = path.join(rootDir, repo.packageJsonPath);
92 const packageJson = yield* fs.readFileString(packageJsonPath).pipe(
93 Effect.flatMap(decodePackageJson),
94 Effect.mapError(
95 (cause) =>
96 new ReferenceRepoSyncError({
97 message: `Unable to read package version for '${repo.id}' from ${packageJsonPath}.`,
98 cause,
99 }),
100 ),
101 );
102 const version = readNestedString(packageJson, repo.packageVersionPath);
103​
104 if (!version) {
105 return yield* new ReferenceRepoSyncError({
106 message: `Unable to resolve package version for '${repo.id}' at ${repo.packageJsonPath}:${repo.packageVersionPath.join(
107 ".",
108 )}.`,
109 });
110 }
111​
112 return `${repo.versionTagPrefix}${version}`;
113});
114​
115export const planReferenceRepoSync = Effect.fn("planReferenceRepoSync")(function* (
116 repo: ReferenceRepo,
117 rootDir: string,
118 latest: boolean,
119) {
120 const fs = yield* FileSystem.FileSystem;
121 const path = yield* Path.Path;
122 const action: ReferenceRepoSyncAction = (yield* fs.exists(path.join(rootDir, repo.prefix)))
123 ? "pull"
124 : "add";
125 const ref = yield* resolveReferenceRepoRef(repo, rootDir, latest);
126​
127 return {
128 repo,
129 action,
130 ref,
131 args: ["subtree", action, `--prefix=${repo.prefix}`, repo.repository, ref, "--squash"],
132 } satisfies ReferenceRepoSyncPlan;
133});
134​
135const runGit = Effect.fn("runGit")(function* (rootDir: string, plan: ReferenceRepoSyncPlan) {
136 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
137 const child = yield* spawner.spawn(ChildProcess.make("git", plan.args, { cwd: rootDir })).pipe(
138 Effect.mapError(
139 (cause) =>
140 new ReferenceRepoSyncError({
141 message: `Unable to start git subtree ${plan.action} for '${plan.repo.id}'.`,
142 cause,
143 }),
144 ),
145 );
146 const [stdout, stderr, exitCode] = yield* Effect.all(
147 [
148 collectStreamAsString(child.stdout),
149 collectStreamAsString(child.stderr),
150 child.exitCode.pipe(Effect.map(Number)),
151 ],
152 { concurrency: "unbounded" },
153 ).pipe(
154 Effect.mapError(
155 (cause) =>
156 new ReferenceRepoSyncError({
157 message: `Unable to run git subtree ${plan.action} for '${plan.repo.id}'.`,
158 cause,
159 }),
160 ),
161 );
162​
163 if (exitCode !== 0) {
164 return yield* new ReferenceRepoSyncError({
165 message: `git subtree ${plan.action} failed for '${plan.repo.id}' with exit code ${exitCode}.\n${stderr.trim()}`,
166 });
167 }
168​
169 if (stdout.trim().length > 0) {
170 yield* Console.log(stdout.trim());
171 }
172});
173​
174export const syncReferenceRepos = Effect.fn("syncReferenceRepos")(function* (
175 options: ReferenceRepoSyncOptions = {},
176) {
177 const path = yield* Path.Path;
178 const rootDir = path.resolve(options.rootDir ?? process.cwd());
179 const repos = yield* getSelectedRepos(options.repoId);
180 const plans: Array<ReferenceRepoSyncPlan> = [];
181​
182 for (const repo of repos) {
183 const plan = yield* planReferenceRepoSync(repo, rootDir, options.latest ?? false);
184 plans.push(plan);
185 yield* Console.log(`Syncing ${repo.id} from ${plan.ref} with git subtree ${plan.action}.`);
186 if (!(options.dryRun ?? false)) {
187 yield* runGit(rootDir, plan).pipe(Effect.scoped);
188 }
189 }
190​
191 return plans;
192});
193​
194export const syncReferenceReposCommand = Command.make(
195 "sync-reference-repos",
196 {
197 repo: Flag.string("repo").pipe(
198 Flag.withDescription("Sync only the named reference repo. Defaults to all configured repos."),
199 Flag.optional,
200 ),
201 latest: Flag.boolean("latest").pipe(
202 Flag.withDescription(
203 "Sync each repo from its latest branch instead of the installed version.",
204 ),
205 Flag.withDefault(false),
206 ),
207 root: Flag.string("root").pipe(
208 Flag.withDescription("Workspace root used to resolve versions and subtree prefixes."),
209 Flag.optional,
210 ),
211 dryRun: Flag.boolean("dry-run").pipe(
212 Flag.withDescription("Print planned subtree operations without running git."),
213 Flag.withDefault(false),
214 ),
215 },
216 ({ repo, latest, root, dryRun }) =>
217 syncReferenceRepos({
218 repoId: Option.getOrUndefined(repo),
219 rootDir: Option.getOrUndefined(root),
220 latest,
221 dryRun,
222 }),
223).pipe(Command.withDescription("Sync vendored reference repositories under .repos/."));
224​
225if (import.meta.main) {
226 Command.run(syncReferenceReposCommand, { version: "0.0.0" }).pipe(
227 Effect.provide(NodeServices.layer),
228 NodeRuntime.runMain,
229 );