generator: Remove DangerWillRobinson.
[libguestfs.git] / generator / generator_fish.ml
1 (* libguestfs
2  * Copyright (C) 2009-2010 Red Hat Inc.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  *)
18
19 (* Please read generator/README first. *)
20
21 open Printf
22
23 open Generator_types
24 open Generator_utils
25 open Generator_pr
26 open Generator_docstrings
27 open Generator_optgroups
28 open Generator_actions
29 open Generator_structs
30 open Generator_prepopts
31 open Generator_c
32
33 (* Generate a lot of different functions for guestfish. *)
34 let generate_fish_cmds () =
35   generate_header CStyle GPLv2plus;
36
37   let all_functions =
38     List.filter (
39       fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
40     ) all_functions in
41   let all_functions_sorted =
42     List.filter (
43       fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
44     ) all_functions_sorted in
45
46   let all_functions_and_fish_commands_sorted =
47     List.sort action_compare (all_functions_sorted @ fish_commands) in
48
49   pr "#include <config.h>\n";
50   pr "\n";
51   pr "/* It is safe to call deprecated functions from this file. */\n";
52   pr "#undef GUESTFS_WARN_DEPRECATED\n";
53   pr "\n";
54   pr "#include <stdio.h>\n";
55   pr "#include <stdlib.h>\n";
56   pr "#include <string.h>\n";
57   pr "#include <inttypes.h>\n";
58   pr "\n";
59   pr "#include \"c-ctype.h\"\n";
60   pr "#include \"full-write.h\"\n";
61   pr "#include \"xstrtol.h\"\n";
62   pr "\n";
63   pr "#include <guestfs.h>\n";
64   pr "#include \"fish.h\"\n";
65   pr "#include \"fish-cmds.h\"\n";
66   pr "#include \"options.h\"\n";
67   pr "#include \"cmds_gperf.h\"\n";
68   pr "\n";
69   pr "/* Valid suffixes allowed for numbers.  See Gnulib xstrtol function. */\n";
70   pr "static const char *xstrtol_suffixes = \"0kKMGTPEZY\";\n";
71   pr "\n";
72
73   List.iter (
74     fun (name, _, _, _, _, _, _) ->
75       pr "static int run_%s (const char *cmd, size_t argc, char *argv[]);\n"
76         name
77   ) all_functions;
78
79   pr "\n";
80
81   (* List of command_entry structs. *)
82   List.iter (
83     fun (name, _, _, flags, _, shortdesc, longdesc) ->
84       let name2 = replace_char name '_' '-' in
85       let aliases =
86         filter_map (function FishAlias n -> Some n | _ -> None) flags in
87       let describe_alias =
88         if aliases <> [] then
89           sprintf "\n\nYou can use %s as an alias for this command."
90             (String.concat " or " (List.map (fun s -> "'" ^ s ^ "'") aliases))
91         else "" in
92
93       let pod =
94         sprintf "%s - %s\n\n=head1 DESCRIPTION\n\n%s\n\n%s"
95           name2 shortdesc longdesc describe_alias in
96       let text =
97         String.concat "\n" (pod2text ~trim:false ~discard:false "NAME" pod)
98         ^ "\n" in
99
100       pr "struct command_entry %s_cmd_entry = {\n" name;
101       pr "  .name = \"%s\",\n" name2;
102       pr "  .help = \"%s\",\n" (c_quote text);
103       pr "  .run = run_%s\n" name;
104       pr "};\n";
105       pr "\n";
106   ) fish_commands;
107
108   List.iter (
109     fun (name, (_, args, optargs), _, flags, _, shortdesc, longdesc) ->
110       let name2 = replace_char name '_' '-' in
111       let aliases =
112         filter_map (function FishAlias n -> Some n | _ -> None) flags in
113
114       let longdesc = replace_str longdesc "C<guestfs_" "C<" in
115       let synopsis =
116         match args with
117         | [] -> name2
118         | args ->
119             let args = List.filter (function Key _ -> false | _ -> true) args in
120             sprintf "%s%s%s"
121               name2
122               (String.concat ""
123                  (List.map (fun arg -> " " ^ name_of_argt arg) args))
124               (String.concat ""
125                  (List.map (fun arg -> sprintf " [%s:..]" (name_of_argt arg)) optargs)) in
126
127       let warnings =
128         if List.exists (function Key _ -> true | _ -> false) args then
129           "\n\nThis command has one or more key or passphrase parameters.
130 Guestfish will prompt for these separately."
131         else "" in
132
133       let warnings =
134         warnings ^
135           if List.mem ProtocolLimitWarning flags then
136             ("\n\n" ^ protocol_limit_warning)
137           else "" in
138
139       let warnings =
140         warnings ^
141           match deprecation_notice flags with
142           | None -> ""
143           | Some txt -> "\n\n" ^ txt in
144
145       let describe_alias =
146         if aliases <> [] then
147           sprintf "\n\nYou can use %s as an alias for this command."
148             (String.concat " or " (List.map (fun s -> "'" ^ s ^ "'") aliases))
149         else "" in
150
151       let pod =
152         sprintf "%s - %s\n\n=head1 SYNOPSIS\n\n %s\n\n=head1 DESCRIPTION\n\n%s%s%s"
153           name2 shortdesc synopsis longdesc warnings describe_alias in
154       let text =
155         String.concat "\n" (pod2text ~trim:false ~discard:false "NAME" pod)
156         ^ "\n" in
157
158       pr "struct command_entry %s_cmd_entry = {\n" name;
159       pr "  .name = \"%s\",\n" name2;
160       pr "  .help = \"%s\",\n" (c_quote text);
161       pr "  .run = run_%s\n" name;
162       pr "};\n";
163       pr "\n";
164   ) all_functions;
165
166   (* list_commands function, which implements guestfish -h *)
167   pr "void list_commands (void)\n";
168   pr "{\n";
169   pr "  printf (\"    %%-16s     %%s\\n\", _(\"Command\"), _(\"Description\"));\n";
170   pr "  list_builtin_commands ();\n";
171   List.iter (
172     fun (name, _, _, flags, _, shortdesc, _) ->
173       let name = replace_char name '_' '-' in
174       pr "  printf (\"%%-20s %%s\\n\", \"%s\", _(\"%s\"));\n"
175         name shortdesc
176   ) all_functions_and_fish_commands_sorted;
177   pr "  printf (\"    %%s\\n\",";
178   pr "          _(\"Use -h <cmd> / help <cmd> to show detailed help for a command.\"));\n";
179   pr "}\n";
180   pr "\n";
181
182   (* display_command function, which implements guestfish -h cmd *)
183   pr "int display_command (const char *cmd)\n";
184   pr "{\n";
185   pr "  const struct command_table *ct;\n";
186   pr "\n";
187   pr "  ct = lookup_fish_command (cmd, strlen (cmd));\n";
188   pr "  if (ct) {\n";
189   pr "    fputs (ct->entry->help, stdout);\n";
190   pr "    return 0;\n";
191   pr "  }\n";
192   pr "  else\n";
193   pr "    return display_builtin_command (cmd);\n";
194   pr "}\n";
195   pr "\n";
196
197   let emit_print_list_function typ =
198     pr "static void print_%s_list (struct guestfs_%s_list *%ss)\n"
199       typ typ typ;
200     pr "{\n";
201     pr "  unsigned int i;\n";
202     pr "\n";
203     pr "  for (i = 0; i < %ss->len; ++i) {\n" typ;
204     pr "    printf (\"[%%d] = {\\n\", i);\n";
205     pr "    print_%s_indent (&%ss->val[i], \"  \");\n" typ typ;
206     pr "    printf (\"}\\n\");\n";
207     pr "  }\n";
208     pr "}\n";
209     pr "\n";
210   in
211
212   (* print_* functions *)
213   List.iter (
214     fun (typ, cols) ->
215       let needs_i =
216         List.exists (function (_, (FUUID|FBuffer)) -> true | _ -> false) cols in
217
218       pr "static void print_%s_indent (struct guestfs_%s *%s, const char *indent)\n" typ typ typ;
219       pr "{\n";
220       if needs_i then (
221         pr "  unsigned int i;\n";
222         pr "\n"
223       );
224       List.iter (
225         function
226         | name, FString ->
227             pr "  printf (\"%%s%s: %%s\\n\", indent, %s->%s);\n" name typ name
228         | name, FUUID ->
229             pr "  printf (\"%%s%s: \", indent);\n" name;
230             pr "  for (i = 0; i < 32; ++i)\n";
231             pr "    printf (\"%%c\", %s->%s[i]);\n" typ name;
232             pr "  printf (\"\\n\");\n"
233         | name, FBuffer ->
234             pr "  printf (\"%%s%s: \", indent);\n" name;
235             pr "  for (i = 0; i < %s->%s_len; ++i)\n" typ name;
236             pr "    if (c_isprint (%s->%s[i]))\n" typ name;
237             pr "      printf (\"%%c\", %s->%s[i]);\n" typ name;
238             pr "    else\n";
239             pr "      printf (\"\\\\x%%02x\", %s->%s[i]);\n" typ name;
240             pr "  printf (\"\\n\");\n"
241         | name, (FUInt64|FBytes) ->
242             pr "  printf (\"%%s%s: %%\" PRIu64 \"\\n\", indent, %s->%s);\n"
243               name typ name
244         | name, FInt64 ->
245             pr "  printf (\"%%s%s: %%\" PRIi64 \"\\n\", indent, %s->%s);\n"
246               name typ name
247         | name, FUInt32 ->
248             pr "  printf (\"%%s%s: %%\" PRIu32 \"\\n\", indent, %s->%s);\n"
249               name typ name
250         | name, FInt32 ->
251             pr "  printf (\"%%s%s: %%\" PRIi32 \"\\n\", indent, %s->%s);\n"
252               name typ name
253         | name, FChar ->
254             pr "  printf (\"%%s%s: %%c\\n\", indent, %s->%s);\n"
255               name typ name
256         | name, FOptPercent ->
257             pr "  if (%s->%s >= 0) printf (\"%%s%s: %%g %%%%\\n\", indent, %s->%s);\n"
258               typ name name typ name;
259             pr "  else printf (\"%%s%s: \\n\", indent);\n" name
260       ) cols;
261       pr "}\n";
262       pr "\n";
263   ) structs;
264
265   (* Emit a print_TYPE_list function definition only if that function is used. *)
266   List.iter (
267     function
268     | typ, (RStructListOnly | RStructAndList) ->
269         (* generate the function for typ *)
270         emit_print_list_function typ
271     | typ, _ -> () (* empty *)
272   ) (rstructs_used_by all_functions);
273
274   (* Emit a print_TYPE function definition only if that function is used. *)
275   List.iter (
276     function
277     | typ, (RStructOnly | RStructAndList) ->
278         pr "static void print_%s (struct guestfs_%s *%s)\n" typ typ typ;
279         pr "{\n";
280         pr "  print_%s_indent (%s, \"\");\n" typ typ;
281         pr "}\n";
282         pr "\n";
283     | typ, _ -> () (* empty *)
284   ) (rstructs_used_by all_functions);
285
286   (* run_<action> actions *)
287   List.iter (
288     fun (name, (ret, args, optargs as style), _, flags, _, _, _) ->
289       pr "static int\n";
290       pr "run_%s (const char *cmd, size_t argc, char *argv[])\n" name;
291       pr "{\n";
292       (match ret with
293        | RErr
294        | RInt _
295        | RBool _ -> pr "  int r;\n"
296        | RInt64 _ -> pr "  int64_t r;\n"
297        | RConstString _ | RConstOptString _ -> pr "  const char *r;\n"
298        | RString _ -> pr "  char *r;\n"
299        | RStringList _ | RHashtable _ -> pr "  char **r;\n"
300        | RStruct (_, typ) -> pr "  struct guestfs_%s *r;\n" typ
301        | RStructList (_, typ) -> pr "  struct guestfs_%s_list *r;\n" typ
302        | RBufferOut _ ->
303            pr "  char *r;\n";
304            pr "  size_t size;\n";
305       );
306       List.iter (
307         function
308         | Device n
309         | String n
310         | OptString n -> pr "  const char *%s;\n" n
311         | Pathname n
312         | Dev_or_Path n
313         | FileIn n
314         | FileOut n
315         | Key n -> pr "  char *%s;\n" n
316         | BufferIn n ->
317             pr "  const char *%s;\n" n;
318             pr "  size_t %s_size;\n" n
319         | StringList n | DeviceList n -> pr "  char **%s;\n" n
320         | Bool n -> pr "  int %s;\n" n
321         | Int n -> pr "  int %s;\n" n
322         | Int64 n -> pr "  int64_t %s;\n" n
323         | Pointer _ -> assert false
324       ) args;
325
326       if optargs <> [] then (
327         pr "  struct guestfs_%s_argv optargs_s = { .bitmask = 0 };\n" name;
328         pr "  struct guestfs_%s_argv *optargs = &optargs_s;\n" name
329       );
330
331       if args <> [] || optargs <> [] then
332         pr "  size_t i = 0;\n";
333
334       pr "\n";
335
336       (* Check and convert parameters. *)
337       let argc_minimum, argc_maximum =
338         let args_no_keys =
339           List.filter (function Key _ -> false | _ -> true) args in
340         let argc_minimum = List.length args_no_keys in
341         let argc_maximum = argc_minimum + List.length optargs in
342         argc_minimum, argc_maximum in
343
344       if argc_minimum = argc_maximum then (
345         pr "  if (argc != %d) {\n" argc_minimum;
346         pr "    fprintf (stderr, _(\"%%s should have %%d parameter(s)\\n\"), cmd, %d);\n"
347           argc_minimum;
348       ) else (
349         pr "  if (argc < %d || argc > %d) {\n" argc_minimum argc_maximum;
350         pr "    fprintf (stderr, _(\"%%s should have %%d-%%d parameter(s)\\n\"), cmd, %d, %d);\n"
351           argc_minimum argc_maximum;
352       );
353       pr "    fprintf (stderr, _(\"type 'help %%s' for help on %%s\\n\"), cmd, cmd);\n";
354       pr "    return -1;\n";
355       pr "  }\n";
356
357       let parse_integer expr fn fntyp rtyp range name =
358         pr "  {\n";
359         pr "    strtol_error xerr;\n";
360         pr "    %s r;\n" fntyp;
361         pr "\n";
362         pr "    xerr = %s (%s, NULL, 0, &r, xstrtol_suffixes);\n" fn expr;
363         pr "    if (xerr != LONGINT_OK) {\n";
364         pr "      fprintf (stderr,\n";
365         pr "               _(\"%%s: %%s: invalid integer parameter (%%s returned %%d)\\n\"),\n";
366         pr "               cmd, \"%s\", \"%s\", xerr);\n" name fn;
367         pr "      return -1;\n";
368         pr "    }\n";
369         (match range with
370          | None -> ()
371          | Some (min, max, comment) ->
372              pr "    /* %s */\n" comment;
373              pr "    if (r < %s || r > %s) {\n" min max;
374              pr "      fprintf (stderr, _(\"%%s: %%s: integer out of range\\n\"), cmd, \"%s\");\n"
375                name;
376              pr "      return -1;\n";
377              pr "    }\n";
378              pr "    /* The check above should ensure this assignment does not overflow. */\n";
379         );
380         pr "    %s = r;\n" name;
381         pr "  }\n";
382       in
383
384       List.iter (
385         function
386         | Device name
387         | String name ->
388             pr "  %s = argv[i++];\n" name
389         | Pathname name
390         | Dev_or_Path name ->
391             pr "  %s = win_prefix (argv[i++]); /* process \"win:\" prefix */\n" name;
392             pr "  if (%s == NULL) return -1;\n" name
393         | OptString name ->
394             pr "  %s = STRNEQ (argv[i], \"\") ? argv[i] : NULL;\n" name;
395             pr "  i++;\n"
396         | BufferIn name ->
397             pr "  %s = argv[i];\n" name;
398             pr "  %s_size = strlen (argv[i]);\n" name;
399             pr "  i++;\n"
400         | FileIn name ->
401             pr "  %s = file_in (argv[i++]);\n" name;
402             pr "  if (%s == NULL) return -1;\n" name
403         | FileOut name ->
404             pr "  %s = file_out (argv[i++]);\n" name;
405             pr "  if (%s == NULL) return -1;\n" name
406         | StringList name | DeviceList name ->
407             pr "  %s = parse_string_list (argv[i++]);\n" name;
408             pr "  if (%s == NULL) return -1;\n" name
409         | Key name ->
410             pr "  %s = read_key (\"%s\");\n" name name;
411             pr "  if (keys_from_stdin)\n";
412             pr "    input_lineno++;\n";
413             pr "  if (%s == NULL) return -1;\n" name
414         | Bool name ->
415             pr "  %s = is_true (argv[i++]) ? 1 : 0;\n" name
416         | Int name ->
417             let range =
418               let min = "(-(2LL<<30))"
419               and max = "((2LL<<30)-1)"
420               and comment =
421                 "The Int type in the generator is a signed 31 bit int." in
422               Some (min, max, comment) in
423             parse_integer "argv[i++]" "xstrtoll" "long long" "int" range name
424         | Int64 name ->
425             parse_integer "argv[i++]" "xstrtoll" "long long" "int64_t" None name
426         | Pointer _ -> assert false
427       ) args;
428
429       (* Optional arguments are prefixed with <argname>:<value> and
430        * may be missing, so we need to parse those until the end of
431        * the argument list.
432        *)
433       if optargs <> [] then (
434         let uc_name = String.uppercase name in
435         pr "\n";
436         pr "  for (; i < argc; ++i) {\n";
437         pr "    uint64_t this_mask;\n";
438         pr "    const char *this_arg;\n";
439         pr "\n";
440         pr "    ";
441         List.iter (
442           fun argt ->
443             let n = name_of_argt argt in
444             let uc_n = String.uppercase n in
445             let len = String.length n in
446             pr "if (STRPREFIX (argv[i], \"%s:\")) {\n" n;
447             (match argt with
448              | Bool n ->
449                  pr "      optargs_s.%s = is_true (&argv[i][%d]) ? 1 : 0;\n"
450                    n (len+1);
451              | Int n ->
452                  let range =
453                    let min = "(-(2LL<<30))"
454                    and max = "((2LL<<30)-1)"
455                    and comment =
456                      "The Int type in the generator is a signed 31 bit int." in
457                    Some (min, max, comment) in
458                  let expr = sprintf "&argv[i][%d]" (len+1) in
459                  parse_integer expr "xstrtoll" "long long" "int" range
460                    (sprintf "optargs_s.%s" n)
461              | Int64 n ->
462                  let expr = sprintf "&argv[i][%d]" (len+1) in
463                  parse_integer expr "xstrtoll" "long long" "int64_t" None
464                    (sprintf "optargs_s.%s" n)
465              | String n ->
466                  pr "      optargs_s.%s = &argv[i][%d];\n" n (len+1);
467              | _ -> assert false
468             );
469             pr "      this_mask = GUESTFS_%s_%s_BITMASK;\n" uc_name uc_n;
470             pr "      this_arg = \"%s\";\n" n;
471             pr "    }\n";
472             pr "    else ";
473         ) optargs;
474
475         pr "{\n";
476         pr "      fprintf (stderr, _(\"%%s: unknown optional argument \\\"%%s\\\"\\n\"),\n";
477         pr "               cmd, argv[i]);\n";
478         pr "      return -1;\n";
479         pr "    }\n";
480         pr "\n";
481         pr "    if (optargs_s.bitmask & this_mask) {\n";
482         pr "      fprintf (stderr, _(\"%%s: optional argument \\\"%%s\\\" given twice\\n\"),\n";
483         pr "               cmd, this_arg);\n";
484         pr "      return -1;\n";
485         pr "    }\n";
486         pr "    optargs_s.bitmask |= this_mask;\n";
487         pr "  }\n";
488         pr "\n";
489       );
490
491       (* Call C API function. *)
492       if optargs = [] then
493         pr "  r = guestfs_%s " name
494       else
495         pr "  r = guestfs_%s_argv " name;
496       generate_c_call_args ~handle:"g" style;
497       pr ";\n";
498
499       List.iter (
500         function
501         | Device _ | String _
502         | OptString _ | Bool _
503         | Int _ | Int64 _
504         | BufferIn _ -> ()
505         | Pathname name | Dev_or_Path name | FileOut name
506         | Key name ->
507             pr "  free (%s);\n" name
508         | FileIn name ->
509             pr "  free_file_in (%s);\n" name
510         | StringList name | DeviceList name ->
511             pr "  free_strings (%s);\n" name
512         | Pointer _ -> assert false
513       ) args;
514
515       (* Any output flags? *)
516       let fish_output =
517         let flags = filter_map (
518           function FishOutput flag -> Some flag | _ -> None
519         ) flags in
520         match flags with
521         | [] -> None
522         | [f] -> Some f
523         | _ ->
524             failwithf "%s: more than one FishOutput flag is not allowed" name in
525
526       (* Check return value for errors and display command results. *)
527       (match ret with
528        | RErr -> pr "  return r;\n"
529        | RInt _ ->
530            pr "  if (r == -1) return -1;\n";
531            (match fish_output with
532             | None ->
533                 pr "  printf (\"%%d\\n\", r);\n";
534             | Some FishOutputOctal ->
535                 pr "  printf (\"%%s%%o\\n\", r != 0 ? \"0\" : \"\", r);\n";
536             | Some FishOutputHexadecimal ->
537                 pr "  printf (\"%%s%%x\\n\", r != 0 ? \"0x\" : \"\", r);\n");
538            pr "  return 0;\n"
539        | RInt64 _ ->
540            pr "  if (r == -1) return -1;\n";
541            (match fish_output with
542             | None ->
543                 pr "  printf (\"%%\" PRIi64 \"\\n\", r);\n";
544             | Some FishOutputOctal ->
545                 pr "  printf (\"%%s%%\" PRIo64 \"\\n\", r != 0 ? \"0\" : \"\", r);\n";
546             | Some FishOutputHexadecimal ->
547                 pr "  printf (\"%%s%%\" PRIx64 \"\\n\", r != 0 ? \"0x\" : \"\", r);\n");
548            pr "  return 0;\n"
549        | RBool _ ->
550            pr "  if (r == -1) return -1;\n";
551            pr "  if (r) printf (\"true\\n\"); else printf (\"false\\n\");\n";
552            pr "  return 0;\n"
553        | RConstString _ ->
554            pr "  if (r == NULL) return -1;\n";
555            pr "  printf (\"%%s\\n\", r);\n";
556            pr "  return 0;\n"
557        | RConstOptString _ ->
558            pr "  printf (\"%%s\\n\", r ? : \"(null)\");\n";
559            pr "  return 0;\n"
560        | RString _ ->
561            pr "  if (r == NULL) return -1;\n";
562            pr "  printf (\"%%s\\n\", r);\n";
563            pr "  free (r);\n";
564            pr "  return 0;\n"
565        | RStringList _ ->
566            pr "  if (r == NULL) return -1;\n";
567            pr "  print_strings (r);\n";
568            pr "  free_strings (r);\n";
569            pr "  return 0;\n"
570        | RStruct (_, typ) ->
571            pr "  if (r == NULL) return -1;\n";
572            pr "  print_%s (r);\n" typ;
573            pr "  guestfs_free_%s (r);\n" typ;
574            pr "  return 0;\n"
575        | RStructList (_, typ) ->
576            pr "  if (r == NULL) return -1;\n";
577            pr "  print_%s_list (r);\n" typ;
578            pr "  guestfs_free_%s_list (r);\n" typ;
579            pr "  return 0;\n"
580        | RHashtable _ ->
581            pr "  if (r == NULL) return -1;\n";
582            pr "  print_table (r);\n";
583            pr "  free_strings (r);\n";
584            pr "  return 0;\n"
585        | RBufferOut _ ->
586            pr "  if (r == NULL) return -1;\n";
587            pr "  if (full_write (1, r, size) != size) {\n";
588            pr "    perror (\"write\");\n";
589            pr "    free (r);\n";
590            pr "    return -1;\n";
591            pr "  }\n";
592            pr "  free (r);\n";
593            pr "  return 0;\n"
594       );
595       pr "}\n";
596       pr "\n"
597   ) all_functions;
598
599   (* run_action function *)
600   pr "int\n";
601   pr "run_action (const char *cmd, size_t argc, char *argv[])\n";
602   pr "{\n";
603   pr "  const struct command_table *ct;\n";
604   pr "\n";
605   pr "  ct = lookup_fish_command (cmd, strlen (cmd));\n";
606   pr "  if (ct)\n";
607   pr "    return ct->entry->run (cmd, argc, argv);\n";
608   pr "  else {\n";
609   pr "    fprintf (stderr, _(\"%%s: unknown command\\n\"), cmd);\n";
610   pr "    if (command_num == 1)\n";
611   pr "      extended_help_message ();\n";
612   pr "    return -1;\n";
613   pr "  }\n";
614   pr "}\n"
615
616 and generate_fish_cmds_h () =
617   generate_header CStyle GPLv2plus;
618
619   pr "#ifndef FISH_CMDS_H\n";
620   pr "#define FISH_CMDS_H\n";
621   pr "\n";
622
623   List.iter (
624     fun (shortname, _, _, _, _, _, _) ->
625       pr "extern int run_%s (const char *cmd, size_t argc, char *argv[]);\n"
626         shortname
627   ) fish_commands;
628
629   pr "\n";
630   pr "#endif /* FISH_CMDS_H */\n"
631
632 (* gperf code to do fast lookups of commands. *)
633 and generate_fish_cmds_gperf () =
634   generate_header CStyle GPLv2plus;
635
636   let all_functions_sorted =
637     List.filter (
638       fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
639     ) all_functions_sorted in
640
641   let all_functions_and_fish_commands_sorted =
642     List.sort action_compare (all_functions_sorted @ fish_commands) in
643
644   pr "\
645 %%language=ANSI-C
646 %%define lookup-function-name lookup_fish_command
647 %%ignore-case
648 %%readonly-tables
649 %%null-strings
650
651 %%{
652
653 #include <config.h>
654
655 #include <stdlib.h>
656 #include <string.h>
657
658 #include \"cmds_gperf.h\"
659
660 ";
661
662   List.iter (
663     fun (name, _, _, _, _, _, _) ->
664       pr "extern struct command_entry %s_cmd_entry;\n" name
665   ) all_functions_and_fish_commands_sorted;
666
667   pr "\
668 %%}
669
670 struct command_table;
671
672 %%%%
673 ";
674
675   List.iter (
676     fun (name, _, _, flags, _, _, _) ->
677       let name2 = replace_char name '_' '-' in
678       let aliases =
679         filter_map (function FishAlias n -> Some n | _ -> None) flags in
680
681       (* The basic command. *)
682       pr "%s, &%s_cmd_entry\n" name name;
683
684       (* Command with dashes instead of underscores. *)
685       if name <> name2 then
686         pr "%s, &%s_cmd_entry\n" name2 name;
687
688       (* Aliases for the command. *)
689       List.iter (
690         fun alias ->
691           pr "%s, &%s_cmd_entry\n" alias name;
692       ) aliases;
693   ) all_functions_and_fish_commands_sorted
694
695 (* Readline completion for guestfish. *)
696 and generate_fish_completion () =
697   generate_header CStyle GPLv2plus;
698
699   let all_functions =
700     List.filter (
701       fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
702     ) all_functions in
703
704   pr "\
705 #include <config.h>
706
707 #include <stdio.h>
708 #include <stdlib.h>
709 #include <string.h>
710
711 #ifdef HAVE_LIBREADLINE
712 #include <readline/readline.h>
713 #endif
714
715 #include \"fish.h\"
716
717 #ifdef HAVE_LIBREADLINE
718
719 static const char *const commands[] = {
720   BUILTIN_COMMANDS_FOR_COMPLETION,
721 ";
722
723   (* Get the commands, including the aliases.  They don't need to be
724    * sorted - the generator() function just does a dumb linear search.
725    *)
726   let commands =
727     List.map (
728       fun (name, _, _, flags, _, _, _) ->
729         let name2 = replace_char name '_' '-' in
730         let aliases =
731           filter_map (function FishAlias n -> Some n | _ -> None) flags in
732         name2 :: aliases
733     ) (all_functions @ fish_commands) in
734   let commands = List.flatten commands in
735
736   List.iter (pr "  \"%s\",\n") commands;
737
738   pr "  NULL
739 };
740
741 static char *
742 generator (const char *text, int state)
743 {
744   static size_t index, len;
745   const char *name;
746
747   if (!state) {
748     index = 0;
749     len = strlen (text);
750   }
751
752   rl_attempted_completion_over = 1;
753
754   while ((name = commands[index]) != NULL) {
755     index++;
756     if (STRCASEEQLEN (name, text, len))
757       return strdup (name);
758   }
759
760   return NULL;
761 }
762
763 #endif /* HAVE_LIBREADLINE */
764
765 #ifdef HAVE_RL_COMPLETION_MATCHES
766 #define RL_COMPLETION_MATCHES rl_completion_matches
767 #else
768 #ifdef HAVE_COMPLETION_MATCHES
769 #define RL_COMPLETION_MATCHES completion_matches
770 #endif
771 #endif /* else just fail if we don't have either symbol */
772
773 char **
774 do_completion (const char *text, int start, int end)
775 {
776   char **matches = NULL;
777
778 #ifdef HAVE_LIBREADLINE
779   rl_completion_append_character = ' ';
780
781   if (start == 0)
782     matches = RL_COMPLETION_MATCHES (text, generator);
783   else if (complete_dest_paths)
784     matches = RL_COMPLETION_MATCHES (text, complete_dest_paths_generator);
785 #endif
786
787   return matches;
788 }
789 ";
790
791 (* Generate the POD documentation for guestfish. *)
792 and generate_fish_actions_pod () =
793   let all_functions_sorted =
794     List.filter (
795       fun (_, _, _, flags, _, _, _) ->
796         not (List.mem NotInFish flags || List.mem NotInDocs flags)
797     ) all_functions_sorted in
798
799   let rex = Str.regexp "C<guestfs_\\([^>]+\\)>" in
800
801   List.iter (
802     fun (name, (_, args, optargs), _, flags, _, _, longdesc) ->
803       let longdesc =
804         Str.global_substitute rex (
805           fun s ->
806             let sub =
807               try Str.matched_group 1 s
808               with Not_found ->
809                 failwithf "error substituting C<guestfs_...> in longdesc of function %s" name in
810             "L</" ^ replace_char sub '_' '-' ^ ">"
811         ) longdesc in
812       let name = replace_char name '_' '-' in
813       let aliases =
814         filter_map (function FishAlias n -> Some n | _ -> None) flags in
815
816       List.iter (
817         fun name ->
818           pr "=head2 %s\n\n" name
819       ) (name :: aliases);
820       pr " %s" name;
821       List.iter (
822         function
823         | Pathname n | Device n | Dev_or_Path n | String n ->
824             pr " %s" n
825         | OptString n -> pr " %s" n
826         | StringList n | DeviceList n -> pr " '%s ...'" n
827         | Bool _ -> pr " true|false"
828         | Int n -> pr " %s" n
829         | Int64 n -> pr " %s" n
830         | FileIn n | FileOut n -> pr " (%s|-)" n
831         | BufferIn n -> pr " %s" n
832         | Key _ -> () (* keys are entered at a prompt *)
833         | Pointer _ -> assert false
834       ) args;
835       List.iter (
836         function
837         | Bool n | Int n | Int64 n | String n -> pr " [%s:..]" n
838         | _ -> assert false
839       ) optargs;
840       pr "\n";
841       pr "\n";
842       pr "%s\n\n" longdesc;
843
844       if List.exists (function FileIn _ | FileOut _ -> true
845                       | _ -> false) args then
846         pr "Use C<-> instead of a filename to read/write from stdin/stdout.\n\n";
847
848       if List.exists (function Key _ -> true | _ -> false) args then
849         pr "This command has one or more key or passphrase parameters.
850 Guestfish will prompt for these separately.\n\n";
851
852       if optargs <> [] then
853         pr "This command has one or more optional arguments.  See L</OPTIONAL ARGUMENTS>.\n\n";
854
855       if List.mem ProtocolLimitWarning flags then
856         pr "%s\n\n" protocol_limit_warning;
857
858       match deprecation_notice flags with
859       | None -> ()
860       | Some txt -> pr "%s\n\n" txt
861   ) all_functions_sorted
862
863 (* Generate documentation for guestfish-only commands. *)
864 and generate_fish_commands_pod () =
865   List.iter (
866     fun (name, _, _, flags, _, _, longdesc) ->
867       let name = replace_char name '_' '-' in
868       let aliases =
869         filter_map (function FishAlias n -> Some n | _ -> None) flags in
870
871       List.iter (
872         fun name ->
873           pr "=head2 %s\n\n" name
874       ) (name :: aliases);
875       pr "%s\n\n" longdesc;
876   ) fish_commands
877
878 and generate_fish_prep_options_h () =
879   generate_header CStyle GPLv2plus;
880
881   pr "#ifndef PREPOPTS_H\n";
882   pr "\n";
883
884   pr "\
885 struct prep {
886   const char *name;             /* eg. \"fs\" */
887
888   size_t nr_params;             /* optional parameters */
889   struct prep_param *params;
890
891   const char *shortdesc;        /* short description */
892   const char *longdesc;         /* long description */
893
894                                 /* functions to implement it */
895   void (*prelaunch) (const char *filename, prep_data *);
896   void (*postlaunch) (const char *filename, prep_data *, const char *device);
897 };
898
899 struct prep_param {
900   const char *pname;            /* parameter name */
901   const char *pdefault;         /* parameter default */
902   const char *pdesc;            /* parameter description */
903 };
904
905 extern const struct prep preps[];
906 #define NR_PREPS %d
907
908 " (List.length prepopts);
909
910   List.iter (
911     fun (name, shortdesc, args, longdesc) ->
912       pr "\
913 extern void prep_prelaunch_%s (const char *filename, prep_data *data);
914 extern void prep_postlaunch_%s (const char *filename, prep_data *data, const char *device);
915
916 " name name;
917   ) prepopts;
918
919   pr "\n";
920   pr "#endif /* PREPOPTS_H */\n"
921
922 and generate_fish_prep_options_c () =
923   generate_header CStyle GPLv2plus;
924
925   pr "\
926 #include <stdio.h>
927
928 #include \"fish.h\"
929 #include \"prepopts.h\"
930
931 ";
932
933   List.iter (
934     fun (name, shortdesc, args, longdesc) ->
935       pr "static struct prep_param %s_args[] = {\n" name;
936       List.iter (
937         fun (n, default, desc) ->
938           pr "  { \"%s\", \"%s\", \"%s\" },\n" n default desc
939       ) args;
940       pr "};\n";
941       pr "\n";
942   ) prepopts;
943
944   pr "const struct prep preps[] = {\n";
945   List.iter (
946     fun (name, shortdesc, args, longdesc) ->
947       pr "  { \"%s\", %d, %s_args,
948     \"%s\",
949     \"%s\",
950     prep_prelaunch_%s, prep_postlaunch_%s },
951 "
952         name (List.length args) name
953         (c_quote shortdesc) (c_quote longdesc)
954         name name;
955   ) prepopts;
956   pr "};\n"