Merge "Update heat-translator requirement"
[parser.git] / tosca2heat / tosca-parser / toscaparser / shell.py
1 #    Licensed under the Apache License, Version 2.0 (the "License"); you may
2 #    not use this file except in compliance with the License. You may obtain
3 #    a copy of the License at
4 #
5 #         http://www.apache.org/licenses/LICENSE-2.0
6 #
7 #    Unless required by applicable law or agreed to in writing, software
8 #    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 #    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 #    License for the specific language governing permissions and limitations
11 #    under the License.
12
13
14 import argparse
15 import logging
16 import os
17 import sys
18
19 from toscaparser.common.exception import ValidationError
20 from toscaparser.tosca_template import ToscaTemplate
21 from toscaparser.utils.gettextutils import _
22 import toscaparser.utils.urlutils
23
24 """
25 CLI entry point to show how TOSCA Parser can be used programmatically
26
27 This is a basic command line utility showing the entry point in the
28 TOSCA Parser and how to iterate over parsed template. It can be extended
29 or modified to fit an individual need.
30
31 It can be used as,
32 #tosca-parser --template-file=<path to the YAML template>
33 #tosca-parser --template-file=<path to the CSAR zip file>
34 #tosca-parser --template-file=<URL to the template or CSAR>
35
36 e.g.
37 #tosca-parser
38  --template-file=toscaparser/tests/data/tosca_helloworld.yaml
39 #tosca-parser
40  --template-file=toscaparser/tests/data/CSAR/csar_hello_world.zip
41 """
42
43 log = logging.getLogger("tosca.model")
44
45
46 class ParserShell(object):
47
48     def get_parser(self, argv):
49         parser = argparse.ArgumentParser(prog="tosca-parser")
50
51         parser.add_argument('--template-file',
52                             metavar='<filename>',
53                             required=True,
54                             help=_('YAML template or CSAR file to parse.'))
55
56         parser.add_argument('-nrpv', dest='no_required_paras_check',
57                             action='store_true', default=False,
58                             help=_('Ignore input parameter validation '
59                                    'when parse template.'))
60
61         parser.add_argument('--debug', dest='debug_mode',
62                             action='store_true', default=False,
63                             help=_('debug mode for print more details '
64                                    'other than raise exceptions when '
65                                    'errors happen as possible'))
66
67         return parser
68
69     def main(self, argv):
70         parser = self.get_parser(argv)
71         (args, extra_args) = parser.parse_known_args(argv)
72         path = args.template_file
73         nrpv = args.no_required_paras_check
74         debug = args.debug_mode
75
76         if os.path.isfile(path):
77             self.parse(path, no_required_paras_check=nrpv, debug_mode=debug)
78         elif toscaparser.utils.urlutils.UrlUtils.validate_url(path):
79             self.parse(path, False,
80                        no_required_paras_check=nrpv,
81                        debug_mode=debug)
82         else:
83             raise ValueError(_('"%(path)s" is not a valid file.')
84                              % {'path': path})
85
86     def parse(self, path, a_file=True, no_required_paras_check=False,
87               debug_mode=False):
88         nrpv = no_required_paras_check
89         try:
90             tosca = ToscaTemplate(path, None, a_file,
91                                   no_required_paras_check=nrpv,
92                                   debug_mode=debug_mode)
93         except ValidationError as e:
94             msg = _('  ===== main service template ===== ')
95             log.error(msg)
96             log.error(e.message)
97             if debug_mode:
98                 print(msg)
99                 print(e.message)
100             else:
101                 raise e
102
103         version = tosca.version if tosca else "unknown"
104         if tosca and tosca.version:
105             print("\nversion: " + version)
106
107         if tosca and hasattr(tosca, 'description'):
108             description = tosca.description
109             if description:
110                 print("\ndescription: " + description)
111
112         if tosca and hasattr(tosca, 'inputs'):
113             inputs = tosca.inputs
114             if inputs:
115                 print("\ninputs:")
116                 for input in inputs:
117                     print("\t" + input.name)
118
119         if tosca and hasattr(tosca, 'nodetemplates'):
120             nodetemplates = tosca.nodetemplates
121             if nodetemplates:
122                 print("\nnodetemplates:")
123                 for node in nodetemplates:
124                     print("\t" + node.name)
125
126         # example of retrieving policy object
127         '''if hasattr(tosca, 'policies'):
128             policies = tosca.policies
129             if policies:
130                 print("policies:")
131                 for policy in policies:
132                     print("\t" + policy.name)
133                     if policy.triggers:
134                         print("\ttriggers:")
135                         for trigger in policy.triggers:
136                             print("\ttrigger name:" + trigger.name)'''
137
138         if tosca and hasattr(tosca, 'outputs'):
139             outputs = tosca.outputs
140             if outputs:
141                 print("\noutputs:")
142                 for output in outputs:
143                     print("\t" + output.name)
144
145
146 def main(args=None):
147     if args is None:
148         args = sys.argv[1:]
149     ParserShell().main(args)
150
151
152 if __name__ == '__main__':
153     main()