+ # search in the PATH
+ var ps = "PATH".environ.split(":")
+ for p in ps do
+ res = p/".."
+ if check_nit_dir(res) then return res.simplify_path
+ end
+
+ fatal_error(null, "Fatal Error: Cannot locate a valid base nit directory. It is quite unexpected. Try to set the environment variable `NIT_DIR` or to use the `--nit-dir` option.")
+ abort
+ end
+
+ private fun check_nit_dir(res: String): Bool
+ do
+ return res.file_exists and "{res}/src/nit.nit".file_exists
+ end
+end
+
+# This class generates a compatible `bash_completion` script file.
+#
+# On some Linux systems `bash_completion` allow the program to control command line behaviour.
+#
+# $ nitls [TAB][TAB]
+# file1.nit file2.nit file3.nit
+#
+# $ nitls --[TAB][TAB]
+# --bash-toolname --keep --path --tree
+# --depends --log --project --verbose
+# --disable-phase --log-dir --quiet --version
+# --gen-bash-completion --no-color --recursive --warn
+# --help --only-metamodel --source
+# --ignore-visibility --only-parse --stop-on-first-error
+#
+# Generated file can be placed in system bash_completion directory `/etc/bash_completion.d/`
+# or source it in `~/.bash_completion`.
+class BashCompletion
+ super Template
+
+ var toolcontext: ToolContext
+
+ private fun extract_options_names: Array[String] do
+ var names = new Array[String]
+ for option in toolcontext.option_context.options do
+ for name in option.names do
+ if name.has_prefix("--") then names.add name
+ end
+ end
+ return names
+ end
+
+ redef fun rendering do
+ var name = toolcontext.toolname
+ var option_names = extract_options_names
+ addn "# generated bash completion file for {name} {toolcontext.version}"
+ addn "_{name}()"
+ addn "\{"
+ addn " local cur prev opts"
+ addn " COMPREPLY=()"
+ addn " cur=\"$\{COMP_WORDS[COMP_CWORD]\}\""
+ addn " prev=\"$\{COMP_WORDS[COMP_CWORD-1]\}\""
+ if not option_names.is_empty then
+ addn " opts=\"{option_names.join(" ")}\""
+ addn " if [[ $\{cur\} == -* ]] ; then"
+ addn " COMPREPLY=( $(compgen -W \"$\{opts\}\" -- $\{cur\}) )"
+ addn " return 0"
+ addn " fi"
+ end
+ addn "\} &&"
+ addn "complete -o default -F _{name} {name}"