Skip to content
stevedonovan edited this page Feb 17, 2013 · 1 revision

This is compact command-line parser, based on the same idea as the Lapp framework; deduce information about known flags (and whether they take values) from the usage text.

-- flags.moonM={}
append =table.insert
usage_ =nilM.quit =(msg)->if msg then io.stderr\write msg,'\n'if usage_
print'\n', usage_
os.exit1
glob =(args)->if#args ==1and args[1]\match '[%*%?]'-- no shell globbing, it's Windows :(
wildcard = args[1]table.remove args,1
f =io.popen'dir /b '..wildcard
path = wildcard\match [[(.-\)[^\]+$]]or''for line in f\lines!
append args, path..line
f\close!
M.parse =(usage)->
usage_ = usage
takes_value, known_flags ={},{}for line in usage\gmatch '[^\n]+'
flag,rest = line\match '^%s+%-(%S+)%s+(.*)'if flag
known_flags[flag]=true
takes_value[flag]= rest\match '^<'
quit =(flag,msg)->M.quit '-'..flag..''..msg
args,i ={},1while i <=#arg
a,val = arg[i]
flag = a\match '^%-(.+)'if flag
ifnot known_flags[flag]then quit flag,'unknown flag'if takes_value[flag]
i +=1if i >#arg or arg[i]\match '^%-[^%-]'
quit flag,'needs a value'
val = arg[i]
args[flag]= val ortrueelse
append args, a
i +=1
glob args
return args
returnM

Here is an exxample of its usage, which also uses Pretty Table Dumper

flags =require'flags'
tstring =require'moondump'
usage =[[usage: lglob [options] <scripts> -t means "tolerant"; defined globals are ok (implies -g and -l) -g accept globals defined in a module -l call require() to track module exports -w <file>, whitelist file containing symbol={entries..}, which are added to _G.]]
args = flags.parse usage
dump =(t)->print tstring t
dump args

Here is some sample output. (Note that it will detect unknown flags and complain if a flag is not given a value.)

scratch$ moon test-flags.moon -w wlist -t
{w:"wlist",t:true}

Clone this wiki locally