-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
122 lines (91 loc) · 3.45 KB
/
main.cpp
File metadata and controls
122 lines (91 loc) · 3.45 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include "platform/execute_cmd.h"
#include "utils.h"
#include <filesystem>
#include <iostream>
#ifdef _WIN32
#include <direct.h>
#else
#include <unistd.h>
#endif
#define MAGENTA "\u001b[35m"
#define RESET "\u001b[0m"
namespace fs = std::filesystem;
int main() {
try {
// Flush after every std::cout / std:cerr
std::cout << std::unitbuf;
std::cerr << std::unitbuf;
char *directory_paths = std::getenv("PATH");
char *home_path = get_home_directory();
std::vector<std::string> history;
std::string input;
std::cout << std::endl;
while (true) {
std::cout << MAGENTA << "$ " << RESET;
std::getline(std::cin, input);
add_to_history(input, history);
if (input.empty())
return 0;
Tokenizer t = Tokenizer(input);
std::vector<Token> arguments = t.get_tokens();
Token cmd = t.command;
if (cmd.value == "exit" && arguments.size() == 1) {
std::cout << std::endl;
return arguments[0].value == "0" ? 0 : 1;
}
if (cmd.value == "echo") {
for (auto tk : arguments) {
std::cout << tk.get_without_quotes();
if (tk.has_space)
std::cout << " ";
}
std::cout << std::endl;
} else if (cmd.value == "type") {
if (arguments.size() != 1) {
continue;
}
print_cmd_type(arguments[0].value, directory_paths);
} else if (cmd.value == "pwd") {
std::cout << fs::current_path().string() << std::endl;
} else if (cmd.value == "cd") {
if (arguments.size() < 1) {
continue;
}
std::string destination_dir = t.concat_args(false);
if (destination_dir._Starts_with("~")) {
destination_dir = home_path + destination_dir.substr(1);
}
int ans = chdir(destination_dir.c_str());
if (ans != 0) {
std::cout << "cd: " << destination_dir
<< ": No such file or directory" << std::endl;
}
} else if (cmd.value == "cat") {
custom_cat_cmd(t.get_cat_args());
} else if (cmd.value == "history") {
print_history(history);
} else if (cmd.value == "clear") {
clear_screen();
} else {
// Check for executable files
std::string file_path =
get_file_path(directory_paths, cmd.get_without_quotes());
if (file_path != "") {
std::string processed_input =
process_exec_input(file_path, arguments);
int output = execute_cmd(processed_input.c_str());
if (output != 1) {
std::cerr << "Error executing command" << std::endl;
}
std::cout << std::endl;
continue;
}
std::cout << input << ": command not found" << std::endl;
}
std::cout << std::endl;
}
} catch (const std::exception &e) {
std::cerr << "Exception in main: " << e.what() << std::endl;
}
return 0;
}