Add --arg-from-stdin to read an argument from stdin

This commit is contained in:
Eelco Dolstra 2024-03-01 14:39:42 +01:00
parent 291b10c607
commit 8ce1f6800b
3 changed files with 16 additions and 1 deletions

View file

@ -40,6 +40,14 @@ MixEvalArgs::MixEvalArgs()
.completer = completePath
});
addFlag({
.longName = "arg-from-stdin",
.description = "Pass the contents of stdin as the argument *name* to Nix functions.",
.category = category,
.labels = {"name"},
.handler = {[&](std::string name) { autoArgs.insert_or_assign(name, AutoArg{AutoArgStdin{}}); }},
});
addFlag({
.longName = "include",
.shortName = 'I',
@ -174,6 +182,9 @@ Bindings * MixEvalArgs::getAutoArgs(EvalState & state)
},
[&](const AutoArgFile & arg) {
v->mkString(readFile(arg.path));
},
[&](const AutoArgStdin & arg) {
v->mkString(readFile(STDIN_FILENO));
}
}, arg);
res.insert(state.symbols.create(name), v);

View file

@ -29,8 +29,9 @@ private:
struct AutoArgExpr { std::string expr; };
struct AutoArgString { std::string s; };
struct AutoArgFile { std::filesystem::path path; };
struct AutoArgStdin { };
using AutoArg = std::variant<AutoArgExpr, AutoArgString, AutoArgFile>;
using AutoArg = std::variant<AutoArgExpr, AutoArgString, AutoArgFile, AutoArgStdin>;
std::map<std::string, AutoArg> autoArgs;
};

View file

@ -49,3 +49,6 @@ printf 123 > $TEST_ROOT/xyzzy/default.nix
if [[ -e /proc/version ]]; then
[[ "$(nix eval --raw --arg-from-file foo /proc/version --expr '{ foo }: { inherit foo; }' foo)" = "$(cat /proc/version)" ]]
fi
# Test --arg-from-stdin.
[[ "$(echo bla | nix eval --raw --arg-from-stdin foo --expr '{ foo }: { inherit foo; }' foo)" = bla ]]