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