- Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmicrocli.c
More file actions
Latest commit
415 lines (341 loc) · 11.5 KB
/
Copy pathmicrocli.c
File metadata and controls
415 lines (341 loc) · 11.5 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
#include"microcli.h"
#include<stdbool.h>
// #include <stdarg.h>
#include<string.h>
#include<assert.h>
// Special characters:
enum {
ESC=27,
SEQ=91,
UP_ARROW=65,
DOWN_ARROW=66,
};
staticvoidinsert_spaces(MicroCLI_t*ctx, intnum)
{
assert(ctx);
assert(num>0);
for(inti=0; i<num; i++) {
ctx->cfg.io.printf(" ");
}
}
staticinlineintcmd_len(constchar*cmdStr)
{
assert(cmdStr);
intinLen=strlen(cmdStr);
inti=0;
for(i=0; i<inLen; i++) {
if(cmdStr[i] ==' ')
break;
}
returni;
}
staticintlookup_command(MicroCLI_t*ctx)
{
assert(ctx);
assert(ctx->cfg.cmdTable);
assert(ctx->cfg.cmdCount >= 0);
// Loop through each possible command
inti=ctx->cfg.cmdCount;
while(i-->0) {
// Compare the input command (delimited by a space) to
// the command in the table
booldiff= false;
intj=strlen(ctx->cfg.cmdTable[i].name);
if(j>cmd_len(ctx->input.buffer))
continue;
while(j-->0&& !diff) {
if(ctx->input.buffer[j] !=ctx->cfg.cmdTable[i].name[j])
diff= true;
}
if(!diff)
returni;
}
returnMICROCLI_ERR_CMD_NOT_FOUND;
}
staticinlinevoidsave_input_to_history(MicroCLI_t*ctx)
{
#ifdefMICROCLI_ENABLE_HISTORY
assert(ctx);
assert(ctx->historySize <= MICRICLI_MAX_HISTORY_MEM); // Memory overflow?
assert((ctx->history!=0) != (ctx->historySize==0)); // Memory leak?
assert(ctx->input.len <= MAX_CLI_INPUT_LEN); // Input overflow?
assert(ctx->input.buffer[ctx->input.len-1] ==0); // Null terminated?
staticconstunsigned intNODE_SIZE=sizeof(MicroCLIHistoryEntry_t);
// Abort if this entry is too large to possibly be stored
if(ctx->input.len>MICRICLI_MAX_HISTORY_MEM-NODE_SIZE)
return;
// Abort if there is no data to save
if(ctx->input.len <= 1)
return;
// Seek last history entry
MicroCLIHistoryEntry_t*last=ctx->history;
while(last&&last->older) {
assert(last!=last->older); // Circular reference?
last=last->older;
}
// Calculate new history size
ctx->historySize+=NODE_SIZE+ctx->input.len;
// Free older entries, to prevent exceeding history max mem
while(last&&ctx->historySize>MICRICLI_MAX_HISTORY_MEM) {
MicroCLIHistoryEntry_t*this=last;
// Trim the last node from the list
last=last->newer;
if(last)
last->older=0;
// Free the allocated string memory within this node
if(this&&this->str) {
MICROCLI_FREE(this->str);
ctx->historySize-=strnlen(this->str, MAX_CLI_INPUT_LEN) +1;
}
// Free the memory of this node itself
MICROCLI_FREE(this);
ctx->historySize-=NODE_SIZE;
// Is the list empty?
if(ctx->history==this)
ctx->history=0;
}
// Allocate memory for new list node
MicroCLIHistoryEntry_t*newEntry=MICROCLI_MALLOC(NODE_SIZE);
assert(newEntry); // Malloc failure?
// Insert new list node at front of list
newEntry->newer=0; // There is no newer entry
newEntry->older=ctx->history;
ctx->history=newEntry;
if(newEntry->older)
newEntry->older->newer=newEntry;
// Allocate memory for the input string
newEntry->str=MICROCLI_MALLOC(ctx->input.len);
assert(newEntry->str); // Malloc failure?
// Save the input string
strcpy(newEntry->str, ctx->input.buffer);
#endif
}
staticinlinevoidprompt_for_input(MicroCLI_t*ctx)
{
assert(ctx);
assert(ctx->cfg.io.printf);
// Only display prompt once per command
if(ctx->prompted== false) {
ctx->cfg.io.printf(ctx->cfg.promptText);
ctx->prompted= true;
}
}
staticinlinevoidclear_line(MicroCLI_t*ctx)
{
assert(ctx);
assert(ctx->cfg.io.printf);
ctx->cfg.io.printf("\r%c%c%c", ESC, SEQ, 'K');
}
staticinlinevoidclear_prompt(MicroCLI_t*ctx)
{
assert(ctx);
assert(ctx->cfg.io.printf);
assert(ctx->cfg.promptText);
clear_line(ctx);
ctx->cfg.io.printf("\r%s", ctx->cfg.promptText);
}
staticinlinevoidprint_history_entry( MicroCLI_t*ctx,
MicroCLIHistoryEntry_t*entry)
{
assert(ctx);
assert(ctx->cfg.io.printf);
assert(entry);
assert(entry->str);
// Clear the line
clear_prompt(ctx);
// Print the history entry text
ctx->cfg.io.printf("%s", entry->str);
}
staticvoidread_from_io(MicroCLI_t*ctx)
{
assert(ctx);
assert(ctx->cfg.io.printf);
assert(ctx->cfg.io.getchar);
// Convenience mapping
char*buffer=ctx->input.buffer;
// Current history entry
staticMicroCLIHistoryEntry_t*hist=0;
// Loop through all available data
while(ctx->input.len< (sizeof(ctx->input.buffer) -1)) {
// Get next character
buffer[ctx->input.len] =ctx->cfg.io.getchar();
// Handle termination characters
if( buffer[ctx->input.len] ==0||// No more data
buffer[ctx->input.len] =='\n'||// New line
buffer[ctx->input.len] =='\r' ) // Carriage return
break;
// Handle escape sequence
if( buffer[ctx->input.len-2] ==ESC&&
buffer[ctx->input.len-1] ==SEQ ) {
// Handle the special character
boolprintFromHistory= false;
switch(buffer[ctx->input.len]) {
caseUP_ARROW:
if(hist&&hist->older) {
hist=hist->older;
printFromHistory= true;
} elseif(!hist&&ctx->history) {
hist=ctx->history;
printFromHistory= true;
}
break;
caseDOWN_ARROW:
if(hist) {
hist=hist->newer;
if(hist) {
printFromHistory= true;
} else {
// Reset back to input buffer
clear_prompt(ctx);
ctx->cfg.io.printf(ctx->input.buffer);
}
}
break;
}
if(printFromHistory&&hist->str)
print_history_entry(ctx, hist);
// Clear the sequence from the input buffer
buffer[ctx->input.len--] =0;
buffer[ctx->input.len--] =0;
buffer[ctx->input.len--] =0;
}
// Handle backspace
if(buffer[ctx->input.len] =='\b') {
if(ctx->input.len>0) {
// Overwrite prev char from screen
ctx->cfg.io.printf("\b \b");
ctx->input.len--;
}
// Erase from buffer
buffer[ctx->input.len] =0;
} else {
// Echo back if not an escape sequence
if( buffer[ctx->input.len] !=ESC&&
buffer[ctx->input.len-1] !=ESC )
ctx->cfg.io.printf("%c", buffer[ctx->input.len]);
ctx->input.len++;
}
}
assert(ctx->input.len<MAX_CLI_INPUT_LEN);
// If buffer is full, delete last char to make room for more input
if(ctx->input.len==sizeof(ctx->input.buffer)) {
ctx->cfg.io.printf("\b");
ctx->input.len--;
buffer[ctx->input.len] =0;
}
assert(ctx->input.len<MAX_CLI_INPUT_LEN);
// No more data to process. Wait for more data.
if(buffer[ctx->input.len] ==0) {
ctx->input.ready= false;
} else {
// Was a historical entry selected?
if(hist&&hist->str) {
strcpy(ctx->input.buffer, hist->str);
ctx->input.len=strnlen(hist->str, MAX_CLI_INPUT_LEN);
}
hist=0;
// Replace escape character with null terminator
buffer[ctx->input.len++] =0;
ctx->cfg.io.printf("\n\r");
// Command entry is complete. Input buffer is ready to be processed
ctx->input.ready= true;
assert(ctx->input.len<MAX_CLI_INPUT_LEN);
save_input_to_history(ctx);
}
}
voidmicrocli_init(MicroCLI_t*ctx, constMicroCLICfg_t*cfg)
{
assert(ctx);
assert(cfg);
assert(cfg->io.printf);
assert(cfg->io.getchar);
assert(cfg->bannerText);
assert(cfg->promptText);
assert(cfg->cmdTable);
*ctx= (MicroCLI_t){0};
ctx->cfg=*cfg;
ctx->verbosity=DEFAULT_VERBOSITY;
}
voidmicrocli_set_verbosity(MicroCLI_t*ctx, intverbosity)
{
assert(ctx);
assert(verbosity <= VERBOSITY_LEVEL_MAX);
ctx->verbosity=verbosity;
}
voidmicrocli_interpreter_tick(MicroCLI_t*ctx)
{
assert(ctx);
assert(ctx->cfg.io.printf);
assert(ctx->cfg.io.getchar);
assert(ctx->cfg.promptText);
// If input buffer does not contain a command, read more data from IO
if(!ctx->input.ready) {
// Prompt user for input
prompt_for_input(ctx);
// Read user input from IO
read_from_io(ctx);
}
// If the input buffer contains a command, process it.
if(ctx->input.ready) {
// Lookup and run command (if found)
intcmdIdx=lookup_command(ctx);
constchar*args=ctx->input.buffer+cmd_len(ctx->input.buffer) +1;
if(cmdIdx >= 0&&cmdIdx<ctx->cfg.cmdCount) {
ctx->cfg.cmdTable[cmdIdx].cmd(ctx, args);
ctx->cfg.io.printf("\n\r");
}
// Reset prompt
ctx->prompted= false;
}
// Reset the prompt, after processing a command
if(ctx->input.ready) {
memset(&ctx->input, 0, sizeof(ctx->input));
ctx->prompted= false;
}
}
intmicrocli_interpret_string(MicroCLI_t*ctx, constchar*str, boolprint)
{
assert(ctx);
assert(ctx->cfg.io.printf);
assert(str);
if(strlen(str) >sizeof(ctx->input.buffer))
returnMICROCLI_ERR_OVERFLOW;
if( (ctx->input.len>0) ||ctx->input.ready )
returnMICROCLI_ERR_BUSY;
// Copy string into the command input buffer
strcpy(ctx->input.buffer, str);
ctx->input.len=strlen(str);
ctx->input.ready= true;
// Optionally print the command to the cli output
if(print) {
// Display the prompt, before printing the command
prompt_for_input(ctx);
// Print the command to the console
ctx->cfg.io.printf("%s\n\r", str);
}
// Tick the interpreter to process the command
microcli_interpreter_tick(ctx);
return0;
}
intmicrocli_banner(MicroCLI_t*ctx)
{
assert(ctx);
assert(ctx->cfg.bannerText);
assert(ctx->cfg.io.printf);
returnctx->cfg.io.printf(ctx->cfg.bannerText);
}
intmicrocli_help(MicroCLI_t*ctx)
{
assert(ctx);
assert(ctx->cfg.io.printf);
assert(ctx->cfg.cmdTable);
assert(ctx->cfg.cmdCount >= 0);
intprintLen=0;
for(inti=0; i<ctx->cfg.cmdCount; i++) {
intcmdLen=ctx->cfg.io.printf("%s", ctx->cfg.cmdTable[i].name);
insert_spaces(ctx, MAX_CLI_CMD_LEN-cmdLen);
printLen+=MAX_CLI_CMD_LEN;
printLen+=ctx->cfg.io.printf("%s\n\r", ctx->cfg.cmdTable[i].help);
}
returnprintLen;
}