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