From 7bcd90e222eb0ec046d5fbf4eb16f323bd1f8e16 Mon Sep 17 00:00:00 2001 From: Jordan Harband Date: Thu, 6 Apr 2023 15:21:57 -0700 Subject: [PATCH] [Fix] properly support the `escape` option Fixes #5 --- README.md | 4 ++-- parse.js | 11 ++++++----- test/parse.js | 1 + 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index c2f6e08..6b545c5 100644 --- a/README.md +++ b/README.md @@ -57,14 +57,14 @@ output ``` js var parse = require('shell-quote/parse'); -var xs = parse('beep --boop="$PWD"', { PWD: '/home/robot' }, { escape: '^' }); +var xs = parse('beep ^--boop="$PWD"', { PWD: '/home/robot' }, { escape: '^' }); console.dir(xs); ``` output ``` -[ 'beep', '--boop=/home/robot' ] +[ 'beep --boop=/home/robot' ] ``` ## parsing shell operators diff --git a/parse.js b/parse.js index d534e5e..078c3b1 100644 --- a/parse.js +++ b/parse.js @@ -7,7 +7,6 @@ var CONTROL = '(?:' + [ ].join('|') + ')'; var controlRE = new RegExp('^' + CONTROL + '$'); var META = '|&;()<> \\t'; -var BAREWORD = '(\\\\[\'"' + META + ']|[^\\s\'"' + META + '])+'; var SINGLE_QUOTE = '"((\\\\"|[^"])*?)"'; var DOUBLE_QUOTE = '\'((\\\\\'|[^\'])*?)\''; var hash = /^#$/; @@ -24,6 +23,12 @@ for (var i = 0; i < 4; i++) { var startsWithToken = new RegExp('^' + TOKEN); function parseInternal(s, env, opts) { + if (!opts) { + opts = {}; + } + var BS = opts.escape || '\\'; + var BAREWORD = '(\\' + BS + '[\'"' + META + ']|[^\\s\'"' + META + '])+'; + var chunker = new RegExp([ '(' + CONTROL + ')', // control chars '(' + BAREWORD + '|' + SINGLE_QUOTE + '|' + DOUBLE_QUOTE + ')*' @@ -36,9 +41,6 @@ function parseInternal(s, env, opts) { if (!env) { env = {}; } - if (!opts) { - opts = {}; - } var commented = false; @@ -75,7 +77,6 @@ function parseInternal(s, env, opts) { // 4. quote context can switch mid-token if there is no whitespace // between the two quote contexts (e.g. all'one'"token" parses as // "allonetoken") - var BS = opts.escape || '\\'; var quote = false; var esc = false; var out = ''; diff --git a/test/parse.js b/test/parse.js index 9c78cbf..1dd7f58 100644 --- a/test/parse.js +++ b/test/parse.js @@ -20,6 +20,7 @@ test('parse shell commands', function (t) { t.same(parse('a\\ b"c d"\\ e\'f g\' h'), ['a bc d ef g', 'h']); t.same(parse("x \"bl'a\"'h'"), ['x', "bl'ah"]); t.same(parse("x bl^'a^'h'", {}, { escape: '^' }), ['x', "bl'a'h"]); + t.same(parse('abcH def', {}, { escape: 'H' }), ['abc def']); t.end(); });