Skip to content

Commit

Permalink
add escape option to .parse
Browse files Browse the repository at this point in the history
  • Loading branch information
okdistribute committed Mar 16, 2016
1 parent 88c9b82 commit 4d400e7
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 8 deletions.
15 changes: 8 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ for (var i = 0; i < 4; i++) {
TOKEN += (Math.pow(16,8)*Math.random()).toString(16);
}

exports.parse = function (s, env) {
var mapped = parse(s, env);
exports.parse = function (s, env, opts) {
var mapped = parse(s, env, opts);
if (typeof env !== 'function') return mapped;
return reduce(mapped, function (acc, s) {
if (typeof s === 'object') return acc.concat(s);
Expand All @@ -49,15 +49,16 @@ exports.parse = function (s, env) {
}, []);
};

function parse (s, env) {
function parse (s, env, opts) {
var chunker = new RegExp([
'(' + CONTROL + ')', // control chars
'(' + BAREWORD + '|' + SINGLE_QUOTE + '|' + DOUBLE_QUOTE + ')*'
].join('|'), 'g');
var match = filter(s.match(chunker), Boolean);

if (!match) return [];
if (!env) env = {};
if (!opts) opts = {};
return map(match, function (s) {
if (RegExp('^' + CONTROL + '$').test(s)) {
return { op: s };
Expand All @@ -76,8 +77,8 @@ function parse (s, env) {
// "allonetoken")
var SQ = "'";
var DQ = '"';
var BS = '\\';
var DS = '$';
var BS = opts.escape || '\\';
var quote = false;
var varname = false;
var esc = false;
Expand Down Expand Up @@ -168,11 +169,11 @@ function parse (s, env) {
return getVar(null, '', varname);
}
});

function getVar (_, pre, key) {
var r = typeof env === 'function' ? env(key) : env[key];
if (r === undefined) r = '';

if (typeof r === 'object') {
return pre + TOKEN + json.stringify(r) + TOKEN;
}
Expand Down
14 changes: 14 additions & 0 deletions readme.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,20 @@ output
[ 'beep', '--boop=/home/robot' ]
```

## parse with custom escape charcter

``` js
var parse = require('shell-quote').parse;
var xs = parse('beep --boop="$PWD"', { PWD: '/home/robot' }, { escape: '^' });
console.dir(xs);
```

output

```
[ 'beep', '--boop=/home/robot' ]
```

## parsing shell operators

``` js
Expand Down
3 changes: 2 additions & 1 deletion test/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ test('parse shell commands', function (t) {
t.same(parse('a\\ b"c d"\\ e f'), [ 'a bc d e', 'f' ]);
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.end();
});

0 comments on commit 4d400e7

Please sign in to comment.