1 (* Copyright (C) 2004, HELM Team.
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.
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.
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.
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,
22 * For details, see the HELM World-Wide-Web page,
23 * http://helm.cs.unibo.it/
30 if debug then prerr_endline ("Helm_registry debugging: " ^ s)
35 let rec aux last_element = function
38 (match last_element with
39 | Some elt when elt = hd -> aux last_element tl
40 | _ -> hd :: aux (Some hd) tl)
44 let starts_with prefix =
46 let rex = Str.regexp (Str.quote prefix) in
47 fun s -> Str.string_match rex s 0
49 let prefix_len = String.length prefix in
52 String.sub s 0 prefix_len = prefix
53 with Invalid_argument _ -> false
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 []
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 *)
67 type validator_id = int
69 (* root XML tag: used by save_to, ignored by load_from *)
70 let root_tag = "helm_registry"
72 let get_next_validator_id =
73 let next_id = ref 0 in
79 let validators = Hashtbl.create magic_size
80 let registry = Hashtbl.create magic_size
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
88 * - no sequences of '_' longer than 1 are permitted
89 * - no uppercase letter are permitted
91 let valid_step_rex_raw = "[a-z0-9]+\\(_[a-z0-9]+\\)*"
92 let valid_key_rex_raw =
93 sprintf "%s\(\\.%s\)*" valid_step_rex_raw valid_step_rex_raw
94 let valid_key_rex = Str.regexp ("^" ^ valid_key_rex_raw ^ "$")
95 let interpolated_key_rex = Str.regexp ("\\$(" ^ valid_key_rex_raw ^ ")")
96 let dot_rex = Str.regexp "\\."
97 let spaces_rex = Str.regexp "[ \t\n\r]+"
98 let heading_spaces_rex = Str.regexp "^[ \t\n\r]+"
101 (* trailing blanks are removed per default by split *)
102 Str.split spaces_rex (Str.global_replace heading_spaces_rex "" s)
103 let merge l = String.concat " " l
105 (* escapes for xml configuration file *)
106 let (escape, unescape) =
107 let (in_enc, out_enc) = (`Enc_utf8, `Enc_utf8) in
108 (Netencoding.Html.encode ~in_enc ~out_enc (),
109 Netencoding.Html.decode ~in_enc ~out_enc ~entity_base:`Xml ())
111 let key_is_valid key =
112 if not (Str.string_match valid_key_rex key 0) then
113 raise (Malformed_key key)
115 let value_is_valid ~key ~value =
117 (fun (validator, descr) ->
118 if not (validator value) then
119 raise (Invalid_value ((key, value), descr)))
120 (Hashtbl.find_all validators key)
122 let set' registry ~key ~value =
123 debug_print (sprintf "Setting %s = %s" key value);
125 value_is_valid ~key ~value;
126 Hashtbl.replace registry key value
128 let unset = Hashtbl.remove registry
130 let env_var_of_key key =
131 Str.global_replace dot_rex "__" (String.uppercase key)
134 let rec aux stack key =
136 if List.mem key stack then begin
137 let msg = (String.concat " -> " (List.rev stack)) ^ " -> " ^ key in
138 raise (Cyclic_definition msg)
140 let registry_value = (* internal value *)
142 Some (Hashtbl.find registry key)
143 with Not_found -> None
145 let env_value = (* environment value *)
147 Some (Sys.getenv (env_var_of_key key))
148 with Not_found -> None
150 let value = (* resulting value *)
151 match (registry_value, env_value) with
152 | Some reg, Some env -> env
153 | Some reg, None -> reg
154 | None, Some env -> env
155 | None, None -> raise (Key_not_found key)
157 interpolate (key :: stack) value
158 and interpolate stack value =
159 Str.global_substitute interpolated_key_rex
161 let matched = Str.matched_string s in
162 (* "$(var)" -> "var" *)
163 let key = String.sub matched 2 (String.length matched - 3) in
169 let set = set' registry
171 let has key = Hashtbl.mem registry key
173 let mk_get_set type_name (from_string: string -> 'a) (to_string: 'a -> string) =
175 let value = get key in
179 raise (Type_error (type_name, value, Printexc.to_string exn))
181 let setter ~key ~value = set ~key ~value:(to_string value) in
184 let (get_string, set_string) = (get, set)
185 let (get_int, set_int) = mk_get_set "int" int_of_string string_of_int
186 let (get_float, set_float) = mk_get_set "float" float_of_string string_of_float
187 let (get_bool, set_bool) = mk_get_set "bool" bool_of_string string_of_bool
188 let (get_string_list, set_string_list) = mk_get_set "string list" split merge
190 let get_opt getter key =
193 with Key_not_found _ -> None
194 let set_opt setter ~key ~value =
197 | Some value -> setter ~key ~value
198 let get_opt_default getter default key =
199 match get_opt getter key with
203 let add_validator ~key ~validator ~descr =
204 let id = get_next_validator_id () in
205 Hashtbl.add validators key (validator, descr);
214 let dtd = new dtd PxpHelmConf.pxp_config.warner `Enc_utf8 in
215 let dot_RE = Str.regexp "\\." in
216 let create_key_node key value = (* create a <key name="foo">value</key> *)
218 create_element_node ~valcheck:false PxpHelmConf.pxp_spec dtd
221 let data = create_data_node PxpHelmConf.pxp_spec dtd value in
222 element#append_node data;
225 let is_section name =
227 match node#node_type with
228 | T_element "section" ->
229 (try node#attribute "name" = Value name with Not_found -> false)
232 let add_key_node root sections key value =
233 let rec aux node = function
235 let key_node = create_key_node key value in
236 node#append_node key_node
240 find ~deeply:false (is_section section) node
243 create_element_node ~valcheck:false PxpHelmConf.pxp_spec dtd
244 "section" ["name", section]
246 node#append_node section_node;
255 create_element_node ~valcheck:false PxpHelmConf.pxp_spec dtd "helm_registry" []
261 match List.rev (Str.split dot_RE key) with
267 add_key_node xml_root sections key value)
269 let outchan = (* let's write xml output to fname *)
270 if Unix.system "xmllint --version &> /dev/null" = Unix.WEXITED 0 then
271 (* xmllint available, use it! *)
272 Unix.open_process_out (sprintf
273 "xmllint --format --encode utf8 -o '%s' -" fname)
275 (* xmllint not available, write pxp ugly output directly to fname *)
278 xml_root#write (`Out_channel outchan) `Enc_utf8;
281 let load_from_absolute =
282 let config = PxpHelmConf.pxp_config in
283 let entry = `Entry_document [ `Extend_dtd_fully; `Parse_xml_decl ] in
284 let fold_key key_stack key =
287 | _ -> String.concat "." key_stack ^ "." ^ key
290 debug_print ("Loading configuration from " ^ fname);
292 parse_wfdocument_entity config (from_file fname) PxpHelmConf.pxp_spec
294 let rec aux key_stack node =
295 node#iter_nodes (fun n ->
297 (match n#node_type with
298 | T_element "section" ->
299 let section = n#required_string_attribute "name" in
300 aux (key_stack @ [section]) n
302 let key = n#required_string_attribute "name" in
303 let value = n#data in
304 set ~key:(fold_key key_stack key) ~value
307 let (fname, line, pos) = n#position in
308 raise (Parse_error (fname, line, pos,
309 "Uncaught exception: " ^ Printexc.to_string exn)))
311 let backup = backup_registry () in
312 Hashtbl.clear registry;
316 restore_registry backup;
319 let load_from ?path fname =
320 if Filename.is_relative fname then begin
321 let no_file_found = ref true in
324 | Some path -> path (* path given as argument *)
325 | None -> [ Sys.getcwd () ] (* no path given, try with cwd *)
329 let conffile = dir ^ "/" ^ fname in
330 if Sys.file_exists conffile then begin
331 no_file_found := false;
332 load_from_absolute conffile
335 if !no_file_found then
337 "Helm_registry.init: no configuration file named %s in [ %s ]"
338 fname (String.concat "; " path))
340 load_from_absolute fname
342 let fold ?prefix f init =
344 | None -> Hashtbl.fold (fun k v acc -> f acc k v) registry init
346 let key_matches = starts_with (s ^ ".") in
347 let rec fold_filter acc = function
349 | (k,v) :: tl when key_matches k -> fold_filter (f acc k v) tl
350 | _ :: tl -> fold_filter acc tl
352 fold_filter init (hashtbl_pairs registry)
354 let iter ?prefix f = fold ?prefix (fun _ k v -> f k v) ()
355 let to_list ?prefix () = fold ?prefix (fun acc k v -> (k, v) :: acc) []
358 let prefix = prefix ^ "." in
359 let prefix_len = String.length prefix in
360 let key_matches = starts_with prefix in
361 let matching_keys = (* collect matching keys' _postfixes_ *)
364 if key_matches key then
365 String.sub key prefix_len (String.length key - prefix_len) :: acc
370 let (sections, keys) =
372 (fun (sections, keys) postfix ->
373 match Str.split dot_rex postfix with
374 | [key] -> (sections, key :: keys)
375 | hd_key :: _ -> (* length > 1 => nested section found *)
376 (hd_key :: sections, keys)
378 ([], []) matching_keys
380 (list_uniq (List.sort Pervasives.compare sections), keys)
384 let dump () = Hashtbl.iter (fun k v -> printf "%s = %s\n" k v) registry