forked from pkgxdev/pkgx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.dump.ts
96 lines (84 loc) · 2.59 KB
/
app.dump.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
93
94
95
96
import { useEnv, usePrint } from "hooks"
import { flatmap } from "utils"
import { isPlainObject } from "is_what"
//TODO should read from the shell configuration files to get originals properly
//TODO don’t wait on each print, instead chain the promises to be more time-efficient
interface Parameters {
env: Record<string, string>
shell?: string
}
export default async function dump({ env, shell }: Parameters) {
const { TEA_REWIND, getEnvAsObject } = useEnv();
const { print } = usePrint()
const [set, unset]= (() => {
switch (shell) {
case "elvish":
return [
(name: string, val: string) => `set-env ${name} '${val}'`,
(name: string) => `unset-env ${name}`
]
case "fish":
return [
(name: string, val: string) => `set -gx ${name} '${val}';`,
(name: string) => `set -e ${name};`
]
default:
return [
(name: string, val: string) => `export ${name}='${val}'`,
(name: string) => `unset ${name}`
]
}
})()
const is_env = env['SRCROOT']
if (is_env) {
const oldenv = getEnvAsObject()
// first rewind the env to the original state
if (oldenv['TEA_REWIND']) {
const rewind = JSON.parse(oldenv['TEA_REWIND']) as { revert: Record<string, string>, unset: string[] }
delete oldenv['TEA_REWIND']
for (const key of rewind.unset) {
if (!env[key]) {
await print(unset(key))
}
delete oldenv[key]
}
for (const [key, value] of Object.entries(rewind.revert)) {
if (!env[key]) {
await print(set(key, value))
}
oldenv[key] = value
}
}
// now calculate the new rewind
const TEA_REWIND = (() => {
const revert: Record<string, string> = {}
const unset: string[] = []
for (const key of Object.keys(env)) {
const value = oldenv[key]?.trim()
if (value) {
revert[key] = value
} else {
unset.push(key)
}
}
return JSON.stringify({
revert, unset
})
})()
// print the setters for the new env
for (const [key, value] of Object.entries(env)) {
if (value) await print(set(key, value))
}
await print(set('TEA_REWIND', TEA_REWIND))
} else {
const unwind = flatmap(TEA_REWIND, JSON.parse) as { revert: Record<string, string>, unset: string[] }
if (!isPlainObject(unwind)) return
for (const key of unwind.unset) {
await print(unset(key))
}
for (const [key, value] of Object.entries(unwind.revert)) {
await print(set(key, value))
}
await print(unset('TEA_REWIND'))
}
}