blob: b6d375c60dc03d07eb2948c0e45a8b599c054303 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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)
|