diff --git a/lix/libutil/args.cc b/lix/libutil/args.cc index bcd142607..9a75b99ee 100644 --- a/lix/libutil/args.cc +++ b/lix/libutil/args.cc @@ -86,7 +86,13 @@ void RootArgs::parseCmdline(const Strings & _cmdline) Strings cmdline(_cmdline); if (auto s = getEnv("NIX_GET_COMPLETIONS")) { - size_t n = std::stoi(*s); + size_t n = [&] { + if (auto parsed = string2Int(*s)) { + return *parsed; + } + throw UsageError("Invalid value for environment variable NIX_GET_COMPLETIONS: %s", *s); + }(); + 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; diff --git a/tests/functional/completions.sh b/tests/functional/completions.sh index 610c15529..378bd1c15 100644 --- a/tests/functional/completions.sh +++ b/tests/functional/completions.sh @@ -37,6 +37,11 @@ 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 value cant be parsed as a number +NIX_GET_COMPLETIONS="-" expectStderr 1 nix \ + | grepQuiet "error: Invalid value for environment variable NIX_GET_COMPLETIONS:" + # 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:"