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