[Libguestfs] [PATCH v3 01/10] mllib: factorize code to add Checksum.get_checksum function

Cédric Bosdonnat
Fri, 10 Feb 2017 15:05:56 -0000

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, 24 insertions(+), 10 deletions(-)

diff --git a/mllib/checksums.ml b/mllib/checksums.ml
index 1009e131c..000214703 100644
--- a/mllib/checksums.ml
+++ b/mllib/checksums.ml
@@ -45,14 +45,14 @@ 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 -    match csum
with
-    | SHA1 c -> "sha1sum", c
-    | SHA256 c -> "sha256sum", c
-    | SHA512 c -> "sha512sum", c
+let compute_checksum csum_type ?tar filename +  let prog +    match csum_type
with
+    | "sha1" -> "sha1sum"
+    | "sha256" -> "sha256sum"
+    | "sha512" -> "sha512sum"
+    | _ -> error (f_"unhandled checksum type '%s'")
csum_type
   in
-
   let cmd      match tar with
     | None ->
@@ -66,9 +66,14 @@ 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))
+    let csum_str = fst (String.split " " line) in
+    of_string csum_type csum_str
+
+let verify_checksum csum ?tar filename +  let csum_type = string_of_csum_t csum
in
+  let csum_actual = compute_checksum csum_type ?tar filename in
+  if csum <> csum_actual then
+    raise (Mismatched_checksum (csum, (string_of_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..92336a18b 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 -> csum_t
+(** [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