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