Skip to content

Commit

Permalink
fix: refactor parseCmdline interface
Browse files Browse the repository at this point in the history
  • Loading branch information
tomberek committed Nov 7, 2023
1 parent e6ed729 commit bbeddf0
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 7 deletions.
9 changes: 4 additions & 5 deletions src/libutil/args.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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);
Expand All @@ -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);

Expand Down
2 changes: 1 addition & 1 deletion src/libutil/args.hh
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
5 changes: 4 additions & 1 deletion src/nix/main.cc
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
#include <ifaddrs.h>
#include <netdb.h>
#include <netinet/in.h>
#include <regex>

#include <nlohmann/json.hpp>

Expand Down Expand Up @@ -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;
}
Expand Down

0 comments on commit bbeddf0

Please sign in to comment.