|
| 1 | +import { execSync } from 'child_process'; |
| 2 | + |
| 3 | +/** |
| 4 | + * Resolve build-time provenance for an app: version, git commit, git branch and build time. |
| 5 | + * |
| 6 | + * Git values prefer the GIT_COMMIT / GIT_BRANCH environment variables — set as Docker |
| 7 | + * build args in CI, where the `.git` directory is intentionally not copied into the image — |
| 8 | + * and fall back to running git locally for `npm run dev` / local builds. When neither is |
| 9 | + * available the value is the literal string 'unknown', which the UI hides. |
| 10 | + * |
| 11 | + * @param {string} version - the app's own package.json version |
| 12 | + * @returns {{ version: string, gitCommit: string, gitBranch: string, buildTime: string }} |
| 13 | + */ |
| 14 | +export function getBuildInfo(version) { |
| 15 | + let gitCommit = process.env.GIT_COMMIT?.trim().slice(0, 7) || 'unknown'; |
| 16 | + if (gitCommit === 'unknown') { |
| 17 | + try { |
| 18 | + gitCommit = execSync('git rev-parse --short HEAD').toString().trim(); |
| 19 | + } catch (error) { |
| 20 | + console.warn('Could not get git commit hash:', error); |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + let gitBranch = process.env.GIT_BRANCH?.trim() || 'unknown'; |
| 25 | + if (gitBranch === 'unknown') { |
| 26 | + try { |
| 27 | + gitBranch = execSync('git rev-parse --abbrev-ref HEAD').toString().trim(); |
| 28 | + } catch (error) { |
| 29 | + console.warn('Could not get git branch:', error); |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + return { version, gitCommit, gitBranch, buildTime: new Date().toISOString() }; |
| 34 | +} |
| 35 | + |
| 36 | +/** |
| 37 | + * Build the Vite `define` map for the build-info globals (`__APP_VERSION__`, |
| 38 | + * `__GIT_COMMIT__`, `__GIT_BRANCH__`, `__BUILD_TIME__`). Spread into a Vite config's |
| 39 | + * `define` block so the values are inlined at build time. |
| 40 | + * |
| 41 | + * @param {string} version - the app's own package.json version |
| 42 | + * @returns {Record<string, string>} |
| 43 | + */ |
| 44 | +export function buildInfoDefine(version) { |
| 45 | + const info = getBuildInfo(version); |
| 46 | + return { |
| 47 | + __APP_VERSION__: JSON.stringify(info.version), |
| 48 | + __GIT_COMMIT__: JSON.stringify(info.gitCommit), |
| 49 | + __GIT_BRANCH__: JSON.stringify(info.gitBranch), |
| 50 | + __BUILD_TIME__: JSON.stringify(info.buildTime) |
| 51 | + }; |
| 52 | +} |
0 commit comments