[Libguestfs] [PATCH v2 1/7] mllib: factorize code to add Checksum.get_checksum function

Cédric Bosdonnat cbosdonnat at suse.com
Tue Feb 7 15:14:16 UTC 2017


Getting checksum involves the same code than verifying them. Create
a get_checksum function and use it in verify_checksum.
---
 mllib/checksums.ml  | 25 ++++++++++++++++---------
 mllib/checksums.mli |  9 +++++++++
 2 files changed, 25 insertions(+), 9 deletions(-)

diff --git a/mllib/checksums.ml b/mllib/checksums.ml
index 1009e131c..bee829085 100644
--- a/mllib/checksums.ml
+++ b/mllib/checksums.ml
@@ -45,14 +45,13 @@ let of_string csum_type csum_value =
   | "sha512" -> SHA512 csum_value
   | _ -> invalid_arg csum_type
 
-let verify_checksum csum ?tar filename =
-  let prog, csum_ref =
+let do_compute_checksum csum ?tar filename =
+  let prog =
     match csum with
-    | SHA1 c -> "sha1sum", c
-    | SHA256 c -> "sha256sum", c
-    | SHA512 c -> "sha512sum", c
+    | SHA1 _ -> "sha1sum"
+    | SHA256 _ -> "sha256sum"
+    | SHA512 _ -> "sha512sum"
   in
-
   let cmd =
     match tar with
     | None ->
@@ -66,9 +65,17 @@ let verify_checksum csum ?tar filename =
   | [] ->
     error (f_"%s did not return any output") prog
   | line :: _ ->
-    let csum_actual = fst (String.split " " line) in
-    if csum_ref <> csum_actual then
-      raise (Mismatched_checksum (csum, csum_actual))
+    fst (String.split " " line)
+
+let compute_checksum csum_type ?tar filename =
+  do_compute_checksum (of_string csum_type "") ?tar filename
+
+let verify_checksum csum ?tar filename =
+  let csum_ref = string_of_csum csum in
+  let csum_type = string_of_csum_t csum in
+  let csum_actual = compute_checksum csum_type ?tar filename in
+  if csum_ref <> csum_actual then
+    raise (Mismatched_checksum (csum, csum_actual))
 
 let verify_checksums checksums filename =
   List.iter (fun c -> verify_checksum c filename) checksums
diff --git a/mllib/checksums.mli b/mllib/checksums.mli
index 9f7041b00..5f470738a 100644
--- a/mllib/checksums.mli
+++ b/mllib/checksums.mli
@@ -43,3 +43,12 @@ val string_of_csum_t : csum_t -> string
 
 val string_of_csum : csum_t -> string
 (** Return a string representation of the checksum value. *)
+
+val compute_checksum : string -> ?tar:string -> string -> string
+(** [compute_checksum type filename] Computes the checksum of the file.
+
+    The [type] is one the possible results of the [string_of_csum_t]
+    function.
+
+    When optional [tar] is used it is path to uncompressed tar archive
+    and the [filename] is a path in the tar archive. *)
-- 
2.11.0




More information about the Libguestfs mailing list