libutil/args: dont crash completion when receiving incorrect number of arguments

When using completion, the number of the word for which the shell
requests completion is provided in the environment variable
`NIX_GET_COMPLETIONS`. When the number smaller than 1 is or larger
than the number of arguments nix coredumps as a assert is violated.

This change removes the assert and instead throws an exception informing
the user that their autocomplete is most likely misconfigured.

Change-Id: I821719e470e576b6f63c06beb097338b53d183e0
This commit is contained in:
git@71rd.net
2025-05-27 14:36:51 +00:00
parent e360cf3a28
commit 20d50b049d
2 changed files with 8 additions and 1 deletions
+2 -1
View File
@@ -87,7 +87,8 @@ void RootArgs::parseCmdline(const Strings & _cmdline)
if (auto s = getEnv("NIX_GET_COMPLETIONS")) {
size_t n = std::stoi(*s);
assert(n > 0 && n <= cmdline.size());
if (!(n > 0 && n <= cmdline.size()))
throw UsageError("Invalid word number to get completion for: %zu\n. Your autocompletions might be misconfigured", n);
*std::next(cmdline.begin(), n - 1) += completionMarker;
completions = std::make_shared<Completions>();
verbosity = lvlError;
+6
View File
@@ -37,6 +37,12 @@ EOF
[[ "$(NIX_GET_COMPLETIONS=1 nix buil)" == $'normal\nbuild\t' ]]
[[ "$(NIX_GET_COMPLETIONS=2 nix flake metad)" == $'normal\nmetadata\t' ]]
# Test how completion fails if the number is not a valid index for the number of arguments
NIX_GET_COMPLETIONS=0 expectStderr 1 nix \
| grepQuiet "error: Invalid word number to get completion for:"
NIX_GET_COMPLETIONS=4 expectStderr 1 nix build a \
| grepQuiet "error: Invalid word number to get completion for:"
# Filename completion
[[ "$(NIX_GET_COMPLETIONS=2 nix build ./f)" == $'filenames\n./foo\t' ]]
[[ "$(NIX_GET_COMPLETIONS=2 nix build ./nonexistent)" == $'filenames' ]]