893a8435b3df3815b23cbae7c1cd219cabacdbcd
[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 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 end
139
140 # Display an error
141 fun error(l: nullable Location, s: String)
142 do
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
146 end
147
148 # Add an error, show errors and quit
149 fun fatal_error(l: nullable Location, s: String)
150 do
151 error(l,s)
152 check_errors
153 end
154
155 # Display a first-level warning.
156 #
157 # First-level warnings are warnings that SHOULD be corrected,
158 # and COULD usually be immediately corrected.
159 #
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)
163 #
164 # First-level warnings are displayed by default (except if option `-q` is given).
165 fun warning(l: nullable Location, tag: String, text: String)
166 do
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
172 end
173
174 # Display a second-level warning.
175 #
176 # Second-level warnings are warnings that should require investigation,
177 # but cannot always be immediately corrected.
178 #
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.
184 #
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)
188 do
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
194 end
195
196 # Display an info
197 fun info(s: String, level: Int)
198 do
199 if level <= verbose_level then
200 print "{s}"
201 end
202 end
203
204 # Executes a program while checking if it's available and if the execution ended correctly
205 #
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)
208 do
209 var prog = args.first
210 args.remove_at 0
211
212 # Is the wanted program available?
213 var proc_which = new IProcess.from_a("which", [prog])
214 proc_which.wait
215 var res = proc_which.status
216 if res != 0 then
217 print "{error}: executable \"{prog}\" not found"
218 exit 1
219 end
220
221 # Execute the wanted program
222 var proc = new Process.from_a(prog, args)
223 proc.wait
224 res = proc.status
225 if res != 0 then
226 print "{error}: execution of \"{prog} {args.join(" ")}\" failed"
227 exit 1
228 end
229 end
230
231 # Global OptionContext
232 var option_context = new OptionContext
233
234 # Option --warn
235 var opt_warn = new OptionCount("Show more warnings", "-W", "--warn")
236
237 # Option --warning
238 var opt_warning = new OptionArray("Show/hide a specific warning", "-w", "--warning")
239
240 # Option --quiet
241 var opt_quiet = new OptionBool("Do not show warnings", "-q", "--quiet")
242
243 # Option --log
244 var opt_log = new OptionBool("Generate various log files", "--log")
245
246 # Option --log-dir
247 var opt_log_dir = new OptionString("Directory where to generate log files", "--log-dir")
248
249 # Option --help
250 var opt_help = new OptionBool("Show Help (This screen)", "-h", "-?", "--help")
251
252 # Option --version
253 var opt_version = new OptionBool("Show version and exit", "--version")
254
255 # Option --set-dummy-tool
256 var opt_set_dummy_tool = new OptionBool("Set toolname and version to DUMMY. Useful for testing", "--set-dummy-tool")
257
258 # Option --verbose
259 var opt_verbose = new OptionCount("Verbose", "-v", "--verbose")
260
261 # Option --stop-on-first-error
262 var opt_stop_on_first_error = new OptionBool("Stop on first error", "--stop-on-first-error")
263
264 # Option --no-color
265 var opt_no_color = new OptionBool("Do not use color to display errors and warnings", "--no-color")
266
267 # Option --bash-completion
268 var opt_bash_completion = new OptionBool("Generate bash_completion file for this program", "--bash-completion")
269
270 # Verbose level
271 var verbose_level: Int = 0
272
273 init
274 do
275 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)
276 end
277
278 # Name, usage and synopsis of the tool.
279 # It is mainly used in `usage`.
280 # Should be correctly set by the client before calling `process_options`
281 # A multi-line string is recommmended.
282 #
283 # eg. `"Usage: tool [OPTION]... [FILE]...\nDo some things."`
284 var tooldescription: String = "Usage: [OPTION]... [ARG]..." is writable
285
286 # Does `process_options` should accept an empty sequence of arguments.
287 # ie. nothing except options.
288 # Is `false` by default.
289 #
290 # If required, if should be set by the client before calling `process_options`
291 var accept_no_arguments = false is writable
292
293 # print the full usage of the tool.
294 # Is called by `process_option` on `--help`.
295 # It also could be called by the client.
296 fun usage
297 do
298 print tooldescription
299 option_context.usage
300 end
301
302 # Parse and process the options given on the command line
303 fun process_options(args: Sequence[String])
304 do
305 self.opt_warn.value = 1
306
307 # init options
308 option_context.parse(args)
309
310 if opt_help.value then
311 usage
312 exit 0
313 end
314
315 if opt_version.value then
316 print version
317 exit 0
318 end
319
320 if opt_bash_completion.value then
321 var bash_completion = new BashCompletion(self)
322 bash_completion.write_to(sys.stdout)
323 exit 0
324 end
325
326 var errors = option_context.get_errors
327 if not errors.is_empty then
328 for e in errors do print "Error: {e}"
329 print tooldescription
330 print "Use --help for help"
331 exit 1
332 end
333
334 if option_context.rest.is_empty and not accept_no_arguments then
335 print tooldescription
336 print "Use --help for help"
337 exit 1
338 end
339
340 # Set verbose level
341 verbose_level = opt_verbose.value
342
343 if self.opt_quiet.value then self.opt_warn.value = 0
344
345 if opt_log_dir.value != null then log_directory = opt_log_dir.value.as(not null)
346 if opt_log.value then
347 # Make sure the output directory exists
348 log_directory.mkdir
349 end
350
351 nit_dir = compute_nit_dir
352 end
353
354 # Get the current `nit_version` or "DUMMY_VERSION" if `--set-dummy-tool` is set.
355 fun version: String do
356 if opt_set_dummy_tool.value then
357 return "DUMMY_VERSION"
358 end
359 return nit_version
360 end
361
362 # Get the name of the tool or "DUMMY_TOOL" id `--set-dummy-tool` is set.
363 fun toolname: String do
364 if opt_set_dummy_tool.value then
365 return "DUMMY_TOOL"
366 end
367 return sys.program_name.basename("")
368 end
369
370 # The identified root directory of the Nit project
371 var nit_dir: nullable String = null
372
373 private fun compute_nit_dir: nullable String
374 do
375 # a environ variable has precedence
376 var res = "NIT_DIR".environ
377 if not res.is_empty then return res
378
379 # find the runpath of the program from argv[0]
380 res = "{sys.program_name.dirname}/.."
381 if res.file_exists and "{res}/src/nit.nit".file_exists then return res.simplify_path
382
383 # find the runpath of the process from /proc
384 var exe = "/proc/self/exe"
385 if exe.file_exists then
386 res = exe.realpath
387 res = res.dirname.join_path("..")
388 if res.file_exists and "{res}/src/nit.nit".file_exists then return res.simplify_path
389 end
390
391 return null
392 end
393 end
394
395 # This class generates a compatible `bash_completion` script file.
396 #
397 # On some Linux systems `bash_completion` allow the program to control command line behaviour.
398 #
399 # $ nitls [TAB][TAB]
400 # file1.nit file2.nit file3.nit
401 #
402 # $ nitls --[TAB][TAB]
403 # --bash-toolname --keep --path --tree
404 # --depends --log --project --verbose
405 # --disable-phase --log-dir --quiet --version
406 # --gen-bash-completion --no-color --recursive --warn
407 # --help --only-metamodel --source
408 # --ignore-visibility --only-parse --stop-on-first-error
409 #
410 # Generated file can be placed in system bash_completion directory `/etc/bash_completion.d/`
411 # or source it in `~/.bash_completion`.
412 class BashCompletion
413 super Template
414
415 var toolcontext: ToolContext
416
417 init(toolcontext: ToolContext) do
418 self.toolcontext = toolcontext
419 end
420
421 private fun extract_options_names: Array[String] do
422 var names = new Array[String]
423 for option in toolcontext.option_context.options do
424 for name in option.names do
425 if name.has_prefix("--") then names.add name
426 end
427 end
428 return names
429 end
430
431 redef fun rendering do
432 var name = toolcontext.toolname
433 var option_names = extract_options_names
434 addn "# generated bash completion file for {name} {toolcontext.version}"
435 addn "_{name}()"
436 addn "\{"
437 addn " local cur prev opts"
438 addn " COMPREPLY=()"
439 addn " cur=\"$\{COMP_WORDS[COMP_CWORD]\}\""
440 addn " prev=\"$\{COMP_WORDS[COMP_CWORD-1]\}\""
441 if option_names != null then
442 addn " opts=\"{option_names.join(" ")}\""
443 addn " if [[ $\{cur\} == -* ]] ; then"
444 addn " COMPREPLY=( $(compgen -W \"$\{opts\}\" -- $\{cur\}) )"
445 addn " return 0"
446 addn " fi"
447 end
448 addn "\} &&"
449 addn "complete -o default -F _{name} {name}"
450 end
451 end