-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathion.c
More file actions
729 lines (684 loc) · 20 KB
/
Copy pathion.c
File metadata and controls
729 lines (684 loc) · 20 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
#include "allocator.h"
#include <dirent.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <termios.h>
#include <unistd.h>
// parse all the arguments entered on the command line
char **parse(char *line) {
char **args = malloc(10 * sizeof(char *));
int i = 0;
char *tok = strtok(line, " ");
while (tok != NULL) {
args[i++] = tok;
tok = strtok(NULL, " ");
}
args[i] = NULL;
return args;
}
// jump directories
// to jump to recently visited directories directly save the visited directories
// in ~/.ion_history file , when jumping directories search for most matching
// directory in .ion_history and chdir() it.
void save_jump(const char *path) {
char filepath[512];
snprintf(filepath, sizeof(filepath), "%s/.ion_history", getenv("HOME"));
char paths[100][512];
int counts[100];
int total = 0;
FILE *file = fopen(filepath, "r");
if (file == NULL) {
perror("failed opening file");
return;
}
char buffer[512];
while (fgets(buffer, sizeof(buffer), file) != NULL) {
sscanf(buffer, "%[^|]|%d", paths[total], &counts[total]);
paths[total][strcspn(paths[total], "\n")] = '\0';
total++;
}
fclose(file);
int found = 0;
for (int i = 0; i < total; i++) {
if (strcmp(paths[i], path) == 0) {
counts[i]++;
found = 1;
}
}
if (!found) {
strcpy(paths[total], path);
counts[total] = 1;
total++;
}
FILE *fw = fopen(filepath, "w");
if (fw == NULL) {
perror("failed opening file");
return;
}
for (int i = 0; i < total; i++) {
fprintf(fw, "%s|%d\n", paths[i], counts[i]);
}
fclose(fw);
}
void jump(char *partial) {
char filepath[512];
snprintf(filepath, sizeof(filepath), "%s/.ion_history", getenv("HOME"));
char paths[100][512];
int counts[100];
int total = 0;
FILE *file = fopen(filepath, "r");
if (file == NULL) {
perror("failed opening file");
return;
}
char buffer[512];
while (fgets(buffer, sizeof(buffer), file) != NULL) {
sscanf(buffer, "%[^|]|%d", paths[total], &counts[total]);
paths[total][strcspn(paths[total], "\n")] = '\0';
total++;
}
fclose(file);
int bestcount = 0;
int bestindex = -1;
for (int i = 0; i < total; i++) {
char *lastpart =
strrchr(paths[i], '/'); // the last part of path(directory name)
if (lastpart != NULL && *(lastpart + 1) != '\0') // ensure it's not root
lastpart++;
else // root case
lastpart = paths[i];
if (strstr(lastpart, partial) != NULL) { // occurrence of partial in
// lastpart
if (counts[i] > bestcount) { // decide switch by counts(no. of visits) for
// same named directories
bestcount = counts[i];
bestindex = i;
}
}
}
if (bestindex == -1) {
printf("\r\nno recent visits to %s", partial);
return;
}
printf("\rinside %s", paths[bestindex]);
chdir(paths[bestindex]);
}
// pipe handling
//
// find the pipe and split two parts of args
char **find_pipe(char **args) {
int i = 0;
while (args[i] != NULL) {
if (strcmp(args[i], "|") == 0) {
args[i] = NULL;
return &args[i + 1];
}
i++;
}
return NULL;
}
// execute the parallel commands specified using pipes
void execute_pipe(char **left, char **right) {
int fds[2];
pipe(fds);
pid_t child1 = fork();
if (child1 == 0) {
close(fds[0]);
dup2(fds[1], STDOUT_FILENO);
close(fds[1]);
execvp(left[0], left);
perror("execvp failed");
exit(1);
} else if (child1 < 0) {
perror("error forking child");
exit(1);
}
pid_t child2 = fork();
if (child2 == 0) {
close(fds[1]);
dup2(fds[0], STDIN_FILENO);
close(fds[0]);
execvp(right[0], right);
perror("execvp failed");
exit(1);
} else if (child2 < 0) {
perror("error forking child");
exit(1);
}
close(fds[0]);
close(fds[1]);
int status;
waitpid(child1, &status, 0);
waitpid(child2, &status, 0);
}
// struct to redirect the operators in fd
typedef struct {
char *input_file;
char *output_file;
int isappend;
} redirect;
// parse_redirects() parses the file operators and file names to perform the
// file operations
redirect parse_redirects(char **args) {
redirect parseddata = {NULL, NULL,
0}; // default redirects,avoid garbage values be safe.
int i = 0;
while (args[i] != NULL) {
if (strcmp(args[i], ">>") == 0) {
parseddata.output_file = args[i + 1];
parseddata.isappend = 1; // open in append to write
args[i] = NULL;
args[i + 1] = NULL;
} else if (strcmp(args[i], ">") == 0) {
parseddata.output_file = args[i + 1];
parseddata.isappend = 0; // open in overwrite to write
args[i] = NULL;
args[i + 1] = NULL;
} else if (strcmp(args[i], "<") == 0) {
parseddata.input_file = args[i + 1];
parseddata.isappend = 0; // open in readonly
args[i] = NULL;
args[i + 1] = NULL;
}
i++;
}
return parseddata;
}
// apply_redirects() opens the file in specified redirects and performs the
// operation
void apply_redirects(redirect r) {
if (r.output_file) {
if (r.isappend) {
int fd = open(r.output_file, O_WRONLY | O_CREAT | O_APPEND, 0644);
if (fd < 0) {
perror("open failed");
exit(1);
}
dup2(fd, STDOUT_FILENO);
close(fd);
} else {
int fd = open(r.output_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd < 0) {
perror("open failed");
exit(1);
}
dup2(fd, STDOUT_FILENO);
close(fd);
}
}
if (r.input_file) {
int fd = open(r.input_file, O_RDONLY, 0644);
if (fd < 0) {
perror("open failed");
exit(1);
}
dup2(fd, STDIN_FILENO);
close(fd);
}
}
// termios to enter raw mode
struct termios orig_termios; // saves original term settings
void disable_raw_mode() {
tcsetattr(STDIN_FILENO, TCSAFLUSH, &orig_termios); // set the orig_termios
// back
}
// enable raw mode after saving the orig_termios
void enable_raw_mode() {
tcgetattr(STDIN_FILENO, &orig_termios);
atexit(disable_raw_mode);
struct termios raw = orig_termios;
raw.c_lflag &=
~(ECHO | ICANON); // bit 1 and bit 3 of lower nibble i.e 0xA ~= 0x5 to
// clear only echo and canonical modes.
raw.c_lflag |= ISIG;
tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw);
}
// execute the external commands with child process using fork() and execvp()
void execute(char **args) {
redirect r = parse_redirects(args);
pid_t pid = fork();
if (pid < 0) {
printf("error forking child\n");
exit(0);
} else if (pid == 0) {
signal(SIGINT, SIG_DFL);
signal(SIGQUIT, SIG_DFL);
apply_redirects(r);
execvp(args[0], args);
perror("execvp failed");
enable_raw_mode();
exit(1);
} else {
int status;
waitpid(pid, &status, 0);
}
}
// tab completions
// auto complete the partial commands or show options
char **get_completions(char *partial, int *count) {
char **options = malloc(1000 * sizeof(char *));
*count = 0;
char *envpath = getenv("PATH");
char *pathcopy = strdup(envpath);
char *dirpath = strtok(pathcopy, ":");
DIR *dir;
struct dirent *entry;
while (dirpath != NULL) {
dir = opendir(dirpath);
if (dir == NULL) {
dirpath = strtok(NULL, ":");
continue;
}
while ((entry = readdir(dir)) != NULL) {
if (strncmp(entry->d_name, partial, strlen(partial)) == 0) {
options[*count] = strdup(entry->d_name);
(*count)++;
}
}
closedir(dir);
dirpath = strtok(NULL, ":");
}
// current working dir completions
char cwd[512];
getcwd(cwd, sizeof(cwd));
DIR *cwdir = opendir(cwd);
if (cwdir != NULL) {
while ((entry = readdir(cwdir)) != NULL) {
if (strncmp(entry->d_name, partial, strlen(partial)) == 0) {
options[*count] = strdup(entry->d_name);
(*count)++;
}
}
closedir(cwdir);
}
free(pathcopy);
return options;
}
char **get_filecompletions(char *partial, int *count) {
char **options = malloc(512 * sizeof(char *));
*count = 0;
char cwd[512];
getcwd(cwd, sizeof(cwd));
DIR *dir;
struct dirent *entry;
dir = opendir(cwd);
if (dir != NULL) {
while ((entry = readdir(dir)) != NULL) {
if (strncmp(entry->d_name, partial, strlen(partial)) == 0) {
options[*count] = strdup(entry->d_name);
(*count)++;
}
}
}
closedir(dir);
return options;
}
// simple structure to store files and directories
struct Direntry {
char *name;
int is_dir;
};
// comparing function to sort entries in tree
int cmp(const void *a, const void *b) {
return strcmp(((struct Direntry *)a)->name, ((struct Direntry *)b)->name);
}
// tree
// generates a tree view of specified path with maxdepth
void tree(const char *path, int depth, int maxdepth) {
if (depth >= maxdepth)
return;
struct Direntry *entries = malloc(512 * sizeof(struct Direntry));
int count = 0;
DIR *dir;
struct dirent *entry;
dir = opendir(path);
if (dir == NULL) {
perror("failed opening dir");
return;
}
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
entries[count].name = strdup(entry->d_name);
entries[count].is_dir = (entry->d_type == DT_DIR);
count++;
}
qsort(entries, count, sizeof(struct Direntry), cmp);
for (int i = 0; i < count; i++) {
printf("\n");
for (int j = 0; j < depth; j++) // indentation (no .of depth)
printf("│ ");
if (i == count - 1) { // last entry
printf("└── %s", entries[i].name);
} else {
printf("├── %s", entries[i].name);
}
if (entries[i].is_dir) {
char fullpath[512]; // build the path
snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entries[i].name);
tree(fullpath, depth + 1, maxdepth); // recursed for sub directories
}
}
for (int i = 0; i < count; i++) {
free(entries[i].name);
}
free(entries);
closedir(dir);
}
// using fn pointers for more independent behavior adding or removing builtins
// made easy
typedef struct {
char *name;
void (*handler)(char **args);
} Builtins;
void builtin_cd(char **args) {
if (chdir(args[1]) != 0)
perror("cd failed");
char cwd[512];
getcwd(cwd, sizeof(cwd));
save_jump(cwd);
}
void builtin_exit(char **args) {
if (strcmp(args[0], "exit") == 0)
exit(0);
}
void builtin_djump(char **args) {
if (args[1] == NULL) {
printf("\r\nusage: j<partial path> jump to recently visited dir");
}
jump(args[1]);
}
void builtin_tree(char **args) {
char cwd[512];
getcwd(cwd, sizeof(cwd));
if (args[1] == NULL) {
tree(cwd, 0, 1);
} else {
int depth = atoi(args[1]);
if (depth <= 0) {
printf("\r\nusage: tree <depth>");
}
tree(cwd, 0, depth);
}
}
Builtins builtins[] = {{"cd", builtin_cd},
{"exit", builtin_exit},
{"j", builtin_djump},
{"tree", builtin_tree},
} ;
// handle builtin commands in parent process
int handle_builtins(char **args) {
for (unsigned int in = 0; in < (sizeof(builtins) / sizeof(builtins[0]));
in++) {
if (strcmp(args[0], builtins[in].name) == 0) {
builtins[in].handler(args);
return 1;
}else if(strcmp(args[0], "stats")==0){
allocator_print_stats();
return 1;
}
}
return 0;
}
int main() {
char history[100][200];
int history_count = 0;
int history_index = 0;
signal(SIGINT, SIG_IGN);
signal(SIGQUIT, SIG_IGN);
enable_raw_mode();
while (1) {
char cwd[512];
getcwd(cwd, sizeof(cwd));
char todisp[512];
char *home = getenv("HOME");
if (strncmp(cwd, home, strlen(home)) == 0) {
snprintf(todisp, sizeof(todisp), "~%s", cwd + strlen(home));
} else {
strcpy(todisp, cwd);
}
strcat(todisp, " >");
char *line = malloc(200);
printf("\r\n%s", todisp);
fflush(stdout);
int i = 0;
int cursor_pos = 0;
char c;
while (1) // read until enter
{
read(STDIN_FILENO, &c, 1);
if (c == '\r' || c == '\n') {
line[i] = '\0';
write(STDOUT_FILENO, "\n", 1); // set alignment (back to col 0)
break;
} else if (c == 3) // ctrl-c
{
i = 0;
line[0] = '\0';
break;
} else if (c == 4 && i == 0) // ctrl-d
{
disable_raw_mode();
exit(0);
// Rule:any special characters(backspace,tab) must be fully handled
// before reaching the else block , otherwise it leaks into buffer
// and gets printed or stored causing issues and segfaults in other
// operations.
} else if (c == 127) // handle backspace
{
if (i > 0) {
if (cursor_pos > 0) {
memmove(&line[cursor_pos - 1], &line[cursor_pos], i - cursor_pos);
cursor_pos--;
i--;
write(STDOUT_FILENO, "\b", 1);
write(STDOUT_FILENO, &line[cursor_pos], i - cursor_pos);
write(STDOUT_FILENO, " ", 1);
for (int k = 0; k <= (i - cursor_pos); k++) {
write(STDOUT_FILENO, "\x1b[D", 3);
}
}
}
} else if (c == 9) // tab autocomplete case
{
if (i <= 0)
continue;
line[i] = '\0'; // terminate with null
int count = 0;
char *spaces =
strchr(line, ' '); // space=file completions,else cmd completions
char **matches;
if (spaces == NULL) {
matches = get_completions(line, &count);
} else {
char *partial = strchr(line, ' ') + 1;
matches = get_filecompletions(partial, &count);
}
if (count == 1) // exact match clear the line and print match
{
for (int j = 0; j < i; j++)
write(STDOUT_FILENO, "\b \b", 3);
char *space = strchr(line, ' ');
if (space != NULL) {
int cmd_len =
space - line +
1; // substract the starting address from current address
// and we get len of args add one to it (includes space)
line[cmd_len] =
'\0'; // insert null after cmd (1st arg) ensure parsing
strcat(line, matches[0]);
} else {
strcpy(line, matches[0]);
}
i = strlen(line);
cursor_pos = i;
write(STDOUT_FILENO, line, i);
} else if (count > 1) // multiple matches display all and reprint
// prompt and line
{
write(STDOUT_FILENO, "\r\n", 2);
for (int j = 0; j < count; j++) {
write(STDOUT_FILENO, matches[j], strlen(matches[j]));
write(STDOUT_FILENO, " ", 2);
}
write(STDOUT_FILENO, "\r\n", 2);
write(STDOUT_FILENO, todisp, strlen(todisp));
write(STDOUT_FILENO, line, i);
}
for (int j = 0; j < count; j++) {
free(matches[j]); // free after use
}
free(matches); // free array
} else if (c == 27) // escape sequence up,down,->,<-
{
char seq[3];
read(STDIN_FILENO, &seq[0], 1); //[
read(STDIN_FILENO, &seq[1], 1); // any of A,B,C,D
if (seq[0] == '[') {
switch (seq[1]) {
case 'A': // up arrow - print previous commands
if (history_index <= 0) // if no previous command do nothing
break;
history_index--; // go back one index and print previous command
for (int k = 0; k < i; k++) {
write(STDOUT_FILENO, "\b \b",
3); // clean the prompt before printnig
}
strcpy(line, history[history_index]);
i = strlen(line);
write(STDOUT_FILENO, line, strlen(line)); // print the previous cmd
cursor_pos = i; // set cursor position back to end of line
break;
case 'B': // down arrow show next cmd
if (history_index >=
history_count) // if current cmd is first do nothing
break;
history_index++; // increment index to get next command
if (history_index ==
history_count) { // if index goes to last cmd(its blank)clear
// the prompt
for (int k = 0; k < i; k++) {
write(STDOUT_FILENO, "\b \b", 3);
}
i = 0; // reset char count(i) , cursor position
cursor_pos = 0;
line[0] = '\0';
break;
}
for (int k = 0; k < i; k++) {
write(STDOUT_FILENO, "\b \b", 3);
}
strcpy(line,
history[history_index]); // load the next cmd from history
i = strlen(line); // set char count
write(STDOUT_FILENO, line,
strlen(line)); // print the next cmd from the history and
// update cursor position
cursor_pos = i;
break;
case 'C':
if (cursor_pos < i) {
cursor_pos++;
write(STDOUT_FILENO, "\x1b[C", 3); // shift cursor to right
}
break;
case 'D':
if (cursor_pos > 0) {
cursor_pos--;
write(STDOUT_FILENO, "\x1b[D", 3); // shift cursor to left
}
break;
case 'H': // Home key
if (cursor_pos == 0)
break;
while (cursor_pos >
0) { // print <- arrow cursor pos times(moves curosr left)
write(STDOUT_FILENO, "\x1b[D", 3);
cursor_pos--;
}
break;
case 'F': // End key
if (cursor_pos == i)
break;
while (cursor_pos < i) { // print -> arrow i-cursor times(char
// count)(moves cursor right)
write(STDOUT_FILENO, "\x1b[C", 3);
cursor_pos++;
}
break;
case '1': // same Home key (some systems use \x1b[1~ for Home)
read(STDIN_FILENO, &seq[2], 1);
if (seq[2] == '~') {
if (cursor_pos == 0)
break;
while (cursor_pos > 0) {
write(STDOUT_FILENO, "\x1b[D", 4);
cursor_pos--;
}
}
break;
case '4'://same End key(some systems use \x1b[4~ for End)
read(STDIN_FILENO, &seq[2], 1);
if (seq[2] == '~') {
if (cursor_pos == i)
break;
while (cursor_pos < i) {
write(STDOUT_FILENO, "\x1b[C", 4);
cursor_pos++;
}
}
break;
}
}
} else {
memmove(&line[cursor_pos + 1], &line[cursor_pos],
i - cursor_pos); // shift buffer right
line[cursor_pos] = c; // store the char under cursor
i++;
cursor_pos++;
write(STDOUT_FILENO, &line[cursor_pos - 1],
i - cursor_pos + 1); // print the typed char
for (int k = 0; k < (i - cursor_pos); k++) {
write(STDOUT_FILENO, "\x1b[D", 3); // shift cursor back
}
}
}
if (i > 0) { // store cmd in history if it is not empty
strcpy(history[history_count % 100], line);
history_count++;
history_index = history_count;
}
line[strcspn(line, "\n")] = '\0';
char **args = parse(line); // parse arguments
if (args[0] == NULL) {
perror("no args specified");
free(line);
free(args);
continue;
}
if (handle_builtins(args)) { // handle builtin commands
free(args);
free(line);
continue;
}
char **nextcmd = find_pipe(args); // handle pipes
if (nextcmd != NULL) {
execute_pipe(args, nextcmd);
free(line);
free(args);
continue;
}
execute(args); // execute commands
// for (int i = 0; args[i] != NULL; i++) {
// printf("%s\n", args[i]);
// }
free(args);
free(line);
}
return 0;
}