@mesh-tech/mesh-cli
Version:
CLI for Mesh platform development utilities
76 lines (75 loc) • 2.42 kB
JavaScript
import { execFileSync } from "child_process";
import * as fs from "fs";
import * as path from "path";
import { fileURLToPath } from "url";
export function detectRuntimeMode(modulePath) {
return modulePath.split(/[\\/]/).includes("dist") ? "dist" : "source";
}
export function formatVersionLine(info) {
if (info.mode === "source") {
const at = [info.commit, info.builtAt].filter(Boolean).join(" ");
return `${info.version} (source${at ? ` @ ${at}` : ""})`;
}
const built = info.builtAt ? ` ${info.builtAt.slice(0, 10)}` : "";
const commit = info.commit ? `, commit ${info.commit}` : "";
const detail = built || commit ? `${built}${commit}` : " — build metadata unavailable";
return `${info.version} (published build${detail})`;
}
function findCliPackageRoot(startDir) {
let dir = startDir;
for (let i = 0; i < 8; i++) {
try {
const pkg = JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf-8"));
if (pkg.name === "@mesh-tech/mesh-cli")
return dir;
}
catch {
}
const parent = path.dirname(dir);
if (parent === dir)
break;
dir = parent;
}
return null;
}
export function resolveCliRuntime(opts) {
const vcs = opts?.vcs ?? true;
const here = path.dirname(fileURLToPath(import.meta.url));
const mode = detectRuntimeMode(here);
const root = findCliPackageRoot(here);
let version = "0.0.0";
if (root) {
try {
version = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf-8")).version ?? version;
}
catch {
}
}
const info = { version, mode };
if (!root)
return info;
if (mode === "dist") {
try {
const meta = JSON.parse(fs.readFileSync(path.join(root, "dist", "build-info.json"), "utf-8"));
info.commit = meta.commit;
info.builtAt = meta.builtAt;
}
catch {
}
return info;
}
if (!vcs)
return info;
try {
const git = (args) => execFileSync("git", args, {
cwd: root,
encoding: "utf-8",
stdio: ["ignore", "pipe", "pipe"],
}).trim();
info.commit = git(["rev-parse", "--short", "HEAD"]);
info.builtAt = git(["log", "-1", "--format=%cs"]);
}
catch {
}
return info;
}