blob: b0163708054acd7b6ed661a836ba35371f797b58 (
plain)
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
|
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdarg.h>
#include <readline/readline.h>
#include <readline/history.h>
#include "rl.h"
#include "cmd.h"
void rl_printf(const char *fmt, ...) {
// save line
char* saved_line = rl_copy_text(0, rl_end);
int saved_point = rl_point;
int saved_end = rl_end;
// clear line
rl_save_prompt();
rl_replace_line("", 0);
rl_redisplay();
// printf
va_list args;
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
// restore line
rl_restore_prompt();
rl_replace_line(saved_line, 0);
rl_point = saved_point;
rl_end = saved_end;
rl_redisplay();
free(saved_line);
}
static bool cli_cmd(char* line) {
for (size_t i = 0; i < cmds_length; i++) {
if (strcmp(line, cmds[i].name) != 0) continue;
cmds[i].handle(line);
return true;
}
return false;
}
int cli_main() {
char* input = NULL;
while (1) {
if (input != NULL) free(input);
input = readline(CLI_PROMPT);
if (input == NULL) return EXIT_SUCCESS; // exit on ^D (EOF)
if (*input == '\0') continue; // ignore empty lines
add_history(input);
if (cli_cmd(input)) continue;
printf("unknown command!\n");
}
return EXIT_SUCCESS;
}
|