toolcontext: attach messages to location, even if quieted
[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 import more_collections
28
29 # A warning or an error
30 class Message
31 super Comparable
32 redef type OTHER: Message
33
34 # The origin of the message in the source code, if any.
35 var location: nullable Location
36
37 # The category of the message.
38 #
39 # Used by quality-control tool for statistics or to enable/disable things individually.
40 var tag: nullable String
41
42 # The human-readable description of the message.
43 #
44 # eg. "Error: cannot find method `foo`."
45 #
46 # A good message should:
47 #
48 # * start with a message type like "Error:", "Syntax Error:", "Warning:".
49 # The type is capitalized and terminated by a column.
50 # The rest on the message starts with a lowercase letter and is terminated with a dot.
51 #
52 # * be short and fit on a single line.
53 #
54 # * have meaningful information first.
55 # This helps the reader and remain usable
56 # when truncated, by an IDE for instance.
57 #
58 # * enclose identifiers, keywords and pieces of code with back-quotes.
59 var text: String
60
61 # The severity level
62 #
63 # * 0 is advices (see `ToolContext::advice`)
64 # * 1 is warnings (see `ToolContext::warning`)
65 # * 2 is errors (see `ToolContext::error`)
66 var level: Int
67
68 # Comparisons are made on message locations.
69 redef fun <(other: OTHER): Bool do
70 if location == null then return true
71 if other.location == null then return false
72
73 return location.as(not null) < other.location.as(not null)
74 end
75
76 redef fun ==(other): Bool do
77 if not other isa Message then return false
78 return location == other.location and tag == other.tag and text == other.text
79 end
80
81 redef fun to_s: String
82 do
83 var l = location
84 if l == null then
85 return text
86 else
87 return "{l}: {text}"
88 end
89 end
90
91 # A colored version of the message including the original source line
92 fun to_color_string: String
93 do
94 var esc = 27.code_point
95 #var red = "{esc}[0;31m"
96 #var bred = "{esc}[1;31m"
97 #var green = "{esc}[0;32m"
98 var yellow = "{esc}[0;33m"
99 var def = "{esc}[0m"
100
101 var tag = tag
102 if tag != null then
103 tag = " ({tag})"
104 else
105 tag = ""
106 end
107 var l = location
108 if l == null then
109 return "{text}{tag}"
110 else if l.file == null then
111 return "{yellow}{l}{def}: {text}{tag}"
112 else
113 return "{yellow}{l}{def}: {text}{tag}\n{l.colored_line("1;31")}"
114 end
115 end
116 end
117
118 redef class Location
119 # Errors and warnings associated to this location.
120 var messages: nullable Array[Message]
121
122 # Add a message to `self`
123 #
124 # See `messages`
125 private fun add_message(m: Message)
126 do
127 var ms = messages
128 if ms == null then
129 ms = new Array[Message]
130 messages = ms
131 end
132 ms.add m
133 end
134 end
135
136 # Global context for tools
137 class ToolContext
138 # Number of errors
139 var error_count: Int = 0
140
141 # Number of warnings
142 var warning_count: Int = 0
143
144 # Directory where to generate log files
145 var log_directory: String = "logs"
146
147 # Stream in `log_directory` where all info messages are written
148 var log_info: nullable Writer = null
149
150 # Messages
151 private var messages = new Array[Message]
152 private var message_sorter: Comparator = default_comparator
153
154 # Does an error prevent the program to stop at `check_errors`?
155 #
156 # Default to false.
157 # Set this value to `true` if you need to keep the program going in case of error.
158 var keep_going = false is writable
159
160 # List of tags per source-file whose warnings are not displayed.
161 #
162 # Initially empty, it is up to the toll to fill it.
163 # The tag "all" means all warnings and advices.
164 var warning_blacklist = new MultiHashMap[SourceFile, String]
165
166 # Is the source-file of `l` associated with `tag` in `warning_blacklist`?
167 #
168 # currently returns `false` if `l` is null or does not have a source-file.
169 fun is_warning_blacklisted(l: nullable Location, tag: String): Bool
170 do
171 if l == null then return false
172 var f = l.file
173 if f == null then return false
174 var tags = warning_blacklist.get_or_null(f)
175 if tags == null then return false
176 return tags.has("all") or tags.has(tag)
177 end
178
179 # Output all current stacked messages, total and exit the program
180 #
181 # If there is no error, exit with 0, else exit with 1.
182 fun quit
183 do
184 check_errors
185 errors_info
186 if error_count > 0 then exit(1) else exit(0)
187 end
188
189 # Output all current stacked messages
190 #
191 # Return true if no errors occurred.
192 #
193 # If some errors occurred, the behavior depends on the value of `keep_going`.
194 # If `keep_going` is false, then the total error informations is displayed and the program exits.
195 # Else, false is returned.
196 fun check_errors: Bool
197 do
198 if messages.length > 0 then
199 message_sorter.sort(messages)
200
201 for m in messages do
202 if opt_no_color.value then
203 sys.stderr.write("{m}\n")
204 else
205 sys.stderr.write("{m.to_color_string}\n")
206 end
207 end
208
209 messages.clear
210 end
211
212 if error_count > 0 then
213 if not keep_going then
214 errors_info
215 exit(1)
216 end
217 return false
218 end
219 return true
220 end
221
222 # Display total error informations
223 fun errors_info
224 do
225 if error_count == 0 and warning_count == 0 then return
226 if opt_no_color.value then return
227 sys.stderr.write "Errors: {error_count}. Warnings: {warning_count}.\n"
228 end
229
230 # Display an error
231 #
232 # Return the message (to add information)
233 fun error(l: nullable Location, s: String): Message
234 do
235 var m = new Message(l, null, s, 2)
236 if messages.has(m) then return m
237 if l != null then l.add_message m
238 messages.add m
239 error_count = error_count + 1
240 if opt_stop_on_first_error.value then check_errors
241 return m
242 end
243
244 # Add an error, show errors and quit
245 #
246 # Because the program will quit, nothing is returned.
247 fun fatal_error(l: nullable Location, s: String)
248 do
249 error(l,s)
250 check_errors
251 end
252
253 # Display a first-level warning.
254 #
255 # First-level warnings are warnings that SHOULD be corrected,
256 # and COULD usually be immediately corrected.
257 #
258 # * There is a simple correction
259 # * There is no reason to let the code this way (no reasonable @supresswarning-like annotation)
260 # * They always are real issues (no false positive)
261 #
262 # First-level warnings are displayed by default (except if option `-q` is given).
263 #
264 # Return the message (to add information) or null if the warning is disabled
265 fun warning(l: nullable Location, tag: String, text: String): nullable Message
266 do
267 if is_warning_blacklisted(l, tag) then return null
268 var m = new Message(l, tag, text, 1)
269 if messages.has(m) then return null
270 if l != null then l.add_message m
271 if opt_warning.value.has("no-{tag}") then return null
272 if not opt_warning.value.has(tag) and opt_warn.value == 0 then return null
273 messages.add m
274 warning_count = warning_count + 1
275 if opt_stop_on_first_error.value then check_errors
276 return m
277 end
278
279 # Display a second-level warning.
280 #
281 # Second-level warnings are warnings that should require investigation,
282 # but cannot always be immediately corrected.
283 #
284 # * The correction could be complex. e.g. require a refactorisation or an API change.
285 # * The correction cannot be done. e.g. Code that use a deprecated API for some compatibility reason.
286 # * There is not a real issue (false positive). Note that this should be unlikely.
287 # * Transitional: While a real warning, it fires a lot in current code, so a transition is needed
288 # in order to fix them before promoting the advice to a warning.
289 #
290 # In order to prevent warning inflation à la Java, second-level warnings are not displayed by
291 # default and require an additional option `-W`.
292 #
293 # Return the message (to add information) or null if the warning is disabled
294 fun advice(l: nullable Location, tag: String, text: String): nullable Message
295 do
296 if is_warning_blacklisted(l, tag) then return null
297 var m = new Message(l, tag, text, 0)
298 if messages.has(m) then return null
299 if l != null then l.add_message m
300 if opt_warning.value.has("no-{tag}") then return null
301 if not opt_warning.value.has(tag) and opt_warn.value <= 1 then return null
302 messages.add m
303 warning_count = warning_count + 1
304 if opt_stop_on_first_error.value then check_errors
305 return m
306 end
307
308 # Display an info
309 fun info(s: String, level: Int)
310 do
311 if level <= verbose_level then
312 print "{s}"
313 end
314 if log_info != null then
315 log_info.write s
316 log_info.write "\n"
317 end
318 end
319
320 # Executes a program while checking if it's available and if the execution ended correctly
321 #
322 # Stops execution and prints errors if the program isn't available or didn't end correctly
323 fun exec_and_check(args: Array[String], error: String)
324 do
325 info("+ {args.join(" ")}", 2)
326
327 var prog = args.first
328 args.remove_at 0
329
330 # Is the wanted program available?
331 var proc_which = new ProcessReader.from_a("which", [prog])
332 proc_which.wait
333 var res = proc_which.status
334 if res != 0 then
335 print "{error}: executable \"{prog}\" not found"
336 exit 1
337 end
338
339 # Execute the wanted program
340 var proc = new Process.from_a(prog, args)
341 proc.wait
342 res = proc.status
343 if res != 0 then
344 print "{error}: execution of \"{prog} {args.join(" ")}\" failed"
345 exit 1
346 end
347 end
348
349 # Global OptionContext
350 var option_context = new OptionContext
351
352 # Option --warn
353 var opt_warn = new OptionCount("Show additional warnings (advices)", "-W", "--warn")
354
355 # Option --warning
356 var opt_warning = new OptionArray("Show/hide a specific warning", "-w", "--warning")
357
358 # Option --quiet
359 var opt_quiet = new OptionBool("Do not show warnings", "-q", "--quiet")
360
361 # Option --log
362 var opt_log = new OptionBool("Generate various log files", "--log")
363
364 # Option --log-dir
365 var opt_log_dir = new OptionString("Directory where to generate log files", "--log-dir")
366
367 # Option --nit-dir
368 var opt_nit_dir = new OptionString("Base directory of the Nit installation", "--nit-dir")
369
370 # Option --help
371 var opt_help = new OptionBool("Show Help (This screen)", "-h", "-?", "--help")
372
373 # Option --version
374 var opt_version = new OptionBool("Show version and exit", "--version")
375
376 # Option --set-dummy-tool
377 var opt_set_dummy_tool = new OptionBool("Set toolname and version to DUMMY. Useful for testing", "--set-dummy-tool")
378
379 # Option --verbose
380 var opt_verbose = new OptionCount("Additional messages from the tool", "-v", "--verbose")
381
382 # Option --stop-on-first-error
383 var opt_stop_on_first_error = new OptionBool("Just display the first encountered error then stop", "--stop-on-first-error")
384
385 # Option --keep-going
386 var opt_keep_going = new OptionBool("Continue after errors, whatever the consequences", "--keep-going")
387
388 # Option --no-color
389 var opt_no_color = new OptionBool("Do not use color to display errors and warnings", "--no-color")
390
391 # Option --bash-completion
392 var opt_bash_completion = new OptionBool("Generate bash_completion file for this program", "--bash-completion")
393
394 # Option --stub-man
395 var opt_stub_man = new OptionBool("Generate a stub manpage in pandoc markdown format", "--stub-man")
396
397 # Verbose level
398 var verbose_level: Int = 0
399
400 init
401 do
402 option_context.add_option(opt_warn, opt_warning, opt_quiet, opt_stop_on_first_error, opt_keep_going, 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)
403
404 # Hide some internal options
405 opt_stub_man.hidden = true
406 opt_bash_completion.hidden = true
407 opt_set_dummy_tool.hidden = true
408 end
409
410 # Name, usage and synopsis of the tool.
411 # It is mainly used in `usage`.
412 # Should be correctly set by the client before calling `process_options`
413 # A multi-line string is recommmended.
414 #
415 # eg. `"Usage: tool [OPTION]... [FILE]...\nDo some things."`
416 var tooldescription: String = "Usage: [OPTION]... [ARG]..." is writable
417
418 # Does `process_options` should accept an empty sequence of arguments.
419 # ie. nothing except options.
420 # Is `false` by default.
421 #
422 # If required, if should be set by the client before calling `process_options`
423 var accept_no_arguments = false is writable
424
425 # print the full usage of the tool.
426 # Is called by `process_option` on `--help`.
427 # It also could be called by the client.
428 fun usage
429 do
430 print tooldescription
431 option_context.usage
432 end
433
434 # Parse and process the options given on the command line
435 fun process_options(args: Sequence[String])
436 do
437 self.opt_warn.value = 1
438
439 # init options
440 option_context.parse(args)
441
442 if opt_help.value then
443 usage
444 exit 0
445 end
446
447 if opt_version.value then
448 print version
449 exit 0
450 end
451
452 if opt_bash_completion.value then
453 var bash_completion = new BashCompletion(self)
454 bash_completion.write_to(sys.stdout)
455 exit 0
456 end
457
458 if opt_stub_man.value then
459 print """
460 # NAME
461
462 {{{tooldescription.split("\n")[1]}}}
463
464 # SYNOPSYS
465
466 # OPTIONS
467 """
468 for o in option_context.options do
469 var first = true
470 printn "### "
471 for n in o.names do
472 if first then first = false else printn ", "
473 printn "`{n}`"
474 end
475 print ""
476 print "{o.helptext}."
477 print ""
478 end
479 print """
480 # SEE ALSO
481
482 The Nit language documentation and the source code of its tools and libraries may be downloaded from <http://nitlanguage.org>"""
483 exit 0
484 end
485
486 var errors = option_context.errors
487 if not errors.is_empty then
488 for e in errors do print "Error: {e}"
489 print tooldescription
490 print "Use --help for help"
491 exit 1
492 end
493
494 nit_dir = compute_nit_dir
495
496 if option_context.rest.is_empty and not accept_no_arguments then
497 print tooldescription
498 print "Use --help for help"
499 exit 1
500 end
501
502 # Set verbose level
503 verbose_level = opt_verbose.value
504
505 if opt_keep_going.value then keep_going = true
506
507 if self.opt_quiet.value then self.opt_warn.value = 0
508
509 if opt_log_dir.value != null then log_directory = opt_log_dir.value.as(not null)
510 if opt_log.value then
511 # Make sure the output directory exists
512 log_directory.mkdir
513
514 # Redirect the verbose messages
515 log_info = (log_directory/"info.txt").to_path.open_wo
516 end
517 end
518
519 # Get the current `nit_version` or "DUMMY_VERSION" if `--set-dummy-tool` is set.
520 fun version: String do
521 if opt_set_dummy_tool.value then
522 return "DUMMY_VERSION"
523 end
524 return nit_version
525 end
526
527 # Get the name of the tool or "DUMMY_TOOL" id `--set-dummy-tool` is set.
528 fun toolname: String do
529 if opt_set_dummy_tool.value then
530 return "DUMMY_TOOL"
531 end
532 return sys.program_name.basename
533 end
534
535 # The identified root directory of the Nit package
536 var nit_dir: String is noinit
537
538 private fun compute_nit_dir: String
539 do
540 # the option has precedence
541 var res = opt_nit_dir.value
542 if res != null then
543 if not check_nit_dir(res) then
544 fatal_error(null, "Fatal Error: the value of --nit-dir does not seem to be a valid base Nit directory: {res}.")
545 end
546 return res
547 end
548
549 # then the environ variable has precedence
550 res = "NIT_DIR".environ
551 if not res.is_empty then
552 if not check_nit_dir(res) then
553 fatal_error(null, "Fatal Error: the value of NIT_DIR does not seem to be a valid base Nit directory: {res}.")
554 end
555 return res
556 end
557
558 # find the runpath of the program from argv[0]
559 res = "{sys.program_name.dirname}/.."
560 if check_nit_dir(res) then return res.simplify_path
561
562 # find the runpath of the process from /proc
563 var exe = "/proc/self/exe"
564 if exe.file_exists then
565 res = exe.realpath
566 res = res.dirname.join_path("..")
567 if check_nit_dir(res) then return res.simplify_path
568 end
569
570 # search in the PATH
571 var ps = "PATH".environ.split(":")
572 for p in ps do
573 res = p/".."
574 if check_nit_dir(res) then return res.simplify_path
575 end
576
577 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.")
578 abort
579 end
580
581 private fun check_nit_dir(res: String): Bool
582 do
583 return res.file_exists and "{res}/src/nit.nit".file_exists
584 end
585 end
586
587 # This class generates a compatible `bash_completion` script file.
588 #
589 # On some Linux systems `bash_completion` allow the program to control command line behaviour.
590 #
591 # ~~~sh
592 # $ nitls [TAB][TAB]
593 # file1.nit file2.nit file3.nit
594 #
595 # $ nitls --[TAB][TAB]
596 # --bash-toolname --keep --path --tree
597 # --depends --log --package --verbose
598 # --disable-phase --log-dir --quiet --version
599 # --gen-bash-completion --no-color --recursive --warn
600 # --help --only-metamodel --source
601 # --ignore-visibility --only-parse --stop-on-first-error
602 # ~~~
603 #
604 # Generated file can be placed in system bash_completion directory `/etc/bash_completion.d/`
605 # or source it in `~/.bash_completion`.
606 class BashCompletion
607 super Template
608
609 var toolcontext: ToolContext
610
611 private fun extract_options_names: Array[String] do
612 var names = new Array[String]
613 for option in toolcontext.option_context.options do
614 for name in option.names do
615 if name.has_prefix("--") then names.add name
616 end
617 end
618 return names
619 end
620
621 redef fun rendering do
622 var name = toolcontext.toolname
623 var option_names = extract_options_names
624 addn "# generated bash completion file for {name} {toolcontext.version}"
625 addn "_{name}()"
626 addn "\{"
627 addn " local cur prev opts"
628 addn " COMPREPLY=()"
629 addn " cur=\"$\{COMP_WORDS[COMP_CWORD]\}\""
630 addn " prev=\"$\{COMP_WORDS[COMP_CWORD-1]\}\""
631 if not option_names.is_empty then
632 addn " opts=\"{option_names.join(" ")}\""
633 addn " if [[ $\{cur\} == -* ]] ; then"
634 addn " COMPREPLY=( $(compgen -W \"$\{opts\}\" -- $\{cur\}) )"
635 addn " return 0"
636 addn " fi"
637 end
638 addn "\} &&"
639 addn "complete -o default -F _{name} {name}"
640 end
641 end