]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/registry/helm_registry.ml
Changed mapping keys <-> environment variables, mixed case envvars are
[helm.git] / helm / ocaml / registry / helm_registry.ml
1 (* Copyright (C) 2004, HELM Team.
2  * 
3  * This file is part of HELM, an Hypertextual, Electronic
4  * Library of Mathematics, developed at the Computer Science
5  * Department, University of Bologna, Italy.
6  * 
7  * HELM is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  * 
12  * HELM is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with HELM; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://helm.cs.unibo.it/
24  *)
25
26 open Printf
27
28 let debug = false
29 let debug_print s =
30   if debug then prerr_endline ("Helm_registry debugging: " ^ s)
31
32   (** <helpers> *)
33
34 let list_uniq l =
35   let rec aux last_element = function
36     | [] -> []
37     | hd :: tl ->
38         (match last_element with
39         | Some elt when elt = hd -> aux last_element tl
40         | _ -> hd :: aux (Some hd) tl)
41   in
42   aux None l
43
44 let starts_with prefix =
45 (*
46   let rex = Str.regexp (Str.quote prefix) in
47   fun s -> Str.string_match rex s 0
48 *)
49   let prefix_len = String.length prefix in
50   fun s ->
51     try
52       String.sub s 0 prefix_len = prefix
53     with Invalid_argument _ -> false
54
55 let hashtbl_keys tbl = Hashtbl.fold (fun k _ acc -> k :: acc) tbl []
56 let hashtbl_pairs tbl = Hashtbl.fold (fun k v acc -> (k,v) :: acc) tbl []
57
58   (** </helpers> *)
59
60 exception Malformed_key of string
61 exception Key_not_found of string
62 exception Cyclic_definition of string
63 exception Type_error of string * string * string (* expected type, value, msg *)
64 exception Parse_error of string * int * int * string  (* file, line, col, msg *)
65 exception Invalid_value of (string * string) * string (* key, value, descr *)
66
67 type validator_id = int
68
69   (* root XML tag: used by save_to, ignored by load_from *)
70 let root_tag = "helm_registry"
71
72 let get_next_validator_id =
73   let next_id = ref 0 in
74   fun () ->
75     incr next_id;
76     !next_id
77
78 let magic_size = 127
79 let validators = Hashtbl.create magic_size
80 let registry = Hashtbl.create magic_size
81
82 let backup_registry () = Hashtbl.copy registry
83 let restore_registry backup =
84   Hashtbl.clear registry;
85   Hashtbl.iter (fun key value -> Hashtbl.replace registry key value) backup
86
87   (* as \\w but:
88    * - no sequences of '_' longer than 1 are permitted
89    *)
90 let valid_step_rex_raw = "[a-zA-Z0-9]+\\(_[a-z0A-Z-9]+\\)*"
91 let valid_key_rex_raw =
92   sprintf "%s\(\\.%s\)*" valid_step_rex_raw valid_step_rex_raw
93 let valid_key_rex = Str.regexp ("^" ^ valid_key_rex_raw ^ "$")
94 let interpolated_key_rex = Str.regexp ("\\$(" ^ valid_key_rex_raw ^ ")")
95 let dot_rex = Str.regexp "\\."
96 let spaces_rex = Str.regexp "[ \t\n\r]+"
97 let heading_spaces_rex = Str.regexp "^[ \t\n\r]+"
98
99 let split s =
100   (* trailing blanks are removed per default by split *)
101   Str.split spaces_rex (Str.global_replace heading_spaces_rex "" s)
102 let merge l = String.concat " " l
103
104   (* escapes for xml configuration file *)
105 let (escape, unescape) =
106   let (in_enc, out_enc) = (`Enc_utf8, `Enc_utf8) in
107   (Netencoding.Html.encode ~in_enc ~out_enc (),
108    Netencoding.Html.decode ~in_enc ~out_enc ~entity_base:`Xml ())
109
110 let key_is_valid key =
111   if not (Str.string_match valid_key_rex key 0) then
112     raise (Malformed_key key)
113
114 let value_is_valid ~key ~value =
115   List.iter
116     (fun (validator, descr) ->
117       if not (validator value) then
118         raise (Invalid_value ((key, value), descr)))
119     (Hashtbl.find_all validators key)
120
121 let set' registry ~key ~value =
122   debug_print (sprintf "Setting %s = %s" key value);
123   key_is_valid key;
124   value_is_valid ~key ~value;
125   Hashtbl.replace registry key value
126
127 let unset = Hashtbl.remove registry
128
129 let env_var_of_key = Str.global_replace dot_rex "__"
130
131 let get key =
132   let rec aux stack key =
133     key_is_valid key;
134     if List.mem key stack then begin
135       let msg = (String.concat " -> " (List.rev stack)) ^ " -> " ^ key in
136       raise (Cyclic_definition msg)
137     end;
138     let registry_value =  (* internal value *)
139       try
140         Some (Hashtbl.find registry key)
141       with Not_found -> None
142     in
143     let env_value = (* environment value *)
144       try
145         Some (Sys.getenv (env_var_of_key key))
146       with Not_found -> None
147     in
148     let value = (* resulting value *)
149       match (registry_value, env_value) with
150       | Some reg, Some env  -> env
151       | Some reg, None      -> reg
152       | None,     Some env  -> env
153       | None,     None      -> raise (Key_not_found key)
154     in
155     interpolate (key :: stack) value
156   and interpolate stack value =
157     Str.global_substitute interpolated_key_rex
158       (fun s ->
159         let matched = Str.matched_string s in
160           (* "$(var)" -> "var" *)
161         let key = String.sub matched 2 (String.length matched - 3) in
162         aux stack key)
163       value
164   in
165   aux [] key
166
167 let set = set' registry
168
169 let has key = Hashtbl.mem registry key
170
171 let mk_get_set type_name (from_string: string -> 'a) (to_string: 'a -> string) =
172   let getter key =
173     let value = get key in
174     try
175       from_string value
176     with exn ->
177       raise (Type_error (type_name, value, Printexc.to_string exn))
178   in
179   let setter ~key ~value = set ~key ~value:(to_string value) in
180   (getter, setter)
181
182 let (get_string, set_string) = (get, set)
183 let (get_int, set_int) = mk_get_set "int" int_of_string string_of_int
184 let (get_float, set_float) = mk_get_set "float" float_of_string string_of_float
185 let (get_bool, set_bool) = mk_get_set "bool" bool_of_string string_of_bool
186 let (get_string_list, set_string_list) = mk_get_set "string list" split merge
187
188 let get_opt getter key =
189   try
190     Some (getter key)
191   with Key_not_found _ -> None
192 let set_opt setter ~key ~value =
193   match value with
194   | None -> unset key
195   | Some value -> setter ~key ~value
196 let get_opt_default getter default key =
197   match get_opt getter key with
198   | None -> default
199   | Some v -> v
200
201 let add_validator ~key ~validator ~descr =
202   let id = get_next_validator_id () in
203   Hashtbl.add validators key (validator, descr);
204   id
205
206 open Pxp_dtd
207 open Pxp_document
208 open Pxp_types
209 open Pxp_yacc
210
211 let save_to =
212   let dtd = new dtd PxpHelmConf.pxp_config.warner `Enc_utf8 in
213   let dot_RE = Str.regexp "\\." in
214   let create_key_node key value = (* create a <key name="foo">value</key> *)
215     let element =
216       create_element_node ~valcheck:false PxpHelmConf.pxp_spec dtd
217         "key" ["name", key]
218     in
219     let data = create_data_node PxpHelmConf.pxp_spec dtd value in
220     element#append_node data;
221     element
222   in
223   let is_section name =
224     fun node ->
225       match node#node_type with
226       | T_element "section" ->
227           (try node#attribute "name" = Value name with Not_found -> false)
228       | _ -> false
229   in
230   let add_key_node root sections key value =
231     let rec aux node = function
232       | [] ->
233           let key_node = create_key_node key value in
234           node#append_node key_node
235       | section :: tl ->
236           let next_node =
237             try
238               find ~deeply:false (is_section section) node
239             with Not_found ->
240               let section_node =
241                 create_element_node ~valcheck:false PxpHelmConf.pxp_spec dtd
242                   "section" ["name", section]
243               in
244               node#append_node section_node;
245               section_node
246           in
247           aux next_node tl
248     in
249     aux root sections
250   in
251   fun fname ->
252     let xml_root =
253       create_element_node ~valcheck:false PxpHelmConf.pxp_spec dtd "helm_registry" []
254     in
255     Hashtbl.iter
256       (fun key value ->
257         let sections, key =
258           let hd, tl =
259             match List.rev (Str.split dot_RE key) with
260             | hd :: tl -> hd, tl
261             | _ -> assert false
262           in
263           List.rev tl, hd
264         in
265         add_key_node xml_root sections key value)
266       registry;
267       let outchan = (* let's write xml output to fname *)
268         if Unix.system "xmllint --version &> /dev/null" = Unix.WEXITED 0 then
269           (* xmllint available, use it! *)
270           Unix.open_process_out (sprintf
271             "xmllint --format --encode utf8 -o '%s' -" fname)
272         else
273           (* xmllint not available, write pxp ugly output directly to fname *)
274           open_out fname
275       in
276       xml_root#write (`Out_channel outchan) `Enc_utf8;
277       close_out outchan
278
279 let load_from_absolute =
280   let config = PxpHelmConf.pxp_config in
281   let entry = `Entry_document [ `Extend_dtd_fully; `Parse_xml_decl ] in
282   let fold_key key_stack key =
283     match key_stack with
284     | [] -> key
285     | _ -> String.concat "." key_stack ^ "." ^ key
286   in
287   fun fname ->
288     debug_print ("Loading configuration from " ^ fname);
289     let document =
290       parse_wfdocument_entity config (from_file fname) PxpHelmConf.pxp_spec
291     in
292     let rec aux key_stack node =
293       node#iter_nodes (fun n ->
294         try
295           (match n#node_type with
296           | T_element "section" ->
297               let section = n#required_string_attribute "name" in
298               aux (key_stack @ [section]) n
299           | T_element "key" ->
300               let key = n#required_string_attribute "name" in
301               let value = n#data in
302               set ~key:(fold_key key_stack key) ~value
303           | _ -> ())
304         with exn ->
305           let (fname, line, pos) = n#position in
306           raise (Parse_error (fname, line, pos,
307             "Uncaught exception: " ^ Printexc.to_string exn)))
308     in
309     let backup = backup_registry () in
310     Hashtbl.clear registry;
311     try
312       aux [] document#root
313     with exn ->
314       restore_registry backup;
315       raise exn
316
317 let load_from ?path fname =
318   if Filename.is_relative fname then begin
319     let no_file_found = ref true in
320     let path =
321       match path with
322       | Some path -> path (* path given as argument *)
323       | None -> [ Sys.getcwd () ] (* no path given, try with cwd *)
324     in
325     List.iter
326       (fun dir ->
327         let conffile = dir ^ "/" ^ fname in
328         if Sys.file_exists conffile then begin
329           no_file_found := false;
330           load_from_absolute conffile
331         end)
332        path;
333     if !no_file_found then
334       failwith (sprintf
335         "Helm_registry.init: no configuration file named %s in [ %s ]"
336         fname (String.concat "; " path))
337   end else
338     load_from_absolute fname
339
340 let fold ?prefix f init =
341   match prefix with
342   | None -> Hashtbl.fold (fun k v acc -> f acc k v) registry init
343   | Some s ->
344       let key_matches = starts_with (s ^ ".") in
345       let rec fold_filter acc = function
346         | [] -> acc
347         | (k,v) :: tl when key_matches k -> fold_filter (f acc k v) tl
348         | _ :: tl -> fold_filter acc tl
349       in
350       fold_filter init (hashtbl_pairs registry)
351
352 let iter ?prefix f = fold ?prefix (fun _ k v -> f k v) ()
353 let to_list ?prefix () = fold ?prefix (fun acc k v -> (k, v) :: acc) []
354
355 let ls prefix =
356   let prefix = prefix ^ "." in
357   let prefix_len = String.length prefix in
358   let key_matches = starts_with prefix in
359   let matching_keys = (* collect matching keys' _postfixes_ *)
360     fold
361       (fun acc key _ ->
362         if key_matches key then
363           String.sub key prefix_len (String.length key - prefix_len) :: acc
364         else
365           acc)
366       []
367   in
368   let (sections, keys) =
369     List.fold_left
370       (fun (sections, keys) postfix ->
371         match Str.split dot_rex postfix with
372         | [key] -> (sections, key :: keys)
373         | hd_key :: _ ->  (* length > 1 => nested section found *)
374             (hd_key :: sections, keys)
375         | _ -> assert false)
376       ([], []) matching_keys
377   in
378   (list_uniq (List.sort Pervasives.compare sections), keys)
379
380   (* DEBUGGING ONLY *)
381
382 let dump () = Hashtbl.iter (fun k v -> printf "%s = %s\n" k v) registry
383