From ebe6923b17de88d37d97846be2567fb75f53292c Mon Sep 17 00:00:00 2001 From: FreeArtMan <=> Date: Thu, 4 Feb 2016 23:02:20 +0000 Subject: Initial commit --- cmd.c | 168 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 168 insertions(+) create mode 100644 cmd.c (limited to 'cmd.c') diff --git a/cmd.c b/cmd.c new file mode 100644 index 0000000..2fb1a76 --- /dev/null +++ b/cmd.c @@ -0,0 +1,168 @@ +#include "cmd.h" + + +int cnt_sep( char *s ) +{ + int cnt=0; + char *p=s; + while ( *p++ ) + { + if (p[0]==' ') + { + cnt++; + } + } + + return cnt; + +} + + +char* cmd_line( char *prompt ) +{ + char *ret = NULL; + char *pmt = ">"; + const int buf_sz = 32; + int ret_sz; + char buf[buf_sz]; + + + if ( prompt != NULL ) + { + pmt = prompt; + } + + memset( buf, 0, buf_sz ); + write( 1, pmt, strlen(pmt) ); + ret_sz = read( 2, buf,buf_sz); + if (ret_sz < 1) + return ret; + + ret = malloc(ret_sz-1); + memcpy( ret, buf, ret_sz-1 ); + + return ret; +} + + +cmd_arg* cmd_parse( char *str ) +{ + int cnt=0; + cmd_arg *ret = NULL; + int i,j; + char *last=str; + int sz; + + + //count white spaces + cnt = cnt_sep( str )+1; + + ret = malloc( sizeof(cmd_arg) ); + ret->argv = malloc( sizeof(void*)*cnt ); + + ret->argc = cnt; + + if ( cnt == 1 ) + { + ret->argv[0] = malloc( strlen(str) ); + memcpy( ret->argv[0], str, strlen(str) ); + return ret; + } + + //best practices + j = 0; + for (i=0;iargv[j] = malloc( sz+1 ); + memcpy(ret->argv[j],last,sz); + ret->argv[j][sz] = '\0'; + last = str+i+1; + j++; + } + } + sz = str + i - last; + ret->argv[j] = malloc(sz+1); + memcpy( ret->argv[j], last, sz ); + ret->argv[j][sz] = '\0'; + + return ret; +} + +int cmd_exec( cmd_arg *cmd, cmd_table *table ) +{ + int ret = 0; + int fret = 0; + int i; + cmd_arg *sub_arg; + + if (cmd->argc < 1) + { + printf("Hm ... no arguments\n"); + return -1; + } + + i = 0; + while ( (table[i].cmd != NULL) && (table[i].clb != NULL) ) + { + if ((strlen(table[i].cmd) == strlen(cmd->argv[0])) + && (strlen(table[i].cmd) != 0)) + if( strncmp( table[i].cmd, cmd->argv[0], strlen(cmd->argv[0]) ) == 0 ) + { + if ( table[i].clb == NULL ) + { + printf("Empty callback for %s\n",table[i].cmd); + ret = -1; + break; + } + + sub_arg = sub_cmd( cmd ); + fret = table[i].clb( sub_arg ); + if ( fret != 0 ) + { + printf("Command unsuccesfull execution\n"); + ret = -1; + break; + } + break; + + } + + i++; + } + + + return ret; +} + + +void cmd_arg_free( cmd_arg *arg ) +{ + +} + +void cmd_sub_arg_free( cmd_arg *arg ) +{ + +} + + +cmd_arg* sub_cmd( cmd_arg *arg ) +{ + int i; + cmd_arg *ret=NULL; + + if ( arg->argc < 1) + return NULL; + + ret = malloc( sizeof(cmd_arg) ); + ret->argc = arg->argc-1; + ret->argv = malloc( sizeof(void*)*ret->argc ); + for (i=0;iargc;i++) + ret->argv[i] = arg->argv[i+1]; + + return ret; +} + -- cgit v1.2.3