diff options
author | Lars Wirzenius <liw@liw.fi> | 2015-05-09 11:06:51 +0300 |
---|---|---|
committer | Lars Wirzenius <liw@liw.fi> | 2015-05-09 11:52:54 +0300 |
commit | 0e8bbdf268eb1cb42f8ef9792fb51ec0b915d0e1 (patch) | |
tree | 488a9f34e77562a111b01882dec89c04e366af0b /yaml-add | |
parent | d4e1e667ceac1023c2ac69410dfc5c71147cd400 (diff) | |
download | ick-0e8bbdf268eb1cb42f8ef9792fb51ec0b915d0e1.tar.gz |
Add helper script to add things to YAML
Diffstat (limited to 'yaml-add')
-rwxr-xr-x | yaml-add | 78 |
1 files changed, 78 insertions, 0 deletions
diff --git a/yaml-add b/yaml-add new file mode 100755 index 0000000..b6d375c --- /dev/null +++ b/yaml-add @@ -0,0 +1,78 @@ +#!/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 <http://www.gnu.org/licenses/>. +# +# =*= 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) |