diff options
author | Richard Ipsum <richard.ipsum@codethink.co.uk> | 2015-03-18 16:56:30 +0000 |
---|---|---|
committer | Richard Ipsum <richard.ipsum@codethink.co.uk> | 2015-03-18 16:56:30 +0000 |
commit | a6cd694fdbd08e79b279cc77f9e891b67aeed04e (patch) | |
tree | c80be54185fc9cddb06b5eba90eeccd7de6c222d /morphlib/util.py | |
parent | 283f6c08eeb8657a65cdec6a4f605c356130c17d (diff) | |
parent | f682482396bcbdded7a3a342c68d792dd4bd791f (diff) | |
download | morph-a6cd694fdbd08e79b279cc77f9e891b67aeed04e.tar.gz |
Merge branch 'baserock/richardipsum/add-hosts-conf-ext-v3'
Reviewed by:
Richard Maw <richard.maw@gmail.com> (+2)
Pedro Alvarez <pedro.alvarez@codethink.co.uk> (v2) (+1)
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 a3a07cce..e733af9d 100644 --- a/morphlib/util.py +++ b/morphlib/util.py @@ -644,3 +644,35 @@ def error_message_for_containerised_commandline( 'Containerisation settings: %s\n' \ 'Error output:\n%s' \ % (argv_string, container_kwargs, err) + + +def write_from_dict(filepath, d, validate=lambda x, y: True): #pragma: no cover + '''Takes a dictionary and appends the contents to a file + + An optional validation callback can be passed to perform validation on + each value in the dictionary. + + e.g. + + def validation_callback(dictionary_key, dictionary_value): + if not dictionary_value.isdigit(): + raise Exception('value contains non-digit character(s)') + + Any callback supplied to this function should raise an exception + if validation fails. + ''' + + # Sort items asciibetically + # the output of the deployment should not depend + # on the locale of the machine running the deployment + items = sorted(d.iteritems(), key=lambda (k, v): [ord(c) for c in v]) + + for (k, v) in items: + validate(k, v) + + with open(filepath, 'a') as f: + for (_, v) in items: + f.write('%s\n' % v) + + os.fchown(f.fileno(), 0, 0) + os.fchmod(f.fileno(), 0644) |