fix: refactor parseCmdline interface

This commit is contained in:
Tom Bereknyei 2023-05-12 07:44:25 -04:00 committed by tomberek
parent e6ed729243
commit bbeddf0602
3 changed files with 9 additions and 7 deletions

View file

@ -83,10 +83,10 @@ std::optional<std::string> RootArgs::needsCompletion(std::string_view s)
void RootArgs::parseCmdline(const Strings & _cmdline)
{
// Default via 5.1.2.2.1 in C standard
Args::parseCmdline("", _cmdline);
Args::parseCmdline(_cmdline, false);
}
void Args::parseCmdline(const std::string & programName, const Strings & _cmdline)
void Args::parseCmdline(const Strings & _cmdline, bool allowShebang)
{
Strings pendingArgs;
bool dashDash = false;
@ -107,8 +107,7 @@ void Args::parseCmdline(const std::string & programName, const Strings & _cmdlin
// if we have at least one argument, it's the name of an
// executable file, and it starts with "#!".
Strings savedArgs;
auto isNixCommand = std::regex_search(programName, std::regex("nix$"));
if (isNixCommand && cmdline.size() > 0) {
if (allowShebang){
auto script = *cmdline.begin();
try {
std::ifstream stream(script);
@ -121,7 +120,7 @@ void Args::parseCmdline(const std::string & programName, const Strings & _cmdlin
std::string line;
std::getline(stream,line);
std::string commentChars("#/\\%@*-");
static const std::string commentChars("#/\\%@*-");
while (std::getline(stream,line) && !line.empty() && commentChars.find(line[0]) != std::string::npos){
line = chomp(line);

View file

@ -30,7 +30,7 @@ public:
* Parse the command line with argv0, throwing a UsageError if something
goes wrong.
*/
void parseCmdline(const std::string & argv0, const Strings & cmdline);
void parseCmdline(const Strings & _cmdline, bool allowShebang);
/**
* Return a short one-line description of the command.

View file

@ -22,6 +22,7 @@
#include <ifaddrs.h>
#include <netdb.h>
#include <netinet/in.h>
#include <regex>
#include <nlohmann/json.hpp>
@ -428,7 +429,9 @@ void mainWrapped(int argc, char * * argv)
});
try {
args.parseCmdline(programName, argvToStrings(argc, argv));
auto isNixCommand = std::regex_search(programName, std::regex("nix$"));
auto allowShebang = isNixCommand && argc > 1;
args.parseCmdline(argvToStrings(argc, argv),allowShebang);
} catch (UsageError &) {
if (!args.helpRequested && !args.completions) throw;
}