Commit 33d42c08
33d42c08e6b5Merged
Yukihiro "Matz" Matsumoto <[email protected]> · 8 months ago · 1 file · ~1 modified
Description
Implement minimal OptionParser in lib/optparse.rb
Pure Ruby implementation compilable by Spinel. Supports:
- on(flag, desc, &block) for --flag and --flag=VALUE
- parse!(argv) with in-place argv mutation
- ParseError exception class
- banner=, separator, on_tail (display-only, no-ops)
Co-Authored-By: Claude Opus 4.6 (1M context) [email protected]
Details
- Commit
- 33d42c08e6b5
- Parent
- faa00164f529
lib/optparse.rbmodifiedView file
@@ -1,2 +1,123 @@
11
# Spinel stub: optparse2-
# Placeholder — OptionParser requires full stdlib implementation.2+
#3+
# Minimal OptionParser implementation for Spinel compilation.4+
# Supports the subset of OptionParser used by lrama:5+
# - .on(flag, desc) { |v| ... } (2-4 args with block)6+
# - .banner=7+
# - .separator(text)8+
# - .on_tail(text)9+
# - .parse!(argv)10+
# - OptionParser::ParseError11+
12+
class OptionParser13+
class ParseError14+
def initialize(msg)15+
@message = msg16+
end17+
18+
def message19+
@message20+
end21+
22+
def to_s23+
@message24+
end25+
end26+
27+
def initialize28+
@banner = ""29+
@short_flags = []30+
@long_flags = []31+
@handlers = []32+
@expects_value = []33+
end34+
35+
def banner=(text)36+
@banner = text37+
end38+
39+
def separator(text)40+
end41+
42+
def on_tail(text)43+
end44+
45+
def on(a1, a2, &block)46+
short = ""47+
long = ""48+
has_value = false49+
if a1[0] == "-" && a1[1] == "-"50+
long = a151+
else52+
short = a153+
end54+
if a2[0] == "-" && a2[1] == "-"55+
long = a256+
end57+
if long.include?("=")58+
has_value = true59+
end60+
@short_flags.push(short)61+
@long_flags.push(long)62+
@handlers.push(block)63+
@expects_value.push(has_value)64+
end65+
66+
def parse!(argv)67+
new_argv = []68+
i = 069+
while i < argv.length70+
arg = argv[i]71+
matched = false72+
j = 073+
while j < @handlers.length74+
sf = @short_flags[j]75+
lf = @long_flags[j]76+
ev = @expects_value[j]77+
if ev && lf != ""78+
# extract base flag name before "="79+
eq_pos = lf.index("=")80+
if eq_pos81+
base = lf[0, eq_pos]82+
else83+
base = lf84+
end85+
# --flag=VALUE form86+
if arg.length > base.length && arg[0, base.length] == base && arg[base.length] == "="87+
value = arg[(base.length + 1), (arg.length - base.length - 1)]88+
@handlers[j].call(value)89+
matched = true90+
# --flag VALUE form91+
elsif arg == base92+
i += 193+
if i < argv.length94+
@handlers[j].call(argv[i])95+
end96+
matched = true97+
end98+
else99+
if arg == sf || arg == lf100+
@handlers[j].call(true)101+
matched = true102+
end103+
end104+
j += 1105+
end106+
if !matched107+
new_argv.push(arg)108+
end109+
i += 1110+
end111+
# replace argv contents with unmatched args112+
argv.clear113+
k = 0114+
while k < new_argv.length115+
argv.push(new_argv[k])116+
k += 1117+
end118+
end119+
120+
def to_s121+
@banner122+
end123+
end