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