Merge pull request #74 from yunyingk/feat/dev-version-visibility
feat: make development builds visibly identifiable
This commit is contained in:
13 files changed
+285
-35
No files matched your search
@@ -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 .` 代替,它会留下不会随源码更新的旧副本。
|
||||
|
||||
|
||||
@@ -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) {
|
||||
|
||||
+5
-10
@@ -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");
|
||||
|
||||
@@ -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"])],
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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" };
|
||||
}
|
||||
|
||||
@@ -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("");
|
||||
|
||||
+3
-3
@@ -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,
|
||||
};
|
||||
|
||||
+2
-2
@@ -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 <命令域> <子命令> [参数] [选项]
|
||||
|
||||
@@ -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("");
|
||||
});
|
||||
|
||||
+2
-2
@@ -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,
|
||||
};
|
||||
|
||||
@@ -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",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
+126
-1
@@ -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<string, string | undefined>; 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]" : ""}`;
|
||||
}
|
||||
Reference in new issue
Block a user