Source file ModuleFs.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
module FpathMap = Map.Make (Fpath)

(* Could also use first-class modules but a bag (record of functions) is simpler. *)
type t = { read_file : Fpath.t -> (string option, [ `Msg of string ]) result }

let create_ondisk () =
  {
    read_file =
      (fun p ->
        (* TODO: Catch exceptions, whatever they are. *)
        let ic = open_in_bin (Fpath.to_string p) in
        let content =
          Fun.protect
            ~finally:(fun () -> close_in_noerr ic)
            (fun () -> In_channel.input_all ic)
        in
        Ok (Some content));
  }

let create_inmemory () =
  let t = FpathMap.empty in
  {
    read_file =
      (fun p ->
        match FpathMap.find_opt p t with
        | None -> Ok None
        | Some content -> Ok (Some content));
  }