#!/usr/bin/env python2 # Copyright 2015 Lars Wirzenius # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # =*= License: GPL-3+ =*= '''Add things to a YAML file. Read an object from a YAML file. The object must be a dictionary. Add a new value to the dictionary, or a sub-dictionary. Save the object back to its original file. Example: echo '{}' > foo.ick yaml-add foo.ick key1 key2 value This would result in: key1: key2: value If there is already a value, the value is made into a list and the new value appended to the list. If the value is already a list, the value is appended to the list. ''' import sys import yaml if len(sys.argv) < 4: sys.stderr.write('too few args\n') sys.exit(1) with open(sys.argv[1]) as f: obj = yaml.safe_load(f) keys = sys.argv[2:-1] value = sys.argv[-1] print keys print value thing = obj for key in keys[:-1]: if key not in thing: thing[key] = {} thing = thing[key] key = keys[-1] old_value = thing.get(key) if old_value is None: thing[key] = value elif type(old_value) is list: old_value.append(value) else: thing[key] = [old_value, value] with open(sys.argv[1], 'w') as f: yaml.safe_dump(obj, stream=f, default_flow_style=False, indent=4)