shell: separate code
This commit is contained in:
parent
422ef6ae51
commit
eb41dd93db
4 changed files with 296 additions and 2 deletions
81
source/shell/cmd.c
Normal file
81
source/shell/cmd.c
Normal file
|
@ -0,0 +1,81 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include <shell.h>
|
||||
|
||||
struct cmd main_cmds[] = {
|
||||
{ "flash", do_flash_cmd },
|
||||
{ NULL, NULL },
|
||||
};
|
||||
|
||||
static char *prompt(const char *prefix)
|
||||
{
|
||||
char *alloc, *line, *s;
|
||||
size_t nbytes = 0, nalloc_bytes = 16;
|
||||
char c;
|
||||
|
||||
printf(prefix);
|
||||
|
||||
if (!(line = malloc(nalloc_bytes)))
|
||||
return NULL;
|
||||
|
||||
s = line;
|
||||
|
||||
while ((c = getchar()) && c != '\n') {
|
||||
putchar(c);
|
||||
|
||||
if (nbytes + 1 >= nalloc_bytes) {
|
||||
nalloc_bytes *= 2;
|
||||
|
||||
if (!(alloc = realloc(line, nalloc_bytes)))
|
||||
goto err_free_line;
|
||||
|
||||
line = alloc;
|
||||
}
|
||||
|
||||
*s++ = c;
|
||||
nbytes++;
|
||||
}
|
||||
|
||||
printf("\n");
|
||||
*s = '\0';
|
||||
|
||||
return line;
|
||||
|
||||
err_free_line:
|
||||
free(line);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void cmd_exec(struct cmd *cmds, const char *line)
|
||||
{
|
||||
struct cmd *cmd;
|
||||
const char *args;
|
||||
char *key;
|
||||
size_t n;
|
||||
|
||||
n = strcspn(line, " \n");
|
||||
key = strndup(line, n);
|
||||
|
||||
args = line + n;
|
||||
args += strspn(args, " \n");
|
||||
|
||||
for (cmd = cmds; cmd->key; ++cmd) {
|
||||
if (strcmp(cmd->key, key) == 0) {
|
||||
cmd->exec(args);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void cmd_loop(const char *show)
|
||||
{
|
||||
char *line;
|
||||
|
||||
while (1) {
|
||||
line = prompt(show);
|
||||
cmd_exec(main_cmds, line);
|
||||
free(line);
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue