Whamcloud - gitweb
fc22ba7f4ab347f39ff04313d872c1869ac7f7ea
[fs/lustre-release.git] / lustre / utils / parser.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * Copyright (C) 2001 Cluster File Systems, Inc.
5  *
6  *   This file is part of Lustre, http://www.sf.net/projects/lustre/
7  *
8  *   Lustre is free software; you can redistribute it and/or
9  *   modify it under the terms of version 2 of the GNU General Public
10  *   License as published by the Free Software Foundation.
11  *
12  *   Lustre is distributed in the hope that it will be useful,
13  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *   GNU General Public License for more details.
16  *
17  *   You should have received a copy of the GNU General Public License
18  *   along with Lustre; if not, write to the Free Software
19  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20  *
21  */
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <ctype.h>
25 #include <string.h>
26 #include <stddef.h>
27 #include <sys/param.h>
28 #include <assert.h>
29
30 #define READLINE_LIBRARY
31 #include <readline/readline.h>
32
33 //extern char **completion_matches __P((char *, rl_compentry_func_t *));
34 extern void using_history(void);
35 extern void stifle_history(int);
36 extern void add_history(char *);
37
38 #include "parser.h"
39 #define CMD_COMPLETE 0
40 #define CMD_INCOMPLETE 1
41 #define CMD_NONE 2
42 #define CMD_AMBIG 3
43
44 static command_t * top_level;           /* Top level of commands, initialized by
45                                     * InitParser                              */
46 static command_t * match_tbl;           /* Command completion against this table */
47 static char * parser_prompt = NULL;/* Parser prompt, set by InitParser      */
48 static int done;                   /* Set to 1 if user types exit or quit   */
49
50
51 /* static functions */
52 static char *skipwhitespace(char *s);
53 static char *skiptowhitespace(char *s);
54 static command_t *find_cmd(char *name, command_t cmds[], char **next);
55 static int process(char *s, char **next, command_t *lookup, command_t **result, char **prev);
56 static char *command_generator(const char *text, int state);
57 static char **command_completion(char *text, int start, int end);
58 static void print_commands(char *str, command_t *table);
59
60 static char * skipwhitespace(char * s) 
61 {
62         char * t;
63         int    len;
64
65         len = (int)strlen(s);
66         for (t = s; t <= s + len && isspace(*t); t++);
67         return(t);
68 }
69
70
71 static char * skiptowhitespace(char * s) 
72 {
73         char * t;
74
75         for (t = s; *t && !isspace(*t); t++);
76         return(t);
77 }
78
79 static int line2args(char *line, char **argv, int maxargs)
80 {
81         char *arg;
82         int i = 0; 
83     
84         arg = strtok(line, " \t");
85         if ( arg ) {
86                 argv[i] = arg;
87                 i++;
88         } else 
89                 return 0;
90
91         while( (arg = strtok(NULL, " \t")) && (i <= maxargs)) {
92                 argv[i] = arg;
93                 i++;
94         }
95         return i;
96 }
97
98 /* find a command -- return it if unique otherwise print alternatives */
99 static command_t *Parser_findargcmd(char *name, command_t cmds[])
100 {
101         command_t *cmd;
102
103         for (cmd = cmds; cmd->pc_name; cmd++) {
104                 if (strcmp(name, cmd->pc_name) == 0)
105                         return cmd;
106         }
107         return NULL;
108 }
109
110 int Parser_execarg(int argc, char **argv, command_t cmds[])
111 {
112         command_t *cmd;
113
114         cmd = Parser_findargcmd(argv[0], cmds);
115         if ( cmd ) {
116                 return (cmd->pc_func)(argc, argv);
117         } else {
118                 printf("Try interactive use without arguments or use one of:\n");
119                 for (cmd = cmds; cmd->pc_name; cmd++)
120                         printf("\"%s\" ", cmd->pc_name);
121                 printf("\nas argument.\n");
122         }
123         return -1;
124 }
125
126 /* returns the command_t * (NULL if not found) corresponding to a
127    _partial_ match with the first token in name.  It sets *next to
128    point to the following token. Does not modify *name. */
129 static command_t * find_cmd(char * name, command_t cmds[], char ** next) 
130 {
131         int    i, len;
132     
133         if (!cmds || !name ) 
134                 return NULL;
135     
136         /* This sets name to point to the first non-white space character,
137            and next to the first whitespace after name, len to the length: do
138            this with strtok*/
139         name = skipwhitespace(name);
140         *next = skiptowhitespace(name);
141         len = *next - name;
142         if (len == 0) 
143                 return NULL;
144
145         for (i = 0; cmds[i].pc_name; i++) {
146                 if (strncasecmp(name, cmds[i].pc_name, len) == 0) {
147                         *next = skipwhitespace(*next);
148                         return(&cmds[i]);
149                 }
150         }
151         return NULL;
152 }
153
154 /* Recursively process a command line string s and find the command
155    corresponding to it. This can be ambiguous, full, incomplete,
156    non-existent. */
157 static int process(char *s, char ** next, command_t *lookup,
158                    command_t **result, char **prev)
159 {
160         *result = find_cmd(s, lookup, next);
161         *prev = s; 
162
163         /* non existent */
164         if ( ! *result ) 
165                 return CMD_NONE;
166
167         /* found entry: is it ambigous, i.e. not exact command name and
168            more than one command in the list matches.  Note that find_cmd
169            points to the first ambiguous entry */
170         if ( strncasecmp(s, (*result)->pc_name, strlen((*result)->pc_name)) &&
171              find_cmd(s, (*result) + 1, next)) 
172                 return CMD_AMBIG;
173
174         /* found a unique command: component or full? */
175         if ( (*result)->pc_func ) {
176                 return CMD_COMPLETE;
177         } else {
178                 if ( *next == '\0' ) {
179                         return CMD_INCOMPLETE;
180                 } else {
181                         return process(*next, next, (*result)->pc_sub_cmd, result, prev);
182                 }
183         }
184 }
185
186 static char * command_generator(const char * text, int state) 
187 {
188         static int index,
189                 len;
190         char       *name;
191
192         /* Do we have a match table? */
193         if (!match_tbl) 
194                 return NULL;
195     
196         /* If this is the first time called on this word, state is 0 */
197         if (!state) {
198                 index = 0;
199                 len = (int)strlen(text);
200         }
201
202         /* Return the next name in the command list that paritally matches test */
203         while ( (name = (match_tbl + index)->pc_name) ) {
204                 index++;
205
206                 if (strncasecmp(name, text, len) == 0) {
207                         return(strdup(name));
208                 }
209         }
210
211         /* No more matches */
212         return NULL;
213 }
214
215 /* probably called by readline */
216 static char **command_completion(char * text, int start, int end) 
217 {
218         command_t         * table;
219         char        * pos;
220
221         match_tbl = top_level;
222         for (table = find_cmd(rl_line_buffer, match_tbl, &pos);
223              table;
224              table = find_cmd(pos, match_tbl, &pos)) {
225
226                 if (*(pos - 1) == ' ') match_tbl = table->pc_sub_cmd;
227         }
228
229         return(completion_matches(text, command_generator));
230 }
231
232 /* take a string and execute the function or print help */
233 int execute_line(char * line)
234 {
235         command_t         *cmd, *ambig;
236         char *prev;
237         char *next, *tmp;
238         char *argv[MAXARGS];
239         int         i;
240         int rc = 0;
241
242         switch( process(line, &next, top_level, &cmd, &prev) ) {
243         case CMD_AMBIG:
244                 fprintf(stderr, "Ambiguous command \'%s\'\nOptions: ", line);
245                 while( (ambig = find_cmd(prev, cmd, &tmp)) ) {
246                         fprintf(stderr, "%s ", ambig->pc_name);
247                         cmd = ambig + 1;
248                 }
249                 fprintf(stderr, "\n");
250                 break;
251         case CMD_NONE:
252                 fprintf(stderr, "No such command, type help\n");
253                 break;
254         case CMD_INCOMPLETE:
255                 fprintf(stderr,
256                         "'%s' incomplete command.  Use '%s x' where x is one of:\n",
257                         line, line);
258                 fprintf(stderr, "\t");
259                 for (i = 0; cmd->pc_sub_cmd[i].pc_name; i++) {
260                         fprintf(stderr, "%s ", cmd->pc_sub_cmd[i].pc_name);
261                 }
262                 fprintf(stderr, "\n");
263                 break;
264         case CMD_COMPLETE:
265                 i = line2args(line, argv, MAXARGS);
266                 rc = (cmd->pc_func)(i, argv);
267                 break;
268         }
269
270         return rc;
271 }
272
273 /* this is the command execution machine */
274 int Parser_commands(void)
275 {
276         char *line, *s;
277         int rc = 0;
278
279         using_history();
280         stifle_history(HISTORY);
281
282         rl_attempted_completion_function = (CPPFunction *)command_completion;
283         rl_completion_entry_function = (void *)command_generator;
284
285         while(!done) {
286                 line = readline(parser_prompt);
287
288                 if (!line) break;
289
290                 s = skipwhitespace(line);
291
292                 if (*s) {
293                         add_history(s);
294                         rc = execute_line(s);
295                 }
296
297                 free(line);
298         }
299         return rc;
300 }
301
302
303 /* sets the parser prompt */
304 void Parser_init(char * prompt, command_t * cmds) 
305 {
306         done = 0;
307         top_level = cmds;
308         if (parser_prompt) free(parser_prompt);
309         parser_prompt = strdup(prompt);
310 }
311
312 /* frees the parser prompt */
313 void Parser_exit(int argc, char *argv[]) 
314 {
315         done = 1;
316         free(parser_prompt);
317         parser_prompt = NULL;
318 }
319
320 /* convert a string to an integer */
321 int Parser_int(char *s, int *val)
322 {
323         int ret;
324
325         if (*s != '0')
326                 ret = sscanf(s, "%d", val);
327         else if (*(s+1) != 'x')
328                 ret = sscanf(s, "%o", val);
329         else {
330                 s++;
331                 ret = sscanf(++s, "%x", val);
332         }
333
334         return(ret);
335 }
336
337
338 void Parser_qhelp(int argc, char *argv[]) {
339
340         printf("Available commands are:\n");
341
342         print_commands(NULL, top_level);
343         printf("For more help type: help command-name\n");
344 }
345
346 int Parser_help(int argc, char **argv) 
347 {
348         char line[1024];
349         char *next, *prev, *tmp;
350         command_t *result, *ambig;
351         int i;
352
353         if ( argc == 1 ) {
354                 Parser_qhelp(argc, argv);
355                 return 0;
356         }
357
358         line[0]='\0';
359         for ( i = 1 ;  i < argc ; i++ ) {
360                 strcat(line, argv[i]);
361         }
362
363         switch ( process(line, &next, top_level, &result, &prev) ) {
364         case CMD_COMPLETE:
365                 fprintf(stderr, "%s: %s\n",line, result->pc_help);
366                 break;
367         case CMD_NONE:
368                 fprintf(stderr, "%s: Unknown command.\n", line);
369                 break;
370         case CMD_INCOMPLETE:
371                 fprintf(stderr,
372                         "'%s' incomplete command.  Use '%s x' where x is one of:\n",
373                         line, line);
374                 fprintf(stderr, "\t");
375                 for (i = 0; result->pc_sub_cmd[i].pc_name; i++) {
376                         fprintf(stderr, "%s ", result->pc_sub_cmd[i].pc_name);
377                 }
378                 fprintf(stderr, "\n");
379                 break;
380         case CMD_AMBIG:
381                 fprintf(stderr, "Ambiguous command \'%s\'\nOptions: ", line);
382                 while( (ambig = find_cmd(prev, result, &tmp)) ) {
383                         fprintf(stderr, "%s ", ambig->pc_name);
384                         result = ambig + 1;
385                 }
386                 fprintf(stderr, "\n");
387                 break;
388         }
389         return 0;
390 }  
391
392 /*************************************************************************
393  * COMMANDS                                                                 *
394  *************************************************************************/ 
395
396
397 static void print_commands(char * str, command_t * table) {
398         command_t * cmds;
399         char         buf[80];
400
401         for (cmds = table; cmds->pc_name; cmds++) {
402                 if (cmds->pc_func) {
403                         if (str) printf("\t%s %s\n", str, cmds->pc_name);
404                         else printf("\t%s\n", cmds->pc_name);
405                 }
406                 if (cmds->pc_sub_cmd) {
407                         if (str) {
408                                 sprintf(buf, "%s %s", str, cmds->pc_name);
409                                 print_commands(buf, cmds->pc_sub_cmd);
410                         } else {
411                                 print_commands(cmds->pc_name, cmds->pc_sub_cmd);
412                         }
413                 }
414         }
415 }
416
417 char *Parser_getstr(const char *prompt, const char *deft, char *res, 
418                     size_t len)
419 {
420         char *line = NULL;
421         int size = strlen(prompt) + strlen(deft) + 8;
422         char *theprompt;
423         theprompt = malloc(size);
424         assert(theprompt);
425
426         sprintf(theprompt, "%s [%s]: ", prompt, deft);
427
428         line  = readline(theprompt);
429         free(theprompt);
430
431         if ( line == NULL || *line == '\0' ) {
432                 strncpy(res, deft, len);
433         } else {
434                 strncpy(res, line, len);
435         }
436
437         if ( line ) {
438                 free(line);
439                 return res;
440         } else {
441                 return NULL;
442         }
443 }
444
445 /* get integer from prompt, loop forever to get it */
446 int Parser_getint(const char *prompt, long min, long max, long deft, int base)
447 {
448         int rc;
449         long result;
450         char *line;
451         int size = strlen(prompt) + 40;
452         char *theprompt = malloc(size);
453         assert(theprompt);
454         sprintf(theprompt,"%s [%ld, (0x%lx)]: ", prompt, deft, deft);
455
456         fflush(stdout);
457
458         do {
459                 line = NULL;
460                 line = readline(theprompt);
461                 if ( !line ) {
462                         fprintf(stdout, "Please enter an integer.\n");
463                         fflush(stdout);
464                         continue;
465                 }
466                 if ( *line == '\0' ) {
467                         free(line);
468                         result =  deft;
469                         break;
470                 }
471                 rc = Parser_arg2int(line, &result, base);
472                 free(line);
473                 if ( rc != 0 ) {
474                         fprintf(stdout, "Invalid string.\n");
475                         fflush(stdout);
476                 } else if ( result > max || result < min ) {
477                         fprintf(stdout, "Error: response must lie between %ld and %ld.\n",
478                                 min, max);
479                         fflush(stdout);
480                 } else {
481                         break;
482                 }
483         } while ( 1 ) ;
484
485         if (theprompt)
486                 free(theprompt);
487         return result;
488
489 }
490
491 /* get boolean (starting with YyNn; loop forever */
492 int Parser_getbool(const char *prompt, int deft)
493 {
494         int result = 0;
495         char *line;
496         int size = strlen(prompt) + 8;
497         char *theprompt = malloc(size);
498         assert(theprompt);
499
500         fflush(stdout);
501     
502         if ( deft != 0 && deft != 1 ) {
503                 fprintf(stderr, "Error: Parser_getbool given bad default (%d).\n",
504                         deft);
505                 assert ( 0 );
506         }
507         sprintf(theprompt, "%s [%s]: ", prompt, (deft==0)? "N" : "Y");
508
509         do {
510                 line = NULL;
511                 line = readline(theprompt);
512                 if ( line == NULL ) {
513                         result = deft;
514                         break;
515                 }
516                 if ( *line == '\0' ) {
517                         result = deft;
518                         break;
519                 }
520                 if ( *line == 'y' || *line == 'Y' ) {
521                         result = 1;
522                         break;
523                 }
524                 if ( *line == 'n' || *line == 'N' ) {
525                         result = 0;
526                         break;
527                 }
528                 if ( line ) 
529                         free(line);
530                 fprintf(stdout, "Invalid string. Must start with yY or nN\n");
531                 fflush(stdout);
532         } while ( 1 );
533
534         if ( line ) 
535                 free(line);
536         if ( theprompt ) 
537                 free(theprompt);
538         return result;
539 }
540
541 /* parse int out of a string or prompt for it */
542 long Parser_intarg(const char *inp, const char *prompt, int deft,
543                    int min, int max, int base)
544 {
545         long result;
546         int rc; 
547     
548         rc = Parser_arg2int(inp, &result, base);
549
550         if ( rc == 0 ) {
551                 return result;
552         } else {
553                 return Parser_getint(prompt, deft, min, max, base);
554         }
555 }
556
557 /* parse int out of a string or prompt for it */
558 char *Parser_strarg(char *inp, const char *prompt, const char *deft,
559                     char *answer, int len)
560 {
561         if ( inp == NULL || *inp == '\0' ) {
562                 return Parser_getstr(prompt, deft, answer, len);
563         } else 
564                 return inp;
565 }
566
567 /* change a string into a number: return 0 on success. No invalid characters
568    allowed. The processing of base and validity follows strtol(3)*/
569 int Parser_arg2int(const char *inp, long *result, int base)
570 {
571         char *endptr;
572
573         if ( (base !=0) && (base < 2 || base > 36) )
574                 return 1;
575
576         *result = strtol(inp, &endptr, base);
577
578         if ( *inp != '\0' && *endptr == '\0' )
579                 return 0;
580         else 
581                 return 1;
582 }
583
584 int Parser_quit(int argc, char **argv)
585 {
586         argc = argc;
587         argv = argv;
588         done = 1;
589         return 0;
590 }