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