soapbox/src/utils/code-compiletime.ts

53 lines
1.3 KiB
TypeScript
Raw Normal View History

2023-09-13 17:04:17 +00:00
import { execSync } from 'node:child_process';
import pkg from '../../package.json';
2021-03-30 17:43:45 +00:00
const { CI_COMMIT_TAG, CI_COMMIT_REF_NAME, CI_COMMIT_SHA } = process.env;
2023-09-13 17:04:17 +00:00
const shortRepoName = (url: string): string => new URL(url).pathname.substring(1);
const trimHash = (hash: string): string => hash.substring(0, 7);
2021-03-30 17:43:45 +00:00
2023-09-13 17:04:17 +00:00
const tryGit = (cmd: string): string | undefined => {
2022-05-01 20:07:55 +00:00
try {
return String(execSync(cmd));
} catch (e) {
return undefined;
2022-05-01 20:07:55 +00:00
}
};
2023-10-13 02:51:06 +00:00
const version = (pkg: { version: string }): string => {
// Try to discern from GitLab CI first
if (CI_COMMIT_TAG === `v${pkg.version}` || CI_COMMIT_REF_NAME === 'stable') {
return pkg.version;
}
if (typeof CI_COMMIT_SHA === 'string') {
return `${pkg.version}-${trimHash(CI_COMMIT_SHA)}`;
}
// Fall back to git directly
2022-05-01 20:07:55 +00:00
const head = tryGit('git rev-parse HEAD');
const tag = tryGit(`git rev-parse v${pkg.version}`);
2022-05-01 20:07:55 +00:00
if (head && head !== tag) return `${pkg.version}-${trimHash(head)}`;
// Fall back to version in package.json
return pkg.version;
};
2023-09-20 21:02:36 +00:00
const code = {
name: pkg.name,
displayName: pkg.displayName,
url: pkg.repository.url,
repository: shortRepoName(pkg.repository.url),
version: version(pkg),
homepage: pkg.homepage,
ref: CI_COMMIT_TAG || CI_COMMIT_SHA || tryGit('git rev-parse HEAD'),
};
export type Code = typeof code;
2023-09-13 17:04:17 +00:00
export default () => ({
2023-09-20 21:02:36 +00:00
data: code,
2023-09-13 17:04:17 +00:00
});