OLD | NEW |
---|---|
1 # Copyright (c) 2012 The Chromium Authors. All rights reserved. | 1 # Copyright (c) 2012 The Chromium Authors. All rights reserved. |
2 # Use of this source code is governed by a BSD-style license that can be | 2 # Use of this source code is governed by a BSD-style license that can be |
3 # found in the LICENSE file. | 3 # found in the LICENSE file. |
4 | 4 |
5 import copy | 5 import copy |
6 import logging | 6 import logging |
7 import os | 7 import os |
8 from collections import defaultdict, Mapping | 8 from collections import defaultdict, Mapping |
9 | 9 |
10 from branch_utility import BranchUtility | |
11 import svn_constants | |
10 import third_party.json_schema_compiler.json_parse as json_parse | 12 import third_party.json_schema_compiler.json_parse as json_parse |
11 import third_party.json_schema_compiler.model as model | 13 import third_party.json_schema_compiler.model as model |
12 import third_party.json_schema_compiler.idl_schema as idl_schema | 14 import third_party.json_schema_compiler.idl_schema as idl_schema |
13 import third_party.json_schema_compiler.idl_parser as idl_parser | 15 import third_party.json_schema_compiler.idl_parser as idl_parser |
14 | 16 |
15 def _RemoveNoDocs(item): | 17 def _RemoveNoDocs(item): |
16 if json_parse.IsDict(item): | 18 if json_parse.IsDict(item): |
17 if item.get('nodoc', False): | 19 if item.get('nodoc', False): |
18 return True | 20 return True |
19 for key, value in item.items(): | 21 for key, value in item.items(): |
(...skipping 76 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
96 def _FormatValue(value): | 98 def _FormatValue(value): |
97 """Inserts commas every three digits for integer values. It is magic. | 99 """Inserts commas every three digits for integer values. It is magic. |
98 """ | 100 """ |
99 s = str(value) | 101 s = str(value) |
100 return ','.join([s[max(0, i - 3):i] for i in range(len(s), 0, -3)][::-1]) | 102 return ','.join([s[max(0, i - 3):i] for i in range(len(s), 0, -3)][::-1]) |
101 | 103 |
102 class _JSCModel(object): | 104 class _JSCModel(object): |
103 """Uses a Model from the JSON Schema Compiler and generates a dict that | 105 """Uses a Model from the JSON Schema Compiler and generates a dict that |
104 a Handlebar template can use for a data source. | 106 a Handlebar template can use for a data source. |
105 """ | 107 """ |
106 def __init__(self, json, ref_resolver, disable_refs, idl=False): | 108 def __init__(self, |
109 json, | |
110 ref_resolver, | |
111 disable_refs, | |
112 availability_finder, | |
113 intro_cache, | |
114 template_data_source, | |
115 idl=False): | |
107 self._ref_resolver = ref_resolver | 116 self._ref_resolver = ref_resolver |
108 self._disable_refs = disable_refs | 117 self._disable_refs = disable_refs |
118 self._availability_finder = availability_finder | |
119 self._intro_tables = intro_cache.GetFromFile( | |
120 '%s/intro_tables.json' % svn_constants.JSON_PATH) | |
121 self._template_data_source = template_data_source | |
109 clean_json = copy.deepcopy(json) | 122 clean_json = copy.deepcopy(json) |
110 if _RemoveNoDocs(clean_json): | 123 if _RemoveNoDocs(clean_json): |
111 self._namespace = None | 124 self._namespace = None |
112 else: | 125 else: |
113 if idl: | 126 if idl: |
114 _DetectInlineableTypes(clean_json) | 127 _DetectInlineableTypes(clean_json) |
115 _InlineDocs(clean_json) | 128 _InlineDocs(clean_json) |
116 self._namespace = model.Namespace(clean_json, clean_json['namespace']) | 129 self._namespace = model.Namespace(clean_json, clean_json['namespace']) |
117 | 130 |
118 def _FormatDescription(self, description): | 131 def _FormatDescription(self, description): |
119 if self._disable_refs: | 132 if self._disable_refs: |
120 return description | 133 return description |
121 return self._ref_resolver.ResolveAllLinks(description, | 134 return self._ref_resolver.ResolveAllLinks(description, |
122 namespace=self._namespace.name) | 135 namespace=self._namespace.name) |
123 | 136 |
124 def _GetLink(self, link): | 137 def _GetLink(self, link): |
125 if self._disable_refs: | 138 if self._disable_refs: |
126 type_name = link.split('.', 1)[-1] | 139 type_name = link.split('.', 1)[-1] |
127 return { 'href': '#type-%s' % type_name, 'text': link, 'name': link } | 140 return { 'href': '#type-%s' % type_name, 'text': link, 'name': link } |
128 return self._ref_resolver.SafeGetLink(link, namespace=self._namespace.name) | 141 return self._ref_resolver.SafeGetLink(link, namespace=self._namespace.name) |
129 | 142 |
130 def ToDict(self): | 143 def ToDict(self): |
131 if self._namespace is None: | 144 if self._namespace is None: |
132 return {} | 145 return {} |
133 return { | 146 return { |
134 'name': self._namespace.name, | 147 'name': self._namespace.name, |
135 'description': self._namespace.description, | |
136 'types': self._GenerateTypes(self._namespace.types.values()), | 148 'types': self._GenerateTypes(self._namespace.types.values()), |
137 'functions': self._GenerateFunctions(self._namespace.functions), | 149 'functions': self._GenerateFunctions(self._namespace.functions), |
138 'events': self._GenerateEvents(self._namespace.events), | 150 'events': self._GenerateEvents(self._namespace.events), |
139 'properties': self._GenerateProperties(self._namespace.properties) | 151 'properties': self._GenerateProperties(self._namespace.properties), |
152 'intro_list': self._GetIntroTableList() | |
140 } | 153 } |
141 | 154 |
155 def _GetIntroTableList(self): | |
156 """Create a generic data structure that can be traversed by the templates | |
157 to create an API intro table. | |
158 """ | |
159 intro_list = [{ | |
160 'title': 'Description', | |
161 'content': [ | |
162 { 'text': self._FormatDescription(self._namespace.description) } | |
163 ] | |
164 }] | |
165 | |
166 if self._IsExperimental(): | |
167 status = 'experimental' | |
168 version = None | |
169 else: | |
170 availability = self._GetApiAvailability() | |
171 status = availability.channel | |
172 version = availability.version | |
173 intro_list.append({ | |
174 'title': 'Availability', | |
175 'content': [ | |
176 { | |
177 'partial': self._template_data_source.get( | |
178 'intro_tables/%s_message.html' % status), | |
179 'version': version | |
180 } | |
181 ] | |
182 }) | |
183 | |
184 # Look up the API name in intro_tables.json, which is structured similarly | |
185 # to the data structure being created. If the name is found, loop through | |
186 # the attributes and add them to this structure. | |
187 table_info = self._intro_tables.get(self._namespace.name) | |
188 if table_info is None: | |
189 return intro_list | |
190 | |
191 # The intro tables have a specific ordering that needs to be followed. | |
192 ordering = ('Permissions', 'Samples', 'Learn More') | |
193 | |
194 for category in ordering: | |
195 if category not in table_info.keys(): | |
196 continue | |
197 # Transform the 'partial' argument from the partial name to the | |
198 # template itself. | |
199 content = table_info[category] | |
200 for node in content: | |
201 # If there is a 'partial' argument and it hasn't already been | |
202 # converted, transform it to a template. | |
203 if 'partial' in node and isinstance (node['partial'], basestring): | |
epeterson
2013/07/18 18:17:07
Similar to the isinstance(.. Handlebar) check, tho
not at google - send to devlin
2013/07/18 21:24:15
Oh so it shouldn't be computing this more than onc
epeterson
2013/07/19 00:05:35
Added a TODO, but I'm curious as to what I may hav
| |
204 node['partial'] = self._template_data_source.get(node['partial']) | |
205 intro_list.append({ | |
206 'title': category, | |
207 'content': content | |
208 }) | |
209 return intro_list | |
210 | |
211 def _GetApiAvailability(self): | |
212 return self._availability_finder.GetApiAvailability(self._namespace.name) | |
213 | |
214 def _IsExperimental(self): | |
215 return self._namespace.name.startswith('experimental') | |
216 | |
142 def _GenerateTypes(self, types): | 217 def _GenerateTypes(self, types): |
143 return [self._GenerateType(t) for t in types] | 218 return [self._GenerateType(t) for t in types] |
144 | 219 |
145 def _GenerateType(self, type_): | 220 def _GenerateType(self, type_): |
146 type_dict = { | 221 type_dict = { |
147 'name': type_.simple_name, | 222 'name': type_.simple_name, |
148 'description': self._FormatDescription(type_.description), | 223 'description': self._FormatDescription(type_.description), |
149 'properties': self._GenerateProperties(type_.properties), | 224 'properties': self._GenerateProperties(type_.properties), |
150 'functions': self._GenerateFunctions(type_.functions), | 225 'functions': self._GenerateFunctions(type_.functions), |
151 'events': self._GenerateEvents(type_.events), | 226 'events': self._GenerateEvents(type_.events), |
(...skipping 166 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
318 self._samples = samples | 393 self._samples = samples |
319 | 394 |
320 def get(self, key): | 395 def get(self, key): |
321 return self._samples.FilterSamples(key, self._api_name) | 396 return self._samples.FilterSamples(key, self._api_name) |
322 | 397 |
323 class APIDataSource(object): | 398 class APIDataSource(object): |
324 """This class fetches and loads JSON APIs from the FileSystem passed in with | 399 """This class fetches and loads JSON APIs from the FileSystem passed in with |
325 |compiled_fs_factory|, so the APIs can be plugged into templates. | 400 |compiled_fs_factory|, so the APIs can be plugged into templates. |
326 """ | 401 """ |
327 class Factory(object): | 402 class Factory(object): |
328 def __init__(self, compiled_fs_factory, base_path): | 403 def __init__(self, |
404 compiled_fs_factory, | |
405 base_path, | |
406 availability_finder_factory): | |
329 def create_compiled_fs(fn, category): | 407 def create_compiled_fs(fn, category): |
330 return compiled_fs_factory.Create(fn, APIDataSource, category=category) | 408 return compiled_fs_factory.Create(fn, APIDataSource, category=category) |
331 | 409 |
332 self._permissions_cache = create_compiled_fs(self._LoadPermissions, | 410 self._permissions_cache = create_compiled_fs(self._LoadPermissions, |
333 'permissions') | 411 'permissions') |
334 | 412 |
335 self._json_cache = create_compiled_fs( | 413 self._json_cache = create_compiled_fs( |
336 lambda api_name, api: self._LoadJsonAPI(api, False), | 414 lambda api_name, api: self._LoadJsonAPI(api, False), |
337 'json') | 415 'json') |
338 self._idl_cache = create_compiled_fs( | 416 self._idl_cache = create_compiled_fs( |
339 lambda api_name, api: self._LoadIdlAPI(api, False), | 417 lambda api_name, api: self._LoadIdlAPI(api, False), |
340 'idl') | 418 'idl') |
341 | 419 |
342 # These caches are used if an APIDataSource does not want to resolve the | 420 # These caches are used if an APIDataSource does not want to resolve the |
343 # $refs in an API. This is needed to prevent infinite recursion in | 421 # $refs in an API. This is needed to prevent infinite recursion in |
344 # ReferenceResolver. | 422 # ReferenceResolver. |
345 self._json_cache_no_refs = create_compiled_fs( | 423 self._json_cache_no_refs = create_compiled_fs( |
346 lambda api_name, api: self._LoadJsonAPI(api, True), | 424 lambda api_name, api: self._LoadJsonAPI(api, True), |
347 'json-no-refs') | 425 'json-no-refs') |
348 self._idl_cache_no_refs = create_compiled_fs( | 426 self._idl_cache_no_refs = create_compiled_fs( |
349 lambda api_name, api: self._LoadIdlAPI(api, True), | 427 lambda api_name, api: self._LoadIdlAPI(api, True), |
350 'idl-no-refs') | 428 'idl-no-refs') |
351 | 429 |
352 self._idl_names_cache = create_compiled_fs(self._GetIDLNames, 'idl-names') | 430 self._idl_names_cache = create_compiled_fs(self._GetIDLNames, 'idl-names') |
353 self._names_cache = create_compiled_fs(self._GetAllNames, 'names') | 431 self._names_cache = create_compiled_fs(self._GetAllNames, 'names') |
354 | 432 |
355 self._base_path = base_path | 433 self._base_path = base_path |
356 | 434 self._availability_finder = availability_finder_factory.Create() |
435 self._intro_cache = create_compiled_fs( | |
436 lambda _, json: json_parse.Parse(json), | |
437 'intro-cache') | |
357 # These must be set later via the SetFooDataSourceFactory methods. | 438 # These must be set later via the SetFooDataSourceFactory methods. |
358 self._ref_resolver_factory = None | 439 self._ref_resolver_factory = None |
359 self._samples_data_source_factory = None | 440 self._samples_data_source_factory = None |
360 | 441 |
361 def SetSamplesDataSourceFactory(self, samples_data_source_factory): | 442 def SetSamplesDataSourceFactory(self, samples_data_source_factory): |
362 self._samples_data_source_factory = samples_data_source_factory | 443 self._samples_data_source_factory = samples_data_source_factory |
363 | 444 |
364 def SetReferenceResolverFactory(self, ref_resolver_factory): | 445 def SetReferenceResolverFactory(self, ref_resolver_factory): |
365 self._ref_resolver_factory = ref_resolver_factory | 446 self._ref_resolver_factory = ref_resolver_factory |
366 | 447 |
448 def SetTemplateDataSource(self, template_data_source_factory): | |
449 # This TemplateDataSource is only being used for fetching template data. | |
450 self._template_data_source = template_data_source_factory.Create(None, '') | |
epeterson
2013/07/18 18:17:07
No request or path data is given here, since this
not at google - send to devlin
2013/07/18 21:24:15
Ah ok. That's fine for now. I will try to refactor
| |
451 | |
367 def Create(self, request, disable_refs=False): | 452 def Create(self, request, disable_refs=False): |
368 """Create an APIDataSource. |disable_refs| specifies whether $ref's in | 453 """Create an APIDataSource. |disable_refs| specifies whether $ref's in |
369 APIs being processed by the |ToDict| method of _JSCModel follows $ref's | 454 APIs being processed by the |ToDict| method of _JSCModel follows $ref's |
370 in the API. This prevents endless recursion in ReferenceResolver. | 455 in the API. This prevents endless recursion in ReferenceResolver. |
371 """ | 456 """ |
372 if self._samples_data_source_factory is None: | 457 if self._samples_data_source_factory is None: |
373 # Only error if there is a request, which means this APIDataSource is | 458 # Only error if there is a request, which means this APIDataSource is |
374 # actually being used to render a page. | 459 # actually being used to render a page. |
375 if request is not None: | 460 if request is not None: |
376 logging.error('SamplesDataSource.Factory was never set in ' | 461 logging.error('SamplesDataSource.Factory was never set in ' |
(...skipping 15 matching lines...) Expand all Loading... | |
392 samples, | 477 samples, |
393 disable_refs) | 478 disable_refs) |
394 | 479 |
395 def _LoadPermissions(self, file_name, json_str): | 480 def _LoadPermissions(self, file_name, json_str): |
396 return json_parse.Parse(json_str) | 481 return json_parse.Parse(json_str) |
397 | 482 |
398 def _LoadJsonAPI(self, api, disable_refs): | 483 def _LoadJsonAPI(self, api, disable_refs): |
399 return _JSCModel( | 484 return _JSCModel( |
400 json_parse.Parse(api)[0], | 485 json_parse.Parse(api)[0], |
401 self._ref_resolver_factory.Create() if not disable_refs else None, | 486 self._ref_resolver_factory.Create() if not disable_refs else None, |
402 disable_refs).ToDict() | 487 disable_refs, |
488 self._availability_finder, | |
489 self._intro_cache, | |
490 self._template_data_source).ToDict() | |
403 | 491 |
404 def _LoadIdlAPI(self, api, disable_refs): | 492 def _LoadIdlAPI(self, api, disable_refs): |
405 idl = idl_parser.IDLParser().ParseData(api) | 493 idl = idl_parser.IDLParser().ParseData(api) |
406 return _JSCModel( | 494 return _JSCModel( |
407 idl_schema.IDLSchema(idl).process()[0], | 495 idl_schema.IDLSchema(idl).process()[0], |
408 self._ref_resolver_factory.Create() if not disable_refs else None, | 496 self._ref_resolver_factory.Create() if not disable_refs else None, |
409 disable_refs, | 497 disable_refs, |
498 self._availability_finder, | |
499 self._intro_cache, | |
500 self._template_data_source, | |
410 idl=True).ToDict() | 501 idl=True).ToDict() |
411 | 502 |
412 def _GetIDLNames(self, base_dir, apis): | 503 def _GetIDLNames(self, base_dir, apis): |
413 return self._GetExtNames(apis, ['idl']) | 504 return self._GetExtNames(apis, ['idl']) |
414 | 505 |
415 def _GetAllNames(self, base_dir, apis): | 506 def _GetAllNames(self, base_dir, apis): |
416 return self._GetExtNames(apis, ['json', 'idl']) | 507 return self._GetExtNames(apis, ['json', 'idl']) |
417 | 508 |
418 def _GetExtNames(self, apis, exts): | 509 def _GetExtNames(self, apis, exts): |
419 return [model.UnixName(os.path.splitext(api)[0]) for api in apis | 510 return [model.UnixName(os.path.splitext(api)[0]) for api in apis |
(...skipping 48 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
468 if feature_data is not None: | 559 if feature_data is not None: |
469 # Note: if you are seeing the exception below, add more heuristics as | 560 # Note: if you are seeing the exception below, add more heuristics as |
470 # required to form a single feature. | 561 # required to form a single feature. |
471 raise ValueError('Multiple potential features match %s. I can\'t ' | 562 raise ValueError('Multiple potential features match %s. I can\'t ' |
472 'decide which one to use. Please help!' % path) | 563 'decide which one to use. Please help!' % path) |
473 feature_data = single_feature | 564 feature_data = single_feature |
474 | 565 |
475 if feature_data and feature_data['channel'] in ('trunk', 'dev', 'beta'): | 566 if feature_data and feature_data['channel'] in ('trunk', 'dev', 'beta'): |
476 feature_data[feature_data['channel']] = True | 567 feature_data[feature_data['channel']] = True |
477 return feature_data | 568 return feature_data |
478 | 569 |
epeterson
2013/07/19 00:05:35
This stuff is gone, it was only used for the warni
| |
479 def _GenerateHandlebarContext(self, handlebar_dict, path): | 570 def _GenerateHandlebarContext(self, handlebar_dict, path): |
480 handlebar_dict['permissions'] = self._GetFeatureData(path) | 571 handlebar_dict['permissions'] = self._GetFeatureData(path) |
481 handlebar_dict['samples'] = _LazySamplesGetter(path, self._samples) | 572 handlebar_dict['samples'] = _LazySamplesGetter(path, self._samples) |
482 return handlebar_dict | 573 return handlebar_dict |
483 | 574 |
484 def _GetAsSubdirectory(self, name): | 575 def _GetAsSubdirectory(self, name): |
485 if name.startswith('experimental_'): | 576 if name.startswith('experimental_'): |
486 parts = name[len('experimental_'):].split('_', 1) | 577 parts = name[len('experimental_'):].split('_', 1) |
487 parts[1] = 'experimental_%s' % parts[1] | 578 if len(parts) > 1: |
488 return '/'.join(parts) | 579 parts[1] = 'experimental_%s' % parts[1] |
580 return '/'.join(parts) | |
581 return '%s/%s' % (parts[0], name) | |
489 return name.replace('_', '/', 1) | 582 return name.replace('_', '/', 1) |
490 | 583 |
491 def get(self, key): | 584 def get(self, key): |
492 if key.endswith('.html') or key.endswith('.json') or key.endswith('.idl'): | 585 if key.endswith('.html') or key.endswith('.json') or key.endswith('.idl'): |
493 path, ext = os.path.splitext(key) | 586 path, ext = os.path.splitext(key) |
494 else: | 587 else: |
495 path = key | 588 path = key |
496 unix_name = model.UnixName(path) | 589 unix_name = model.UnixName(path) |
497 idl_names = self._idl_names_cache.GetFromFileListing(self._base_path) | 590 idl_names = self._idl_names_cache.GetFromFileListing(self._base_path) |
498 names = self._names_cache.GetFromFileListing(self._base_path) | 591 names = self._names_cache.GetFromFileListing(self._base_path) |
499 if unix_name not in names and self._GetAsSubdirectory(unix_name) in names: | 592 if unix_name not in names and self._GetAsSubdirectory(unix_name) in names: |
500 unix_name = self._GetAsSubdirectory(unix_name) | 593 unix_name = self._GetAsSubdirectory(unix_name) |
501 | 594 |
502 if self._disable_refs: | 595 if self._disable_refs: |
503 cache, ext = ( | 596 cache, ext = ( |
504 (self._idl_cache_no_refs, '.idl') if (unix_name in idl_names) else | 597 (self._idl_cache_no_refs, '.idl') if (unix_name in idl_names) else |
505 (self._json_cache_no_refs, '.json')) | 598 (self._json_cache_no_refs, '.json')) |
506 else: | 599 else: |
507 cache, ext = ((self._idl_cache, '.idl') if (unix_name in idl_names) else | 600 cache, ext = ((self._idl_cache, '.idl') if (unix_name in idl_names) else |
508 (self._json_cache, '.json')) | 601 (self._json_cache, '.json')) |
509 return self._GenerateHandlebarContext( | 602 return self._GenerateHandlebarContext( |
510 cache.GetFromFile('%s/%s%s' % (self._base_path, unix_name, ext)), | 603 cache.GetFromFile('%s/%s%s' % (self._base_path, unix_name, ext)), |
511 path) | 604 path) |
OLD | NEW |