package mgit

  1. Overview
  2. Docs

Source file mgit_cli.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
let error_msgf fmt = Fmt.kstr (fun msg -> Error (`Msg msg)) fmt
let msgf fmt = Fmt.kstr (fun msg -> `Msg msg) fmt
let ( let* ) = Result.bind
let src = Logs.Src.create "mgit.cli"

module Log = (val Logs.src_log src : Logs.LOG)
open Cmdliner

let output_options = "OUTPUT OPTIONS"

let verbosity =
  let env = Cmd.Env.info "MGIT_LOGS" in
  Logs_cli.level ~docs:output_options ~env ()

let renderer =
  let env = Cmd.Env.info "MGIT_FMT" in
  Fmt_cli.style_renderer ~docs:output_options ~env ()

let utf_8 =
  let doc = "Allow binaries to emit UTF-8 characters." in
  let env = Cmd.Env.info "MGIT_UTF_8" in
  Arg.(value & opt bool true & info [ "with-utf-8" ] ~doc ~env)

let reporter ppf =
  let report src level ~over k msgf =
    let k _ = over (); k () in
    let with_metadata header _tags k ppf fmt =
      Fmt.kpf k ppf
        ("[%a]%a[%a]: " ^^ fmt ^^ "\n%!")
        Fmt.(styled `Cyan int)
        (Stdlib.Domain.self () :> int)
        Logs_fmt.pp_header (level, header)
        Fmt.(styled `Magenta string)
        (Logs.Src.name src)
    in
    msgf @@ fun ?header ?tags fmt -> with_metadata header tags k ppf fmt
  in
  { Logs.report }

let setup_logs utf_8 style_renderer level =
  Fmt_tty.setup_std_outputs ~utf_8 ?style_renderer ();
  Logs.set_level level;
  Logs.set_reporter (reporter Fmt.stderr);
  Option.is_none level

let setup_logs = Term.(const setup_logs $ utf_8 $ renderer $ verbosity)

let bytes_of_string s =
  let s = String.trim s in
  let len = String.length s in
  let rec find_non_digit i =
    if i >= len then i
    else if s.[i] >= '0' && s.[i] <= '9' then find_non_digit (i + 1)
    else i
  in
  let idx = find_non_digit 0 in
  let number_str = String.sub s 0 idx |> String.trim in
  let unit_str = String.sub s idx (len - idx) |> String.trim in
  let ( let* ) = Option.bind in
  let* number = int_of_string_opt number_str in
  let* multiplier =
    match String.lowercase_ascii unit_str with
    | "" | "b" -> Some 1
    | "kib" -> Some 1024
    | "mib" -> Some (1024 * 1024)
    | "gib" -> Some (1024 * 1024 * 1024)
    | "tib" -> Some (1024 * 1024 * 1024 * 1024)
    | _ -> None
  in
  Some (number * multiplier)

let sizes = [| "B"; "KiB"; "MiB"; "GiB"; "TiB" |]

let bytes_to_size = function
  | 0 -> "0b"
  | n ->
      let n = float_of_int n in
      let i = Float.floor (Float.log n /. Float.log 1024.) in
      let r = n /. Float.pow 1024. i in
      Fmt.str "%.0f%s" r sizes.(int_of_float i)

let size =
  let parser str =
    match bytes_of_string str with
    | Some n -> Ok n
    | None -> error_msgf "Invalid size: %S" str
  in
  Arg.conv (parser, Fmt.(using bytes_to_size string))

let non_existing_file =
  let parser str =
    match Fpath.of_string str with
    | Ok v when Sys.file_exists str = false -> Ok v
    | Ok v -> error_msgf "Invalid path (it already exists): %a" Fpath.pp v
    | Error _ as err -> err
  in
  Arg.conv (parser, Fpath.pp)

let existing_file =
  let parser str =
    match Fpath.of_string str with
    | Ok v when Sys.file_exists str && Sys.is_regular_file str -> Ok v
    | Ok v -> error_msgf "%a is not a file and/or does not exists" Fpath.pp v
    | Error _ as err -> err
  in
  Arg.conv (parser, Fpath.pp)

let docs_hexdump = "HEX OUTPUT"

let colorscheme =
  let x = Array.make 256 `None in
  for i = 0 to 31 do
    x.(i) <- `Style (`Fg, `bit24 (0xaf, 0xd7, 0xff))
  done;
  for i = 48 to 57 do
    x.(i) <- `Style (`Fg, `bit24 (0xaf, 0xdf, 0x77))
  done;
  for i = 65 to 90 do
    x.(i) <- `Style (`Fg, `bit24 (0xff, 0xaf, 0x5f))
  done;
  for i = 97 to 122 do
    x.(i) <- `Style (`Fg, `bit24 (0xff, 0xaf, 0xd7))
  done;
  Hxd.colorscheme_of_array x

let cols =
  let doc = "Format $(i,COLS) octets per line. Default 16. Max 256." in
  let parser str =
    match int_of_string str with
    | n when n < 1 || n > 256 ->
        error_msgf "Invalid COLS value (must <= 256 && > 0): %d" n
    | n -> Ok n
    | exception _ -> error_msgf "Invalid COLS value: %S" str
  in
  let open Arg in
  let cols = conv (parser, Fmt.int) in
  value
  & opt (some cols) None
  & info [ "c"; "cols" ] ~doc ~docv:"COLS" ~docs:docs_hexdump

let groupsize =
  let doc =
    "Separate the output of every $(i,bytes) bytes (two hex characters) by a \
     whitespace. Specify -g 0 to supress grouping. $(i,bytes) defaults to 2."
  in
  let open Arg in
  value
  & opt (some int) None
  & info [ "g"; "groupsize" ] ~doc ~docv:"BYTES" ~docs:docs_hexdump

let len =
  let doc = "Stop after writing $(i,LEN) octets." in
  let open Arg in
  value
  & opt (some int) None
  & info [ "l"; "len" ] ~doc ~docv:"LEN" ~docs:docs_hexdump

let uppercase =
  let doc = "Use upper case hex letters. Default is lower case." in
  let open Arg in
  value & flag & info [ "u" ] ~doc ~docs:docs_hexdump

let setup_hxd cols groupsize len uppercase =
  Hxd.xxd ?cols ?groupsize ?long:len ~uppercase colorscheme

let setup_hxd = Term.(const setup_hxd $ cols $ groupsize $ len $ uppercase)
let docs_dns = "DOMAIN NAME SERVICE"

let timeout =
  let is_digit = function '0' .. '9' -> true | _ -> false in
  let parser str =
    let len =
      let len = ref 0 in
      while !len < String.length str && is_digit str.[!len] do
        incr len
      done;
      !len
    in
    let meter = String.sub str len (String.length str - len) in
    let value = String.sub str 0 len in
    match meter with
    | "ns" -> Ok (Int64.of_string value)
    | "us" -> Ok (Duration.of_us (int_of_string value))
    | "ms" -> Ok (Duration.of_ms (int_of_string value))
    | "sec" | "s" -> Ok (Duration.of_sec (int_of_string value))
    | "min" | "m" -> Ok (Duration.of_min (int_of_string value))
    | "hour" | "h" -> Ok (Duration.of_hour (int_of_string value))
    | _ -> error_msgf "Invalid time: %S" str
  in
  Arg.conv ~docv:"TIME" (parser, Duration.pp)

let aaaa_timeout =
  let doc = "The timeout applied to the IPv6 resolution." in
  let open Arg in
  value
  & opt (some timeout) None
  & info [ "aaaa-timeout" ] ~doc ~docv:"TIME" ~docs:docs_dns

let connect_delay =
  let doc =
    "Time to repeat another connection attempt if the others don't respond."
  in
  let open Arg in
  value
  & opt (some timeout) None
  & info [ "connect-delay" ] ~doc ~docv:"TIME" ~docs:docs_dns

let connect_timeout =
  let doc = "The timeout applied to $(b,connect())." in
  let open Arg in
  value
  & opt (some timeout) None
  & info [ "connect-timeout" ] ~doc ~docv:"TIME" ~docs:docs_dns

let resolve_timeout =
  let doc = "The timeout applied to the domain-name resolution." in
  let open Arg in
  value
  & opt (some timeout) None
  & info [ "resolve-timeout" ] ~doc ~docv:"TIME" ~docs:docs_dns

let resolve_retries =
  let doc = "The number $(i,N) of attempts to make a connection." in
  let open Arg in
  value
  & opt (some int) None
  & info [ "resolve-retries" ] ~doc ~docv:"N" ~docs:docs_dns

type happy_eyeballs = {
    aaaa_timeout: int64 option
  ; connect_delay: int64 option
  ; connect_timeout: int64 option
  ; resolve_timeout: int64 option
  ; resolve_retries: int option
}

let setup_happy_eyeballs aaaa_timeout connect_delay connect_timeout
    resolve_timeout resolve_retries = function
  | false ->
      Some
        {
          aaaa_timeout
        ; connect_delay
        ; connect_timeout
        ; resolve_timeout
        ; resolve_retries
        }
  | _ -> None

let without_happy_eyeballs =
  let doc = "Don't use the happy-eyeballs algorithm (RFC8305)." in
  let open Arg in
  value & flag & info [ "without-happy-eyeballs" ] ~doc ~docs:docs_dns

let setup_happy_eyeballs =
  let open Term in
  const setup_happy_eyeballs
  $ aaaa_timeout
  $ connect_delay
  $ connect_timeout
  $ resolve_timeout
  $ resolve_retries
  $ without_happy_eyeballs

let ipaddr_with_port_of_string ~default str =
  match Ipaddr.with_port_of_string ~default str with
  | Ok _ as value -> value
  | Error _ as err -> begin
      let host, port =
        match String.split_on_char ':' str with
        | [ host; port ] -> (host, int_of_string_opt port)
        | _ -> (str, Some default)
      in
      match (port, Unix.gethostbyname host) with
      | Some port, { Unix.h_addr_list; _ } when Array.length h_addr_list > 0 ->
          Ok (Ipaddr_unix.of_inet_addr h_addr_list.(0), port)
      | _ | (exception Not_found) -> err
    end

let nameserver_of_string str =
  let ( let* ) = Result.bind in
  match String.split_on_char ':' str with
  | "tls" :: rest -> (
      let str = String.concat ":" rest in
      match String.split_on_char '!' str with
      | [ nameserver ] ->
          let* ipaddr, port =
            ipaddr_with_port_of_string ~default:853 nameserver
          in
          let* authenticator = Ca_certs.authenticator () in
          let* tls = Tls.Config.client ~authenticator () in
          Ok (`Tcp, `Tls (tls, ipaddr, port))
      | nameserver :: authenticator ->
          let* ipaddr, port =
            ipaddr_with_port_of_string ~default:853 nameserver
          in
          let authenticator = String.concat "!" authenticator in
          let* authenticator = X509.Authenticator.of_string authenticator in
          let time () = Some (Ptime.v (Ptime_clock.now_d_ps ())) in
          let authenticator = authenticator time in
          let* tls = Tls.Config.client ~authenticator () in
          Ok (`Tcp, `Tls (tls, ipaddr, port))
      | [] -> assert false)
  | "tcp" :: nameserver ->
      let str = String.concat ":" nameserver in
      let* ipaddr, port = ipaddr_with_port_of_string ~default:53 str in
      Ok (`Tcp, `Plaintext (ipaddr, port))
  | "udp" :: nameserver | nameserver ->
      let str = String.concat ":" nameserver in
      let* ipaddr, port = ipaddr_with_port_of_string ~default:53 str in
      Ok (`Udp, `Plaintext (ipaddr, port))

type nameserver =
  [ `Plaintext of Ipaddr.t * int | `Tls of Tls.Config.client * Ipaddr.t * int ]

let nameserver =
  let parser = nameserver_of_string in
  let pp ppf = function
    | _, `Tls (_, ipaddr, 853) ->
        Fmt.pf ppf "tls:%a!<authenticator>" Ipaddr.pp ipaddr
    | _, `Tls (_, ipaddr, port) ->
        Fmt.pf ppf "tls:%a:%d!<authenticator>" Ipaddr.pp ipaddr port
    | `Tcp, `Plaintext (ipaddr, 53) -> Fmt.pf ppf "tcp:%a" Ipaddr.pp ipaddr
    | `Udp, `Plaintext (ipaddr, 53) -> Fmt.pf ppf "%a" Ipaddr.pp ipaddr
    | `Tcp, `Plaintext (ipaddr, port) ->
        Fmt.pf ppf "tcp:%a:%d" Ipaddr.pp ipaddr port
    | `Udp, `Plaintext (ipaddr, port) ->
        Fmt.pf ppf "%a:%d" Ipaddr.pp ipaddr port
  in
  Arg.conv (parser, pp) ~docv:"NAMESERVER"

let nameservers =
  let doc = "The $(i,NAMESERVER) used to resolve domain-names." in
  let google_com = (`Udp, `Plaintext (Ipaddr.of_string_exn "8.8.8.8", 53)) in
  let open Arg in
  value
  & opt_all nameserver [ google_com ]
  & info [ "n"; "nameserver" ] ~doc ~docv:"NAMESERVER" ~docs:docs_dns

let setup_nameservers nameservers =
  let tcp, udp =
    List.partition_map
      (function `Udp, v -> Either.Right v | `Tcp, v -> Either.Left v)
      nameservers
  in
  match (tcp, udp) with
  | [], [] -> `Ok None
  | [], nameservers -> `Ok (Some (`Udp, nameservers))
  | nameservers, [] -> `Ok (Some (`Tcp, nameservers))
  | _ -> `Error (true, "Impossible to use TCP & UDP protocols for nameservers")

let setup_nameservers = Term.(ret (const setup_nameservers $ nameservers))

module Block = Mgit_unix.Block
module Flow = Mgit_unix.Flow
module Git = Mgit_unix

let ssh =
  let doc = "The $(b,ssh) executable we use for SSH transports." in
  Cmd.Env.info "MGIT_SSH" ~doc

let setup_context happy_eyeballs nameservers =
  let ssh = Sys.getenv_opt "MGIT_SSH" in
  match (happy_eyeballs, nameservers) with
  | None, None -> Flow.ctx ?ssh ()
  | Some cfg, _ ->
      let happy_eyeballs =
        Happy_eyeballs.create ?aaaa_timeout:cfg.aaaa_timeout
          ?connect_delay:cfg.connect_delay ?connect_timeout:cfg.connect_timeout
          ?resolve_timeout:cfg.resolve_timeout
          ?resolve_retries:cfg.resolve_retries
          (Mtime_clock.elapsed_ns ())
      in
      Flow.ctx ~happy_eyeballs ?ssh ()
  | None, Some _ -> assert false

let setup_context =
  let open Term in
  const setup_context $ setup_happy_eyeballs $ setup_nameservers

let date =
  let doc = "The $(b,epoch) time used for commits." in
  Cmd.Env.info "MGIT_DATE" ~doc

let now =
  match Sys.getenv_opt "MGIT_DATE" with
  | Some ts ->
      begin match int_of_string_opt ts with
      | Some ts when ts >= 0 -> Fun.const ts
      | Some _ | None ->
          Logs.warn (fun m ->
              m "The given MGIT_DATE is wrong (it must a non-negative number)");
          fun () -> int_of_float (Unix.time ())
      end
  | None -> fun () -> int_of_float (Unix.time ())

let setup_git ctx depth remote branch filename =
  let* branch =
    match (remote, branch) with
    | Some { Mgit_sync.Endpoint.branch= Some branch; _ }, None ->
        Ok (Some branch)
    | (Some { Mgit_sync.Endpoint.branch= None; _ } | None), branch -> Ok branch
    | Some { Mgit_sync.Endpoint.branch= Some a; _ }, Some b ->
        error_msgf
          "Impossible to choose a branch between the given endpoint (%s) and \
           the given branch (%s)"
          a b
  in
  Log.debug (fun m -> m "branch: %a" Fmt.(Dump.option string) branch);
  let remote =
    match remote with
    | Some remote ->
        Git.remote ctx (Mgit_sync.Endpoint.to_string remote)
        |> Result.get_ok
        |> Option.some
    | None -> None
  in
  let* blk = Block.load (Fpath.to_string filename) in
  Git.make ?branch ?depth ~now ?remote (Git.Blk blk)

let non_negative_int =
  let parser str =
    match int_of_string_opt str with
    | Some n when n >= 0 -> Ok n
    | Some _ -> error_msgf "A depth must be greater or equal to than 0"
    | None -> error_msgf "Invalid depth: %S" str
  in
  Arg.conv (parser, Fmt.int)

let depth =
  let doc = "The depth of the Git history." in
  let env = Cmd.Env.info "MGIT_DEPTH" in
  let open Arg in
  value
  & opt (some non_negative_int) (Some 1)
  & info [ "depth" ] ~doc ~env ~docv:"DEPTH"

let endpoint =
  let parser = Mgit_sync.Endpoint.of_string in
  let pp = Mgit_sync.Endpoint.pp in
  Arg.conv (parser, pp)

let remote =
  let doc = "The remote Git repository." in
  let env = Cmd.Env.info "MGIT_REMOTE" in
  let open Arg in
  value
  & opt (some endpoint) None
  & info [ "r"; "remote" ] ~doc ~env ~docv:"REMOTE"

let branch =
  let doc = "The branch of the Git repository." in
  let env = Cmd.Env.info "MGIT_BRANCH" in
  let open Arg in
  value
  & opt (some string) None
  & info [ "b"; "branch" ] ~doc ~env ~docv:"BRANCH"

let filename =
  let doc = "The block-device as a file to load." in
  let open Arg in
  required & pos 0 (some existing_file) None & info [] ~doc ~docv:"FILENAME"

let absolute_path =
  let parser str =
    match Fpath.of_string str with
    | Ok v when Fpath.is_abs v -> Ok str
    | Ok _ ->
        error_msgf
          "The given path must be absolute and represent a file (an edge)"
    | Error _ as err -> err
  in
  Arg.conv (parser, Fmt.string)

let path =
  let doc = "A path into the given Git repository." in
  let open Arg in
  required & pos 1 (some absolute_path) None & info [] ~doc ~docv:"PATH"

let absolute_path_for_entry =
  let parser str =
    match Fpath.of_string str with
    | Ok v when Fpath.is_abs v && Fpath.is_file_path v -> Ok str
    | Ok _ ->
        error_msgf
          "The given path must be absolute and represent a file (an edge)"
    | Error _ as err -> err
  in
  Arg.conv (parser, Fmt.string)

let entry =
  let doc = "The path of the entry into a Git repository." in
  let open Arg in
  required
  & pos 1 (some absolute_path_for_entry) None
  & info [] ~doc ~docv:"PATH"

let setup_git =
  let open Term in
  const setup_git
  $ setup_context
  $ depth
  $ remote
  $ branch
  $ filename
  |> map (Result.map_error (msgf "%a" Mgit.pp_error))
  |> term_result ~usage:false

let uid =
  let parser str = Mgit.uid_of_hex str in
  let pp ppf uid = Fmt.string ppf (Mgit.uid_to_hex uid) in
  Arg.conv (parser, pp)