f7c9af4ce9edae9abd4b477a6bca375f6d808a96
[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     f = None
59     try:
60         with open(dest, 'wb') as f:
61             logger.debug('Saving file to - ' + dest)
62             response = __get_url_response(url)
63             f.write(response.read())
64         return f
65     finally:
66         if f:
67             f.close()
68
69
70 def get_content_length(url):
71     """
72     Returns the number of bytes to be downloaded from the given URL
73     :param url: the URL to inspect
74     :return: the number of bytes
75     """
76     response = __get_url_response(url)
77     return response.headers['Content-Length']
78
79
80 def __get_url_response(url):
81     """
82     Returns a response object for a given URL
83     :param url: the URL
84     :return: the response
85     """
86     proxy_handler = urllib.ProxyHandler({})
87     opener = urllib.build_opener(proxy_handler)
88     urllib.install_opener(opener)
89     return urllib.urlopen(url)
90
91
92 def read_yaml(config_file_path):
93     """
94     Reads the yaml file and returns a dictionary object representation
95     :param config_file_path: The file path to config
96     :return: a dictionary
97     """
98     logger.debug('Attempting to load configuration file - ' + config_file_path)
99     with open(config_file_path) as config_file:
100         config = yaml.safe_load(config_file)
101         logger.info('Loaded configuration')
102     config_file.close()
103     logger.info('Closing configuration file')
104     return config
105
106
107 def read_os_env_file(os_env_filename):
108     """
109     Reads the OS environment source file and returns a map of each key/value
110     Will ignore lines beginning with a '#' and will replace any single or double quotes contained within the value
111     :param os_env_filename: The name of the OS environment file to read
112     :return: a dictionary
113     """
114     if os_env_filename:
115         logger.info('Attempting to read OS environment file - ' + os_env_filename)
116         out = {}
117         for line in open(os_env_filename):
118             line = line.lstrip()
119             if not line.startswith('#') and line.startswith('export '):
120                 line = line.lstrip('export ').strip()
121                 tokens = line.split('=')
122                 if len(tokens) > 1:
123                     # Remove leading and trailing ' & " characters from value
124                     out[tokens[0]] = tokens[1].lstrip('\'').lstrip('\"').rstrip('\'').rstrip('\"')
125         return out
126
127
128 def read_file(filename):
129     """
130     Returns the contents of a file as a string
131     :param filename: the name of the file
132     :return:
133     """
134     out = str()
135     for line in open(filename):
136         out += line
137
138     return out