Source file scriptable.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
open Error_monad
type output_format = Rows of {separator : string; escape : [`No | `OCaml]}
let rows separator escape = Rows {separator; escape}
let tsv = rows "\t" `No
let csv = rows "," `OCaml
let clic_arg () =
let open Tezos_clic in
arg
~doc:"Make the output script-friendly. Possible values are 'TSV' and 'CSV'."
~long:"for-script"
~placeholder:"FORMAT"
(parameter (fun _ spec ->
let open Lwt_result_syntax in
match String.lowercase_ascii spec with
| "tsv" -> return tsv
| "csv" -> return csv
| other ->
failwith
"Cannot recognize format %S, please try 'TSV' or 'CSV'"
other))
let fprintf_lwt chan fmt =
let open Lwt_syntax in
Format.kasprintf
(fun s ->
protect (fun () ->
let* () = Lwt_io.write chan s in
return_ok_unit))
fmt
let output ?(channel = Lwt_io.stdout) how_option ~for_human ~for_script =
let open Lwt_result_syntax in
match how_option with
| None -> for_human ()
| Some (Rows {separator; escape}) ->
let open Format in
let* () =
List.iter_es
(fun row ->
fprintf_lwt
channel
"%a@."
(pp_print_list
~pp_sep:(fun fmt () -> pp_print_string fmt separator)
(fun fmt cell ->
match escape with
| `OCaml -> fprintf fmt "%S" cell
| `No -> pp_print_string fmt cell))
row)
(for_script ())
in
protect (fun () ->
let*! () = Lwt_io.flush channel in
return_unit)
let output_for_human how_option for_human =
output how_option ~for_human ~for_script:(fun () -> [])
let output_row ?channel how_option ~for_human ~for_script =
output ?channel how_option ~for_human ~for_script:(fun () -> [for_script ()])