-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrecall.c
110 lines (91 loc) · 2.76 KB
/
recall.c
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
#include "shell.h"
#include "utils.h"
#include "history.h"
#include "prompt.h"
#include "pipe.h"
#include "recall.h"
bool is_recall(char* command) {
// checks if it is a command-recall
// returns true if the first characters match those of an up-arrow
size_t len = strlen(command);
if (len < 3) {
return false;
}
return (
command[0] == UP_0 &&
command[1] == UP_1 &&
command[2] == UP_2
);
}
void handle_recall(char* command, int argc, char** argv) {
// pre-process the arguments for a recall command
if (argc > 0 && strcmp(argv[argc-1], "&") == 0) {
argc--;
}
if (argc != 0) {
fprintf(stderr, "Could not recall command history: Invalid syntax.\n");
return;
}
size_t len = strlen(command);
if (len % 3 != 0) {
fprintf(stderr, "Could not recall command history: Invalid syntax.\n");
return;
}
for (size_t i = 0; i < len; i++) {
if (i % 3 == 0) {
if (command[i] != UP_0) {
fprintf(stderr, "Could not recall command history: Invalid syntax.\n");
return;
}
} else if (i % 3 == 1) {
if (command[i] != UP_1) {
fprintf(stderr, "Could not recall command history: Invalid syntax.\n");
return;
}
} else {
if (command[i] != UP_2) {
fprintf(stderr, "Could not recall command history: Invalid syntax.\n");
return;
}
}
}
int up = len / 3;
if (up > 20) {
fprintf(stderr, "Could not recall command history: Recall limit of 20 exceeded.\n");
return;
}
recall(up);
}
bool recall(int up) {
// recalls that command
if (up < 0) {
fprintf(stderr, "Could not recall command history: Invalid arguments.\n");
return false;
}
if (up > history.ind_h + 1) {
fprintf(stderr, "Could not recall command history: Invalid arguments.\n");
return false;
}
if (up > 20) {
fprintf(stderr, "Could not recall command history: Recall limit of 20 exceeded.\n");
return false;
}
int index = 0;
if (history.ind_h < 20) {
index = (history.ind_h - up + 1) % 20;
} else if (up <= history.ind_h - 20) {
index = (history.ind_h - up - 19) % 20;
} else {
index = (history.ind_h - up + 1) % 20;
}
char* command = (char*)malloc(sizeof(char) * (strlen(history.data[index]) + 1));
strcpy(command, history.data[index]);
prompt();
printf("%s\n", command);
if (!is_recall(command)) {
store_history(command); // the recalled command is stored in history again
}
pied_piper(command);
free(command);
return true;
}