From 2ed9bf0236c813b7cb9cc82f7f94e53c23b83505 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Sun, 13 Sep 2026 14:24:27 +0800 Subject: [PATCH] feat: make development builds visibly identifiable --- README.md | 2 +- scripts/build-binary.mjs | 74 +++++++++++++++++--- scripts/bump-version.ts | 15 ++-- scripts/check-version-sync.ts | 1 - scripts/dev-hygiene.test.ts | 9 ++- scripts/dev-hygiene.ts | 6 +- src/aipro-cli.test.ts | 3 +- src/aipro-cli.ts | 6 +- src/cli/printer.ts | 4 +- src/cli/runner.test.ts | 8 +-- src/cli/runner.ts | 4 +- src/version.test.ts | 61 ++++++++++++++++ src/version.ts | 127 +++++++++++++++++++++++++++++++++- 13 files changed, 285 insertions(+), 35 deletions(-) create mode 100644 src/version.test.ts diff --git a/README.md b/README.md index 749be03..5d1da87 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ bun run dev:override hose-use version ``` -该命令会构建本机二进制、原子替换全局 `hose-use`,同步 `~/.agents/skills/hose-use`,并保留 `hose-aipro` 别名;后台服务若正在运行会自动重启。只预览动作可运行 `bun run dev:override -- --dry-run`。 +该命令会构建本机二进制、原子替换全局 `hose-use`,同步 `~/.agents/skills/hose-use`,并保留 `hose-aipro` 别名;后台服务若正在运行会自动重启。开发构建会把 Git 信息编译进版本,例如 `hose-use v0.8.6-dev.1+gabc1234 [DEV BUILD]`,不会再与正式版混淆;`hose-use version --json` 还会返回 `channel`、`isRelease` 和 `git` 元数据。只预览动作可运行 `bun run dev:override -- --dry-run`。 > 开发版安装会覆盖当前 PATH 中的 `hose-use`,适合本机测试;发布环境请使用正式 Release 安装脚本。不要用 `npm install -g .` 代替,它会留下不会随源码更新的旧副本。 diff --git a/scripts/build-binary.mjs b/scripts/build-binary.mjs index d6154d9..9042ee6 100644 --- a/scripts/build-binary.mjs +++ b/scripts/build-binary.mjs @@ -1,4 +1,4 @@ -import { mkdirSync, existsSync, unlinkSync, symlinkSync } from "node:fs"; +import { mkdirSync, readFileSync, existsSync, unlinkSync, symlinkSync } from "node:fs"; import { spawnSync } from "node:child_process"; import { dirname, resolve } from "node:path"; import { fileURLToPath } from "node:url"; @@ -17,20 +17,77 @@ const TARGET_MAP = { const args = process.argv.slice(2); const isAll = args.includes("--all") || args.includes("--matrix"); const targetArg = args.find((arg) => arg.startsWith("--target="))?.replace("--target=", ""); +const isRelease = args.includes("--release") || + process.env.HOSE_BUILD_RELEASE === "1" || + (Boolean(process.env.CI) && process.env.GITHUB_REF_TYPE === "tag"); + +function getBuildInfo(releaseMode) { + const pkg = JSON.parse(readFileSync(resolve(root, "package.json"), "utf8")); + if (releaseMode) return { version: pkg.version, channel: "release", isRelease: true }; + + try { + const result = spawnSync("git", ["describe", "--tags", "--long", "--dirty", "--always"], { cwd: root, encoding: "utf8" }); + if (result.status === 0 && result.stdout) { + const trimmed = result.stdout.trim(); + const dirty = trimmed.endsWith("-dirty"); + const clean = dirty ? trimmed.slice(0, -6) : trimmed; + const longMatch = clean.match(/^v?(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?)-(\d+)-g([0-9a-f]+)$/); + let baseVersion = pkg.version; + let commitsAhead = 0; + let commit = ""; + if (longMatch) { + baseVersion = longMatch[1]; + commitsAhead = Number.parseInt(longMatch[2], 10); + commit = longMatch[3]; + } else { + const revision = spawnSync("git", ["rev-parse", "--short", "HEAD"], { cwd: root, encoding: "utf8" }); + if (revision.status === 0 && revision.stdout) commit = revision.stdout.trim(); + } + const dirtySuffix = dirty ? ".dirty" : ""; + const commitSuffix = commit ? `+g${commit}${dirtySuffix}` : dirty ? "+dirty" : ""; + return { + version: `${baseVersion}-dev.${commitsAhead}${commitSuffix}`, + channel: "dev", + isRelease: false, + git: { baseVersion, commitsAhead, commit, dirty, describe: trimmed } + }; + } + } catch { + // Fall back below if git is unavailable. + } + return { version: `${pkg.version}-dev.0+local`, channel: "dev", isRelease: false }; +} + +const buildInfo = getBuildInfo(isRelease); +const buildEnv = { + ...process.env, + HOSE_BUILD_VERSION: buildInfo.version, + HOSE_BUILD_CHANNEL: buildInfo.channel, + HOSE_BUILD_IS_RELEASE: String(buildInfo.isRelease), + ...(buildInfo.git ? { + HOSE_BUILD_GIT_BASE: buildInfo.git.baseVersion, + HOSE_BUILD_GIT_COMMITS_AHEAD: String(buildInfo.git.commitsAhead), + HOSE_BUILD_GIT_COMMIT: buildInfo.git.commit, + HOSE_BUILD_GIT_DIRTY: String(buildInfo.git.dirty), + HOSE_BUILD_GIT_DESCRIBE: buildInfo.git.describe + } : {}) +}; + +console.log(`[build:binary] version: ${buildInfo.version} (${buildInfo.channel}, isRelease: ${buildInfo.isRelease})`); if (isAll) { for (const [name, config] of Object.entries(TARGET_MAP)) { - buildTarget(name, config.bunTarget, resolve(root, config.outfile)); + buildTarget(name, config.bunTarget, resolve(root, config.outfile), "src/cli.ts", buildEnv); } } else if (targetArg) { const config = TARGET_MAP[targetArg]; if (!config) { throw new Error(`Unknown target: ${targetArg}. Available targets: ${Object.keys(TARGET_MAP).join(", ")}`); } - buildTarget(targetArg, config.bunTarget, resolve(root, config.outfile)); + buildTarget(targetArg, config.bunTarget, resolve(root, config.outfile), "src/cli.ts", buildEnv); } else { const outputHose = resolve(root, "dist/bin/hose-use"); - buildTarget("host", null, outputHose, "src/cli.ts"); + buildTarget("host", null, outputHose, "src/cli.ts", buildEnv); // Unix Multicall Binary: 创建 hose-aipro -> hose-use 软链接别名 const outputAipro = resolve(root, "dist/bin/hose-aipro"); @@ -43,16 +100,16 @@ if (isAll) { } } -function buildTarget(name, bunTarget, output, entry = "src/cli.ts") { +function buildTarget(name, bunTarget, output, entry = "src/cli.ts", env = process.env) { mkdirSync(dirname(output), { recursive: true }); - const buildArgs = ["build", "--compile"]; + const buildArgs = ["build", "--compile", "--env=HOSE_BUILD_*"]; if (bunTarget) { buildArgs.push(`--target=${bunTarget}`); } buildArgs.push("--outfile", output, entry); console.log(`[build:binary] compiling target: ${name} -> ${output}`); - run(bun, buildArgs); + run(bun, buildArgs, { env }); if (process.platform === "darwin" && (name.startsWith("darwin") || name === "host")) { try { @@ -71,7 +128,8 @@ function buildTarget(name, bunTarget, output, entry = "src/cli.ts") { function run(command, args, options = {}) { const result = spawnSync(command, args, { cwd: root, - stdio: options.quiet ? ["ignore", "ignore", "ignore"] : "inherit" + stdio: options.quiet ? ["ignore", "ignore", "ignore"] : "inherit", + env: options.env ?? process.env }); if (result.error) throw result.error; if (result.status !== 0) { diff --git a/scripts/bump-version.ts b/scripts/bump-version.ts index 2aa1100..64eefcc 100644 --- a/scripts/bump-version.ts +++ b/scripts/bump-version.ts @@ -35,19 +35,14 @@ pkg.version = nextVersion; writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + "\n"); console.log("✓ Updated package.json"); -// 2. src/version.ts -const versionTsPath = join(ROOT, "src", "version.ts"); -writeFileSync(versionTsPath, `export const VERSION = "${nextVersion}";\n`); -console.log("✓ Updated src/version.ts"); - -// 3. README.md +// 2. README.md const readmePath = join(ROOT, "README.md"); let readmeContent = readFileSync(readmePath, "utf-8"); readmeContent = readmeContent.replace(/# hose-use \(v[\d.]+\)/g, `# hose-use (v${nextVersion})`); writeFileSync(readmePath, readmeContent); console.log("✓ Updated README.md"); -// 4. skills/hose-use/SKILL.md +// 3. skills/hose-use/SKILL.md const skillPath = join(ROOT, "skills", "hose-use", "SKILL.md"); let skillContent = readFileSync(skillPath, "utf-8"); skillContent = skillContent.replace(/# hose-use \(v[\d.]+\)/g, `# hose-use (v${nextVersion})`); @@ -57,7 +52,7 @@ skillContent = skillContent.replace(/\(v[\d.]+\)/g, `(v${nextVersion})`); writeFileSync(skillPath, skillContent); console.log("✓ Updated skills/hose-use/SKILL.md"); -// 5. openapi/openapi.yaml +// 4. openapi/openapi.yaml const openapiPath = join(ROOT, "openapi", "openapi.yaml"); if (existsSync(openapiPath)) { let openapiContent = readFileSync(openapiPath, "utf-8"); @@ -66,7 +61,7 @@ if (existsSync(openapiPath)) { console.log("✓ Updated openapi/openapi.yaml"); } -// 5.5 .zcode-plugin/plugin.json +// 4.5 .zcode-plugin/plugin.json const pluginJsonPath = join(ROOT, ".zcode-plugin", "plugin.json"); if (existsSync(pluginJsonPath)) { const pluginJson = JSON.parse(readFileSync(pluginJsonPath, "utf-8")); @@ -75,7 +70,7 @@ if (existsSync(pluginJsonPath)) { console.log("✓ Updated .zcode-plugin/plugin.json"); } -// 6. Sync to global ~/.agents/skills/hose-use/ if present +// 5. Sync to global ~/.agents/skills/hose-use/ if present const globalSkillDir = join(process.env.HOME || "", ".agents", "skills", "hose-use"); if (existsSync(globalSkillDir)) { const srcDir = join(ROOT, "skills", "hose-use"); diff --git a/scripts/check-version-sync.ts b/scripts/check-version-sync.ts index b5db603..c8c4548 100644 --- a/scripts/check-version-sync.ts +++ b/scripts/check-version-sync.ts @@ -6,7 +6,6 @@ const root = join(import.meta.dirname, ".."); const packageVersion = (JSON.parse(readFileSync(join(root, "package.json"), "utf8")) as { version: string }).version; const expected: Array<[string, string | undefined]> = [ ["package.json", packageVersion], - ["src/version.ts", readFileSync(join(root, "src/version.ts"), "utf8").match(/VERSION\s*=\s*[\"']([^\"']+)/)?.[1]], [".zcode-plugin/plugin.json", readJsonVersion(".zcode-plugin/plugin.json")], ["openapi/openapi.yaml", readFileSync(join(root, "openapi/openapi.yaml"), "utf8").match(/^\s+version:\s+([^\s]+)\s*$/m)?.[1]], ["dist/openapi.json", readJsonVersion("dist/openapi.json", ["info", "version"])], diff --git a/scripts/dev-hygiene.test.ts b/scripts/dev-hygiene.test.ts index db78466..5d4c778 100644 --- a/scripts/dev-hygiene.test.ts +++ b/scripts/dev-hygiene.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test"; -import { buildCleanupPlan, classifyExitCode, parseDevHygieneArgs, type Finding } from "./dev-hygiene.ts"; +import { buildCleanupPlan, classifyExitCode, isCompatibleBinaryVersion, parseDevHygieneArgs, type Finding } from "./dev-hygiene.ts"; describe("dev hygiene tooling", () => { test("only accepts development-scoped modes and confirmation flags", () => { @@ -16,6 +16,13 @@ describe("dev hygiene tooling", () => { expect(classifyExitCode([finding("blocked")])).toBe(3); }); + test("accepts a development build based on the current stable version", () => { + expect(isCompatibleBinaryVersion("0.8.6", "0.8.6")).toBe(true); + expect(isCompatibleBinaryVersion("0.8.6-dev.2+gabc1234", "0.8.6")).toBe(true); + expect(isCompatibleBinaryVersion("0.8.5-dev.1+gold", "0.8.6")).toBe(false); + expect(isCompatibleBinaryVersion(undefined, "0.8.6")).toBe(false); + }); + test("only plans deletion for clean merged worktrees and local branches", () => { const snapshot = { repository: {} as any, diff --git a/scripts/dev-hygiene.ts b/scripts/dev-hygiene.ts index ca5985b..4c65ce6 100644 --- a/scripts/dev-hygiene.ts +++ b/scripts/dev-hygiene.ts @@ -285,6 +285,10 @@ function resolveCommand(name: string): string | undefined { return undefined; } +export function isCompatibleBinaryVersion(actual: string | undefined, expected: string): boolean { + return actual === expected || actual?.startsWith(`${expected}-dev.`) === true; +} + function inspectBinary(name: string): HygieneSnapshot["binaries"][number] { const path = resolveCommand(name); if (!path) return { name, expectedVersion: PACKAGE.version, matches: false, error: "PATH 中未找到" }; @@ -294,7 +298,7 @@ function inspectBinary(name: string): HygieneSnapshot["binaries"][number] { } try { const version = (JSON.parse(result.stdout) as { version?: string }).version; - return { name, path, version, expectedVersion: PACKAGE.version, matches: version === PACKAGE.version }; + return { name, path, version, expectedVersion: PACKAGE.version, matches: isCompatibleBinaryVersion(version, PACKAGE.version) }; } catch { return { name, path, expectedVersion: PACKAGE.version, matches: false, error: "版本输出不是 JSON" }; } diff --git a/src/aipro-cli.test.ts b/src/aipro-cli.test.ts index 871067b..741a7b0 100644 --- a/src/aipro-cli.test.ts +++ b/src/aipro-cli.test.ts @@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { runAiProCli } from "./aipro-cli.js"; import { closeApprovalDatabase, getApprovalDatabase } from "./domains/approval/db.js"; import { ApprovalRepository } from "./domains/approval/repository.js"; +import { getVersionInfo } from "./version.js"; describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => { beforeEach(() => { @@ -29,7 +30,7 @@ describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => { const version = await runAiProCli(["version", "--json"]); const help = await runAiProCli(["help", "--json"]); - expect(JSON.parse(version.stdout)).toEqual({ name: "hose-aipro", version: expect.any(String) }); + expect(JSON.parse(version.stdout)).toEqual(getVersionInfo("hose-aipro")); expect(JSON.parse(help.stdout).help).toContain("hose-aipro"); expect(version.stderr).toBe(""); expect(help.stderr).toBe(""); diff --git a/src/aipro-cli.ts b/src/aipro-cli.ts index 0ed5fe7..164ad7b 100644 --- a/src/aipro-cli.ts +++ b/src/aipro-cli.ts @@ -17,7 +17,7 @@ import { import { getRawBillFlow } from "./domains/bill/api.js"; import { approveBill, rejectBill, getTranslatorContext } from "./domains/bill/tools.js"; import { translateBillFlowToMarkdown } from "./domains/bill/translator.js"; -import { VERSION } from "./version.js"; +import { VERSION, formatVersionLabel, getVersionInfo } from "./version.js"; export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; stderr: string; exitCode: number }> { const parsed = parseArgs(rawArgs); @@ -77,8 +77,8 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; if (command === "version" || command === "v" || booleanOption(parsed.options, ["version", "v"])) { return { stdout: jsonMode - ? printJson({ name: "hose-aipro", version: VERSION }) + "\n" - : `hose-aipro v${VERSION}\n`, + ? printJson(getVersionInfo("hose-aipro")) + "\n" + : `${formatVersionLabel("hose-aipro")}\n`, stderr: "", exitCode: 0, }; diff --git a/src/cli/printer.ts b/src/cli/printer.ts index ee7bcbd..50b6d14 100644 --- a/src/cli/printer.ts +++ b/src/cli/printer.ts @@ -1,5 +1,5 @@ import { writeFileSync } from "node:fs"; -import { VERSION } from "../version.js"; +import { formatVersionLabel } from "../version.js"; import type { OutputOptions } from "./types.js"; import { PayloadTooLargeError } from "./errors.js"; import { renderScopedHelp } from "./help.js"; @@ -115,7 +115,7 @@ export function printTable( export function printHelp(target: string[] = []): string { if (target.length) return renderScopedHelp(target); return ` -合思/易快报企业级 CLI 工具 (hose-use) v${VERSION} +合思/易快报企业级 CLI 工具 (${formatVersionLabel("hose-use")}) 用法: hose-use <命令域> <子命令> [参数] [选项] diff --git a/src/cli/runner.test.ts b/src/cli/runner.test.ts index b83911d..dd273e5 100644 --- a/src/cli/runner.test.ts +++ b/src/cli/runner.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "bun:test"; import { runCli } from "./runner.js"; -import { VERSION } from "../version.js"; +import { VERSION_INFO, formatVersionLabel } from "../version.js"; describe("CLI runner - version and help aliases", () => { const versionVariants = [ @@ -25,7 +25,7 @@ describe("CLI runner - version and help aliases", () => { const result = await runCli(args); expect(result.exitCode).toBe(0); expect(result.stderr).toBe(""); - expect(result.stdout).toBe(`hose-use v${VERSION}\n`); + expect(result.stdout).toBe(`${formatVersionLabel("hose-use")}\n`); }); } @@ -50,7 +50,7 @@ describe("CLI runner - version and help aliases", () => { const result = await runCli(args); expect(result.exitCode).toBe(0); expect(result.stderr).toBe(""); - expect(result.stdout).toContain(`合思/易快报企业级 CLI 工具 (hose-use) v${VERSION}`); + expect(result.stdout).toContain(`合思/易快报企业级 CLI 工具 (${formatVersionLabel("hose-use")})`); expect(result.stdout).toContain("用法:"); }); } @@ -94,7 +94,7 @@ describe("CLI runner - version and help aliases", () => { const version = await runCli(["version", "--json"]); expect(JSON.parse(help.stdout).help).toContain("workflow -"); - expect(JSON.parse(version.stdout)).toEqual({ name: "hose-use", version: VERSION }); + expect(JSON.parse(version.stdout)).toEqual(VERSION_INFO); expect(help.stderr).toBe(""); expect(version.stderr).toBe(""); }); diff --git a/src/cli/runner.ts b/src/cli/runner.ts index 5a188b3..17d1d22 100644 --- a/src/cli/runner.ts +++ b/src/cli/runner.ts @@ -1,4 +1,4 @@ -import { VERSION } from "../version.js"; +import { VERSION_INFO, formatVersionLabel } from "../version.js"; import { parseArgs, stringOption, booleanOption, outputOptions } from "./parser.js"; import { printHelp, printJson, redactSensitiveText } from "./printer.js"; import { classifyCliError } from "./errors.js"; @@ -144,7 +144,7 @@ async function dispatchCli( if (isVersionRequested(parsed)) { return { - stdout: jsonMode ? printJson({ name: "hose-use", version: VERSION }) : `hose-use v${VERSION}\n`, + stdout: jsonMode ? printJson(VERSION_INFO) : `${formatVersionLabel("hose-use")}\n`, stderr: "", exitCode: 0, }; diff --git a/src/version.test.ts b/src/version.test.ts new file mode 100644 index 0000000..7308a72 --- /dev/null +++ b/src/version.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, test } from "bun:test"; +import { formatDevVersion, parseGitDescribe, resolveVersionInfo } from "./version.js"; + +describe("build version metadata", () => { + test("parses tagged commits and dirty state", () => { + expect(parseGitDescribe("v0.8.6-3-gabc1234")).toMatchObject({ + baseVersion: "0.8.6", + commitsAhead: 3, + commit: "abc1234", + dirty: false, + }); + expect(parseGitDescribe("v0.8.6-dirty")).toMatchObject({ + baseVersion: "0.8.6", + commitsAhead: 0, + dirty: true, + }); + }); + + test("formats a visible semver development version", () => { + expect(formatDevVersion("0.8.6", 2, "abc1234", false)).toBe("0.8.6-dev.2+gabc1234"); + expect(formatDevVersion("0.8.6", 2, "abc1234", true)).toBe("0.8.6-dev.2+gabc1234.dirty"); + }); + + test("uses compile-time release metadata when a binary provides it", () => { + expect(resolveVersionInfo({ + env: { + HOSE_BUILD_VERSION: "0.8.6", + HOSE_BUILD_CHANNEL: "release", + HOSE_BUILD_IS_RELEASE: "true", + }, + })).toEqual({ name: "hose-use", version: "0.8.6", channel: "release", isRelease: true }); + }); + + test("includes git metadata in development mode", () => { + const info = resolveVersionInfo({ + env: { + HOSE_BUILD_VERSION: "0.8.6-dev.2+gabc1234", + HOSE_BUILD_CHANNEL: "dev", + HOSE_BUILD_IS_RELEASE: "false", + HOSE_BUILD_GIT_BASE: "0.8.6", + HOSE_BUILD_GIT_COMMITS_AHEAD: "2", + HOSE_BUILD_GIT_COMMIT: "abc1234", + HOSE_BUILD_GIT_DIRTY: "true", + HOSE_BUILD_GIT_DESCRIBE: "v0.8.6-2-gabc1234-dirty", + }, + }); + expect(info).toEqual({ + name: "hose-use", + version: "0.8.6-dev.2+gabc1234", + channel: "dev", + isRelease: false, + git: { + baseVersion: "0.8.6", + commitsAhead: 2, + commit: "abc1234", + dirty: true, + describe: "v0.8.6-2-gabc1234-dirty", + }, + }); + }); +}); diff --git a/src/version.ts b/src/version.ts index 9e2e3a4..03027eb 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1 +1,126 @@ -export const VERSION = "0.8.6"; +import { spawnSync } from "node:child_process"; +import packageJson from "../package.json" with { type: "json" }; + +export interface GitBuildInfo { + baseVersion: string; + commitsAhead: number; + commit: string; + dirty: boolean; + describe: string; +} + +export interface VersionInfo { + name: "hose-use" | "hose-aipro"; + version: string; + channel: "release" | "dev"; + isRelease: boolean; + git?: GitBuildInfo; +} + +export function parseGitDescribe(output: string, fallbackVersion = packageJson.version): GitBuildInfo | null { + const trimmed = output.trim(); + if (!trimmed) return null; + + const dirty = trimmed.endsWith("-dirty"); + const clean = dirty ? trimmed.slice(0, -6) : trimmed; + const longMatch = clean.match(/^v?(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?)-(\d+)-g([0-9a-f]+)$/); + if (longMatch && longMatch[1] && longMatch[2] && longMatch[3]) { + return { baseVersion: longMatch[1], commitsAhead: Number.parseInt(longMatch[2], 10), commit: longMatch[3], dirty, describe: trimmed }; + } + + const tagMatch = clean.match(/^v?(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?)$/); + if (tagMatch && tagMatch[1]) { + return { baseVersion: tagMatch[1], commitsAhead: 0, commit: "", dirty, describe: trimmed }; + } + + const commitMatch = clean.match(/^([0-9a-f]{7,40})$/); + if (commitMatch && commitMatch[1]) { + return { baseVersion: fallbackVersion, commitsAhead: 0, commit: commitMatch[1], dirty, describe: trimmed }; + } + return null; +} + +export function formatDevVersion(baseVersion: string, commitsAhead: number, commit: string, dirty: boolean): string { + const dirtySuffix = dirty ? ".dirty" : ""; + const commitSuffix = commit ? `+g${commit}${dirtySuffix}` : dirty ? "+dirty" : ""; + return `${baseVersion}-dev.${commitsAhead}${commitSuffix}`; +} + +export function resolveVersionInfo(options?: { env?: Record; cwd?: string }): VersionInfo { + const customEnv = options?.env; + // Keep these as direct property accesses: Bun can inline them into compiled binaries. + const buildVersion = customEnv?.HOSE_BUILD_VERSION ?? process.env.HOSE_BUILD_VERSION; + const buildIsRelease = customEnv?.HOSE_BUILD_IS_RELEASE ?? process.env.HOSE_BUILD_IS_RELEASE; + const buildChannel = customEnv?.HOSE_BUILD_CHANNEL ?? process.env.HOSE_BUILD_CHANNEL; + const buildGitBase = customEnv?.HOSE_BUILD_GIT_BASE ?? process.env.HOSE_BUILD_GIT_BASE; + const buildGitCommitsAhead = customEnv?.HOSE_BUILD_GIT_COMMITS_AHEAD ?? process.env.HOSE_BUILD_GIT_COMMITS_AHEAD; + const buildGitCommit = customEnv?.HOSE_BUILD_GIT_COMMIT ?? process.env.HOSE_BUILD_GIT_COMMIT; + const buildGitDirty = customEnv?.HOSE_BUILD_GIT_DIRTY ?? process.env.HOSE_BUILD_GIT_DIRTY; + const buildGitDescribe = customEnv?.HOSE_BUILD_GIT_DESCRIBE ?? process.env.HOSE_BUILD_GIT_DESCRIBE; + const forceRelease = customEnv?.HOSE_FORCE_RELEASE ?? process.env.HOSE_FORCE_RELEASE; + + if (buildVersion) { + const isRelease = buildIsRelease === "true"; + const channel = (buildChannel as "release" | "dev") || (isRelease ? "release" : "dev"); + const result: VersionInfo = { name: "hose-use", version: buildVersion, channel, isRelease }; + if (buildGitBase) { + result.git = { + baseVersion: buildGitBase, + commitsAhead: Number.parseInt(buildGitCommitsAhead || "0", 10), + commit: buildGitCommit || "", + dirty: buildGitDirty === "true", + describe: buildGitDescribe || buildVersion, + }; + } + return result; + } + + if (buildIsRelease === "true" || forceRelease === "1") { + return { name: "hose-use", version: packageJson.version, channel: "release", isRelease: true }; + } + + try { + const result = spawnSync("git", ["describe", "--tags", "--long", "--dirty", "--always"], { + cwd: options?.cwd, + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + }); + if (result.status === 0 && result.stdout) { + const gitInfo = parseGitDescribe(result.stdout.trim(), packageJson.version); + if (gitInfo) { + if (!gitInfo.commit) { + const revision = spawnSync("git", ["rev-parse", "--short", "HEAD"], { + cwd: options?.cwd, + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + }); + if (revision.status === 0 && revision.stdout) gitInfo.commit = revision.stdout.trim(); + } + return { + name: "hose-use", + version: formatDevVersion(gitInfo.baseVersion, gitInfo.commitsAhead, gitInfo.commit, gitInfo.dirty), + channel: "dev", + isRelease: false, + git: gitInfo, + }; + } + } + } catch { + // Fall back below if git is unavailable. + } + + return { name: "hose-use", version: `${packageJson.version}-dev.0+local`, channel: "dev", isRelease: false }; +} + +export const VERSION_INFO = resolveVersionInfo(); +export const VERSION = VERSION_INFO.version; +export const IS_RELEASE = VERSION_INFO.isRelease; +export const CHANNEL = VERSION_INFO.channel; + +export function getVersionInfo(name: VersionInfo["name"]): VersionInfo { + return { ...VERSION_INFO, name }; +} + +export function formatVersionLabel(name: VersionInfo["name"]): string { + return `${name} v${VERSION}${CHANNEL === "dev" ? " [DEV BUILD]" : ""}`; +}