Allow ssh when testing via ansible
[snaps.git] / snaps / file_utils.py
index a321cc2..a7ed13c 100644 (file)
@@ -42,21 +42,12 @@ def file_exists(file_path):
     return False
 
 
-def get_file(file_path):
-    """
-    Returns True if the image file has already been downloaded
-    :return: the image file object
-    :raise Exception when file cannot be found
-    """
-    if file_exists(file_path):
-        return open(file_path, 'rb')
-    else:
-        raise Exception('File with path cannot be found - ' + file_path)
-
-
 def download(url, dest_path, name=None):
     """
     Download a file to a destination path given a URL
+    :param url: the endpoint to the file to download
+    :param dest_path: the directory to save the file
+    :param name: the file name (optional)
     :rtype : File object
     """
     if not name:
@@ -64,11 +55,22 @@ def download(url, dest_path, name=None):
     dest = dest_path + '/' + name
     logger.debug('Downloading file from - ' + url)
     # Override proxy settings to use localhost to download file
-    with open(dest, 'wb') as f:
-        logger.debug('Saving file to - ' + dest)
-        response = __get_url_response(url)
-        f.write(response.read())
-    return f
+    f = None
+
+    if not os.path.isdir(dest_path):
+        try:
+            os.mkdir(dest_path)
+        except:
+            raise
+    try:
+        with open(dest, 'wb') as f:
+            logger.debug('Saving file to - ' + os.path.abspath(f.name))
+            response = __get_url_response(url)
+            f.write(response.read())
+        return f
+    finally:
+        if f:
+            f.close()
 
 
 def get_content_length(url):
@@ -127,3 +129,16 @@ def read_os_env_file(os_env_filename):
                     # Remove leading and trailing ' & " characters from value
                     out[tokens[0]] = tokens[1].lstrip('\'').lstrip('\"').rstrip('\'').rstrip('\"')
         return out
+
+
+def read_file(filename):
+    """
+    Returns the contents of a file as a string
+    :param filename: the name of the file
+    :return:
+    """
+    out = str()
+    for line in open(filename):
+        out += line
+
+    return out