Corey Bryant 110b773d98 Move common utility functions to Utils class
Common utility functions that were defined in base.py are moved to their
own Utils class. Additionally this patch adds some checks to ensure keys
exist in setup() before attempting to access them.

Change-Id: Ib940eefce140e3552f41ff0e32123ae90fe81fe4
2017-04-06 17:34:48 +00:00

75 lines
2.2 KiB
Python

#!/usr/bin/env python
# Copyright 2016 Canonical UK Limited
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging
import os
LOG = logging.getLogger(__name__)
SNAP_ENV = ['SNAP_NAME',
'SNAP_VERSION',
'SNAP_REVISION',
'SNAP_ARCH',
'SNAP_LIBRARY_PATH',
'SNAP',
'SNAP_DATA',
'SNAP_COMMON',
'SNAP_USER_DATA',
'SNAP_USER_COMMON',
'TMPDIR']
class SnapUtils(object):
'''Class for common utilities'''
def __init__(self):
self._snap_env = self._collect_snap_env()
def _collect_snap_env(self):
'''Collect SNAP* environment variables
@return dict of all SNAP* environment variables indexed in lower case
'''
_env = {}
for key in SNAP_ENV:
_env[key.lower()] = os.environ.get(key)
LOG.info('Snap environment: {}'.format(_env))
return _env
@property
def snap_env(self):
'''Return SNAP* environment variables
@return dict of all SNAP* environment variables indexed in lower case
'''
return self._snap_env
def ensure_dir(self, path, is_file=False):
'''Ensure a directory exists
Ensure that the directory structure to support the provided file or
directory exists.
@param path: string containing full path to file or directory
@param is_file: true if directory name needs to be determined for file
'''
dir_name = path
if is_file:
dir_name = os.path.dirname(path)
if not os.path.exists(dir_name):
LOG.info('Creating directory {}'.format(dir_name))
os.makedirs(dir_name, 0o750)