argvs.c 11.6 KB
Newer Older
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
/* todo: make ; splitting work better
 *
 * argvs - argv - shell
 *
 * a small method/dispatcher for C functions following the int main (int argc,
 * char **argv) pattern for receiving it's arguments.
 *
 * It is written in such a way that it should be easily repurposable for
 * various purposes. And possibly easy to extend if one wants to add more
 * advacned behavior.
 */

#include <stdio.h>

#define USE_LINENOISE
#ifdef USE_LINENOISE
#include "linenoise/linenoise.h"
#include "linenoise/linenoise.c"
#else

#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#endif
#include "argvs.h"

27
#ifdef HAVE_MRG
28 29 30 31 32 33
#define MRG_PRINTF 1
#ifdef MRG_PRINTF
#include <mrg.h>
#include <mrg-string.h>
extern Mrg *mrg;
extern MrgList *scrollback;
34
extern int use_ui;
35 36 37

#define printf(foo...) \
   do{ MrgString *str = mrg_string_new_printf (foo);\
38
       if (use_ui) \
39
       mrg_list_prepend (&scrollback, mrg_string_dissolve (str));\
40 41 42 43 44
       else \
       {\
       fprintf (stdout, "%s", str->str);\
       mrg_string_free (str, 1);\
       }\
45 46
   }while(0)
#endif
47
#endif
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
typedef struct _CmdIterator CmdIterator;
typedef struct _CmdEntry CmdEntry;

struct _CmdEntry {
  int (*fun)(COMMAND_ARGS);
  char *name;
  int         req_args;
  char *args;
  char *help;
};

static CmdEntry commands[] = {{0,}};
static CmdEntry dynamic_commands[512] = {{0,}};
static int dynamic_count = 0;

void
argvs_add (int (*fun)(COMMAND_ARGS),
           const char *name,
           int         required_arguments,
           const char *argument_help,
           const char *help)
{
  CmdEntry *entry = &dynamic_commands[dynamic_count++];
  entry->fun = fun;
  if (name)
    entry->name = strdup (name);
  entry->req_args = required_arguments;
  if (argument_help)
    entry->args = strdup (argument_help);
  if (help)
    entry->help = strdup (help);
}


static CmdIterator   *cmd_iterator_new (void *foo);
static CmdEntry      *cmd_iterator_next (CmdIterator *i);
static void           cmd_iterator_stop (CmdIterator *i);

static void
argvs_free (CmdEntry *e)
{
  free (e->help);
  free (e->args);
  free (e->name);
}

static void
argvs_cleanup (void)
{
  CmdIterator *i = cmd_iterator_new (NULL);
  CmdEntry *e;
  while ((e = cmd_iterator_next (i)))
    argvs_free (e);
}

#include "argvs-commands.inc"
/* cmds.inc is supposed to be created by your build system by using the
 * following shell-script to run with your .c files as argument for
 * collecting command definitions.
 */

#if 0
#!/bin/sh

echo "/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */"
echo "/* this file is autogenerated by $0 */"
echo "/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */"

# create function declarations for each item
cat $* | grep COMMAND_ARGS | grep ^int | sort | \
  sed -e 's/^int */int /' -e 's#(COMMAND_ARGS).*#(COMMAND_ARGS);#'

# create a function that registers all items found
echo "void argvs_register(void) {" 
cat $* | grep COMMAND_ARGS | grep ^int | sort | \
  sed -e 's/^int */ argvs_add (/ ' -e 's#(COMMAND_ARGS) */\*#, #' -e 's#\*/$#);#'
echo "};"

#endif

struct _CmdIterator {
  int       i;
  int       j;
  CmdEntry  internal;
  char     *name;
  char     *req_args;
  char     *help;
};

static CmdIterator *cmd_iterator_new (void *foo)
{
  CmdIterator *i = malloc (sizeof (CmdIterator));
  static int first_run = 1;
  if (first_run)
    {
      /* register the build-system harvested items */
      argvs_register ();
      first_run = 0;

      /* free up allocations, so valgrind will not be angry */
      atexit (argvs_cleanup);
    }

  /* at the moment, creating the iterator fills it up with possible sources,
   * this could be done half-lazily,.. adding references to unused sources
   * and expanding each as it is consumed, this allows stopping earlier with
   * less resource use.
   */
  i->name = NULL;

  i->j = -1;
  i->i = -1;
  return i;
}

static void cmd_iterator_stop (CmdIterator *i)
{
  if (i->name)
    free (i->name);
  i->name = NULL;
  free (i);
}

static CmdEntry *cmd_iterator_next (CmdIterator *i)
{
  if (i->name)
    free (i->name);
  i->name = NULL;

  /* first iterate commands from db, then fixed list - this
   * order permits overriding internal commands like forth does */
  i->j++;
  if (i->j < dynamic_count)
    return &dynamic_commands[i->j];

  /* first iterate commands from db, then fixed list - this
   * order permits overriding internal commands like forth does */
  i->i++;
  if ((unsigned)i->i < sizeof (commands) / sizeof (commands[0]))
    if (commands[i->i].fun)
      return &commands[i->i];
  cmd_iterator_stop (i);
  return NULL;
}

/******* the rest should be using the iteration API for access
 * to commands and not poke around in internals   ************/

static char *string_chop_head (char *orig) /* return pointer to reset after arg */
{
  int j=0;
  int eat=0; /* number of chars to eat at start */
  
  if(orig)
    {
      int got_more;
      char *o = orig;
      while(o[j] == ' ')
        {j++;eat++;}
      
      if (o[j]=='"')
        {
          eat++;j++;
          while(o[j] != '"' &&
                o[j] != 0)
            j++;
          o[j]='\0';
          j++;
        }
      else if (o[j]=='\'')
        {
          eat++;j++;
          while(o[j] != '\'' &&
                o[j] != 0)
            j++;
          o[j]='\0';
          j++;
        }
      else
        {
          while(o[j] != ' ' &&
                o[j] != 0 &&
                o[j] != ';')
            j++;
        }

      if (o[j] == 0 ||
          o[j] == ';')
        got_more = 0;
      else
        got_more = 1;
      o[j]=0; /* XXX: this is where foo;bar won't work but foo ;bar works*/

      if(eat)
       {
         int k;
         for (k=0; k<j-eat; k++)
           orig[k] = orig[k+eat];
       }
      if (got_more)
        return &orig[j+1];
    }
  return NULL;
}

int argvs_eval (const char *cmdline)
{
  char *cargv[32];
  int   cargc;
  char *rest, *copy;
  int ret = 0;

  copy = calloc (strlen (cmdline)+2, 1);
  strcpy (copy, cmdline);
  rest = copy;

  /* XXX: detect ; and pause ... we could have a label that we go back
   * to and evaluate again when one is encountered... t c*/
  do {
    cargc = 0;
    while (rest && cargc < 30 && rest[0] != ';')
      {
        cargv[cargc++] = rest;
        rest = string_chop_head (rest);
      }
    cargv[cargc] = NULL;

276

277 278 279 280
    if (cargv[0])
      {
        CmdIterator *ci = cmd_iterator_new (NULL);
        CmdEntry *command;
281
        int found = 0;
282 283 284 285 286 287 288 289 290 291 292 293 294 295
        while ((command = cmd_iterator_next (ci)))
          if (!strcmp (cargv[0], command->name))
            {
              if (command->req_args > cargc - 1)
                {
                  printf ("command '%s' needs %i args, %i given\n",
                      command->name, command->req_args, cargc - 1);
                  ret = -1;
                }
              else
                ret = command->fun (cargc, cargv, NULL);
              if (ret)
                printf ("%s returned: %i\n", command->name, ret);
              cmd_iterator_stop (ci);
296
              found = 1;
297 298 299 300
              break;
              goto b;
            }
b:
301
        if (cargv[0][0] && !found)
302 303 304 305 306
          {
            //XXX: somehow pipe this back into the ui
            //fprintf (stdout, "unknown command '%s'\n", cargv[0]);
            //fflush (NULL);
            //sleep (1);
307
            printf ("unknown command '%s' use ? for a list of registered commands\n", cargv[0]);
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 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
          }
      }
    if (rest && rest[0]==';')
      {
        rest++;
        while (rest[0] == ' ')rest++;
      }
  } while (rest && rest[0]);

  free (copy);
  return ret;
}

//#include "common.h"

static int echo_on = 0;
static char  prompt[60] = "> ";

void update_prompt ()
{
  {
    snprintf (prompt, 59, "> ");
  }
}

int cmd_echo_on (COMMAND_ARGS) /* "echo_on", 0, "", "enables command echoing udring sourcing" */
{
  echo_on = 1;
  return 0;
}

int argvs_source (const char *path)
{
  FILE *f = fopen(path, "r");
  if (!f)
    return -1;

  char commandline[1024]="";

  for (fgets(commandline,1023,f);
       fgets(commandline,1023,f);)
    {
      commandline[strlen(commandline)-1]=0; /* remove newline */
      if (echo_on && commandline[0])
        {
          update_prompt ();
          printf ("%s", prompt);
          printf ("%s\n", commandline);
        }
      argvs_eval (commandline);
    }
  fclose (f);
  return 0;
}

int cmd_source (COMMAND_ARGS) /* ".", 1, "<path>", "sources script at path"*/
{
  return argvs_source (argv[1]);
}

#ifdef USE_LINENOISE
static int str_has_prefix (const char *string, const char *buf)
{
  return !strncmp (string, buf, strlen (buf));
}
static void linenoise_completion (const char *buf, linenoiseCompletions *lc)
{
  CmdIterator *ci = cmd_iterator_new (NULL);
  CmdEntry *command;

  while ((command = cmd_iterator_next (ci)))
    {
      if (str_has_prefix (command->name, buf))
        linenoiseAddCompletion (lc, (void*)command->name);
    }

  /* add completions for some central commands,. like help.. */
}
#endif

int cmd_argvs (COMMAND_ARGS) /* "argvs", 0, "<script | -c <command> >", "the minimalistic shell with int argc, char **argv semantics you now use" */
{    

  if (argv[1] && !strcmp(argv[1], "-c"))
    {
      argvs_eval (argv[2]);
    }
  else if (argc > 1)
    {
      CmdIterator *ci = cmd_iterator_new (NULL);
      CmdEntry *command;

      while ((command = cmd_iterator_next (ci)))
        {
          if (!strcmp (argv[1], command->name))
            {
              if (command->req_args > argc - 2)
                {
                  printf ("command '%s' needs %i args, %i given\n",
                      command->name, command->req_args, argc - 2);
                  cmd_iterator_stop (ci);
                  return -1;
                }
              cmd_iterator_stop (ci);
              return command->fun (argc-1, argv+1, NULL);
            }
        }
      /* didn't match a command, gamble that it is a file instead */
      {
        cmd_source (argc, argv, NULL);
      }
    }
  else
    {
#ifdef USE_LINENOISE
      char *commandline;
      
      linenoiseSetCompletionCallback(linenoise_completion);
      update_prompt ();
      while ( (commandline = linenoise(prompt))!=NULL &&
               strcmp(commandline, "q") &&
               strcmp(commandline, "quit"))
      {
        linenoiseHistoryAdd (commandline);
        argvs_eval (commandline);
        free (commandline);
        update_prompt ();
      }
#else
      char commandline[1024];
      printf ("> ");
      fgets (commandline, 1023, stdin);
      for (;
           strcmp (commandline, "quit\n") && strcmp (commandline,"q\n"); 
           fgets (commandline, 1023, stdin))
        {
          commandline[strlen(commandline)-1]=0; /* remove newline */
          argvs_eval (commandline);
          printf ("> ");
        }
#endif
    }
  return 0;
}

453
int cmd_aa_help (COMMAND_ARGS) /* "?", 0, "[command]", "get's help about a coloritto command" */
454 455 456 457 458 459 460 461 462 463
{
  if (argv[1])
    {
      CmdIterator *ci = cmd_iterator_new (NULL);
      CmdEntry *command;

      while ((command = cmd_iterator_next (ci)))
        {
          if (!strcmp (argv[1], "?") ||
              !strcmp (command->name, argv[1]))
464 465 466 467
          {
            printf ("%s %s\n", command->name, command->args);
            printf ("  %s\n\n", command->help);
          }
468 469 470 471 472 473 474 475 476 477 478 479
        }
    }
  else
    {
      CmdIterator *ci = cmd_iterator_new (NULL);
      printf ("Available commands:\n");

      CmdEntry *command;

      while ((command = cmd_iterator_next (ci)))
        printf ("%s ", command->name);
      printf ("\n\n");
480 481
      printf ("Enter ? <commandname>    for details on a command\n");
      printf ("      ? ?                for details on all commands\n");
482 483 484 485 486 487 488 489 490 491 492 493
    }
  return 0;
}

#ifdef COMPILE_TEST
int main (int argc, char **argv)
{
  /* just transfer control to the shell */
  cmd_argvs (argc, argv, NULL);
  return 0;
}
#endif