Add --arg-from-file for reading a string from a file

This commit is contained in:
Eelco Dolstra 2024-03-01 14:35:27 +01:00
parent d72ee91d07
commit 291b10c607
3 changed files with 22 additions and 1 deletions

View file

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

View file

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

View file

@ -41,3 +41,11 @@ mkdir -p $TEST_ROOT/xyzzy $TEST_ROOT/foo
ln -sfn ../xyzzy $TEST_ROOT/foo/bar
printf 123 > $TEST_ROOT/xyzzy/default.nix
[[ $(nix eval --impure --expr "import $TEST_ROOT/foo/bar") = 123 ]]
# Test --arg-from-file.
[[ "$(nix eval --raw --arg-from-file foo config.nix --expr '{ foo }: { inherit foo; }' foo)" = "$(cat config.nix)" ]]
# Check that special(-ish) files are drained.
if [[ -e /proc/version ]]; then
[[ "$(nix eval --raw --arg-from-file foo /proc/version --expr '{ foo }: { inherit foo; }' foo)" = "$(cat /proc/version)" ]]
fi