root / snf-image-helper / decode-properties.py @ 21be5a41
History | View | Annotate | Download (2.5 kB)
1 |
#!/usr/bin/env python
|
---|---|
2 |
|
3 |
# Copyright (C) 2011 GRNET S.A.
|
4 |
#
|
5 |
# This program is free software; you can redistribute it and/or modify
|
6 |
# it under the terms of the GNU General Public License as published by
|
7 |
# the Free Software Foundation; either version 2 of the License, or
|
8 |
# (at your option) any later version.
|
9 |
#
|
10 |
# This program is distributed in the hope that it will be useful, but
|
11 |
# WITHOUT ANY WARRANTY; without even the implied warranty of
|
12 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
13 |
# General Public License for more details.
|
14 |
#
|
15 |
# You should have received a copy of the GNU General Public License
|
16 |
# along with this program; if not, write to the Free Software
|
17 |
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
|
18 |
# 02110-1301, USA.
|
19 |
|
20 |
"""Decode a json encoded string with properties
|
21 |
|
22 |
This program decodes a json encoded properties string and outputs it in a
|
23 |
bash sourcable way. The properties are passed to the program through a JSON
|
24 |
string either read from a file or from standard input and are outputed to a
|
25 |
target file.
|
26 |
"""
|
27 |
|
28 |
import sys |
29 |
import os |
30 |
import subprocess |
31 |
import json |
32 |
from StringIO import StringIO |
33 |
from optparse import OptionParser |
34 |
|
35 |
def parse_arguments(input_args): |
36 |
usage = "Usage: %prog [options] <output_file>"
|
37 |
parser = OptionParser(usage=usage) |
38 |
parser.add_option("-i", "--input", |
39 |
action="store",type='string', dest="input_file", |
40 |
help="get input from FILE instead of stdin",
|
41 |
metavar="FILE")
|
42 |
|
43 |
opts, args = parser.parse_args(input_args) |
44 |
|
45 |
if len(args) != 1: |
46 |
parser.error('output file is missing')
|
47 |
output_file = args[0]
|
48 |
|
49 |
if opts.input_file is not None: |
50 |
if not os.path.isfile(opts.input_file): |
51 |
parser.error('input file does not exist')
|
52 |
|
53 |
return (opts.input_file, output_file)
|
54 |
|
55 |
|
56 |
def main(): |
57 |
(input_file, output_file) = parse_arguments(sys.argv[1:])
|
58 |
|
59 |
infh = sys.stdin if input_file is None else open(input_file, 'r') |
60 |
outfh = open(output_file, 'w') |
61 |
|
62 |
properties = json.load(infh) |
63 |
for key, value in properties.items(): |
64 |
os.environ['SNF_IMAGE_PROPERTY_' + key] = value
|
65 |
|
66 |
p = subprocess.Popen(['bash', '-c', 'set'], stdout=subprocess.PIPE) |
67 |
output = StringIO(p.communicate()[0]);
|
68 |
for line in iter(output): |
69 |
if line.startswith('SNF_IMAGE_PROPERTY_'): |
70 |
outfh.write('export ' + line)
|
71 |
|
72 |
infh.close() |
73 |
outfh.close() |
74 |
return 0 |
75 |
|
76 |
|
77 |
if __name__ == "__main__": |
78 |
sys.exit(main()) |
79 |
|
80 |
# vim: set sta sts=4 shiftwidth=4 sw=4 et ai :
|