-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.cpp
More file actions
113 lines (102 loc) · 2.68 KB
/
utils.cpp
File metadata and controls
113 lines (102 loc) · 2.68 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
#include "allFunctions.h"
// Replaces home directory path with ~ for display purposes
string tildeDisplay(const string &path, const string &homeDir)
{
if (path == homeDir)
return "~";
if (!homeDir.empty() && path.rfind(homeDir + "/", 0) == 0)
return "~" + path.substr(homeDir.size());
return path;
}
// Expands ~ to the home directory path
string tildeExpand(const string &arg, const string &homeDir)
{
if (arg == "~")
return homeDir;
if (arg.size() >= 2 && arg[0] == '~' && arg[1] == '/')
return homeDir + arg.substr(1);
return arg;
}
// Tokenizes a command string handling quotes, pipes, and redirections
vector<string> tokenize(const string &command)
{
vector<string> tokens;
string cur;
bool inSingle = false, inDouble = false;
for (int i = 0; i < command.size(); ++i)
{
char c = command[i];
if (inSingle)
{
if (c == '\'')
inSingle = false;
else
cur.push_back(c);
}
else if (inDouble)
{
if (c == '"')
inDouble = false;
else if (c == '\\' && i + 1 < command.size())
cur.push_back(command[++i]);
else
cur.push_back(c);
}
else
{
if (c == '|' || c == '<' || c == '>')
{
if (!cur.empty())
{
tokens.push_back(cur);
cur.clear();
}
if (c == '>' && i + 1 < command.size() && command[i + 1] == '>')
{
tokens.push_back(">>");
i++;
}
else
{
tokens.push_back(string(1, c));
}
}
else if (isspace(static_cast<unsigned char>(c)))
{
if (!cur.empty())
{
tokens.push_back(cur);
cur.clear();
}
}
else if (c == '\'')
{
inSingle = true;
}
else if (c == '"')
{
inDouble = true;
}
else
{
cur.push_back(c);
}
}
}
if (!cur.empty())
tokens.push_back(cur);
return tokens;
}
// Splits input by semicolons into separate commands
vector<string> semicolonSplit(const string &input)
{
vector<string> commands;
stringstream ss(input);
string cmd;
while (getline(ss, cmd, ';'))
{
if (!cmd.empty())
commands.push_back(cmd);
}
return commands;
}