Skip to content

Commit dfc3589

Browse files
committed
fixing quotes parsing
1 parent a4faf9e commit dfc3589

File tree

2 files changed

+43
-20
lines changed

2 files changed

+43
-20
lines changed

src/shell.cpp

Lines changed: 42 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -20,26 +20,7 @@ void Shell::run() {
2020
iss >> cmd;
2121
std::getline(iss, args);
2222

23-
// trim leading whitespace
24-
size_t start = args.find_first_not_of(" ");
25-
if (args.find_first_of("'") != std::string::npos && args.find_first_of("'") < args.find_last_of("'")) {
26-
args = args.substr(args.find_first_of("'") + 1, args.find_last_of("'")-2);
27-
} else {
28-
std::istringstream argsStream(args);
29-
std::vector<std::string> argList;
30-
std::string arg;
31-
while (argsStream >> arg) {
32-
argList.push_back(arg);
33-
}
34-
35-
args.clear();
36-
for(size_t i = 0; i < argList.size(); ++i) {
37-
args += argList[i];
38-
if (i < argList.size()) {
39-
args += " ";
40-
}
41-
}
42-
}
23+
args = cleanArgs(args);
4324

4425
if(auto* command = commandFactory.get(cmd)) {
4526
command->execute(args);
@@ -52,6 +33,47 @@ void Shell::run() {
5233
}
5334
};
5435

36+
std::string Shell::cleanArgs(const std::string& args) {
37+
std::vector<std::string> result;
38+
std::string current;
39+
bool inQuotes = false;
40+
41+
for(size_t i = 0; i < args.size(); ++i) {
42+
char c = args[i];
43+
if (c == '\'') {
44+
inQuotes = !inQuotes;
45+
if (!inQuotes && !current.empty()) {
46+
result.push_back(current);
47+
current.clear();
48+
} else if (inQuotes && !current.empty()) {
49+
current += c;
50+
}
51+
} else if (std::isspace(c) && !inQuotes) {
52+
if (!current.empty()) {
53+
result.push_back(current);
54+
current.clear();
55+
}
56+
} else {
57+
current += c;
58+
}
59+
}
60+
if (!current.empty()) {
61+
if (inQuotes) {
62+
current = "'" + current;
63+
}
64+
result.push_back(current);
65+
}
66+
67+
std::string cleanedArgs;
68+
for(size_t i = 0; i < result.size(); ++i) {
69+
cleanedArgs += result[i];
70+
if (i + 1 < result.size()) {
71+
cleanedArgs += " ";
72+
}
73+
}
74+
return cleanedArgs;
75+
};
76+
5577
bool Shell::executeCustomCommand(const std::string& cmd, const std::string& args) {
5678
const std::string path = "PATH";
5779
const char* envPath = getenv(path.c_str());

src/shell.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,5 @@ class Shell {
77
public:
88
void run();
99
bool executeCustomCommand(const std::string& cmd, const std::string& args);
10+
std::string cleanArgs(const std::string& args);
1011
};

0 commit comments

Comments
 (0)