|
| 1 | +import Git from 'simple-git' |
| 2 | +import { isDevelopment } from 'std-env' |
| 3 | +import * as process from 'node:process' |
| 4 | + |
| 5 | +export { version } from '../package.json' |
| 6 | + |
| 7 | +/** |
| 8 | + * Environment variable `PULL_REQUEST` provided by Netlify. |
| 9 | + * @see {@link https://docs.netlify.com/build/configure-builds/environment-variables/#git-metadata} |
| 10 | + * |
| 11 | + * Whether triggered by a GitHub PR |
| 12 | + */ |
| 13 | +export const isPR = process.env.PULL_REQUEST === 'true' |
| 14 | + |
| 15 | +/** |
| 16 | + * Environment variable `BRANCH` provided by Netlify. |
| 17 | + * @see {@link https://docs.netlify.com/build/configure-builds/environment-variables/#git-metadata} |
| 18 | + * |
| 19 | + * Git branch |
| 20 | + */ |
| 21 | +export const gitBranch = process.env.BRANCH |
| 22 | + |
| 23 | +/** |
| 24 | + * Environment variable `CONTEXT` provided by Netlify. |
| 25 | + * @see {@link https://docs.netlify.com/build/configure-builds/environment-variables/#build-metadata} |
| 26 | + * |
| 27 | + * Whether triggered by PR, `deploy-preview` or `dev`. |
| 28 | + */ |
| 29 | +export const isPreview = |
| 30 | + isPR || process.env.CONTEXT === 'deploy-preview' || process.env.CONTEXT === 'dev' |
| 31 | + |
| 32 | +const git = Git() |
| 33 | +export async function getGitInfo() { |
| 34 | + let branch |
| 35 | + try { |
| 36 | + branch = gitBranch || (await git.revparse(['--abbrev-ref', 'HEAD'])) |
| 37 | + } catch { |
| 38 | + branch = 'unknown' |
| 39 | + } |
| 40 | + |
| 41 | + let commit |
| 42 | + try { |
| 43 | + commit = await git.revparse(['HEAD']) |
| 44 | + } catch { |
| 45 | + commit = 'unknown' |
| 46 | + } |
| 47 | + |
| 48 | + let shortCommit |
| 49 | + try { |
| 50 | + shortCommit = await git.revparse(['--short=7', 'HEAD']) |
| 51 | + } catch { |
| 52 | + shortCommit = 'unknown' |
| 53 | + } |
| 54 | + |
| 55 | + return { branch, commit, shortCommit } |
| 56 | +} |
| 57 | + |
| 58 | +export async function getEnv() { |
| 59 | + const { commit, shortCommit, branch } = await getGitInfo() |
| 60 | + const env = isDevelopment |
| 61 | + ? 'dev' |
| 62 | + : isPreview |
| 63 | + ? 'preview' |
| 64 | + : branch === 'main' |
| 65 | + ? 'canary' |
| 66 | + : 'release' |
| 67 | + return { commit, shortCommit, branch, env } as const |
| 68 | +} |
0 commit comments