-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathversions.ts
More file actions
571 lines (509 loc) · 15 KB
/
versions.ts
File metadata and controls
571 lines (509 loc) · 15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
/**
* Workspace version management tool.
*
* Can be used as a library or as a standalone script.
*
* Library usage:
* ```typescript
* import * as versions from "@eserstack/codebase/versions";
*
* // Show versions
* const result = await versions.showVersions();
* console.log(result.packages);
*
* // Sync versions
* const syncResult = await versions.versions("sync", { dryRun: true });
* console.log(syncResult.updates);
* ```
*
* CLI usage:
* deno run --allow-all ./versions.ts # Show versions table
* deno run --allow-all ./versions.ts sync # Sync all to highest version
* deno run --allow-all ./versions.ts patch # Bump patch, sync all
* deno run --allow-all ./versions.ts minor # Bump minor, sync all
* deno run --allow-all ./versions.ts major # Bump major, sync all
* deno run --allow-all ./versions.ts --dry-run # Preview without changes
*
* @module
*/
import * as cliParseArgs from "@std/cli/parse-args";
import * as stdPath from "@std/path";
import * as stdSemver from "@std/semver";
import * as primitives from "@eserstack/primitives";
import * as standards from "@eserstack/standards";
import * as functions from "@eserstack/functions";
import type * as shellArgs from "@eserstack/shell/args";
import * as tui from "@eserstack/shell/tui";
import { createCliContext, runCliMain, toCliEvent } from "./cli-support.ts";
import * as pkg from "./package/mod.ts";
import { requireLib } from "./ffi-client.ts";
const { ctx, output: out } = createCliContext();
/**
* Valid version commands.
*/
export type VersionCommand = "sync" | "patch" | "minor" | "major" | "explicit";
/**
* Options for version operations.
*/
export type VersionOptions = {
/** Root directory (default: ".") */
readonly root?: string;
/** Preview changes without applying */
readonly dryRun?: boolean;
/** Update the VERSION file in root (default: true) */
readonly updateVersionFile?: boolean;
/** Explicit version string (used when command is "explicit") */
readonly explicitVersion?: string;
};
/**
* Information about a package version.
*/
export type PackageVersion = {
/** Package name */
readonly name: string;
/** Package version */
readonly version: string;
};
/**
* Update information for a single package.
*/
export type VersionUpdate = {
/** Package name */
readonly name: string;
/** Version before update */
readonly from: string;
/** Version after update */
readonly to: string;
/** Whether the package was updated */
readonly changed: boolean;
};
/**
* Result of showing versions.
*/
export type ShowVersionsResult = {
/** All packages with their versions */
readonly packages: PackageVersion[];
};
/**
* Update information for a standalone file (e.g., VERSION).
*/
export type FileUpdate = {
/** File path relative to root */
readonly path: string;
/** Version before update */
readonly from: string;
/** Version after update */
readonly to: string;
/** Whether the file was updated */
readonly changed: boolean;
};
/**
* Result of a version operation.
*/
export type VersionsResult = {
/** Command that was executed */
readonly command: VersionCommand;
/** Target version */
readonly targetVersion: string;
/** All package updates */
readonly updates: VersionUpdate[];
/** Standalone file updates (e.g., VERSION file) */
readonly fileUpdates: FileUpdate[];
/** Number of packages that changed */
readonly changedCount: number;
/** Whether this was a dry run */
readonly dryRun: boolean;
};
/**
* Reads the current version from the VERSION file.
*
* @param options - Options with root directory
* @returns The version string, or undefined if the file doesn't exist
*/
export const readVersionFile = async (
options: VersionOptions = {},
): Promise<string | undefined> => {
const { root = "." } = options;
const versionFilePath = stdPath.join(root, "VERSION");
try {
const content = await standards.crossRuntime.runtime.fs.readTextFile(
versionFilePath,
);
return content.trim();
} catch {
return undefined;
}
};
/**
* Purely calculates the next version from a current version and a command.
* Delegates to Go FFI when available; falls back to @std/semver.
*
* @param current - The current semver version string
* @param command - The bump command: "patch" | "minor" | "major" | "explicit" | "sync"
* @param explicit - Required when command is "explicit"
* @returns The resulting version string
*/
export const bumpVersion = async (
current: string,
command: VersionCommand,
explicit?: string,
): Promise<string> => {
const lib = await requireLib();
const raw = lib.symbols.EserAjanCodebaseBumpVersion(
JSON.stringify({ current, command, explicit }),
);
const parsed = JSON.parse(raw) as { version?: string; error?: string };
if (parsed.error !== undefined) {
throw new Error(parsed.error);
}
if (parsed.version === undefined) {
throw new Error("bumpVersion: FFI returned no version");
}
return parsed.version;
};
/**
* Writes a version string to the VERSION file.
*/
const writeVersionFile = async (
root: string,
version: string,
): Promise<void> => {
const versionFilePath = stdPath.join(root, "VERSION");
await standards.crossRuntime.runtime.fs.writeTextFile(
versionFilePath,
version + "\n",
);
};
/**
* Syncs @eserstack/ajan-* optionalDependencies and dist/npm platform
* package.json files to match the target version.
*/
const syncAjanVersions = async (
root: string,
version: string,
): Promise<void> => {
const runtime = standards.crossRuntime.runtime;
// 1. Update optionalDependencies in pkg/@eserstack/ajan/package.json
const ajanPkgPath = stdPath.join(root, "pkg/@eserstack/ajan/package.json");
try {
const content = await runtime.fs.readTextFile(ajanPkgPath);
const updated = content.replace(
/"@eserstack\/ajan-[^"]+": "[^"]+"/g,
(match) => {
const name = match.split(":")[0]!;
return `${name}: "${version}"`;
},
);
if (updated !== content) {
await runtime.fs.writeTextFile(ajanPkgPath, updated);
}
} catch {
// ajan package may not exist in all contexts
}
// 2. Update dist/npm platform package.json files
const distNpmDir = stdPath.join(root, "pkg/@eserstack/ajan/dist/npm");
try {
for await (const entry of runtime.fs.readDir(distNpmDir)) {
if (!entry.isDirectory || !entry.name.startsWith("ajan-")) continue;
const pkgPath = stdPath.join(distNpmDir, entry.name, "package.json");
try {
const content = await runtime.fs.readTextFile(pkgPath);
const updated = content.replace(
/"version": "[^"]+"/,
`"version": "${version}"`,
);
if (updated !== content) {
await runtime.fs.writeTextFile(pkgPath, updated);
}
} catch {
// file may not exist
}
}
} catch {
// dist/npm directory may not exist
}
};
/**
* Finds the highest version from an array of version strings.
*/
const findHighestVersion = (versions: string[]): string => {
let highest = stdSemver.parse("0.0.0");
for (const version of versions) {
const v = stdSemver.parse(version);
if (stdSemver.compare(v, highest) > 0) {
highest = v;
}
}
return stdSemver.format(highest);
};
/**
* Shows all package versions in the workspace.
*
* @param options - Options for the operation
* @returns Result with package versions
*/
export const showVersions = async (
options: VersionOptions = {},
): Promise<ShowVersionsResult> => {
const { root = "." } = options;
const [rootConfig, modules] = await pkg.getWorkspaceModules(root);
const rootVersion = rootConfig.version?.value ?? "0.0.0";
const rootName = rootConfig.name?.value ?? "(root)";
const packages: PackageVersion[] = [
{ name: rootName, version: rootVersion },
...modules.map((m) => ({ name: m.name, version: m.version })),
];
return { packages };
};
/**
* Executes a version command (sync, patch, minor, major).
*
* @param command - The command to execute
* @param options - Options for the operation
* @returns Result of the operation
*/
export const versions = async (
command: VersionCommand,
options: VersionOptions = {},
): Promise<VersionsResult> => {
const {
root = ".",
dryRun = false,
updateVersionFile: shouldUpdateVersionFile = true,
} = options;
const [rootConfig, modules] = await pkg.getWorkspaceModules(root);
const rootVersion = rootConfig.version?.value ?? "0.0.0";
const rootName = rootConfig.name?.value ?? "(root)";
// Calculate target version
const allVersions = [rootVersion, ...modules.map((m) => m.version)];
const highestVersion = findHighestVersion(allVersions);
let targetVersion: string;
if (command === "explicit") {
if (options.explicitVersion === undefined) {
throw new Error(
'explicitVersion is required when command is "explicit".',
);
}
stdSemver.parse(options.explicitVersion); // validate format
targetVersion = options.explicitVersion;
} else if (command === "sync") {
targetVersion = highestVersion;
} else {
targetVersion = stdSemver.format(
stdSemver.increment(
stdSemver.parse(highestVersion),
command as stdSemver.ReleaseType,
),
);
}
// Apply package updates (including root)
const updates: VersionUpdate[] = [];
// Update root config
const rootNeedsUpdate = rootVersion !== targetVersion;
if (!dryRun) {
await pkg.updateVersion(rootConfig, targetVersion);
}
updates.push({
name: rootName,
from: rootVersion,
to: targetVersion,
changed: rootNeedsUpdate,
});
// Update workspace modules
for (const module of modules) {
const needsUpdate = module.version !== targetVersion;
if (!dryRun) {
await pkg.updateVersion(module.config, targetVersion);
}
updates.push({
name: module.name,
from: module.version,
to: targetVersion,
changed: needsUpdate,
});
}
// Sync ajan optionalDependencies + dist/npm platform packages
if (!dryRun) {
await syncAjanVersions(root, targetVersion);
}
// Update VERSION file
const fileUpdates: FileUpdate[] = [];
if (shouldUpdateVersionFile) {
const currentFileVersion = await readVersionFile({ root });
const fileChanged = currentFileVersion !== targetVersion;
if (!dryRun && fileChanged) {
await writeVersionFile(root, targetVersion);
}
fileUpdates.push({
path: "VERSION",
from: currentFileVersion ?? "",
to: targetVersion,
changed: fileChanged,
});
}
const changedCount = updates.filter((u) => u.changed).length;
return {
command,
targetVersion,
updates,
fileUpdates,
changedCount,
dryRun,
};
};
// --- Handler / Adapter / ResponseMapper (CLI layer) ---
/**
* Discriminated input for the versions functions.handler.
*/
export type VersionsInput =
| { readonly mode: "show" }
| {
readonly mode: "update";
readonly command: VersionCommand;
readonly options: VersionOptions;
};
/**
* Discriminated output from the versions functions.handler.
*/
export type VersionsOutput =
| { readonly mode: "show"; readonly result: ShowVersionsResult }
| { readonly mode: "update"; readonly result: VersionsResult };
/**
* Core handler — wraps existing library functions using `fromPromise`.
*/
export const versionsHandler: functions.handler.Handler<
VersionsInput,
VersionsOutput,
Error
> = (
input,
) => {
if (input.mode === "show") {
return functions.task.fromPromise(
async () => {
const result = await showVersions();
return { mode: "show" as const, result };
},
);
}
return functions.task.fromPromise(
async () => {
const result = await versions(input.command, input.options);
return { mode: "update" as const, result };
},
);
};
/**
* CLI Adapter — converts a `functions.triggers.CliEvent` into `VersionsInput`.
*/
const cliAdapter: functions.handler.Adapter<
functions.triggers.CliEvent,
VersionsInput
> = (event) => {
const arg = event.args[0] as string | undefined;
// No args → show mode
if (arg === undefined) {
return primitives.results.ok({ mode: "show" as const });
}
// Has arg → update mode
const validCommands = ["sync", "patch", "minor", "major"];
let command: VersionCommand;
let explicitVersion: string | undefined;
if (validCommands.includes(arg)) {
command = arg as VersionCommand;
} else {
command = "explicit";
explicitVersion = arg;
}
const dryRun = event.flags["dry-run"] === true;
return primitives.results.ok({
mode: "update" as const,
command,
options: { dryRun, explicitVersion },
});
};
/**
* CLI ResponseMapper — formats handler output for terminal display.
*/
const cliResponseMapper: functions.handler.ResponseMapper<
VersionsOutput,
Error | functions.handler.AdaptError,
shellArgs.CliResult<void>
> = (result) => {
if (primitives.results.isFail(result)) {
return primitives.results.fail({
exitCode: 1,
message: String(result.error),
});
}
const handlerOutput = result.value;
if (handlerOutput.mode === "show") {
console.table(handlerOutput.result.packages);
return primitives.results.ok(undefined);
}
// Update mode
const { result: updateResult } = handlerOutput;
if (updateResult.command === "sync") {
tui.log.info(ctx, "Syncing all versions...");
} else if (updateResult.command === "explicit") {
tui.log.info(
ctx,
`Setting all versions to ${updateResult.targetVersion}...`,
);
} else {
tui.log.info(
ctx,
`Bumping all versions (${updateResult.command})...`,
);
}
tui.log.info(ctx, `Target version: ${updateResult.targetVersion}`);
console.table(updateResult.updates);
for (const fileUpdate of updateResult.fileUpdates) {
if (fileUpdate.changed) {
tui.log.info(
ctx,
`${fileUpdate.path} (${fileUpdate.from} → ${fileUpdate.to})`,
);
}
}
if (updateResult.dryRun) {
tui.log.info(
ctx,
`Dry run - ${updateResult.changedCount} packages would be modified.`,
);
} else {
tui.log.success(
ctx,
`Done. Updated ${updateResult.changedCount} packages.`,
);
}
return primitives.results.ok(undefined);
};
/**
* CLI trigger — wired handler for command-line invocation.
*/
export const handleCli: (
event: functions.triggers.CliEvent,
) => Promise<shellArgs.CliResult<void>> = functions.handler.createTrigger({
handler: versionsHandler,
adaptInput: cliAdapter,
adaptOutput: cliResponseMapper,
});
/** CLI entry point for dispatcher compatibility. */
export const main = async (
cliArgs?: readonly string[],
): Promise<shellArgs.CliResult<void>> => {
const parsed = cliParseArgs.parseArgs(
(cliArgs ?? []) as string[],
{ boolean: ["dry-run"] },
);
const event = toCliEvent("versions", parsed);
return await handleCli(event);
};
if (import.meta.main) {
runCliMain(
await main(standards.crossRuntime.runtime.process.args as string[]),
out,
);
}