Utils: Create a generic hash function for autotest

In order to get rid of md5/sha deprecation messages
when using python 2.6 and keeping 2.4 working, a
new function called utils.hash() was created: This
function abstracts the complexity of conditional
importing and can be used throughout autotest in
pretty much all the scenarios where an md5 or sha1
hash is needed.

The function returns a hash object, so if you want
the digest or hexdigest of the whole content you
need to explicitly call hexdigest(). This was made
because in some occasions we don't want to calculate
the digest straight away, rather we update the hash
with content until the point we can evaluate the
digest.

By the way, the name chosen does not clash with the
API of neither py 2.6 hashlib nor py 2.4 md5 or sha.

Signed-off-by: Lucas Meneghel Rodrigues <lmr@redhat.com>


git-svn-id: http://test.kernel.org/svn/autotest/trunk@4203 592f7852-d20e-0410-864c-8624ca9c26a4
diff --git a/client/common_lib/utils.py b/client/common_lib/utils.py
index 12e66c6..b42415e 100644
--- a/client/common_lib/utils.py
+++ b/client/common_lib/utils.py
@@ -4,6 +4,10 @@
 import os, pickle, random, re, resource, select, shutil, signal, StringIO
 import socket, struct, subprocess, sys, time, textwrap, urlparse
 import warnings, smtplib, logging, urllib2
+try:
+    import hashlib
+except ImportError:
+    import md5, sha
 from autotest_lib.client.common_lib import error, barrier, logging_manager
 
 def deprecated(func):
@@ -278,6 +282,36 @@
         src_file.close()
 
 
+def hash(type, input=None):
+    """
+    Returns an hash object of type md5 or sha1. This function is implemented in
+    order to encapsulate hash objects in a way that is compatible with python
+    2.4 and python 2.6 without warnings.
+
+    Note that even though python 2.6 hashlib supports hash types other than
+    md5 and sha1, we are artificially limiting the input values in order to
+    make the function to behave exactly the same among both python
+    implementations.
+
+    @param input: Optional input string that will be used to update the hash.
+    """
+    if type not in ['md5', 'sha1']:
+        raise ValueError("Unsupported hash type: %s" % type)
+
+    try:
+        hash = hashlib.new(type)
+    except NameError:
+        if type == 'md5':
+            hash = md5.new()
+        elif type == 'sha1':
+            hash = sha.new()
+
+    if input:
+        hash.update(input)
+
+    return hash
+
+
 def get_file(src, dest, permissions=None):
     """Get a file from src, which can be local or a remote URL"""
     if src == dest:
@@ -620,7 +654,7 @@
     @param ignore_status: if ignore_status=False, throw an exception if the
             command's exit code is non-zero
             if ignore_stauts=True, return the exit code.
-    
+
     @return exit status of command
             (note, this will always be zero unless ignore_status=True)
     """