1
0
Fork 0
mirror of https://github.com/NixOS/nix synced 2025-07-02 13:31:48 +02:00

Make subcommand construction in MultiCommand lazy

(cherry picked from commit a0de58f471)
This commit is contained in:
Eelco Dolstra 2019-06-18 16:01:35 +02:00
parent f964f428fe
commit ac67685606
28 changed files with 61 additions and 201 deletions

View file

@ -215,17 +215,15 @@ void Command::printHelp(const string & programName, std::ostream & out)
}
}
MultiCommand::MultiCommand(const std::vector<ref<Command>> & _commands)
MultiCommand::MultiCommand(const Commands & commands)
: commands(commands)
{
for (auto & command : _commands)
commands.emplace(command->name(), command);
expectedArgs.push_back(ExpectedArg{"command", 1, true, [=](std::vector<std::string> ss) {
assert(!command);
auto i = commands.find(ss[0]);
if (i == commands.end())
throw UsageError("'%s' is not a recognised command", ss[0]);
command = i->second;
command = i->second();
}});
}
@ -246,10 +244,11 @@ void MultiCommand::printHelp(const string & programName, std::ostream & out)
out << "Available commands:\n";
Table2 table;
for (auto & command : commands) {
auto descr = command.second->description();
for (auto & i : commands) {
auto command = i.second();
auto descr = command->description();
if (!descr.empty())
table.push_back(std::make_pair(command.second->name(), descr));
table.push_back(std::make_pair(command->name(), descr));
}
printTable(out, table);
}

View file

@ -192,8 +192,15 @@ public:
run() method. */
struct Command : virtual Args
{
private:
std::string _name;
public:
virtual ~Command() { }
virtual std::string name() = 0;
std::string name() { return _name; }
virtual void prepare() { };
virtual void run() = 0;
@ -210,7 +217,7 @@ struct Command : virtual Args
void printHelp(const string & programName, std::ostream & out) override;
};
typedef std::map<std::string, ref<Command>> Commands;
typedef std::map<std::string, std::function<ref<Command>()>> Commands;
/* An argument parser that supports multiple subcommands,
i.e. <command> <subcommand>. */
@ -221,7 +228,7 @@ public:
std::shared_ptr<Command> command;
MultiCommand(const std::vector<ref<Command>> & commands);
MultiCommand(const Commands & commands);
void printHelp(const string & programName, std::ostream & out) override;