Blame view

mu/shell.c 14.9 KB
Sergey Poznyakoff authored
1
/* GNU Mailutils -- a suite of utilities for electronic mail
2
   Copyright (C) 2010-2012, 2014-2016 Free Software Foundation, Inc.
Sergey Poznyakoff authored
3 4 5 6 7 8 9 10 11 12 13 14 15 16

   GNU Mailutils is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3, or (at your option)
   any later version.

   GNU Mailutils is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with GNU Mailutils.  If not, see <http://www.gnu.org/licenses/>. */

17
#include "mu.h"
Sergey Poznyakoff authored
18
#include <signal.h>
Sergey Poznyakoff authored
19
#include "muaux.h"
Sergey Poznyakoff authored
20 21 22 23 24 25 26

#ifdef WITH_READLINE
# include <readline/readline.h>
# include <readline/history.h>
#endif

char *mutool_shell_prompt;
27
char **mutool_prompt_env;
28
int mutool_shell_interactive;
Sergey Poznyakoff authored
29 30


Sergey Poznyakoff authored
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
static int got_signal = 0;

static void
_shell_sig (int sig)
{
  got_signal = sig;
}

#define shell_interrupted() (got_signal == SIGINT)

static void
report_signals ()
{
  switch (got_signal)
    {
    case 0:
      break;

    case SIGINT:
      mu_stream_printf (mu_strerr, _("Interrupt\n"));
      mu_stream_flush (mu_strerr);

    default:
      got_signal = 0;
    }
}

Sergey Poznyakoff authored
58 59 60 61 62 63 64 65
static int shell_exit (int, char **);
static int shell_help (int, char **);
static int shell_prompt (int, char **);
#ifdef WITH_READLINE
static int shell_history (int, char **);
#endif

struct mutool_command default_comtab[] = {
66
  { "prompt",     1, 2, CMD_COALESCE_EXTRA_ARGS, shell_prompt,
67 68
    N_("STRING"),
    N_("set command prompt") },
69 70
  { "exit",       1, 1, 0, shell_exit,    NULL,        N_("exit program") },
  { "help",       1, 2, 0, shell_help,
71 72
    N_("[COMMAND]"),
    N_("display this text") },
73
  { "?",          1, 1, 0, shell_help,
74 75
    N_("[COMMAND]"),
    N_("synonym for `help'") },
Sergey Poznyakoff authored
76
#ifdef WITH_READLINE
77
  { "history",    1, 1, 0, shell_history,
78 79
    NULL,
    N_("show command history") },
Sergey Poznyakoff authored
80 81 82 83
#endif
  { NULL }
};

84 85 86 87
#define DESCRCOL 25
#define NUMCOLS  80
#define DESCRWIDTH (NUMCOLS - DESCRCOL)

Sergey Poznyakoff authored
88 89
/* Print a single comtab entry */
static void
90
print_comtab (mu_stream_t stream, struct mutool_command *tab)
Sergey Poznyakoff authored
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
  size_t size = 0;
  const char *text;
  
  if (tab->docstring == NULL)
    return;

  mu_stream_printf (stream, "%s ", tab->name);
  size += strlen (tab->name) + 1;
  if (tab->argdoc)
    {
      text = gettext (tab->argdoc);
      mu_stream_printf (stream, "%s", text);
      size += strlen (text);
    }
  if (size >= DESCRCOL)
    mu_stream_printf (stream, "\n%-*s", DESCRCOL, "");
  else
    mu_stream_printf (stream, "%-*s", (int) (DESCRCOL - size), "");

  text = gettext (tab->docstring);
  size = strlen (text);
  
  while (*text)
    {
      size_t len = size;
      if (len > DESCRWIDTH)
	{
	  /* Fold the text */
	  size_t n = 0;
	  
	  while (n < len)
	    {
	      size_t delta;
	      char *p;
	      
	      p = mu_str_skip_cset_comp (text + n, " \t");
	      delta = p - (text + n);
	      if (n + delta > DESCRWIDTH)
		break;
	      n += delta;
	      
	      p = mu_str_skip_cset (text + n, " \t");
	      delta = p - (text + n);
	      if (n + delta > DESCRWIDTH)
		break;
	      n += delta;
	    }

	  len = n;
	}
      mu_stream_write (stream, text, len, NULL);
      text += len;
      size -= len;
      mu_stream_write (stream, "\n", 1, NULL);
      if (size)
	mu_stream_printf (stream, "%-*s", DESCRCOL, "");
    }
Sergey Poznyakoff authored
149 150 151 152 153
}  

/* Print a single comtab entry.
   FIXME: Way too primitive. Rewrite. */
int
154
print_help (mu_stream_t stream, struct mutool_command *tab, size_t n)
Sergey Poznyakoff authored
155 156 157 158
{
  if (n)
    {
      for (; n > 0 && tab->name; tab++, n--)
159
	print_comtab (stream, tab);
Sergey Poznyakoff authored
160 161 162 163
    }
  else
    {
      for (; tab->name; tab++)
164
	print_comtab (stream, tab);
Sergey Poznyakoff authored
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
    }
  return 0;
}

/* Print all commands from TAB matching NAME.
   FIXME: Way too primitive. Rewrite. */
void
list_commands (struct mutool_command *tab, const char *name)
{
  size_t namelen = strlen (name);
  int printed = 0;
  
  for (; tab->name; tab++)
    {
      /* Print in six columns. */
      if (printed == 6)
	{
	  printed = 0;
183
	  mu_printf ("\n");
Sergey Poznyakoff authored
184 185 186
	}
      if (mu_c_strncasecmp (tab->name, name, namelen) == 0)
	{
187
	  mu_printf ("%s\t", tab->name);
Sergey Poznyakoff authored
188 189 190 191
	  printed++;
	}
    }
  if (printed && printed < 6)
192
    mu_printf ("\n");
Sergey Poznyakoff authored
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
}

static struct mutool_command *
simple_find_command (struct mutool_command *cp, const char *name)
{
  for (; cp->name; cp++)
    if (strcmp (cp->name, name) == 0)
      return cp;
  return NULL;
}


static struct mutool_command *shell_comtab;
static size_t user_command_count;

static struct mutool_command *
find_command (const char *name)
{
  return simple_find_command (shell_comtab, name);
}

/* Print out help for ARG, or for all of the commands if ARG is
   not present. */
int
shell_help (int argc, char **argv)
{
  char *name = argv[1];
220
  
Sergey Poznyakoff authored
221 222 223 224 225
  if (name)
    {
      struct mutool_command *com = find_command (argv[1]);

      if (com)
226
	print_comtab (mu_strout, com);
Sergey Poznyakoff authored
227 228
      else
	{
229
	  mu_printf ("No commands match `%s'.  Possibilties are:\n", name);
Sergey Poznyakoff authored
230 231 232 233 234
	  list_commands (shell_comtab, name);
	}
    }
  else
    {
235 236 237 238 239
      mu_stream_t str = mutool_open_pager ();
      print_help (str, shell_comtab, user_command_count);
      mu_stream_printf (str, "\n");
      print_help (str, shell_comtab + user_command_count, 0);
      mu_stream_destroy (&str);
Sergey Poznyakoff authored
240 241 242 243 244 245 246
    }
  return 0;
}

static int
shell_prompt (int argc, char **argv)
{
247
  mu_wordsplit_t ws;
Sergey Poznyakoff authored
248
  
249 250 251 252 253 254 255 256
  if (mu_wordsplit (argv[1], &ws, MU_WRDSF_NOSPLIT | MU_WRDSF_DEFFLAGS))
    mu_error ("mu_wordsplit: %s", mu_wordsplit_strerror (&ws));
  else
    {
      free (mutool_shell_prompt);
      mutool_shell_prompt = mu_strdup (ws.ws_wordv[0]);
    }
  mu_wordsplit_free (&ws);
Sergey Poznyakoff authored
257 258 259
  return 0;
}

260 261 262 263 264 265 266
mu_stream_t
mutool_open_pager ()
{
  char *pager;
  if (mutool_shell_interactive && (pager = getenv ("PAGER")) != NULL)
    {
      mu_stream_t stream;
267
      int rc = mu_command_stream_create (&stream, pager, MU_STREAM_WRITE);
268 269 270 271
      if (rc == 0)
	return stream;
      mu_error (_("cannot start pager: %s"), mu_strerror (rc));
    }
272 273
  mu_stream_ref (mu_strout);
  return mu_strout;
274
}
Sergey Poznyakoff authored
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289


#ifdef WITH_READLINE
#define HISTFILE_PREFIX "~/.mu_"
#define HISTFILE_SUFFIX "_history"

static char *
get_history_file_name ()
{
  static char *filename = NULL;

  if (!filename)
    {
      char *hname;
      
290 291
      hname = mu_alloc (sizeof HISTFILE_PREFIX + strlen (rl_readline_name) +
		        sizeof HISTFILE_SUFFIX - 1);
Sergey Poznyakoff authored
292
      strcpy (hname, HISTFILE_PREFIX);
Sergey Poznyakoff authored
293 294
      strcat (hname, rl_readline_name);
      strcat (hname, HISTFILE_SUFFIX);
295
      filename = mu_tilde_expansion (hname, MU_HIERARCHY_DELIMITER, NULL);
Sergey Poznyakoff authored
296
      free (hname);
Sergey Poznyakoff authored
297 298 299 300
    }
  return filename;
}

Sergey Poznyakoff authored
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
static int
_shell_getc (FILE *stream)
{
  unsigned char c;

  while (1)
    {
      if (read (fileno (stream), &c, 1) == 1)
	return c;
      if (errno == EINTR)
	{
	  if (shell_interrupted ())
	    break;
	  /* keep going if we handled the signal */
	}
      else
	break;
    }
  return EOF;
}

Sergey Poznyakoff authored
322 323 324 325 326 327 328 329 330 331 332 333 334 335
/* Interface to Readline Completion */

static char *shell_command_generator (const char *, int);
static char **shell_completion (char *, int, int);

/* Tell the GNU Readline library how to complete.  We want to try to complete
   on command names if this is the first word in the line, or on filenames
   if not. */
void
mutool_initialize_readline (const char *name)
{
  /* Allow conditional parsing of the ~/.inputrc file. */
  rl_readline_name = (char *) name;
  rl_attempted_completion_function = (CPPFunction *) shell_completion;
Sergey Poznyakoff authored
336
  rl_getc_function = _shell_getc;
Sergey Poznyakoff authored
337 338 339 340 341 342
  read_history (get_history_file_name ());
}

static void
finish_readline ()
{
Sergey Poznyakoff authored
343
  write_history (get_history_file_name ());
Sergey Poznyakoff authored
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
}

/* Attempt to complete on the contents of TEXT.  START and END bound the
   region of rl_line_buffer that contains the word to complete.  TEXT is
   the word to complete.  We can use the entire contents of rl_line_buffer
   in case we want to do some simple parsing.  Return the array of matches,
   or NULL if there aren't any. */
static char **
shell_completion (char *text, int start, int end MU_ARG_UNUSED)
{
  char **matches;

  matches = (char **) NULL;

  /* If this word is at the start of the line, then it is a command
     to complete.  Otherwise it is the name of a file in the current
     directory. */
  if (start == 0)
    matches = rl_completion_matches (text, shell_command_generator);

  return (matches);
}

/* Generator function for command completion.  STATE lets us know whether
   to start from scratch; without any state (i.e. STATE == 0), then we
   start at the top of the list. */
static char *
shell_command_generator (const char *text, int state)
{
  const char *name;
  static int len;
  static struct mutool_command *cmd;

  /* If this is a new word to complete, initialize now.  This includes
     saving the length of TEXT for efficiency, and initializing the index
     variable to 0. */
  if (!state)
    {
      cmd = shell_comtab;
      len = strlen (text);
    }

  if (!cmd->name)
    return NULL;
    
  
  /* Return the next name which partially matches from the command list. */
  while ((name = cmd->name))
    {
      cmd++;
      if (strncmp (name, text, len) == 0)
395
	return mu_strdup (name);
Sergey Poznyakoff authored
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
    }

  /* If no names matched, then return NULL. */
  return NULL;
}

static char *pre_input_line;

static int
pre_input (void)
{
  rl_insert_text (pre_input_line);
  free (pre_input_line);
  rl_pre_input_hook = NULL;
  rl_redisplay ();
  return 0;
}

static int
retrieve_history (char *str)
{
  char *out;
  int rc;

  rc = history_expand (str, &out);
  switch (rc)
    {
    case -1:
      mu_error ("%s", out);
      free (out);
      return 1;

    case 0:
      break;

    case 1:
      pre_input_line = out;
      rl_pre_input_hook = pre_input;
      return 1;

    case 2:
437
      mu_printf ("%s\n", out);
Sergey Poznyakoff authored
438 439 440 441 442 443 444 445 446 447 448
      free (out);
      return 1;
    }
  return 0;
}

static int
shell_history (int argc, char **argv)
{
  int i;
  HIST_ENTRY **hlist;
449 450
  mu_stream_t out = mutool_open_pager ();
  
Sergey Poznyakoff authored
451 452
  hlist = history_list ();
  for (i = 0; i < history_length; i++)
453
    mu_stream_printf (out, "%4d) %s\n", i + 1, hlist[i]->line);
Sergey Poznyakoff authored
454

455
  mu_stream_destroy (&out);
Sergey Poznyakoff authored
456 457 458 459 460
  return 0;
}

#else
# define finish_readline()
Sergey Poznyakoff authored
461
# define mutool_initialize_readline(name)
Sergey Poznyakoff authored
462 463 464 465 466 467

char *
readline (char *prompt)
{
  static size_t size = 0;
  static char *buf = NULL;
Sergey Poznyakoff authored
468
  size_t n;
Sergey Poznyakoff authored
469 470 471

  if (prompt)
    {
472 473
      mu_printf ("%s", prompt);
      mu_stream_flush (mu_strout);
Sergey Poznyakoff authored
474
    }
475
  if (mu_stream_getline (mu_strin, &buf, &size, &n) || n == 0)
476 477 478 479 480 481
    {
      free (buf);
      buf = NULL;
      size = 0;
      return NULL;
    }
Sergey Poznyakoff authored
482 483 484 485 486 487 488 489 490
  return buf;
}

void
add_history (const char *s MU_ARG_UNUSED)
{
}
#endif

491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
static int
next_arg (struct mu_wordsplit *ws)
{
  int rc = mu_wordsplit (NULL, ws, MU_WRDSF_INCREMENTAL);
  if (rc == MU_WRDSE_NOINPUT)
    {
      mu_error ("%s: too few arguments", ws->ws_wordv[0]);
      mu_wordsplit_free (ws);
      return -1;
    }
  else if (rc)
    {
      mu_error ("cannot parse input line: %s",
		mu_wordsplit_strerror (ws));
      return 1;
    }
  return 0;
}

Sergey Poznyakoff authored
510 511 512 513
/* Parse and execute a command line. */
int
execute_line (char *line)
{
514
  int rc;
515
  struct mu_wordsplit ws;
516
  struct mutool_command *cmd;
Sergey Poznyakoff authored
517
  int status = 0;
518
  
519
  ws.ws_comment = "#";
520
  ws.ws_escape[0] = ws.ws_escape[1] = "\\\\\"\"";
521
  rc = mu_wordsplit (line, &ws,
522
		     MU_WRDSF_DEFFLAGS|MU_WRDSF_COMMENT|MU_WRDSF_ESCAPE|
523 524 525 526 527 528 529
		     MU_WRDSF_INCREMENTAL|MU_WRDSF_APPEND);
  if (rc == MU_WRDSE_NOINPUT)
    {
      mu_wordsplit_free (&ws);
      return 0;
    }
  else if (rc)
Sergey Poznyakoff authored
530
    {
531
      mu_error ("cannot parse input line: %s", mu_wordsplit_strerror (&ws));
Sergey Poznyakoff authored
532 533
      return 0;
    }
534
  
535
  if (ws.ws_wordc)
Sergey Poznyakoff authored
536
    {
537 538 539
      int argmin;
      cmd = find_command (ws.ws_wordv[0]);

Sergey Poznyakoff authored
540
      if (!cmd)
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
	{
	  mu_error ("%s: no such command.", ws.ws_wordv[0]);
	  mu_wordsplit_free (&ws);
	  return 0;
	}

      argmin = cmd->argmin;
      if (cmd->flags & CMD_COALESCE_EXTRA_ARGS)
	--argmin;
      while (ws.ws_wordc < argmin)
	{
	  if (next_arg (&ws))
	    return 0;
	}

      if (cmd->flags & CMD_COALESCE_EXTRA_ARGS)
	{
	  ws.ws_flags |= MU_WRDSF_NOSPLIT;
	  if (next_arg (&ws))
	    return 0;
	}
Sergey Poznyakoff authored
562 563
      else
	{
564
	  for (;;)
Sergey Poznyakoff authored
565
	    {
566
	      if (cmd->argmax > 0 && ws.ws_wordc > cmd->argmax)
Sergey Poznyakoff authored
567
		{
568 569 570 571 572 573 574 575 576 577 578 579 580 581
		  mu_error ("%s: too many arguments", ws.ws_wordv[0]);
		  mu_wordsplit_free (&ws);
		  return 0;
		}
	      rc = mu_wordsplit (NULL, &ws, MU_WRDSF_INCREMENTAL);
	      if (rc == 0)
		continue;
	      else if (rc == MU_WRDSE_NOINPUT)
		break;
	      else
		{
		  mu_error ("cannot parse input line: %s",
			    mu_wordsplit_strerror (&ws));
		  return 0;
Sergey Poznyakoff authored
582 583 584
		}
	    }
	}
585 586

      status = cmd->func (ws.ws_wordc, ws.ws_wordv);
Sergey Poznyakoff authored
587
    }
588
  mu_wordsplit_free (&ws);
Sergey Poznyakoff authored
589 590 591 592 593 594
  return status;
}

static char *
input_line_interactive ()
{
595 596 597 598
  char *line;
  int wsflags = MU_WRDSF_NOSPLIT | MU_WRDSF_NOCMD;
  struct mu_wordsplit ws;
  
Sergey Poznyakoff authored
599
  report_signals ();
600 601 602 603 604 605 606 607 608 609 610 611
  if (mutool_prompt_env)
    {
      ws.ws_env = (const char **)mutool_prompt_env;
      wsflags |= MU_WRDSF_ENV | MU_WRDSF_ENV_KV;
    }
  if (mu_wordsplit (mutool_shell_prompt, &ws, wsflags))
    line = readline (mutool_shell_prompt);
  else
    {
      line = readline (ws.ws_wordv[0]);
      mu_wordsplit_free (&ws);
    }
Sergey Poznyakoff authored
612 613 614 615 616 617
  return line;
}

static char *
input_line_script ()
{
Sergey Poznyakoff authored
618
  size_t size = 0, n;
Sergey Poznyakoff authored
619
  char *buf = NULL;
Sergey Poznyakoff authored
620

Sergey Poznyakoff authored
621
  report_signals ();
622
  if (mu_stream_getline (mu_strin, &buf, &size, &n) || n == 0)
Sergey Poznyakoff authored
623 624 625 626 627 628 629 630 631 632 633 634
    return NULL;
  return buf;
}

static int done;

static int
shell_exit (int argc MU_ARG_UNUSED, char **argv MU_ARG_UNUSED)
{
  done = 1;
  return 0;
}
Sergey Poznyakoff authored
635

Sergey Poznyakoff authored
636 637 638 639
int
mutool_shell (const char *name, struct mutool_command *cmd)
{
  size_t n;
640
  char *(*input_line) ();
Sergey Poznyakoff authored
641 642
  static int sigv[] = { SIGPIPE, SIGINT };
				   
643 644
  mutool_shell_interactive = isatty (0);
  input_line = mutool_shell_interactive ?
Sergey Poznyakoff authored
645 646 647 648 649 650
                             input_line_interactive : input_line_script;

  for (n = 0; cmd[n].name; n++)
    ;

  user_command_count = n;
651 652
  shell_comtab = mu_calloc (n + MU_ARRAY_SIZE (default_comtab),
			    sizeof (shell_comtab[0]));
Sergey Poznyakoff authored
653 654 655 656
  memcpy (shell_comtab, cmd, n * sizeof (shell_comtab[0]));
  memcpy (shell_comtab + n, default_comtab, sizeof (default_comtab));

  mutool_initialize_readline (name);
Sergey Poznyakoff authored
657
  mu_set_signals (_shell_sig, sigv, MU_ARRAY_SIZE (sigv));
Sergey Poznyakoff authored
658 659 660 661
  while (!done)
    {
      char *s, *line = input_line ();
      if (!line)
Sergey Poznyakoff authored
662 663 664 665 666 667 668
	{
	  if (shell_interrupted ())
	    {
	      report_signals ();
	      continue;
	    }
	  else
Sergey Poznyakoff authored
669 670 671 672
	    {
	      mu_printf ("\n");
	      break;
	    }
Sergey Poznyakoff authored
673 674
	}
      
Sergey Poznyakoff authored
675 676 677 678 679 680 681 682 683 684
      /* Remove leading and trailing whitespace from the line.
         Then, if there is anything left, add it to the history list
         and execute it. */
      s = mu_str_stripws (line);

      if (*s)
	{
	  int status;

#ifdef WITH_READLINE
685
	  if (mutool_shell_interactive)
Sergey Poznyakoff authored
686 687 688 689 690 691 692 693 694 695 696 697 698 699
	    {
	      if (retrieve_history (s))
		continue;
	      add_history (s);
	    }
#endif

	  status = execute_line (s);
	  if (status != 0)
	    mu_error ("Error: %s", mu_strerror (status));
	}

      free (line);
    }
700
  if (mutool_shell_interactive)
Sergey Poznyakoff authored
701
    finish_readline ();
702 703
  mu_stream_destroy (&mu_strin);
  mu_stream_destroy (&mu_strout);
Sergey Poznyakoff authored
704 705
  return 0;
}
706