1 (* Copyright (C) 2004-2005, 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/
32 if debug then prerr_endline ("Helm_registry debugging: " ^ (Lazy.force s))
37 let rec aux last_element = function
40 (match last_element with
41 | Some elt when elt = hd -> aux last_element tl
42 | _ -> hd :: aux (Some hd) tl)
46 let starts_with prefix =
48 let rex = Str.regexp (Str.quote prefix) in
49 fun s -> Str.string_match rex s 0
51 let prefix_len = String.length prefix in
54 String.sub s 0 prefix_len = prefix
55 with Invalid_argument _ -> false
57 let hashtbl_keys tbl = Hashtbl.fold (fun k _ acc -> k :: acc) tbl []
58 let hashtbl_pairs tbl = Hashtbl.fold (fun k v acc -> (k,v) :: acc) tbl []
62 exception Malformed_key of string
63 exception Key_not_found of string
64 exception Cyclic_definition of string
65 exception Type_error of string (* expected type, value, msg *)
66 exception Parse_error of string * int * int * string (* file, line, col, msg *)
68 (* root XML tag: used by save_to, ignored by load_from *)
69 let root_tag = "helm_registry"
73 let backup_registry registry = Hashtbl.copy registry
74 let restore_registry backup registry =
75 Hashtbl.clear registry;
76 Hashtbl.iter (fun key value -> Hashtbl.add registry key value) backup
79 * - no sequences of '_' longer than 1 are permitted
81 let valid_step_rex_raw = "[a-zA-Z0-9]+\\(_[a-z0A-Z-9]+\\)*"
82 let valid_key_rex_raw =
83 sprintf "%s\\(\\.%s\\)*" valid_step_rex_raw valid_step_rex_raw
84 let valid_key_rex = Str.regexp ("^" ^ valid_key_rex_raw ^ "$")
85 let interpolated_key_rex = Str.regexp ("\\$(" ^ valid_key_rex_raw ^ ")")
86 let dot_rex = Str.regexp "\\."
87 let spaces_rex = Str.regexp "[ \t\n\r]+"
88 let heading_spaces_rex = Str.regexp "^[ \t\n\r]+"
89 let margin_blanks_rex =
90 Str.regexp "^\\([ \t\n\r]*\\)\\([^ \t\n\r]*\\)\\([ \t\n\r]*\\)$"
92 let strip_blanks s = Str.global_replace margin_blanks_rex "\\2" s
95 (* trailing blanks are removed per default by split *)
96 Str.split spaces_rex (Str.global_replace heading_spaces_rex "" s)
97 let merge l = String.concat " " l
99 let handle_type_error f x =
100 try f x with exn -> raise (Type_error (Printexc.to_string exn))
102 (** marshallers/unmarshallers *)
104 let int = handle_type_error int_of_string
105 let float = handle_type_error float_of_string
106 let bool = handle_type_error bool_of_string
108 let of_int = handle_type_error string_of_int
109 let of_float = handle_type_error string_of_float
110 let of_bool = handle_type_error string_of_bool
113 let pair fst_unmarshaller snd_unmarshaller v =
114 match Str.split spaces_rex v with
115 | [fst; snd] -> fst_unmarshaller fst, snd_unmarshaller snd
116 | _ -> raise (Type_error "not a pair")
118 (* escapes for xml configuration file *)
119 let (escape, unescape) =
120 let (in_enc, out_enc) = (`Enc_utf8, `Enc_utf8) in
121 (Netencoding.Html.encode ~in_enc ~out_enc (),
122 Netencoding.Html.decode ~in_enc ~out_enc ~entity_base:`Xml ())
124 let key_is_valid key =
125 if not (Str.string_match valid_key_rex key 0) then
126 raise (Malformed_key key)
128 let set' ?(replace=false) registry ~key ~value =
129 debug_print (lazy(sprintf "Setting (replace: %b) %s = %s" replace key value));
131 let add_fun = if replace then Hashtbl.replace else Hashtbl.add in
132 add_fun registry key value
134 let unset registry = Hashtbl.remove registry
136 let env_var_of_key s = String.uppercase (Str.global_replace dot_rex "_" s)
138 let singleton = function
140 raise (Type_error ("empty list value found where singleton was expected"))
143 let get registry key =
144 let rec aux stack key =
146 if List.mem key stack then begin
147 let msg = (String.concat " -> " (List.rev stack)) ^ " -> " ^ key in
148 raise (Cyclic_definition msg)
151 let registry_values = List.rev (Hashtbl.find_all registry key) in
152 let env_value = (* environment value *)
154 Some (Sys.getenv (env_var_of_key key))
155 with Not_found -> None
157 let values = (* resulting value *)
158 match registry_values, env_value with
159 | _, Some env -> [env]
163 with Not_found -> raise (Key_not_found key))
164 | values, None -> values
166 List.map (interpolate (key :: stack)) values
167 and interpolate stack value =
168 Str.global_substitute interpolated_key_rex
170 let matched = Str.matched_string s in
171 (* "$(var)" -> "var" *)
172 let key = String.sub matched 2 (String.length matched - 3) in
173 singleton (aux stack key))
176 List.map strip_blanks (aux [] key)
178 let has registry key = Hashtbl.mem registry key
180 let get_typed registry unmarshaller key =
181 let value = singleton (get registry key) in
184 let set_typed registry marshaller ~key ~value =
185 set' ~replace:true registry ~key ~value:(marshaller value)
187 let get_opt registry unmarshaller key =
189 Some (unmarshaller (singleton (get registry key)))
190 with Key_not_found _ -> None
192 let get_opt_default registry unmarshaller ~default key =
193 match get_opt registry unmarshaller key with
197 let set_opt registry marshaller ~key ~value =
199 | None -> unset registry key
200 | Some value -> set' ~replace:true registry ~key ~value:(marshaller value)
202 let get_list registry unmarshaller key =
204 let tmp = get registry key in
205 let rc = List.map unmarshaller tmp in
207 with Key_not_found _ -> []
210 let get_pair registry fst_unmarshaller snd_unmarshaller =
211 get_typed registry (pair fst_unmarshaller snd_unmarshaller)
213 let set_list registry marshaller ~key ~value =
214 (* since ocaml hash table are crazy... *)
215 while Hashtbl.mem registry key do
216 Hashtbl.remove registry key
218 List.iter (fun v -> set' registry ~key ~value:(marshaller v)) value
222 | Element of string * (string * string) list * xml_tree list
224 let dot_RE = Str.regexp "\\."
226 let xml_tree_of_registry registry =
227 let has_child name elements =
230 | Element (_, ["name", name'], _) when name = name' -> true
234 let rec get_child name = function
236 | (Element (_, ["name", name'], _) as child) :: tl when name = name' ->
239 let child, rest = get_child name tl in
242 let rec add_key path value tree =
243 match path, tree with
244 | [key], Element (name, attrs, children) ->
245 Element (name, attrs,
246 Element ("key", ["name", key],
247 [Cdata (strip_blanks value)]) :: children)
248 | dir :: path, Element (name, attrs, children) ->
249 if has_child dir children then
250 let child, rest = get_child dir children in
251 Element (name, attrs, add_key path value child :: rest)
253 Element (name, attrs,
254 ((add_key path value (Element ("section", ["name", dir], [])))
259 (fun k v tree -> add_key ((Str.split dot_RE k)) v tree)
261 (Element (root_tag, [], []))
263 let rec stream_of_xml_tree = function
264 | Cdata s -> Xml.xml_cdata s
265 | Element (name, attrs, children) ->
267 (List.map (fun (n, v) -> (None, n, v)) attrs)
268 (stream_of_xml_trees children)
269 and stream_of_xml_trees = function
271 | hd :: tl -> [< stream_of_xml_tree hd; stream_of_xml_trees tl >]
273 let save_to registry fname =
274 let token_stream = stream_of_xml_tree (xml_tree_of_registry registry) in
275 let oc = open_out fname in
276 Xml.pp_to_outchan token_stream oc;
279 let rec load_from_absolute ?path registry fname =
280 let _path = ref (match path with None -> [] | Some p -> p)in
281 (* <section> elements entered so far *)
282 let in_key = ref false in (* have we entered a <key> element? *)
283 let cdata = ref "" in (* collected cdata (inside <key> *)
284 let push_path name = _path := name :: !_path in
285 let pop_path () = _path := List.tl !_path in
286 let start_element tag attrs =
287 match tag, attrs with
288 | "section", ["name", name] -> push_path name
289 | "key", ["name", name] -> in_key := true; push_path name
290 | "helm_registry", _ -> ()
291 | "include", ["href", fname] ->
292 debug_print (lazy ("including file " ^ fname));
293 load_from_absolute ~path:!_path registry fname
295 raise (Parse_error (fname, ~-1, ~-1,
296 (sprintf "unexpected element <%s> or wrong attribute set" tag)))
298 let end_element tag =
300 | "section" -> pop_path ()
302 let key = String.concat "." (List.rev !_path) in
303 set' registry ~key ~value:!cdata;
307 | "include" | "helm_registry" -> ()
310 let character_data text =
311 if !in_key then cdata := !cdata ^ text
314 XmlPushParser.default_callbacks with
315 XmlPushParser.start_element = Some start_element;
316 XmlPushParser.end_element = Some end_element;
317 XmlPushParser.character_data = Some character_data;
319 let xml_parser = XmlPushParser.create_parser callbacks in
320 let backup = backup_registry registry in
321 (* if path = None then Hashtbl.clear registry; *)
323 XmlPushParser.parse xml_parser (`File fname)
325 restore_registry backup registry;
328 let load_from registry ?path fname =
329 if Filename.is_relative fname then begin
330 let no_file_found = ref true in
333 | Some path -> path (* path given as argument *)
334 | None -> [ Sys.getcwd () ] (* no path given, try with cwd *)
338 let conffile = dir ^ "/" ^ fname in
339 if Sys.file_exists conffile then begin
340 no_file_found := false;
341 load_from_absolute registry conffile
344 if !no_file_found then
346 "Helm_registry.init: no configuration file named %s in [ %s ]"
347 fname (String.concat "; " path))
349 load_from_absolute registry fname
351 let fold registry ?prefix ?(interpolate = true) f init =
353 if interpolate then singleton (get registry k) else strip_blanks v
356 | None -> Hashtbl.fold (fun k v acc -> f acc k (value_of k v)) registry init
358 let key_matches = starts_with (s ^ ".") in
359 let rec fold_filter acc = function
361 | (k,v) :: tl when key_matches k ->
362 fold_filter (f acc k (value_of k v)) tl
363 | _ :: tl -> fold_filter acc tl
365 fold_filter init (hashtbl_pairs registry)
367 let iter registry ?prefix ?interpolate f =
368 fold registry ?prefix ?interpolate (fun _ k v -> f k v) ()
369 let to_list registry ?prefix ?interpolate () =
370 fold registry ?prefix ?interpolate (fun acc k v -> (k, v) :: acc) []
372 let ls registry prefix =
373 let prefix = prefix ^ "." in
374 let prefix_len = String.length prefix in
375 let key_matches = starts_with prefix in
376 let matching_keys = (* collect matching keys' _postfixes_ *)
379 if key_matches key then
380 String.sub key prefix_len (String.length key - prefix_len) :: acc
385 let (sections, keys) =
387 (fun (sections, keys) postfix ->
388 match Str.split dot_rex postfix with
389 | [key] -> (sections, key :: keys)
390 | hd_key :: _ -> (* length > 1 => nested section found *)
391 (hd_key :: sections, keys)
393 ([], []) matching_keys
395 (list_uniq (List.sort Pervasives.compare sections), keys)
397 (** {2 API implementation}
398 * functional methods above are wrapped so that they work on a default
399 * (imperative) registry*)
401 let default_registry = Hashtbl.create magic_size
403 let get key = singleton (get default_registry key)
404 let set = set' ~replace:true default_registry
405 let has = has default_registry
406 let fold ?prefix ?interpolate f init =
407 fold default_registry ?prefix ?interpolate f init
408 let iter = iter default_registry
409 let to_list = to_list default_registry
410 let ls = ls default_registry
411 let get_typed unmarshaller = get_typed default_registry unmarshaller
412 let get_opt unmarshaller = get_opt default_registry unmarshaller
413 let get_opt_default unmarshaller = get_opt_default default_registry unmarshaller
414 let get_list unmarshaller = get_list default_registry unmarshaller
415 let get_pair unmarshaller = get_pair default_registry unmarshaller
416 let set_typed marshaller = set_typed default_registry marshaller
417 let set_opt unmarshaller = set_opt default_registry unmarshaller
418 let set_list marshaller = set_list default_registry marshaller
419 let unset = unset default_registry
420 let save_to = save_to default_registry
421 let load_from = load_from default_registry
422 let clear () = Hashtbl.clear default_registry
424 let get_string = get_typed string
425 let get_int = get_typed int
426 let get_float = get_typed float
427 let get_bool = get_typed bool
428 let set_string = set_typed of_string
429 let set_int = set_typed of_int
430 let set_float = set_typed of_float
431 let set_bool = set_typed of_bool