import { execSync } from 'node:child_process' export function gitStatusEnv() { const PREV_COMMIT = execSync('git fetch && git rev-parse HEAD').toString().slice(0, 7) const GIT_STATUS = execSync('git status').toString() const modifications = (GIT_STATUS.includes('modified:') && !GIT_STATUS.includes('HEAD detached')) ? '+M' : '' let aheadOfOrigin = '' if (GIT_STATUS.includes('up to date with')) { aheadOfOrigin = '✓' } if (GIT_STATUS.includes('diverged')) { aheadOfOrigin = 'D' } else if (GIT_STATUS.includes('is ahead')) { // https://regex101.com/r/MwRFCd/1 aheadOfOrigin = `A${GIT_STATUS.match(/ahead(.*)(by \d)/)?.[2]?.split(' ')?.[1] || '?'}` } else if (GIT_STATUS.includes('is behind')) { aheadOfOrigin = `B${GIT_STATUS.match(/behind(.*)(by \d)/)?.[2]?.split(' ')?.[1] || '?'}` } const GIT_STATUS_INFO = aheadOfOrigin + modifications console.log('previous commit hash:', PREV_COMMIT) console.log('status:', GIT_STATUS) console.log('status info:', GIT_STATUS_INFO) return { PREV_COMMIT, GIT_STATUS, GIT_STATUS_INFO } } export const gitHMR = { name: 'git-hmr-updates', async handleHotUpdate({ server, file, modules, read }) { try { const { PREV_COMMIT, GIT_STATUS_INFO } = gitStatusEnv() console.log({ GIT_STATUS_INFO, modules }) const dataObject = { PREV_COMMIT, GIT_STATUS_INFO, } const customHMRevt = { type: 'custom', event: 'git:hmr', data: dataObject, } server.ws.send(customHMRevt) } catch (error) { console.error('[git-hmr] error', error) } return modules }, }