Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(624)

Side by Side Diff: chrome/common/extensions/docs/server2/api_data_source.py

Issue 18323018: Linking AvailabilityFinder with APIDataSource and intro-table templates. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Rebase with master Created 7 years, 5 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
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
12 from third_party.handlebar import Handlebar
10 import third_party.json_schema_compiler.json_parse as json_parse 13 import third_party.json_schema_compiler.json_parse as json_parse
11 import third_party.json_schema_compiler.model as model 14 import third_party.json_schema_compiler.model as model
12 import third_party.json_schema_compiler.idl_schema as idl_schema 15 import third_party.json_schema_compiler.idl_schema as idl_schema
13 import third_party.json_schema_compiler.idl_parser as idl_parser 16 import third_party.json_schema_compiler.idl_parser as idl_parser
14 17
15 def _RemoveNoDocs(item): 18 def _RemoveNoDocs(item):
16 if json_parse.IsDict(item): 19 if json_parse.IsDict(item):
17 if item.get('nodoc', False): 20 if item.get('nodoc', False):
18 return True 21 return True
19 for key, value in item.items(): 22 for key, value in item.items():
(...skipping 76 matching lines...) Expand 10 before | Expand all | Expand 10 after
96 def _FormatValue(value): 99 def _FormatValue(value):
97 """Inserts commas every three digits for integer values. It is magic. 100 """Inserts commas every three digits for integer values. It is magic.
98 """ 101 """
99 s = str(value) 102 s = str(value)
100 return ','.join([s[max(0, i - 3):i] for i in range(len(s), 0, -3)][::-1]) 103 return ','.join([s[max(0, i - 3):i] for i in range(len(s), 0, -3)][::-1])
101 104
102 class _JSCModel(object): 105 class _JSCModel(object):
103 """Uses a Model from the JSON Schema Compiler and generates a dict that 106 """Uses a Model from the JSON Schema Compiler and generates a dict that
104 a Handlebar template can use for a data source. 107 a Handlebar template can use for a data source.
105 """ 108 """
106 def __init__(self, json, ref_resolver, disable_refs, idl=False): 109 def __init__(self,
110 json,
111 ref_resolver,
112 disable_refs,
113 availability_finder,
114 intro_cache,
115 template_data_source,
116 idl=False):
107 self._ref_resolver = ref_resolver 117 self._ref_resolver = ref_resolver
108 self._disable_refs = disable_refs 118 self._disable_refs = disable_refs
119 self._availability_finder = availability_finder
120 self._intro_tables = intro_cache.GetFromFile(
121 '%s/intro_tables.json' % svn_constants.JSON_PATH)
122 self._template_data_source = template_data_source
109 clean_json = copy.deepcopy(json) 123 clean_json = copy.deepcopy(json)
110 if _RemoveNoDocs(clean_json): 124 if _RemoveNoDocs(clean_json):
111 self._namespace = None 125 self._namespace = None
112 else: 126 else:
113 if idl: 127 if idl:
114 _DetectInlineableTypes(clean_json) 128 _DetectInlineableTypes(clean_json)
115 _InlineDocs(clean_json) 129 _InlineDocs(clean_json)
116 self._namespace = model.Namespace(clean_json, clean_json['namespace']) 130 self._namespace = model.Namespace(clean_json, clean_json['namespace'])
117 131
118 def _FormatDescription(self, description): 132 def _FormatDescription(self, description):
119 if self._disable_refs: 133 if self._disable_refs:
120 return description 134 return description
121 return self._ref_resolver.ResolveAllLinks(description, 135 return self._ref_resolver.ResolveAllLinks(description,
122 namespace=self._namespace.name) 136 namespace=self._namespace.name)
123 137
124 def _GetLink(self, link): 138 def _GetLink(self, link):
125 if self._disable_refs: 139 if self._disable_refs:
126 type_name = link.split('.', 1)[-1] 140 type_name = link.split('.', 1)[-1]
127 return { 'href': '#type-%s' % type_name, 'text': link, 'name': link } 141 return { 'href': '#type-%s' % type_name, 'text': link, 'name': link }
128 return self._ref_resolver.SafeGetLink(link, namespace=self._namespace.name) 142 return self._ref_resolver.SafeGetLink(link, namespace=self._namespace.name)
129 143
130 def ToDict(self): 144 def ToDict(self):
131 if self._namespace is None: 145 if self._namespace is None:
132 return {} 146 return {}
133 return { 147 return {
134 'name': self._namespace.name, 148 'name': self._namespace.name,
135 'description': self._namespace.description,
136 'types': self._GenerateTypes(self._namespace.types.values()), 149 'types': self._GenerateTypes(self._namespace.types.values()),
137 'functions': self._GenerateFunctions(self._namespace.functions), 150 'functions': self._GenerateFunctions(self._namespace.functions),
138 'events': self._GenerateEvents(self._namespace.events), 151 'events': self._GenerateEvents(self._namespace.events),
139 'properties': self._GenerateProperties(self._namespace.properties) 152 'properties': self._GenerateProperties(self._namespace.properties),
153 'intro_list': self._GetIntroTableList(),
154 'channel_warning': self._GetChannelWarning()
140 } 155 }
141 156
157 def _GetIntroTableList(self):
158 """Create a generic data structure that can be traversed by the templates
159 to create an API intro table.
160 """
161 intro_list = [{
162 'title': 'Description',
163 'content': [
164 { 'text': self._FormatDescription(self._namespace.description) }
165 ]
166 }]
167
168 if self._IsExperimental():
169 status = 'experimental'
170 version = None
171 else:
172 availability = self._GetApiAvailability()
173 status = availability.channel
174 version = availability.version
175 intro_list.append({
176 'title': 'Availability',
177 'content': [
178 {
179 'partial': self._template_data_source.get(
180 'intro_tables/%s_message.html' % status),
181 'version': version
182 }
183 ]
184 })
185
186 # Look up the API name in intro_tables.json, which is structured similarly
187 # to the data structure being created. If the name is found, loop through
188 # the attributes and add them to this structure.
189 table_info = self._intro_tables.get(self._namespace.name)
190 if table_info is None:
191 return intro_list
192
193 # The intro tables have a specific ordering that needs to be followed.
194 ordering = ('Permissions', 'Samples', 'Learn More')
195
196 for category in ordering:
197 if category not in table_info.keys():
198 continue
199 # Transform the 'partial' argument from the partial name to the
200 # template itself.
201 content = table_info[category]
202 for node in content:
203 # If there is a 'partial' argument and it hasn't already been
204 # converted to a Handlebar object, transform it to a template.
205 # TODO(epeterson/kalman): figure out why this check is necessary
206 # since it should be caching.
207 if 'partial' in node and not isinstance(node['partial'], Handlebar):
208 node['partial'] = self._template_data_source.get(node['partial'])
209 intro_list.append({
210 'title': category,
211 'content': content
212 })
213 return intro_list
214
215 def _GetApiAvailability(self):
216 return self._availability_finder.GetApiAvailability(self._namespace.name)
217
218 def _GetChannelWarning(self):
219 if not self._IsExperimental():
220 return { self._GetApiAvailability().channel: True }
221 return None
222
223 def _IsExperimental(self):
224 return self._namespace.name.startswith('experimental')
225
142 def _GenerateTypes(self, types): 226 def _GenerateTypes(self, types):
143 return [self._GenerateType(t) for t in types] 227 return [self._GenerateType(t) for t in types]
144 228
145 def _GenerateType(self, type_): 229 def _GenerateType(self, type_):
146 type_dict = { 230 type_dict = {
147 'name': type_.simple_name, 231 'name': type_.simple_name,
148 'description': self._FormatDescription(type_.description), 232 'description': self._FormatDescription(type_.description),
149 'properties': self._GenerateProperties(type_.properties), 233 'properties': self._GenerateProperties(type_.properties),
150 'functions': self._GenerateFunctions(type_.functions), 234 'functions': self._GenerateFunctions(type_.functions),
151 'events': self._GenerateEvents(type_.events), 235 'events': self._GenerateEvents(type_.events),
(...skipping 166 matching lines...) Expand 10 before | Expand all | Expand 10 after
318 self._samples = samples 402 self._samples = samples
319 403
320 def get(self, key): 404 def get(self, key):
321 return self._samples.FilterSamples(key, self._api_name) 405 return self._samples.FilterSamples(key, self._api_name)
322 406
323 class APIDataSource(object): 407 class APIDataSource(object):
324 """This class fetches and loads JSON APIs from the FileSystem passed in with 408 """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. 409 |compiled_fs_factory|, so the APIs can be plugged into templates.
326 """ 410 """
327 class Factory(object): 411 class Factory(object):
328 def __init__(self, compiled_fs_factory, base_path): 412 def __init__(self,
413 compiled_fs_factory,
414 base_path,
415 availability_finder_factory):
329 def create_compiled_fs(fn, category): 416 def create_compiled_fs(fn, category):
330 return compiled_fs_factory.Create(fn, APIDataSource, category=category) 417 return compiled_fs_factory.Create(fn, APIDataSource, category=category)
331 418
332 self._permissions_cache = create_compiled_fs(self._LoadPermissions,
333 'permissions')
334
335 self._json_cache = create_compiled_fs( 419 self._json_cache = create_compiled_fs(
336 lambda api_name, api: self._LoadJsonAPI(api, False), 420 lambda api_name, api: self._LoadJsonAPI(api, False),
337 'json') 421 'json')
338 self._idl_cache = create_compiled_fs( 422 self._idl_cache = create_compiled_fs(
339 lambda api_name, api: self._LoadIdlAPI(api, False), 423 lambda api_name, api: self._LoadIdlAPI(api, False),
340 'idl') 424 'idl')
341 425
342 # These caches are used if an APIDataSource does not want to resolve the 426 # 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 427 # $refs in an API. This is needed to prevent infinite recursion in
344 # ReferenceResolver. 428 # ReferenceResolver.
345 self._json_cache_no_refs = create_compiled_fs( 429 self._json_cache_no_refs = create_compiled_fs(
346 lambda api_name, api: self._LoadJsonAPI(api, True), 430 lambda api_name, api: self._LoadJsonAPI(api, True),
347 'json-no-refs') 431 'json-no-refs')
348 self._idl_cache_no_refs = create_compiled_fs( 432 self._idl_cache_no_refs = create_compiled_fs(
349 lambda api_name, api: self._LoadIdlAPI(api, True), 433 lambda api_name, api: self._LoadIdlAPI(api, True),
350 'idl-no-refs') 434 'idl-no-refs')
351 435
352 self._idl_names_cache = create_compiled_fs(self._GetIDLNames, 'idl-names') 436 self._idl_names_cache = create_compiled_fs(self._GetIDLNames, 'idl-names')
353 self._names_cache = create_compiled_fs(self._GetAllNames, 'names') 437 self._names_cache = create_compiled_fs(self._GetAllNames, 'names')
354 438
355 self._base_path = base_path 439 self._base_path = base_path
356 440 self._availability_finder = availability_finder_factory.Create()
441 self._intro_cache = create_compiled_fs(
442 lambda _, json: json_parse.Parse(json),
443 'intro-cache')
357 # These must be set later via the SetFooDataSourceFactory methods. 444 # These must be set later via the SetFooDataSourceFactory methods.
358 self._ref_resolver_factory = None 445 self._ref_resolver_factory = None
359 self._samples_data_source_factory = None 446 self._samples_data_source_factory = None
360 447
361 def SetSamplesDataSourceFactory(self, samples_data_source_factory): 448 def SetSamplesDataSourceFactory(self, samples_data_source_factory):
362 self._samples_data_source_factory = samples_data_source_factory 449 self._samples_data_source_factory = samples_data_source_factory
363 450
364 def SetReferenceResolverFactory(self, ref_resolver_factory): 451 def SetReferenceResolverFactory(self, ref_resolver_factory):
365 self._ref_resolver_factory = ref_resolver_factory 452 self._ref_resolver_factory = ref_resolver_factory
366 453
454 def SetTemplateDataSource(self, template_data_source_factory):
455 # This TemplateDataSource is only being used for fetching template data.
456 self._template_data_source = template_data_source_factory.Create(None, '')
457
367 def Create(self, request, disable_refs=False): 458 def Create(self, request, disable_refs=False):
368 """Create an APIDataSource. |disable_refs| specifies whether $ref's in 459 """Create an APIDataSource. |disable_refs| specifies whether $ref's in
369 APIs being processed by the |ToDict| method of _JSCModel follows $ref's 460 APIs being processed by the |ToDict| method of _JSCModel follows $ref's
370 in the API. This prevents endless recursion in ReferenceResolver. 461 in the API. This prevents endless recursion in ReferenceResolver.
371 """ 462 """
372 if self._samples_data_source_factory is None: 463 if self._samples_data_source_factory is None:
373 # Only error if there is a request, which means this APIDataSource is 464 # Only error if there is a request, which means this APIDataSource is
374 # actually being used to render a page. 465 # actually being used to render a page.
375 if request is not None: 466 if request is not None:
376 logging.error('SamplesDataSource.Factory was never set in ' 467 logging.error('SamplesDataSource.Factory was never set in '
377 'APIDataSource.Factory.') 468 'APIDataSource.Factory.')
378 samples = None 469 samples = None
379 else: 470 else:
380 samples = self._samples_data_source_factory.Create(request) 471 samples = self._samples_data_source_factory.Create(request)
381 if not disable_refs and self._ref_resolver_factory is None: 472 if not disable_refs and self._ref_resolver_factory is None:
382 logging.error('ReferenceResolver.Factory was never set in ' 473 logging.error('ReferenceResolver.Factory was never set in '
383 'APIDataSource.Factory.') 474 'APIDataSource.Factory.')
384 return APIDataSource(self._permissions_cache, 475 return APIDataSource(self._json_cache,
385 self._json_cache,
386 self._idl_cache, 476 self._idl_cache,
387 self._json_cache_no_refs, 477 self._json_cache_no_refs,
388 self._idl_cache_no_refs, 478 self._idl_cache_no_refs,
389 self._names_cache, 479 self._names_cache,
390 self._idl_names_cache, 480 self._idl_names_cache,
391 self._base_path, 481 self._base_path,
392 samples, 482 samples,
393 disable_refs) 483 disable_refs)
394 484
395 def _LoadPermissions(self, file_name, json_str):
396 return json_parse.Parse(json_str)
397
398 def _LoadJsonAPI(self, api, disable_refs): 485 def _LoadJsonAPI(self, api, disable_refs):
399 return _JSCModel( 486 return _JSCModel(
400 json_parse.Parse(api)[0], 487 json_parse.Parse(api)[0],
401 self._ref_resolver_factory.Create() if not disable_refs else None, 488 self._ref_resolver_factory.Create() if not disable_refs else None,
402 disable_refs).ToDict() 489 disable_refs,
490 self._availability_finder,
491 self._intro_cache,
492 self._template_data_source).ToDict()
403 493
404 def _LoadIdlAPI(self, api, disable_refs): 494 def _LoadIdlAPI(self, api, disable_refs):
405 idl = idl_parser.IDLParser().ParseData(api) 495 idl = idl_parser.IDLParser().ParseData(api)
406 return _JSCModel( 496 return _JSCModel(
407 idl_schema.IDLSchema(idl).process()[0], 497 idl_schema.IDLSchema(idl).process()[0],
408 self._ref_resolver_factory.Create() if not disable_refs else None, 498 self._ref_resolver_factory.Create() if not disable_refs else None,
409 disable_refs, 499 disable_refs,
500 self._availability_finder,
501 self._intro_cache,
502 self._template_data_source,
410 idl=True).ToDict() 503 idl=True).ToDict()
411 504
412 def _GetIDLNames(self, base_dir, apis): 505 def _GetIDLNames(self, base_dir, apis):
413 return self._GetExtNames(apis, ['idl']) 506 return self._GetExtNames(apis, ['idl'])
414 507
415 def _GetAllNames(self, base_dir, apis): 508 def _GetAllNames(self, base_dir, apis):
416 return self._GetExtNames(apis, ['json', 'idl']) 509 return self._GetExtNames(apis, ['json', 'idl'])
417 510
418 def _GetExtNames(self, apis, exts): 511 def _GetExtNames(self, apis, exts):
419 return [model.UnixName(os.path.splitext(api)[0]) for api in apis 512 return [model.UnixName(os.path.splitext(api)[0]) for api in apis
420 if os.path.splitext(api)[1][1:] in exts] 513 if os.path.splitext(api)[1][1:] in exts]
421 514
422 def __init__(self, 515 def __init__(self,
423 permissions_cache,
424 json_cache, 516 json_cache,
425 idl_cache, 517 idl_cache,
426 json_cache_no_refs, 518 json_cache_no_refs,
427 idl_cache_no_refs, 519 idl_cache_no_refs,
428 names_cache, 520 names_cache,
429 idl_names_cache, 521 idl_names_cache,
430 base_path, 522 base_path,
431 samples, 523 samples,
432 disable_refs): 524 disable_refs):
433 self._base_path = base_path 525 self._base_path = base_path
434 self._permissions_cache = permissions_cache
435 self._json_cache = json_cache 526 self._json_cache = json_cache
436 self._idl_cache = idl_cache 527 self._idl_cache = idl_cache
437 self._json_cache_no_refs = json_cache_no_refs 528 self._json_cache_no_refs = json_cache_no_refs
438 self._idl_cache_no_refs = idl_cache_no_refs 529 self._idl_cache_no_refs = idl_cache_no_refs
439 self._names_cache = names_cache 530 self._names_cache = names_cache
440 self._idl_names_cache = idl_names_cache 531 self._idl_names_cache = idl_names_cache
441 self._samples = samples 532 self._samples = samples
442 self._disable_refs = disable_refs 533 self._disable_refs = disable_refs
443 534
444 def _GetFeatureFile(self, filename):
445 perms = self._permissions_cache.GetFromFile('%s/%s' %
446 (self._base_path, filename))
447 return dict((model.UnixName(k), v) for k, v in perms.iteritems())
448
449 def _GetFeatureData(self, path):
450 # Remove 'experimental_' from path name to match the keys in
451 # _permissions_features.json.
452 path = model.UnixName(path.replace('experimental_', ''))
453
454 for filename in ['_permission_features.json', '_manifest_features.json']:
455 feature_data = self._GetFeatureFile(filename).get(path, None)
456 if feature_data is not None:
457 break
458
459 # There are specific cases in which the feature is actually a list of
460 # features where only one needs to match; but currently these are only
461 # used to whitelist features for specific extension IDs. Filter those out.
462 if isinstance(feature_data, list):
463 feature_list = feature_data
464 feature_data = None
465 for single_feature in feature_list:
466 if 'whitelist' in single_feature:
467 continue
468 if feature_data is not None:
469 # Note: if you are seeing the exception below, add more heuristics as
470 # required to form a single feature.
471 raise ValueError('Multiple potential features match %s. I can\'t '
472 'decide which one to use. Please help!' % path)
473 feature_data = single_feature
474
475 if feature_data and feature_data['channel'] in ('trunk', 'dev', 'beta'):
476 feature_data[feature_data['channel']] = True
477 return feature_data
478
479 def _GenerateHandlebarContext(self, handlebar_dict, path): 535 def _GenerateHandlebarContext(self, handlebar_dict, path):
480 handlebar_dict['permissions'] = self._GetFeatureData(path)
481 handlebar_dict['samples'] = _LazySamplesGetter(path, self._samples) 536 handlebar_dict['samples'] = _LazySamplesGetter(path, self._samples)
482 return handlebar_dict 537 return handlebar_dict
483 538
484 def _GetAsSubdirectory(self, name): 539 def _GetAsSubdirectory(self, name):
485 if name.startswith('experimental_'): 540 if name.startswith('experimental_'):
486 parts = name[len('experimental_'):].split('_', 1) 541 parts = name[len('experimental_'):].split('_', 1)
487 parts[1] = 'experimental_%s' % parts[1] 542 if len(parts) > 1:
488 return '/'.join(parts) 543 parts[1] = 'experimental_%s' % parts[1]
544 return '/'.join(parts)
545 return '%s/%s' % (parts[0], name)
489 return name.replace('_', '/', 1) 546 return name.replace('_', '/', 1)
490 547
491 def get(self, key): 548 def get(self, key):
492 if key.endswith('.html') or key.endswith('.json') or key.endswith('.idl'): 549 if key.endswith('.html') or key.endswith('.json') or key.endswith('.idl'):
493 path, ext = os.path.splitext(key) 550 path, ext = os.path.splitext(key)
494 else: 551 else:
495 path = key 552 path = key
496 unix_name = model.UnixName(path) 553 unix_name = model.UnixName(path)
497 idl_names = self._idl_names_cache.GetFromFileListing(self._base_path) 554 idl_names = self._idl_names_cache.GetFromFileListing(self._base_path)
498 names = self._names_cache.GetFromFileListing(self._base_path) 555 names = self._names_cache.GetFromFileListing(self._base_path)
499 if unix_name not in names and self._GetAsSubdirectory(unix_name) in names: 556 if unix_name not in names and self._GetAsSubdirectory(unix_name) in names:
500 unix_name = self._GetAsSubdirectory(unix_name) 557 unix_name = self._GetAsSubdirectory(unix_name)
501 558
502 if self._disable_refs: 559 if self._disable_refs:
503 cache, ext = ( 560 cache, ext = (
504 (self._idl_cache_no_refs, '.idl') if (unix_name in idl_names) else 561 (self._idl_cache_no_refs, '.idl') if (unix_name in idl_names) else
505 (self._json_cache_no_refs, '.json')) 562 (self._json_cache_no_refs, '.json'))
506 else: 563 else:
507 cache, ext = ((self._idl_cache, '.idl') if (unix_name in idl_names) else 564 cache, ext = ((self._idl_cache, '.idl') if (unix_name in idl_names) else
508 (self._json_cache, '.json')) 565 (self._json_cache, '.json'))
509 return self._GenerateHandlebarContext( 566 return self._GenerateHandlebarContext(
510 cache.GetFromFile('%s/%s%s' % (self._base_path, unix_name, ext)), 567 cache.GetFromFile('%s/%s%s' % (self._base_path, unix_name, ext)),
511 path) 568 path)
OLDNEW
« no previous file with comments | « chrome/common/extensions/api/sync_file_system.idl ('k') | chrome/common/extensions/docs/server2/api_data_source_test.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698