summaryrefslogtreecommitdiff
path: root/lib/getopts.rb
blob: 9e1e8a2cf69375428b97839fc04a183ceb0b0e70 (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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
#
#		getopts.rb - 
#			$Release Version: $
#			$Revision$
#			$Date$
#			by Yasuo OHBA(SHL Japan Inc. Technology Dept.)
#
# --
#
#	
#

$RCS_ID=%q$Header$

def isSingle(lopt)
  if lopt.index(":")
    if lopt.split(":")[0].length == 1
      return TRUE
    end
  end
  return nil
end

def getOptionName(lopt)
  return lopt.split(":")[0]
end

def getDefaultOption(lopt)
  od = lopt.split(":")[1]
  if od
    return od
  end
  return nil
end

def setOption(name, value)
  eval("$OPT_" + name + " = " + 'value')
end

def setDefaultOption(lopt)
  d = getDefaultOption(lopt)
  if d
    setOption(getOptionName(lopt), d)
  end
end

def setNewArgv(newargv)
  ARGV.clear
  for na in newargv
    ARGV << na
  end
end


def getopts(single_opts, *options)
  if options
    single_colon = ""
    long_opts = []
    sc = 0
    for o in options
      setDefaultOption(o)
      if isSingle(o)
	single_colon[sc, 0] = getOptionName(o)
	sc += 1
      else
	long_opts.push(o)
      end
    end
  end
  
  opts = {}
  count = 0
  newargv = []
  while ARGV.length != 0
    compare = nil
    case ARGV[0]
    when /^--?$/
      ARGV.shift
      newargv += ARGV
      break
    when /^--.*/
      compare = ARGV[0][2, (ARGV[0].length - 2)]
      if long_opts != ""
	for lo in long_opts
	  if lo.index(":") && getOptionName(lo) == compare
	    if ARGV.length <= 1
	      return nil
	    end
	    setOption(compare, ARGV[1])
	    opts[compare] = TRUE
	    ARGV.shift
	    count += 1
	    break
	  elsif lo == compare
	    setOption(compare, TRUE)
	    opts[compare] = TRUE
	    count += 1
	    break
	  end
	end
      end
      if compare.length <= 1
	return nil
      end
    when /^-.*/
      for idx in 1..(ARGV[0].length - 1)
	compare = ARGV[0][idx, 1]
	if single_opts && compare =~ "[" + single_opts + "]"
	  setOption(compare, TRUE)
	  opts[compare] = TRUE
	  count += 1
	elsif single_colon != "" && compare =~ "[" + single_colon + "]"
	  if ARGV[0][idx..-1].length > 1
	    setOption(compare, ARGV[0][(idx + 1)..-1])
	    opts[compare] = TRUE
	    count += 1
	  elsif ARGV.length <= 1
	    return nil
	  else
	    setOption(compare, ARGV[1])
	    opts[compare] = TRUE
	    ARGV.shift
	    count += 1
	  end
	  break
	end
      end
    else
      compare = ARGV[0]
      opts[compare] = TRUE
      newargv << ARGV[0]
    end
    
    ARGV.shift
    if !opts.has_key?(compare)
      return nil
    end
  end
  setNewArgv(newargv)
  return count
end