misc/vim: inform the user when no results are found
[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 with an enum as parameter
178 # In the code, declaring an option enum (-e) with an enum like `["zero", "one", "two"]
179 # In the command line, typing `myprog -e one` is giving 1 as value
180 class OptionEnum
181 super OptionParameter
182 redef type VALUE: Int
183
184 # Values in the enumeration.
185 var values: Array[String]
186
187 # Init a new OptionEnum from `values` with a `help` message and `names`.
188 #
189 # `default` is the index of the default value in `values`.
190 init(values: Array[String], help: String, default: Int, names: String...) is old_style_init do
191 assert values.length > 0
192 self.values = values.to_a
193 super("{help} <{values.join(", ")}>", default, names)
194 end
195
196 redef fun convert(str)
197 do
198 var id = values.index_of(str)
199 if id == -1 then
200 var e = "Unrecognized value for option {names.join(", ")}.\n"
201 e += "Expected values are: {values.join(", ")}."
202 errors.add(e)
203 end
204 return id
205 end
206
207 # Get the value name from `values`.
208 fun value_name: String do return values[value]
209
210 redef fun pretty_default
211 do
212 return " ({values[default_value]})"
213 end
214 end
215
216 # An option with an Int as parameter
217 class OptionInt
218 super OptionParameter
219 redef type VALUE: Int
220
221 # Init a new OptionInt with a `help` message, a `default` value and `names`.
222 init(help: String, default: Int, names: String...) is old_style_init do
223 super(help, default, names)
224 end
225
226 redef fun convert(str) do return str.to_i
227 end
228
229 # An option with a Float as parameter
230 class OptionFloat
231 super OptionParameter
232 redef type VALUE: Float
233
234 # Init a new OptionFloat with a `help` message, a `default` value and `names`.
235 init(help: String, default: Float, names: String...) is old_style_init do
236 super(help, default, names)
237 end
238
239 redef fun convert(str) do return str.to_f
240 end
241
242 # An option with an array as parameter
243 # `myprog -optA arg1 -optA arg2` is giving an Array `["arg1", "arg2"]`
244 class OptionArray
245 super OptionParameter
246 redef type VALUE: Array[String]
247
248 # Init a new OptionArray with a `help` message and `names`.
249 init(help: String, names: String...) is old_style_init do
250 values = new Array[String]
251 super(help, values, names)
252 end
253
254 private var values: Array[String]
255 redef fun convert(str)
256 do
257 values.add(str)
258 return values
259 end
260 end
261
262 # Context where the options process
263 class OptionContext
264 # Options present in the context
265 var options = new Array[Option]
266
267 # Rest of the options after `parse` is called
268 var rest = new Array[String]
269
270 # Errors found in the context after parsing
271 var errors = new Array[String]
272
273 private var optmap = new HashMap[String, Option]
274
275 # Add one or more options to the context
276 fun add_option(opts: Option...) do
277 options.add_all(opts)
278 end
279
280 # Display all the options available
281 fun usage
282 do
283 var lmax = 1
284 for i in options do
285 var l = 3
286 for n in i.names do
287 l += n.length + 2
288 end
289 if lmax < l then lmax = l
290 end
291
292 for i in options do
293 if not i.hidden then
294 print(i.pretty(lmax))
295 end
296 end
297 end
298
299 # Parse and assign options everywhere in the argument list
300 fun parse(argv: Collection[String])
301 do
302 var it = argv.iterator
303 parse_intern(it)
304 end
305
306 # Must all option be given before the first argument?
307 #
308 # When set to `false` (the default), options of the command line are
309 # all parsed until the end of the list of arguments or until "--" is met (in this case "--" is discarded).
310 #
311 # When set to `true` options are parsed until the first non-option is met.
312 var options_before_rest = false is writable
313
314 # Parse the command line
315 protected fun parse_intern(it: Iterator[String])
316 do
317 var parseargs = true
318 build
319 var rest = rest
320
321 while parseargs and it.is_ok do
322 var str = it.item
323 if str == "--" then
324 it.next
325 rest.add_all(it.to_a)
326 parseargs = false
327 else
328 # We're looking for packed short options
329 if str.chars.last_index_of('-') == 0 and str.length > 2 then
330 var next_called = false
331 for i in [1..str.length[ do
332 var short_opt = "-" + str.chars[i].to_s
333 if optmap.has_key(short_opt) then
334 var option = optmap[short_opt]
335 if option isa OptionParameter then
336 it.next
337 next_called = true
338 end
339 option.read_param(it)
340 end
341 end
342 if not next_called then it.next
343 else
344 if optmap.has_key(str) then
345 var opt = optmap[str]
346 it.next
347 opt.read_param(it)
348 else
349 rest.add(it.item)
350 it.next
351 if options_before_rest then
352 rest.add_all(it.to_a)
353 parseargs = false
354 end
355 end
356 end
357 end
358 end
359
360 for opt in options do
361 if opt.mandatory and not opt.read then
362 errors.add("Mandatory option {opt.names.join(", ")} not found.")
363 end
364 end
365 end
366
367 private fun build
368 do
369 for o in options do
370 for n in o.names do
371 optmap[n] = o
372 end
373 end
374 end
375
376 # Options parsing errors.
377 fun get_errors: Array[String]
378 do
379 var errors = new Array[String]
380 errors.add_all(errors)
381 for o in options do
382 for e in o.errors do
383 errors.add(e)
384 end
385 end
386 return errors
387 end
388 end