Skip to content
Myr

Print the release's version from the CLI's --version in the binaries and the npm build

Before adoption: this commit came in with the history the project adopted, so no landing records it.

- One module says the version: `apps/cli/src/version.ts` exports `cliVersion`, read from `import.meta.env.CLI_BUILD_VERSION`, which both bundlers replace at build and vitest leaves undefined, so an unbuilt run says `0.0.0` (the release's `UNRELEASED`). `main.ts`' `--version` and the stdio MCP server's `version` read it. - One define for both bundlers: `versionDefine(version)` in `tsdown.config.ts` (re-exported by `build.ts`; defining it in `build.ts` would make an import cycle). `npm(version)` makes the three tsdown entries with it, and `compileArgs` passes it to each `bun build --compile` as `--define`. - `build.ts` takes `--version <semver>` (absent builds `0.0.0`), with effect/cli's built-in boolean `--version` turned off; it builds only under `import.meta.main`, so tests import its pure parts (`parseBuild`, `compileArgs`). - The release's `tsdown` step passes `--version <release.version>`; `UNRELEASED`'s comment says the build now stamps it. - Tests: `apps/cli/test/version.test.ts` (unbuilt `0.0.0` and `--version`; the define replaces what `version.ts` reads; every npm config carries it; a real tsdown build of `version.ts` reads `9.9.9-test`; the compile argv; the flag parser). `packages/config/test/release.test.ts` records the `tsdown` step's command for `0.2.0-demo.1`. - Hand build (issue 1104's comments): `--version 9.9.9-test` makes node, bun and the compiled binary print `myr v9.9.9-test`; no flag prints `myr v0.0.0`. - ASSUMPTION: Bun fills `import.meta.env` from the process env, so an unbuilt Bun run with `CLI_BUILD_VERSION` set reports it; built outputs never look.

authored by oscabriel · committed by oscabriel · parent 42ea9b7 · Browse files · 9 files+426 added−56 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

9 files+426 added−56 removed

  • tests:+236 added−0 removed
  • other:+190 added−56 removed

9 files+426 added−56 removed

modified:apps/cli/src/main.ts+2 added-6 removed
21 unmodified lines
22 RemoteClient,23 transportMessage,24} from "./remote.ts";25import { commands, mcp, UnknownCommand } from "./surfaces.ts";26import { cliVersion } from "./version.ts";2728/**29 * The three commands that start any contribution, first in `--help`, so a30 * person or an agent who knows nothing else knows where to begin.
12 unmodified lines
43 Command.withDescription(banner),44 Command.withSubcommands(tree)45);4646/**47 * The CLI's version until the release build stamps its own.48 */49const version = "0.0.0";5047/** The exit code of a usage error, as for a command line effect/cli can't parse. */48const USAGE = 2;4950/**
120 unmodified lines
171172 const exit = yield* Effect.exit(173 Command.runWith(root.pipe(Command.provideEffectDiscard(stdout.open)), {174 renderErrors: false,179 version,175 version: cliVersion,176 })(argv).pipe(177 Effect.provideService(178 CliConfig.CliConfig,179 CliConfig.make({ builtIns: builtInsFor(policy) })
28 unmodified lines
modified:apps/cli/src/surfaces.ts+2 added-1 removed
40 unmodified lines
41import { Output } from "./output.ts";42import { refusalsIn, views } from "./render.ts";43import { repoContext } from "./repo-context.ts";44import { today } from "./tui/command.ts";45import { cliVersion } from "./version.ts";4647/** The folder the CLI stands in: the process's own, unless a test says otherwise. */48export const WorkingDirectory = Context.Reference<string>(49 "cli/WorkingDirectory",
265 unmodified lines
315 McpProtocol.v2025_06_18,316 McpProtocol.v2025_03_26,317 McpProtocol.v2024_11_05,318 ],318 version: "0.0.0",319 version: cliVersion,320 })321 )322 );323
11 unmodified lines
added:apps/cli/src/version.ts+26 added
added:apps/cli/test/version.test.ts+169 added
1/**2 * The CLI's version: `src/version.ts` says it, a run no build stamped says3 * `0.0.0`, and `build.ts` stamps a release's version into both bundlers'4 * output through one define. The real build compiles binaries, so it is5 * run by hand (issue 1104's comments), not here.6 */7import { NodeServices } from "@effect/platform-node";8import { describe, expect, it } from "@effect/vitest";9import { Brand } from "@repo/brand";10import { Client } from "@repo/protocol/contracts";11import { Effect, FileSystem, Layer, Option, Path, Ref, Schema } from "effect";12import { CliOutput } from "effect/cli";13import { TestConsole } from "effect/testing";14import { build } from "tsdown";1516import { compileArgs, parseBuild, versionDefine } from "../build.ts";17import type { BuildOptions } from "../build.ts";18import { program } from "../src/main.ts";19import { OutputPlain } from "../src/output.ts";20import { cliVersion } from "../src/version.ts";21import { npm } from "../tsdown.config.ts";22import { SignedOut } from "./signed-out.ts";2324const services = Layer.mergeAll(25 TestConsole.layer,26 CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),27 Layer.mock(Client)({}),28 OutputPlain,29 SignedOut30).pipe(Layer.provideMerge(NodeServices.layer));3132/** What a built `version.ts` exports. */33const Built = Schema.Struct({ cliVersion: Schema.String });3435describe("the CLI's version, unbuilt", () => {36 it.effect("is 0.0.0, and --version prints it", () =>37 Effect.gen(function* () {38 yield* program(["--version"]);3940 expect({41 cliVersion,42 printed: (yield* TestConsole.logLines).map(String),43 }).toStrictEqual({44 cliVersion: "0.0.0",45 printed: [`${Brand.cli} v0.0.0`],46 });47 }).pipe(Effect.provide(services))48 );49});5051describe("the build's version stamp", () => {52 it.effect(53 "replaces the expression version.ts reads with the version, as a string literal",54 () =>55 Effect.gen(function* () {56 const fs = yield* FileSystem.FileSystem;57 const path = yield* Path.Path;58 const root = yield* path.fromFileUrl(new URL("..", import.meta.url));5960 const source = yield* fs.readFileString(61 path.join(root, "src", "version.ts")62 );6364 const define = versionDefine("9.9.9-test");6566 expect({67 define,68 unread: Object.keys(define).filter((key) => !source.includes(key)),69 }).toStrictEqual({70 define: { "import.meta.env.CLI_BUILD_VERSION": '"9.9.9-test"' },71 unread: [],72 });73 }).pipe(Effect.provide(NodeServices.layer))74 );7576 it("is in every config tsdown.config.ts makes, for the version it is given", () => {77 expect(npm("9.9.9-test").map((config) => config.define)).toStrictEqual(78 Array.from({ length: 3 }, () => versionDefine("9.9.9-test"))79 );80 });8182 it.live(83 "stamps the npm build: tsdown's build of version.ts reads the version",84 () =>85 Effect.gen(function* () {86 const fs = yield* FileSystem.FileSystem;87 const path = yield* Path.Path;88 const root = yield* path.fromFileUrl(new URL("..", import.meta.url));8990 const out = yield* fs.makeTempDirectoryScoped({91 prefix: "cli-version-",92 });9394 const [first] = npm("9.9.9-test");9596 yield* Effect.tryPromise(() =>97 build({98 ...first,99 config: false,100 cwd: root,101 entry: { version: path.join(root, "src", "version.ts") },102 logLevel: "silent",103 outDir: out,104 })105 );106107 const built = yield* Effect.tryPromise(108 () => import(path.join(out, "version.js"))109 ).pipe(Effect.flatMap(Schema.decodeUnknownEffect(Built)));110111 expect(built.cliVersion).toBe("9.9.9-test");112 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))113 );114115 it("stamps each compiled binary with the same define", () => {116 expect(117 compileArgs({118 entry: "/b/main.ts",119 outfile: "/b/out",120 target: "linux-x64",121 version: "9.9.9-test",122 })123 ).toStrictEqual([124 "build",125 "--compile",126 "--minify",127 "--define",128 'import.meta.env.CLI_BUILD_VERSION="9.9.9-test"',129 "--target=bun-linux-x64",130 "/b/main.ts",131 "--outfile",132 "/b/out",133 ]);134 });135});136137/** What the build would run with for `argv`, if it would run. */138const parsed = (argv: readonly string[]) =>139 Effect.gen(function* () {140 const seen = yield* Ref.make(Option.none<BuildOptions>());141142 yield* parseBuild(argv, (options) => Ref.set(seen, Option.some(options)));143144 return yield* Ref.get(seen);145 }).pipe(Effect.provide(services));146147describe("the build's flags", () => {148 it.effect(149 "read --version and --targets, and build 0.0.0 without a version",150 () =>151 Effect.gen(function* () {152 expect({153 stamped: yield* parsed([154 "--targets",155 "bun-linux-x64,darwin-arm64",156 "--version",157 "9.9.9-test",158 ]),159 unstamped: yield* parsed([]),160 }).toStrictEqual({161 stamped: Option.some({162 targets: ["linux-x64", "darwin-arm64"],163 version: "9.9.9-test",164 }),165 unstamped: Option.some({ targets: [], version: "0.0.0" }),166 });167 })168 );169});
modified:apps/cli/build.ts+112 added-38 removed
15 unmodified lines
16 * 4. Beside each binary, `git-credential-<slug>` links to it: the binary17 * sees the name it was started by (`src/bin.ts`), so the link is git's18 * credential helper.19 *20 * `--version <semver>` stamps both builds (`versionDefine`): it is what21 * the CLI's `--version` prints. Without it the build says `0.0.0`.22 *23 * A Bun script, outside every Worker's graph. Names come from `Brand`.24 * Importing it builds nothing (`tsdown.config.ts` and the tests read its25 * pure parts): only `bun build.ts` runs the build.26 */27import { BunRuntime, BunServices } from "@effect/platform-bun";28import { Brand } from "@repo/brand";29import {
4 unmodified lines
34 Path,35 Predicate,36 Schema,37} from "effect";33import { Command, Flag } from "effect/cli";38import { CliConfig, Command, Flag, GlobalFlag } from "effect/cli";39import { ChildProcess, ChildProcessSpawner } from "effect/process";40import { build } from "tsdown";4142import { NATIVE, npmMachineOf } from "./build-targets.ts";43import { EMBEDDED_KEY } from "./src/local/config-runtime.ts";39import { declarations, library } from "./tsdown.config.ts";44import {45 declarations,46 library,47 npm,48 UNSTAMPED,49 versionDefine,50} from "./tsdown.config.ts";5152// The one define both bundlers get, kept beside tsdown's configs, which53// this module imports (lint refuses an import cycle).54export { versionDefine } from "./tsdown.config.ts";5556/** What one build is asked for. */57export interface BuildOptions {58 /** Bun targets to cross-compile for, without `bun-`; none builds for this machine. */59 readonly targets: readonly string[];60 /** The version both builds are stamped with. */61 readonly version: string;62}6364/**65 * `bun build --compile`'s arguments for one binary: `entry` compiled to66 * `outfile`, for `target` (this machine when absent), stamped with `version`.67 */68export const compileArgs = (input: {69 readonly entry: string;70 readonly outfile: string;71 readonly target?: string;72 readonly version: string;73}) => [74 "build",75 "--compile",76 "--minify",77 ...Object.entries(versionDefine(input.version)).flatMap(([key, value]) => [78 "--define",79 `${key}=${value}`,80 ]),81 ...(input.target === undefined ? [] : [`--target=bun-${input.target}`]),82 input.entry,83 "--outfile",84 input.outfile,85];8687class BuildFailed extends Data.TaggedError("BuildFailed")<{88 readonly step: string;89 readonly detail: string;90}> {}
71 unmodified lines
162 catch: (cause) => new BuildFailed({ detail: String(cause), step }),163 try: () => build(config),164 });165120const make = (targets: readonly string[]) =>166const make = ({ targets, version }: BuildOptions) =>167 Effect.gen(function* () {168 const fs = yield* FileSystem.FileSystem;169 const path = yield* Path.Path;170 const root = yield* path.fromFileUrl(new URL(".", import.meta.url));
36 unmodified lines
207 fs.writeFileString(path.join(dir, name), JSON.stringify(config)),208 path.join(dir, name)209 );210165 // 1. The npm build.166 yield* tsdown("tsdown", {167 config: path.join(root, "tsdown.config.ts"),168 cwd: root,169 });211 // 1. The npm build, one entry at a time: the first cleans `dist/`.212 for (const config of npm(version)) {213 yield* tsdown("tsdown", { ...config, config: false, cwd: root });214 }215216 // 2. The library entries' types. tsgo declares them in a folder at a217 // fixed path, removed once the build ends: the bundled `.d.ts` files keep218 // each source's path in a comment, so a temp folder's random name would
171 unmodified lines
390391 yield* run(392 "bun build --compile",393 "bun",349 [350 "build",351 "--compile",352 "--minify",394 compileArgs({395 entry: path.join(compile, "main.ts"),396 outfile: path.join(dir, Brand.cli),397 version,398 ...Option.match(target, {354 onNone: () => [],355 onSome: (name) => [`--target=bun-${name}`],399 onNone: () => ({}),400 onSome: (name) => ({ target: name }),401 }),357 path.join(compile, "main.ts"),358 "--outfile",359 path.join(dir, Brand.cli),360 ],402 }),403 { env }404 );405406 yield* fs.symlink(Brand.cli, path.join(dir, Brand.gitCredentialHelper));
6 unmodified lines
413 ),414 Flag.optional415);416375const command = Command.make("build", { targets }, (flags) =>376 make(377 Option.match(flags.targets, {378 onNone: () => [],379 onSome: (list) =>380 list381 .split(",")382 .map((target) => target.trim().replace(/^bun-/u, ""))383 .filter((target) => target.length > 0),384 })385 )386).pipe(387 Command.withDescription(388 "Build the CLI: the npm dist/, and a standalone binary that is also git's credential helper."389 )417const version = Flag.String("version").pipe(418 Flag.withDescription(419 `The version both builds are stamped with, which the CLI's --version prints (default ${UNSTAMPED}).`420 ),421 Flag.optional422);423424/** The build's command line, running `then` with what it asks for. */425const command = <E, R>(426 then: (options: BuildOptions) => Effect.Effect<void, E, R>427) =>428 Command.make("build", { targets, version }, (flags) =>429 then({430 targets: Option.match(flags.targets, {431 onNone: () => [],432 onSome: (list) =>433 list434 .split(",")435 .map((target) => target.trim().replace(/^bun-/u, ""))436 .filter((target) => target.length > 0),437 }),438 version: Option.getOrElse(flags.version, () => UNSTAMPED),439 })440 ).pipe(441 Command.withDescription(442 "Build the CLI: the npm dist/, and a standalone binary that is also git's credential helper."443 )444 );445446/**447 * The build's own `--version` takes a value, so effect/cli's built-in448 * `--version` (a boolean that prints and exits) is left out.449 */450const builtIns = CliConfig.make({451 builtIns: GlobalFlag.BuiltIns.filter((flag) => flag !== GlobalFlag.Version),452});453454/** Runs `then` with what `argv`, the build's arguments, asks for. */455export const parseBuild = <E, R>(456 argv: readonly string[],457 then: (options: BuildOptions) => Effect.Effect<void, E, R>458) =>459 Command.runWith(command(then), { version: UNSTAMPED })(argv).pipe(460 Effect.provideService(CliConfig.CliConfig, builtIns)461 );462463if (import.meta.main) {464 BunRuntime.runMain(392BunRuntime.runMain(393 Command.run(command, { version: "0.0.0" }).pipe(394 Effect.provide(BunServices.layer)395 )396);465 Command.run(command(make), { version: UNSTAMPED }).pipe(466 Effect.provideService(CliConfig.CliConfig, builtIns),467 Effect.provide(BunServices.layer)468 )469 );470}
modified:apps/cli/tsdown.config.ts+33 added-7 removed
modified:packages/config/test/release.test.ts+67 added
11 unmodified lines
12 Effect,13 FileSystem,14 Option,15 Order,16 Layer,17 Path,18 Ref,19 Result,20 Schema,21 Sink,22 Stream,23} from "effect";24import { ChildProcess, ChildProcessSpawner } from "effect/process";25
18 unmodified lines
44 uploads,45 VersionNeeded,46 VersionReleased,47} from "../../../scripts/lib/release.ts";48import { layoutOf, runStep } from "../../../scripts/lib/release/steps.ts";49import { Brand } from "../../brand/src/index.ts";50import { repoRoot } from "./root.ts";5152/** What the test reads of a package manifest. */
378 unmodified lines
431 [`${Brand.slug}-darwin-arm64`]: { bytes: 62_800_000, sha256: digest("d") },432 [`${Brand.slug}-linux-x64`]: { bytes: 81_900_000, sha256: digest("e") },433};434435/**436 * A spawner that runs nothing and exits 0: each command it was asked for,437 * as `<folder>$ <command> <args>`, its folder relative to the repo root.438 */439const recordingSpawner = Effect.gen(function* () {440 const path = yield* Path.Path;441 const root = yield* repoRoot;442 const lines = yield* Ref.make<readonly string[]>([]);443444 const spawner = ChildProcessSpawner.make((command) =>445 Effect.gen(function* () {446 if (!ChildProcess.isStandardCommand(command)) {447 return yield* Effect.die("the release pipes no commands");448 }449450 yield* Ref.update(lines, (all) => [451 ...all,452 `${path.relative(root, command.options.cwd ?? root)}$ ${[command.command, ...command.args].join(" ")}`,453 ]);454455 return ChildProcessSpawner.makeHandle({456 all: Stream.empty,457 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),458 getInputFd: () => Sink.drain,459 getOutputFd: () => Stream.empty,460 isRunning: Effect.succeed(false),461 kill: () => Effect.void,462 pid: ChildProcessSpawner.ProcessId(1),463 stderr: Stream.empty,464 stdin: Sink.drain,465 stdout: Stream.empty,466 unref: Effect.succeed(Effect.void),467 });468 })469 );470471 return {472 layer: Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),473 spawned: Ref.get(lines),474 };475});476477describe("a release's build step", () => {478 it.effect(479 "builds the CLI stamped with the release's version, for both targets",480 () =>481 Effect.gen(function* () {482 const { layer, spawned } = yield* recordingSpawner;483 const layout = yield* layoutOf(yield* repoRoot);484485 yield* runStep("tsdown", layout, {486 origin: "https://platform.example",487 stage: Option.none(),488 version: "0.2.0-demo.1",489 }).pipe(Effect.provide(layer));490491 expect(yield* spawned).toStrictEqual([492 "apps/cli$ bun run build -- --targets bun-linux-x64,bun-darwin-arm64 --version 0.2.0-demo.1",493 ]);494 }).pipe(Effect.provide(NodeServices.layer))495 );496});497498describe("the release manifest", () => {499 it.effect(500 "keeps every earlier version, makes the new one latest, and is what the platform decodes",501 () =>
259 unmodified lines
modified:scripts/lib/release/steps.ts+11 added-2 removed
1 unmodified line
2 * What each step of a release does on this machine, over the3 * plan `scripts/lib/release.ts` makes:4 *5 * - `tsdown`: the CLI's `bun run build` in `apps/cli`, with both targets6 * (`dist/`, and `dist/bin/<target>/` per target);6 * (`dist/`, and `dist/bin/<target>/` per target), stamped with the7 * release's version (what `--version` prints);8 * - `manifest`: the npm package, staged in `apps/cli/release/npm/`: the9 * build's `dist/*.js` and `*.d.ts`, the generated `package.json`, its10 * README and the repo's licence;11 * - `copySkills`: the platform's skill (`@repo/agent-kit`'s
603 unmodified lines
615 Match.when("tsdown", () =>616 run(617 "tsdown",618 "bun",618 ["run", "build", "--", "--targets", targets.join(",")],619 [620 "run",621 "build",622 "--",623 "--targets",624 targets.join(","),625 "--version",626 release.version,627 ],628 layout.cli629 )630 ),631 Match.when("manifest", () => stagePackage(layout, release)),
8 unmodified lines
modified:scripts/lib/release.ts+4 added-2 removed
388 unmodified lines
389 })390 );391392/**393 * What the CLI reports itself as until a build stamps it (`main.ts`394 * says `0.0.0`), and so what a build that neither uploads nor publishes is.393 * What a build that neither uploads nor publishes is stamped with. The394 * build stamps the release's version into the CLI (`apps/cli/build.ts`'s395 * `--version`, which the `tsdown` step passes), and a run no build stamped396 * reports this too (`apps/cli/src/version.ts`).397 */398const UNRELEASED = "0.0.0";399400/**
136 unmodified lines