Created
November 27, 2018 18:16
-
-
Save simonwep/061eb3fd572afde489e924040280a215 to your computer and use it in GitHub Desktop.
Function to parse cli commands
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Parses a cli command, e.g. "mov a b -p all 'C:/user/me'" | |
* Example result of `mov -p 1000 -a "f and b" "/s/d/l" -l`: | |
* | |
* { | |
* "cmd": "mov", | |
* "params": { | |
* "p": "1000", | |
* "a": "f and b", | |
* "l": "" | |
* }, | |
* "vals": [ | |
* "/s/d/l" | |
* ] | |
* } | |
* | |
* @param str | |
* @returns {{cmd, params, vals: string[]}} | |
*/ | |
function parseCliCommand(str) { | |
// Find first param and additional values | |
const [, cmd, rest] = str.match(/^(.*?)( .*|$)$/); | |
const params = {}; | |
// Match all params with some magic regexp | |
const paramsRegex = /'.*?'|".*?"|(?<= )-([\w]+)( *(["' ])(.+?)(\3|$)|)/g; | |
let matchRest = ''; | |
for (let match, index = 0; (match = paramsRegex.exec(rest));) { | |
/** | |
* If the first match is empty a quoted string has been matched | |
* so ignore it. | |
*/ | |
if (!match[1]) { | |
continue; | |
} | |
// Append not-matched string parts (later we will extract values from it) | |
matchRest += rest.substring(index, match.index); | |
index = match.index + match[0].length; | |
// Save prop | |
params[match[1]] = match[4] || ''; | |
} | |
return { | |
cmd, params, | |
// Extract values from match rest | |
vals: matchRest.match(/".*?"|'.*?'|.+/g) | |
.map(v => { | |
v = v.trim(); | |
// Check if value is in quotes and remove these if so | |
if (v[0] === `'` || v[0] === `"`) { | |
return v.substring(1, v.length - 1); | |
} | |
return v; | |
}) | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment