build-metadata.mjs 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. import { execSync } from "node:child_process";
  2. import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
  3. import { createRequire } from "node:module";
  4. import { resolve } from "node:path";
  5. import { fileURLToPath } from "node:url";
  6. const require = createRequire(import.meta.url);
  7. const moduleDir = import.meta.dirname;
  8. function findPackageDir(packageName, startDirs) {
  9. for (const startDir of startDirs) {
  10. let currentDir = resolve(startDir);
  11. while (true) {
  12. const packageJsonPath = resolve(currentDir, "package.json");
  13. if (existsSync(packageJsonPath)) {
  14. try {
  15. const packageJson = readJson(packageJsonPath);
  16. if (packageJson.name === packageName) {
  17. return currentDir;
  18. }
  19. } catch {
  20. // ignore invalid package.json and continue walking up
  21. }
  22. }
  23. const parentDir = resolve(currentDir, "..");
  24. if (parentDir === currentDir) {
  25. break;
  26. }
  27. currentDir = parentDir;
  28. }
  29. }
  30. throw new Error(`Unable to find package directory for ${packageName}`);
  31. }
  32. const desktopDir = findPackageDir("@zcode/desktop", [
  33. moduleDir,
  34. resolve(moduleDir, ".."),
  35. process.cwd(),
  36. ]);
  37. const workspaceDir = resolve(desktopDir, "../..");
  38. const metadataDir = resolve(desktopDir, "out/metadata");
  39. const metadataPath = resolve(metadataDir, "build-meta.json");
  40. function readJson(filePath) {
  41. return JSON.parse(readFileSync(filePath, "utf-8"));
  42. }
  43. function normalizeVersion(version) {
  44. if (typeof version !== "string" || version.length === 0) {
  45. return "unknown";
  46. }
  47. const normalized = version.replace(/^[^\d]*/, "");
  48. return normalized || version;
  49. }
  50. function resolveInstalledPackageVersion(packageName, fallbackVersion) {
  51. try {
  52. const packageJsonPath = require.resolve(`${packageName}/package.json`, { paths: [desktopDir] });
  53. return normalizeVersion(readJson(packageJsonPath).version);
  54. } catch {
  55. return normalizeVersion(fallbackVersion);
  56. }
  57. }
  58. function resolveCommitId() {
  59. try {
  60. return execSync("git rev-parse --short=8 HEAD", {
  61. cwd: workspaceDir,
  62. stdio: ["ignore", "pipe", "ignore"],
  63. })
  64. .toString()
  65. .trim();
  66. } catch {
  67. return process.env.ZCODE_COMMIT ?? "unknown";
  68. }
  69. }
  70. export function collectBuildMetadata() {
  71. const rootPackageJson = readJson(resolve(workspaceDir, "package.json"));
  72. const desktopPackageJson = readJson(resolve(desktopDir, "package.json"));
  73. return {
  74. appVersion: normalizeVersion(rootPackageJson.version),
  75. buildCommitId: resolveCommitId(),
  76. buildTime: new Date().toISOString(),
  77. electronBuilderVersion: resolveInstalledPackageVersion(
  78. "electron-builder",
  79. desktopPackageJson.devDependencies?.["electron-builder"],
  80. ),
  81. };
  82. }
  83. export function readBuildMetadata() {
  84. if (!existsSync(metadataPath)) {
  85. return null;
  86. }
  87. try {
  88. return readJson(metadataPath);
  89. } catch {
  90. return null;
  91. }
  92. }
  93. export function getBuildMetadata() {
  94. return readBuildMetadata() ?? collectBuildMetadata();
  95. }
  96. export function writeBuildMetadata() {
  97. // About 之前分别在 tsup、vite 里各算一份 commit 和时间。
  98. // 问题原因:两次构建是独立进程,时间点天然不一致;后面再打包时,最终安装包里展示的信息也不一定对应同一次产物。
  99. // 这里先统一落盘成 build-meta.json,再让构建和运行时都复用同一份数据,保证 about 可追溯。
  100. const metadata = collectBuildMetadata();
  101. mkdirSync(metadataDir, { recursive: true });
  102. writeFileSync(metadataPath, `${JSON.stringify(metadata, null, 2)}\n`, "utf-8");
  103. return metadata;
  104. }
  105. export function getBuildMetadataPath() {
  106. return metadataPath;
  107. }
  108. const entryFilePath = process.argv[1] ? resolve(process.argv[1]) : null;
  109. const currentFilePath = fileURLToPath(import.meta.url);
  110. if (entryFilePath === currentFilePath) {
  111. const metadata = writeBuildMetadata();
  112. process.stdout.write(`[build-meta] wrote ${metadataPath}\n`);
  113. process.stdout.write(
  114. `[build-meta] commit=${metadata.buildCommitId} time=${metadata.buildTime}\n`,
  115. );
  116. }