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