Whamcloud - gitweb
- more of the locking infrastructure.
[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     
100 static command_t *Parser_findargcmd(char *name, command_t cmds[])
101 {
102         command_t *cmd;
103         int i;
104
105         for (i = 0; cmds[i].pc_name; i++) {
106                 cmd = &cmds[i];
107
108                 if (strlen(name) != strlen(cmd->pc_name))
109                         continue;
110
111                 if (strlen(name) == strlen(cmd->pc_name)) {
112                         if (strcmp(name, cmd->pc_name) == 0) 
113                                 return cmd;
114                         else
115                                 continue;
116                 }
117
118         }
119         return NULL;
120 }
121
122 int Parser_execarg(int argc, char **argv, command_t cmds[])
123 {
124         command_t *cmd;
125         int i;
126
127         cmd = Parser_findargcmd(argv[0], cmds);
128         if ( cmd ) {
129                 return (cmd->pc_func)(argc, argv);
130         } else {
131                 printf("Try interactive use without arguments or use one of: ");
132                 for (i=0 ; cmds[i].pc_name ; i++) {
133                         cmd = &cmds[i];
134                         printf("\"%s\" ", cmd->pc_name);
135                 }
136                 printf("as argument.\n");
137         }
138         return -1;
139 }
140
141 /* returns the command_t * (NULL if not found) corresponding to a
142    _partial_ match with the first token in name.  It sets *next to
143    point to the following token. Does not modify *name. */
144 static command_t * find_cmd(char * name, command_t cmds[], char ** next) 
145 {
146         int    i, len;
147     
148         if (!cmds || !name ) 
149                 return NULL;
150     
151         /* This sets name to point to the first non-white space character,
152            and next to the first whitespace after name, len to the length: do
153            this with strtok*/
154         name = skipwhitespace(name);
155         *next = skiptowhitespace(name);
156         len = *next - name;
157         if (len == 0) 
158                 return NULL;
159
160         for (i = 0; cmds[i].pc_name; i++) {
161                 if (strncasecmp(name, cmds[i].pc_name, len) == 0) {
162                         *next = skipwhitespace(*next);
163                         return(&cmds[i]);
164                 }
165         }
166         return NULL;
167 }
168
169 /* Recursively process a command line string s and find the command
170    corresponding to it. This can be ambiguous, full, incomplete,
171    non-existent. */
172 static int process(char *s, char ** next, command_t *lookup,
173                    command_t **result, char **prev)
174 {
175         *result = find_cmd(s, lookup, next);
176         *prev = s; 
177
178         /* non existent */
179         if ( ! *result ) 
180                 return CMD_NONE;
181
182         /* found entry: is it ambigous, i.e. not exact command name and
183            more than one command in the list matches.  Note that find_cmd
184            points to the first ambiguous entry */
185         if ( strncasecmp(s, (*result)->pc_name, strlen((*result)->pc_name)) &&
186              find_cmd(s, (*result) + 1, next)) 
187                 return CMD_AMBIG;
188
189         /* found a unique command: component or full? */
190         if ( (*result)->pc_func ) {
191                 return CMD_COMPLETE;
192         } else {
193                 if ( *next == '\0' ) {
194                         return CMD_INCOMPLETE;
195                 } else {
196                         return process(*next, next, (*result)->pc_sub_cmd, result, prev);
197                 }
198         }
199 }
200
201 static char * command_generator(const char * text, int state) 
202 {
203         static int index,
204                 len;
205         char       *name;
206
207         /* Do we have a match table? */
208         if (!match_tbl) 
209                 return NULL;
210     
211         /* If this is the first time called on this word, state is 0 */
212         if (!state) {
213                 index = 0;
214                 len = (int)strlen(text);
215         }
216
217         /* Return the next name in the command list that paritally matches test */
218         while ( (name = (match_tbl + index)->pc_name) ) {
219                 index++;
220
221                 if (strncasecmp(name, text, len) == 0) {
222                         return(strdup(name));
223                 }
224         }
225
226         /* No more matches */
227         return NULL;
228 }
229
230 /* probably called by readline */
231 static char **command_completion(char * text, int start, int end) 
232 {
233         command_t         * table;
234         char        * pos;
235
236         match_tbl = top_level;
237         for (table = find_cmd(rl_line_buffer, match_tbl, &pos);
238              table;
239              table = find_cmd(pos, match_tbl, &pos)) {
240
241                 if (*(pos - 1) == ' ') match_tbl = table->pc_sub_cmd;
242         }
243
244         return(completion_matches(text, command_generator));
245 }
246
247 /* take a string and execute the function or print help */
248 void execute_line(char * line) 
249 {
250         command_t         *cmd, *ambig;
251         char *prev;
252         char *next, *tmp;
253         char *argv[MAXARGS];
254         int         i;
255
256         switch( process(line, &next, top_level, &cmd, &prev) ) {
257         case CMD_AMBIG:
258                 fprintf(stderr, "Ambiguous command \'%s\'\nOptions: ", line);
259                 while( (ambig = find_cmd(prev, cmd, &tmp)) ) {
260                         fprintf(stderr, "%s ", ambig->pc_name);
261                         cmd = ambig + 1;
262                 }
263                 fprintf(stderr, "\n");
264                 break;
265         case CMD_NONE:
266                 fprintf(stderr, "No such command, type help\n");
267                 break;
268         case CMD_INCOMPLETE:
269                 fprintf(stderr,
270                         "'%s' incomplete command.  Use '%s x' where x is one of:\n",
271                         line, line);
272                 fprintf(stderr, "\t");
273                 for (i = 0; cmd->pc_sub_cmd[i].pc_name; i++) {
274                         fprintf(stderr, "%s ", cmd->pc_sub_cmd[i].pc_name);
275                 }
276                 fprintf(stderr, "\n");
277                 break;
278         case CMD_COMPLETE:
279                 i = line2args(line, argv, MAXARGS);
280                 (cmd->pc_func)(i, argv);
281                 break;
282         }
283     
284         return;
285 }
286
287 /* this is the command execution machine */
288 void Parser_commands(void) 
289 {
290         char *line,
291                 *s;
292
293         using_history();
294         stifle_history(HISTORY);
295
296         rl_attempted_completion_function = 
297                 (CPPFunction *)command_completion;
298         rl_completion_entry_function = (void *)command_generator;
299     
300         while(!done) {
301                 line = readline(parser_prompt);
302
303                 if (!line) break;
304
305                 s = skipwhitespace(line);
306
307                 if (*s) {
308                         add_history(s);
309                         execute_line(s);
310                 }
311
312                 free(line);
313         }
314 }
315
316
317 /* sets the parser prompt */
318 void Parser_init(char * prompt, command_t * cmds) 
319 {
320         done = 0;
321         top_level = cmds;
322         if (parser_prompt) free(parser_prompt);
323         parser_prompt = strdup(prompt);
324 }
325
326 /* frees the parser prompt */
327 void Parser_exit(int argc, char *argv[]) 
328 {
329         done = 1;
330         free(parser_prompt);
331         parser_prompt = NULL;
332 }
333
334 /* convert a string to an integer */
335 int Parser_int(char *s, int *val)
336 {
337         int ret;
338
339         if (*s != '0')
340                 ret = sscanf(s, "%d", val);
341         else if (*(s+1) != 'x')
342                 ret = sscanf(s, "%o", val);
343         else {
344                 s++;
345                 ret = sscanf(++s, "%x", val);
346         }
347
348         return(ret);
349 }
350
351
352     
353 void Parser_qhelp(int argc, char *argv[]) {
354
355         printf("Available commands are:\n");
356         
357         print_commands(NULL, top_level);
358         printf("For more help type: help command-name\n");
359 }
360
361 int Parser_help(int argc, char **argv) 
362 {
363         char line[1024];
364         char *next, *prev, *tmp;
365         command_t *result, *ambig;
366         int i;
367
368         if ( argc == 1 ) {
369                 Parser_qhelp(argc, argv);
370                 return 0;
371         }
372
373         line[0]='\0';
374         for ( i = 1 ;  i < argc ; i++ ) {
375                 strcat(line, argv[i]);
376         }
377
378         switch ( process(line, &next, top_level, &result, &prev) ) {
379         case CMD_COMPLETE:
380                 fprintf(stderr, "%s: %s\n",line, result->pc_help);
381                 break;
382         case CMD_NONE:
383                 fprintf(stderr, "%s: Unknown command.\n", line);
384                 break;
385         case CMD_INCOMPLETE:
386                 fprintf(stderr,
387                         "'%s' incomplete command.  Use '%s x' where x is one of:\n",
388                         line, line);
389                 fprintf(stderr, "\t");
390                 for (i = 0; result->pc_sub_cmd[i].pc_name; i++) {
391                         fprintf(stderr, "%s ", result->pc_sub_cmd[i].pc_name);
392                 }
393                 fprintf(stderr, "\n");
394                 break;
395         case CMD_AMBIG:
396                 fprintf(stderr, "Ambiguous command \'%s\'\nOptions: ", line);
397                 while( (ambig = find_cmd(prev, result, &tmp)) ) {
398                         fprintf(stderr, "%s ", ambig->pc_name);
399                         result = ambig + 1;
400                 }
401                 fprintf(stderr, "\n");
402                 break;
403         }
404         return 0;
405 }  
406
407 /*************************************************************************
408  * COMMANDS                                                                 *
409  *************************************************************************/ 
410
411
412 static void print_commands(char * str, command_t * table) {
413         command_t * cmds;
414         char         buf[80];
415
416         for (cmds = table; cmds->pc_name; cmds++) {
417                 if (cmds->pc_func) {
418                         if (str) printf("\t%s %s\n", str, cmds->pc_name);
419                         else printf("\t%s\n", cmds->pc_name);
420                 }
421                 if (cmds->pc_sub_cmd) {
422                         if (str) {
423                                 sprintf(buf, "%s %s", str, cmds->pc_name);
424                                 print_commands(buf, cmds->pc_sub_cmd);
425                         } else {
426                                 print_commands(cmds->pc_name, cmds->pc_sub_cmd);
427                         }
428                 }
429         }
430 }
431
432 char *Parser_getstr(const char *prompt, const char *deft, char *res, 
433                     size_t len)
434 {
435         char *line = NULL;
436         int size = strlen(prompt) + strlen(deft) + 8;
437         char *theprompt;
438         theprompt = malloc(size);
439         assert(theprompt);
440
441         sprintf(theprompt, "%s [%s]: ", prompt, deft);
442
443         line  = readline(theprompt);
444         free(theprompt);
445
446         if ( line == NULL || *line == '\0' ) {
447                 strncpy(res, deft, len);
448         } else {
449                 strncpy(res, line, len);
450         }
451
452         if ( line ) {
453                 free(line);
454                 return res;
455         } else {
456                 return NULL;
457         }
458 }
459
460 /* get integer from prompt, loop forever to get it */
461 int Parser_getint(const char *prompt, long min, long max, long deft, int base)
462 {
463         int rc;
464         long result;
465         char *line;
466         int size = strlen(prompt) + 40;
467         char *theprompt = malloc(size);
468         assert(theprompt);
469         sprintf(theprompt,"%s [%ld, (0x%lx)]: ", prompt, deft, deft);
470
471         fflush(stdout);
472
473         do {
474                 line = NULL;
475                 line = readline(theprompt);
476                 if ( !line ) {
477                         fprintf(stdout, "Please enter an integer.\n");
478                         fflush(stdout);
479                         continue;
480                 }
481                 if ( *line == '\0' ) {
482                         free(line);
483                         result =  deft;
484                         break;
485                 }
486                 rc = Parser_arg2int(line, &result, base);
487                 free(line);
488                 if ( rc != 0 ) {
489                         fprintf(stdout, "Invalid string.\n");
490                         fflush(stdout);
491                 } else if ( result > max || result < min ) {
492                         fprintf(stdout, "Error: response must lie between %ld and %ld.\n",
493                                 min, max);
494                         fflush(stdout);
495                 } else {
496                         break;
497                 }
498         } while ( 1 ) ;
499
500         if (theprompt)
501                 free(theprompt);
502         return result;
503
504 }
505
506 /* get boolean (starting with YyNn; loop forever */
507 int Parser_getbool(const char *prompt, int deft)
508 {
509         int result = 0;
510         char *line;
511         int size = strlen(prompt) + 8;
512         char *theprompt = malloc(size);
513         assert(theprompt);
514
515         fflush(stdout);
516     
517         if ( deft != 0 && deft != 1 ) {
518                 fprintf(stderr, "Error: Parser_getbool given bad default (%d).\n",
519                         deft);
520                 assert ( 0 );
521         }
522         sprintf(theprompt, "%s [%s]: ", prompt, (deft==0)? "N" : "Y");
523
524         do {
525                 line = NULL;
526                 line = readline(theprompt);
527                 if ( line == NULL ) {
528                         result = deft;
529                         break;
530                 }
531                 if ( *line == '\0' ) {
532                         result = deft;
533                         break;
534                 }
535                 if ( *line == 'y' || *line == 'Y' ) {
536                         result = 1;
537                         break;
538                 }
539                 if ( *line == 'n' || *line == 'N' ) {
540                         result = 0;
541                         break;
542                 }
543                 if ( line ) 
544                         free(line);
545                 fprintf(stdout, "Invalid string. Must start with yY or nN\n");
546                 fflush(stdout);
547         } while ( 1 );
548
549         if ( line ) 
550                 free(line);
551         if ( theprompt ) 
552                 free(theprompt);
553         return result;
554 }
555
556 /* parse int out of a string or prompt for it */
557 long Parser_intarg(const char *inp, const char *prompt, int deft,
558                    int min, int max, int base)
559 {
560         long result;
561         int rc; 
562     
563         rc = Parser_arg2int(inp, &result, base);
564
565         if ( rc == 0 ) {
566                 return result;
567         } else {
568                 return Parser_getint(prompt, deft, min, max, base);
569         }
570 }
571
572 /* parse int out of a string or prompt for it */
573 char *Parser_strarg(char *inp, const char *prompt, const char *deft,
574                     char *answer, int len)
575 {
576     
577         if ( inp == NULL || *inp == '\0' ) {
578                 return Parser_getstr(prompt, deft, answer, len);
579         } else 
580                 return inp;
581 }
582
583 /* change a string into a number: return 0 on success. No invalid characters
584    allowed. The processing of base and validity follows strtol(3)*/
585 int Parser_arg2int(const char *inp, long *result, int base)
586 {
587         char *endptr;
588
589         if ( (base !=0) && (base < 2 || base > 36) )
590                 return 1;
591
592         *result = strtol(inp, &endptr, base);
593
594         if ( *inp != '\0' && *endptr == '\0' )
595                 return 0;
596         else 
597                 return 1;
598 }
599
600 int Parser_quit(int argc, char **argv)
601 {
602         argc = argc;
603         argv = argv;
604         done = 1; 
605         return 0;
606 }