Whamcloud - gitweb
b06f624b4c221684180e65c47205a2b362361a39
[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 void Parser_printhelp(char *cmd)
394 {
395         char *argv[] = { "help", cmd }; 
396         Parser_help(2, argv);
397 }
398
399
400 /*************************************************************************
401  * COMMANDS                                                                 *
402  *************************************************************************/ 
403
404
405 static void print_commands(char * str, command_t * table) {
406         command_t * cmds;
407         char         buf[80];
408
409         for (cmds = table; cmds->pc_name; cmds++) {
410                 if (cmds->pc_func) {
411                         if (str) printf("\t%s %s\n", str, cmds->pc_name);
412                         else printf("\t%s\n", cmds->pc_name);
413                 }
414                 if (cmds->pc_sub_cmd) {
415                         if (str) {
416                                 sprintf(buf, "%s %s", str, cmds->pc_name);
417                                 print_commands(buf, cmds->pc_sub_cmd);
418                         } else {
419                                 print_commands(cmds->pc_name, cmds->pc_sub_cmd);
420                         }
421                 }
422         }
423 }
424
425 char *Parser_getstr(const char *prompt, const char *deft, char *res, 
426                     size_t len)
427 {
428         char *line = NULL;
429         int size = strlen(prompt) + strlen(deft) + 8;
430         char *theprompt;
431         theprompt = malloc(size);
432         assert(theprompt);
433
434         sprintf(theprompt, "%s [%s]: ", prompt, deft);
435
436         line  = readline(theprompt);
437         free(theprompt);
438
439         if ( line == NULL || *line == '\0' ) {
440                 strncpy(res, deft, len);
441         } else {
442                 strncpy(res, line, len);
443         }
444
445         if ( line ) {
446                 free(line);
447                 return res;
448         } else {
449                 return NULL;
450         }
451 }
452
453 /* get integer from prompt, loop forever to get it */
454 int Parser_getint(const char *prompt, long min, long max, long deft, int base)
455 {
456         int rc;
457         long result;
458         char *line;
459         int size = strlen(prompt) + 40;
460         char *theprompt = malloc(size);
461         assert(theprompt);
462         sprintf(theprompt,"%s [%ld, (0x%lx)]: ", prompt, deft, deft);
463
464         fflush(stdout);
465
466         do {
467                 line = NULL;
468                 line = readline(theprompt);
469                 if ( !line ) {
470                         fprintf(stdout, "Please enter an integer.\n");
471                         fflush(stdout);
472                         continue;
473                 }
474                 if ( *line == '\0' ) {
475                         free(line);
476                         result =  deft;
477                         break;
478                 }
479                 rc = Parser_arg2int(line, &result, base);
480                 free(line);
481                 if ( rc != 0 ) {
482                         fprintf(stdout, "Invalid string.\n");
483                         fflush(stdout);
484                 } else if ( result > max || result < min ) {
485                         fprintf(stdout, "Error: response must lie between %ld and %ld.\n",
486                                 min, max);
487                         fflush(stdout);
488                 } else {
489                         break;
490                 }
491         } while ( 1 ) ;
492
493         if (theprompt)
494                 free(theprompt);
495         return result;
496
497 }
498
499 /* get boolean (starting with YyNn; loop forever */
500 int Parser_getbool(const char *prompt, int deft)
501 {
502         int result = 0;
503         char *line;
504         int size = strlen(prompt) + 8;
505         char *theprompt = malloc(size);
506         assert(theprompt);
507
508         fflush(stdout);
509     
510         if ( deft != 0 && deft != 1 ) {
511                 fprintf(stderr, "Error: Parser_getbool given bad default (%d).\n",
512                         deft);
513                 assert ( 0 );
514         }
515         sprintf(theprompt, "%s [%s]: ", prompt, (deft==0)? "N" : "Y");
516
517         do {
518                 line = NULL;
519                 line = readline(theprompt);
520                 if ( line == NULL ) {
521                         result = deft;
522                         break;
523                 }
524                 if ( *line == '\0' ) {
525                         result = deft;
526                         break;
527                 }
528                 if ( *line == 'y' || *line == 'Y' ) {
529                         result = 1;
530                         break;
531                 }
532                 if ( *line == 'n' || *line == 'N' ) {
533                         result = 0;
534                         break;
535                 }
536                 if ( line ) 
537                         free(line);
538                 fprintf(stdout, "Invalid string. Must start with yY or nN\n");
539                 fflush(stdout);
540         } while ( 1 );
541
542         if ( line ) 
543                 free(line);
544         if ( theprompt ) 
545                 free(theprompt);
546         return result;
547 }
548
549 /* parse int out of a string or prompt for it */
550 long Parser_intarg(const char *inp, const char *prompt, int deft,
551                    int min, int max, int base)
552 {
553         long result;
554         int rc; 
555     
556         rc = Parser_arg2int(inp, &result, base);
557
558         if ( rc == 0 ) {
559                 return result;
560         } else {
561                 return Parser_getint(prompt, deft, min, max, base);
562         }
563 }
564
565 /* parse int out of a string or prompt for it */
566 char *Parser_strarg(char *inp, const char *prompt, const char *deft,
567                     char *answer, int len)
568 {
569         if ( inp == NULL || *inp == '\0' ) {
570                 return Parser_getstr(prompt, deft, answer, len);
571         } else 
572                 return inp;
573 }
574
575 /* change a string into a number: return 0 on success. No invalid characters
576    allowed. The processing of base and validity follows strtol(3)*/
577 int Parser_arg2int(const char *inp, long *result, int base)
578 {
579         char *endptr;
580
581         if ( (base !=0) && (base < 2 || base > 36) )
582                 return 1;
583
584         *result = strtol(inp, &endptr, base);
585
586         if ( *inp != '\0' && *endptr == '\0' )
587                 return 0;
588         else 
589                 return 1;
590 }
591
592 int Parser_quit(int argc, char **argv)
593 {
594         argc = argc;
595         argv = argv;
596         done = 1;
597         return 0;
598 }