projects: update some short descriptions
[nit.git] / lib / opts.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2008 Floréal Morandat <morandat@lirmm.fr>
4 # Copyright 2008 Jean Privat <jean@pryen.org>
5 #
6 # This file is free software, which comes along with NIT. This software is
7 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
8 # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
9 # PARTICULAR PURPOSE. You can modify it is you want, provided this header
10 # is kept unaltered, and a notification of the changes is added.
11 # You are allowed to redistribute it and sell it, alone or is a part of
12 # another product.
13
14 # Management of options on the command line
15 module opts
16
17 # Super class of all option's class
18 abstract class Option
19 # Names for the option (including long and short ones)
20 var names: Array[String]
21
22 # Type of the value of the option
23 type VALUE: nullable Object
24
25 # Human readable description of the option
26 var helptext: String
27
28 # Gathering errors during parsing
29 var errors: Array[String] = new Array[String]
30
31 # Is this option mandatory?
32 var mandatory: Bool = false is writable
33
34 # Is this option hidden from `usage`?
35 var hidden: Bool = false is writable
36
37 # Has this option been read?
38 var read: Bool = false is writable
39
40 # Current value of this option
41 var value: VALUE is writable
42
43 # Default value of this option
44 var default_value: VALUE is writable
45
46 # Create a new option
47 init(help: String, default: VALUE, names: nullable Array[String]) is old_style_init do
48 init_opt(help, default, names)
49 end
50
51 # Init option `helptext`, `default_value` and `names`.
52 #
53 # Also set current `value` to `default`.
54 fun init_opt(help: String, default: VALUE, names: nullable Array[String])
55 do
56 if names == null then
57 self.names = new Array[String]
58 else
59 self.names = names.to_a
60 end
61 helptext = help
62 default_value = default
63 value = default
64 end
65
66 # Add new aliases for this option
67 fun add_aliases(names: String...) do names.add_all(names)
68
69 # An help text for this option with default settings
70 redef fun to_s do return pretty(2)
71
72 # A pretty print for this help
73 fun pretty(off: Int): String
74 do
75 var text = new FlatBuffer.from(" ")
76 text.append(names.join(", "))
77 text.append(" ")
78 var rest = off - text.length
79 if rest > 0 then text.append(" " * rest)
80 text.append(helptext)
81 #text.append(pretty_default)
82 return text.to_s
83 end
84
85 # Pretty print the default value.
86 fun pretty_default: String
87 do
88 var dv = default_value
89 if dv != null then return " ({dv.to_s})"
90 return ""
91 end
92
93 # Consume parameters for this option
94 protected fun read_param(it: Iterator[String])
95 do
96 read = true
97 end
98 end
99
100 # Not really an option. Just add a line of text when displaying the usage
101 class OptionText
102 super Option
103
104 # Init a new OptionText with `text`.
105 init(text: String) is old_style_init do super(text, null, null)
106
107 redef fun pretty(off) do return to_s
108
109 redef fun to_s do return helptext
110 end
111
112 # A boolean option, `true` when present, `false` if not
113 class OptionBool
114 super Option
115 redef type VALUE: Bool
116
117 # Init a new OptionBool with a `help` message and `names`.
118 init(help: String, names: String...) is old_style_init do super(help, false, names)
119
120 redef fun read_param(it)
121 do
122 super
123 value = true
124 end
125 end
126
127 # A count option. Count the number of time this option is present
128 class OptionCount
129 super Option
130 redef type VALUE: Int
131
132 # Init a new OptionCount with a `help` message and `names`.
133 init(help: String, names: String...) is old_style_init do super(help, 0, names)
134
135 redef fun read_param(it)
136 do
137 super
138 value += 1
139 end
140 end
141
142 # Option with one parameter (mandatory by default)
143 abstract class OptionParameter
144 super Option
145
146 # Convert `str` to a value of type `VALUE`.
147 protected fun convert(str: String): VALUE is abstract
148
149 # Is the parameter mandatory?
150 var parameter_mandatory: Bool = true is writable
151
152 redef fun read_param(it)
153 do
154 super
155 if it.is_ok and (it.item.is_empty or it.item.chars.first != '-') then
156 value = convert(it.item)
157 it.next
158 else
159 if parameter_mandatory then
160 errors.add("Parameter expected for option {names.first}.")
161 end
162 end
163 end
164 end
165
166 # An option with a `String` as parameter
167 class OptionString
168 super OptionParameter
169 redef type VALUE: nullable String
170
171 # Init a new OptionString with a `help` message and `names`.
172 init(help: String, names: String...) is old_style_init do super(help, null, names)
173
174 redef fun convert(str) do return str
175 end
176
177 # An option to choose from an enumeration
178 #
179 # Declare an enumeration option with all its possible values as an array.
180 # Once the arguments are processed, `value` is set as the index of the selected value, if any.
181 class OptionEnum
182 super OptionParameter
183 redef type VALUE: Int
184
185 # Values in the enumeration.
186 var values: Array[String]
187
188 # Init a new OptionEnum from `values` with a `help` message and `names`.
189 #
190 # `default` is the index of the default value in `values`.
191 init(values: Array[String], help: String, default: Int, names: String...) is old_style_init do
192 assert values.length > 0
193 self.values = values.to_a
194 super("{help} <{values.join(", ")}>", default, names)
195 end
196
197 redef fun convert(str)
198 do
199 var id = values.index_of(str)
200 if id == -1 then
201 var e = "Unrecognized value for option {names.join(", ")}.\n"
202 e += "Expected values are: {values.join(", ")}."
203 errors.add(e)
204 end
205 return id
206 end
207
208 # Get the value name from `values`.
209 fun value_name: String do return values[value]
210
211 redef fun pretty_default
212 do
213 return " ({values[default_value]})"
214 end
215 end
216
217 # An option with an Int as parameter
218 class OptionInt
219 super OptionParameter
220 redef type VALUE: Int
221
222 # Init a new OptionInt with a `help` message, a `default` value and `names`.
223 init(help: String, default: Int, names: String...) is old_style_init do
224 super(help, default, names)
225 end
226
227 redef fun convert(str) do return str.to_i
228 end
229
230 # An option with a Float as parameter
231 class OptionFloat
232 super OptionParameter
233 redef type VALUE: Float
234
235 # Init a new OptionFloat with a `help` message, a `default` value and `names`.
236 init(help: String, default: Float, names: String...) is old_style_init do
237 super(help, default, names)
238 end
239
240 redef fun convert(str) do return str.to_f
241 end
242
243 # An option with an array as parameter
244 # `myprog -optA arg1 -optA arg2` is giving an Array `["arg1", "arg2"]`
245 class OptionArray
246 super OptionParameter
247 redef type VALUE: Array[String]
248
249 # Init a new OptionArray with a `help` message and `names`.
250 init(help: String, names: String...) is old_style_init do
251 values = new Array[String]
252 super(help, values, names)
253 end
254
255 private var values: Array[String]
256 redef fun convert(str)
257 do
258 values.add(str)
259 return values
260 end
261 end
262
263 # Context where the options process
264 class OptionContext
265 # Options present in the context
266 var options = new Array[Option]
267
268 # Rest of the options after `parse` is called
269 var rest = new Array[String]
270
271 # Errors found in the context after parsing
272 var errors = new Array[String]
273
274 private var optmap = new HashMap[String, Option]
275
276 # Add one or more options to the context
277 fun add_option(opts: Option...) do
278 options.add_all(opts)
279 end
280
281 # Display all the options available
282 fun usage
283 do
284 var lmax = 1
285 for i in options do
286 var l = 3
287 for n in i.names do
288 l += n.length + 2
289 end
290 if lmax < l then lmax = l
291 end
292
293 for i in options do
294 if not i.hidden then
295 print(i.pretty(lmax))
296 end
297 end
298 end
299
300 # Parse and assign options everywhere in the argument list
301 fun parse(argv: Collection[String])
302 do
303 var it = argv.iterator
304 parse_intern(it)
305 end
306
307 # Must all option be given before the first argument?
308 #
309 # When set to `false` (the default), options of the command line are
310 # all parsed until the end of the list of arguments or until "--" is met (in this case "--" is discarded).
311 #
312 # When set to `true` options are parsed until the first non-option is met.
313 var options_before_rest = false is writable
314
315 # Parse the command line
316 protected fun parse_intern(it: Iterator[String])
317 do
318 var parseargs = true
319 build
320 var rest = rest
321
322 while parseargs and it.is_ok do
323 var str = it.item
324 if str == "--" then
325 it.next
326 rest.add_all(it.to_a)
327 parseargs = false
328 else
329 # We're looking for packed short options
330 if str.chars.last_index_of('-') == 0 and str.length > 2 then
331 var next_called = false
332 for i in [1..str.length[ do
333 var short_opt = "-" + str.chars[i].to_s
334 if optmap.has_key(short_opt) then
335 var option = optmap[short_opt]
336 if option isa OptionParameter then
337 it.next
338 next_called = true
339 end
340 option.read_param(it)
341 end
342 end
343 if not next_called then it.next
344 else
345 if optmap.has_key(str) then
346 var opt = optmap[str]
347 it.next
348 opt.read_param(it)
349 else
350 rest.add(it.item)
351 it.next
352 if options_before_rest then
353 rest.add_all(it.to_a)
354 parseargs = false
355 end
356 end
357 end
358 end
359 end
360
361 for opt in options do
362 if opt.mandatory and not opt.read then
363 errors.add("Mandatory option {opt.names.join(", ")} not found.")
364 end
365 end
366 end
367
368 private fun build
369 do
370 for o in options do
371 for n in o.names do
372 optmap[n] = o
373 end
374 end
375 end
376
377 # Options parsing errors.
378 fun get_errors: Array[String]
379 do
380 var errors = new Array[String]
381 errors.add_all(errors)
382 for o in options do
383 for e in o.errors do
384 errors.add(e)
385 end
386 end
387 return errors
388 end
389 end