Merge remote-tracking branch 'origin/master' into flakes

This commit is contained in:
Eelco Dolstra 2020-05-05 18:59:33 +02:00
commit 6f3244ce45
40 changed files with 635 additions and 501 deletions

View file

@ -56,6 +56,3 @@
#include <sys/wait.h> #include <sys/wait.h>
#include <termios.h> #include <termios.h>
#include <unistd.h> #include <unistd.h>
#include "util.hh"
#include "args.hh"

View file

@ -12,44 +12,48 @@ namespace nix {
MixEvalArgs::MixEvalArgs() MixEvalArgs::MixEvalArgs()
{ {
mkFlag() addFlag({
.longName("arg") .longName = "arg",
.description("argument to be passed to Nix functions") .description = "argument to be passed to Nix functions",
.labels({"name", "expr"}) .labels = {"name", "expr"},
.handler([&](std::vector<std::string> ss) { autoArgs[ss[0]] = 'E' + ss[1]; }); .handler = {[&](std::string name, std::string expr) { autoArgs[name] = 'E' + expr; }}
});
mkFlag() addFlag({
.longName("argstr") .longName = "argstr",
.description("string-valued argument to be passed to Nix functions") .description = "string-valued argument to be passed to Nix functions",
.labels({"name", "string"}) .labels = {"name", "string"},
.handler([&](std::vector<std::string> ss) { autoArgs[ss[0]] = 'S' + ss[1]; }); .handler = {[&](std::string name, std::string s) { autoArgs[name] = 'S' + s; }},
});
mkFlag() addFlag({
.shortName('I') .longName = "include",
.longName("include") .shortName = 'I',
.description("add a path to the list of locations used to look up <...> file names") .description = "add a path to the list of locations used to look up <...> file names",
.label("path") .labels = {"path"},
.handler([&](std::string s) { searchPath.push_back(s); }); .handler = {[&](std::string s) { searchPath.push_back(s); }}
});
mkFlag() addFlag({
.longName("impure") .longName = "impure",
.description("allow access to mutable paths and repositories") .description = "allow access to mutable paths and repositories",
.handler([&](std::vector<std::string> ss) { .handler = {[&]() {
evalSettings.pureEval = false; evalSettings.pureEval = false;
}); }},
});
mkFlag() addFlag({
.longName("override-flake") .longName = "override-flake",
.labels({"original-ref", "resolved-ref"}) .description = "override a flake registry value",
.description("override a flake registry value") .labels = {"original-ref", "resolved-ref"},
.arity(2) .handler = {[&](std::string _from, std::string _to) {
.handler([&](std::vector<std::string> ss) { auto from = parseFlakeRef(_from, absPath("."));
auto from = parseFlakeRef(ss[0], absPath(".")); auto to = parseFlakeRef(_to, absPath("."));
auto to = parseFlakeRef(ss[1], absPath(".")); fetchers::Attrs extraAttrs;
fetchers::Attrs extraAttrs; if (to.subdir != "") extraAttrs["dir"] = to.subdir;
if (to.subdir != "") extraAttrs["dir"] = to.subdir; fetchers::overrideRegistry(from.input, to.input, extraAttrs);
fetchers::overrideRegistry(from.input, to.input, extraAttrs); }}
}); });
} }
Bindings * MixEvalArgs::getAutoArgs(EvalState & state) Bindings * MixEvalArgs::getAutoArgs(EvalState & state)

View file

@ -6,43 +6,47 @@ namespace nix {
MixCommonArgs::MixCommonArgs(const string & programName) MixCommonArgs::MixCommonArgs(const string & programName)
: programName(programName) : programName(programName)
{ {
mkFlag() addFlag({
.longName("verbose") .longName = "verbose",
.shortName('v') .shortName = 'v',
.description("increase verbosity level") .description = "increase verbosity level",
.handler([]() { verbosity = (Verbosity) (verbosity + 1); }); .handler = {[]() { verbosity = (Verbosity) (verbosity + 1); }},
});
mkFlag() addFlag({
.longName("quiet") .longName = "quiet",
.description("decrease verbosity level") .description = "decrease verbosity level",
.handler([]() { verbosity = verbosity > lvlError ? (Verbosity) (verbosity - 1) : lvlError; }); .handler = {[]() { verbosity = verbosity > lvlError ? (Verbosity) (verbosity - 1) : lvlError; }},
});
mkFlag() addFlag({
.longName("debug") .longName = "debug",
.description("enable debug output") .description = "enable debug output",
.handler([]() { verbosity = lvlDebug; }); .handler = {[]() { verbosity = lvlDebug; }},
});
mkFlag() addFlag({
.longName("option") .longName = "option",
.labels({"name", "value"}) .description = "set a Nix configuration option (overriding nix.conf)",
.description("set a Nix configuration option (overriding nix.conf)") .labels = {"name", "value"},
.arity(2) .handler = {[](std::string name, std::string value) {
.handler([](std::vector<std::string> ss) {
try { try {
globalConfig.set(ss[0], ss[1]); globalConfig.set(name, value);
} catch (UsageError & e) { } catch (UsageError & e) {
warn(e.what()); warn(e.what());
} }
}); }},
});
mkFlag() addFlag({
.longName("max-jobs") .longName = "max-jobs",
.shortName('j') .shortName = 'j',
.label("jobs") .description = "maximum number of parallel builds",
.description("maximum number of parallel builds") .labels = Strings{"jobs"},
.handler([=](std::string s) { .handler = {[=](std::string s) {
settings.set("max-jobs", s); settings.set("max-jobs", s);
}); }}
});
std::string cat = "config"; std::string cat = "config";
globalConfig.convertToArgs(*this, cat); globalConfig.convertToArgs(*this, cat);

View file

@ -165,28 +165,32 @@ LegacyArgs::LegacyArgs(const std::string & programName,
std::function<bool(Strings::iterator & arg, const Strings::iterator & end)> parseArg) std::function<bool(Strings::iterator & arg, const Strings::iterator & end)> parseArg)
: MixCommonArgs(programName), parseArg(parseArg) : MixCommonArgs(programName), parseArg(parseArg)
{ {
mkFlag() addFlag({
.longName("no-build-output") .longName = "no-build-output",
.shortName('Q') .shortName = 'Q',
.description("do not show build output") .description = "do not show build output",
.set(&settings.verboseBuild, false); .handler = {&settings.verboseBuild, false},
});
mkFlag() addFlag({
.longName("keep-failed") .longName = "keep-failed",
.shortName('K') .shortName ='K',
.description("keep temporary directories of failed builds") .description = "keep temporary directories of failed builds",
.set(&(bool&) settings.keepFailed, true); .handler = {&(bool&) settings.keepFailed, true},
});
mkFlag() addFlag({
.longName("keep-going") .longName = "keep-going",
.shortName('k') .shortName ='k',
.description("keep going after a build fails") .description = "keep going after a build fails",
.set(&(bool&) settings.keepGoing, true); .handler = {&(bool&) settings.keepGoing, true},
});
mkFlag() addFlag({
.longName("fallback") .longName = "fallback",
.description("build from source if substitution fails") .description = "build from source if substitution fails",
.set(&(bool&) settings.tryFallback, true); .handler = {&(bool&) settings.tryFallback, true},
});
auto intSettingAlias = [&](char shortName, const std::string & longName, auto intSettingAlias = [&](char shortName, const std::string & longName,
const std::string & description, const std::string & dest) { const std::string & description, const std::string & dest) {
@ -205,11 +209,12 @@ LegacyArgs::LegacyArgs(const std::string & programName,
mkFlag(0, "no-gc-warning", "disable warning about not using '--add-root'", mkFlag(0, "no-gc-warning", "disable warning about not using '--add-root'",
&gcWarning, false); &gcWarning, false);
mkFlag() addFlag({
.longName("store") .longName = "store",
.label("store-uri") .description = "URI of the Nix store to use",
.description("URI of the Nix store to use") .labels = {"store-uri"},
.dest(&(std::string&) settings.storeUri); .handler = {&(std::string&) settings.storeUri},
});
} }

View file

@ -167,21 +167,24 @@ template<> void BaseSetting<SandboxMode>::toJSON(JSONPlaceholder & out)
template<> void BaseSetting<SandboxMode>::convertToArg(Args & args, const std::string & category) template<> void BaseSetting<SandboxMode>::convertToArg(Args & args, const std::string & category)
{ {
args.mkFlag() args.addFlag({
.longName(name) .longName = name,
.description("Enable sandboxing.") .description = "Enable sandboxing.",
.handler([=](std::vector<std::string> ss) { override(smEnabled); }) .category = category,
.category(category); .handler = {[=]() { override(smEnabled); }}
args.mkFlag() });
.longName("no-" + name) args.addFlag({
.description("Disable sandboxing.") .longName = "no-" + name,
.handler([=](std::vector<std::string> ss) { override(smDisabled); }) .description = "Disable sandboxing.",
.category(category); .category = category,
args.mkFlag() .handler = {[=]() { override(smDisabled); }}
.longName("relaxed-" + name) });
.description("Enable sandboxing, but allow builds to disable it.") args.addFlag({
.handler([=](std::vector<std::string> ss) { override(smRelaxed); }) .longName = "relaxed-" + name,
.category(category); .description = "Enable sandboxing, but allow builds to disable it.",
.category = category,
.handler = {[=]() { override(smRelaxed); }}
});
} }
void MaxBuildJobsSetting::set(const std::string & str) void MaxBuildJobsSetting::set(const std::string & str)

View file

@ -779,8 +779,10 @@ std::exception_ptr RemoteStore::Connection::processStderr(Sink * sink, Source *
return std::make_exception_ptr(Error(status, error)); return std::make_exception_ptr(Error(status, error));
} }
else if (msg == STDERR_NEXT) else if (msg == STDERR_NEXT) {
printError(chomp(readString(from))); string s = chomp(readString(from));
printMsg(lvlVomit, "stderr %s", s);
}
else if (msg == STDERR_START_ACTIVITY) { else if (msg == STDERR_START_ACTIVITY) {
auto act = readNum<ActivityId>(from); auto act = readNum<ActivityId>(from);

View file

@ -1,13 +1,15 @@
#pragma once #pragma once
namespace nix namespace nix {
{
/* Some ANSI escape sequences. */ /* Some ANSI escape sequences. */
#define ANSI_NORMAL "\e[0m" #define ANSI_NORMAL "\e[0m"
#define ANSI_BOLD "\e[1m" #define ANSI_BOLD "\e[1m"
#define ANSI_FAINT "\e[2m" #define ANSI_FAINT "\e[2m"
#define ANSI_RED "\e[31;1m" #define ANSI_ITALIC "\e[3m"
#define ANSI_GREEN "\e[32;1m" #define ANSI_RED "\e[31;1m"
#define ANSI_YELLOW "\e[33;1m" #define ANSI_GREEN "\e[32;1m"
#define ANSI_BLUE "\e[34;1m" #define ANSI_YELLOW "\e[33;1m"
#define ANSI_BLUE "\e[34;1m"
} }

View file

@ -3,16 +3,14 @@
namespace nix { namespace nix {
Args::FlagMaker Args::mkFlag() void Args::addFlag(Flag && flag_)
{
return FlagMaker(*this);
}
Args::FlagMaker::~FlagMaker()
{ {
auto flag = std::make_shared<Flag>(std::move(flag_));
if (flag->handler.arity != ArityAny)
assert(flag->handler.arity == flag->labels.size());
assert(flag->longName != ""); assert(flag->longName != "");
args.longFlags[flag->longName] = flag; longFlags[flag->longName] = flag;
if (flag->shortName) args.shortFlags[flag->shortName] = flag; if (flag->shortName) shortFlags[flag->shortName] = flag;
} }
void Args::parseCmdline(const Strings & _cmdline) void Args::parseCmdline(const Strings & _cmdline)
@ -61,7 +59,7 @@ void Args::parseCmdline(const Strings & _cmdline)
void Args::printHelp(const string & programName, std::ostream & out) void Args::printHelp(const string & programName, std::ostream & out)
{ {
std::cout << "Usage: " << programName << " <FLAGS>..."; std::cout << fmt(ANSI_BOLD "Usage:" ANSI_NORMAL " %s " ANSI_ITALIC "FLAGS..." ANSI_NORMAL, programName);
for (auto & exp : expectedArgs) { for (auto & exp : expectedArgs) {
std::cout << renderLabels({exp.label}); std::cout << renderLabels({exp.label});
// FIXME: handle arity > 1 // FIXME: handle arity > 1
@ -72,11 +70,11 @@ void Args::printHelp(const string & programName, std::ostream & out)
auto s = description(); auto s = description();
if (s != "") if (s != "")
std::cout << "\nSummary: " << s << ".\n"; std::cout << "\n" ANSI_BOLD "Summary:" ANSI_NORMAL " " << s << ".\n";
if (longFlags.size()) { if (longFlags.size()) {
std::cout << "\n"; std::cout << "\n";
std::cout << "Flags:\n"; std::cout << ANSI_BOLD "Flags:" ANSI_NORMAL "\n";
printFlags(out); printFlags(out);
} }
} }
@ -101,15 +99,14 @@ bool Args::processFlag(Strings::iterator & pos, Strings::iterator end)
auto process = [&](const std::string & name, const Flag & flag) -> bool { auto process = [&](const std::string & name, const Flag & flag) -> bool {
++pos; ++pos;
std::vector<std::string> args; std::vector<std::string> args;
for (size_t n = 0 ; n < flag.arity; ++n) { for (size_t n = 0 ; n < flag.handler.arity; ++n) {
if (pos == end) { if (pos == end) {
if (flag.arity == ArityAny) break; if (flag.handler.arity == ArityAny) break;
throw UsageError(format("flag '%1%' requires %2% argument(s)") throw UsageError("flag '%s' requires %d argument(s)", name, flag.handler.arity);
% name % flag.arity);
} }
args.push_back(*pos++); args.push_back(*pos++);
} }
flag.handler(std::move(args)); flag.handler.fun(std::move(args));
return true; return true;
}; };
@ -157,17 +154,18 @@ bool Args::processArgs(const Strings & args, bool finish)
return res; return res;
} }
Args::FlagMaker & Args::FlagMaker::mkHashTypeFlag(HashType * ht) Args::Flag Args::Flag::mkHashTypeFlag(std::string && longName, HashType * ht)
{ {
arity(1); return Flag {
label("type"); .longName = std::move(longName),
description("hash algorithm ('md5', 'sha1', 'sha256', or 'sha512')"); .description = "hash algorithm ('md5', 'sha1', 'sha256', or 'sha512')",
handler([ht](std::string s) { .labels = {"hash-algo"},
*ht = parseHashType(s); .handler = {[ht](std::string s) {
if (*ht == htUnknown) *ht = parseHashType(s);
throw UsageError("unknown hash type '%1%'", s); if (*ht == htUnknown)
}); throw UsageError("unknown hash type '%1%'", s);
return *this; }}
};
} }
Strings argvToStrings(int argc, char * * argv) Strings argvToStrings(int argc, char * * argv)
@ -183,7 +181,7 @@ std::string renderLabels(const Strings & labels)
std::string res; std::string res;
for (auto label : labels) { for (auto label : labels) {
for (auto & c : label) c = std::toupper(c); for (auto & c : label) c = std::toupper(c);
res += " <" + label + ">"; res += " " ANSI_ITALIC + label + ANSI_NORMAL;
} }
return res; return res;
} }
@ -192,10 +190,10 @@ void printTable(std::ostream & out, const Table2 & table)
{ {
size_t max = 0; size_t max = 0;
for (auto & row : table) for (auto & row : table)
max = std::max(max, row.first.size()); max = std::max(max, filterANSIEscapes(row.first, true).size());
for (auto & row : table) { for (auto & row : table) {
out << " " << row.first out << " " << row.first
<< std::string(max - row.first.size() + 2, ' ') << std::string(max - filterANSIEscapes(row.first, true).size() + 2, ' ')
<< row.second << "\n"; << row.second << "\n";
} }
} }
@ -206,8 +204,7 @@ void Command::printHelp(const string & programName, std::ostream & out)
auto exs = examples(); auto exs = examples();
if (!exs.empty()) { if (!exs.empty()) {
out << "\n"; out << "\n" ANSI_BOLD "Examples:" ANSI_NORMAL "\n";
out << "Examples:\n";
for (auto & ex : exs) for (auto & ex : exs)
out << "\n" out << "\n"
<< " " << ex.description << "\n" // FIXME: wrap << " " << ex.description << "\n" // FIXME: wrap
@ -223,49 +220,55 @@ MultiCommand::MultiCommand(const Commands & commands)
auto i = commands.find(ss[0]); auto i = commands.find(ss[0]);
if (i == commands.end()) if (i == commands.end())
throw UsageError("'%s' is not a recognised command", ss[0]); throw UsageError("'%s' is not a recognised command", ss[0]);
command = i->second(); command = {ss[0], i->second()};
command->_name = ss[0];
}}); }});
categories[Command::catDefault] = "Available commands";
} }
void MultiCommand::printHelp(const string & programName, std::ostream & out) void MultiCommand::printHelp(const string & programName, std::ostream & out)
{ {
if (command) { if (command) {
command->printHelp(programName + " " + command->name(), out); command->second->printHelp(programName + " " + command->first, out);
return; return;
} }
out << "Usage: " << programName << " <COMMAND> <FLAGS>... <ARGS>...\n"; out << fmt(ANSI_BOLD "Usage:" ANSI_NORMAL " %s " ANSI_ITALIC "COMMAND FLAGS... ARGS..." ANSI_NORMAL "\n", programName);
out << "\n"; out << "\n" ANSI_BOLD "Common flags:" ANSI_NORMAL "\n";
out << "Common flags:\n";
printFlags(out); printFlags(out);
out << "\n"; std::map<Command::Category, std::map<std::string, ref<Command>>> commandsByCategory;
out << "Available commands:\n";
Table2 table; for (auto & [name, commandFun] : commands) {
for (auto & i : commands) { auto command = commandFun();
auto command = i.second(); commandsByCategory[command->category()].insert_or_assign(name, command);
command->_name = i.first; }
auto descr = command->description();
if (!descr.empty()) for (auto & [category, commands] : commandsByCategory) {
table.push_back(std::make_pair(command->name(), descr)); out << fmt("\n" ANSI_BOLD "%s:" ANSI_NORMAL "\n", categories[category]);
Table2 table;
for (auto & [name, command] : commands) {
auto descr = command->description();
if (!descr.empty())
table.push_back(std::make_pair(name, descr));
}
printTable(out, table);
} }
printTable(out, table);
} }
bool MultiCommand::processFlag(Strings::iterator & pos, Strings::iterator end) bool MultiCommand::processFlag(Strings::iterator & pos, Strings::iterator end)
{ {
if (Args::processFlag(pos, end)) return true; if (Args::processFlag(pos, end)) return true;
if (command && command->processFlag(pos, end)) return true; if (command && command->second->processFlag(pos, end)) return true;
return false; return false;
} }
bool MultiCommand::processArgs(const Strings & args, bool finish) bool MultiCommand::processArgs(const Strings & args, bool finish)
{ {
if (command) if (command)
return command->processArgs(args, finish); return command->second->processArgs(args, finish);
else else
return Args::processArgs(args, finish); return Args::processArgs(args, finish);
} }

View file

@ -32,13 +32,59 @@ protected:
struct Flag struct Flag
{ {
typedef std::shared_ptr<Flag> ptr; typedef std::shared_ptr<Flag> ptr;
struct Handler
{
std::function<void(std::vector<std::string>)> fun;
size_t arity;
Handler() {}
Handler(std::function<void(std::vector<std::string>)> && fun)
: fun(std::move(fun))
, arity(ArityAny)
{ }
Handler(std::function<void()> && handler)
: fun([handler{std::move(handler)}](std::vector<std::string>) { handler(); })
, arity(0)
{ }
Handler(std::function<void(std::string)> && handler)
: fun([handler{std::move(handler)}](std::vector<std::string> ss) {
handler(std::move(ss[0]));
})
, arity(1)
{ }
Handler(std::function<void(std::string, std::string)> && handler)
: fun([handler{std::move(handler)}](std::vector<std::string> ss) {
handler(std::move(ss[0]), std::move(ss[1]));
})
, arity(2)
{ }
template<class T>
Handler(T * dest)
: fun([=](std::vector<std::string> ss) { *dest = ss[0]; })
, arity(1)
{ }
template<class T>
Handler(T * dest, const T & val)
: fun([=](std::vector<std::string> ss) { *dest = val; })
, arity(0)
{ }
};
std::string longName; std::string longName;
char shortName = 0; char shortName = 0;
std::string description; std::string description;
Strings labels;
size_t arity = 0;
std::function<void(std::vector<std::string>)> handler;
std::string category; std::string category;
Strings labels;
Handler handler;
static Flag mkHashTypeFlag(std::string && longName, HashType * ht);
}; };
std::map<std::string, Flag::ptr> longFlags; std::map<std::string, Flag::ptr> longFlags;
@ -65,49 +111,7 @@ protected:
public: public:
class FlagMaker void addFlag(Flag && flag);
{
Args & args;
Flag::ptr flag;
friend class Args;
FlagMaker(Args & args) : args(args), flag(std::make_shared<Flag>()) { }
public:
~FlagMaker();
FlagMaker & longName(const std::string & s) { flag->longName = s; return *this; }
FlagMaker & shortName(char s) { flag->shortName = s; return *this; }
FlagMaker & description(const std::string & s) { flag->description = s; return *this; }
FlagMaker & label(const std::string & l) { flag->arity = 1; flag->labels = {l}; return *this; }
FlagMaker & labels(const Strings & ls) { flag->arity = ls.size(); flag->labels = ls; return *this; }
FlagMaker & arity(size_t arity) { flag->arity = arity; return *this; }
FlagMaker & handler(std::function<void(std::vector<std::string>)> handler) { flag->handler = handler; return *this; }
FlagMaker & handler(std::function<void()> handler) { flag->handler = [handler](std::vector<std::string>) { handler(); }; return *this; }
FlagMaker & handler(std::function<void(std::string)> handler) {
flag->arity = 1;
flag->handler = [handler](std::vector<std::string> ss) { handler(std::move(ss[0])); };
return *this;
}
FlagMaker & category(const std::string & s) { flag->category = s; return *this; }
template<class T>
FlagMaker & dest(T * dest)
{
flag->arity = 1;
flag->handler = [=](std::vector<std::string> ss) { *dest = ss[0]; };
return *this;
}
template<class T>
FlagMaker & set(T * dest, const T & val)
{
flag->arity = 0;
flag->handler = [=](std::vector<std::string> ss) { *dest = val; };
return *this;
}
FlagMaker & mkHashTypeFlag(HashType * ht);
};
FlagMaker mkFlag();
/* Helper functions for constructing flags / positional /* Helper functions for constructing flags / positional
arguments. */ arguments. */
@ -116,13 +120,13 @@ public:
const std::string & label, const std::string & description, const std::string & label, const std::string & description,
std::function<void(std::string)> fun) std::function<void(std::string)> fun)
{ {
mkFlag() addFlag({
.shortName(shortName) .longName = longName,
.longName(longName) .shortName = shortName,
.labels({label}) .description = description,
.description(description) .labels = {label},
.arity(1) .handler = {[=](std::string s) { fun(s); }}
.handler([=](std::vector<std::string> ss) { fun(ss[0]); }); });
} }
void mkFlag(char shortName, const std::string & name, void mkFlag(char shortName, const std::string & name,
@ -135,11 +139,12 @@ public:
void mkFlag(char shortName, const std::string & longName, const std::string & description, void mkFlag(char shortName, const std::string & longName, const std::string & description,
T * dest, const T & value) T * dest, const T & value)
{ {
mkFlag() addFlag({
.shortName(shortName) .longName = longName,
.longName(longName) .shortName = shortName,
.description(description) .description = description,
.handler([=](std::vector<std::string> ss) { *dest = value; }); .handler = {[=]() { *dest = value; }}
});
} }
template<class I> template<class I>
@ -155,18 +160,18 @@ public:
void mkFlag(char shortName, const std::string & longName, void mkFlag(char shortName, const std::string & longName,
const std::string & description, std::function<void(I)> fun) const std::string & description, std::function<void(I)> fun)
{ {
mkFlag() addFlag({
.shortName(shortName) .longName = longName,
.longName(longName) .shortName = shortName,
.labels({"N"}) .description = description,
.description(description) .labels = {"N"},
.arity(1) .handler = {[=](std::string s) {
.handler([=](std::vector<std::string> ss) {
I n; I n;
if (!string2Int(ss[0], n)) if (!string2Int(s, n))
throw UsageError("flag '--%s' requires a integer argument", longName); throw UsageError("flag '--%s' requires a integer argument", longName);
fun(n); fun(n);
}); }}
});
} }
/* Expect a string argument. */ /* Expect a string argument. */
@ -192,17 +197,10 @@ public:
run() method. */ run() method. */
struct Command : virtual Args struct Command : virtual Args
{ {
private:
std::string _name;
friend class MultiCommand; friend class MultiCommand;
public:
virtual ~Command() { } virtual ~Command() { }
std::string name() { return _name; }
virtual void prepare() { }; virtual void prepare() { };
virtual void run() = 0; virtual void run() = 0;
@ -216,6 +214,12 @@ public:
virtual Examples examples() { return Examples(); } virtual Examples examples() { return Examples(); }
typedef int Category;
static constexpr Category catDefault = 0;
virtual Category category() { return catDefault; }
void printHelp(const string & programName, std::ostream & out) override; void printHelp(const string & programName, std::ostream & out) override;
}; };
@ -228,7 +232,10 @@ class MultiCommand : virtual Args
public: public:
Commands commands; Commands commands;
std::shared_ptr<Command> command; std::map<Command::Category, std::string> categories;
// Selected command, if any.
std::optional<std::pair<std::string, ref<Command>>> command;
MultiCommand(const Commands & commands); MultiCommand(const Commands & commands);

View file

@ -177,12 +177,13 @@ void BaseSetting<T>::toJSON(JSONPlaceholder & out)
template<typename T> template<typename T>
void BaseSetting<T>::convertToArg(Args & args, const std::string & category) void BaseSetting<T>::convertToArg(Args & args, const std::string & category)
{ {
args.mkFlag() args.addFlag({
.longName(name) .longName = name,
.description(description) .description = description,
.arity(1) .category = category,
.handler([=](std::vector<std::string> ss) { overriden = true; set(ss[0]); }) .labels = {"value"},
.category(category); .handler = {[=](std::string s) { overriden = true; set(s); }},
});
} }
template<> void BaseSetting<std::string>::set(const std::string & str) template<> void BaseSetting<std::string>::set(const std::string & str)
@ -227,16 +228,18 @@ template<> std::string BaseSetting<bool>::to_string() const
template<> void BaseSetting<bool>::convertToArg(Args & args, const std::string & category) template<> void BaseSetting<bool>::convertToArg(Args & args, const std::string & category)
{ {
args.mkFlag() args.addFlag({
.longName(name) .longName = name,
.description(description) .description = description,
.handler([=](std::vector<std::string> ss) { override(true); }) .category = category,
.category(category); .handler = {[=]() { override(true); }}
args.mkFlag() });
.longName("no-" + name) args.addFlag({
.description(description) .longName = "no-" + name,
.handler([=](std::vector<std::string> ss) { override(false); }) .description = description,
.category(category); .category = category,
.handler = {[=]() { override(false); }}
});
} }
template<> void BaseSetting<Strings>::set(const std::string & str) template<> void BaseSetting<Strings>::set(const std::string & str)

View file

@ -63,6 +63,16 @@ public:
writeToStderr(prefix + filterANSIEscapes(fs.s, !tty) + "\n"); writeToStderr(prefix + filterANSIEscapes(fs.s, !tty) + "\n");
} }
void result(ActivityId act, ResultType type, const std::vector<Field> & fields) override
{
if (type == resBuildLogLine || type == resPostBuildLogLine) {
assert(0 < fields.size());
assert(fields[0].type == Logger::Field::tString);
auto lastLine = fields[0].s;
log(lvlInfo, lastLine);
}
}
void startActivity(ActivityId act, Verbosity lvl, ActivityType type, void startActivity(ActivityId act, Verbosity lvl, ActivityType type,
const std::string & s, const Fields & fields, ActivityId parent) const std::string & s, const Fields & fields, ActivityId parent)
override override

View file

@ -14,12 +14,13 @@ struct CmdAddToStore : MixDryRun, StoreCommand
{ {
expectArg("path", &path); expectArg("path", &path);
mkFlag() addFlag({
.longName("name") .longName = "name",
.shortName('n') .shortName = 'n',
.description("name component of the store path") .description = "name component of the store path",
.labels({"name"}) .labels = {"name"},
.dest(&namePart); .handler = {&namePart},
});
} }
std::string description() override std::string description() override
@ -33,6 +34,8 @@ struct CmdAddToStore : MixDryRun, StoreCommand
}; };
} }
Category category() override { return catUtility; }
void run(ref<Store> store) override void run(ref<Store> store) override
{ {
if (!namePart) namePart = baseNameOf(path); if (!namePart) namePart = baseNameOf(path);

View file

@ -12,17 +12,19 @@ struct CmdBuild : InstallablesCommand, MixDryRun, MixProfile
CmdBuild() CmdBuild()
{ {
mkFlag() addFlag({
.longName("out-link") .longName = "out-link",
.shortName('o') .shortName = 'o',
.description("path of the symlink to the build result") .description = "path of the symlink to the build result",
.labels({"path"}) .labels = {"path"},
.dest(&outLink); .handler = {&outLink},
});
mkFlag() addFlag({
.longName("no-link") .longName = "no-link",
.description("do not create a symlink to the build result") .description = "do not create a symlink to the build result",
.set(&outLink, Path("")); .handler = {&outLink, Path("")},
});
} }
std::string description() override std::string description() override

View file

@ -30,9 +30,11 @@ struct CmdCatStore : StoreCommand, MixCat
std::string description() override std::string description() override
{ {
return "print the contents of a store file on stdout"; return "print the contents of a file in the Nix store on stdout";
} }
Category category() override { return catUtility; }
void run(ref<Store> store) override void run(ref<Store> store) override
{ {
cat(store->getFSAccessor()); cat(store->getFSAccessor());
@ -51,9 +53,11 @@ struct CmdCatNar : StoreCommand, MixCat
std::string description() override std::string description() override
{ {
return "print the contents of a file inside a NAR file"; return "print the contents of a file inside a NAR file on stdout";
} }
Category category() override { return catUtility; }
void run(ref<Store> store) override void run(ref<Store> store) override
{ {
cat(makeNarAccessor(make_ref<std::string>(readFile(narPath)))); cat(makeNarAccessor(make_ref<std::string>(readFile(narPath))));

View file

@ -35,16 +35,18 @@ StorePathsCommand::StorePathsCommand(bool recursive)
: recursive(recursive) : recursive(recursive)
{ {
if (recursive) if (recursive)
mkFlag() addFlag({
.longName("no-recursive") .longName = "no-recursive",
.description("apply operation to specified paths only") .description = "apply operation to specified paths only",
.set(&this->recursive, false); .handler = {&this->recursive, false},
});
else else
mkFlag() addFlag({
.longName("recursive") .longName = "recursive",
.shortName('r') .shortName = 'r',
.description("apply operation to closure of the specified paths") .description = "apply operation to closure of the specified paths",
.set(&this->recursive, true); .handler = {&this->recursive, true},
});
mkFlag(0, "all", "apply operation to the entire store", &all); mkFlag(0, "all", "apply operation to the entire store", &all);
} }
@ -101,11 +103,12 @@ Strings editorFor(const Pos & pos)
MixProfile::MixProfile() MixProfile::MixProfile()
{ {
mkFlag() addFlag({
.longName("profile") .longName = "profile",
.description("profile to update") .description = "profile to update",
.labels({"path"}) .labels = {"path"},
.dest(&profile); .handler = {&profile},
});
} }
void MixProfile::updateProfile(const StorePath & storePath) void MixProfile::updateProfile(const StorePath & storePath)
@ -145,28 +148,30 @@ MixDefaultProfile::MixDefaultProfile()
profile = getDefaultProfile(); profile = getDefaultProfile();
} }
MixEnvironment::MixEnvironment() : ignoreEnvironment(false) { MixEnvironment::MixEnvironment() : ignoreEnvironment(false)
mkFlag() {
.longName("ignore-environment") addFlag({
.shortName('i') .longName = "ignore-environment",
.description("clear the entire environment (except those specified with --keep)") .shortName = 'i',
.set(&ignoreEnvironment, true); .description = "clear the entire environment (except those specified with --keep)",
.handler = {&ignoreEnvironment, true},
});
mkFlag() addFlag({
.longName("keep") .longName = "keep",
.shortName('k') .shortName = 'k',
.description("keep specified environment variable") .description = "keep specified environment variable",
.arity(1) .labels = {"name"},
.labels({"name"}) .handler = {[&](std::string s) { keep.insert(s); }},
.handler([&](std::vector<std::string> ss) { keep.insert(ss.front()); }); });
mkFlag() addFlag({
.longName("unset") .longName = "unset",
.shortName('u') .shortName = 'u',
.description("unset specified environment variable") .description = "unset specified environment variable",
.arity(1) .labels = {"name"},
.labels({"name"}) .handler = {[&](std::string s) { unset.insert(s); }},
.handler([&](std::vector<std::string> ss) { unset.insert(ss.front()); }); });
} }
void MixEnvironment::setEnviron() { void MixEnvironment::setEnviron() {

View file

@ -16,6 +16,10 @@ class EvalState;
struct Pos; struct Pos;
class Store; class Store;
static constexpr Command::Category catSecondary = 100;
static constexpr Command::Category catUtility = 101;
static constexpr Command::Category catNixInstallation = 102;
/* A command that requires a Nix store. */ /* A command that requires a Nix store. */
struct StoreCommand : virtual Command struct StoreCommand : virtual Command
{ {

View file

@ -19,27 +19,32 @@ struct CmdCopy : StorePathsCommand
CmdCopy() CmdCopy()
: StorePathsCommand(true) : StorePathsCommand(true)
{ {
mkFlag() addFlag({
.longName("from") .longName = "from",
.labels({"store-uri"}) .description = "URI of the source Nix store",
.description("URI of the source Nix store") .labels = {"store-uri"},
.dest(&srcUri); .handler = {&srcUri},
mkFlag() });
.longName("to")
.labels({"store-uri"})
.description("URI of the destination Nix store")
.dest(&dstUri);
mkFlag() addFlag({
.longName("no-check-sigs") .longName = "to",
.description("do not require that paths are signed by trusted keys") .description = "URI of the destination Nix store",
.set(&checkSigs, NoCheckSigs); .labels = {"store-uri"},
.handler = {&dstUri},
});
mkFlag() addFlag({
.longName("substitute-on-destination") .longName = "no-check-sigs",
.shortName('s') .description = "do not require that paths are signed by trusted keys",
.description("whether to try substitutes on the destination store (only supported by SSH)") .handler = {&checkSigs, NoCheckSigs},
.set(&substitute, Substitute); });
addFlag({
.longName = "substitute-on-destination",
.shortName = 's',
.description = "whether to try substitutes on the destination store (only supported by SSH)",
.handler = {&substitute, Substitute},
});
realiseMode = Build; realiseMode = Build;
} }
@ -77,6 +82,8 @@ struct CmdCopy : StorePathsCommand
}; };
} }
Category category() override { return catSecondary; }
ref<Store> createStore() override ref<Store> createStore() override
{ {
return srcUri.empty() ? StoreCommand::createStore() : openStore(srcUri); return srcUri.empty() ? StoreCommand::createStore() : openStore(srcUri);

View file

@ -242,16 +242,16 @@ struct CmdDevShell : Common, MixEnvironment
CmdDevShell() CmdDevShell()
{ {
mkFlag() addFlag({
.longName("command") .longName = "command",
.shortName('c') .shortName = 'c',
.description("command and arguments to be executed insted of an interactive shell") .description = "command and arguments to be executed insted of an interactive shell",
.labels({"command", "args"}) .labels = {"command", "args"},
.arity(ArityAny) .handler = {[&](std::vector<std::string> ss) {
.handler([&](std::vector<std::string> ss) {
if (ss.empty()) throw UsageError("--command requires at least one argument"); if (ss.empty()) throw UsageError("--command requires at least one argument");
command = ss; command = ss;
}); }}
});
} }
std::string description() override std::string description() override
@ -337,6 +337,8 @@ struct CmdPrintDevEnv : Common
}; };
} }
Category category() override { return catUtility; }
void run(ref<Store> store) override void run(ref<Store> store) override
{ {
auto buildEnvironment = getBuildEnvironment(store).first; auto buildEnvironment = getBuildEnvironment(store).first;

View file

@ -40,9 +40,11 @@ struct CmdDoctor : StoreCommand
std::string description() override std::string description() override
{ {
return "check your system for potential problems and print a PASS or FAIL for each check."; return "check your system for potential problems and print a PASS or FAIL for each check";
} }
Category category() override { return catNixInstallation; }
void run(ref<Store> store) override void run(ref<Store> store) override
{ {
logger->log("Running checks against store uri: " + store->getUri()); logger->log("Running checks against store uri: " + store->getUri());

View file

@ -20,6 +20,8 @@ struct CmdDumpPath : StorePathCommand
}; };
} }
Category category() override { return catUtility; }
void run(ref<Store> store, const StorePath & storePath) override void run(ref<Store> store, const StorePath & storePath) override
{ {
FdSink sink(STDOUT_FILENO); FdSink sink(STDOUT_FILENO);

View file

@ -25,6 +25,8 @@ struct CmdEdit : InstallableCommand
}; };
} }
Category category() override { return catSecondary; }
void run(ref<Store> store) override void run(ref<Store> store) override
{ {
auto state = getEvalState(); auto state = getEvalState();

View file

@ -45,6 +45,8 @@ struct CmdEval : MixJSON, InstallableCommand
}; };
} }
Category category() override { return catSecondary; }
void run(ref<Store> store) override void run(ref<Store> store) override
{ {
if (raw && json) if (raw && json)

View file

@ -204,10 +204,11 @@ struct CmdFlakeCheck : FlakeCommand
CmdFlakeCheck() CmdFlakeCheck()
{ {
mkFlag() addFlag({
.longName("no-build") .longName = "no-build",
.description("do not build checks") .description = "do not build checks",
.set(&build, false); .handler = {&build, false}
});
} }
std::string description() override std::string description() override
@ -577,12 +578,13 @@ struct CmdFlakeClone : FlakeCommand
CmdFlakeClone() CmdFlakeClone()
{ {
mkFlag() addFlag({
.shortName('f') .longName = "dest",
.longName("dest") .shortName = 'f',
.label("path") .description = "destination path",
.description("destination path") .labels = {"path"},
.dest(&destDir); .handler = {&destDir}
});
} }
void run(nix::ref<nix::Store> store) override void run(nix::ref<nix::Store> store) override
@ -600,11 +602,12 @@ struct CmdFlakeArchive : FlakeCommand, MixJSON, MixDryRun
CmdFlakeArchive() CmdFlakeArchive()
{ {
mkFlag() addFlag({
.longName("to") .longName = "to",
.labels({"store-uri"}) .description = "URI of the destination Nix store",
.description("URI of the destination Nix store") .labels = {"store-uri"},
.dest(&dstUri); .handler = {&dstUri}
});
} }
std::string description() override std::string description() override
@ -677,15 +680,17 @@ struct CmdFlakeShow : FlakeCommand
CmdFlakeShow() CmdFlakeShow()
{ {
mkFlag() addFlag({
.longName("legacy") .longName = "legacy",
.description("show the contents of the 'legacyPackages' output") .description = "show the contents of the 'legacyPackages' output",
.set(&showLegacy, true); .handler = {&showLegacy, true}
});
mkFlag() addFlag({
.longName("no-eval-cache") .longName = "no-eval-cache",
.description("do not use the flake evaluation cache") .description = "do not use the flake evaluation cache",
.handler([&]() { useEvalCache = false; }); .handler = {[&]() { useEvalCache = false; }}
});
} }
std::string description() override std::string description() override
@ -849,8 +854,8 @@ struct CmdFlake : virtual MultiCommand, virtual Command
{ {
if (!command) if (!command)
throw UsageError("'nix flake' requires a sub-command."); throw UsageError("'nix flake' requires a sub-command.");
command->prepare(); command->second->prepare();
command->run(); command->second->run();
} }
void printHelp(const string & programName, std::ostream & out) override void printHelp(const string & programName, std::ostream & out) override

View file

@ -23,9 +23,7 @@ struct CmdHash : Command
mkFlag(0, "base64", "print hash in base-64", &base, Base64); mkFlag(0, "base64", "print hash in base-64", &base, Base64);
mkFlag(0, "base32", "print hash in base-32 (Nix-specific)", &base, Base32); mkFlag(0, "base32", "print hash in base-32 (Nix-specific)", &base, Base32);
mkFlag(0, "base16", "print hash in base-16", &base, Base16); mkFlag(0, "base16", "print hash in base-16", &base, Base16);
mkFlag() addFlag(Flag::mkHashTypeFlag("type", &ht));
.longName("type")
.mkHashTypeFlag(&ht);
#if 0 #if 0
mkFlag() mkFlag()
.longName("modulo") .longName("modulo")
@ -43,6 +41,8 @@ struct CmdHash : Command
: "print cryptographic hash of the NAR serialisation of a path"; : "print cryptographic hash of the NAR serialisation of a path";
} }
Category category() override { return catUtility; }
void run() override void run() override
{ {
for (auto path : paths) { for (auto path : paths) {
@ -76,9 +76,7 @@ struct CmdToBase : Command
CmdToBase(Base base) : base(base) CmdToBase(Base base) : base(base)
{ {
mkFlag() addFlag(Flag::mkHashTypeFlag("type", &ht));
.longName("type")
.mkHashTypeFlag(&ht);
expectArgs("strings", &args); expectArgs("strings", &args);
} }
@ -91,6 +89,8 @@ struct CmdToBase : Command
"SRI"); "SRI");
} }
Category category() override { return catUtility; }
void run() override void run() override
{ {
for (auto s : args) for (auto s : args)

View file

@ -19,65 +19,73 @@ namespace nix {
MixFlakeOptions::MixFlakeOptions() MixFlakeOptions::MixFlakeOptions()
{ {
mkFlag() addFlag({
.longName("recreate-lock-file") .longName = "recreate-lock-file",
.description("recreate lock file from scratch") .description = "recreate lock file from scratch",
.set(&lockFlags.recreateLockFile, true); .handler = {&lockFlags.recreateLockFile, true}
});
mkFlag() addFlag({
.longName("no-update-lock-file") .longName = "no-update-lock-file",
.description("do not allow any updates to the lock file") .description = "do not allow any updates to the lock file",
.set(&lockFlags.updateLockFile, false); .handler = {&lockFlags.updateLockFile, false}
});
mkFlag() addFlag({
.longName("no-write-lock-file") .longName = "no-write-lock-file",
.description("do not write the newly generated lock file") .description = "do not write the newly generated lock file",
.set(&lockFlags.writeLockFile, false); .handler = {&lockFlags.writeLockFile, false}
});
mkFlag() addFlag({
.longName("no-registries") .longName = "no-registries",
.description("don't use flake registries") .description = "don't use flake registries",
.set(&lockFlags.useRegistries, false); .handler = {&lockFlags.useRegistries, false}
});
mkFlag() addFlag({
.longName("commit-lock-file") .longName = "commit-lock-file",
.description("commit changes to the lock file") .description = "commit changes to the lock file",
.set(&lockFlags.commitLockFile, true); .handler = {&lockFlags.commitLockFile, true}
});
mkFlag() addFlag({
.longName("update-input") .longName = "update-input",
.description("update a specific flake input") .description = "update a specific flake input",
.label("input-path") .labels = {"input-path"},
.handler([&](std::vector<std::string> ss) { .handler = {[&](std::string s) {
lockFlags.inputUpdates.insert(flake::parseInputPath(ss[0])); lockFlags.inputUpdates.insert(flake::parseInputPath(s));
}); }}
});
mkFlag() addFlag({
.longName("override-input") .longName = "override-input",
.description("override a specific flake input (e.g. 'dwarffs/nixpkgs')") .description = "override a specific flake input (e.g. 'dwarffs/nixpkgs')",
.arity(2) .labels = {"input-path", "flake-url"},
.labels({"input-path", "flake-url"}) .handler = {[&](std::string inputPath, std::string flakeRef) {
.handler([&](std::vector<std::string> ss) {
lockFlags.inputOverrides.insert_or_assign( lockFlags.inputOverrides.insert_or_assign(
flake::parseInputPath(ss[0]), flake::parseInputPath(inputPath),
parseFlakeRef(ss[1], absPath("."))); parseFlakeRef(flakeRef, absPath(".")));
}); }}
});
} }
SourceExprCommand::SourceExprCommand() SourceExprCommand::SourceExprCommand()
{ {
mkFlag() addFlag({
.shortName('f') .longName = "file",
.longName("file") .shortName = 'f',
.label("file") .description = "evaluate FILE rather than the default",
.description("evaluate attributes from FILE") .labels = {"file"},
.dest(&file); .handler = {&file}
});
mkFlag() addFlag({
.longName("expr") .longName ="expr",
.label("expr") .description = "evaluate attributes from EXPR",
.description("evaluate attributes from EXPR") .labels = {"expr"},
.dest(&expr); .handler = {&expr}
});
} }
Strings SourceExprCommand::getDefaultFlakeAttrPaths() Strings SourceExprCommand::getDefaultFlakeAttrPaths()

View file

@ -31,6 +31,8 @@ struct CmdLog : InstallableCommand
}; };
} }
Category category() override { return catSecondary; }
void run(ref<Store> store) override void run(ref<Store> store) override
{ {
settings.readOnlyMode = true; settings.readOnlyMode = true;

View file

@ -100,9 +100,11 @@ struct CmdLsStore : StoreCommand, MixLs
std::string description() override std::string description() override
{ {
return "show information about a store path"; return "show information about a path in the Nix store";
} }
Category category() override { return catUtility; }
void run(ref<Store> store) override void run(ref<Store> store) override
{ {
list(store->getFSAccessor()); list(store->getFSAccessor());
@ -131,9 +133,11 @@ struct CmdLsNar : Command, MixLs
std::string description() override std::string description() override
{ {
return "show information about the contents of a NAR file"; return "show information about a path inside a NAR file";
} }
Category category() override { return catUtility; }
void run() override void run() override
{ {
list(makeNarAccessor(make_ref<std::string>(readFile(narPath, true)))); list(makeNarAccessor(make_ref<std::string>(readFile(narPath, true))));

View file

@ -59,15 +59,22 @@ struct NixArgs : virtual MultiCommand, virtual MixCommonArgs
NixArgs() : MultiCommand(*RegisterCommand::commands), MixCommonArgs("nix") NixArgs() : MultiCommand(*RegisterCommand::commands), MixCommonArgs("nix")
{ {
mkFlag() categories.clear();
.longName("help") categories[Command::catDefault] = "Main commands";
.description("show usage information") categories[catSecondary] = "Infrequently used commands";
.handler([&]() { showHelpAndExit(); }); categories[catUtility] = "Utility/scripting commands";
categories[catNixInstallation] = "Commands for upgrading or troubleshooting your Nix installation";
mkFlag() addFlag({
.longName("help-config") .longName = "help",
.description("show configuration options") .description = "show usage information",
.handler([&]() { .handler = {[&]() { showHelpAndExit(); }},
});
addFlag({
.longName = "help-config",
.description = "show configuration options",
.handler = {[&]() {
std::cout << "The following configuration options are available:\n\n"; std::cout << "The following configuration options are available:\n\n";
Table2 tbl; Table2 tbl;
std::map<std::string, Config::SettingInfo> settings; std::map<std::string, Config::SettingInfo> settings;
@ -76,28 +83,33 @@ struct NixArgs : virtual MultiCommand, virtual MixCommonArgs
tbl.emplace_back(s.first, s.second.description); tbl.emplace_back(s.first, s.second.description);
printTable(std::cout, tbl); printTable(std::cout, tbl);
throw Exit(); throw Exit();
}); }},
});
mkFlag() addFlag({
.longName("print-build-logs") .longName = "print-build-logs",
.shortName('L') .shortName = 'L',
.description("print full build logs on stderr") .description = "print full build logs on stderr",
.set(&printBuildLogs, true); .handler = {&printBuildLogs, true},
});
mkFlag() addFlag({
.longName("version") .longName = "version",
.description("show version information") .description = "show version information",
.handler([&]() { printVersion(programName); }); .handler = {[&]() { printVersion(programName); }},
});
mkFlag() addFlag({
.longName("no-net") .longName = "no-net",
.description("disable substituters and consider all previously downloaded files up-to-date") .description = "disable substituters and consider all previously downloaded files up-to-date",
.handler([&]() { useNet = false; }); .handler = {[&]() { useNet = false; }},
});
mkFlag() addFlag({
.longName("refresh") .longName = "refresh",
.description("consider all previously downloaded files out-of-date") .description = "consider all previously downloaded files out-of-date",
.handler([&]() { refresh = true; }); .handler = {[&]() { refresh = true; }},
});
} }
void printFlags(std::ostream & out) override void printFlags(std::ostream & out) override
@ -105,8 +117,8 @@ struct NixArgs : virtual MultiCommand, virtual MixCommonArgs
Args::printFlags(out); Args::printFlags(out);
std::cout << std::cout <<
"\n" "\n"
"In addition, most configuration settings can be overriden using '--<name> <value>'.\n" "In addition, most configuration settings can be overriden using '--" ANSI_ITALIC "name value" ANSI_NORMAL "'.\n"
"Boolean settings can be overriden using '--<name>' or '--no-<name>'. See 'nix\n" "Boolean settings can be overriden using '--" ANSI_ITALIC "name" ANSI_NORMAL "' or '--no-" ANSI_ITALIC "name" ANSI_NORMAL "'. See 'nix\n"
"--help-config' for a list of configuration settings.\n"; "--help-config' for a list of configuration settings.\n";
} }
@ -115,10 +127,10 @@ struct NixArgs : virtual MultiCommand, virtual MixCommonArgs
MultiCommand::printHelp(programName, out); MultiCommand::printHelp(programName, out);
#if 0 #if 0
out << "\nFor full documentation, run 'man " << programName << "' or 'man " << programName << "-<COMMAND>'.\n"; out << "\nFor full documentation, run 'man " << programName << "' or 'man " << programName << "-" ANSI_ITALIC "COMMAND" ANSI_NORMAL "'.\n";
#endif #endif
std::cout << "\nNote: this program is EXPERIMENTAL and subject to change.\n"; std::cout << "\nNote: this program is " ANSI_RED "EXPERIMENTAL" ANSI_NORMAL " and subject to change.\n";
} }
void showHelpAndExit() void showHelpAndExit()
@ -186,8 +198,8 @@ void mainWrapped(int argc, char * * argv)
if (args.refresh) if (args.refresh)
settings.tarballTtl = 0; settings.tarballTtl = 0;
args.command->prepare(); args.command->second->prepare();
args.command->run(); args.command->second->run();
} }
} }

View file

@ -31,6 +31,9 @@ struct CmdMakeContentAddressable : StorePathsCommand, MixJSON
}, },
}; };
} }
Category category() override { return catUtility; }
void run(ref<Store> store, StorePaths storePaths) override void run(ref<Store> store, StorePaths storePaths) override
{ {
auto paths = store->topoSortPaths(storePathsToSet(storePaths)); auto paths = store->topoSortPaths(storePathsToSet(storePaths));

View file

@ -23,6 +23,8 @@ struct CmdOptimiseStore : StoreCommand
}; };
} }
Category category() override { return catUtility; }
void run(ref<Store> store) override void run(ref<Store> store) override
{ {
store->optimiseStore(); store->optimiseStore();

View file

@ -29,6 +29,8 @@ struct CmdPathInfo : StorePathsCommand, MixJSON
return "query information about store paths"; return "query information about store paths";
} }
Category category() override { return catSecondary; }
Examples examples() override Examples examples() override
{ {
return { return {

View file

@ -21,6 +21,8 @@ struct CmdPingStore : StoreCommand
}; };
} }
Category category() override { return catUtility; }
void run(ref<Store> store) override void run(ref<Store> store) override
{ {
store->connect(); store->connect();

View file

@ -413,8 +413,8 @@ struct CmdProfile : virtual MultiCommand, virtual Command
{ {
if (!command) if (!command)
throw UsageError("'nix profile' requires a sub-command."); throw UsageError("'nix profile' requires a sub-command.");
command->prepare(); command->second->prepare();
command->run(); command->second->run();
} }
void printHelp(const string & programName, std::ostream & out) override void printHelp(const string & programName, std::ostream & out) override

View file

@ -63,16 +63,16 @@ struct CmdShell : InstallablesCommand, RunCommon, MixEnvironment
CmdShell() CmdShell()
{ {
mkFlag() addFlag({
.longName("command") .longName = "command",
.shortName('c') .shortName = 'c',
.description("command and arguments to be executed; defaults to '$SHELL'") .description = "command and arguments to be executed; defaults to '$SHELL'",
.labels({"command", "args"}) .labels = {"command", "args"},
.arity(ArityAny) .handler = {[&](std::vector<std::string> ss) {
.handler([&](std::vector<std::string> ss) {
if (ss.empty()) throw UsageError("--command requires at least one argument"); if (ss.empty()) throw UsageError("--command requires at least one argument");
command = ss; command = ss;
}); }}
});
} }
std::string description() override std::string description() override
@ -84,8 +84,8 @@ struct CmdShell : InstallablesCommand, RunCommon, MixEnvironment
{ {
return { return {
Example{ Example{
"To start a shell providing GNU Hello from NixOS 17.03:", "To start a shell providing GNU Hello from NixOS 20.03:",
"nix shell -f channel:nixos-17.03 hello" "nix shell nixpkgs/nixos-20.03#hello"
}, },
Example{ Example{
"To start a shell providing youtube-dl from your 'nixpkgs' channel:", "To start a shell providing youtube-dl from your 'nixpkgs' channel:",

View file

@ -13,6 +13,8 @@ struct CmdShowConfig : Command, MixJSON
return "show the Nix configuration"; return "show the Nix configuration";
} }
Category category() override { return catUtility; }
void run() override void run() override
{ {
if (json) { if (json) {

View file

@ -15,11 +15,12 @@ struct CmdShowDerivation : InstallablesCommand
CmdShowDerivation() CmdShowDerivation()
{ {
mkFlag() addFlag({
.longName("recursive") .longName = "recursive",
.shortName('r') .shortName = 'r',
.description("include the dependencies of the specified derivations") .description = "include the dependencies of the specified derivations",
.set(&recursive, true); .handler = {&recursive, true}
});
} }
std::string description() override std::string description() override
@ -41,6 +42,8 @@ struct CmdShowDerivation : InstallablesCommand
}; };
} }
Category category() override { return catUtility; }
void run(ref<Store> store) override void run(ref<Store> store) override
{ {
auto drvPaths = toDerivations(store, installables, true); auto drvPaths = toDerivations(store, installables, true);

View file

@ -13,13 +13,13 @@ struct CmdCopySigs : StorePathsCommand
CmdCopySigs() CmdCopySigs()
{ {
mkFlag() addFlag({
.longName("substituter") .longName = "substituter",
.shortName('s') .shortName = 's',
.labels({"store-uri"}) .description = "use signatures from specified store",
.description("use signatures from specified store") .labels = {"store-uri"},
.arity(1) .handler = {[&](std::string s) { substituterUris.push_back(s); }},
.handler([&](std::vector<std::string> ss) { substituterUris.push_back(ss[0]); }); });
} }
std::string description() override std::string description() override
@ -27,6 +27,8 @@ struct CmdCopySigs : StorePathsCommand
return "copy path signatures from substituters (like binary caches)"; return "copy path signatures from substituters (like binary caches)";
} }
Category category() override { return catUtility; }
void run(ref<Store> store, StorePaths storePaths) override void run(ref<Store> store, StorePaths storePaths) override
{ {
if (substituterUris.empty()) if (substituterUris.empty())
@ -98,12 +100,13 @@ struct CmdSignPaths : StorePathsCommand
CmdSignPaths() CmdSignPaths()
{ {
mkFlag() addFlag({
.shortName('k') .longName = "key-file",
.longName("key-file") .shortName = 'k',
.label("file") .description = "file containing the secret signing key",
.description("file containing the secret signing key") .labels = {"file"},
.dest(&secretKeyFile); .handler = {&secretKeyFile}
});
} }
std::string description() override std::string description() override
@ -111,6 +114,8 @@ struct CmdSignPaths : StorePathsCommand
return "sign the specified paths"; return "sign the specified paths";
} }
Category category() override { return catUtility; }
void run(ref<Store> store, StorePaths storePaths) override void run(ref<Store> store, StorePaths storePaths) override
{ {
if (secretKeyFile.empty()) if (secretKeyFile.empty())

View file

@ -16,18 +16,20 @@ struct CmdUpgradeNix : MixDryRun, StoreCommand
CmdUpgradeNix() CmdUpgradeNix()
{ {
mkFlag() addFlag({
.longName("profile") .longName = "profile",
.shortName('p') .shortName = 'p',
.labels({"profile-dir"}) .description = "the Nix profile to upgrade",
.description("the Nix profile to upgrade") .labels = {"profile-dir"},
.dest(&profileDir); .handler = {&profileDir}
});
mkFlag() addFlag({
.longName("nix-store-paths-url") .longName = "nix-store-paths-url",
.labels({"url"}) .description = "URL of the file that contains the store paths of the latest Nix release",
.description("URL of the file that contains the store paths of the latest Nix release") .labels = {"url"},
.dest(&storePathsUrl); .handler = {&storePathsUrl}
});
} }
std::string description() override std::string description() override
@ -49,6 +51,8 @@ struct CmdUpgradeNix : MixDryRun, StoreCommand
}; };
} }
Category category() override { return catNixInstallation; }
void run(ref<Store> store) override void run(ref<Store> store) override
{ {
evalSettings.pureEval = true; evalSettings.pureEval = true;

View file

@ -20,13 +20,13 @@ struct CmdVerify : StorePathsCommand
{ {
mkFlag(0, "no-contents", "do not verify the contents of each store path", &noContents); mkFlag(0, "no-contents", "do not verify the contents of each store path", &noContents);
mkFlag(0, "no-trust", "do not verify whether each store path is trusted", &noTrust); mkFlag(0, "no-trust", "do not verify whether each store path is trusted", &noTrust);
mkFlag() addFlag({
.longName("substituter") .longName = "substituter",
.shortName('s') .shortName = 's',
.labels({"store-uri"}) .description = "use signatures from specified store",
.description("use signatures from specified store") .labels = {"store-uri"},
.arity(1) .handler = {[&](std::string s) { substituterUris.push_back(s); }}
.handler([&](std::vector<std::string> ss) { substituterUris.push_back(ss[0]); }); });
mkIntFlag('n', "sigs-needed", "require that each path has at least N valid signatures", &sigsNeeded); mkIntFlag('n', "sigs-needed", "require that each path has at least N valid signatures", &sigsNeeded);
} }
@ -49,6 +49,8 @@ struct CmdVerify : StorePathsCommand
}; };
} }
Category category() override { return catSecondary; }
void run(ref<Store> store, StorePaths storePaths) override void run(ref<Store> store, StorePaths storePaths) override
{ {
std::vector<ref<Store>> substituters; std::vector<ref<Store>> substituters;

View file

@ -37,11 +37,12 @@ struct CmdWhyDepends : SourceExprCommand
expectArg("package", &_package); expectArg("package", &_package);
expectArg("dependency", &_dependency); expectArg("dependency", &_dependency);
mkFlag() addFlag({
.longName("all") .longName = "all",
.shortName('a') .shortName = 'a',
.description("show all edges in the dependency graph leading from 'package' to 'dependency', rather than just a shortest path") .description = "show all edges in the dependency graph leading from 'package' to 'dependency', rather than just a shortest path",
.set(&all, true); .handler = {&all, true},
});
} }
std::string description() override std::string description() override
@ -67,6 +68,8 @@ struct CmdWhyDepends : SourceExprCommand
}; };
} }
Category category() override { return catSecondary; }
void run(ref<Store> store) override void run(ref<Store> store) override
{ {
auto package = parseInstallable(store, _package); auto package = parseInstallable(store, _package);