[Libguestfs] [PATCH 2/5] mllib: factorize code to add Checksum.get_checksum function

Cédric Bosdonnat cbosdonnat at suse.com
Tue Jan 3 10:18:53 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  | 20 +++++++++-----------
 mllib/checksums.mli |  3 +++
 2 files changed, 12 insertions(+), 11 deletions(-)

diff --git a/mllib/checksums.ml b/mllib/checksums.ml
index dfa8c3ae7..3efc764b9 100644
--- a/mllib/checksums.ml
+++ b/mllib/checksums.ml
@@ -45,23 +45,21 @@ let of_string csum_type csum_value =
   | "sha512" -> SHA512 csum_value
   | _ -> invalid_arg csum_type
 
-let verify_checksum csum filename =
-  let prog, csum_ref =
-    match csum with
-    | SHA1 c -> "sha1sum", c
-    | SHA256 c -> "sha256sum", c
-    | SHA512 c -> "sha512sum", c
-  in
-
+let get_checksum csum filename =
+  let prog = (string_of_csum_t csum) ^ "sum" in
   let cmd = sprintf "%s %s" prog (Filename.quote filename) in
   let lines = external_command cmd in
   match lines with
   | [] ->
     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 verify_checksum csum filename =
+  let csum_ref = string_of_csum csum in
+  let csum_actual = get_checksum csum 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 0074837b3..e09d61890 100644
--- a/mllib/checksums.mli
+++ b/mllib/checksums.mli
@@ -40,3 +40,6 @@ val string_of_csum_t : csum_t -> string
 
 val string_of_csum : csum_t -> string
 (** Return a string representation of the checksum value. *)
+
+val get_checksum : csum_t -> string -> string
+(** Computes the checksum of the file. *)
-- 
2.11.0




More information about the Libguestfs mailing list