Update git-utils.ts

This commit is contained in:
NotII
2025-04-06 16:08:19 +01:00
parent e40828d4f0
commit a5f46d68f0

View File

@@ -11,7 +11,8 @@ let cachedGitInfo: GitInfo | null = null;
/** /**
* Gets the current git commit hash from various sources * Gets the current git commit hash from various sources
* - First tries environment variable (from Docker) * - 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 * - Then tries the JSON file created by our build script
* - Returns "dev" if nothing is available * - Returns "dev" if nothing is available
*/ */
@@ -21,26 +22,16 @@ export async function getGitCommitInfo(): Promise<GitInfo> {
return cachedGitInfo; return cachedGitInfo;
} }
// First, check if we have the env variable (from Docker) // In Docker or server, try to read the hash file directly first (most reliable method)
if (process.env.GIT_COMMIT_SHA) {
const gitInfo: GitInfo = {
commitHash: process.env.GIT_COMMIT_SHA,
buildTime: new Date().toISOString(),
};
cachedGitInfo = gitInfo;
return gitInfo;
}
// In Docker, the hash might be stored in a file at /app/git_commit_sha
if (typeof window === 'undefined') { if (typeof window === 'undefined') {
try { try {
const fs = require('fs'); const fs = require('fs');
const path = require('path');
// Check for Docker-specific git hash file // Check for Docker-specific git hash file
const dockerGitHashPath = '/app/git_commit_sha'; const dockerGitHashPath = '/app/git_commit_sha';
if (fs.existsSync(dockerGitHashPath)) { if (fs.existsSync(dockerGitHashPath)) {
const hash = fs.readFileSync(dockerGitHashPath, 'utf8').trim(); const hash = fs.readFileSync(dockerGitHashPath, 'utf8').trim();
console.log(`Read git hash from file: ${hash}`);
const gitInfo: GitInfo = { const gitInfo: GitInfo = {
commitHash: hash, commitHash: hash,
buildTime: new Date().toISOString(), buildTime: new Date().toISOString(),
@@ -53,6 +44,21 @@ export async function getGitCommitInfo(): Promise<GitInfo> {
} }
} }
// 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 // In the browser, fetch from the public directory
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
try { try {