fish: In generated code, put function names on a new line.
[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) printf (\"%%s%s: %%g %%%%\\n\", indent, %s->%s);\n"
271               typ name name typ name;
272             pr "  else printf (\"%%s%s: \\n\", indent);\n" name
273       ) cols;
274       pr "}\n";
275       pr "\n";
276   ) structs;
277
278   (* Emit a print_TYPE_list function definition only if that function is used. *)
279   List.iter (
280     function
281     | typ, (RStructListOnly | RStructAndList) ->
282         (* generate the function for typ *)
283         emit_print_list_function typ
284     | typ, _ -> () (* empty *)
285   ) (rstructs_used_by all_functions);
286
287   (* Emit a print_TYPE function definition only if that function is used. *)
288   List.iter (
289     function
290     | typ, (RStructOnly | RStructAndList) ->
291         pr "static void\n";
292         pr "print_%s (struct guestfs_%s *%s)\n" typ typ typ;
293         pr "{\n";
294         pr "  print_%s_indent (%s, \"\");\n" typ typ;
295         pr "}\n";
296         pr "\n";
297     | typ, _ -> () (* empty *)
298   ) (rstructs_used_by all_functions);
299
300   (* run_<action> actions *)
301   List.iter (
302     fun (name, (ret, args, optargs as style), _, flags, _, _, _) ->
303       pr "static int\n";
304       pr "run_%s (const char *cmd, size_t argc, char *argv[])\n" name;
305       pr "{\n";
306       (match ret with
307        | RErr
308        | RInt _
309        | RBool _ -> pr "  int r;\n"
310        | RInt64 _ -> pr "  int64_t r;\n"
311        | RConstString _ | RConstOptString _ -> pr "  const char *r;\n"
312        | RString _ -> pr "  char *r;\n"
313        | RStringList _ | RHashtable _ -> pr "  char **r;\n"
314        | RStruct (_, typ) -> pr "  struct guestfs_%s *r;\n" typ
315        | RStructList (_, typ) -> pr "  struct guestfs_%s_list *r;\n" typ
316        | RBufferOut _ ->
317            pr "  char *r;\n";
318            pr "  size_t size;\n";
319       );
320       List.iter (
321         function
322         | Device n
323         | String n
324         | OptString n -> pr "  const char *%s;\n" n
325         | Pathname n
326         | Dev_or_Path n
327         | FileIn n
328         | FileOut n
329         | Key n -> pr "  char *%s;\n" n
330         | BufferIn n ->
331             pr "  const char *%s;\n" n;
332             pr "  size_t %s_size;\n" n
333         | StringList n | DeviceList n -> pr "  char **%s;\n" n
334         | Bool n -> pr "  int %s;\n" n
335         | Int n -> pr "  int %s;\n" n
336         | Int64 n -> pr "  int64_t %s;\n" n
337         | Pointer _ -> assert false
338       ) args;
339
340       if optargs <> [] then (
341         pr "  struct guestfs_%s_argv optargs_s = { .bitmask = 0 };\n" name;
342         pr "  struct guestfs_%s_argv *optargs = &optargs_s;\n" name
343       );
344
345       if args <> [] || optargs <> [] then
346         pr "  size_t i = 0;\n";
347
348       pr "\n";
349
350       (* Check and convert parameters. *)
351       let argc_minimum, argc_maximum =
352         let args_no_keys =
353           List.filter (function Key _ -> false | _ -> true) args in
354         let argc_minimum = List.length args_no_keys in
355         let argc_maximum = argc_minimum + List.length optargs in
356         argc_minimum, argc_maximum in
357
358       if argc_minimum = argc_maximum then (
359         pr "  if (argc != %d) {\n" argc_minimum;
360         pr "    fprintf (stderr, _(\"%%s should have %%d parameter(s)\\n\"), cmd, %d);\n"
361           argc_minimum;
362       ) else (
363         pr "  if (argc < %d || argc > %d) {\n" argc_minimum argc_maximum;
364         pr "    fprintf (stderr, _(\"%%s should have %%d-%%d parameter(s)\\n\"), cmd, %d, %d);\n"
365           argc_minimum argc_maximum;
366       );
367       pr "    fprintf (stderr, _(\"type 'help %%s' for help on %%s\\n\"), cmd, cmd);\n";
368       pr "    return -1;\n";
369       pr "  }\n";
370
371       let parse_integer expr fn fntyp rtyp range name =
372         pr "  {\n";
373         pr "    strtol_error xerr;\n";
374         pr "    %s r;\n" fntyp;
375         pr "\n";
376         pr "    xerr = %s (%s, NULL, 0, &r, xstrtol_suffixes);\n" fn expr;
377         pr "    if (xerr != LONGINT_OK) {\n";
378         pr "      fprintf (stderr,\n";
379         pr "               _(\"%%s: %%s: invalid integer parameter (%%s returned %%d)\\n\"),\n";
380         pr "               cmd, \"%s\", \"%s\", xerr);\n" name fn;
381         pr "      return -1;\n";
382         pr "    }\n";
383         (match range with
384          | None -> ()
385          | Some (min, max, comment) ->
386              pr "    /* %s */\n" comment;
387              pr "    if (r < %s || r > %s) {\n" min max;
388              pr "      fprintf (stderr, _(\"%%s: %%s: integer out of range\\n\"), cmd, \"%s\");\n"
389                name;
390              pr "      return -1;\n";
391              pr "    }\n";
392              pr "    /* The check above should ensure this assignment does not overflow. */\n";
393         );
394         pr "    %s = r;\n" name;
395         pr "  }\n";
396       in
397
398       List.iter (
399         function
400         | Device name
401         | String name ->
402             pr "  %s = argv[i++];\n" name
403         | Pathname name
404         | Dev_or_Path name ->
405             pr "  %s = win_prefix (argv[i++]); /* process \"win:\" prefix */\n" name;
406             pr "  if (%s == NULL) return -1;\n" name
407         | OptString name ->
408             pr "  %s = STRNEQ (argv[i], \"\") ? argv[i] : NULL;\n" name;
409             pr "  i++;\n"
410         | BufferIn name ->
411             pr "  %s = argv[i];\n" name;
412             pr "  %s_size = strlen (argv[i]);\n" name;
413             pr "  i++;\n"
414         | FileIn name ->
415             pr "  %s = file_in (argv[i++]);\n" name;
416             pr "  if (%s == NULL) return -1;\n" name
417         | FileOut name ->
418             pr "  %s = file_out (argv[i++]);\n" name;
419             pr "  if (%s == NULL) return -1;\n" name
420         | StringList name | DeviceList name ->
421             pr "  %s = parse_string_list (argv[i++]);\n" name;
422             pr "  if (%s == NULL) return -1;\n" name
423         | Key name ->
424             pr "  %s = read_key (\"%s\");\n" name name;
425             pr "  if (keys_from_stdin)\n";
426             pr "    input_lineno++;\n";
427             pr "  if (%s == NULL) return -1;\n" name
428         | Bool name ->
429             pr "  %s = is_true (argv[i++]) ? 1 : 0;\n" name
430         | Int name ->
431             let range =
432               let min = "(-(2LL<<30))"
433               and max = "((2LL<<30)-1)"
434               and comment =
435                 "The Int type in the generator is a signed 31 bit int." in
436               Some (min, max, comment) in
437             parse_integer "argv[i++]" "xstrtoll" "long long" "int" range name
438         | Int64 name ->
439             parse_integer "argv[i++]" "xstrtoll" "long long" "int64_t" None name
440         | Pointer _ -> assert false
441       ) args;
442
443       (* Optional arguments are prefixed with <argname>:<value> and
444        * may be missing, so we need to parse those until the end of
445        * the argument list.
446        *)
447       if optargs <> [] then (
448         let uc_name = String.uppercase name in
449         pr "\n";
450         pr "  for (; i < argc; ++i) {\n";
451         pr "    uint64_t this_mask;\n";
452         pr "    const char *this_arg;\n";
453         pr "\n";
454         pr "    ";
455         List.iter (
456           fun argt ->
457             let n = name_of_argt argt in
458             let uc_n = String.uppercase n in
459             let len = String.length n in
460             pr "if (STRPREFIX (argv[i], \"%s:\")) {\n" n;
461             (match argt with
462              | Bool n ->
463                  pr "      optargs_s.%s = is_true (&argv[i][%d]) ? 1 : 0;\n"
464                    n (len+1);
465              | Int n ->
466                  let range =
467                    let min = "(-(2LL<<30))"
468                    and max = "((2LL<<30)-1)"
469                    and comment =
470                      "The Int type in the generator is a signed 31 bit int." in
471                    Some (min, max, comment) in
472                  let expr = sprintf "&argv[i][%d]" (len+1) in
473                  parse_integer expr "xstrtoll" "long long" "int" range
474                    (sprintf "optargs_s.%s" n)
475              | Int64 n ->
476                  let expr = sprintf "&argv[i][%d]" (len+1) in
477                  parse_integer expr "xstrtoll" "long long" "int64_t" None
478                    (sprintf "optargs_s.%s" n)
479              | String n ->
480                  pr "      optargs_s.%s = &argv[i][%d];\n" n (len+1);
481              | _ -> assert false
482             );
483             pr "      this_mask = GUESTFS_%s_%s_BITMASK;\n" uc_name uc_n;
484             pr "      this_arg = \"%s\";\n" n;
485             pr "    }\n";
486             pr "    else ";
487         ) optargs;
488
489         pr "{\n";
490         pr "      fprintf (stderr, _(\"%%s: unknown optional argument \\\"%%s\\\"\\n\"),\n";
491         pr "               cmd, argv[i]);\n";
492         pr "      return -1;\n";
493         pr "    }\n";
494         pr "\n";
495         pr "    if (optargs_s.bitmask & this_mask) {\n";
496         pr "      fprintf (stderr, _(\"%%s: optional argument \\\"%%s\\\" given twice\\n\"),\n";
497         pr "               cmd, this_arg);\n";
498         pr "      return -1;\n";
499         pr "    }\n";
500         pr "    optargs_s.bitmask |= this_mask;\n";
501         pr "  }\n";
502         pr "\n";
503       );
504
505       (* Call C API function. *)
506       if optargs = [] then
507         pr "  r = guestfs_%s " name
508       else
509         pr "  r = guestfs_%s_argv " name;
510       generate_c_call_args ~handle:"g" style;
511       pr ";\n";
512
513       List.iter (
514         function
515         | Device _ | String _
516         | OptString _ | Bool _
517         | Int _ | Int64 _
518         | BufferIn _ -> ()
519         | Pathname name | Dev_or_Path name | FileOut name
520         | Key name ->
521             pr "  free (%s);\n" name
522         | FileIn name ->
523             pr "  free_file_in (%s);\n" name
524         | StringList name | DeviceList name ->
525             pr "  free_strings (%s);\n" name
526         | Pointer _ -> assert false
527       ) args;
528
529       (* Any output flags? *)
530       let fish_output =
531         let flags = filter_map (
532           function FishOutput flag -> Some flag | _ -> None
533         ) flags in
534         match flags with
535         | [] -> None
536         | [f] -> Some f
537         | _ ->
538             failwithf "%s: more than one FishOutput flag is not allowed" name in
539
540       (* Check return value for errors and display command results. *)
541       (match ret with
542        | RErr -> pr "  return r;\n"
543        | RInt _ ->
544            pr "  if (r == -1) return -1;\n";
545            (match fish_output with
546             | None ->
547                 pr "  printf (\"%%d\\n\", r);\n";
548             | Some FishOutputOctal ->
549                 pr "  printf (\"%%s%%o\\n\", r != 0 ? \"0\" : \"\", r);\n";
550             | Some FishOutputHexadecimal ->
551                 pr "  printf (\"%%s%%x\\n\", r != 0 ? \"0x\" : \"\", r);\n");
552            pr "  return 0;\n"
553        | RInt64 _ ->
554            pr "  if (r == -1) return -1;\n";
555            (match fish_output with
556             | None ->
557                 pr "  printf (\"%%\" PRIi64 \"\\n\", r);\n";
558             | Some FishOutputOctal ->
559                 pr "  printf (\"%%s%%\" PRIo64 \"\\n\", r != 0 ? \"0\" : \"\", r);\n";
560             | Some FishOutputHexadecimal ->
561                 pr "  printf (\"%%s%%\" PRIx64 \"\\n\", r != 0 ? \"0x\" : \"\", r);\n");
562            pr "  return 0;\n"
563        | RBool _ ->
564            pr "  if (r == -1) return -1;\n";
565            pr "  if (r) printf (\"true\\n\"); else printf (\"false\\n\");\n";
566            pr "  return 0;\n"
567        | RConstString _ ->
568            pr "  if (r == NULL) return -1;\n";
569            pr "  printf (\"%%s\\n\", r);\n";
570            pr "  return 0;\n"
571        | RConstOptString _ ->
572            pr "  printf (\"%%s\\n\", r ? : \"(null)\");\n";
573            pr "  return 0;\n"
574        | RString _ ->
575            pr "  if (r == NULL) return -1;\n";
576            pr "  printf (\"%%s\\n\", r);\n";
577            pr "  free (r);\n";
578            pr "  return 0;\n"
579        | RStringList _ ->
580            pr "  if (r == NULL) return -1;\n";
581            pr "  print_strings (r);\n";
582            pr "  free_strings (r);\n";
583            pr "  return 0;\n"
584        | RStruct (_, typ) ->
585            pr "  if (r == NULL) return -1;\n";
586            pr "  print_%s (r);\n" typ;
587            pr "  guestfs_free_%s (r);\n" typ;
588            pr "  return 0;\n"
589        | RStructList (_, typ) ->
590            pr "  if (r == NULL) return -1;\n";
591            pr "  print_%s_list (r);\n" typ;
592            pr "  guestfs_free_%s_list (r);\n" typ;
593            pr "  return 0;\n"
594        | RHashtable _ ->
595            pr "  if (r == NULL) return -1;\n";
596            pr "  print_table (r);\n";
597            pr "  free_strings (r);\n";
598            pr "  return 0;\n"
599        | RBufferOut _ ->
600            pr "  if (r == NULL) return -1;\n";
601            pr "  if (full_write (1, r, size) != size) {\n";
602            pr "    perror (\"write\");\n";
603            pr "    free (r);\n";
604            pr "    return -1;\n";
605            pr "  }\n";
606            pr "  free (r);\n";
607            pr "  return 0;\n"
608       );
609       pr "}\n";
610       pr "\n"
611   ) all_functions;
612
613   (* run_action function *)
614   pr "int\n";
615   pr "run_action (const char *cmd, size_t argc, char *argv[])\n";
616   pr "{\n";
617   pr "  const struct command_table *ct;\n";
618   pr "\n";
619   pr "  ct = lookup_fish_command (cmd, strlen (cmd));\n";
620   pr "  if (ct)\n";
621   pr "    return ct->entry->run (cmd, argc, argv);\n";
622   pr "  else {\n";
623   pr "    fprintf (stderr, _(\"%%s: unknown command\\n\"), cmd);\n";
624   pr "    if (command_num == 1)\n";
625   pr "      extended_help_message ();\n";
626   pr "    return -1;\n";
627   pr "  }\n";
628   pr "}\n"
629
630 and generate_fish_cmds_h () =
631   generate_header CStyle GPLv2plus;
632
633   pr "#ifndef FISH_CMDS_H\n";
634   pr "#define FISH_CMDS_H\n";
635   pr "\n";
636
637   List.iter (
638     fun (shortname, _, _, _, _, _, _) ->
639       pr "extern int run_%s (const char *cmd, size_t argc, char *argv[]);\n"
640         shortname
641   ) fish_commands;
642
643   pr "\n";
644   pr "#endif /* FISH_CMDS_H */\n"
645
646 (* gperf code to do fast lookups of commands. *)
647 and generate_fish_cmds_gperf () =
648   generate_header CStyle GPLv2plus;
649
650   let all_functions_sorted =
651     List.filter (
652       fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
653     ) all_functions_sorted in
654
655   let all_functions_and_fish_commands_sorted =
656     List.sort action_compare (all_functions_sorted @ fish_commands) in
657
658   pr "\
659 %%language=ANSI-C
660 %%define lookup-function-name lookup_fish_command
661 %%ignore-case
662 %%readonly-tables
663 %%null-strings
664
665 %%{
666
667 #include <config.h>
668
669 #include <stdlib.h>
670 #include <string.h>
671
672 #include \"cmds_gperf.h\"
673
674 ";
675
676   List.iter (
677     fun (name, _, _, _, _, _, _) ->
678       pr "extern struct command_entry %s_cmd_entry;\n" name
679   ) all_functions_and_fish_commands_sorted;
680
681   pr "\
682 %%}
683
684 struct command_table;
685
686 %%%%
687 ";
688
689   List.iter (
690     fun (name, _, _, flags, _, _, _) ->
691       let name2 = replace_char name '_' '-' in
692       let aliases =
693         filter_map (function FishAlias n -> Some n | _ -> None) flags in
694
695       (* The basic command. *)
696       pr "%s, &%s_cmd_entry\n" name name;
697
698       (* Command with dashes instead of underscores. *)
699       if name <> name2 then
700         pr "%s, &%s_cmd_entry\n" name2 name;
701
702       (* Aliases for the command. *)
703       List.iter (
704         fun alias ->
705           pr "%s, &%s_cmd_entry\n" alias name;
706       ) aliases;
707   ) all_functions_and_fish_commands_sorted
708
709 (* Readline completion for guestfish. *)
710 and generate_fish_completion () =
711   generate_header CStyle GPLv2plus;
712
713   let all_functions =
714     List.filter (
715       fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
716     ) all_functions in
717
718   pr "\
719 #include <config.h>
720
721 #include <stdio.h>
722 #include <stdlib.h>
723 #include <string.h>
724
725 #ifdef HAVE_LIBREADLINE
726 #include <readline/readline.h>
727 #endif
728
729 #include \"fish.h\"
730
731 #ifdef HAVE_LIBREADLINE
732
733 static const char *const commands[] = {
734   BUILTIN_COMMANDS_FOR_COMPLETION,
735 ";
736
737   (* Get the commands, including the aliases.  They don't need to be
738    * sorted - the generator() function just does a dumb linear search.
739    *)
740   let commands =
741     List.map (
742       fun (name, _, _, flags, _, _, _) ->
743         let name2 = replace_char name '_' '-' in
744         let aliases =
745           filter_map (function FishAlias n -> Some n | _ -> None) flags in
746         name2 :: aliases
747     ) (all_functions @ fish_commands) in
748   let commands = List.flatten commands in
749
750   List.iter (pr "  \"%s\",\n") commands;
751
752   pr "  NULL
753 };
754
755 static char *
756 generator (const char *text, int state)
757 {
758   static size_t index, len;
759   const char *name;
760
761   if (!state) {
762     index = 0;
763     len = strlen (text);
764   }
765
766   rl_attempted_completion_over = 1;
767
768   while ((name = commands[index]) != NULL) {
769     index++;
770     if (STRCASEEQLEN (name, text, len))
771       return strdup (name);
772   }
773
774   return NULL;
775 }
776
777 #endif /* HAVE_LIBREADLINE */
778
779 #ifdef HAVE_RL_COMPLETION_MATCHES
780 #define RL_COMPLETION_MATCHES rl_completion_matches
781 #else
782 #ifdef HAVE_COMPLETION_MATCHES
783 #define RL_COMPLETION_MATCHES completion_matches
784 #endif
785 #endif /* else just fail if we don't have either symbol */
786
787 char **
788 do_completion (const char *text, int start, int end)
789 {
790   char **matches = NULL;
791
792 #ifdef HAVE_LIBREADLINE
793   rl_completion_append_character = ' ';
794
795   if (start == 0)
796     matches = RL_COMPLETION_MATCHES (text, generator);
797   else if (complete_dest_paths)
798     matches = RL_COMPLETION_MATCHES (text, complete_dest_paths_generator);
799 #endif
800
801   return matches;
802 }
803 ";
804
805 (* Generate the POD documentation for guestfish. *)
806 and generate_fish_actions_pod () =
807   let all_functions_sorted =
808     List.filter (
809       fun (_, _, _, flags, _, _, _) ->
810         not (List.mem NotInFish flags || List.mem NotInDocs flags)
811     ) all_functions_sorted in
812
813   let rex = Str.regexp "C<guestfs_\\([^>]+\\)>" in
814
815   List.iter (
816     fun (name, (_, args, optargs), _, flags, _, _, longdesc) ->
817       let longdesc =
818         Str.global_substitute rex (
819           fun s ->
820             let sub =
821               try Str.matched_group 1 s
822               with Not_found ->
823                 failwithf "error substituting C<guestfs_...> in longdesc of function %s" name in
824             "L</" ^ replace_char sub '_' '-' ^ ">"
825         ) longdesc in
826       let name = replace_char name '_' '-' in
827       let aliases =
828         filter_map (function FishAlias n -> Some n | _ -> None) flags in
829
830       List.iter (
831         fun name ->
832           pr "=head2 %s\n\n" name
833       ) (name :: aliases);
834       pr " %s" name;
835       List.iter (
836         function
837         | Pathname n | Device n | Dev_or_Path n | String n ->
838             pr " %s" n
839         | OptString n -> pr " %s" n
840         | StringList n | DeviceList n -> pr " '%s ...'" n
841         | Bool _ -> pr " true|false"
842         | Int n -> pr " %s" n
843         | Int64 n -> pr " %s" n
844         | FileIn n | FileOut n -> pr " (%s|-)" n
845         | BufferIn n -> pr " %s" n
846         | Key _ -> () (* keys are entered at a prompt *)
847         | Pointer _ -> assert false
848       ) args;
849       List.iter (
850         function
851         | (Bool n | Int n | Int64 n | String n) as arg ->
852           pr " [%s:%s]" n (doc_opttype_of arg)
853         | _ -> assert false
854       ) optargs;
855       pr "\n";
856       pr "\n";
857       pr "%s\n\n" longdesc;
858
859       if List.exists (function FileIn _ | FileOut _ -> true
860                       | _ -> false) args then
861         pr "Use C<-> instead of a filename to read/write from stdin/stdout.\n\n";
862
863       if List.exists (function Key _ -> true | _ -> false) args then
864         pr "This command has one or more key or passphrase parameters.
865 Guestfish will prompt for these separately.\n\n";
866
867       if optargs <> [] then
868         pr "This command has one or more optional arguments.  See L</OPTIONAL ARGUMENTS>.\n\n";
869
870       if List.mem ProtocolLimitWarning flags then
871         pr "%s\n\n" protocol_limit_warning;
872
873       match deprecation_notice flags with
874       | None -> ()
875       | Some txt -> pr "%s\n\n" txt
876   ) all_functions_sorted
877
878 (* Generate documentation for guestfish-only commands. *)
879 and generate_fish_commands_pod () =
880   List.iter (
881     fun (name, _, _, flags, _, _, longdesc) ->
882       let name = replace_char name '_' '-' in
883       let aliases =
884         filter_map (function FishAlias n -> Some n | _ -> None) flags in
885
886       List.iter (
887         fun name ->
888           pr "=head2 %s\n\n" name
889       ) (name :: aliases);
890       pr "%s\n\n" longdesc;
891   ) fish_commands
892
893 and generate_fish_prep_options_h () =
894   generate_header CStyle GPLv2plus;
895
896   pr "#ifndef PREPOPTS_H\n";
897   pr "\n";
898
899   pr "\
900 struct prep {
901   const char *name;             /* eg. \"fs\" */
902
903   size_t nr_params;             /* optional parameters */
904   struct prep_param *params;
905
906   const char *shortdesc;        /* short description */
907   const char *longdesc;         /* long description */
908
909                                 /* functions to implement it */
910   void (*prelaunch) (const char *filename, prep_data *);
911   void (*postlaunch) (const char *filename, prep_data *, const char *device);
912 };
913
914 struct prep_param {
915   const char *pname;            /* parameter name */
916   const char *pdefault;         /* parameter default */
917   const char *pdesc;            /* parameter description */
918 };
919
920 extern const struct prep preps[];
921 #define NR_PREPS %d
922
923 " (List.length prepopts);
924
925   List.iter (
926     fun (name, shortdesc, args, longdesc) ->
927       pr "\
928 extern void prep_prelaunch_%s (const char *filename, prep_data *data);
929 extern void prep_postlaunch_%s (const char *filename, prep_data *data, const char *device);
930
931 " name name;
932   ) prepopts;
933
934   pr "\n";
935   pr "#endif /* PREPOPTS_H */\n"
936
937 and generate_fish_prep_options_c () =
938   generate_header CStyle GPLv2plus;
939
940   pr "\
941 #include <stdio.h>
942
943 #include \"fish.h\"
944 #include \"prepopts.h\"
945
946 ";
947
948   List.iter (
949     fun (name, shortdesc, args, longdesc) ->
950       pr "static struct prep_param %s_args[] = {\n" name;
951       List.iter (
952         fun (n, default, desc) ->
953           pr "  { \"%s\", \"%s\", \"%s\" },\n" n default desc
954       ) args;
955       pr "};\n";
956       pr "\n";
957   ) prepopts;
958
959   pr "const struct prep preps[] = {\n";
960   List.iter (
961     fun (name, shortdesc, args, longdesc) ->
962       pr "  { \"%s\", %d, %s_args,
963     \"%s\",
964     \"%s\",
965     prep_prelaunch_%s, prep_postlaunch_%s },
966 "
967         name (List.length args) name
968         (c_quote shortdesc) (c_quote longdesc)
969         name name;
970   ) prepopts;
971   pr "};\n"