blob: a9ee25f99098561c8da37feef799170f8eef3540 [file] [log] [blame]
Igor Murashkin96bd0192012-11-19 16:49:37 -08001#!/usr/bin/python
2
3#
4# Copyright (C) 2012 The Android Open Source Project
5#
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17#
18
19"""
20A parser for metadata_properties.xml can also render the resulting model
21over a Mako template.
22
23Usage:
Igor Murashkin617da162012-11-29 13:35:15 -080024 metadata_parser_xml.py <filename.xml> <template.mako>
Igor Murashkin96bd0192012-11-19 16:49:37 -080025 - outputs the resulting template to stdout
26
27Module:
28 The parser is also available as a module import (MetadataParserXml) to use
29 in other modules.
30
31Dependencies:
32 BeautifulSoup - an HTML/XML parser available to download from
33 http://www.crummy.com/software/BeautifulSoup/
34 Mako - a template engine for Python, available to download from
35 http://www.makotemplates.org/
36"""
37
38import sys
Igor Murashkinda1c3142012-11-21 17:11:37 -080039import os
40import StringIO
Igor Murashkin96bd0192012-11-19 16:49:37 -080041
42from bs4 import BeautifulSoup
43from bs4 import NavigableString
44
45from mako.template import Template
Igor Murashkinda1c3142012-11-21 17:11:37 -080046from mako.lookup import TemplateLookup
47from mako.runtime import Context
Igor Murashkin96bd0192012-11-19 16:49:37 -080048
49from metadata_model import *
Igor Murashkin617da162012-11-29 13:35:15 -080050import metadata_model
Igor Murashkin96bd0192012-11-19 16:49:37 -080051from metadata_validate import *
Igor Murashkinda1c3142012-11-21 17:11:37 -080052import metadata_helpers
Igor Murashkin96bd0192012-11-19 16:49:37 -080053
54class MetadataParserXml:
55 """
56 A class to parse any XML file that passes validation with metadata-validate.
57 It builds a metadata_model.Metadata graph and then renders it over a
58 Mako template.
59
60 Attributes (Read-Only):
61 soup: an instance of BeautifulSoup corresponding to the XML contents
62 metadata: a constructed instance of metadata_model.Metadata
63 """
64 def __init__(self, file_name):
65 """
66 Construct a new MetadataParserXml, immediately try to parse it into a
67 metadata model.
68
69 Args:
70 file_name: path to an XML file that passes metadata-validate
71
72 Raises:
73 ValueError: if the XML file failed to pass metadata_validate.py
74 """
75 self._soup = validate_xml(file_name)
76
77 if self._soup is None:
78 raise ValueError("%s has an invalid XML file" %(file_name))
79
80 self._metadata = Metadata()
81 self._parse()
82 self._metadata.construct_graph()
83
84 @property
85 def soup(self):
86 return self._soup
87
88 @property
89 def metadata(self):
90 return self._metadata
91
92 @staticmethod
93 def _find_direct_strings(element):
94 if element.string is not None:
95 return [element.string]
96
97 return [i for i in element.contents if isinstance(i, NavigableString)]
98
99 @staticmethod
100 def _strings_no_nl(element):
101 return "".join([i.strip() for i in MetadataParserXml._find_direct_strings(element)])
102
103 def _parse(self):
104
105 tags = self.soup.tags
106 if tags is not None:
107 for tag in tags.find_all('tag'):
108 self.metadata.insert_tag(tag['id'], tag.string)
109
110 for entry in self.soup.find_all("entry"):
111 d = {
112 'name': fully_qualified_name(entry),
113 'type': entry['type'],
114 'kind': find_kind(entry),
115 'type_notes': entry.attrs.get('type_notes')
116 }
117
118 d2 = self._parse_entry(entry)
119 d3 = self._parse_entry_optional(entry)
120
121 entry_dict = dict(d.items() + d2.items() + d3.items())
122 self.metadata.insert_entry(entry_dict)
123
124 entry = None
125
126 for clone in self.soup.find_all("clone"):
127 d = {
128 'name': clone['entry'],
129 'kind': find_kind(clone),
130 'target_kind': clone['kind'],
131 # no type since its the same
132 # no type_notes since its the same
133 }
134
135 d2 = self._parse_entry_optional(clone)
136 clone_dict = dict(d.items() + d2.items())
137 self.metadata.insert_clone(clone_dict)
138
139 self.metadata.construct_graph()
140
141 def _parse_entry(self, entry):
142 d = {}
143
144 #
145 # Enum
146 #
147 if entry['type'] == 'enum':
148
149 enum_values = []
150 enum_optionals = []
151 enum_notes = {}
152 enum_ids = {}
153 for value in entry.enum.find_all('value'):
154
155 value_body = self._strings_no_nl(value)
156 enum_values.append(value_body)
157
158 if value.attrs.get('optional', 'false') == 'true':
159 enum_optionals.append(value_body)
160
161 notes = value.find('notes')
162 if notes is not None:
163 enum_notes[value_body] = notes.string
164
165 if value.attrs.get('id') is not None:
166 enum_ids[value_body] = value['id']
167
168 d['enum_values'] = enum_values
169 d['enum_optionals'] = enum_optionals
170 d['enum_notes'] = enum_notes
171 d['enum_ids'] = enum_ids
172
173 #
174 # Container (Array/Tuple)
175 #
176 if entry.attrs.get('container') is not None:
177 container_name = entry['container']
178
179 array = entry.find('array')
180 if array is not None:
181 array_sizes = []
182 for size in array.find_all('size'):
183 array_sizes.append(size.string)
184 d['container_sizes'] = array_sizes
185
186 tupl = entry.find('tuple')
187 if tupl is not None:
188 tupl_values = []
189 for val in tupl.find_all('value'):
190 tupl_values.append(val.name)
191 d['tuple_values'] = tupl_values
192 d['container_sizes'] = len(tupl_values)
193
194 d['container'] = container_name
195
196 return d
197
198 def _parse_entry_optional(self, entry):
199 d = {}
200
201 optional_elements = ['description', 'range', 'units', 'notes']
202 for i in optional_elements:
203 prop = find_child_tag(entry, i)
204
205 if prop is not None:
206 d[i] = prop.string
207
208 tag_ids = []
209 for tag in entry.find_all('tag'):
210 tag_ids.append(tag['id'])
211
212 d['tag_ids'] = tag_ids
213
214 return d
215
216 def render(self, template, output_name=None):
217 """
218 Render the metadata model using a Mako template as the view.
219
Igor Murashkinda1c3142012-11-21 17:11:37 -0800220 The template gets the metadata as an argument, as well as all
221 public attributes from the metadata_helpers module.
222
Igor Murashkin96bd0192012-11-19 16:49:37 -0800223 Args:
224 template: path to a Mako template file
225 output_name: path to the output file, or None to use stdout
226 """
Igor Murashkinda1c3142012-11-21 17:11:37 -0800227 buf = StringIO.StringIO()
228 metadata_helpers._context_buf = buf
229
230 helpers = [(i, getattr(metadata_helpers, i))
231 for i in dir(metadata_helpers) if not i.startswith('_')]
232 helpers = dict(helpers)
233
234 lookup = TemplateLookup(directories=[os.getcwd()])
235 tpl = Template(filename=template, lookup=lookup)
236
237 ctx = Context(buf, metadata=self.metadata, **helpers)
238 tpl.render_context(ctx)
239
240 tpl_data = buf.getvalue()
241 metadata_helpers._context_buf = None
242 buf.close()
Igor Murashkin96bd0192012-11-19 16:49:37 -0800243
244 if output_name is None:
245 print tpl_data
246 else:
247 file(output_name, "w").write(tpl_data)
248
249#####################
250#####################
251
252if __name__ == "__main__":
253 if len(sys.argv) <= 1:
Igor Murashkin617da162012-11-29 13:35:15 -0800254 print >> sys.stderr, "Usage: %s <filename.xml> <template.mako>" \
255 % (sys.argv[0])
Igor Murashkin96bd0192012-11-19 16:49:37 -0800256 sys.exit(0)
257
258 file_name = sys.argv[1]
Igor Murashkin617da162012-11-29 13:35:15 -0800259 template_name = sys.argv[2]
Igor Murashkin96bd0192012-11-19 16:49:37 -0800260 parser = MetadataParserXml(file_name)
Igor Murashkin617da162012-11-29 13:35:15 -0800261 parser.render(template_name)
Igor Murashkin96bd0192012-11-19 16:49:37 -0800262
263 sys.exit(0)