From 4a6a3fd305872707fa55a1fe866db274586c18a6 Mon Sep 17 00:00:00 2001 From: Stephen Fromm Date: Thu, 14 Jun 2012 07:18:46 -0700 Subject: [PATCH] Conditionally import hashlib (issue #471) Import hashlib if it is there, otherwise import md5. Adds method file_digest that wraps the logic on which module to invoke. --- library/assemble | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/library/assemble b/library/assemble index fcfd6bf52c..23c50221b2 100755 --- a/library/assemble +++ b/library/assemble @@ -23,12 +23,17 @@ except ImportError: import simplejson as json import os import os.path -import md5 import sys import shlex import shutil import syslog import tempfile +try: + import hashlib + HAVE_HASHLIB=True +except ImportError: + import md5 + HAVE_HASHLIB=False # Since hashlib is only available in 2.5 and onwards, this module # uses md5 which is available in 2.4. @@ -59,6 +64,13 @@ def write_temp_file(data): os.close(fd) return path +def file_digest(path): + if HAVE_HASHLIB: + digest = hashlib.md5(file(path).read()).hexdigest() + else: + digest = md5.new(file(path).read()).hexdigest() + return digest + # =========================================== if len(sys.argv) == 1: @@ -99,10 +111,10 @@ if not os.path.isdir(src): fail_json(msg="Source (%s) is not a directory" % src) path = write_temp_file(assemble_from_fragments(src)) -pathmd5 = md5.new(file(path).read()).hexdigest() +pathmd5 = file_digest(path) if os.path.exists(dest): - destmd5 = md5.new(file(dest).read()).hexdigest() + destmd5 = file_digest(dest) if pathmd5 != destmd5: shutil.copy(path, dest)