Skip to content
This repository has been archived by the owner on Apr 22, 2023. It is now read-only.

Commit

Permalink
cli: make argument to -p optional
Browse files Browse the repository at this point in the history
  • Loading branch information
bnoordhuis committed Sep 4, 2012
1 parent f03c320 commit 83b1dda
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
22 changes: 20 additions & 2 deletions src/node.cc
Expand Up @@ -2389,13 +2389,31 @@ static void ParseArgs(int argc, char **argv) {
strcmp(arg, "--print") == 0 ||
strcmp(arg, "-pe") == 0 ||
strcmp(arg, "-p") == 0) {
if (argc <= i + 1) {
bool is_eval = strchr(arg, 'e') != NULL;
bool is_print = strchr(arg, 'p') != NULL;

// argument to -p and --print is optional
if (is_eval == true && i + 1 >= argc) {
fprintf(stderr, "Error: %s requires an argument\n", arg);
exit(1);
}
print_eval = print_eval || strchr(arg, 'p') != NULL;

print_eval = print_eval || is_print;
argv[i] = const_cast<char*>("");

// --eval, -e and -pe always require an argument
if (is_eval == true) {
eval_string = argv[++i];
continue;
}

// next arg is the expression to evaluate unless it starts with:
// - a dash, then it's another switch
// - "\\-", then it's an escaped expression, drop the backslash
if (argv[i + 1] == NULL) continue;
if (argv[i + 1][0] == '-') continue;
eval_string = argv[++i];
if (strncmp(eval_string, "\\-", 2) == 0) ++eval_string;
} else if (strcmp(arg, "--interactive") == 0 || strcmp(arg, "-i") == 0) {
force_repl = true;
argv[i] = const_cast<char*>("");
Expand Down
8 changes: 7 additions & 1 deletion test/simple/test-cli-eval.js
Expand Up @@ -48,7 +48,7 @@ child.exec(nodejs + ' --eval "console.error(42)"',
});

// assert that the expected output is written to stdout
'--print -pe -p'.split(' ').forEach(function(s) {
['--print', '-p -e', '-pe', '-p'].forEach(function(s) {
var cmd = nodejs + ' ' + s + ' ';

child.exec(cmd + '42',
Expand Down Expand Up @@ -79,3 +79,9 @@ child.exec(nodejs + ' -e ""', function(status, stdout, stderr) {
assert.equal(stdout, '');
assert.equal(stderr, '');
});

// "\\-42" should be interpreted as an escaped expression, not a switch
child.exec(nodejs + ' -p "\\-42"',
function(err, stdout, stderr) {
assert.equal(stdout, '-42\n');
});

0 comments on commit 83b1dda

Please sign in to comment.