summaryrefslogtreecommitdiff
path: root/lib/config.ml
blob: 7e037ef0d8754b23f9d6791e92826871fd1378e9 (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
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
(* -*- mode: tuareg; -*- *)

open Toml

type t = {
  user : string;
  default_branch : string;
  git_project_root : string;
  commits_max_displayed : int;
}

let default =
  {
    user = Unix.getlogin ();
    default_branch = "master";
    git_project_root = Filename.concat (Sys.getenv "HOME") "git.test";
    commits_max_displayed = 10;
  }

let locate_config_file () =
  match List.find_map Sys.getenv_opt [ "OGIT_CONFIG"; "XDG_CONFIG_HOME" ] with
  | Some file -> file
  | None -> "/etc/ogit/config.toml"

let config_file = locate_config_file ()

let to_table t =
  let open Types in
  List.map
    (fun (k, v) -> (Min.key k, v))
    [
      ("user", TString t.user);
      ("default_branch", TString t.default_branch);
      ("git_project_root", TString t.git_project_root);
      ("commits_max_displayed", TInt t.commits_max_displayed);
    ]
  |> Min.of_key_values

let write_file ?(file = config_file) table =
  let oc = open_out file in
  Printer.string_of_table table |> Printf.fprintf oc "%s\n";
  close_out oc

let read_file ?(file = config_file) () =
  try
    match Toml.Parser.from_filename file with
    | `Error (e, l) ->
        Error (Printf.sprintf "%s: %s at line %d" l.source e l.line)
    | `Ok table ->
        let find_string key =
          match Types.Table.find_opt (Min.key key) table with
          | Some (TString s) -> Ok s
          | Some _ -> Error ("Expected string for key: " ^ key)
          | None -> Error ("Missing key: " ^ key)
        in
        let find_int key =
          match Types.Table.find_opt (Min.key key) table with
          | Some (TInt i) -> Ok i
          | Some _ -> Error ("Expected int for key: " ^ key)
          | None -> Error ("Missing key: " ^ key)
        in
        let ( let* ) = Result.bind in
        let* git_project_root = find_string "git_project_root" in
        let* user = find_string "user" in
        let* default_branch = find_string "default_branch" in
        let* commits_max_displayed = find_int "max_commits_displayed" in
        Ok { git_project_root; user; default_branch; commits_max_displayed }
  with _ ->
    prerr_endline "[config.ml] Falling back to default config.";
    Ok default

let config = match read_file () with Ok cfg -> cfg | Error _ -> default
Copyright 2019--2025 Marius PETER