{repeat} = require './helpers'
{repeat} = require './helpers'
コマンドラインからオプションフラグを解析するためのシンプルなOptionParserクラス。以下のような用途があります
parser = new OptionParser switches, helpBanner
options = parser.parse process.argv
最初の非オプションはファイル(およびファイルオプション)リストの先頭とみなされ、それ以降のすべての引数は解析されません。
exports.OptionParser = class OptionParser
有効なオプションのリストを、以下の形式で初期化します
[short-flag, long-flag, description]
使用方法に関するヘルプのオプションバナーがあれば、それを添えてください。
constructor: (rules, @banner) ->
@rules = buildRules rules
引数のリストを解析し、指定されたすべてのオプションを持つoptions
オブジェクトを設定して、それを返します。最初以外の非オプション引数は、引数として扱われます。options.arguments
は、残りの引数を含む配列になります。これは、すべてのフラグにコールバックアクションをアタッチできる多くのオプションパーサーよりもシンプルなAPIです。代わりに、オプションオブジェクトの解釈の責任があなたにあります。
parse: (args) ->
options = arguments: []
skippingArgument = no
originalArgs = args
args = normalizeArguments args
for arg, i in args
if skippingArgument
skippingArgument = no
continue
if arg is '--'
pos = originalArgs.indexOf '--'
options.arguments = options.arguments.concat originalArgs[(pos + 1)..]
break
isOption = !!(arg.match(LONG_FLAG) or arg.match(SHORT_FLAG))
CSオプションパーサーは少し変わっています。最初の非オプション引数以降のオプションは非オプション引数そのものとして扱われます
seenNonOptionArg = options.arguments.length > 0
unless seenNonOptionArg
matchedRule = no
for rule in @rules
if rule.shortFlag is arg or rule.longFlag is arg
value = true
if rule.hasArgument
skippingArgument = yes
value = args[i + 1]
options[rule.name] = if rule.isList then (options[rule.name] or []).concat value else value
matchedRule = yes
break
throw new Error "unrecognized option: #{arg}" if isOption and not matchedRule
if seenNonOptionArg or not isOption
options.arguments.push arg
options
このOptionParserのヘルプテキストを返し、すべて有効なオプションをリストして説明します(--help
など)。
help: ->
lines = []
lines.unshift "#{@banner}\n" if @banner
for rule in @rules
spaces = 15 - rule.longFlag.length
spaces = if spaces > 0 then repeat ' ', spaces else ''
letPart = if rule.shortFlag then rule.shortFlag + ', ' else ' '
lines.push ' ' + letPart + rule.longFlag + spaces + rule.description
"\n#{ lines.join('\n') }\n"
オプションフラグに対する正規表現マッチャ―。
LONG_FLAG = /^(--\w[\w\-]*)/
SHORT_FLAG = /^(-\w)$/
MULTI_FLAG = /^-(\w{2,})/
OPTIONAL = /\[(\w+(\*?))\]/
オプションルールリストを作成して返します。オプションのshort-flagが指定されていない場合は、null
を追加してパディングします。
buildRules = (rules) ->
for tuple in rules
tuple.unshift null if tuple.length < 3
buildRule tuple...
-o
short flag、--output [DIR]
long flag、およびオプションの実施内容の説明からルールを作成します。
buildRule = (shortFlag, longFlag, description, options = {}) ->
match = longFlag.match(OPTIONAL)
longFlag = longFlag.match(LONG_FLAG)[1]
{
name: longFlag.substr 2
shortFlag: shortFlag
longFlag: longFlag
description: description
hasArgument: !!(match and match[1])
isList: !!(match and match[2])
}
マージされたフラグを複数のフラグに展開して引数を正規化します。これにより、-wl
を--watch --lint
と同じにすることができます。
normalizeArguments = (args) ->
args = args[..]
result = []
for arg in args
if match = arg.match MULTI_FLAG
result.push '-' + l for l in match[1].split ''
else
result.push arg
result