Node.js 引数のパーサ一段階目
いったん key=value の配列に直したほうが扱いやすそうだったので その形に変換する
- value がないのは
[key, null]
- key がないのは
[null, value]
--
と-
単体は[null, "--"]
か[null, "-"]
- いまのとこ boolean 型の key 指定がないので
--ab 10
で 10 は単体にならない- 3 つ目にフラグで argv の要素が別れていたかもたせる?
import parseFirst from "./parseFirst" | |
parseFirst(["-a", "1", "--bc-d", "3", "--ae", "--bb=a31", "-r=100", "-zxyz", "-", "qq", "--", "89", "-1", "-u7"]) | |
/* | |
[ | |
["a", "1"], | |
["bc-d", "3"], | |
["ae", null], | |
["bb", "a31"], | |
["r", "100"], | |
["z", null], | |
["x", null], | |
["y", null], | |
["z", null], | |
[null, "-"], | |
[null, "qq"], | |
[null, "--"], | |
[null, "89"], | |
["1", null], | |
["u", "7"], | |
] | |
*/ |
export default function(args){ | |
const result = { | |
flush(){ | |
if(this.buf){ | |
this.values.push([this.buf, null]) | |
this.buf = null | |
} | |
}, | |
append(key, value = null){ | |
this.values.push([key, value]) | |
}, | |
keep(key){ | |
if(this.buf){ | |
throw new Error("already has keeped value.") | |
} | |
this.buf = key | |
}, | |
single(value){ | |
if(this.buf){ | |
this.values.push([this.buf, value]) | |
this.buf = null | |
}else{ | |
this.values.push([null, value]) | |
} | |
}, | |
buf: null, | |
values: [], | |
} | |
for(const arg of args){ | |
if(arg === "--" || arg === "-"){ | |
result.flush() | |
result.append(null, arg) | |
}else if(arg.startsWith("--")){ | |
result.flush() | |
const str = arg.substr(2) | |
if(str.includes("=")){ | |
const [, key, value] = str.match(/^([^=]*)=?(.*)$/) | |
result.append(key, value) | |
}else{ | |
result.keep(str) | |
} | |
}else if(arg.startsWith("-")){ | |
result.flush() | |
const str = arg.substr(1) | |
const [, chars, body] = str.match(/^(.[a-zA-Z]*)=?(.*)$/) | |
const last = chars.substr(-1) | |
for(const char of chars.slice(0, -1)){ | |
result.append(char) | |
} | |
if(body){ | |
result.append(last, body) | |
}else{ | |
result.keep(last) | |
} | |
}else{ | |
result.single(arg) | |
} | |
} | |
result.flush() | |
return result.values | |
} |