summaryrefslogtreecommitdiffstats
path: root/roles/mailman/files/yamlget
blob: 68a5876bf9d779bd7e1184a30f884c39fef01d78 (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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#!/usr/bin/env python
# vim: set fileencoding=utf-8 tabstop=4 shiftwidth=4 expandtab smartindent:

u"""
yamlget
-------

Output any key in a YAML-formatted file. The aim is to make such a
configuration file accessible to shell scripts.

.. :Authors:
      Aurélien Bompard <aurelien@bompard.org> <http://aurelien.bompard.org>

.. :License:
      GNU GPL v3 or later
"""

from __future__ import print_function

import os
import sys
from optparse import OptionParser

import yaml


def get_key(fullkey, data):
    """
    Get the requested key from the parsed data.
    :param fullkey: the key to get, nested values can be accessed by using a
                    colon (":") as the separator
    :param data: the parsed data, from yaml.load()

    Examples:

    >>> data = {
    ...  'bool': [True, False, True, False],
    ...  'dict': {'hp': 13, 'sp': 5},
    ...  'float': 3.14159,
    ...  'int': 42,
    ...  'list': ['LITE', 'RES_ACID', 'SUS_DEXT'],
    ...  'none': [None, None],
    ...  'text': "The Set of Gauntlets 'Pauraegen'",
    ... }
    >>> get_key('bool', data)
    [True, False, True, False]
    >>> get_key('bool:2', data)
    False
    >>> get_key('dict', data)
    {'hp': 13, 'sp': 5}
    >>> get_key('dict:hp', data)
    13
    >>> get_key('float', data)
    3.14159
    >>> get_key('int', data)
    42
    >>> get_key('list', data)
    ['LITE', 'RES_ACID', 'SUS_DEXT']
    >>> get_key('list:2', data)
    'RES_ACID'
    >>> get_key('list:2:5', data)
    'RES_ACID'
    >>> get_key('none', data)
    [None, None]
    >>> get_key('none:1', data)
    >>> get_key('text', data)
    "The Set of Gauntlets 'Pauraegen'"
    >>> get_key('2', ['item1', 'item2', 'item3'])
    'item2'
    """

    value = data
    while value is not None:
        key, _sep, fullkey = fullkey.partition(":")
        if isinstance(value, list):
            try:
                key = int(key)
            except TypeError:
                print("Wrong key format: %s, it should be an integer" % key,
                      file=sys.stderr)
                sys.exit(1)
            value = value[key - 1] # start at 1, not 0
        elif isinstance(value, dict):
            value = value.get(key)
        else:
            break # we've got the value now
        if not fullkey:
            break # can't go any further
    return value

def main():
    parser = OptionParser(usage="%prog <key> <yaml-file>")
    args = parser.parse_args()[1]
    if len(args) != 2:
        parser.error("wrong number of arguments")
    fullkey, filepath = args
    if not os.path.exists(filepath):
        parser.error("no such file: %s" % filepath)

    with open(filepath) as yamlfile:
        data = yaml.safe_load_all(yamlfile).next()

    #from pprint import pprint; pprint(data)
    value = get_key(fullkey, data)
    if value is not None:
        print(value)


if __name__ == "__main__":
    main()