28 lines
1.1 KiB
JavaScript
28 lines
1.1 KiB
JavaScript
'use strict';
|
|
|
|
const fs = require('node:fs');
|
|
const path = require('node:path');
|
|
const { execFileSync } = require('node:child_process');
|
|
|
|
const isGitRevision = value => typeof value === 'string' && value.length === 40 && /^[0-9a-f]{40}$/.test(value);
|
|
|
|
function getBuildId(root) {
|
|
// The image's baked revision is authoritative; never accept arbitrary HTML/header text.
|
|
try {
|
|
const baked = fs.readFileSync(path.join(root, 'BUILD_ID'), 'utf8').trim();
|
|
return isGitRevision(baked) ? baked : 'unknown';
|
|
} catch (_) {}
|
|
// Require this checkout's marker, not an unrelated ancestor repository.
|
|
if (!fs.existsSync(path.join(root, '.git'))) return 'unknown';
|
|
try {
|
|
const revision = execFileSync('git', ['-C', root, 'rev-parse', '--verify', 'HEAD^{commit}'], {
|
|
encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'],
|
|
env: Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('GIT_'))),
|
|
}).trim();
|
|
return isGitRevision(revision) ? revision : 'unknown';
|
|
} catch (_) {
|
|
return 'unknown';
|
|
}
|
|
}
|
|
|
|
module.exports = { getBuildId, isGitRevision };
|