Add the program name as the first parameter in the command of the btrfs tool
[platform/upstream/btrfs-progs.git] / btrfs.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public
4  * License v2 as published by the Free Software Foundation.
5  *
6  * This program is distributed in the hope that it will be useful,
7  * but WITHOUT ANY WARRANTY; without even the implied warranty of
8  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
9  * General Public License for more details.
10  *
11  * You should have received a copy of the GNU General Public
12  * License along with this program; if not, write to the
13  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
14  * Boston, MA 021110-1307, USA.
15  */
16
17
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21
22 #include "btrfs_cmds.h"
23 #include "version.h"
24
25 typedef int (*CommandFunction)(int argc, char **argv);
26
27 struct Command {
28         CommandFunction func;   /* function which implements the command */
29         int     nargs;          /* if == 999, any number of arguments
30                                    if >= 0, number of arguments,
31                                    if < 0, _minimum_ number of arguments */
32         char    *verb;          /* verb */
33         char    *help;          /* help lines; form the 2nd onward they are
34                                    indented */
35
36         /* the following fields are run-time filled by the program */
37         char    **cmds;         /* array of subcommands */
38         int     ncmds;          /* number of subcommand */
39 };
40
41 static struct Command commands[] = {
42
43         /*
44                 avoid short commands different for the case only
45         */
46         { do_clone, 2,
47           "subvolume snapshot", "<source> [<dest>/]<name>\n"
48                 "Create a writable snapshot of the subvolume <source> with\n"
49                 "the name <name> in the <dest> directory."
50         },
51         { do_delete_subvolume, 1,
52           "subvolume delete", "<subvolume>\n"
53                 "Delete the subvolume <subvolume>."
54         },
55         { do_create_subvol, 1,
56           "subvolume create", "[<dest>/]<name>\n"
57                 "Create a subvolume in <dest> (or the current directory if\n"
58                 "not passed)."
59         },
60         { do_subvol_list, 1, "subvolume list", "<path>\n"
61                 "List the snapshot/subvolume of a filesystem."
62         },
63
64         { do_defrag, -1,
65           "filesystem defragment", "[-vcf] [-s start] [-l len] [-t size] <file>|<dir> [<file>|<dir>...]\n"
66                 "Defragment a file or a directory."
67         },
68         { do_fssync, 1,
69           "filesystem sync", "<path>\n"
70                 "Force a sync on the filesystem <path>."
71         },
72         { do_resize, 2,
73           "filesystem resize", "[+/-]<newsize>[gkm]|max <filesystem>\n"
74                 "Resize the file system. If 'max' is passed, the filesystem\n"
75                 "will occupe all available space on the device."
76         },
77         { do_show_filesystem, 999,
78           "filesystem show", "[<uuid>|<label>]\n"
79                 "Show the info of a btrfs filesystem. If no <uuid> or <label>\n"
80                 "is passed, info of all the btrfs filesystem are shown."
81         },
82         { do_balance, 1,
83           "filesystem balance", "<path>\n"
84                 "Balance the chunks across the device."
85         },
86         { do_scan,
87           999, "device scan", "[<device> [<device>..]\n"
88                 "Scan all device for or the passed device for a btrfs\n"
89                 "filesystem."
90         },
91         { do_add_volume, -1,
92           "device add", "<dev> [<dev>..] <path>\n"
93                 "Add a device to a filesystem."
94         },
95         { do_remove_volume, -1,
96           "device delete", "<dev> [<dev>..] <path>\n"
97                 "Remove a device from a filesystem."
98         },
99         /* coming soon
100         { 2, "filesystem label", "<label> <path>\n"
101                 "Set the label of a filesystem"
102         }
103         */
104         { 0, 0 , 0 }
105 };
106
107
108
109
110 static char *get_prgname(char *programname)
111 {
112         char    *np;
113         np = strrchr(programname,'/');
114         if(!np)
115                 np = programname;
116         else
117                 np++;
118
119         return np;
120 }
121
122 static void print_help(char *programname, struct Command *cmd)
123 {
124         char    *pc;
125
126         printf("\t%s %s ", programname, cmd->verb );
127
128         for(pc = cmd->help; *pc; pc++){
129                 putchar(*pc);
130                 if(*pc == '\n')
131                         printf("\t\t");
132         }
133         putchar('\n');
134 }
135
136 static void help(char *np)
137 {
138         struct Command *cp;
139
140         printf("Usage:\n");
141         for( cp = commands; cp->verb; cp++ )
142                 print_help(np, cp);
143
144         printf("\n\t%s help|--help|-h\n\t\tShow the help.\n",np);
145         printf("\n%s\n", BTRFS_BUILD_VERSION);
146 }
147
148 static int split_command(char *cmd, char ***commands)
149 {
150         int     c, l;
151         char    *p, *s;
152
153         for( *commands = 0, l = c = 0, p = s = cmd ; ; p++, l++ ){
154                 if ( *p && *p != ' ' )
155                         continue;
156
157                 /* c + 2 so that we have room for the null */
158                 (*commands) = realloc( (*commands), sizeof(char *)*(c + 2));
159                 (*commands)[c] = strndup(s, l);
160                 c++;
161                 l = 0;
162                 s = p+1;
163                 if( !*p ) break;
164         }
165
166         (*commands)[c] = 0;
167         return c;
168 }
169
170 /*
171         This function checks if the passed command is ambiguous
172 */
173 static int check_ambiguity(struct Command *cmd, char **argv){
174         int             i;
175         struct Command  *cp;
176         /* check for ambiguity */
177         for( i = 0 ; i < cmd->ncmds ; i++ ){
178                 int match;
179                 for( match = 0, cp = commands; cp->verb; cp++ ){
180                         int     j, skip;
181                         char    *s1, *s2;
182
183                         if( cp->ncmds < i )
184                                 continue;
185
186                         for( skip = 0, j = 0 ; j < i ; j++ )
187                                 if( strcmp(cmd->cmds[j], cp->cmds[j])){
188                                         skip=1;
189                                         break;
190                                 }
191                         if(skip)
192                                 continue;
193
194                         if( !strcmp(cmd->cmds[i], cp->cmds[i]))
195                                 continue;
196                         for(s2 = cp->cmds[i], s1 = argv[i+1];
197                                 *s1 == *s2 && *s1; s1++, s2++ ) ;
198                         if( !*s1 )
199                                 match++;
200                 }
201                 if(match){
202                         int j;
203                         fprintf(stderr, "ERROR: in command '");
204                         for( j = 0 ; j <= i ; j++ )
205                                 fprintf(stderr, "%s%s",j?" ":"", argv[j+1]);
206                         fprintf(stderr, "', '%s' is ambiguous\n",argv[j]);
207                         return -2;
208                 }
209         }
210         return 0;
211 }
212
213 /*
214  * This function, compacts the program name and the command in the first
215  * element of the '*av' array
216  */
217 static int prepare_args(int *ac, char ***av, char *prgname, struct Command *cmd ){
218
219         char    **ret;
220         int     i;
221         char    *newname;
222
223         ret = (char **)malloc(sizeof(char*)*(*ac+1));
224         newname = (char*)malloc(strlen(prgname)+strlen(cmd->verb)+2);
225         if( !ret || !newname ){
226                 free(ret);
227                 free(newname);
228                 return -1;
229         }
230
231         ret[0] = newname;
232         for(i=0; i < *ac ; i++ )
233                 ret[i+1] = (*av)[i];
234
235         strcpy(newname, prgname);
236         strcat(newname, " ");
237         strcat(newname, cmd->verb);
238
239         (*ac)++;
240         *av = ret;
241
242         return 0;
243
244 }
245
246
247
248 /*
249
250         This function perform the following jobs:
251         - show the help if '--help' or 'help' or '-h' are passed
252         - verify that a command is not ambiguous, otherwise show which
253           part of the command is ambiguous
254         - if after a (even partial) command there is '--help' show the help
255           for all the matching commands
256         - if the command doesn't' match show an error
257         - finally, if a command match, they return which command is matched and
258           the arguments
259
260         The function return 0 in case of help is requested; <0 in case
261         of uncorrect command; >0 in case of matching commands
262         argc, argv are the arg-counter and arg-vector (input)
263         *nargs_ is the number of the arguments after the command (output)
264         **cmd_  is the invoked command (output)
265         ***args_ are the arguments after the command
266
267 */
268 static int parse_args(int argc, char **argv,
269                       CommandFunction *func_,
270                       int *nargs_, char **cmd_, char ***args_ )
271 {
272         struct Command  *cp;
273         struct Command  *matchcmd=0;
274         char            *prgname = get_prgname(argv[0]);
275         int             i=0, helprequested=0;
276
277         if( argc < 2 || !strcmp(argv[1], "help") ||
278                 !strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")){
279                 help(prgname);
280                 return 0;
281         }
282
283         for( cp = commands; cp->verb; cp++ )
284                 if( !cp->ncmds)
285                         cp->ncmds = split_command(cp->verb, &(cp->cmds));
286
287         for( cp = commands; cp->verb; cp++ ){
288                 int     match;
289
290                 if( argc-1 < cp->ncmds )
291                         continue;
292                 for( match = 1, i = 0 ; i < cp->ncmds ; i++ ){
293                         char    *s1, *s2;
294                         s1 = cp->cmds[i];
295                         s2 = argv[i+1];
296
297                         for(s2 = cp->cmds[i], s1 = argv[i+1];
298                                 *s1 == *s2 && *s1;
299                                 s1++, s2++ ) ;
300                         if( *s1 ){
301                                 match=0;
302                                 break;
303                         }
304                 }
305
306                 /* If you understand why this code works ...
307                         you are a genious !! */
308                 if(argc>i+1 && !strcmp(argv[i+1],"--help")){
309                         if(!helprequested)
310                                 printf("Usage:\n");
311                         print_help(prgname, cp);
312                         helprequested=1;
313                         continue;
314                 }
315
316                 if(!match)
317                         continue;
318
319                 matchcmd = cp;
320                 *nargs_  = argc-matchcmd->ncmds-1;
321                 *cmd_ = matchcmd->verb;
322                 *args_ = argv+matchcmd->ncmds+1;
323                 *func_ = cp->func;
324
325                 break;
326         }
327
328         if(helprequested){
329                 printf("\n%s\n", BTRFS_BUILD_VERSION);
330                 return 0;
331         }
332
333         if(!matchcmd){
334                 fprintf( stderr, "ERROR: unknown command '%s'\n",argv[1]);
335                 help(prgname);
336                 return -1;
337         }
338
339         if(check_ambiguity(matchcmd, argv))
340                 return -2;
341
342         /* check the number of argument */
343         if (matchcmd->nargs < 0 && matchcmd->nargs < -*nargs_ ){
344                 fprintf(stderr, "ERROR: '%s' requires minimum %d arg(s)\n",
345                         matchcmd->verb, -matchcmd->nargs);
346                         return -2;
347         }
348         if(matchcmd->nargs >= 0 && matchcmd->nargs != *nargs_ && matchcmd->nargs != 999){
349                 fprintf(stderr, "ERROR: '%s' requires %d arg(s)\n",
350                         matchcmd->verb, matchcmd->nargs);
351                         return -2;
352         }
353         
354         if (prepare_args( nargs_, args_, prgname, matchcmd )){
355                 fprintf(stderr, "ERROR: not enough memory\\n");
356                 return -20;
357         }
358
359
360         return 1;
361 }
362 int main(int ac, char **av )
363 {
364
365         char            *cmd=0, **args=0;
366         int             nargs=0, r;
367         CommandFunction func=0;
368
369         r = parse_args(ac, av, &func, &nargs, &cmd, &args);
370         if( r <= 0 ){
371                 /* error or no command to parse*/
372                 exit(-r);
373         }
374
375         exit(func(nargs, args));
376
377 }
378