dune/src/env.ml

82 lines
1.7 KiB
OCaml
Raw Normal View History

open Import
module Var = struct
type t = string
2018-03-12 03:47:56 +00:00
let compare =
if Sys.win32 then (
fun a b -> String.compare (String.lowercase a) (String.lowercase b)
) else (
String.compare
)
end
2018-03-10 14:15:02 +00:00
module Map = Map.Make(Var)
type t =
{ vars : string Map.t
; mutable unix : string array option
2018-03-10 14:15:02 +00:00
}
2018-03-12 03:43:43 +00:00
let make vars =
{ vars
; unix = None
2018-03-10 14:15:02 +00:00
}
let get t k = Map.find t.vars k
let to_unix t =
match t.unix with
| Some v -> v
| None ->
let res =
Map.foldi ~init:[] ~f:(fun k v acc ->
(sprintf "%s=%s" k v)::acc
) t.vars
2018-03-12 03:43:43 +00:00
|> Array.of_list in
t.unix <- Some res;
res
2018-03-12 03:43:43 +00:00
let of_unix arr =
Array.to_list arr
|> List.map ~f:(fun s ->
match String.lsplit2 s ~on:'=' with
| None ->
2018-03-12 11:22:54 +00:00
Sexp.code_error "Env.of_unix: entry without '=' found in the environ"
["var", Sexp.To_sexp.string s]
2018-03-12 03:43:43 +00:00
| Some (k, v) -> (k, v))
2018-03-12 11:22:54 +00:00
|> Map.of_list
|> function
| Ok x -> x
| Error (var, v1, v2) ->
Sexp.code_error "Env.of_unix: duplicated variable found in the environment"
[ "var" , Sexp.To_sexp.string var
; "value1", Sexp.To_sexp.string v1
; "value2", Sexp.To_sexp.string v2
]
2018-03-12 03:43:43 +00:00
2018-03-10 14:15:02 +00:00
let initial =
let i =
lazy (
2018-03-12 03:43:43 +00:00
make (Lazy.force Colors.setup_env_for_colors;
Unix.environment ()
|> of_unix)
2018-03-10 14:15:02 +00:00
) in
fun () -> Lazy.force i
2018-03-12 03:43:43 +00:00
let add t ~var ~value =
make (Map.add t.vars var value)
2018-03-12 03:43:43 +00:00
2018-03-10 14:15:02 +00:00
let extend t ~vars =
make (Map.union t.vars vars ~f:(fun _ _ v -> Some v))
2018-03-11 04:45:47 +00:00
2018-03-12 03:43:43 +00:00
let sexp_of_t t =
let open Sexp.To_sexp in
(list (pair string string)) (Map.to_list t.vars)
2018-03-12 03:43:43 +00:00
let diff x y =
Map.merge x.vars y.vars ~f:(fun _k vx vy ->
2018-03-12 03:43:43 +00:00
match vy with
| Some _ -> None
| None -> vx)
|> make