-
Notifications
You must be signed in to change notification settings - Fork 6
/
utils.ts
77 lines (66 loc) · 2.11 KB
/
utils.ts
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
76
77
import './mc-versions/types.d.ts'
import * as path from 'https://deno.land/[email protected]/path/mod.ts'
const versionDataDir = path.resolve('mc-versions', 'data')
export async function spawn(program: string, args: string[], opts: Omit<Deno.RunOptions, 'cmd'> = {}) {
const cp = Deno.run({...opts, cmd: [program, ...args]})
return await cp.status()
}
export async function spawnText(cmd: string[]) {
const cp = Deno.run({cmd, stdout: 'piped'})
const text = new TextDecoder().decode(await cp.output())
const {code} = await cp.status()
if (code) throw code
return text
}
const ERAS: Record<string, string> = {
inf: 'infdev',
in: 'indev',
af: 'april-fools',
a: 'alpha',
'server-a': 'alpha',
b: 'beta',
combat: 'combat',
c: 'classic',
'server-c': 'classic',
rd: 'pre-classic'
}
export async function getEra(version: string, data?: VersionData) {
for (const key in ERAS) {
if (version.startsWith(key)) return ERAS[key]
}
const releaseTarget = (data || await getVersionDetails(version)).releaseTarget
if (releaseTarget && /^\d+\.\d+/.test(releaseTarget)) {
const [, era] = releaseTarget.match(/^(\d+\.\d+)/) as string[]
return era
}
return releaseTarget as string
}
export async function getVersionDetails(id: string): Promise<VersionData> {
return JSON.parse(await Deno.readTextFile(path.resolve(versionDataDir, 'version', id + '.json')))
}
export function byKey<T>(array: T[], key: (v: T) => string): Record<string, T> {
const obj: Record<string, T> = {}
for (const v of array) {
obj[key(v)] = v
}
return obj
}
export function multiMapAdd<V>(map: Record<string, V[]>, key: string, value: V) {
let vs = map[key]
if (!vs) map[key] = vs = []
vs.push(value)
}
export function getOrPut<V>(map: Record<string, V>, k: string, v: V) {
const prev = map[k]
if (prev) return prev
return map[k] = v
}
export async function exists(path: string) {
try {
await Deno.stat(path)
return true
} catch (e) {
if (e instanceof Deno.errors.NotFound) return false
throw e
}
}