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