Skip to content

Instantly share code, notes, and snippets.

@giautm
Created June 14, 2018 08:09
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save giautm/742aef6fe3c1bede9e4a92e71715a1c2 to your computer and use it in GitHub Desktop.
Save giautm/742aef6fe3c1bede9e4a92e71715a1c2 to your computer and use it in GitHub Desktop.
Next.JS Build-ID with last git commit
const fs = require('fs')
const path = require('path')
const { execFile } = require('child_process')
function lastCommitId(dir) {
return new Promise((resolve, reject) => {
const gitArgs = [
`--git-dir=${path.join(dir, '.git')}`,
`--work-tree=${dir}`,
'rev-parse',
'HEAD',
]
execFile('git', gitArgs, (err, stdout, stderr) => {
if (err) return reject(err)
if (stderr) return reject(String(stderr).trim())
if (stdout) return resolve(String(stdout).trim())
return reject(new Error(`No output from command: git ${gitArgs.join(' ')}`))
})
})
}
function findDotGit(inputDir, maxAttempts = 999) {
// inputDir may not be the project root so look for .git dir in parent dirs too
let dir = inputDir
const { root } = path.parse(dir)
let attempts = 0 // protect against infinite tight loop if libs misbehave
while (dir !== root && attempts < maxAttempts) {
attempts += 1
try {
fs.accessSync(path.join(dir, '.git'), (fs.constants || fs).R_OK)
break
} catch (_) {
dir = path.dirname(dir)
}
}
if (dir === root || attempts >= maxAttempts) {
dir = inputDir
}
return dir
}
function determineBuildId({ dir } = { dir: __dirname }) {
return lastCommitId(findDotGit(dir))
}
module.exports = {
determineBuildId,
findDotGit,
lastCommitId,
}
const { determineBuildId } = require('./build-id')
module.exports = {
generateBuildId: async () => {
const buildId = await determineBuildId()
console.log(`> Build ID: ${buildId}`)
return buildId
},
}
@themegabyte
Copy link

How would you access this in your code? (browser and server). Thank you.

@yakumomutsuki
Copy link

@themegabyte
you can include commit hash if you set below this config

https://nextjs.org/docs/app/api-reference/next-config-js/generateBuildId

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment