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