|
| 1 | +/* eslint-disable no-console */ |
| 2 | +const fs = require("fs"); |
| 3 | +const path = require("path"); |
| 4 | +const { execSync } = require("child_process"); |
| 5 | + |
| 6 | +function shortSha(sha) { |
| 7 | + if (!sha || typeof sha !== "string") return null; |
| 8 | + const cleaned = sha.trim(); |
| 9 | + if (!cleaned) return null; |
| 10 | + return cleaned.slice(0, 8); |
| 11 | +} |
| 12 | + |
| 13 | +function getVersionTag() { |
| 14 | + const envCandidates = [ |
| 15 | + process.env.GIT_COMMIT, |
| 16 | + process.env.COMMIT, |
| 17 | + process.env.SOURCE_COMMIT, |
| 18 | + process.env.VERCEL_GIT_COMMIT_SHA, |
| 19 | + process.env.GITHUB_SHA, |
| 20 | + process.env.CF_PAGES_COMMIT_SHA, |
| 21 | + ]; |
| 22 | + for (const candidate of envCandidates) { |
| 23 | + const s = shortSha(candidate); |
| 24 | + if (s) return s; |
| 25 | + } |
| 26 | + |
| 27 | + try { |
| 28 | + const sha = execSync("git rev-parse --short HEAD", { |
| 29 | + stdio: ["ignore", "pipe", "ignore"], |
| 30 | + }) |
| 31 | + .toString() |
| 32 | + .trim(); |
| 33 | + if (sha) return sha; |
| 34 | + } catch (_) { |
| 35 | + // ignore |
| 36 | + } |
| 37 | + |
| 38 | + // Final fallback: time-based tag, stable within the build |
| 39 | + return `dev-${Math.floor(Date.now() / 1000).toString(36)}`; |
| 40 | +} |
| 41 | + |
| 42 | +function ensureDir(dirPath) { |
| 43 | + if (!fs.existsSync(dirPath)) { |
| 44 | + fs.mkdirSync(dirPath, { recursive: true }); |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +function writeEnvJs(targetPath, version) { |
| 49 | + const contents = `// Auto-generated by scripts/gen-env.js |
| 50 | +export const version = "${version}"; |
| 51 | +export function now() { |
| 52 | + if (typeof performance !== "undefined" && typeof performance.now === "function") { |
| 53 | + return performance.now(); |
| 54 | + } |
| 55 | + return Date.now(); |
| 56 | +} |
| 57 | +export default { version, now }; |
| 58 | +`; |
| 59 | + fs.writeFileSync(targetPath, contents, "utf8"); |
| 60 | +} |
| 61 | + |
| 62 | +function main() { |
| 63 | + const repoRoot = path.resolve(__dirname, ".."); |
| 64 | + const pkgDir = path.join(repoRoot, "pkg"); |
| 65 | + ensureDir(pkgDir); |
| 66 | + |
| 67 | + const version = getVersionTag(); |
| 68 | + const target = path.join(pkgDir, "env.js"); |
| 69 | + writeEnvJs(target, version); |
| 70 | + console.log( |
| 71 | + `[gen-env] wrote ${path.relative(repoRoot, target)} with version: ${version}` |
| 72 | + ); |
| 73 | +} |
| 74 | + |
| 75 | +main(); |
0 commit comments