Add image-properties support in helper
[snf-image] / snf-image-helper / decode-properties.py
1 #!/usr/bin/env python
2
3 """Decode a json encoded string with properties
4
5 This program decodes a json encoded properties string and outputs it in a
6 bash sourcable way. The properties are passed to the program through a JSON
7 string either read from a file or from standard input and are outputed to a
8 target file.
9 """
10
11 import sys
12 import os
13 import subprocess
14 import json
15 from StringIO import StringIO
16 from optparse import OptionParser
17
18 def parse_arguments(input_args):
19     usage = "Usage: %prog [options] <output_file>"
20     parser = OptionParser(usage=usage)
21     parser.add_option("-i", "--input",
22                         action="store",type='string', dest="input_file",
23                         help="get input from FILE instead of stdin",
24                         metavar="FILE")
25
26     opts, args = parser.parse_args(input_args)
27
28     if len(args) != 1:
29         parser.error('output file is missing')
30     output_file = args[0]
31    
32     if opts.input_file is not None:
33         if not os.path.isfile(opts.input_file):
34             parser.error('input file does not exist')
35  
36     return (opts.input_file, output_file)
37
38
39 def main():
40     (input_file, output_file) = parse_arguments(sys.argv[1:])
41
42     infh = sys.stdin if input_file is None else open(input_file, 'r')
43     outfh = open(output_file, 'w')
44
45     properties = json.load(infh)
46     for key, value in properties.items():
47         os.environ['SNF_IMAGE_PROPERTY_' + key] = value
48
49     output = StringIO(subprocess.check_output(['bash', '-c', 'set']))
50     for line in iter(output):
51         if line.startswith('SNF_IMAGE_PROPERTY_'):
52             outfh.write(line)
53
54     infh.close()
55     outfh.close()
56     return 0
57
58
59 if __name__ == "__main__":
60     sys.exit(main())
61
62 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :