Files
ember-market-frontend/lib/git-utils.ts
2025-04-06 16:08:19 +01:00

99 lines
3.0 KiB
TypeScript

/**
* Git utility to load commit hash in both development and production environments
*/
interface GitInfo {
commitHash: string;
buildTime: string;
}
let cachedGitInfo: GitInfo | null = null;
/**
* Gets the current git commit hash from various sources
* - First tries to read directly from the Git hash file in Docker
* - Then tries environment variable (from Docker)
* - Then tries the JSON file created by our build script
* - Returns "dev" if nothing is available
*/
export async function getGitCommitInfo(): Promise<GitInfo> {
// Return cached value if available
if (cachedGitInfo) {
return cachedGitInfo;
}
// In Docker or server, try to read the hash file directly first (most reliable method)
if (typeof window === 'undefined') {
try {
const fs = require('fs');
// Check for Docker-specific git hash file
const dockerGitHashPath = '/app/git_commit_sha';
if (fs.existsSync(dockerGitHashPath)) {
const hash = fs.readFileSync(dockerGitHashPath, 'utf8').trim();
console.log(`Read git hash from file: ${hash}`);
const gitInfo: GitInfo = {
commitHash: hash,
buildTime: new Date().toISOString(),
};
cachedGitInfo = gitInfo;
return gitInfo;
}
} catch (error) {
console.warn('Could not read git hash from Docker file', error);
}
}
// Then, check if we have the env variable
if (process.env.GIT_COMMIT_SHA) {
// Check if it's the literal string, which is an error case
if (process.env.GIT_COMMIT_SHA.includes('$(cat')) {
console.warn('GIT_COMMIT_SHA contains a shell command instead of the actual hash');
} else {
const gitInfo: GitInfo = {
commitHash: process.env.GIT_COMMIT_SHA,
buildTime: new Date().toISOString(),
};
cachedGitInfo = gitInfo;
return gitInfo;
}
}
// In the browser, fetch from the public directory
if (typeof window !== 'undefined') {
try {
const response = await fetch('/git-info.json');
if (response.ok) {
const gitInfo: GitInfo = await response.json();
cachedGitInfo = gitInfo;
return gitInfo;
}
} catch (error) {
console.warn('Could not fetch git info from public directory', error);
}
} else {
// On the server (during local development), try to load from the static directory
try {
// We use dynamic import to avoid bundling this in the client build
const fs = require('fs');
const path = require('path');
const gitInfoPath = path.join(process.cwd(), 'public', 'git-info.json');
if (fs.existsSync(gitInfoPath)) {
const gitInfo: GitInfo = JSON.parse(fs.readFileSync(gitInfoPath, 'utf8'));
cachedGitInfo = gitInfo;
return gitInfo;
}
} catch (error) {
console.warn('Could not read git info from file system', error);
}
}
// Default if nothing else works
const defaultGitInfo: GitInfo = {
commitHash: 'development',
buildTime: new Date().toISOString(),
};
return defaultGitInfo;
}