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/
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 (* 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 (* root XML tag: used by save_to, ignored by load_from *)
68 let root_tag = "helm_registry"
72 let backup_registry registry = Hashtbl.copy registry
73 let restore_registry backup registry =
74 Hashtbl.clear registry;
75 Hashtbl.iter (fun key value -> Hashtbl.add registry key value) backup
78 * - no sequences of '_' longer than 1 are permitted
80 let valid_step_rex_raw = "[a-zA-Z0-9]+\\(_[a-z0A-Z-9]+\\)*"
81 let valid_key_rex_raw =
82 sprintf "%s\\(\\.%s\\)*" valid_step_rex_raw valid_step_rex_raw
83 let valid_key_rex = Str.regexp ("^" ^ valid_key_rex_raw ^ "$")
84 let interpolated_key_rex = Str.regexp ("\\$(" ^ valid_key_rex_raw ^ ")")
85 let dot_rex = Str.regexp "\\."
86 let spaces_rex = Str.regexp "[ \t\n\r]+"
87 let heading_spaces_rex = Str.regexp "^[ \t\n\r]+"
88 let margin_blanks_rex =
89 Str.regexp "^\\([ \t\n\r]*\\)\\([^ \t\n\r]*\\)\\([ \t\n\r]*\\)$"
91 let strip_blanks s = Str.global_replace margin_blanks_rex "\\2" s
94 (* trailing blanks are removed per default by split *)
95 Str.split spaces_rex (Str.global_replace heading_spaces_rex "" s)
96 let merge l = String.concat " " l
98 let handle_type_error f x =
99 try f x with exn -> raise (Type_error (Printexc.to_string exn))
101 (** marshallers/unmarshallers *)
103 let int = handle_type_error int_of_string
104 let float = handle_type_error float_of_string
105 let bool = handle_type_error bool_of_string
107 let of_int = handle_type_error string_of_int
108 let of_float = handle_type_error string_of_float
109 let of_bool = handle_type_error string_of_bool
111 (* escapes for xml configuration file *)
112 let (escape, unescape) =
113 let (in_enc, out_enc) = (`Enc_utf8, `Enc_utf8) in
114 (Netencoding.Html.encode ~in_enc ~out_enc (),
115 Netencoding.Html.decode ~in_enc ~out_enc ~entity_base:`Xml ())
117 let key_is_valid key =
118 if not (Str.string_match valid_key_rex key 0) then
119 raise (Malformed_key key)
121 let set' registry ~key ~value =
122 debug_print (sprintf "Setting %s = %s" key value);
124 Hashtbl.add registry key value
126 let unset registry = Hashtbl.remove registry
128 let env_var_of_key = Str.global_replace dot_rex "__"
130 let singleton = function
132 raise (Type_error ("empty list value found where singleton was expected"))
135 let get registry key =
136 let rec aux stack key =
138 if List.mem key stack then begin
139 let msg = (String.concat " -> " (List.rev stack)) ^ " -> " ^ key in
140 raise (Cyclic_definition msg)
143 let registry_values = List.rev (Hashtbl.find_all registry key) in
144 let env_value = (* environment value *)
146 Some (Sys.getenv (env_var_of_key key))
147 with Not_found -> None
149 let values = (* resulting value *)
150 match registry_values, env_value with
151 | _, Some env -> [env]
152 | [], None -> raise (Key_not_found key)
153 | values, None -> values
155 List.map (interpolate (key :: stack)) values
156 and interpolate stack value =
157 Str.global_substitute interpolated_key_rex
159 let matched = Str.matched_string s in
160 (* "$(var)" -> "var" *)
161 let key = String.sub matched 2 (String.length matched - 3) in
162 singleton (aux stack key))
165 List.map strip_blanks (aux [] key)
167 let set registry = set' registry
169 let has registry key = Hashtbl.mem registry key
171 let get_typed registry unmarshaller key =
172 let value = singleton (get registry key) in
175 let set_typed registry marshaller ~key ~value =
176 set registry ~key ~value:(marshaller value)
178 let get_opt registry unmarshaller key =
180 Some (unmarshaller (singleton (get registry key)))
181 with Key_not_found _ -> None
183 let get_opt_default registry unmarshaller ~default key =
184 match get_opt registry unmarshaller key with
188 let set_opt registry marshaller ~key ~value =
190 | None -> unset registry key
191 | Some value -> set registry ~key ~value:(marshaller value)
193 let get_list registry unmarshaller key =
195 List.map unmarshaller (get registry key)
196 with Key_not_found _ -> []
198 let set_list registry marshaller ~key ~value =
199 List.iter (fun v -> set registry ~key ~value:(marshaller v)) value
203 | Element of string * (string * string) list * xml_tree list
205 let dot_RE = Str.regexp "\\."
207 let xml_tree_of_registry registry =
208 let has_child name elements =
211 | Element (_, ["name", name'], _) when name = name' -> true
215 let rec get_child name = function
217 | (Element (_, ["name", name'], _) as child) :: tl when name = name' ->
220 let child, rest = get_child name tl in
223 let rec add_key path value tree =
224 match path, tree with
225 | [key], Element (name, attrs, children) ->
226 Element (name, attrs,
227 Element ("key", ["name", key],
228 [Cdata (strip_blanks value)]) :: children)
229 | dir :: path, Element (name, attrs, children) ->
230 if has_child dir children then
231 let child, rest = get_child dir children in
232 Element (name, attrs, add_key path value child :: rest)
234 Element (name, attrs,
235 ((add_key path value (Element ("section", ["name", dir], [])))
240 (fun k v tree -> add_key ("helm_registry" :: (Str.split dot_RE k)) v tree)
242 (Element ("helm_registry", [], []))
244 let rec stream_of_xml_tree = function
245 | Cdata s -> Xml.xml_cdata s
246 | Element (name, attrs, children) ->
248 (List.map (fun (n, v) -> (None, n, v)) attrs)
249 (stream_of_xml_trees children)
250 and stream_of_xml_trees = function
252 | hd :: tl -> [< stream_of_xml_tree hd; stream_of_xml_trees tl >]
254 let save_to registry fname =
255 let token_stream = stream_of_xml_tree (xml_tree_of_registry registry) in
256 let oc = open_out fname in
257 Xml.pp_to_outchan token_stream oc;
260 let load_from_absolute registry fname =
261 let path = ref [] in (* <section> elements entered so far *)
262 let in_key = ref false in (* have we entered a <key> element? *)
263 let cdata = ref "" in (* collected cdata (inside <key> *)
264 let push_path name = path := name :: !path in
265 let pop_path () = path := List.tl !path in
266 let start_element tag attrs =
267 match tag, attrs with
268 | "section", ["name", name] -> push_path name
269 | "key", ["name", name] -> in_key := true; push_path name
270 | "helm_registry", _ -> ()
272 raise (Parse_error (fname, ~-1, ~-1,
273 (sprintf "unexpected element <%s> or wrong attribute set" tag)))
275 let end_element tag =
277 | "section" -> pop_path ()
279 let key = String.concat "." (List.rev !path) in
280 set registry ~key ~value:!cdata;
284 | "helm_registry" -> ()
287 let character_data text =
288 if !in_key then cdata := !cdata ^ text
291 XmlPushParser.default_callbacks with
292 XmlPushParser.start_element = Some start_element;
293 XmlPushParser.end_element = Some end_element;
294 XmlPushParser.character_data = Some character_data;
296 let xml_parser = XmlPushParser.create_parser callbacks in
297 let backup = backup_registry registry in
298 Hashtbl.clear registry;
300 XmlPushParser.parse xml_parser (`File fname)
302 restore_registry backup registry;
305 let load_from registry ?path fname =
306 if Filename.is_relative fname then begin
307 let no_file_found = ref true in
310 | Some path -> path (* path given as argument *)
311 | None -> [ Sys.getcwd () ] (* no path given, try with cwd *)
315 let conffile = dir ^ "/" ^ fname in
316 if Sys.file_exists conffile then begin
317 no_file_found := false;
318 load_from_absolute registry conffile
321 if !no_file_found then
323 "Helm_registry.init: no configuration file named %s in [ %s ]"
324 fname (String.concat "; " path))
326 load_from_absolute registry fname
328 let fold registry ?prefix ?(interpolate = true) f init =
330 if interpolate then singleton (get registry k) else strip_blanks v
333 | None -> Hashtbl.fold (fun k v acc -> f acc k (value_of k v)) registry init
335 let key_matches = starts_with (s ^ ".") in
336 let rec fold_filter acc = function
338 | (k,v) :: tl when key_matches k ->
339 fold_filter (f acc k (value_of k v)) tl
340 | _ :: tl -> fold_filter acc tl
342 fold_filter init (hashtbl_pairs registry)
344 let iter registry ?prefix ?interpolate f =
345 fold registry ?prefix ?interpolate (fun _ k v -> f k v) ()
346 let to_list registry ?prefix ?interpolate () =
347 fold registry ?prefix ?interpolate (fun acc k v -> (k, v) :: acc) []
349 let ls registry prefix =
350 let prefix = prefix ^ "." in
351 let prefix_len = String.length prefix in
352 let key_matches = starts_with prefix in
353 let matching_keys = (* collect matching keys' _postfixes_ *)
356 if key_matches key then
357 String.sub key prefix_len (String.length key - prefix_len) :: acc
362 let (sections, keys) =
364 (fun (sections, keys) postfix ->
365 match Str.split dot_rex postfix with
366 | [key] -> (sections, key :: keys)
367 | hd_key :: _ -> (* length > 1 => nested section found *)
368 (hd_key :: sections, keys)
370 ([], []) matching_keys
372 (list_uniq (List.sort Pervasives.compare sections), keys)
374 (** {2 API implementation}
375 * functional methods above are wrapped so that they work on a default
376 * (imperative) registry*)
378 let default_registry = Hashtbl.create magic_size
380 let get key = singleton (get default_registry key)
381 let set = set default_registry
382 let has = has default_registry
383 let fold ?prefix ?interpolate f init =
384 fold default_registry ?prefix ?interpolate f init
385 let iter = iter default_registry
386 let to_list = to_list default_registry
387 let ls = ls default_registry
388 let get_typed unmarshaller = get_typed default_registry unmarshaller
389 let get_opt unmarshaller = get_opt default_registry unmarshaller
390 let get_opt_default unmarshaller = get_opt_default default_registry unmarshaller
391 let get_list unmarshaller = get_list default_registry unmarshaller
392 let set_typed marshaller = set_typed default_registry marshaller
393 let set_opt unmarshaller = set_opt default_registry unmarshaller
394 let set_list marshaller = set_list default_registry marshaller
395 let unset = unset default_registry
396 let save_to = save_to default_registry
397 let load_from = load_from default_registry
399 let get_string = get_typed string
400 let get_int = get_typed int
401 let get_float = get_typed float
402 let get_bool = get_typed bool
403 let set_string = set_typed of_string
404 let set_int = set_typed of_int
405 let set_float = set_typed of_float
406 let set_bool = set_typed of_bool