1#!/usr/bin/python2
2
3# Copyright (c) 2015, Intel Corporation
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without modification,
7# are permitted provided that the following conditions are met:
8#
9# 1. Redistributions of source code must retain the above copyright notice, this
10# list of conditions and the following disclaimer.
11#
12# 2. Redistributions in binary form must reproduce the above copyright notice,
13# this list of conditions and the following disclaimer in the documentation and/or
14# other materials provided with the distribution.
15#
16# 3. Neither the name of the copyright holder nor the names of its contributors
17# may be used to endorse or promote products derived from this software without
18# specific prior written permission.
19#
20# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
21# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
22# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
24# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
25# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
27# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31import EddParser
32from PfwBaseTranslator import PfwBaseTranslator
33
34import argparse
35import sys
36
37class PfwScriptTranslator(PfwBaseTranslator):
38
39    def __init__(self):
40        super(PfwScriptTranslator, self).__init__()
41
42        self._script = []
43
44    def getScript(self):
45        return self._script
46
47    def _doCreateDomain(self, name):
48        self._script.append(
49                "{cmd} {domain}".format(
50                cmd="createDomain",
51                domain=name))
52
53    def _doSetSequenceAware(self):
54        self._script.append(
55                "{cmd} {domain} {aware}".format(
56                cmd="setSequenceAwareness",
57                domain=self._ctx_domain,
58                aware="true"))
59
60    def _doAddElement(self, path):
61        self._script.append(
62                "{cmd} {domain} {path}".format(
63                cmd="addElement",
64                domain=self._ctx_domain,
65                path=path))
66
67    def _doCreateConfiguration(self, name):
68        self._script.append(
69                "{cmd} {domain} {config}".format(
70                cmd="createConfiguration",
71                domain=self._ctx_domain,
72                config=name))
73
74    def _doSetElementSequence(self, paths):
75        self._script.append(
76                "{cmd} {domain} {config} {paths}".format(
77                cmd="setElementSequence",
78                domain=self._ctx_domain,
79                config=self._ctx_configuration,
80                paths=" ".join(paths)))
81
82    def _doSetRule(self, rule):
83        self._script.append(
84                "{cmd} {domain} {config} {rule}".format(
85                cmd="setRule",
86                domain=self._ctx_domain,
87                config=self._ctx_configuration,
88                rule=rule))
89
90    def _doSetParameter(self, path, value):
91        self._script.append(
92                "{cmd} {domain} {config} {path} '{value}'".format(
93                cmd="setConfigurationParameter",
94                domain=self._ctx_domain,
95                config=self._ctx_configuration,
96                path=path,
97                value=value))
98
99class ArgparseArgumentParser(object) :
100    """class that parse command line arguments with argparse library
101
102    result of parsing are the class atributs"""
103    def __init__(self) :
104
105        myArgParser = argparse.ArgumentParser(description='Process domain scripts.')
106
107        myArgParser.add_argument('input', nargs='?',
108                type=argparse.FileType('r'), default=sys.stdin,
109                help="the domain script file, default stdin")
110
111        myArgParser.add_argument('-o', '--output',
112                type=argparse.FileType('w'), default=sys.stdout,
113                help="the output file, default stdout")
114
115        myArgParser.add_argument('-d', '--debug',
116                action='store_true',
117                help="print debug warnings")
118
119        myArgParser.add_argument('--output-kind',
120                choices=['pfw', 'raw'],
121                default='pfw',
122                help="output kind; can be either 'raw' (debug only) or 'pfw' (pfw commands; default choice)")
123
124
125        # process command line arguments
126        options = myArgParser.parse_args()
127
128        # maping to atributs
129        self.input = options.input
130        self.output = options.output
131
132        self.debug = options.debug
133
134        self.output_kind = options.output_kind
135
136
137# ==============
138# main function
139# ==============
140
141def printE(s):
142    """print in stderr"""
143    sys.stderr.write(str(s))
144
145def main ():
146
147    options = ArgparseArgumentParser()
148
149    myparser = EddParser.Parser()
150    try:
151        myroot = myparser.parse(options.input, options.debug)
152
153    except EddParser.MySyntaxError as ex:
154        printE(ex)
155        printE("EXIT ON FAILURE")
156        exit(2)
157
158    if options.output_kind == 'raw':
159        options.output.write(str(myroot))
160    else:
161        try:
162            myroot.propagate()
163
164        except EddParser.MyPropagationError, ex :
165            printE(ex)
166            printE("EXIT ON FAILURE")
167            exit(1)
168
169        if options.output_kind == 'pfw':
170            translator = PfwScriptTranslator()
171            myroot.translate(translator)
172            options.output.write("\n".join(translator.getScript()))
173
174# execute main function if the python interpreter is running this module as the main program
175if __name__ == "__main__" :
176    main()
177
178