[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]

[Libguestfs] [PATCH v12 03/11] daemon: utils: New functions and tests.



These utility functions will be used in the OCaml inspection code.
---
 daemon/daemon_utils_tests.ml | 10 ++++++++++
 daemon/utils.ml              | 17 +++++++++++++++++
 daemon/utils.mli             | 11 +++++++++++
 3 files changed, 38 insertions(+)

diff --git a/daemon/daemon_utils_tests.ml b/daemon/daemon_utils_tests.ml
index 892509d89..db94161a0 100644
--- a/daemon/daemon_utils_tests.ml
+++ b/daemon/daemon_utils_tests.ml
@@ -46,3 +46,13 @@ let () =
 let () =
   assert (proc_unmangle_path "\\040" = " ");
   assert (proc_unmangle_path "\\040\\040" = "  ")
+
+(* Test unix_canonical_path. *)
+let () =
+  assert (unix_canonical_path "/" = "/");
+  assert (unix_canonical_path "/usr" = "/usr");
+  assert (unix_canonical_path "/usr/" = "/usr");
+  assert (unix_canonical_path "/usr/local" = "/usr/local");
+  assert (unix_canonical_path "///" = "/");
+  assert (unix_canonical_path "///usr//local//" = "/usr/local");
+  assert (unix_canonical_path "/usr///" = "/usr")
diff --git a/daemon/utils.ml b/daemon/utils.ml
index ecf967966..d87ad75db 100644
--- a/daemon/utils.ml
+++ b/daemon/utils.ml
@@ -212,3 +212,20 @@ let proc_unmangle_path path =
 let is_small_file path =
   is_regular_file path &&
     (stat path).st_size <= 2 * 1048 * 1024
+
+let read_small_file filename =
+  if not (is_small_file filename) then (
+    eprintf "%s: not a regular file or too large\n" filename;
+    None
+  )
+  else (
+    let content = read_whole_file filename in
+    let lines = String.nsplit "\n" content in
+    Some lines
+  )
+
+let unix_canonical_path path =
+  let is_absolute = String.length path > 0 && path.[0] = '/' in
+  let path = String.nsplit "/" path in
+  let path = List.filter ((<>) "") path in
+  (if is_absolute then "/" else "") ^ String.concat "/" path
diff --git a/daemon/utils.mli b/daemon/utils.mli
index 9f9f91a49..f312bde41 100644
--- a/daemon/utils.mli
+++ b/daemon/utils.mli
@@ -86,5 +86,16 @@ val commandr : ?fold_stdout_on_stderr:bool -> string -> string list -> (int * st
 val is_small_file : string -> bool
 (** Return true if the path is a small regular file. *)
 
+val read_small_file : string -> string list option
+(** If [filename] is a small file (see {!is_small_file}) then read it
+    split into lines.  Otherwise emits a debug message and returns
+    [None]. *)
+
+val unix_canonical_path : string -> string
+(** Canonicalize a Unix path, so "///usr//local//" -> "/usr/local"
+
+    The path is modified in place because the result is always
+    the same length or shorter than the argument passed. *)
+
 (**/**)
 val get_verbose_flag : unit -> bool
-- 
2.13.2


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]