f669e273b1ae84e5e9792b8ec121550569b642a9
[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_valid',
57                             action='store_true', default=False,
58                             help=_('Ignore input parameter validation '
59                                    'when parse template.'))
60
61         return parser
62
63     def main(self, argv):
64         parser = self.get_parser(argv)
65         (args, extra_args) = parser.parse_known_args(argv)
66         path = args.template_file
67         nrpv = args.no_required_paras_valid
68         if os.path.isfile(path):
69             self.parse(path, no_req_paras_valid=nrpv)
70         elif toscaparser.utils.urlutils.UrlUtils.validate_url(path):
71             self.parse(path, False, no_req_paras_valid=nrpv)
72         else:
73             raise ValueError(_('"%(path)s" is not a valid file.')
74                              % {'path': path})
75
76     def parse(self, path, a_file=True, no_req_paras_valid=False):
77         output = None
78         tosca = None
79         try:
80             tosca = ToscaTemplate(path, None, a_file,
81                                   no_required_paras_valid=no_req_paras_valid)
82         except ValidationError as e:
83             msg = _('  ===== main service template ===== ')
84             log.error(msg)
85             log.error(e.message)
86             raise e
87
88         version = tosca.version
89         if tosca.version:
90             print("\nversion: " + version)
91
92         if hasattr(tosca, 'description'):
93             description = tosca.description
94             if description:
95                 print("\ndescription: " + description)
96
97         if hasattr(tosca, 'inputs'):
98             inputs = tosca.inputs
99             if inputs:
100                 print("\ninputs:")
101                 for input in inputs:
102                     print("\t" + input.name)
103
104         if hasattr(tosca, 'nodetemplates'):
105             nodetemplates = tosca.nodetemplates
106             if nodetemplates:
107                 print("\nnodetemplates:")
108                 for node in nodetemplates:
109                     print("\t" + node.name)
110
111         # example of retrieving policy object
112         '''if hasattr(tosca, 'policies'):
113             policies = tosca.policies
114             if policies:
115                 print("policies:")
116                 for policy in policies:
117                     print("\t" + policy.name)
118                     if policy.triggers:
119                         print("\ttriggers:")
120                         for trigger in policy.triggers:
121                             print("\ttrigger name:" + trigger.name)'''
122
123         if hasattr(tosca, 'outputs'):
124             outputs = tosca.outputs
125             if outputs:
126                 print("\noutputs:")
127                 for output in outputs:
128                     print("\t" + output.name)
129
130
131 def main(args=None):
132     if args is None:
133         args = sys.argv[1:]
134     ParserShell().main(args)
135
136
137 if __name__ == '__main__':
138     main()