blog.hangerthem.com/utils/git.ts
2026-08-03 17:54:08 +02:00

55 lines
1.4 KiB
TypeScript

/**
* Get the current git commit hash.
* @returns The current git commit hash, or null if it cannot be determined.
*/
export async function getGitCommitHash(): Promise<string | null> {
if (process.env.GIT_COMMIT_HASH) {
return process.env.GIT_COMMIT_HASH
}
try {
const { exec } = await import('child_process')
const hash = await new Promise<string>((res, rej) => {
exec('git rev-parse HEAD', (err, stdout) => (err ? rej(err) : res(stdout.trim())))
})
return hash
} catch {
return null
}
}
/**
* Get the git origin URL.
* @returns The git origin URL, or null if it cannot be determined.
*/
export async function getGitOriginUrl(): Promise<string | null> {
const envUrl = process.env.GIT_ORIGIN_URL
if (envUrl) return normalizeGitUrl(envUrl)
try {
const { exec } = await import('child_process')
const url = await new Promise<string>((res, rej) => {
exec('git config --get remote.origin.url', (err, stdout) =>
err ? rej(err) : res(stdout.trim()),
)
})
return normalizeGitUrl(url)
} catch {
return null
}
}
/**
* Normalize a git URL to a standard format.
* @param url The git URL to normalize.
* @returns The normalized git URL.
*/
function normalizeGitUrl(url: string): string {
if (url.startsWith('ssh://')) {
return url
.replace(/^ssh:\/\/git@/, 'https://')
.replace(/\.git$/, '')
.replace(/:\d+/, '')
}
return url
}