1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2024-09-14 20:13:21 +02:00

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.
This commit is contained in:
Stephen Fromm 2012-06-14 07:18:46 -07:00
parent 2a8d1f07d4
commit 4a6a3fd305

View file

@ -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)