generated from stagas/ts
/
index.ts
92 lines (78 loc) · 2.43 KB
/
index.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import * as fs from 'fs'
import { diffString } from 'json-diff'
import * as path from 'path'
const read = (name: string) => fs.readFileSync(name, 'utf8')
const readJson = (name: string) => JSON.parse(read(name))
const write = (name: string, data: string) => {
fs.mkdirSync(path.dirname(name), { recursive: true })
fs.writeFileSync(name, data, 'utf8')
}
const writeJson = (name: string, data: any) => write(name, JSON.stringify(data, null, 2) + '\n')
const copy = (data: any) => JSON.parse(JSON.stringify(data))
const sort = (data: any) => {
const sorted = Object.fromEntries(
Object.entries(data).sort(([a]: any, [b]: any) => (a > b ? 1 : -1))
)
for (const key in data) delete data[key]
Object.assign(data, sorted)
return data
}
export const pullConfigs = (remote: string, local: string) => {
const assign = Object.assign
const omit = (obj: Record<string, any>, keys: string[]): Record<string, any> => {
const result = Object.assign({}, obj)
for (const key of keys) delete result[key]
return result
}
const pick = (obj: Record<string, any>, keys: string[]): Record<string, any> => {
const result: Record<string, any> = {}
for (const key of keys) result[key] = obj[key]
return result
}
const fail = (file: string, res: Response) => {
console.log('failed:', file, res.status, res.statusText)
}
const merge = async (file: string, replacer?: (prev: any, next: any) => void) => {
const res = await fetch(remote + file)
if (!res.ok) return fail(file, res)
const next = (await res.json()) as any
let prev = {}
try {
prev = readJson(local + file)
} catch {
//
}
const old = copy(prev)
if (replacer) {
replacer(prev, next)
} else {
assign(prev, next)
}
const diff = diffString(old, prev)
if (diff.length) {
console.log('merging:', file)
console.log(diff)
writeJson(local + file, prev)
}
}
const replace = async (file: string) => {
const res = await fetch(remote + file)
if (!res.ok) return fail(file, res)
const next = await res.text()
let msg = 'replacing:'
let prev = ''
try {
prev = read(local + file)
} catch (error) {
if ((error as any).code === 'ENOENT') {
msg = 'adding:'
}
}
if (prev !== next) {
console.log(msg, file)
write(local + file, next)
}
}
return { assign, omit, pick, sort, merge, replace }
}
export default pullConfigs