7b93a6dea4d6d0d0fe070232900df057c5fe93e9
[snaps.git] / snaps / file_utils.py
1 # Copyright (c) 2017 Cable Television Laboratories, Inc. ("CableLabs")
2 #                    and others.  All rights reserved.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at:
7 #
8 #     http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 import os
16 import logging
17 try:
18     import urllib.request as urllib
19 except ImportError:
20     import urllib2 as urllib
21
22 import yaml
23
24 __author__ = 'spisarski'
25
26 """
27 Utilities for basic file handling
28 """
29
30 logger = logging.getLogger('file_utils')
31
32
33 def file_exists(file_path):
34     """
35     Returns True if the image file already exists and throws an exception if the path is a directory
36     :return:
37     """
38     if os.path.exists(file_path):
39         if os.path.isdir(file_path):
40             return False
41         return os.path.isfile(file_path)
42     return False
43
44
45 def download(url, dest_path, name=None):
46     """
47     Download a file to a destination path given a URL
48     :param url: the endpoint to the file to download
49     :param dest_path: the directory to save the file
50     :param name: the file name (optional)
51     :rtype : File object
52     """
53     if not name:
54         name = url.rsplit('/')[-1]
55     dest = dest_path + '/' + name
56     logger.debug('Downloading file from - ' + url)
57     # Override proxy settings to use localhost to download file
58     with open(dest, 'wb') as f:
59         logger.debug('Saving file to - ' + dest)
60         response = __get_url_response(url)
61         f.write(response.read())
62     return f
63
64
65 def get_content_length(url):
66     """
67     Returns the number of bytes to be downloaded from the given URL
68     :param url: the URL to inspect
69     :return: the number of bytes
70     """
71     response = __get_url_response(url)
72     return response.headers['Content-Length']
73
74
75 def __get_url_response(url):
76     """
77     Returns a response object for a given URL
78     :param url: the URL
79     :return: the response
80     """
81     proxy_handler = urllib.ProxyHandler({})
82     opener = urllib.build_opener(proxy_handler)
83     urllib.install_opener(opener)
84     return urllib.urlopen(url)
85
86
87 def read_yaml(config_file_path):
88     """
89     Reads the yaml file and returns a dictionary object representation
90     :param config_file_path: The file path to config
91     :return: a dictionary
92     """
93     logger.debug('Attempting to load configuration file - ' + config_file_path)
94     with open(config_file_path) as config_file:
95         config = yaml.safe_load(config_file)
96         logger.info('Loaded configuration')
97     config_file.close()
98     logger.info('Closing configuration file')
99     return config
100
101
102 def read_os_env_file(os_env_filename):
103     """
104     Reads the OS environment source file and returns a map of each key/value
105     Will ignore lines beginning with a '#' and will replace any single or double quotes contained within the value
106     :param os_env_filename: The name of the OS environment file to read
107     :return: a dictionary
108     """
109     if os_env_filename:
110         logger.info('Attempting to read OS environment file - ' + os_env_filename)
111         out = {}
112         for line in open(os_env_filename):
113             line = line.lstrip()
114             if not line.startswith('#') and line.startswith('export '):
115                 line = line.lstrip('export ').strip()
116                 tokens = line.split('=')
117                 if len(tokens) > 1:
118                     # Remove leading and trailing ' & " characters from value
119                     out[tokens[0]] = tokens[1].lstrip('\'').lstrip('\"').rstrip('\'').rstrip('\"')
120         return out