+
+ nit_dir = compute_nit_dir
+ end
+
+ # Get the current `nit_version` or "DUMMY_VERSION" if `--set-dummy-tool` is set.
+ fun version: String do
+ if opt_set_dummy_tool.value then
+ return "DUMMY_VERSION"
+ end
+ return nit_version
+ end
+
+ # Get the name of the tool or "DUMMY_TOOL" id `--set-dummy-tool` is set.
+ fun toolname: String do
+ if opt_set_dummy_tool.value then
+ return "DUMMY_TOOL"
+ end
+ return sys.program_name.basename("")
+ end
+
+ # The identified root directory of the Nit project
+ var nit_dir: nullable String = null
+
+ private fun compute_nit_dir: nullable String
+ do
+ # a environ variable has precedence
+ var res = "NIT_DIR".environ
+ if not res.is_empty then return res
+
+ # find the runpath of the program from argv[0]
+ res = "{sys.program_name.dirname}/.."
+ if res.file_exists and "{res}/src/nit.nit".file_exists then return res.simplify_path
+
+ # find the runpath of the process from /proc
+ var exe = "/proc/self/exe"
+ if exe.file_exists then
+ res = exe.realpath
+ res = res.dirname.join_path("..")
+ if res.file_exists and "{res}/src/nit.nit".file_exists then return res.simplify_path
+ end
+
+ return null
+ 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
+
+ init(toolcontext: ToolContext) do
+ self.toolcontext = toolcontext
+ end
+
+ 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 option_names != null 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}"