diff options
author | Richard Maw <richard.maw@codethink.co.uk> | 2013-08-13 09:53:32 +0000 |
---|---|---|
committer | Richard Maw <richard.maw@codethink.co.uk> | 2013-08-13 14:21:52 +0000 |
commit | ec6d4e10304293157ba61501b7f053cb1cbc142a (patch) | |
tree | 144869b0f95956aac6756ad3016221580f835028 /morphlib/util.py | |
parent | c38b5ddeb6359f6f848553bcfdde52365c807ab4 (diff) | |
download | morph-ec6d4e10304293157ba61501b7f053cb1cbc142a.tar.gz |
deploy: refactor environment argument parsing
It is now a tested helper function in morphlib.util
Diffstat (limited to 'morphlib/util.py')
-rw-r--r-- | morphlib/util.py | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/morphlib/util.py b/morphlib/util.py index ead0bafe..b83211e3 100644 --- a/morphlib/util.py +++ b/morphlib/util.py @@ -327,3 +327,35 @@ def find_leaf(dirname, subdir_name): return None dirname = subdirs[0] + +class EnvironmentAlreadySetError(morphlib.Error): + + def __init__(self, conflicts): + self.conflicts = conflicts + morphlib.Error.__init__( + self, 'Keys %r are already set in the environment' % conflicts) + + +def parse_environment_pairs(env, pairs): + '''Add key=value pairs to the environment dict. + + Given a dict and a list of strings of the form key=value, + set dict[key] = value, unless key is already set in the + environment, at which point raise an exception. + + This does not modify the passed in dict. + + Returns the extended dict. + + ''' + + extra_env = dict(p.split('=', 1) for p in pairs) + conflicting = [k for k in extra_env if k in env] + if conflicting: + raise EnvironmentAlreadySetError(conflicting) + + # Return a dict that is the union of the two + # This is not the most performant, since it creates + # 3 unnecessary lists, but I felt this was the most + # easy to read. Using itertools.chain may be more efficicent + return dict(env.items() + extra_env.items()) |