]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/registry/helm_registry.ml
- more structured configuration file
[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 exception Malformed_key of string
33 exception Key_not_found of string
34 exception Cyclic_definition of string
35 exception Type_error of string * string * string (* expected type, value, msg *)
36 exception Parse_error of string * int * int * string  (* file, line, col, msg *)
37 exception Invalid_value of (string * string) * string (* key, value, descr *)
38
39 type validator_id = int
40
41   (* root XML tag: used by save_to, ignored by load_from *)
42 let root_tag = "helm_registry"
43
44 let get_next_validator_id =
45   let next_id = ref 0 in
46   fun () ->
47     incr next_id;
48     !next_id
49
50 let magic_size = 127
51 let validators = Hashtbl.create magic_size
52 let registry = Hashtbl.create magic_size
53
54 let backup_registry () = Hashtbl.copy registry
55 let restore_registry backup =
56   Hashtbl.clear registry;
57   Hashtbl.iter (fun key value -> Hashtbl.replace registry key value) backup
58
59   (* as \\w but:
60    * - no sequences of '_' longer than 1 are permitted
61    * - no uppercase letter are permitted
62    *)
63 let valid_step_rex_raw = "[a-z0-9]+\\(_[a-z0-9]+\\)*"
64 let valid_key_rex_raw =
65   sprintf "%s\(\\.%s\)*" valid_step_rex_raw valid_step_rex_raw
66 let valid_key_rex = Str.regexp ("^" ^ valid_key_rex_raw ^ "$")
67 let interpolated_key_rex = Str.regexp ("\\$(" ^ valid_key_rex_raw ^ ")")
68 let dot_rex = Str.regexp "\\."
69 let spaces_rex = Str.regexp "[ \t\n\r]+"
70 let heading_spaces_rex = Str.regexp "^[ \t\n\r]+"
71
72   (* escapes for xml configuration file *)
73 let (escape, unescape) =
74   let (in_enc, out_enc) = (`Enc_utf8, `Enc_utf8) in
75   (Netencoding.Html.encode ~in_enc ~out_enc (),
76    Netencoding.Html.decode ~in_enc ~out_enc ~entity_base:`Xml ())
77
78 let key_is_valid key =
79 (*   if not (Pcre.pmatch ~rex:valid_key_rex key) then *)
80   if not (Str.string_match valid_key_rex key 0) then
81     raise (Malformed_key key)
82
83 let value_is_valid ~key ~value =
84   List.iter
85     (fun (validator, descr) ->
86       if not (validator value) then
87         raise (Invalid_value ((key, value), descr)))
88     (Hashtbl.find_all validators key)
89
90 let set' registry ~key ~value =
91   debug_print (sprintf "Setting %s = %s" key value);
92   key_is_valid key;
93   value_is_valid ~key ~value;
94   Hashtbl.replace registry key value
95
96 let env_var_of_key key =
97 (*   Pcre.replace ~rex:dot_rex ~templ:"__" (String.uppercase key) *)
98   Str.global_replace dot_rex "__" (String.uppercase key)
99
100 let get key =
101   let rec aux stack key =
102     key_is_valid key;
103     if List.mem key stack then begin
104       let msg = (String.concat " -> " (List.rev stack)) ^ " -> " ^ key in
105       raise (Cyclic_definition msg)
106     end;
107     let registry_value =  (* internal value *)
108       try
109         Some (Hashtbl.find registry key)
110       with Not_found -> None
111     in
112     let env_value = (* environment value *)
113       try
114         Some (Sys.getenv (env_var_of_key key))
115       with Not_found -> None
116     in
117     let value = (* resulting value *)
118       match (registry_value, env_value) with
119       | Some reg, Some env  -> env
120       | Some reg, None      -> reg
121       | None,     Some env  -> env
122       | None,     None      -> raise (Key_not_found key)
123     in
124     interpolate (key :: stack) value
125   and interpolate stack value =
126     Str.global_substitute interpolated_key_rex
127       (fun s ->
128         let matched = Str.matched_string s in
129           (* "$(var)" -> "var" *)
130         let key = String.sub matched 2 (String.length matched - 3) in
131         aux stack key)
132       value
133   in
134   aux [] key
135
136 let set = set' registry
137
138 let string_list_of_string s =
139   (* trailing blanks are removed per default by split *)
140 (*   Pcre.split ~res:spaces_rex (Pcre.replace ~rex:heading_spaces_rex s) *)
141   Str.split spaces_rex (Str.global_replace heading_spaces_rex "" s)
142 let string_of_string_list l = String.concat " " l
143
144 let mk_get_set type_name (from_string: string -> 'a) (to_string: 'a -> string) =
145   let getter key =
146     let value = get key in
147     try
148       from_string value
149     with exn ->
150       raise (Type_error (type_name, value, Printexc.to_string exn))
151   in
152   let setter ~key ~value = set ~key ~value:(to_string value) in
153   (getter, setter)
154
155 let (get_string, set_string) = (get, set)
156 let (get_int, set_int) = mk_get_set "int" int_of_string string_of_int
157 let (get_float, set_float) = mk_get_set "float" float_of_string string_of_float
158 let (get_string_list, set_string_list) =
159   mk_get_set "string list" string_list_of_string string_of_string_list
160
161 (*
162 let save_to =
163   let dtd = new dtd default_config.warner `Enc_utf8 in
164   let rec create_key node sections key value =
165     match sections with
166     | [] -> create_element_node ~valcheck:false default_spec dtd
167 *)
168
169 let save_to fname =
170   debug_print ("Saving configuration to " ^ fname);
171   let oc = open_out fname in
172   output_string oc "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
173   output_string oc "<helm_registry>\n";
174   try
175     Hashtbl.iter
176       (fun key value ->
177         fprintf oc "  <value key=\"%s\">%s</value>\n" key (escape value))
178       registry;
179     output_string oc "</helm_registry>";
180     close_out oc
181   with e ->
182     close_out oc;
183     raise e
184
185 let add_validator ~key ~validator ~descr =
186   let id = get_next_validator_id () in
187   Hashtbl.add validators key (validator, descr);
188   id
189
190 open Pxp_document
191 open Pxp_types
192 open Pxp_yacc
193
194 let load_from_absolute =
195   let config = default_config in
196   let entry = `Entry_document [ `Extend_dtd_fully; `Parse_xml_decl ] in
197   let fold_key key_stack key = String.concat "." key_stack ^ "." ^ key in
198   fun fname ->
199     debug_print ("Loading configuration from " ^ fname);
200     let document =
201       parse_wfdocument_entity config (from_file fname) default_spec
202     in
203     let rec aux key_stack node =
204       node#iter_nodes (fun n ->
205         try
206           (match n#node_type with
207           | T_element "section" ->
208               let section = n#required_string_attribute "name" in
209               aux (key_stack @ [section]) n
210           | T_element "key" ->
211               let key = n#required_string_attribute "name" in
212               let value = n#data in
213               set ~key:(fold_key key_stack key) ~value
214           | _ -> ())
215         with exn ->
216           let (fname, line, pos) = n#position in
217           raise (Parse_error (fname, line, pos,
218             "Uncaught exception: " ^ Printexc.to_string exn)))
219     in
220     let backup = backup_registry () in
221     Hashtbl.clear registry;
222     try
223       aux [] document#root
224     with exn ->
225       restore_registry backup;
226       raise exn
227
228 let load_from ?path fname =
229   if Filename.is_relative fname then begin
230     let no_file_found = ref true in
231     let path =
232       match path with
233       | Some path -> path (* path given as argument *)
234       | None -> [ Sys.getcwd () ] (* no path given, try with cwd *)
235     in
236     List.iter
237       (fun dir ->
238         let conffile = dir ^ "/" ^ fname in
239         if Sys.file_exists conffile then begin
240           no_file_found := false;
241           load_from_absolute conffile
242         end)
243        path;
244     if !no_file_found then
245       failwith (sprintf
246         "Helm_registry.init: no configuration file named %s in [ %s ]"
247         fname (String.concat "; " path))
248   end else
249     load_from_absolute fname
250
251   (* DEBUGGING ONLY *)
252
253 let dump () = Hashtbl.iter (fun k v -> printf "%s = %s\n" k v) registry
254