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