Created
June 13, 2012 13:13
-
-
Save fracek/2923969 to your computer and use it in GitHub Desktop.
parse command
This file contains 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
#!/usr/bin/env node | |
/* | |
* Given a string return a map in the form { cmd: 'args', cmd2: 'args' } | |
*/ | |
function parseCommand(s) { | |
m = {} | |
state = 0; | |
currentcmd = ''; | |
currentargs = ''; | |
for (i = 0; i < s.length; i++) { | |
c = s[i]; | |
//console.log(c, ' ', state); | |
switch (state) { | |
case 0: | |
if (c != ' ') { | |
state = 1; | |
currentcmd += c; | |
} | |
break; | |
case 1: | |
if (c == ' ') { | |
state = 2; | |
} else { | |
currentcmd += c; | |
} | |
break; | |
case 2: | |
if (c != ' ') { | |
state = 3; | |
currentargs += c; | |
} | |
break; | |
case 3: | |
if (c == '\n') { | |
state = 0; | |
m[currentcmd] = currentargs; | |
currentcmd = ''; | |
currentargs = ''; | |
} else { | |
currentargs += c; | |
} | |
break; | |
} | |
} | |
m[currentcmd] = currentargs; | |
return m; | |
} | |
var cmds = ['mono program.exe arg1 arg2', | |
' mono program.exe arg1 arg2', | |
'cmd1 arg1 arg2 arg3\n cmd2 arg11 arg12 etc ']; | |
cmds.forEach(function(c) { | |
console.log(c, parseCommand(c)); | |
}); | |
/* | |
* Requires node.js | |
* $ node parse.js | |
* mono program.exe arg1 arg2 { mono: 'program.exe arg1 arg2' } | |
* mono program.exe arg1 arg2 { mono: 'program.exe arg1 arg2' } | |
* cmd1 arg1 arg2 arg3 | |
* cmd2 arg11 arg12 etc { cmd1: 'arg1 arg2 arg3', cmd2: 'arg11 arg12 etc ' } | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment