shell: implement functions to parse command lines into an (argc, argv) tuple
This commit is contained in:
parent
7d0f730212
commit
5b97afd1bc
3 changed files with 79 additions and 0 deletions
1
Makefile
1
Makefile
|
@ -37,6 +37,7 @@ obj-y += source/ftl/ftl.o
|
||||||
obj-y += source/ftl/gc.o
|
obj-y += source/ftl/gc.o
|
||||||
obj-y += source/ftl/map.o
|
obj-y += source/ftl/map.o
|
||||||
|
|
||||||
|
obj-y += source/shell/args.o
|
||||||
obj-y += source/shell/cmd.o
|
obj-y += source/shell/cmd.o
|
||||||
obj-y += source/shell/flash.o
|
obj-y += source/shell/flash.o
|
||||||
obj-y += source/shell/ftl.o
|
obj-y += source/shell/ftl.o
|
||||||
|
|
|
@ -1,5 +1,8 @@
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
size_t count_args(char *line);
|
||||||
|
char **parse_args(char *line, size_t *argc);
|
||||||
|
|
||||||
struct cmd {
|
struct cmd {
|
||||||
const char *key;
|
const char *key;
|
||||||
void (* exec)(const char *line);
|
void (* exec)(const char *line);
|
||||||
|
|
75
source/shell/args.c
Normal file
75
source/shell/args.c
Normal file
|
@ -0,0 +1,75 @@
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include <shell.h>
|
||||||
|
|
||||||
|
size_t count_args(char *line)
|
||||||
|
{
|
||||||
|
char *p = line;
|
||||||
|
size_t n = 0;
|
||||||
|
|
||||||
|
while (*p != '\0') {
|
||||||
|
p += strspn(p, " \n\r");
|
||||||
|
|
||||||
|
while (*p != '\0' && *p != ' ') {
|
||||||
|
if (*p++ != '\"')
|
||||||
|
continue;
|
||||||
|
|
||||||
|
while (*p != '\0' && *p != '\"')
|
||||||
|
++p;
|
||||||
|
|
||||||
|
if (*p == '\"')
|
||||||
|
++p;
|
||||||
|
}
|
||||||
|
|
||||||
|
++n;
|
||||||
|
}
|
||||||
|
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
char **parse_args(char *line, size_t *argc)
|
||||||
|
{
|
||||||
|
char **argv;
|
||||||
|
char **arg;
|
||||||
|
char *p = line;
|
||||||
|
char *s;
|
||||||
|
size_t n;
|
||||||
|
|
||||||
|
if (!argc)
|
||||||
|
argc = &n;
|
||||||
|
|
||||||
|
*argc = count_args(line);
|
||||||
|
|
||||||
|
if (!(argv = malloc(*argc * sizeof(char *) + strlen(line) + 1)))
|
||||||
|
return NULL;
|
||||||
|
|
||||||
|
arg = argv;
|
||||||
|
s = (char *)argv + *argc * sizeof(char *);
|
||||||
|
|
||||||
|
while (*p != '\0') {
|
||||||
|
p += strspn(p, " \n\r");
|
||||||
|
*arg++ = s;
|
||||||
|
|
||||||
|
while (*p != '\0' && *p != ' ') {
|
||||||
|
if (*p != '\"') {
|
||||||
|
*s++ = *p++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
++p;
|
||||||
|
|
||||||
|
while (*p != '\0' && *p != '\"')
|
||||||
|
*s++ = *p++;
|
||||||
|
|
||||||
|
if (*p == '\"')
|
||||||
|
++p;
|
||||||
|
}
|
||||||
|
|
||||||
|
*s++ = '\0';
|
||||||
|
}
|
||||||
|
|
||||||
|
return argv;
|
||||||
|
}
|
||||||
|
|
Loading…
Add table
Reference in a new issue