[Libguestfs] [PATCH v2 1/2] daemon: add split_key_value_strings helper

Pino Toscano ptoscano at redhat.com
Mon Oct 16 15:58:10 UTC 2017


Add a simple helper to turn a list of strings into key/value pairs,
splitting by '=', with the possibility to apply a function to unquote
values.

Add also a simple unquote function.
---
 daemon/utils.ml  | 16 ++++++++++++++++
 daemon/utils.mli | 11 +++++++++++
 2 files changed, 27 insertions(+)

diff --git a/daemon/utils.ml b/daemon/utils.ml
index d87ad75db..865936280 100644
--- a/daemon/utils.ml
+++ b/daemon/utils.ml
@@ -229,3 +229,19 @@ let unix_canonical_path path =
   let path = String.nsplit "/" path in
   let path = List.filter ((<>) "") path in
   (if is_absolute then "/" else "") ^ String.concat "/" path
+
+let simple_unquote s =
+  let n = String.length s in
+  if n >= 2 &&
+     ((s.[0] = '"' && s.[n-1] = '"') || (s.[0] = '\'' && s.[n-1] = '\'')) then
+    String.sub s 1 (n-2)
+  else
+    s
+
+let split_key_value_strings ?unquote lines =
+  let lines = List.filter ((<>) "") lines in
+  let lines = List.filter (fun s -> s.[0] <> '#') lines in
+  let lines = List.map (String.split "=") lines in
+  match unquote with
+  | None -> lines
+  | Some f -> List.map (fun (k, v) -> (k, f v)) lines
diff --git a/daemon/utils.mli b/daemon/utils.mli
index f312bde41..c44a6dc76 100644
--- a/daemon/utils.mli
+++ b/daemon/utils.mli
@@ -97,5 +97,16 @@ val unix_canonical_path : string -> string
     The path is modified in place because the result is always
     the same length or shorter than the argument passed. *)
 
+val simple_unquote : string -> string
+(** Unquote the string, by removing a pair of single- or double-quotes
+    at the beginning and the end of the string.
+
+    No other handling is done, unlike what {!shell_unquote} does. *)
+
+val split_key_value_strings : ?unquote:(string -> string) -> string list -> (string * string) list
+(** Split the lines by the [=] separator; if [unquote] is specified,
+    it is applied on the values as unquote function.  Empty lines,
+    or that start with a comment character [#], are ignored. *)
+
 (**/**)
 val get_verbose_flag : unit -> bool
-- 
2.13.6




More information about the Libguestfs mailing list