1 | import os from 'os';
|
2 |
|
3 | const OS_WIN = 'win32';
|
4 |
|
5 | // 对命令字符串进行shell转义
|
6 | export function escape(arg = ''): string {
|
7 | // windows保持原样
|
8 | if (os.platform() === OS_WIN) {
|
9 | return arg;
|
10 | }
|
11 | let newArg = arg;
|
12 | if (newArg.startsWith('\'') && newArg.endsWith('\'')) {
|
13 | newArg = newArg.substring(1, newArg.length - 1);
|
14 | }
|
15 | if (/[^A-Za-z0-9_/:=-]/.test(newArg)) {
|
16 | newArg = '\'' + newArg.replace(/'/g, '\'\\\'\'') + '\'';
|
17 | newArg = newArg.replace(/^(?:'')+/g, '') // 消除重复的单引号
|
18 | .replace(/\\'''/g, '\\\''); // 如果有两个转义单引号,则删除非转义单引号
|
19 | }
|
20 | return newArg;
|
21 | }
|