Skip to content

Commit 926341b

Browse files
committed
Improve argument parser in npx command
1 parent b27ea93 commit 926341b

1 file changed

Lines changed: 31 additions & 17 deletions

File tree

bin/mpp.js

Lines changed: 31 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -58,37 +58,51 @@ var udlPath = packagePath + '/udl';
5858

5959
/*
6060
* Parse arguments passed from user command input.
61+
* "-f" can only be passed at first or last argument.
62+
* "-l/-h/-v" can only be passed at first argument.
6163
* @param {Array<string>} args - Arguments from Node's `process.argv.slice(2)`.
6264
* @param {Array<string>} buildinThemes - Basically the theme names in <config/>.
65+
* @return {Object} - The parsed object passing to build steps.
6366
*/
6467
var parseArgs = function(args, buildinThemes) {
6568
var options = {
6669
themeNames: [],
67-
force: false
70+
shouldContinue: false,
71+
isForce: false
6872
};
69-
// Loop the arguments.
70-
var arg;
71-
for (var i = 0; i < args.length; i++) {
72-
arg = args[i];
73-
if (arg === '-l' || arg === '--list') {
73+
// Parse the first argument. Quit asap if user put a proper flag.
74+
var firstArg = args[0];
75+
switch (firstArg) {
76+
case '-l': case '--list':
7477
console.log(buildinThemes.join('\n'));
75-
break;
76-
}
77-
if (arg === '-v' || arg === '--version') {
78+
return options;
79+
case '-v': case '--version':
7880
console.log(version);
79-
break;
80-
}
81-
if (arg === '-h' || arg === '--help') {
81+
return options;
82+
case '-h': case '--help':
8283
console.log(usageMsg.join('\n'));
83-
break;
84-
}
84+
return options;
85+
}
86+
// Loop all arguments. Match the theme names, otherwise the program should quits.
87+
var arg;
88+
for (var i = 0; i < args.length; i++) {
89+
arg = args[i];
8590
if (arg === '-f' || arg === '--force') {
86-
console.log('Warning! In force mode, any existing file(s) will be overwritten.\n');
87-
options.force = true;
88-
} else {
91+
if (i === 0 || i === args.length - 1) {
92+
console.log('Warning! In force mode, any existing file(s) will be overwritten.\n');
93+
options.isForce = true;
94+
} else {
95+
console.log('arg[' + i + ']: You pass the \"' + arg + '\" flag in wrong position. Quit for safety.');
96+
return options;
97+
}
98+
} else if (buildinThemes.indexOf(arg) >= 0) {
8999
options.themeNames.push(arg);
100+
} else {
101+
console.log('arg[' + i + ']: ' + 'Unsupported option \"' + arg + '\" or combination of options.');
102+
return options;
90103
}
91104
}
105+
options.shouldContinue = true;
92106
return options;
93107
};
94108

0 commit comments

Comments
 (0)