-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshell.cpp
More file actions
98 lines (89 loc) · 2.73 KB
/
shell.cpp
File metadata and controls
98 lines (89 loc) · 2.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include "shell.h"
#include <iostream>
#include <sstream>
#include <unistd.h>
#include <vector>
void Shell::run() {
// Flush after every std::cout / std:cerr
std::cout << std::unitbuf;
std::cerr << std::unitbuf;
std::string input;
while (true) {
std::cout << "$ ";
if(!std::getline(std::cin, input) || input.empty()) {
break;
}
std::istringstream iss(input);
std::string cmd, args;
iss >> cmd;
std::getline(iss, args);
std::string cleanedArgs = cleanArgs(args);
if(auto* command = commandFactory.get(cmd)) {
command->execute(cleanedArgs);
} else {
bool customCommandFound = executeCustomCommand(cmd, args);
if (!customCommandFound) {
std::cout << cmd << ": command not found" << std::endl;
}
}
}
};
std::string Shell::cleanArgs(const std::string& args) {
std::vector<std::string> result;
std::string current;
bool inQuotes = false;
bool justClosedQuote = false;
for(size_t i = 0; i < args.size(); ++i) {
char c = args[i];
if (c == '\'') {
inQuotes = !inQuotes;
if (!inQuotes) {
justClosedQuote = true;
} else if (!current.empty() && !justClosedQuote) {
result.push_back(current);
current.clear();
}
} else if (std::isspace(c) && !inQuotes) {
if (!current.empty()) {
result.push_back(current);
current.clear();
}
justClosedQuote = false;
} else {
current += c;
justClosedQuote = false;
}
}
if (!current.empty()) {
if (inQuotes) {
current = "'" + current;
}
result.push_back(current);
}
std::string cleanedArgs;
for(size_t i = 0; i < result.size(); ++i) {
cleanedArgs += result[i];
if (i + 1 < result.size()) {
cleanedArgs += " ";
}
}
return cleanedArgs;
};
bool Shell::executeCustomCommand(const std::string& cmd, const std::string& args) {
const std::string path = "PATH";
const char* envPath = getenv(path.c_str());
if (envPath != nullptr) {
std::string pathEnvStr(envPath);
size_t start = 0, end = 0;
while ((end = pathEnvStr.find(':', start)) != std::string::npos) {
std::string dir = pathEnvStr.substr(start, end - start);
std::string fullPath = dir + "/" + cmd;
if (access(fullPath.c_str(), X_OK) == 0) {
system((cmd + " " + args).c_str());
return true;
}
start = end + 1;
}
}
return false;
};