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
28 # A warning or an error
31 redef type OTHER: Message
33 # The origin of the message in the source code, if any.
34 var location
: nullable Location
36 # The category of the message.
38 # Used by quality-control tool for statistics or to enable/disable things individually.
39 var tag
: nullable String
41 # The human-readable description of the message.
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.
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
53 return location
.as(not null) < other
.location
.as(not null)
56 redef fun to_s
: String
66 # A colored version of the message including the original source line
67 fun to_color_string
: String
70 #var red = "{esc}[0;31m"
71 #var bred = "{esc}[1;31m"
72 #var green = "{esc}[0;32m"
73 var yellow
= "{esc}[0;33m"
85 else if l
.file
== null then
86 return "{yellow}{l}{def}: {text}{tag}"
88 return "{yellow}{l}{def}: {text}{tag}\n{l.colored_line("1;31")}"
93 # Global context for tools
96 var error_count
: Int = 0
99 var warning_count
: Int = 0
101 # Directory where to generate log files
102 var log_directory
: String = "logs"
105 private var messages
= new Array[Message]
106 private var message_sorter
: Comparator = default_comparator
108 # Output all current stacked messages.
109 # If some errors occurred, exits the program.
112 if messages
.length
> 0 then
113 message_sorter
.sort
(messages
)
116 if opt_no_color
.value
then
117 sys
.stderr
.write
("{m}\n")
119 sys
.stderr
.write
("{m.to_color_string}\n")
126 if error_count
> 0 then
132 # Display total error informations
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"
141 fun error
(l
: nullable Location, s
: String)
143 messages
.add
(new Message(l
,null,s
))
144 error_count
= error_count
+ 1
145 if opt_stop_on_first_error
.value
then check_errors
148 # Add an error, show errors and quit
149 fun fatal_error
(l
: nullable Location, s
: String)
155 # Display a first-level warning.
157 # First-level warnings are warnings that SHOULD be corrected,
158 # and COULD usually be immediately corrected.
160 # * There is a simple correction
161 # * There is no reason to let the code this way (no reasonable @supresswarning-like annotation)
162 # * They always are real issues (no false positive)
164 # First-level warnings are displayed by default (except if option `-q` is given).
165 fun warning
(l
: nullable Location, tag
: String, text
: String)
167 if opt_warning
.value
.has
("no-{tag}") then return
168 if not opt_warning
.value
.has
(tag
) and opt_warn
.value
== 0 then return
169 messages
.add
(new Message(l
, tag
, text
))
170 warning_count
= warning_count
+ 1
171 if opt_stop_on_first_error
.value
then check_errors
174 # Display a second-level warning.
176 # Second-level warnings are warnings that should require investigation,
177 # but cannot always be immediately corrected.
179 # * The correction could be complex. e.g. require a refactorisation or an API change.
180 # * The correction cannot be done. e.g. Code that use a deprecated API for some compatibility reason.
181 # * There is not a real issue (false positive). Note that this should be unlikely.
182 # * Transitional: While a real warning, it fires a lot in current code, so a transition is needed
183 # in order to fix them before promoting the advice to a warning.
185 # In order to prevent warning inflation à la Java, second-level warnings are not displayed by
186 # default and require an additional option `-W`.
187 fun advice
(l
: nullable Location, tag
: String, text
: String)
189 if opt_warning
.value
.has
("no-{tag}") then return
190 if not opt_warning
.value
.has
(tag
) and opt_warn
.value
<= 1 then return
191 messages
.add
(new Message(l
, tag
, text
))
192 warning_count
= warning_count
+ 1
193 if opt_stop_on_first_error
.value
then check_errors
197 fun info
(s
: String, level
: Int)
199 if level
<= verbose_level
then
204 # Executes a program while checking if it's available and if the execution ended correctly
206 # Stops execution and prints errors if the program isn't available or didn't end correctly
207 fun exec_and_check
(args
: Array[String], error
: String)
209 var prog
= args
.first
212 # Is the wanted program available?
213 var proc_which
= new IProcess.from_a
("which", [prog
])
215 var res
= proc_which
.status
217 print
"{error}: executable \"{prog}\
" not found"
221 # Execute the wanted program
222 var proc
= new Process.from_a
(prog
, args
)
226 print
"{error}: execution of \"{prog} {args.join(" ")}\
" failed"
231 # Global OptionContext
232 var option_context
= new OptionContext
235 var opt_warn
= new OptionCount("Show more warnings", "-W", "--warn")
238 var opt_warning
= new OptionArray("Show/hide a specific warning", "-w", "--warning")
241 var opt_quiet
= new OptionBool("Do not show warnings", "-q", "--quiet")
244 var opt_log
= new OptionBool("Generate various log files", "--log")
247 var opt_log_dir
= new OptionString("Directory where to generate log files", "--log-dir")
250 var opt_nit_dir
= new OptionString("Base directory of the Nit installation", "--nit-dir")
253 var opt_help
= new OptionBool("Show Help (This screen)", "-h", "-?", "--help")
256 var opt_version
= new OptionBool("Show version and exit", "--version")
258 # Option --set-dummy-tool
259 var opt_set_dummy_tool
= new OptionBool("Set toolname and version to DUMMY. Useful for testing", "--set-dummy-tool")
262 var opt_verbose
= new OptionCount("Verbose", "-v", "--verbose")
264 # Option --stop-on-first-error
265 var opt_stop_on_first_error
= new OptionBool("Stop on first error", "--stop-on-first-error")
268 var opt_no_color
= new OptionBool("Do not use color to display errors and warnings", "--no-color")
270 # Option --bash-completion
271 var opt_bash_completion
= new OptionBool("Generate bash_completion file for this program", "--bash-completion")
274 var opt_stub_man
= new OptionBool("Generate a stub manpage in pandoc markdown format", "--stub-man")
277 var verbose_level
: Int = 0
281 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
)
283 # Hide some internal options
284 opt_stub_man
.hidden
= true
285 opt_bash_completion
.hidden
= true
286 opt_set_dummy_tool
.hidden
= true
289 # Name, usage and synopsis of the tool.
290 # It is mainly used in `usage`.
291 # Should be correctly set by the client before calling `process_options`
292 # A multi-line string is recommmended.
294 # eg. `"Usage: tool [OPTION]... [FILE]...\nDo some things."`
295 var tooldescription
: String = "Usage: [OPTION]... [ARG]..." is writable
297 # Does `process_options` should accept an empty sequence of arguments.
298 # ie. nothing except options.
299 # Is `false` by default.
301 # If required, if should be set by the client before calling `process_options`
302 var accept_no_arguments
= false is writable
304 # print the full usage of the tool.
305 # Is called by `process_option` on `--help`.
306 # It also could be called by the client.
309 print tooldescription
313 # Parse and process the options given on the command line
314 fun process_options
(args
: Sequence[String])
316 self.opt_warn
.value
= 1
319 option_context
.parse
(args
)
321 if opt_help
.value
then
326 if opt_version
.value
then
331 if opt_bash_completion
.value
then
332 var bash_completion
= new BashCompletion(self)
333 bash_completion
.write_to
(sys
.stdout
)
337 if opt_stub_man
.value
then
339 % {{{toolname.to_upper}}}(1)
343 {{{tooldescription.split("\n")[1]}}}
347 {{{toolname}}} [*options*]...
351 for o
in option_context
.options
do
354 if first
then first
= false else printn
", "
358 print
": {o.helptext}"
364 The Nit language documentation and the source code of its tools and libraries may be downloaded from <http://nitlanguage.org>"""
368 var errors
= option_context
.get_errors
369 if not errors
.is_empty
then
370 for e
in errors
do print
"Error: {e}"
371 print tooldescription
372 print
"Use --help for help"
376 nit_dir
= compute_nit_dir
378 if option_context
.rest
.is_empty
and not accept_no_arguments
then
379 print tooldescription
380 print
"Use --help for help"
385 verbose_level
= opt_verbose
.value
387 if self.opt_quiet
.value
then self.opt_warn
.value
= 0
389 if opt_log_dir
.value
!= null then log_directory
= opt_log_dir
.value
.as(not null)
390 if opt_log
.value
then
391 # Make sure the output directory exists
397 # Get the current `nit_version` or "DUMMY_VERSION" if `--set-dummy-tool` is set.
398 fun version
: String do
399 if opt_set_dummy_tool
.value
then
400 return "DUMMY_VERSION"
405 # Get the name of the tool or "DUMMY_TOOL" id `--set-dummy-tool` is set.
406 fun toolname
: String do
407 if opt_set_dummy_tool
.value
then
410 return sys
.program_name
.basename
("")
413 # The identified root directory of the Nit project
414 var nit_dir
: String is noinit
416 private fun compute_nit_dir
: String
418 # the option has precedence
419 var res
= opt_nit_dir
.value
421 if not check_nit_dir
(res
) then
422 fatal_error
(null, "Fatal Error: the value of --nit-dir does not seem to be a valid base Nit directory: {res}")
427 # then the environ variable has precedence
428 res
= "NIT_DIR".environ
429 if not res
.is_empty
then
430 if not check_nit_dir
(res
) then
431 fatal_error
(null, "Fatal Error: the value of NIT_DIR does not seem to be a valid base Nit directory: {res}")
436 # find the runpath of the program from argv[0]
437 res
= "{sys.program_name.dirname}/.."
438 if check_nit_dir
(res
) then return res
.simplify_path
440 # find the runpath of the process from /proc
441 var exe
= "/proc/self/exe"
442 if exe
.file_exists
then
444 res
= res
.dirname
.join_path
("..")
445 if check_nit_dir
(res
) then return res
.simplify_path
449 var ps
= "PATH".environ
.split
(":")
452 if check_nit_dir
(res
) then return res
.simplify_path
455 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.")
459 private fun check_nit_dir
(res
: String): Bool
461 return res
.file_exists
and "{res}/src/nit.nit".file_exists
465 # This class generates a compatible `bash_completion` script file.
467 # On some Linux systems `bash_completion` allow the program to control command line behaviour.
470 # file1.nit file2.nit file3.nit
472 # $ nitls --[TAB][TAB]
473 # --bash-toolname --keep --path --tree
474 # --depends --log --project --verbose
475 # --disable-phase --log-dir --quiet --version
476 # --gen-bash-completion --no-color --recursive --warn
477 # --help --only-metamodel --source
478 # --ignore-visibility --only-parse --stop-on-first-error
480 # Generated file can be placed in system bash_completion directory `/etc/bash_completion.d/`
481 # or source it in `~/.bash_completion`.
485 var toolcontext
: ToolContext
487 private fun extract_options_names
: Array[String] do
488 var names
= new Array[String]
489 for option
in toolcontext
.option_context
.options
do
490 for name
in option
.names
do
491 if name
.has_prefix
("--") then names
.add name
497 redef fun rendering
do
498 var name
= toolcontext
.toolname
499 var option_names
= extract_options_names
500 addn
"# generated bash completion file for {name} {toolcontext.version}"
503 addn
" local cur prev opts"
505 addn
" cur=\"$\
{COMP_WORDS[COMP_CWORD]\}\
""
506 addn
" prev=\"$\
{COMP_WORDS[COMP_CWORD-1]\}\
""
507 if not option_names
.is_empty
then
508 addn
" opts=\"{option_names.join(" ")}\
""
509 addn
" if [[ $\{cur\} == -* ]] ; then"
510 addn
" COMPREPLY=( $(compgen -W \"$\
{opts\}\
" -- $\{cur\}) )"
515 addn
"complete -o default -F _{name} {name}"