Source code for uw.local.deploy.environment

"""Environment-related routines for system deployment.

This includes functions for combining environment settings from various
sources and updating the OS environ accordingly.
"""

import os
import re

env_re = re.compile ('^\s*(?P<var>\w+)\s*=\s*(?P<value>[-.\w]*)\s*$', flags=re.A)

[docs]def parse_environment (fp, fname): """Parse a file for environment settings. :param fp: An iterable of text lines. :param fname: The filename, for use in error reporting. :return: A dictionary of environment settings parsed from the file. """ result = {} for i, line in enumerate (fp, start=1): m = env_re.match (line) if m is not None: result[m.group ('var')] = m.group ('value') else: raise ValueError ('Unable to parse line %d of environment file "%s"' % (i, fname)) return result
[docs]def combine_environment (*args): """Combine environment settings from various sources. :param \*args: Sources of environment settings, either a filename to parse or a dictionary of predetermined settings. :return: A dictionary of the combined settings. Combine the given predetermined settings and settings parsed from the specified files into a single dictionary. """ result = {} for source in args: if isinstance (source, dict): # Pre-determined environment values d = source elif isinstance (source, str): # Filename to parse d = parse_environment (open (source), source) else: raise TypeError ('combine_environment() args must be dict or str') result.update (d) return result
[docs]def import_environment (*args): """Update the OS environ from settings. :param \*args: Sources of environment settings, either a filename to parse or a dictionary of predetermined settings. Use :func:`combine_environment` to combine the sources and update the OS environ from the combined settings. """ os.environ.update (combine_environment (*args))