toolcontext: add a new category for warnings: advices.
[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 fun to_color_string: String
67 do
68 var esc = 27.ascii
69 var red = "{esc}[0;31m"
70 var bred = "{esc}[1;31m"
71 var green = "{esc}[0;32m"
72 var yellow = "{esc}[0;33m"
73 var def = "{esc}[0m"
74
75 var tag = tag
76 if tag != null then
77 tag = " ({tag})"
78 else
79 tag = ""
80 end
81 var l = location
82 if l == null then
83 return "{text}{tag}"
84 else if l.file == null then
85 return "{yellow}{l}{def}: {text}{tag}"
86 else
87 return "{yellow}{l}{def}: {text}{tag}\n{l.colored_line("1;31")}"
88 end
89 end
90 end
91
92 # Global context for tools
93 class ToolContext
94 # Number of errors
95 var error_count: Int = 0
96
97 # Number of warnings
98 var warning_count: Int = 0
99
100 # Directory where to generate log files
101 var log_directory: String = "logs"
102
103 # Messages
104 private var messages: Array[Message] = new Array[Message]
105 private var message_sorter: ComparableSorter[Message] = new ComparableSorter[Message]
106
107 fun check_errors
108 do
109 if messages.length > 0 then
110 message_sorter.sort(messages)
111
112 for m in messages do
113 if opt_no_color.value then
114 sys.stderr.write("{m}\n")
115 else
116 sys.stderr.write("{m.to_color_string}\n")
117 end
118 end
119
120 messages.clear
121 end
122
123 if error_count > 0 then
124 errors_info
125 exit(1)
126 end
127 end
128
129 # Display total error informations
130 fun errors_info
131 do
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"
135 end
136
137 # Display an error
138 fun error(l: nullable Location, s: String)
139 do
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
143 end
144
145 # Add an error, show errors and quit
146 fun fatal_error(l: nullable Location, s: String)
147 do
148 error(l,s)
149 check_errors
150 end
151
152 # Display a first-level warning.
153 #
154 # First-level warnings are warnings that SHOULD be corrected,
155 # and COULD usually be immediately corrected.
156 #
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)
160 #
161 # First-level warnings are displayed by default (except if option `-q` is given).
162 fun warning(l: nullable Location, tag: String, text: String)
163 do
164 if opt_warn.value == 0 then return
165 messages.add(new Message(l, tag, text))
166 warning_count = warning_count + 1
167 if opt_stop_on_first_error.value then check_errors
168 end
169
170 # Display a second-level warning.
171 #
172 # Second-level warnings are warnings that should require investigation,
173 # but cannot always be immediately corrected.
174 #
175 # * The correction could be complex. e.g. require a refactorisation or an API change.
176 # * The correction cannot be done. e.g. Code that use a deprecated API for some compatibility reason.
177 # * There is not a real issue (false positive). Note that this should be unlikely.
178 # * Transitional: While a real warning, it fires a lot in current code, so a transition is needed
179 # in order to fix them before promoting the advice to a warning.
180 #
181 # In order to prevent warning inflation à la Java, second-level warnings are not displayed by
182 # default and require an additional option `-W`.
183 fun advice(l: nullable Location, tag: String, text: String)
184 do
185 if opt_warn.value <= 1 then return
186 messages.add(new Message(l, tag, text))
187 warning_count = warning_count + 1
188 if opt_stop_on_first_error.value then check_errors
189 end
190
191 # Display an info
192 fun info(s: String, level: Int)
193 do
194 if level <= verbose_level then
195 print "{s}"
196 end
197 end
198
199 # Executes a program while checking if it's available and if the execution ended correctly
200 #
201 # Stops execution and prints errors if the program isn't available or didn't end correctly
202 fun exec_and_check(args: Array[String], error: String)
203 do
204 var prog = args.first
205 args.remove_at 0
206
207 # Is the wanted program available?
208 var proc_which = new IProcess.from_a("which", [prog])
209 proc_which.wait
210 var res = proc_which.status
211 if res != 0 then
212 print "{error}: executable \"{prog}\" not found"
213 exit 1
214 end
215
216 # Execute the wanted program
217 var proc = new Process.from_a(prog, args)
218 proc.wait
219 res = proc.status
220 if res != 0 then
221 print "{error}: execution of \"{prog} {args.join(" ")}\" failed"
222 exit 1
223 end
224 end
225
226 # Global OptionContext
227 var option_context: OptionContext = new OptionContext
228
229 # Option --warn
230 var opt_warn: OptionCount = new OptionCount("Show warnings", "-W", "--warn")
231
232 # Option --quiet
233 var opt_quiet: OptionBool = new OptionBool("Do not show warnings", "-q", "--quiet")
234
235 # Option --log
236 var opt_log: OptionBool = new OptionBool("Generate various log files", "--log")
237
238 # Option --log-dir
239 var opt_log_dir: OptionString = new OptionString("Directory where to generate log files", "--log-dir")
240
241 # Option --help
242 var opt_help: OptionBool = new OptionBool("Show Help (This screen)", "-h", "-?", "--help")
243
244 # Option --version
245 var opt_version: OptionBool = new OptionBool("Show version and exit", "--version")
246
247 # Option --set-dummy-tool
248 var opt_set_dummy_tool: OptionBool = new OptionBool("Set toolname and version to DUMMY. Useful for testing", "--set-dummy-tool")
249
250 # Option --verbose
251 var opt_verbose: OptionCount = new OptionCount("Verbose", "-v", "--verbose")
252
253 # Option --stop-on-first-error
254 var opt_stop_on_first_error: OptionBool = new OptionBool("Stop on first error", "--stop-on-first-error")
255
256 # Option --no-color
257 var opt_no_color: OptionBool = new OptionBool("Do not use color to display errors and warnings", "--no-color")
258
259 # Option --bash-completion
260 var opt_bash_completion: OptionBool = new OptionBool("Generate bash_completion file for this program", "--bash-completion")
261
262 # Verbose level
263 var verbose_level: Int = 0
264
265 init
266 do
267 option_context.add_option(opt_warn, 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)
268 end
269
270 # Name, usage and synopsis of the tool.
271 # It is mainly used in `usage`.
272 # Should be correctly set by the client before calling `process_options`
273 # A multi-line string is recommmended.
274 #
275 # eg. `"Usage: tool [OPTION]... [FILE]...\nDo some things."`
276 var tooldescription: String = "Usage: [OPTION]... [ARG]..." is writable
277
278 # Does `process_options` should accept an empty sequence of arguments.
279 # ie. nothing except options.
280 # Is `false` by default.
281 #
282 # If required, if should be set by the client before calling `process_options`
283 var accept_no_arguments = false is writable
284
285 # print the full usage of the tool.
286 # Is called by `process_option` on `--help`.
287 # It also could be called by the client.
288 fun usage
289 do
290 print tooldescription
291 option_context.usage
292 end
293
294 # Parse and process the options given on the command line
295 fun process_options(args: Sequence[String])
296 do
297 self.opt_warn.value = 1
298
299 # init options
300 option_context.parse(args)
301
302 if opt_help.value then
303 usage
304 exit 0
305 end
306
307 if opt_version.value then
308 print version
309 exit 0
310 end
311
312 if opt_bash_completion.value then
313 var bash_completion = new BashCompletion(self)
314 bash_completion.write_to(sys.stdout)
315 exit 0
316 end
317
318 var errors = option_context.get_errors
319 if not errors.is_empty then
320 for e in errors do print "Error: {e}"
321 print tooldescription
322 print "Use --help for help"
323 exit 1
324 end
325
326 if option_context.rest.is_empty and not accept_no_arguments then
327 print tooldescription
328 print "Use --help for help"
329 exit 1
330 end
331
332 # Set verbose level
333 verbose_level = opt_verbose.value
334
335 if self.opt_quiet.value then self.opt_warn.value = 0
336
337 if opt_log_dir.value != null then log_directory = opt_log_dir.value.as(not null)
338 if opt_log.value then
339 # Make sure the output directory exists
340 log_directory.mkdir
341 end
342
343 nit_dir = compute_nit_dir
344 end
345
346 # Get the current `nit_version` or "DUMMY_VERSION" if `--set-dummy-tool` is set.
347 fun version: String do
348 if opt_set_dummy_tool.value then
349 return "DUMMY_VERSION"
350 end
351 return nit_version
352 end
353
354 # Get the name of the tool or "DUMMY_TOOL" id `--set-dummy-tool` is set.
355 fun toolname: String do
356 if opt_set_dummy_tool.value then
357 return "DUMMY_TOOL"
358 end
359 return sys.program_name.basename("")
360 end
361
362 # The identified root directory of the Nit project
363 var nit_dir: nullable String = null
364
365 private fun compute_nit_dir: nullable String
366 do
367 # a environ variable has precedence
368 var res = "NIT_DIR".environ
369 if not res.is_empty then return res
370
371 # find the runpath of the program from argv[0]
372 res = "{sys.program_name.dirname}/.."
373 if res.file_exists and "{res}/src/nit.nit".file_exists then return res.simplify_path
374
375 # find the runpath of the process from /proc
376 var exe = "/proc/self/exe"
377 if exe.file_exists then
378 res = exe.realpath
379 res = res.dirname.join_path("..")
380 if res.file_exists and "{res}/src/nit.nit".file_exists then return res.simplify_path
381 end
382
383 return null
384 end
385 end
386
387 # This class generates a compatible `bash_completion` script file.
388 #
389 # On some Linux systems `bash_completion` allow the program to control command line behaviour.
390 #
391 # $ nitls [TAB][TAB]
392 # file1.nit file2.nit file3.nit
393 #
394 # $ nitls --[TAB][TAB]
395 # --bash-toolname --keep --path --tree
396 # --depends --log --project --verbose
397 # --disable-phase --log-dir --quiet --version
398 # --gen-bash-completion --no-color --recursive --warn
399 # --help --only-metamodel --source
400 # --ignore-visibility --only-parse --stop-on-first-error
401 #
402 # Generated file can be placed in system bash_completion directory `/etc/bash_completion.d/`
403 # or source it in `~/.bash_completion`.
404 class BashCompletion
405 super Template
406
407 var toolcontext: ToolContext
408
409 init(toolcontext: ToolContext) do
410 self.toolcontext = toolcontext
411 end
412
413 private fun extract_options_names: Array[String] do
414 var names = new Array[String]
415 for option in toolcontext.option_context.options do
416 for name in option.names do
417 if name.has_prefix("--") then names.add name
418 end
419 end
420 return names
421 end
422
423 redef fun rendering do
424 var name = toolcontext.toolname
425 var option_names = extract_options_names
426 addn "# generated bash completion file for {name} {toolcontext.version}"
427 addn "_{name}()"
428 addn "\{"
429 addn " local cur prev opts"
430 addn " COMPREPLY=()"
431 addn " cur=\"$\{COMP_WORDS[COMP_CWORD]\}\""
432 addn " prev=\"$\{COMP_WORDS[COMP_CWORD-1]\}\""
433 if option_names != null then
434 addn " opts=\"{option_names.join(" ")}\""
435 addn " if [[ $\{cur\} == -* ]] ; then"
436 addn " COMPREPLY=( $(compgen -W \"$\{opts\}\" -- $\{cur\}) )"
437 addn " return 0"
438 addn " fi"
439 end
440 addn "\} &&"
441 addn "complete -o default -F _{name} {name}"
442 end
443 end