diff options
Diffstat (limited to 'cmd.c')
-rw-r--r-- | cmd.c | 168 |
1 files changed, 0 insertions, 168 deletions
@@ -1,168 +0,0 @@ -#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;i<strlen(str);i++) - { - if (str[i]==' ') - { - sz = (str+i)-last; - ret->argv[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;i<ret->argc;i++) - ret->argv[i] = arg->argv[i+1]; - - return ret; -} - |