toolcontext: add `keep_going` flag to possibly let the tool continue after errors
[nit.git] / src / toolcontext.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2006-2008 Floréal Morandat <morandat@lirmm.fr>
4 # Copyright 2008-2012 Jean Privat <jean@pryen.org>
5 # Copyright 2009 Jean-Sebastien Gelinas <calestar@gmail.com>
6 # Copyright 2014 Alexandre Terrasa <alexandre@moz-code.org>
7 #
8 # Licensed under the Apache License, Version 2.0 (the "License");
9 # you may not use this file except in compliance with the License.
10 # You may obtain a copy of the License at
11 #
12 # http://www.apache.org/licenses/LICENSE-2.0
13 #
14 # Unless required by applicable law or agreed to in writing, software
15 # distributed under the License is distributed on an "AS IS" BASIS,
16 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 # See the License for the specific language governing permissions and
18 # limitations under the License.
19
20 # Common command-line tool infrastructure than handle options and error messages
21 module toolcontext
22
23 import opts
24 import location
25 import version
26 import template
27
28 # A warning or an error
29 class Message
30 super Comparable
31 redef type OTHER: Message
32
33 # The origin of the message in the source code, if any.
34 var location: nullable Location
35
36 # The category of the message.
37 #
38 # Used by quality-control tool for statistics or to enable/disable things individually.
39 var tag: nullable String
40
41 # The human-readable description of the message.
42 #
43 # It should be short and fit on a single line.
44 # It should also have meaningful information first in case
45 # on truncation by an IDE for instance.
46 var text: String
47
48 # Comparisons are made on message locations.
49 redef fun <(other: OTHER): Bool do
50 if location == null then return true
51 if other.location == null then return false
52
53 return location.as(not null) < other.location.as(not null)
54 end
55
56 redef fun to_s: String
57 do
58 var l = location
59 if l == null then
60 return text
61 else
62 return "{l}: {text}"
63 end
64 end
65
66 # A colored version of the message including the original source line
67 fun to_color_string: String
68 do
69 var esc = 27.ascii
70 #var red = "{esc}[0;31m"
71 #var bred = "{esc}[1;31m"
72 #var green = "{esc}[0;32m"
73 var yellow = "{esc}[0;33m"
74 var def = "{esc}[0m"
75
76 var tag = tag
77 if tag != null then
78 tag = " ({tag})"
79 else
80 tag = ""
81 end
82 var l = location
83 if l == null then
84 return "{text}{tag}"
85 else if l.file == null then
86 return "{yellow}{l}{def}: {text}{tag}"
87 else
88 return "{yellow}{l}{def}: {text}{tag}\n{l.colored_line("1;31")}"
89 end
90 end
91 end
92
93 # Global context for tools
94 class ToolContext
95 # Number of errors
96 var error_count: Int = 0
97
98 # Number of warnings
99 var warning_count: Int = 0
100
101 # Directory where to generate log files
102 var log_directory: String = "logs"
103
104 # Messages
105 private var messages = new Array[Message]
106 private var message_sorter: Comparator = default_comparator
107
108 # Does an error prevent the program to stop at `check_errors`?
109 #
110 # Default to false.
111 # Set this value to `true` if you need to keep the program going in case of error.
112 var keep_going = false is writable
113
114 # Output all current stacked messages and display total error informations
115 #
116 # Return true if no errors occurred.
117 #
118 # If some errors occurred, the behavior depends on the value of `keep_going`.
119 # If `keep_going` is false, then the program exits.
120 # Else, the error count and the warning count are reset and false is returned.
121 fun check_errors: Bool
122 do
123 if messages.length > 0 then
124 message_sorter.sort(messages)
125
126 for m in messages do
127 if opt_no_color.value then
128 sys.stderr.write("{m}\n")
129 else
130 sys.stderr.write("{m.to_color_string}\n")
131 end
132 end
133
134 messages.clear
135 end
136
137 if error_count > 0 then
138 errors_info
139 if not keep_going then exit(1)
140 return false
141 end
142 return true
143 end
144
145 # Display (and reset) total error informations
146 fun errors_info
147 do
148 if error_count == 0 and warning_count == 0 then return
149 if opt_no_color.value then return
150 sys.stderr.write "Errors: {error_count}. Warnings: {warning_count}.\n"
151 error_count = 0
152 warning_count = 0
153 end
154
155 # Display an error
156 fun error(l: nullable Location, s: String)
157 do
158 messages.add(new Message(l,null,s))
159 error_count = error_count + 1
160 if opt_stop_on_first_error.value then check_errors
161 end
162
163 # Add an error, show errors and quit
164 fun fatal_error(l: nullable Location, s: String)
165 do
166 error(l,s)
167 check_errors
168 end
169
170 # Display a first-level warning.
171 #
172 # First-level warnings are warnings that SHOULD be corrected,
173 # and COULD usually be immediately corrected.
174 #
175 # * There is a simple correction
176 # * There is no reason to let the code this way (no reasonable @supresswarning-like annotation)
177 # * They always are real issues (no false positive)
178 #
179 # First-level warnings are displayed by default (except if option `-q` is given).
180 fun warning(l: nullable Location, tag: String, text: String)
181 do
182 if opt_warning.value.has("no-{tag}") then return
183 if not opt_warning.value.has(tag) and opt_warn.value == 0 then return
184 messages.add(new Message(l, tag, text))
185 warning_count = warning_count + 1
186 if opt_stop_on_first_error.value then check_errors
187 end
188
189 # Display a second-level warning.
190 #
191 # Second-level warnings are warnings that should require investigation,
192 # but cannot always be immediately corrected.
193 #
194 # * The correction could be complex. e.g. require a refactorisation or an API change.
195 # * The correction cannot be done. e.g. Code that use a deprecated API for some compatibility reason.
196 # * There is not a real issue (false positive). Note that this should be unlikely.
197 # * Transitional: While a real warning, it fires a lot in current code, so a transition is needed
198 # in order to fix them before promoting the advice to a warning.
199 #
200 # In order to prevent warning inflation à la Java, second-level warnings are not displayed by
201 # default and require an additional option `-W`.
202 fun advice(l: nullable Location, tag: String, text: String)
203 do
204 if opt_warning.value.has("no-{tag}") then return
205 if not opt_warning.value.has(tag) and opt_warn.value <= 1 then return
206 messages.add(new Message(l, tag, text))
207 warning_count = warning_count + 1
208 if opt_stop_on_first_error.value then check_errors
209 end
210
211 # Display an info
212 fun info(s: String, level: Int)
213 do
214 if level <= verbose_level then
215 print "{s}"
216 end
217 end
218
219 # Executes a program while checking if it's available and if the execution ended correctly
220 #
221 # Stops execution and prints errors if the program isn't available or didn't end correctly
222 fun exec_and_check(args: Array[String], error: String)
223 do
224 var prog = args.first
225 args.remove_at 0
226
227 # Is the wanted program available?
228 var proc_which = new IProcess.from_a("which", [prog])
229 proc_which.wait
230 var res = proc_which.status
231 if res != 0 then
232 print "{error}: executable \"{prog}\" not found"
233 exit 1
234 end
235
236 # Execute the wanted program
237 var proc = new Process.from_a(prog, args)
238 proc.wait
239 res = proc.status
240 if res != 0 then
241 print "{error}: execution of \"{prog} {args.join(" ")}\" failed"
242 exit 1
243 end
244 end
245
246 # Global OptionContext
247 var option_context = new OptionContext
248
249 # Option --warn
250 var opt_warn = new OptionCount("Show more warnings", "-W", "--warn")
251
252 # Option --warning
253 var opt_warning = new OptionArray("Show/hide a specific warning", "-w", "--warning")
254
255 # Option --quiet
256 var opt_quiet = new OptionBool("Do not show warnings", "-q", "--quiet")
257
258 # Option --log
259 var opt_log = new OptionBool("Generate various log files", "--log")
260
261 # Option --log-dir
262 var opt_log_dir = new OptionString("Directory where to generate log files", "--log-dir")
263
264 # Option --nit-dir
265 var opt_nit_dir = new OptionString("Base directory of the Nit installation", "--nit-dir")
266
267 # Option --help
268 var opt_help = new OptionBool("Show Help (This screen)", "-h", "-?", "--help")
269
270 # Option --version
271 var opt_version = new OptionBool("Show version and exit", "--version")
272
273 # Option --set-dummy-tool
274 var opt_set_dummy_tool = new OptionBool("Set toolname and version to DUMMY. Useful for testing", "--set-dummy-tool")
275
276 # Option --verbose
277 var opt_verbose = new OptionCount("Verbose", "-v", "--verbose")
278
279 # Option --stop-on-first-error
280 var opt_stop_on_first_error = new OptionBool("Stop on first error", "--stop-on-first-error")
281
282 # Option --no-color
283 var opt_no_color = new OptionBool("Do not use color to display errors and warnings", "--no-color")
284
285 # Option --bash-completion
286 var opt_bash_completion = new OptionBool("Generate bash_completion file for this program", "--bash-completion")
287
288 # Option --stub-man
289 var opt_stub_man = new OptionBool("Generate a stub manpage in pandoc markdown format", "--stub-man")
290
291 # Verbose level
292 var verbose_level: Int = 0
293
294 init
295 do
296 option_context.add_option(opt_warn, opt_warning, opt_quiet, opt_stop_on_first_error, opt_no_color, opt_log, opt_log_dir, opt_nit_dir, opt_help, opt_version, opt_set_dummy_tool, opt_verbose, opt_bash_completion, opt_stub_man)
297
298 # Hide some internal options
299 opt_stub_man.hidden = true
300 opt_bash_completion.hidden = true
301 opt_set_dummy_tool.hidden = true
302 end
303
304 # Name, usage and synopsis of the tool.
305 # It is mainly used in `usage`.
306 # Should be correctly set by the client before calling `process_options`
307 # A multi-line string is recommmended.
308 #
309 # eg. `"Usage: tool [OPTION]... [FILE]...\nDo some things."`
310 var tooldescription: String = "Usage: [OPTION]... [ARG]..." is writable
311
312 # Does `process_options` should accept an empty sequence of arguments.
313 # ie. nothing except options.
314 # Is `false` by default.
315 #
316 # If required, if should be set by the client before calling `process_options`
317 var accept_no_arguments = false is writable
318
319 # print the full usage of the tool.
320 # Is called by `process_option` on `--help`.
321 # It also could be called by the client.
322 fun usage
323 do
324 print tooldescription
325 option_context.usage
326 end
327
328 # Parse and process the options given on the command line
329 fun process_options(args: Sequence[String])
330 do
331 self.opt_warn.value = 1
332
333 # init options
334 option_context.parse(args)
335
336 if opt_help.value then
337 usage
338 exit 0
339 end
340
341 if opt_version.value then
342 print version
343 exit 0
344 end
345
346 if opt_bash_completion.value then
347 var bash_completion = new BashCompletion(self)
348 bash_completion.write_to(sys.stdout)
349 exit 0
350 end
351
352 if opt_stub_man.value then
353 print """
354 % {{{toolname.to_upper}}}(1)
355
356 # NAME
357
358 {{{tooldescription.split("\n")[1]}}}
359
360 # SYNOPSYS
361
362 {{{toolname}}} [*options*]...
363
364 # OPTIONS
365 """
366 for o in option_context.options do
367 var first = true
368 for n in o.names do
369 if first then first = false else printn ", "
370 printn "`{n}`"
371 end
372 print ""
373 print ": {o.helptext}"
374 print ""
375 end
376 print """
377 # SEE ALSO
378
379 The Nit language documentation and the source code of its tools and libraries may be downloaded from <http://nitlanguage.org>"""
380 exit 0
381 end
382
383 var errors = option_context.get_errors
384 if not errors.is_empty then
385 for e in errors do print "Error: {e}"
386 print tooldescription
387 print "Use --help for help"
388 exit 1
389 end
390
391 nit_dir = compute_nit_dir
392
393 if option_context.rest.is_empty and not accept_no_arguments then
394 print tooldescription
395 print "Use --help for help"
396 exit 1
397 end
398
399 # Set verbose level
400 verbose_level = opt_verbose.value
401
402 if self.opt_quiet.value then self.opt_warn.value = 0
403
404 if opt_log_dir.value != null then log_directory = opt_log_dir.value.as(not null)
405 if opt_log.value then
406 # Make sure the output directory exists
407 log_directory.mkdir
408 end
409
410 end
411
412 # Get the current `nit_version` or "DUMMY_VERSION" if `--set-dummy-tool` is set.
413 fun version: String do
414 if opt_set_dummy_tool.value then
415 return "DUMMY_VERSION"
416 end
417 return nit_version
418 end
419
420 # Get the name of the tool or "DUMMY_TOOL" id `--set-dummy-tool` is set.
421 fun toolname: String do
422 if opt_set_dummy_tool.value then
423 return "DUMMY_TOOL"
424 end
425 return sys.program_name.basename("")
426 end
427
428 # The identified root directory of the Nit project
429 var nit_dir: String is noinit
430
431 private fun compute_nit_dir: String
432 do
433 # the option has precedence
434 var res = opt_nit_dir.value
435 if res != null then
436 if not check_nit_dir(res) then
437 fatal_error(null, "Fatal Error: the value of --nit-dir does not seem to be a valid base Nit directory: {res}")
438 end
439 return res
440 end
441
442 # then the environ variable has precedence
443 res = "NIT_DIR".environ
444 if not res.is_empty then
445 if not check_nit_dir(res) then
446 fatal_error(null, "Fatal Error: the value of NIT_DIR does not seem to be a valid base Nit directory: {res}")
447 end
448 return res
449 end
450
451 # find the runpath of the program from argv[0]
452 res = "{sys.program_name.dirname}/.."
453 if check_nit_dir(res) then return res.simplify_path
454
455 # find the runpath of the process from /proc
456 var exe = "/proc/self/exe"
457 if exe.file_exists then
458 res = exe.realpath
459 res = res.dirname.join_path("..")
460 if check_nit_dir(res) then return res.simplify_path
461 end
462
463 # search in the PATH
464 var ps = "PATH".environ.split(":")
465 for p in ps do
466 res = p/".."
467 if check_nit_dir(res) then return res.simplify_path
468 end
469
470 fatal_error(null, "Fatal Error: Cannot locate a valid base nit directory. It is quite unexpected. Try to set the environment variable `NIT_DIR` or to use the `--nit-dir` option.")
471 abort
472 end
473
474 private fun check_nit_dir(res: String): Bool
475 do
476 return res.file_exists and "{res}/src/nit.nit".file_exists
477 end
478 end
479
480 # This class generates a compatible `bash_completion` script file.
481 #
482 # On some Linux systems `bash_completion` allow the program to control command line behaviour.
483 #
484 # $ nitls [TAB][TAB]
485 # file1.nit file2.nit file3.nit
486 #
487 # $ nitls --[TAB][TAB]
488 # --bash-toolname --keep --path --tree
489 # --depends --log --project --verbose
490 # --disable-phase --log-dir --quiet --version
491 # --gen-bash-completion --no-color --recursive --warn
492 # --help --only-metamodel --source
493 # --ignore-visibility --only-parse --stop-on-first-error
494 #
495 # Generated file can be placed in system bash_completion directory `/etc/bash_completion.d/`
496 # or source it in `~/.bash_completion`.
497 class BashCompletion
498 super Template
499
500 var toolcontext: ToolContext
501
502 private fun extract_options_names: Array[String] do
503 var names = new Array[String]
504 for option in toolcontext.option_context.options do
505 for name in option.names do
506 if name.has_prefix("--") then names.add name
507 end
508 end
509 return names
510 end
511
512 redef fun rendering do
513 var name = toolcontext.toolname
514 var option_names = extract_options_names
515 addn "# generated bash completion file for {name} {toolcontext.version}"
516 addn "_{name}()"
517 addn "\{"
518 addn " local cur prev opts"
519 addn " COMPREPLY=()"
520 addn " cur=\"$\{COMP_WORDS[COMP_CWORD]\}\""
521 addn " prev=\"$\{COMP_WORDS[COMP_CWORD-1]\}\""
522 if not option_names.is_empty then
523 addn " opts=\"{option_names.join(" ")}\""
524 addn " if [[ $\{cur\} == -* ]] ; then"
525 addn " COMPREPLY=( $(compgen -W \"$\{opts\}\" -- $\{cur\}) )"
526 addn " return 0"
527 addn " fi"
528 end
529 addn "\} &&"
530 addn "complete -o default -F _{name} {name}"
531 end
532 end