-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathcmd.js
More file actions
75 lines (69 loc) · 2.17 KB
/
cmd.js
File metadata and controls
75 lines (69 loc) · 2.17 KB
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
/**
* @overview Provides functionality for the Windows Command Prompt.
* @license MPL-2.0
*/
import RegExp from "@ericcornelissen/lregexp";
/**
* Returns a function to escape arguments for use in CMD for the given use case.
*
* @returns {function(string): string} A function to escape arguments.
*/
export function getEscapeFunction() {
const controls = new RegExp("[\0\u0008\r\u001B\u009B]", "g");
const newlines = new RegExp("\n", "g");
const specials = new RegExp("([%&<>^|])", "g");
const quotes = new RegExp('"', "g");
const backslashes = new RegExp("(^|[^\\\\])(\\\\*)\0", "g");
return (arg) =>
arg
.replace(controls, "")
.replace(newlines, " ")
.replace(specials, "^$1")
.replace(quotes, '\0\\^"')
.replace(backslashes, "$1$2$2");
}
/**
* Escape an argument for use in CMD when the argument is being quoted.
*
* @returns {function(string): string} A function to escape arguments.
*/
function getQuoteEscapeFunction() {
const controls = new RegExp("[\0\u0008\r\u001B\u009B]", "g");
const newlines = new RegExp("\n", "g");
const quotes = new RegExp('"', "g");
const specials = new RegExp("([%&<>^|])", "g");
const backslashes = new RegExp('(^|[^\\\\])(\\\\+)("|$)', "g");
return (arg) =>
arg
.replace(controls, "")
.replace(newlines, " ")
.replace(quotes, '""')
.replace(specials, '"^$1"')
.replace(backslashes, "$1$2$2$3");
}
/**
* Quotes an argument for use in CMD.
*
* @param {string} arg The argument to quote.
* @returns {string} The quoted argument.
*/
function quoteArg(arg) {
return `"${arg}"`;
}
/**
* Returns a pair of functions to escape and quote arguments for use in CMD.
*
* @returns {(function(string): string)[]} A function pair to escape & quote arguments.
*/
export function getQuoteFunction() {
return [getQuoteEscapeFunction(), quoteArg];
}
/**
* Returns a function to protect against flag injection for CMD.
*
* @returns {function(string): string} A function to protect against flag injection.
*/
export function getFlagProtectionFunction() {
const leadingHyphensAndSlashes = new RegExp("^(?:-+|/+)");
return (arg) => arg.replace(leadingHyphensAndSlashes, "");
}