[Libguestfs] [PATCH 5/6] mllib: add quick section/key lookup method

Pino Toscano ptoscano at redhat.com
Wed Jul 8 14:42:17 UTC 2015


Add an helper method to lookup the value of a key within a parsed ini
configuration.
---
 mllib/ini_reader.ml  | 16 ++++++++++++++++
 mllib/ini_reader.mli |  5 +++++
 2 files changed, 21 insertions(+)

diff --git a/mllib/ini_reader.ml b/mllib/ini_reader.ml
index 08f3ec7..3c9dcee 100644
--- a/mllib/ini_reader.ml
+++ b/mllib/ini_reader.ml
@@ -24,6 +24,9 @@ and section = string * fields                (* [name] + fields *)
 and fields = field list
 and field = string * string option * string  (* key + subkey + value *)
 
+exception Section_not_found of string (* section *)
+exception Key_not_found of (string * string * string option) (* section, key, subkey *)
+
 (* Types returned by the C index parser. *)
 type c_sections = c_section array
 and c_section = string * c_fields             (* [name] + fields *)
@@ -80,3 +83,16 @@ let read_ini ?(error_suffix = "") ?real_uri
   );
 
   sections
+
+let ini_get_value ?subkey ini group key =
+  let confgroup =
+    match List.filter (fun (n, _) -> n = group) ini with
+    | [] -> raise (Section_not_found group)
+    | (_, fields) :: _ -> fields in
+  let confkey = List.filter (
+    fun (field, subfield, _) ->
+      field = key && subfield = subkey
+  ) confgroup in
+  match confkey with
+  | [] -> raise (Key_not_found (group, key, subkey))
+  | (_, _, value) :: _ -> value
diff --git a/mllib/ini_reader.mli b/mllib/ini_reader.mli
index 63e7572..f55f596 100644
--- a/mllib/ini_reader.mli
+++ b/mllib/ini_reader.mli
@@ -21,4 +21,9 @@ and section = string * fields                (* [name] + fields *)
 and fields = field list
 and field = string * string option * string  (* key + subkey + value *)
 
+exception Section_not_found of string (* section *)
+exception Key_not_found of (string * string * string option) (* section, key, subkey *)
+
 val read_ini : ?error_suffix:string -> ?real_uri:string -> ?check_duplicated_sections:bool -> ?check_duplicated_fields:bool -> string -> sections
+
+val ini_get_value : ?subkey:string -> sections -> string -> string -> string
-- 
2.1.0




More information about the Libguestfs mailing list