-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStream.cpp
More file actions
337 lines (301 loc) · 12.8 KB
/
Stream.cpp
File metadata and controls
337 lines (301 loc) · 12.8 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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
#include <string>
#include <iostream>
#include <fstream>
#include <cctype>
#include <stdexcept>
#include "Stream.h"
// Stream (manages multiple InputStream nodes)
void Stream::clear() {
nodes.clear();
pos = 0;
pipeline.clear();
}
void Stream::split(const std::string& line) {
pipeline.clear();
std::string segment;
for (char c : line) {
if (c == '|') {
// push trimmed segment if it contains any non-whitespace
std::string trimmed = segment;
int l = 0; while (l < trimmed.size() && std::isspace(static_cast<unsigned char>(trimmed[l]))) ++l;
int r = static_cast<int>(trimmed.size()); while (r > l && std::isspace(static_cast<unsigned char>(trimmed[r-1]))) --r;
if (r > l) pipeline.push_back(trimmed.substr(l, r - l));
segment.clear();
} else {
segment += c;
}
}
if (!segment.empty()) {
std::string trimmed = segment;
int l = 0; while (l < trimmed.size() && std::isspace(static_cast<unsigned char>(trimmed[l]))) ++l;
int r = static_cast<int>(trimmed.size()); while (r > l && std::isspace(static_cast<unsigned char>(trimmed[r-1]))) --r;
if (r > l) pipeline.push_back(trimmed.substr(l, r - l));
}
}
static bool isTxtFileCandidate(const std::string& arg) {
return arg.size() >= 4 && arg.front() != '"' && arg.back() != '"' && arg.substr(arg.size() - 4) == ".txt";
}
static void trimRight(std::string& s) {
while (!s.empty() && std::isspace(static_cast<unsigned char>(s.back()))) s.pop_back();
}
static void trimLeft(std::string& s) {
int i = 0; while (i < s.size() && std::isspace(static_cast<unsigned char>(s[i]))) ++i; s.erase(0, i);
}
static void trim(std::string& s){ trimRight(s); trimLeft(s);}
// Extract trailing redirections and support forms without spaces like "<file" or ">>file"
static void parseRedirections(std::string& raw, std::string& inFile, std::string& outFile, bool& appendOut) {
const char GT = '>';
const char LT = '<';
inFile.clear(); outFile.clear(); appendOut = false;
// Allow both in any order; consume from the end repeatedly
bool changed = true;
while (changed) {
changed = false;
trimRight(raw);
if (raw.empty()) break;
int j = static_cast<int>(raw.size()) - 1;
// skip trailing whitespace
while (j >= 0 && std::isspace(static_cast<unsigned char>(raw[j]))) --j;
if (j < 0) break;
// move back to start of filename token; stop at whitespace or a redirection operator
int end = j;
while (j >= 0 && !std::isspace(static_cast<unsigned char>(raw[j])) && raw[j] != LT && raw[j] != GT) --j;
int startFile = j + 1;
std::string file = raw.substr(startFile, end - startFile + 1);
// skip whitespace before operator (if any)
while (j >= 0 && std::isspace(static_cast<unsigned char>(raw[j]))) --j;
if (j < 0) break;
char op = raw[j];
if (op == LT) {
// consume '<file' or '< file'
--j; changed = true; inFile = file;
raw.erase(j + 1); // remove from '<' to end
continue;
}
if (op == GT) {
int opEnd = j; // position of rightmost '>'
--j;
bool dbl = (j >= 0 && raw[j] == GT);
int opStart = dbl ? j : opEnd;
if (dbl) --j;
changed = true; outFile = file; appendOut = dbl;
raw.erase(opStart); // remove from first '>' to end
continue;
}
// not a redirection tail
break;
}
trimRight(raw);
}
// Overload >> to parse a line into Stream's nodes
std::istream& operator>>(std::istream& in, Stream& stream) {
// Reset previous parsed list
stream.clear();
std::string line;
if (!std::getline(in, line)) return in;
if (line.empty()) {
std::cerr << "\nError code 10 - Empty input" << std::endl;
return in;
}
if (line.size() > MAX_SIZE) {
std::cerr << "\nError code 11 - Input size exceeds maximum size" << std::endl;
return in;
}
stream.split(line);
for (auto& rawSeg : stream.pipeline) {
std::string raw = rawSeg;
std::string inFile, outFile; bool appendOut = false;
parseRedirections(raw, inFile, outFile, appendOut);
// Detect if this segment is NOT the first in the pipeline
bool hasPreviousSegment = !stream.nodes.empty();
InputStream* node = new InputStream(raw);
// Skip segments that do not produce a command (e.g., whitespace-only)
if (node->getCommand().empty()) { delete node; continue; }
// attach redirections
node->setInRedirect(inFile);
node->setOutRedirect(outFile, appendOut);
const std::string cmd = node->getCommand();
// For echo/wc/head/batch, if no explicit arg, provide it from input redirection or heredoc/multiline
if (cmd == "echo" || cmd == "wc" || cmd == "head" || cmd == "batch") {
if (!node->hasExplicitArgument()) {
if (!inFile.empty()) {
std::ifstream f(inFile);
if (!f.is_open()) {
std::cerr << "\nError code 5 - Could not open file: " << inFile << std::endl;
} else {
std::string line2, acc;
while (std::getline(f, line2)) { if (!acc.empty()) acc += '\n'; acc += line2; }
f.close();
node->setArgument("\"" + acc + "\"");
}
} else if (node->getArgument().empty()) {
// Only read interactively for the first pipeline segment. For piped segments,
// we let the previous command's stdout be bridged at execution time.
if (!hasPreviousSegment) {
std::string acc;
std::string extra;
while (std::getline(in, extra)) {
if (extra == "EOF" || extra.empty()) {
node->setArgument("\"" + acc + "\"");
break;
}
if (!acc.empty()) acc += '\n';
acc += extra;
}
}
}
}
}
// For echo/wc with explicit unquoted .txt argument, read file content
if ((cmd == "echo" || cmd == "wc") && isTxtFileCandidate(node->getArgument())) {
FileStream* fnode = new FileStream(node->getCommand(), node->getOption(), node->getArgument());
// preserve redirections on new node
fnode->setInRedirect(inFile);
fnode->setOutRedirect(outFile, appendOut);
delete node;
node = fnode;
}
// For tr: if first argument is an unquoted .txt file, load its content into argument (quoted)
if (cmd == "tr" && isTxtFileCandidate(node->getArgument())) {
FileStream* fnode = new FileStream(node->getCommand(), node->getOption(), node->getArgument());
// we need to preserve argument2 and argument3 from the original parse
// Since FileStream only sets argument, we copy over arg2/arg3 after reading
std::string arg2 = node->getArgument2();
std::string arg3 = node->getArgument3();
fnode->setInRedirect(inFile);
fnode->setOutRedirect(outFile, appendOut);
delete node;
node = fnode;
// Restore arg2/arg3
node->setArgument2(arg2);
node->setArgument3(arg3);
}
// For tr: if less than 3 tokens provided, treat provided tokens as what/with and read input
if (cmd == "tr") {
int tokenCount = 0;
if (!node->getArgument().empty()) ++tokenCount;
if (!node->getArgument2().empty()) ++tokenCount;
if (!node->getArgument3().empty()) ++tokenCount;
if (tokenCount == 1 || tokenCount == 2) {
std::string whatTok = node->getArgument();
std::string withTok = node->getArgument2();
std::string acc;
if (!inFile.empty()) {
std::ifstream f(inFile);
if (!f.is_open()) {
std::cerr << "\nError code 5 - Could not open file: " << inFile << std::endl;
} else {
std::string line2;
while (std::getline(f, line2)) { if (!acc.empty()) acc += '\n'; acc += line2; }
f.close();
}
} else if (!hasPreviousSegment) {
// Only read interactively if this is the first segment; otherwise pipeline will provide input
std::string extra;
while (std::getline(in, extra)) {
if (extra == "EOF" || extra.empty()) {
break;
}
if (!acc.empty()) acc += '\n';
acc += extra;
}
}
if (!acc.empty()) node->setArgument("\"" + acc + "\"");
node->setArgument2(whatTok);
node->setArgument3(withTok);
}
}
// For head: load file content when first arg is .txt
if (cmd == "head" && isTxtFileCandidate(node->getArgument())) {
FileStream* fnode = new FileStream(node->getCommand(), node->getOption(), node->getArgument());
fnode->setInRedirect(inFile);
fnode->setOutRedirect(outFile, appendOut);
delete node;
node = fnode;
}
// For batch: load file content when first arg is .txt
if (cmd == "batch" && isTxtFileCandidate(node->getArgument())) {
FileStream* fnode = new FileStream(node->getCommand(), node->getOption(), node->getArgument());
fnode->setInRedirect(inFile);
fnode->setOutRedirect(outFile, appendOut);
delete node;
node = fnode;
}
stream.insert(node);
}
return in;
}
// InputStream (node), parses a single command segment into a command, option, and up to 3 arguments
InputStream::InputStream(const std::string& line) { parse(line); }
void InputStream::appendArgumentLine(const std::string& line) {
if (!argument.empty()) argument += '\n';
argument += line;
}
std::string InputStream::nextToken(const std::string& line, int& i) {
while (i < line.size() && std::isspace(static_cast<unsigned char>(line[i]))) ++i;
if (i >= line.size()) return {};
std::string tok;
if (line[i] == '"') {
tok += line[i++];
while (i < line.size()) {
tok += line[i];
if (line[i] == '"') { ++i; break; }
++i;
}
} else {
while (i < line.size() && !std::isspace(static_cast<unsigned char>(line[i]))) {
tok += line[i++];
}
}
while (i < line.size() && std::isspace(static_cast<unsigned char>(line[i]))) ++i;
return tok;
}
void InputStream::parse(const std::string& line) {
int i = 0;
std::string firstTok = nextToken(line, i);
command = firstTok;
if (command.empty()) return;
std::string second = nextToken(line, i);
if (!second.empty() && second[0] == '-') {
option = second;
std::string third = nextToken(line, i);
if (!third.empty()) { argument = third; setHasExplicitArgument(true); }
std::string fourth = nextToken(line, i);
if (!fourth.empty()) argument2 = fourth;
std::string fifth = nextToken(line, i);
if (!fifth.empty()) argument3 = fifth;
} else {
if (!second.empty()) { argument = second; setHasExplicitArgument(true); }
std::string third = nextToken(line, i);
if (!third.empty()) argument2 = third;
std::string fourth = nextToken(line, i);
if (!fourth.empty()) argument3 = fourth;
}
}
// ---------------- FileStream ----------------
FileStream::FileStream(const std::string& command,
const std::string& option,
const std::string& filePath) {
setCommand(command);
setOption(option);
readFromFile(filePath);
}
void FileStream::readFromFile(const std::string& filePath) {
try {
std::ifstream f(filePath);
if (!f.is_open()) {
throw std::runtime_error("\nError code 5 - Could not open file: " + filePath);
}
std::string line;
std::string acc;
while (std::getline(f, line)) {
if (!acc.empty()) acc += '\n';
acc += line;
}
f.close();
setArgument("\"" + acc + "\"");
}
catch (const std::exception& e) {
std::cerr << "\nError code 6 - Error reading from file " << e.what() << std::endl;
}
}