1 # This file is part of NIT ( http://www.nitlanguage.org ).
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>
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
12 # http://www.apache.org/licenses/LICENSE-2.0
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.
20 # Common command-line tool infrastructure than handle options and error messages
27 import more_collections
29 # A warning or an error
32 redef type OTHER: Message
34 # The origin of the message in the source code, if any.
35 var location
: nullable Location
37 # The category of the message.
39 # Used by quality-control tool for statistics or to enable/disable things individually.
40 var tag
: nullable String
42 # The human-readable description of the message.
44 # eg. "Error: cannot find method `foo`."
46 # A good message should:
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.
52 # * be short and fit on a single line.
54 # * have meaningful information first.
55 # This helps the reader and remain usable
56 # when truncated, by an IDE for instance.
58 # * enclose identifiers, keywords and pieces of code with back-quotes.
63 # * 0 is advices (see `ToolContext::advice`)
64 # * 1 is warnings (see `ToolContext::warning`)
65 # * 2 is errors (see `ToolContext::error`)
68 # Comparisons are made on message locations.
69 redef fun <(other
: OTHER): Bool do
70 if location
== null then return true
71 if other
.location
== null then return false
73 return location
.as(not null) < other
.location
.as(not null)
76 redef fun ==(other
): Bool do
77 if not other
isa Message then return false
78 return location
== other
.location
and tag
== other
.tag
and text
== other
.text
81 redef fun to_s
: String
91 # A colored version of the message including the original source line
92 fun to_color_string
: String
94 var esc
= 27.code_point
95 #var red = "{esc}[0;31m"
96 #var bred = "{esc}[1;31m"
97 #var green = "{esc}[0;32m"
98 var yellow
= "{esc}[0;33m"
110 else if l
.file
== null then
111 return "{yellow}{l}{def}: {text}{tag}"
113 return "{yellow}{l}{def}: {text}{tag}\n{l.colored_line("1;31")}"
119 # Errors and warnings associated to this location.
120 var messages
: nullable Array[Message]
122 # Add a message to `self`
125 private fun add_message
(m
: Message)
129 ms
= new Array[Message]
134 if s
!= null then s
.messages
.add m
138 redef class SourceFile
139 # Errors and warnings associated to the whole source.
140 var messages
= new Array[Message]
143 # Global context for tools
146 var error_count
: Int = 0 is writable
149 var warning_count
: Int = 0
151 # Directory where to generate log files
152 var log_directory
: String = "logs"
154 # Stream in `log_directory` where all info messages are written
155 var log_info
: nullable Writer = null
158 private var messages
= new Array[Message]
159 private var message_sorter
: Comparator = default_comparator
161 # Does an error prevent the program to stop at `check_errors`?
164 # Set this value to `true` if you need to keep the program going in case of error.
165 var keep_going
= false is writable
167 # List of tags per source-file whose warnings are not displayed.
169 # Initially empty, it is up to the toll to fill it.
170 # The tag "all" means all warnings and advices.
171 var warning_blacklist
= new MultiHashMap[SourceFile, String]
173 # Is the source-file of `l` associated with `tag` in `warning_blacklist`?
175 # currently returns `false` if `l` is null or does not have a source-file.
176 fun is_warning_blacklisted
(l
: nullable Location, tag
: String): Bool
178 if l
== null then return false
180 if f
== null then return false
181 var tags
= warning_blacklist
.get_or_null
(f
)
182 if tags
== null then return false
183 return tags
.has
("all") or tags
.has
(tag
)
186 # Output all current stacked messages, total and exit the program
188 # If there is no error, exit with 0, else exit with 1.
193 if error_count
> 0 then exit
(1) else exit
(0)
196 # Output all current stacked messages
198 # Return true if no errors occurred.
200 # If some errors occurred, the behavior depends on the value of `keep_going`.
201 # If `keep_going` is false, then the total error informations is displayed and the program exits.
202 # Else, false is returned.
203 fun check_errors
: Bool
205 if messages
.length
> 0 then
206 message_sorter
.sort
(messages
)
209 if opt_no_color
.value
then
210 sys
.stderr
.write
("{m}\n")
212 sys
.stderr
.write
("{m.to_color_string}\n")
219 if error_count
> 0 then
220 if not keep_going
then
229 # Display total error informations
232 if error_count
== 0 and warning_count
== 0 then return
233 if opt_no_color
.value
then return
234 sys
.stderr
.write
"Errors: {error_count}. Warnings: {warning_count}.\n"
239 # Return the message (to add information)
240 fun error
(l
: nullable Location, s
: String): Message
242 var m
= new Message(l
, null, s
, 2)
243 if messages
.has
(m
) then return m
244 if l
!= null then l
.add_message m
245 if opt_warn
.value
<= -1 then return m
247 error_count
= error_count
+ 1
248 if opt_stop_on_first_error
.value
then check_errors
252 # Add an error, show errors and quit
254 # Because the program will quit, nothing is returned.
255 fun fatal_error
(l
: nullable Location, s
: String)
261 # Display a first-level warning.
263 # First-level warnings are warnings that SHOULD be corrected,
264 # and COULD usually be immediately corrected.
266 # * There is a simple correction
267 # * There is no reason to let the code this way (no reasonable @supresswarning-like annotation)
268 # * They always are real issues (no false positive)
270 # First-level warnings are displayed by default (except if option `-q` is given).
272 # Return the message (to add information) or null if the warning is disabled
273 fun warning
(l
: nullable Location, tag
: String, text
: String): nullable Message
275 if is_warning_blacklisted
(l
, tag
) then return null
276 var m
= new Message(l
, tag
, text
, 1)
277 if messages
.has
(m
) then return null
278 if l
!= null then l
.add_message m
279 if opt_warning
.value
.has
("no-{tag}") then return null
280 if not opt_warning
.value
.has
(tag
) and opt_warn
.value
<= 0 then return null
282 warning_count
= warning_count
+ 1
283 if opt_stop_on_first_error
.value
then check_errors
287 # Display a second-level warning.
289 # Second-level warnings are warnings that should require investigation,
290 # but cannot always be immediately corrected.
292 # * The correction could be complex. e.g. require a refactorisation or an API change.
293 # * The correction cannot be done. e.g. Code that use a deprecated API for some compatibility reason.
294 # * There is not a real issue (false positive). Note that this should be unlikely.
295 # * Transitional: While a real warning, it fires a lot in current code, so a transition is needed
296 # in order to fix them before promoting the advice to a warning.
298 # In order to prevent warning inflation à la Java, second-level warnings are not displayed by
299 # default and require an additional option `-W`.
301 # Return the message (to add information) or null if the warning is disabled
302 fun advice
(l
: nullable Location, tag
: String, text
: String): nullable Message
304 if is_warning_blacklisted
(l
, tag
) then return null
305 var m
= new Message(l
, tag
, text
, 0)
306 if messages
.has
(m
) then return null
307 if l
!= null then l
.add_message m
308 if opt_warning
.value
.has
("no-{tag}") then return null
309 if not opt_warning
.value
.has
(tag
) and opt_warn
.value
<= 1 then return null
311 warning_count
= warning_count
+ 1
312 if opt_stop_on_first_error
.value
then check_errors
317 fun info
(s
: String, level
: Int)
319 if level
<= verbose_level
then
322 if log_info
!= null then
328 #Â Executes a program while checking if it's available and if the execution ended correctly
330 # Stops execution and prints errors if the program isn't available or didn't end correctly
331 fun exec_and_check
(args
: Array[String], error
: String)
333 info
("+ {args.join(" ")}", 2)
335 var prog
= args
.first
338 # Is the wanted program available?
339 var proc_which
= new ProcessReader.from_a
("which", [prog
])
341 var res
= proc_which
.status
343 print_error
"{error}: executable \"{prog}\
" not found"
347 # Execute the wanted program
348 var proc
= new Process.from_a
(prog
, args
)
352 print_error
"{error}: execution of \"{prog} {args.join(" ")}\
" failed"
357 # Global OptionContext
358 var option_context
= new OptionContext
361 var opt_warn
= new OptionCount("Show additional warnings (advices)", "-W", "--warn")
364 var opt_warning
= new OptionArray("Show/hide a specific warning", "-w", "--warning")
367 var opt_quiet
= new OptionBool("Do not show warnings", "-q", "--quiet")
370 var opt_log
= new OptionBool("Generate various log files", "--log")
373 var opt_log_dir
= new OptionString("Directory where to generate log files", "--log-dir")
376 var opt_nit_dir
= new OptionString("Base directory of the Nit installation", "--nit-dir")
379 var opt_share_dir
= new OptionString("Directory containing tools assets", "--share-dir")
382 var opt_help
= new OptionBool("Show Help (This screen)", "-h", "-?", "--help")
385 var opt_version
= new OptionBool("Show version and exit", "--version")
387 # Option --set-dummy-tool
388 var opt_set_dummy_tool
= new OptionBool("Set toolname and version to DUMMY. Useful for testing", "--set-dummy-tool")
391 var opt_verbose
= new OptionCount("Additional messages from the tool", "-v", "--verbose")
393 # Option --stop-on-first-error
394 var opt_stop_on_first_error
= new OptionBool("Just display the first encountered error then stop", "--stop-on-first-error")
396 # Option --keep-going
397 var opt_keep_going
= new OptionBool("Continue after errors, whatever the consequences", "--keep-going")
400 var opt_no_color
= new OptionBool("Do not use color to display errors and warnings", "--no-color")
402 # Option --bash-completion
403 var opt_bash_completion
= new OptionBool("Generate bash_completion file for this program", "--bash-completion")
406 var opt_stub_man
= new OptionBool("Generate a stub manpage in pandoc markdown format", "--stub-man")
409 var verbose_level
: Int = 0
413 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
)
415 # Hide some internal options
416 opt_stub_man
.hidden
= true
417 opt_bash_completion
.hidden
= true
418 opt_set_dummy_tool
.hidden
= true
421 # Name, usage and synopsis of the tool.
422 # It is mainly used in `usage`.
423 # Should be correctly set by the client before calling `process_options`
424 # A multi-line string is recommmended.
426 # eg. `"Usage: tool [OPTION]... [FILE]...\nDo some things."`
427 var tooldescription
: String = "Usage: [OPTION]... [ARG]..." is writable
429 # Does `process_options` should accept an empty sequence of arguments.
430 # ie. nothing except options.
431 # Is `false` by default.
433 # If required, if should be set by the client before calling `process_options`
434 var accept_no_arguments
= false is writable
436 # print the full usage of the tool.
437 # Is called by `process_option` on `--help`.
438 # It also could be called by the client.
441 print tooldescription
445 # Parse and process the options given on the command line
446 fun process_options
(args
: Sequence[String])
448 self.opt_warn
.value
= 1
451 option_context
.parse
(args
)
453 if opt_help
.value
then
458 if opt_version
.value
then
463 if opt_bash_completion
.value
then
464 var bash_completion
= new BashCompletion(self)
465 bash_completion
.write_to
(sys
.stdout
)
469 if opt_stub_man
.value
then
473 {{{tooldescription.split("\n")[1]}}}
479 for o
in option_context
.options
do
483 if first
then first
= false else printn
", "
487 print
"{o.helptext}."
493 The Nit language documentation and the source code of its tools and libraries may be downloaded from <http://nitlanguage.org>"""
497 var errors
= option_context
.errors
498 if not errors
.is_empty
then
499 for e
in errors
do print
"Error: {e}"
500 print tooldescription
501 print
"Use --help for help"
505 nit_dir
= locate_nit_dir
507 if option_context
.rest
.is_empty
and not accept_no_arguments
then
508 print tooldescription
509 print
"Use --help for help"
514 verbose_level
= opt_verbose
.value
516 if opt_keep_going
.value
then keep_going
= true
518 if self.opt_quiet
.value
then self.opt_warn
.value
= 0
520 if opt_log_dir
.value
!= null then log_directory
= opt_log_dir
.value
.as(not null)
521 if opt_log
.value
then
522 # Make sure the output directory exists
525 # Redirect the verbose messages
526 log_info
= (log_directory
/"info.txt").to_path
.open_wo
530 # Get the current `nit_version` or "DUMMY_VERSION" if `--set-dummy-tool` is set.
531 fun version
: String do
532 if opt_set_dummy_tool
.value
then
533 return "DUMMY_VERSION"
538 # Get the name of the tool or "DUMMY_TOOL" id `--set-dummy-tool` is set.
539 fun toolname
: String do
540 if opt_set_dummy_tool
.value
then
543 return sys
.program_name
.basename
546 # The identified root directory of the Nit package
548 # It is assignable but is automatically set by `process_options` with `locate_nit_dir`.
549 var nit_dir
: nullable String = null is writable
551 # Shared files directory.
553 # Most often `nit/share/`.
554 var share_dir
: String is lazy
do
555 var sharedir
= opt_share_dir
.value
556 if sharedir
== null then
557 sharedir
= nit_dir
/ "share"
558 if not sharedir
.file_exists
then
559 fatal_error
(null, "Fatal Error: cannot locate shared files directory in {sharedir}. Uses --share-dir to define it's location.")
565 # Guess a possible nit_dir.
569 # * the option `opt_nit_dir`
570 # * the environment variable `NIT_DIR`
571 # * the runpath of the program from argv[0]
572 # * the runpath of the process from /proc
573 # * the search in PATH
575 # If there is errors (e.g. the indicated path is invalid) or if no
576 # path is found, then an error is displayed and the program exits.
578 # The result is returned without being assigned to `nit_dir`.
579 # This function is automatically called by `process_options`
580 fun locate_nit_dir
: String
582 # the option has precedence
583 var res
= opt_nit_dir
.value
585 if not check_nit_dir
(res
) then
586 fatal_error
(null, "Fatal Error: the value of --nit-dir does not seem to be a valid base Nit directory: {res}.")
591 # then the environ variable has precedence
592 res
= "NIT_DIR".environ
593 if not res
.is_empty
then
594 if not check_nit_dir
(res
) then
595 fatal_error
(null, "Fatal Error: the value of NIT_DIR does not seem to be a valid base Nit directory: {res}.")
600 # find the runpath of the program from argv[0]
601 res
= "{sys.program_name.dirname}/.."
602 if check_nit_dir
(res
) then return res
.simplify_path
604 # find the runpath of the process from /proc
605 var exe
= "/proc/self/exe"
606 if exe
.file_exists
then
608 res
= res
.dirname
.join_path
("..")
609 if check_nit_dir
(res
) then return res
.simplify_path
613 var path_sep
= if is_windows
then ";" else ":"
614 var ps
= "PATH".environ
.split
(path_sep
)
617 if check_nit_dir
(res
) then return res
.simplify_path
620 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.")
624 private fun check_nit_dir
(res
: String): Bool
626 return res
.file_exists
and "{res}/src/nit.nit".file_exists
630 # This class generates a compatible `bash_completion` script file.
632 # On some Linux systems `bash_completion` allow the program to control command line behaviour.
636 # file1.nit file2.nit file3.nit
638 # $ nitls --[TAB][TAB]
639 # --bash-toolname --keep --path --tree
640 # --depends --log --package --verbose
641 # --disable-phase --log-dir --quiet --version
642 # --gen-bash-completion --no-color --recursive --warn
643 # --help --only-metamodel --source
644 # --ignore-visibility --only-parse --stop-on-first-error
647 # Generated file can be placed in system bash_completion directory `/etc/bash_completion.d/`
648 # or source it in `~/.bash_completion`.
652 var toolcontext
: ToolContext
654 private fun extract_options_names
: Array[String] do
655 var names
= new Array[String]
656 for option
in toolcontext
.option_context
.options
do
657 for name
in option
.names
do
658 if name
.has_prefix
("--") then names
.add name
664 redef fun rendering
do
665 var name
= toolcontext
.toolname
666 var option_names
= extract_options_names
667 addn
"# generated bash completion file for {name} {toolcontext.version}"
670 addn
" local cur prev opts"
672 addn
" cur=\"$\
{COMP_WORDS[COMP_CWORD]\}\
""
673 addn
" prev=\"$\
{COMP_WORDS[COMP_CWORD-1]\}\
""
674 if not option_names
.is_empty
then
675 addn
" opts=\"{option_names.join(" ")}\
""
676 addn
" if [[ $\{cur\} == -* ]] ; then"
677 addn
" COMPREPLY=( $(compgen -W \"$\
{opts\}\
" -- $\{cur\}) )"
682 addn
"complete -o default -F _{name} {name}"