build-info.mjs 3 KB
/**
 * 构建指纹 —— 「线上跑的到底是哪个 commit?」
 *
 * 没有这个文件时,排查线上问题只能靠比对产物里某个 js 的 hash 去猜,或者去问
 * 「刚才谁发的」。产物一旦离开构建机就断了溯源链,而部署根是覆盖式写入、不留历史。
 *
 * 落点:产物根 BUILD_INFO.json(随产物一起上传,运维和排障都看得到)。
 * 内容刻意只放「定位版本需要的最小集合」,不放依赖清单 —— 那是 lock 文件的事。
 *
 * ⚠ 它会公开可访问(静态站的根目录没有鉴权)。里面没有密钥,但有 commit sha 与分支名;
 *   若不希望公开,可在 nginx 里 `location = /BUILD_INFO.json { deny all; }`,
 *   或上传时排除该文件(此时本文件只作为本地产物留痕)。
 */
import fs from 'node:fs';
import path from 'node:path';
import { spawnSync } from 'node:child_process';

/** 读 git 元信息。不在 git 仓库里(CI 的浅检出、打好的 tar 包)就返回 null,不阻断发布。 */
function gitInfo(root) {
  const run = (args) => {
    const r = spawnSync('git', args, { cwd: root, encoding: 'utf8' });
    return r.status === 0 ? String(r.stdout).trim() : '';
  };
  const sha = run(['rev-parse', 'HEAD']);
  if (!sha) return null;
  return {
    sha,
    shortSha: sha.slice(0, 7),
    branch: run(['rev-parse', '--abbrev-ref', 'HEAD']) || '(detached)',
    // 有未提交改动时标出来:这类产物无法用 sha 完整还原,排障时是关键信息
    dirty: run(['status', '--porcelain']).length > 0,
  };
}

/**
 * @param {object} o
 * @param {string} o.root        仓库根(读 git 用)
 * @param {string} o.outRoot     产物根(写文件用)
 * @param {string} odistVersion 本次发布版本号
 * @param {string[]} o.apps      本次发版的子系统
 * @param {string|null} o.hostRel 主壳版本目录相对路径,未发主壳传 null
 * @param {string|null} [o.manifestVersion] 产物清单里的 version 字段
 * @param {string} [o.source]    发布入口(release:spec / release:all / release:affected / release)
 * @returns {object} 写入的内容
 */
export function writeBuildInfo(o) {
  const { root, outRoot, releaseVersion, apps, hostRel, manifestVersion, source } = o;
  const info = {
    releaseVersion,
    builtAt: new Date().toISOString(),
    source: source ?? null,
    apps: [...apps].sort(),
    host: hostRel ?? null,
    manifestVersion: manifestVersion ?? null,
    git: gitInfo(root),
    node: process.version,
    platform: `${process.platform}-${process.arch}`,
  };
  fs.mkdirSync(outRoot, { recursive: true });
  fs.writeFileSync(
    path.join(outRoot, 'BUILD_INFO.json'),
    `${JSON.stringify(info, null, 2)}\n`,
    'utf8',
  );
  return info;
}

/** 读产物里的清单 version(清单缺失或损坏时返回 null,不影响发布)。 */
export function manifestVersionOf(manifestFile) {
  try {
    return JSON.parse(fs.readFileSync(manifestFile, 'utf8')).version ?? null;
  } catch {
    return null;
  }
}