c468499e12291dbaf80efbdff8f2e0b61c9022ac
[invirt/packages/invirt-base.git] / files / usr / sbin / invirt-getconf
1 #!/usr/bin/env python2.5
2
3 """
4 invirt-getconf [-f FILE] KEY prints the configuration the option named KEY from
5 the invirt configuration file FILE.  Keys are dot-separated paths into the YAML
6 configuration tree.  List indexes (0-based) are also treated as path
7 components.
8
9 (Due to this path language, certain restrictions are placed on the keys used in
10 the YAML configuration, e.g. they cannot contain dots.)
11
12 Examples:
13
14   invirt-getconf db.uri
15   invirt-getconf authn.0.type
16 """
17
18 from invirt.config import load
19 from sys import argv, exit, stderr
20 from optparse import OptionParser
21
22 class invirt_exception( Exception ): pass
23
24 def main( argv ):
25     try:
26         parser = OptionParser()
27         parser.add_option('-f', '--file', default = '/etc/invirt/master.yaml',
28                 help = 'the configuration file to read from')
29         options, args = parser.parse_args()
30
31         try: [key] = args
32         except: raise invirt_exception( __doc__ )
33
34         conf = load()
35         components = key.split('.')
36         for i, component in enumerate( components ):
37             progress = lambda: '.'.join( components[:i] )
38             if type( conf ) not in [ dict, list ]:
39                 raise invirt_exception(
40                         'prematurely arrived at an atomic datum in the tree:\n'
41                         '%s has no children' % progress() )
42             if type( conf ) == list:
43                 try: component = int( component )
44                 except: raise invirt_exception(
45                         '%s is a list, requires an integral path component '
46                         'but got "%s"' % ( progress(), component ) )
47             try: conf = conf[ component ]
48             except KeyError: raise invirt_exception(
49                     '"%s" not in "%s"' % ( component, progress() ) )
50         print conf
51     except invirt_exception, ex:
52         print >> stderr, ex
53         return 1
54
55 if __name__ == '__main__': exit( main( argv ) )
56
57 # vim:et:sw=4:ts=4