-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathversion.ts
More file actions
58 lines (48 loc) · 1.18 KB
/
version.ts
File metadata and controls
58 lines (48 loc) · 1.18 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
import type { Version } from '@pi-base/core'
import { execFile } from 'node:child_process'
import { resolve } from 'node:path'
import { promisify } from 'node:util'
import { readFile } from './fs.js'
function refName(raw: string) {
const match = /refs\/heads\/([^\n]+)/.exec(raw)
return match && match[1]
}
export async function find(root = '.') {
let version = await fromRepo(root)
if (version) {
return version
}
version = fromEnv()
if (version) {
return version
}
throw new Error('Could not determine bundle version')
}
async function fromRepo(root = '.'): Promise<Version | undefined> {
const contents = await readFile(resolve(root, '.git', 'HEAD')).catch(() => {})
if (!contents) {
return
}
const head = refName(contents)
if (head) {
const { stdout } = await promisify(execFile)('git', ['rev-parse', 'HEAD'], {
cwd: root,
})
return {
ref: head,
sha: stdout.trim(),
}
}
}
function fromEnv(env: NodeJS.ProcessEnv = process.env): Version | undefined {
if (!env.GITHUB_REF) {
return
}
if (!env.GITHUB_SHA) {
return
}
return {
ref: refName(env.GITHUB_REF) || 'unknown',
sha: env.GITHUB_SHA,
}
}