-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshellbox.ts
70 lines (68 loc) · 1.86 KB
/
shellbox.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
/**
* @file shellbox.ts
* @description Utilities to sandbox subprocess commands
* @copyright 2020 Brandon Kalinowski (brandonkal)
* @license MIT
*/
const envarNameRe = /^[a-zA-Z_]\w*$/
/**
* Builds a clean command using `env -i`.
* Only provided environment variables will be available to the running command.
* Environment variables are escaped, but you should ensure the provided cmd is trusted.
* @param cmd Array of strings specifying command to execute. Will be escaped for single quotes.
* @param env Desired environment.
* PATH and HOME from the parent process will automatically be set if not provided.
*/
export function buildCleanCommand(
cmd: string[],
env: Record<string, string>,
pwd?: string
) {
let needsHome = true
let needsPath = true
let needsPwd = typeof pwd === 'string'
const envars = Object.entries(env).map(([key, value]) => {
if (!envarNameRe.exec(key)) {
throw new Error(`Invalid environment variable name: ${key}`)
}
if (key === 'PATH') needsPath = false
if (key === 'HOME') needsHome = false
if (key === 'PWD' && pwd) {
needsPwd = false
return `PWD=${pwd}`
}
return `${key}=${value}`
})
if (needsHome) {
const home = Deno.env.get('HOME')
if (home) {
envars.push(`HOME=${home}`)
}
}
if (needsPath) {
const path = Deno.env.get('PATH')
if (path) {
envars.push(`PATH=${path}`)
}
}
if (needsPwd && pwd) {
envars.push(`PWD=${pwd}`)
}
const args = ['env', '-i', ...envars, ...cmd]
return args
}
/**
* @returns a shell compatible format
*/
export function shellquote(s: string) {
if (/[^A-Za-z0-9_\/:=-]/.test(s)) {
s = "'" + s.replace(/'/g, "'\\''") + "'"
s = s
.replace(/^(?:'')+/g, '') // unduplicate single-quote at the beginning
.replace(/\\'''/g, "\\'") // remove non-escaped single-quote if there are enclosed between 2 escaped
}
if (!s.startsWith("'")) {
s = "'" + s + "'"
}
return s
}