aboutsummaryrefslogtreecommitdiff
path: root/lib/helpers/helpers.ml
blob: 9d6fcb8041ac614e7a734426a6e553bc6ff62608 (plain)
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
module Toml = Toml
module Console = Console

let date_from_csv : string -> CalendarLib.Date.t option =
 fun value ->
  let open CalendarLib.Date in
  try Some (Scanf.sscanf value "%d/%d/%d" (fun d m y -> make y m d)) with
  | _ -> (
      (* If the date is a number, try from julian day *)
      match int_of_string_opt value with
      | None -> None
      | Some v -> Some (add (make 1899 12 30) (Period.day v)))

let fold_opt : ('a -> 'b -> 'a option) -> 'a -> 'b -> 'a =
 fun f acc b ->
  match f acc b with
  | None -> acc
  | Some v -> v

let try_opt exp =
  try Some (exp ()) with
  | _ -> None

let repr_date formatter date =
  Format.fprintf formatter "%02d/%02d/%d"
    (CalendarLib.Date.day_of_month date)
    CalendarLib.Date.(int_of_month @@ month date)
    (CalendarLib.Date.year date)

let s_repr_date date =
  Format.sprintf "%02d/%02d/%d"
    (CalendarLib.Date.day_of_month date)
    CalendarLib.Date.(int_of_month @@ month date)
    (CalendarLib.Date.year date)

let repr_opt f channel = function
  | None -> ()
  | Some v -> f channel v

let str_format f =
  let buffer = Buffer.create 16 in
  let formatter = Format.formatter_of_buffer buffer in
  f formatter;
  Format.pp_print_flush formatter ();
  Buffer.contents buffer