-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathgitInfo.ts
More file actions
75 lines (64 loc) · 2.44 KB
/
Copy pathgitInfo.ts
File metadata and controls
75 lines (64 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import { execFileSync } from 'child_process';
import { resolve } from 'path';
import type { Plugin } from 'vite';
type Options = {
appEnv: string;
head: string;
isDevelopmentMode: boolean;
rootDir: string;
};
const GIT_INFO_MODULE_ID = 'virtual:git-info';
const RESOLVED_GIT_INFO_MODULE_ID = `\0${GIT_INFO_MODULE_ID}`;
export default function buildGitInfoPlugin({
appEnv,
head,
isDevelopmentMode,
rootDir,
}: Options): Plugin {
return {
name: 'git-info',
resolveId(id) {
return id === GIT_INFO_MODULE_ID ? RESOLVED_GIT_INFO_MODULE_ID : undefined;
},
load(id) {
if (id !== RESOLVED_GIT_INFO_MODULE_ID) return undefined;
const branch = head || getGitValue(rootDir, ['rev-parse', '--abbrev-ref', 'HEAD']);
const commit = getGitValue(rootDir, ['rev-parse', '--short=7', 'HEAD']);
const shouldDisplayOnlyCommit = appEnv === 'staging' || !branch || branch === 'HEAD';
const appRevision = shouldDisplayOnlyCommit ? commit : `${branch}#${commit}`;
return `export const APP_REVISION = ${JSON.stringify(appRevision)};`;
},
configureServer(server) {
if (!isDevelopmentMode || head) return;
let watchPaths = buildWatchPaths(rootDir);
if (!watchPaths.length) return;
server.watcher.add(watchPaths);
server.watcher.on('change', (changedPath) => {
if (!watchPaths.includes(changedPath)) return;
const module = server.moduleGraph.getModuleById(RESOLVED_GIT_INFO_MODULE_ID);
if (module) server.moduleGraph.invalidateModule(module);
watchPaths = buildWatchPaths(rootDir);
server.watcher.add(watchPaths);
server.ws.send({ type: 'full-reload' });
});
},
};
}
function buildWatchPaths(rootDir: string) {
const headPath = getGitValue(rootDir, ['rev-parse', '--git-path', 'HEAD']);
const packedRefsPath = getGitValue(rootDir, ['rev-parse', '--git-path', 'packed-refs']);
const branch = getGitValue(rootDir, ['symbolic-ref', '--quiet', 'HEAD']);
const branchPath = branch ? getGitValue(rootDir, ['rev-parse', '--git-path', branch]) : '';
return Array.from(new Set([
headPath ? resolve(rootDir, headPath) : '',
packedRefsPath ? resolve(rootDir, packedRefsPath) : '',
branchPath ? resolve(rootDir, branchPath) : '',
].filter(Boolean)));
}
function getGitValue(rootDir: string, args: string[]) {
try {
return execFileSync('git', args, { cwd: rootDir, encoding: 'utf8' }).trim();
} catch {
return '';
}
}