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