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 fun to_color_string
: String
69 var red
= "{esc}[0;31m"
70 var bred
= "{esc}[1;31m"
71 var green
= "{esc}[0;32m"
72 var yellow
= "{esc}[0;33m"
84 else if l
.file
== null then
85 return "{yellow}{l}{def}: {text}{tag}"
87 return "{yellow}{l}{def}: {text}{tag}\n{l.colored_line("1;31")}"
92 # Global context for tools
95 var error_count
: Int = 0
98 var warning_count
: Int = 0
100 # Directory where to generate log files
101 var log_directory
: String = "logs"
104 private var messages
: Array[Message] = new Array[Message]
105 private var message_sorter
: ComparableSorter[Message] = new ComparableSorter[Message]
109 if messages
.length
> 0 then
110 message_sorter
.sort
(messages
)
113 if opt_no_color
.value
then
114 sys
.stderr
.write
("{m}\n")
116 sys
.stderr
.write
("{m.to_color_string}\n")
123 if error_count
> 0 then
129 # Display total error informations
132 if error_count
== 0 and warning_count
== 0 then return
133 if opt_no_color
.value
then return
134 sys
.stderr
.write
"Errors: {error_count}. Warnings: {warning_count}.\n"
138 fun error
(l
: nullable Location, s
: String)
140 messages
.add
(new Message(l
,null,s
))
141 error_count
= error_count
+ 1
142 if opt_stop_on_first_error
.value
then check_errors
145 # Add an error, show errors and quit
146 fun fatal_error
(l
: nullable Location, s
: String)
152 # Display a first-level warning.
154 # First-level warnings are warnings that SHOULD be corrected,
155 # and COULD usually be immediately corrected.
157 # * There is a simple correction
158 # * There is no reason to let the code this way (no reasonable @supresswarning-like annotation)
159 # * They always are real issues (no false positive)
161 # First-level warnings are displayed by default (except if option `-q` is given).
162 fun warning
(l
: nullable Location, tag
: String, text
: String)
164 if opt_warning
.value
.has
("no-{tag}") then return
165 if not opt_warning
.value
.has
(tag
) and opt_warn
.value
== 0 then return
166 messages
.add
(new Message(l
, tag
, text
))
167 warning_count
= warning_count
+ 1
168 if opt_stop_on_first_error
.value
then check_errors
171 # Display a second-level warning.
173 # Second-level warnings are warnings that should require investigation,
174 # but cannot always be immediately corrected.
176 # * The correction could be complex. e.g. require a refactorisation or an API change.
177 # * The correction cannot be done. e.g. Code that use a deprecated API for some compatibility reason.
178 # * There is not a real issue (false positive). Note that this should be unlikely.
179 # * Transitional: While a real warning, it fires a lot in current code, so a transition is needed
180 # in order to fix them before promoting the advice to a warning.
182 # In order to prevent warning inflation à la Java, second-level warnings are not displayed by
183 # default and require an additional option `-W`.
184 fun advice
(l
: nullable Location, tag
: String, text
: String)
186 if opt_warning
.value
.has
("no-{tag}") then return
187 if not opt_warning
.value
.has
(tag
) and opt_warn
.value
<= 1 then return
188 messages
.add
(new Message(l
, tag
, text
))
189 warning_count
= warning_count
+ 1
190 if opt_stop_on_first_error
.value
then check_errors
194 fun info
(s
: String, level
: Int)
196 if level
<= verbose_level
then
201 # Executes a program while checking if it's available and if the execution ended correctly
203 # Stops execution and prints errors if the program isn't available or didn't end correctly
204 fun exec_and_check
(args
: Array[String], error
: String)
206 var prog
= args
.first
209 # Is the wanted program available?
210 var proc_which
= new IProcess.from_a
("which", [prog
])
212 var res
= proc_which
.status
214 print
"{error}: executable \"{prog}\
" not found"
218 # Execute the wanted program
219 var proc
= new Process.from_a
(prog
, args
)
223 print
"{error}: execution of \"{prog} {args.join(" ")}\
" failed"
228 # Global OptionContext
229 var option_context
: OptionContext = new OptionContext
232 var opt_warn
: OptionCount = new OptionCount("Show more warnings", "-W", "--warn")
235 var opt_warning
= new OptionArray("Show/hide a specific warning", "-w", "--warning")
238 var opt_quiet
: OptionBool = new OptionBool("Do not show warnings", "-q", "--quiet")
241 var opt_log
: OptionBool = new OptionBool("Generate various log files", "--log")
244 var opt_log_dir
: OptionString = new OptionString("Directory where to generate log files", "--log-dir")
247 var opt_help
: OptionBool = new OptionBool("Show Help (This screen)", "-h", "-?", "--help")
250 var opt_version
: OptionBool = new OptionBool("Show version and exit", "--version")
252 # Option --set-dummy-tool
253 var opt_set_dummy_tool
: OptionBool = new OptionBool("Set toolname and version to DUMMY. Useful for testing", "--set-dummy-tool")
256 var opt_verbose
: OptionCount = new OptionCount("Verbose", "-v", "--verbose")
258 # Option --stop-on-first-error
259 var opt_stop_on_first_error
: OptionBool = new OptionBool("Stop on first error", "--stop-on-first-error")
262 var opt_no_color
: OptionBool = new OptionBool("Do not use color to display errors and warnings", "--no-color")
264 # Option --bash-completion
265 var opt_bash_completion
: OptionBool = new OptionBool("Generate bash_completion file for this program", "--bash-completion")
268 var verbose_level
: Int = 0
272 option_context
.add_option
(opt_warn
, opt_warning
, opt_quiet
, opt_stop_on_first_error
, opt_no_color
, opt_log
, opt_log_dir
, opt_help
, opt_version
, opt_set_dummy_tool
, opt_verbose
, opt_bash_completion
)
275 # Name, usage and synopsis of the tool.
276 # It is mainly used in `usage`.
277 # Should be correctly set by the client before calling `process_options`
278 # A multi-line string is recommmended.
280 # eg. `"Usage: tool [OPTION]... [FILE]...\nDo some things."`
281 var tooldescription
: String = "Usage: [OPTION]... [ARG]..." is writable
283 # Does `process_options` should accept an empty sequence of arguments.
284 # ie. nothing except options.
285 # Is `false` by default.
287 # If required, if should be set by the client before calling `process_options`
288 var accept_no_arguments
= false is writable
290 # print the full usage of the tool.
291 # Is called by `process_option` on `--help`.
292 # It also could be called by the client.
295 print tooldescription
299 # Parse and process the options given on the command line
300 fun process_options
(args
: Sequence[String])
302 self.opt_warn
.value
= 1
305 option_context
.parse
(args
)
307 if opt_help
.value
then
312 if opt_version
.value
then
317 if opt_bash_completion
.value
then
318 var bash_completion
= new BashCompletion(self)
319 bash_completion
.write_to
(sys
.stdout
)
323 var errors
= option_context
.get_errors
324 if not errors
.is_empty
then
325 for e
in errors
do print
"Error: {e}"
326 print tooldescription
327 print
"Use --help for help"
331 if option_context
.rest
.is_empty
and not accept_no_arguments
then
332 print tooldescription
333 print
"Use --help for help"
338 verbose_level
= opt_verbose
.value
340 if self.opt_quiet
.value
then self.opt_warn
.value
= 0
342 if opt_log_dir
.value
!= null then log_directory
= opt_log_dir
.value
.as(not null)
343 if opt_log
.value
then
344 # Make sure the output directory exists
348 nit_dir
= compute_nit_dir
351 # Get the current `nit_version` or "DUMMY_VERSION" if `--set-dummy-tool` is set.
352 fun version
: String do
353 if opt_set_dummy_tool
.value
then
354 return "DUMMY_VERSION"
359 # Get the name of the tool or "DUMMY_TOOL" id `--set-dummy-tool` is set.
360 fun toolname
: String do
361 if opt_set_dummy_tool
.value
then
364 return sys
.program_name
.basename
("")
367 # The identified root directory of the Nit project
368 var nit_dir
: nullable String = null
370 private fun compute_nit_dir
: nullable String
372 # a environ variable has precedence
373 var res
= "NIT_DIR".environ
374 if not res
.is_empty
then return res
376 # find the runpath of the program from argv[0]
377 res
= "{sys.program_name.dirname}/.."
378 if res
.file_exists
and "{res}/src/nit.nit".file_exists
then return res
.simplify_path
380 # find the runpath of the process from /proc
381 var exe
= "/proc/self/exe"
382 if exe
.file_exists
then
384 res
= res
.dirname
.join_path
("..")
385 if res
.file_exists
and "{res}/src/nit.nit".file_exists
then return res
.simplify_path
392 # This class generates a compatible `bash_completion` script file.
394 # On some Linux systems `bash_completion` allow the program to control command line behaviour.
397 # file1.nit file2.nit file3.nit
399 # $ nitls --[TAB][TAB]
400 # --bash-toolname --keep --path --tree
401 # --depends --log --project --verbose
402 # --disable-phase --log-dir --quiet --version
403 # --gen-bash-completion --no-color --recursive --warn
404 # --help --only-metamodel --source
405 # --ignore-visibility --only-parse --stop-on-first-error
407 # Generated file can be placed in system bash_completion directory `/etc/bash_completion.d/`
408 # or source it in `~/.bash_completion`.
412 var toolcontext
: ToolContext
414 init(toolcontext
: ToolContext) do
415 self.toolcontext
= toolcontext
418 private fun extract_options_names
: Array[String] do
419 var names
= new Array[String]
420 for option
in toolcontext
.option_context
.options
do
421 for name
in option
.names
do
422 if name
.has_prefix
("--") then names
.add name
428 redef fun rendering
do
429 var name
= toolcontext
.toolname
430 var option_names
= extract_options_names
431 addn
"# generated bash completion file for {name} {toolcontext.version}"
434 addn
" local cur prev opts"
436 addn
" cur=\"$\
{COMP_WORDS[COMP_CWORD]\}\
""
437 addn
" prev=\"$\
{COMP_WORDS[COMP_CWORD-1]\}\
""
438 if option_names
!= null then
439 addn
" opts=\"{option_names.join(" ")}\
""
440 addn
" if [[ $\{cur\} == -* ]] ; then"
441 addn
" COMPREPLY=( $(compgen -W \"$\
{opts\}\
" -- $\{cur\}) )"
446 addn
"complete -o default -F _{name} {name}"