Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
1046 lines (909 loc) · 30.6 KB
/
Copy pathmain.cpp
File metadata and controls
1046 lines (909 loc) · 30.6 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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <algorithm>
#include <cinttypes>
#include <complex>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <filesystem>
#include <fstream>
#include <ios>
#include <iostream>
#include <iterator>
#include <limits.h>
#include <new>
#include <ostream>
#include <readline/chardefs.h>
#include <readline/history.h>
#include <readline/readline.h> //readline headers
#include <set>
#include <sstream>
#include <string>
#include <sys/types.h>
#include <sys/wait.h> //required for wait
#include <system_error>
#include <unistd.h>
#include <vector>
#include <cctype>
namespace fs = std::filesystem;
struct RedirectionInfo {
std::string filename;
int target_fd; // 1 for stdout, 2 for stderr, -1 for none
bool append; // true=append (>>), false=overwrite (>)
};
std::vector<std::string> builtin_commands = {"echo", "exit", "type",
"pwd", "cd", "history"};
std::vector<std::string> command_history;
size_t history_file_index = 0;
// cp command implementation - copy files and directories
// Supports: cp [options] source dest
// Options: -r (recursive), -f (force), -i (interactive), -v (verbose), -p
// (preserve)
void builtin_cp(const std::vector<std::string> &args) {
bool opt_recursive = false;
bool opt_force = false;
bool opt_interactive = false;
bool opt_verbose = false;
bool opt_preserve = false;
std::vector<std::string> sources;
std::string destination;
// Parse options and arguments
size_t i = 1;
while (i < args.size()) {
std::string arg = args[i];
// Stop parsing options if we hit a non-option argument
if (arg.empty() || arg[0] != '-') {
// This is a source or destination
break;
}
// Handle -- (end of options)
if (arg == "--") {
i++;
break;
}
// Parse individual options
for (size_t j = 1; j < arg.size(); j++) {
char c = arg[j];
switch (c) {
case 'r':
case 'R':
opt_recursive = true;
break;
case 'f':
opt_force = true;
break;
case 'i':
opt_interactive = true;
break;
case 'v':
opt_verbose = true;
break;
case 'p':
opt_preserve = true;
break;
default:
std::cerr << "cp: invalid option -- '" << c << "'" << std::endl;
std::cerr << "Try 'cp --help' for more information." << std::endl;
return;
}
}
i++;
}
// Collect remaining arguments as sources and destination
while (i < args.size()) {
sources.push_back(args[i]);
i++;
}
// Validate arguments
if (sources.empty()) {
std::cerr << "cp: missing file operand" << std::endl;
std::cerr << "Try 'cp --help' for more information." << std::endl;
return;
}
if (sources.size() == 1) {
std::cerr << "cp: missing destination file operand" << std::endl;
std::cerr << "Try 'cp --help' for more information." << std::endl;
return;
}
// Last argument is the destination
destination = sources.back();
sources.pop_back();
// Check if destination is a directory
bool dest_is_dir = fs::exists(destination) && fs::is_directory(destination);
// Process each source
for (const auto &src : sources) {
fs::path src_path(src);
fs::path dest_path(destination);
// Check if source exists
if (!fs::exists(src_path)) {
std::cerr << "cp: cannot stat '" << src << "': No such file or directory"
<< std::endl;
continue;
}
// Determine if source is directory or file
bool src_is_dir = fs::is_directory(src_path);
// Handle directory copy
if (src_is_dir) {
if (!opt_recursive) {
std::cerr << "cp: -r not specified; omitting directory '" << src << "'"
<< std::endl;
continue;
}
// If destination doesn't exist as a dir, or we have multiple sources,
// the destination should be a directory
if (!dest_is_dir && sources.size() > 1) {
dest_is_dir = true;
}
if (dest_is_dir) {
// Copy into destination directory
dest_path = dest_path / src_path.filename();
}
// Interactive mode: ask before overwriting
if (opt_interactive && fs::exists(dest_path)) {
std::cout << "cp: overwrite '" << dest_path << "'? ";
char response;
if (!(std::cin >> response) || (response != 'y' && response != 'Y')) {
continue;
}
}
// Force mode: remove destination if it exists
if (opt_force && fs::exists(dest_path)) {
try {
fs::remove_all(dest_path);
} catch (const fs::filesystem_error &e) {
std::cerr << "cp: cannot remove '" << dest_path << "': " << e.what()
<< std::endl;
continue;
}
}
// Copy directory recursively
try {
fs::copy_options copy_opts = fs::copy_options::recursive |
fs::copy_options::overwrite_existing |
fs::copy_options::skip_existing;
if (opt_preserve) {
copy_opts |= fs::copy_options::copy_symlinks;
}
fs::copy(src_path, dest_path, copy_opts);
if (opt_verbose) {
std::cout << "'" << src << "' -> '" << dest_path << "'" << std::endl;
}
} catch (const fs::filesystem_error &e) {
std::cerr << "cp: cannot copy '" << src << "': " << e.what()
<< std::endl;
}
} else {
// Source is a regular file
fs::path final_dest = dest_path;
// If destination is a directory, append source filename
if (dest_is_dir) {
final_dest = dest_path / src_path.filename();
}
// Interactive mode: ask before overwriting
if (opt_interactive && fs::exists(final_dest)) {
std::cout << "cp: overwrite '" << final_dest << "'? ";
char response;
if (!(std::cin >> response) || (response != 'y' && response != 'Y')) {
continue;
}
}
// Force mode: remove destination if it exists
if (opt_force && fs::exists(final_dest)) {
try {
fs::remove(final_dest);
} catch (const fs::filesystem_error &e) {
std::cerr << "cp: cannot remove '" << final_dest << "': " << e.what()
<< std::endl;
continue;
}
}
// Copy the file
try {
// copy_file supports overwrite semantics; symlink behavior is handled
// in recursive directory copy path above.
fs::copy_options copy_opts = fs::copy_options::overwrite_existing;
fs::copy_file(src_path, final_dest, copy_opts);
if (opt_verbose) {
std::cout << "'" << src << "' -> '" << final_dest << "'" << std::endl;
}
} catch (const fs::filesystem_error &e) {
std::cerr << "cp: cannot copy '" << src << "': " << e.what()
<< std::endl;
}
}
}
}
std::string get_path(std::string command) {
const char *get_env_cstr = std::getenv("PATH");
if (get_env_cstr == nullptr) {
return ""; // PATH not set!, can't find command
}
std::string path_env = get_env_cstr;
std::stringstream ss(path_env);
std::string path_dir;
while (std::getline(ss, path_dir, ':')) {
fs::path full_path = path_dir;
full_path /= command; // append command to directory (e.g., /usr/bin/ + ls)
// Check if file exists and is executable
if (fs::exists(full_path) && access(full_path.c_str(), X_OK) == 0) {
return full_path.string();
}
}
return "";
}
void execute_external(const std::string &path,
const std::vector<std::string> &parts) {
// 1) convert std::vector<std::string> to char* array (c-style)
std::vector<char *> c_args;
for (const auto &part : parts) {
c_args.push_back(const_cast<char *>(part.c_str()));
}
c_args.push_back(nullptr); // null terminates the list otherwise it will give
// segmentation fault error
// fork and execute
pid_t pid = fork();
if (pid == 0) {
// child process
execv(path.c_str(), c_args.data());
exit(1); // should only reach here if execv fails
} else if (pid > 0) {
// parent process
wait(nullptr);
} else {
std::cerr << "Fork Failed" << std::endl;
}
}
// Source - https://stackoverflow.com/a/69847310
// Posted by Remy Lebeau, modified by community. See post 'Timeline' for change
// history Retrieved 2026-01-11, License - CC BY-SA 4.0
// --builtin-cd --
// this function handles the logic to change the directory
void builtin_cd(std::string path) {
// for checking home directory
if (path == "~") {
const char *home = std::getenv("HOME");
if (home) {
path = home;
}
} else if (path.substr(0, 2) == "~/") {
const char *home = std::getenv("HOME");
if (home) {
// replace "~" with the actual home path
path = std::string(home) + path.substr(1);
}
}
// check if the directory exists and is actually a directory
if (fs::exists(path) && fs::is_directory(path)) {
// this tells the operating systeme to change the directory
// equivalent to the c function chdir()
try {
fs::current_path(path);
} catch (const fs::filesystem_error &e) {
// should permission fail, etc.
std::cerr << "cd: " << path << ": " << e.what() << std::endl;
}
} else {
std::cout << "cd: " << path << ": No such file or directory" << std::endl;
}
}
// --- PARSER: Handle Single Quotes ---
std::vector<std::string> split_line(const std::string &input) {
std::vector<std::string> args;
std::string current_tokens;
bool in_single_quotes = false; // are we currently inside '...'?
bool in_double_quotes = false; // are we currently inside "..."?
for (size_t i = 0; i < input.length(); i++) {
char c = input[i];
// 1) Handle Backslashes (\)
// we handle Backslashes first because they can escape quotes too (eg: \")
if (c == '\\') {
// case A: inside single quotes ('....')
// Backslashes are not special inside the single quotes. they are just
// text
if (in_single_quotes) {
current_tokens += c;
}
// case B: inside the double quotes ("....")
// Backslashes only escape specific characters: \, ", $, and newline
else if (in_double_quotes) {
if (i + 1 < input.length()) {
char next_c = input[i + 1];
// if the next char is one of the special ones, escape it
if (next_c == '\\' || next_c == '"' || next_c == '$' ||
next_c == '\n') {
current_tokens += next_c;
i++; // skip the next character (we just consumed it)
} else {
// otherwise, keep the Backslashe literal (eg: "\a" -> "\a")
current_tokens += c;
}
} else {
current_tokens += c; // trailing Backslashes at the end of string
}
}
// case C: outside quotes
// the Backslashes escapes any character that follows in
else {
if (i + 1 < input.length()) {
current_tokens += input[i + 1]; // add the next char literally
i++; // skip the next character (we just consumed it)
}
}
continue;
}
// 2) handle quotes and unquoted whitespace separators
if (c == '\'' && !in_double_quotes) {
in_single_quotes = !in_single_quotes;
} else if (c == '"' && !in_single_quotes) {
in_double_quotes = !in_double_quotes;
} else if (std::isspace(static_cast<unsigned char>(c)) && !in_single_quotes &&
!in_double_quotes) {
if (!current_tokens.empty()) {
args.push_back(current_tokens);
current_tokens.clear();
}
} else {
current_tokens += c;
}
}
if (!current_tokens.empty()) {
args.push_back(current_tokens);
}
return args;
}
RedirectionInfo parse_redirection(std::vector<std::string> &args) {
RedirectionInfo info = {"", -1, false}; // default: no redirection
for (size_t i = 0; i < args.size(); i++) {
// ">" operator to redirect standard output to a file
if (args[i] == ">" || args[i] == "1>") {
if (i + 1 < args.size()) {
info.filename = args[i + 1];
info.target_fd = 1; // 1
info.append = false;
args.erase(args.begin() + i, args.begin() + i + 2);
return info;
}
} else if (args[i] == ">>" || args[i] == "1>>") {
if (i + 1 < args.size()) {
info.filename = args[i + 1];
info.target_fd = 1; // always standard output (1)
info.append = true; // enable append mode
args.erase(args.begin() + i, args.begin() + i + 2);
return info;
}
} // standard error overwrite (2>)
else if (args[i] == "2>") {
if (i + 1 < args.size()) {
info.filename = args[i + 1];
info.target_fd = 2; // 2
info.append = false;
args.erase(args.begin() + i, args.begin() + i + 2);
return info;
}
} // standard error append (2>>)
else if (args[i] == "2>>") {
if (i + 1 < args.size()) {
info.filename = args[i + 1];
info.target_fd = 2;
info.append = true;
args.erase(args.begin() + i, args.begin() + i + 2);
return info;
}
}
}
return info;
}
// AUTOCOMPLETE LOGIC START
// 1) The Generator
// Readline calls this repeatedly. state is 0 the first time, then 1, 2, etc.
// We return the next match, or nullptr when done.
char *command_generator(const char *text, int state) {
// Static variables persist between calls during the same TAB session
static std::vector<std::string> matches;
static size_t match_index = 0;
// State 0 = first call for this TAB press. We must find all matches now
if (state == 0) {
matches.clear();
match_index = 0;
std::string text_str(text);
std::set<std::string> found; // to avoid duplicates
// 1) search builtin_commands
for (const auto &cmd : builtin_commands) {
// check if builtin starts with 'text'
if (cmd.find(text_str) == 0) {
matches.push_back(cmd);
found.insert(cmd);
}
}
// 2) search for path executable
const char *path_env = std::getenv("PATH");
if (path_env) {
std::string path_str = path_env;
std::stringstream ss(path_str);
std::string dir;
while (std::getline(ss, dir, ':')) {
fs::path p(dir);
// gracefully handle directories that don't exists
if (!fs::exists(p) || !fs::is_directory(p))
continue;
// iterate over files in the directory
try {
for (const auto &entry : fs::directory_iterator(p)) {
// skip if not a regular file (eg: skip directories/ socekts inside
// bin)
if (!entry.is_regular_file())
continue;
std::string filename = entry.path().filename().string();
// check if filename starts with what user typed
if (filename.find(text_str) == 0) {
// check if file is executable (X_OK)
// this filters out README's or other non-program files
if (access(entry.path().c_str(), X_OK) == 0) {
// only add if we haven't seen this command yet
if (found.find(filename) == found.end()) {
matches.push_back(filename);
found.insert(filename);
}
}
}
}
} catch (...) {
// ignore permission errors (eg: if we can't read a directory)
}
}
}
}
// return the next match on our list
if (match_index < matches.size()) {
// readline requires us to return a malloc'd string (strdup does this)
return strdup(matches[match_index++].c_str());
}
// no more matches
return nullptr;
}
// filename generator
// this handles autocompleting file names in the current directory
char *filename_generator(const char *text, int state) {
static std::vector<std::string> matches;
static size_t match_index = 0;
if (state == 0) {
matches.clear();
match_index = 0;
std::string text_str(text);
try {
// iterate over files in the current directory
for (const auto &entry : fs::directory_iterator(fs::current_path())) {
std::string filename = entry.path().filename().string();
// if the file starts with the text user typed
if (filename.find(text_str) == 0) {
// add trailing slash for directories
if (fs::is_directory(entry.path())) {
matches.push_back(filename + "/");
} else {
matches.push_back(filename);
}
}
}
// sort alphabetically to ensure conisistent results
std::sort(matches.begin(), matches.end());
} catch (...) {
// ignore permission/filesystem errors
}
}
// return the next match in our list
if (match_index < matches.size()) {
return strdup(matches[match_index++].c_str());
}
return nullptr;
}
// 2) The Hook
// this function tells readline what generator to use based on cursor position
char **shell_completion(const char *text, int start, int end) {
// prevent readline from falling back to its own default completion
rl_attempted_completion_over = 1;
// start == 0 means this is the first word (the command)
if (start == 0) {
return rl_completion_matches(text, command_generator);
}
// start>0 means this is an argument (a file)
else {
return rl_completion_matches(text, filename_generator);
}
}
// custom display for multiple matches
// this overrides Readline's default column printing for Double-Tab
void custom_display_matches(char **matches, int num_matches, int max_lenght) {
std::cout << std::endl; // move to a new line
// matches[0] is the longest common prefix, so we skip it
// the actual matches start at index 1
for (int i = 1; i <= num_matches; i++) {
std::cout << matches[i];
if (i < num_matches) {
std::cout << " "; // two spaces between entries
}
}
std::cout << std::endl;
// tell readline to redraw the prompt and the text the user already typed
rl_on_new_line();
rl_redisplay();
}
// AUTOCOMPLETE LOGIC END
// manual implementation to get pwd without current_path() :)
std::string get_pwd() {
// PATH_MAX is usually defined in limits.h (often 4096 bytes)
// If not defined, we fallback to 4096.
#ifndef PATH_MAX
#define PATH_MAX 4096
#endif
char buffer[PATH_MAX];
// getcwd(buffer, size);
// Returns a pointer to buffer on success, or NULL on failure.
// if (getcwd(buffer, sizeof(buffer)) != nullptr){
// return std::string(buffer);
// } else {
// If it fails (e.g., path is too long), print a system error
// perror("pwd error");
// return "";
// }
// }
if (getcwd(buffer, sizeof(buffer)) != nullptr) {
return std::string(buffer);
} else {
perror("pwd error");
return "";
}
}
// this function runs builtins OR external commands
// it returns true if it ran a builtin, false if it tried to run external (execv
// usually doesn't return).
bool run_command_logic(const std::vector<std::string> &args) {
std::string command_name = args[0];
if (command_name == "exit") {
// in a pipline, this exits the child (correct)
// in main, we handle exit separately to close the shell
exit(0);
} else if (command_name == "echo") {
for (size_t i = 1; i < args.size(); i++) {
std::cout << args[i];
if (i < args.size() - 1)
std::cout << " ";
}
std::cout << std::endl;
return true;
} else if (command_name == "type") {
if (args.size() > 1) {
std::string arg = args[1];
if (arg == "echo" || arg == "exit" || arg == "type" || arg == "pwd" ||
arg == "cd" || arg == "history")
std::cout << arg << " is a shell builtin" << std::endl;
else {
std::string p = get_path(arg);
if (!p.empty())
std::cout << arg << " is " << p << std::endl;
else
std::cout << arg << ": not found" << std::endl;
}
}
return true;
} else if (command_name == "pwd") {
std::cout << fs::current_path().string() << std::endl;
return true;
} else if (command_name == "cd") {
if (args.size() >= 2)
builtin_cd(args[1]);
else
builtin_cd("~");
return true;
} else if (command_name == "history") {
// read from the file (-r)
if (args.size() > 1 && args[1] == "-r") {
if (args.size() < 3) {
std::cerr << "history: -r: requires an argument" << std::endl;
return true;
}
std::string filepath = args[2];
std::ifstream history_file(filepath);
if (!history_file.is_open()) {
std::cerr << "bash: history: " << filepath
<< ": No such file or directory" << std::endl;
return true;
}
std::string line;
while (std::getline(history_file, line)) {
if (!line.empty()) {
command_history.push_back(line);
}
}
history_file.close();
return true; // done (dont print anything)
}
// write to file (-w)
else if (args.size() > 1 && args[1] == "-w") {
if (args.size() > 3) {
std::cerr << "history: -w: requires an argument" << std::endl;
return true;
}
std::string filepath = args[2];
// open file for writing (Truncate existing content or creates new file)
std::ofstream history_file(filepath);
if (!history_file.is_open()) {
std::cerr << "bash: history: " << filepath << ": Cannot write to file"
<< std::endl;
return true;
}
// write every command in memory to the file
for (const auto &cmd : command_history) {
history_file << cmd << std::endl;
}
history_file.close();
return true;
} // append to file (-a)
else if (args.size() > 1 && args[1] == "-a") {
if (args.size() > 3) {
std::cerr << "history: -a: requires an argument" << std::endl;
return true;
}
std::string filepath = args[2];
// open in append mode (std::ios::app)
std::ofstream history_file(filepath, std::ios::app);
if (!history_file.is_open()) {
std::cerr << "bash: history: " << filepath << ": Cannot write to file"
<< std::endl;
return true;
}
// only write commands that haven't been written yet
for (size_t i = history_file_index; i < command_history.size(); i++) {
history_file << command_history[i] << std::endl;
}
history_file.close();
// update the index so we don't write these lines again next time
history_file_index = command_history.size();
return true;
}
size_t count = command_history.size(); // default: show all
// check if user provided a number (eg: "history 2")
if (args.size() > 1) {
try {
int limit = std::stoi(args[1]);
// if the limit is smaller than total history, verify where to start
if (limit > 0 && (size_t)limit < count) {
count = (size_t)limit;
}
} catch (...) {
// handle cases like "history abc"
// standard bash ususally ignores invalid args or shows usage
}
}
// calculate where to start printing
// if history has 10 items and we want last 2:
// start_index = 10-2=8. we print index 8 and 9
size_t start_index = command_history.size() - count;
for (size_t i = start_index; i < command_history.size(); i++) {
std::cout << " " << (i + 1) << " " << command_history[i] << std::endl;
}
return true;
} else {
// external commands
std::string path = get_path(command_name);
if (path.empty()) {
std::cout << command_name << ": command not found" << std::endl;
// return true here so the caller knows we "handled" the error
// and doesn't crash, but usually for pipeline we exit(1).
return true;
} else {
execute_external(path, args); // this contains fork/execv for normal cases
return false;
}
}
return false;
}
std::vector<std::vector<std::string>>
parse_pipeline_args(const std::vector<std::string> &args) {
std::vector<std::vector<std::string>> commands;
std::vector<std::string> current_cmd;
for (const auto &arg : args) {
if (arg == "|") {
if (!current_cmd.empty()) {
commands.push_back(current_cmd);
current_cmd.clear();
}
} else {
current_cmd.push_back(arg);
}
}
if (!current_cmd.empty()) {
commands.push_back(current_cmd);
}
return commands;
}
void execute_n_pipeline(const std::vector<std::vector<std::string>> &commands) {
int num_cmds = commands.size();
int prev_pipe_fd = -1; // Holds the Read End of the previous pipe
std::vector<pid_t> pids; // Keep track of children to wait for them later
for (int i = 0; i < num_cmds; i++) {
int pipefd[2];
bool is_last = (i == num_cmds - 1);
// Create a pipe for the *next* connection (unless we are the last command)
if (!is_last) {
if (pipe(pipefd) == -1) {
perror("pipe");
return;
}
}
pid_t pid = fork();
if (pid == 0) {
// --- CHILD PROCESS ---
// 1. INPUT SETUP: If there was a previous pipe, read from it
if (prev_pipe_fd != -1) {
dup2(prev_pipe_fd, STDIN_FILENO);
close(prev_pipe_fd);
}
// 2. OUTPUT SETUP: If not the last command, write to the new pipe
if (!is_last) {
dup2(pipefd[1], STDOUT_FILENO);
close(pipefd[1]);
close(pipefd[0]); // Child doesn't read from its own output pipe
}
// 3. EXECUTE COMMAND
const std::vector<std::string> &cmd_args = commands[i];
std::string cmd = cmd_args[0];
// Check for Builtins
// We use run_command_logic, but we must ensure we EXIT afterwards.
bool is_builtin = (cmd == "echo" || cmd == "type" || cmd == "pwd" ||
cmd == "cd" || cmd == "exit");
if (is_builtin) {
run_command_logic(cmd_args);
exit(0); // Important: Child must exit after builtin finishes
} else {
// External Command
std::string path = get_path(cmd);
if (path.empty()) {
std::cerr << cmd << ": command not found" << std::endl;
exit(1);
}
// Convert to C-style args
std::vector<char *> c_args;
for (const auto &arg : cmd_args)
c_args.push_back(const_cast<char *>(arg.c_str()));
c_args.push_back(nullptr);
execv(path.c_str(), c_args.data());
exit(1); // Exec failed
}
}
// --- PARENT PROCESS ---
pids.push_back(pid);
// 1. Cleanup used input pipe (child has it now, we don't need it)
if (prev_pipe_fd != -1) {
close(prev_pipe_fd);
}
// 2. Setup input for the NEXT loop iteration
if (!is_last) {
prev_pipe_fd = pipefd[0]; // Save the read end
close(pipefd[1]); // Close write end (child has it)
}
}
// Wait for ALL children to finish
for (pid_t p : pids) {
waitpid(p, nullptr, 0);
}
}
// --- Helper: Save History on Exit ---
void save_history() {
// 1. Check if HISTFILE is set
const char *histfile_env = std::getenv("HISTFILE");
if (!histfile_env)
return; // Do nothing if variable isn't set
// 2. Open file in APPEND mode
std::ofstream hist_file(histfile_env, std::ios::app);
if (hist_file.is_open()) {
// 3. Write only the new commands (from index to end)
for (size_t i = history_file_index; i < command_history.size(); i++) {
hist_file << command_history[i] << std::endl;
}
hist_file.close();
}
}
int main() {
// Use unitbuf to ensure output is flushed immediately
std::cout << std::unitbuf;
std::cerr << std::unitbuf;
// load history from HISTFILE on startup
const char *histfile_env = std::getenv("HISTFILE");
if (histfile_env) {
std::ifstream hist_file(histfile_env);
if (hist_file.is_open()) {
std::string line;
while (std::getline(hist_file, line)) {
if (!line.empty()) {
command_history.push_back(line);
}
}
hist_file.close();
// Important: mark these lines as "already written"
// so 'history -a' doesn't duplicate them later
history_file_index = command_history.size();
}
}
// 1. REGISTER AUTOCOMPLETE
// Tell readline to use our custom function when TAB is pressed
rl_attempted_completion_function = shell_completion;
// tell readline how to print double tab matches
rl_completion_display_matches_hook = custom_display_matches;
char *input_cstr;
// 2. MAIN LOOP
// readline("$ ") prints the prompt and handles user input (including
// Tab/Arrow keys) It returns nullptr when the user presses Ctrl+D (EOF)
while ((input_cstr = readline("$ ")) != nullptr) {
std::string input_line(input_cstr);
// Add valid commands to history so Up-Arrow works
if (!input_line.empty()) {
add_history(input_cstr);
// store every command, even invalid ones, into out vector
command_history.push_back(input_line);
}
// Readline allocates memory for the input string, we must free it
free(input_cstr);
// Skip empty lines
if (input_line.empty()) {
continue;
}
// 3. PARSE ARGS
std::vector<std::string> args = split_line(input_line);
if (args.empty())
continue;
// --CHECK FOR PIPELINE--
// use the new parser to verify if we have multiple commands separated by
// "|"
std::vector<std::vector<std::string>> commands = parse_pipeline_args(args);
if (commands.size() > 1) {
// we have pipeline (eg: cmd1 | cmd2 ....)
execute_n_pipeline(commands);
continue; // skip the rest of the loop
}
// --END PIPELINE CHECK--
// 4. HANDLE REDIRECTION
RedirectionInfo redir = parse_redirection(args);
int saved_fd = -1;
int file_fd = -1;
if (redir.target_fd != -1) {
// Save original stream
saved_fd = dup(redir.target_fd);