blob: 34fb0d644272182f5dd8efe163cffdda76329afe (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
|
#
# getopts.rb -
# $Release Version: $
# $Revision$
# $Date$
# by Yasuo OHBA(SHL Japan Inc. Technology Dept.)
#
# --
# this is obsolete; use getoptlong
#
# 2000-03-21
# modified by Minero Aoki <aamine@dp.u-netsurf.ne.jp>
#
# 2002-03-05
# rewritten by Akinori MUSHA <knu@ruby-lang.org>
#
$RCS_ID=%q$Header$
def getopts(single_options, *options)
boolopts = {}
valopts = {}
#
# set defaults
#
single_options.scan(/.:?/) do |opt|
if opt.size == 1
boolopts[opt] = false
else
valopts[opt[0, 1]] = nil
end
end if single_options
options.each do |arg|
opt, val = arg.split(':', 2)
if val
valopts[opt] = val.empty? ? nil : val
else
boolopts[opt] = false
end
end
#
# scan
#
c = 0
argv = ARGV
while arg = argv.shift
case arg
when /\A--(.*)/
if $1.empty? # xinit -- -bpp 24
break
end
opt, val = $1.split('=', 2)
if opt.size == 1
argv.unshift arg
return nil
elsif valopts.key? opt # imclean --src +trash
valopts[opt] = val || argv.shift or return nil
elsif boolopts.key? opt # ruby --verbose
boolopts[opt] = true
else
argv.unshift arg
return nil
end
c += 1
when /\A-(.+)/
opts = $1
until opts.empty?
opt = opts.slice!(0, 1)
if valopts.key? opt
val = opts
if val.empty? # ruby -e 'p $:'
valopts[opt] = argv.shift or return nil
else # cc -ohello ...
valopts[opt] = val
end
c += 1
break
elsif boolopts.key? opt
boolopts[opt] = true # ruby -h
c += 1
else
argv.unshift arg
return nil
end
end
else
argv.unshift arg
break
end
end
#
# set
#
$OPT = {}
boolopts.each do |opt, val|
$OPT[opt] = val
sopt = opt.gsub(/[^A-Za-z0-9_]/, '_')
eval "$OPT_#{sopt} = val"
end
valopts.each do |opt, val|
$OPT[opt] = val
sopt = opt.gsub(/[^A-Za-z0-9_]/, '_')
eval "$OPT_#{sopt} = val"
end
c
end
|