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

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: Figuring out partials 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
« no previous file with comments | « no previous file | chrome/common/extensions/docs/server2/api_data_source_test.py » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
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 from docs_server_utils import FormatKey
12 import svn_constants
13 from third_party.handlebar import Handlebar
10 import third_party.json_schema_compiler.json_parse as json_parse 14 import third_party.json_schema_compiler.json_parse as json_parse
11 import third_party.json_schema_compiler.model as model 15 import third_party.json_schema_compiler.model as model
12 import third_party.json_schema_compiler.idl_schema as idl_schema 16 import third_party.json_schema_compiler.idl_schema as idl_schema
13 import third_party.json_schema_compiler.idl_parser as idl_parser 17 import third_party.json_schema_compiler.idl_parser as idl_parser
14 18
15 def _RemoveNoDocs(item): 19 def _RemoveNoDocs(item):
16 if json_parse.IsDict(item): 20 if json_parse.IsDict(item):
17 if item.get('nodoc', False): 21 if item.get('nodoc', False):
18 return True 22 return True
19 for key, value in item.items(): 23 for key, value in item.items():
(...skipping 76 matching lines...) Expand 10 before | Expand all | Expand 10 after
96 def _FormatValue(value): 100 def _FormatValue(value):
97 """Inserts commas every three digits for integer values. It is magic. 101 """Inserts commas every three digits for integer values. It is magic.
98 """ 102 """
99 s = str(value) 103 s = str(value)
100 return ','.join([s[max(0, i - 3):i] for i in range(len(s), 0, -3)][::-1]) 104 return ','.join([s[max(0, i - 3):i] for i in range(len(s), 0, -3)][::-1])
101 105
102 class _JSCModel(object): 106 class _JSCModel(object):
103 """Uses a Model from the JSON Schema Compiler and generates a dict that 107 """Uses a Model from the JSON Schema Compiler and generates a dict that
104 a Handlebar template can use for a data source. 108 a Handlebar template can use for a data source.
105 """ 109 """
106 def __init__(self, json, ref_resolver, disable_refs, idl=False): 110 def __init__(self,
111 json,
112 ref_resolver,
113 disable_refs,
114 availability_finder,
115 intro_cache,
116 partial_cache,
117 idl=False):
107 self._ref_resolver = ref_resolver 118 self._ref_resolver = ref_resolver
108 self._disable_refs = disable_refs 119 self._disable_refs = disable_refs
120 self._availability_finder = availability_finder
121 self._intro_tables = intro_cache.GetFromFile(
122 '%s/intro_tables.json' % svn_constants.JSON_PATH)
123 self._partial_cache = partial_cache
not at google - send to devlin 2013/07/18 02:20:30 can you pass in the TemplateDataSource instance in
109 clean_json = copy.deepcopy(json) 124 clean_json = copy.deepcopy(json)
110 if _RemoveNoDocs(clean_json): 125 if _RemoveNoDocs(clean_json):
111 self._namespace = None 126 self._namespace = None
112 else: 127 else:
113 if idl: 128 if idl:
114 _DetectInlineableTypes(clean_json) 129 _DetectInlineableTypes(clean_json)
115 _InlineDocs(clean_json) 130 _InlineDocs(clean_json)
116 self._namespace = model.Namespace(clean_json, clean_json['namespace']) 131 self._namespace = model.Namespace(clean_json, clean_json['namespace'])
117 132
118 def _FormatDescription(self, description): 133 def _FormatDescription(self, description):
119 if self._disable_refs: 134 if self._disable_refs:
120 return description 135 return description
121 return self._ref_resolver.ResolveAllLinks(description, 136 return self._ref_resolver.ResolveAllLinks(description,
122 namespace=self._namespace.name) 137 namespace=self._namespace.name)
123 138
124 def _GetLink(self, link): 139 def _GetLink(self, link):
125 if self._disable_refs: 140 if self._disable_refs:
126 type_name = link.split('.', 1)[-1] 141 type_name = link.split('.', 1)[-1]
127 return { 'href': '#type-%s' % type_name, 'text': link, 'name': link } 142 return { 'href': '#type-%s' % type_name, 'text': link, 'name': link }
128 return self._ref_resolver.SafeGetLink(link, namespace=self._namespace.name) 143 return self._ref_resolver.SafeGetLink(link, namespace=self._namespace.name)
129 144
130 def ToDict(self): 145 def ToDict(self):
131 if self._namespace is None: 146 if self._namespace is None:
132 return {} 147 return {}
133 return { 148 return {
134 'name': self._namespace.name, 149 'name': self._namespace.name,
135 'description': self._namespace.description,
136 'types': self._GenerateTypes(self._namespace.types.values()), 150 'types': self._GenerateTypes(self._namespace.types.values()),
137 'functions': self._GenerateFunctions(self._namespace.functions), 151 'functions': self._GenerateFunctions(self._namespace.functions),
138 'events': self._GenerateEvents(self._namespace.events), 152 'events': self._GenerateEvents(self._namespace.events),
139 'properties': self._GenerateProperties(self._namespace.properties) 153 'properties': self._GenerateProperties(self._namespace.properties),
154 'intro_list': self._GetIntroTableList()
140 } 155 }
141 156
157 def _GetPartial(self, template_name):
158 return self._partial_cache.GetFromFile(
159 '/'.join((svn_constants.PRIVATE_TEMPLATE_PATH,
160 FormatKey(template_name))))
161
162 def _GetIntroTableList(self):
163 """Create a generic data structure that can be traversed by the templates
164 to create an API intro table.
165 """
166 intro_list = [{
167 'title': 'Description',
168 'content': [
169 { 'text': self._FormatDescription(self._namespace.description) }
170 ]
171 }]
172
173 if self._IsExperimental():
174 status = 'experimental'
175 version = None
176 else:
177 availability = self._GetApiAvailability()
178 status = availability.channel
179 version = availability.version
180 intro_list.append({
181 'title': 'Availability',
182 'content': [
183 {
184 'partial': self._GetPartial('intro_tables/%s_message.html' % status),
185 'version': version
186 }
187 ]
188 })
189
190 # Look up the API name in intro_tables.json, which is structured similarly
191 # to the data structure being created. If the name is found, loop through
192 # the attributes and add them to this structure.
193 table_info = self._intro_tables.get(self._namespace.name)
194 if table_info is None:
195 return intro_list
196
197 # The intro tables have a specific ordering that needs to be followed.
198 ordering = ('Permissions', 'Samples', 'Learn More')
199
200 for category in ordering:
201 if category in table_info.keys():
not at google - send to devlin 2013/07/18 02:20:30 early-exit here: if category not in table_info.ke
202 node = { 'title': category, 'content': table_info.get(category, []) }
203 for obj in node['content']:
204 if ('partial' in obj.keys() and
205 not isinstance(obj['partial'], Handlebar)):
206 obj['partial'] = self._GetPartial(obj['partial'])
207 intro_list.append(node)
epeterson 2013/07/17 23:48:23 Also, this became messy with the special behavior
not at google - send to devlin 2013/07/18 02:20:30 ah right. Yeah - oh well. when is isinstance(obj[
208 return intro_list
209
210 def _GetApiAvailability(self):
211 return self._availability_finder.GetApiAvailability(self._namespace.name)
212
213 def _IsExperimental(self):
214 return self._namespace.name.startswith('experimental')
215
142 def _GenerateTypes(self, types): 216 def _GenerateTypes(self, types):
143 return [self._GenerateType(t) for t in types] 217 return [self._GenerateType(t) for t in types]
144 218
145 def _GenerateType(self, type_): 219 def _GenerateType(self, type_):
146 type_dict = { 220 type_dict = {
147 'name': type_.simple_name, 221 'name': type_.simple_name,
148 'description': self._FormatDescription(type_.description), 222 'description': self._FormatDescription(type_.description),
149 'properties': self._GenerateProperties(type_.properties), 223 'properties': self._GenerateProperties(type_.properties),
150 'functions': self._GenerateFunctions(type_.functions), 224 'functions': self._GenerateFunctions(type_.functions),
151 'events': self._GenerateEvents(type_.events), 225 'events': self._GenerateEvents(type_.events),
(...skipping 166 matching lines...) Expand 10 before | Expand all | Expand 10 after
318 self._samples = samples 392 self._samples = samples
319 393
320 def get(self, key): 394 def get(self, key):
321 return self._samples.FilterSamples(key, self._api_name) 395 return self._samples.FilterSamples(key, self._api_name)
322 396
323 class APIDataSource(object): 397 class APIDataSource(object):
324 """This class fetches and loads JSON APIs from the FileSystem passed in with 398 """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. 399 |compiled_fs_factory|, so the APIs can be plugged into templates.
326 """ 400 """
327 class Factory(object): 401 class Factory(object):
328 def __init__(self, compiled_fs_factory, base_path): 402 def __init__(self,
403 compiled_fs_factory,
404 base_path,
405 availability_finder_factory):
329 def create_compiled_fs(fn, category): 406 def create_compiled_fs(fn, category):
330 return compiled_fs_factory.Create(fn, APIDataSource, category=category) 407 return compiled_fs_factory.Create(fn, APIDataSource, category=category)
331 408
332 self._permissions_cache = create_compiled_fs(self._LoadPermissions, 409 self._permissions_cache = create_compiled_fs(self._LoadPermissions,
333 'permissions') 410 'permissions')
334 411
335 self._json_cache = create_compiled_fs( 412 self._json_cache = create_compiled_fs(
336 lambda api_name, api: self._LoadJsonAPI(api, False), 413 lambda api_name, api: self._LoadJsonAPI(api, False),
337 'json') 414 'json')
338 self._idl_cache = create_compiled_fs( 415 self._idl_cache = create_compiled_fs(
339 lambda api_name, api: self._LoadIdlAPI(api, False), 416 lambda api_name, api: self._LoadIdlAPI(api, False),
340 'idl') 417 'idl')
341 418
342 # These caches are used if an APIDataSource does not want to resolve the 419 # 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 420 # $refs in an API. This is needed to prevent infinite recursion in
344 # ReferenceResolver. 421 # ReferenceResolver.
345 self._json_cache_no_refs = create_compiled_fs( 422 self._json_cache_no_refs = create_compiled_fs(
346 lambda api_name, api: self._LoadJsonAPI(api, True), 423 lambda api_name, api: self._LoadJsonAPI(api, True),
347 'json-no-refs') 424 'json-no-refs')
348 self._idl_cache_no_refs = create_compiled_fs( 425 self._idl_cache_no_refs = create_compiled_fs(
349 lambda api_name, api: self._LoadIdlAPI(api, True), 426 lambda api_name, api: self._LoadIdlAPI(api, True),
350 'idl-no-refs') 427 'idl-no-refs')
351 428
352 self._idl_names_cache = create_compiled_fs(self._GetIDLNames, 'idl-names') 429 self._idl_names_cache = create_compiled_fs(self._GetIDLNames, 'idl-names')
353 self._names_cache = create_compiled_fs(self._GetAllNames, 'names') 430 self._names_cache = create_compiled_fs(self._GetAllNames, 'names')
354 431
355 self._base_path = base_path 432 self._base_path = base_path
356 433 self._availability_finder = availability_finder_factory.Create()
434 self._intro_cache = create_compiled_fs(
435 lambda _, json: json_parse.Parse(json),
436 'intro-cache')
437 self._partial_cache = create_compiled_fs(
438 lambda _, text: Handlebar(text),
439 'partial-cache')
357 # These must be set later via the SetFooDataSourceFactory methods. 440 # These must be set later via the SetFooDataSourceFactory methods.
358 self._ref_resolver_factory = None 441 self._ref_resolver_factory = None
359 self._samples_data_source_factory = None 442 self._samples_data_source_factory = None
360 443
361 def SetSamplesDataSourceFactory(self, samples_data_source_factory): 444 def SetSamplesDataSourceFactory(self, samples_data_source_factory):
362 self._samples_data_source_factory = samples_data_source_factory 445 self._samples_data_source_factory = samples_data_source_factory
363 446
364 def SetReferenceResolverFactory(self, ref_resolver_factory): 447 def SetReferenceResolverFactory(self, ref_resolver_factory):
365 self._ref_resolver_factory = ref_resolver_factory 448 self._ref_resolver_factory = ref_resolver_factory
366 449
(...skipping 25 matching lines...) Expand all
392 samples, 475 samples,
393 disable_refs) 476 disable_refs)
394 477
395 def _LoadPermissions(self, file_name, json_str): 478 def _LoadPermissions(self, file_name, json_str):
396 return json_parse.Parse(json_str) 479 return json_parse.Parse(json_str)
397 480
398 def _LoadJsonAPI(self, api, disable_refs): 481 def _LoadJsonAPI(self, api, disable_refs):
399 return _JSCModel( 482 return _JSCModel(
400 json_parse.Parse(api)[0], 483 json_parse.Parse(api)[0],
401 self._ref_resolver_factory.Create() if not disable_refs else None, 484 self._ref_resolver_factory.Create() if not disable_refs else None,
402 disable_refs).ToDict() 485 disable_refs,
486 self._availability_finder,
487 self._intro_cache,
488 self._partial_cache).ToDict()
403 489
404 def _LoadIdlAPI(self, api, disable_refs): 490 def _LoadIdlAPI(self, api, disable_refs):
405 idl = idl_parser.IDLParser().ParseData(api) 491 idl = idl_parser.IDLParser().ParseData(api)
406 return _JSCModel( 492 return _JSCModel(
407 idl_schema.IDLSchema(idl).process()[0], 493 idl_schema.IDLSchema(idl).process()[0],
408 self._ref_resolver_factory.Create() if not disable_refs else None, 494 self._ref_resolver_factory.Create() if not disable_refs else None,
409 disable_refs, 495 disable_refs,
496 self._availability_finder,
497 self._intro_cache,
498 self._partial_cache,
410 idl=True).ToDict() 499 idl=True).ToDict()
411 500
412 def _GetIDLNames(self, base_dir, apis): 501 def _GetIDLNames(self, base_dir, apis):
413 return self._GetExtNames(apis, ['idl']) 502 return self._GetExtNames(apis, ['idl'])
414 503
415 def _GetAllNames(self, base_dir, apis): 504 def _GetAllNames(self, base_dir, apis):
416 return self._GetExtNames(apis, ['json', 'idl']) 505 return self._GetExtNames(apis, ['json', 'idl'])
417 506
418 def _GetExtNames(self, apis, exts): 507 def _GetExtNames(self, apis, exts):
419 return [model.UnixName(os.path.splitext(api)[0]) for api in apis 508 return [model.UnixName(os.path.splitext(api)[0]) for api in apis
(...skipping 57 matching lines...) Expand 10 before | Expand all | Expand 10 after
477 return feature_data 566 return feature_data
478 567
479 def _GenerateHandlebarContext(self, handlebar_dict, path): 568 def _GenerateHandlebarContext(self, handlebar_dict, path):
480 handlebar_dict['permissions'] = self._GetFeatureData(path) 569 handlebar_dict['permissions'] = self._GetFeatureData(path)
481 handlebar_dict['samples'] = _LazySamplesGetter(path, self._samples) 570 handlebar_dict['samples'] = _LazySamplesGetter(path, self._samples)
482 return handlebar_dict 571 return handlebar_dict
483 572
484 def _GetAsSubdirectory(self, name): 573 def _GetAsSubdirectory(self, name):
485 if name.startswith('experimental_'): 574 if name.startswith('experimental_'):
486 parts = name[len('experimental_'):].split('_', 1) 575 parts = name[len('experimental_'):].split('_', 1)
487 parts[1] = 'experimental_%s' % parts[1] 576 if len(parts) > 1:
488 return '/'.join(parts) 577 parts[1] = 'experimental_%s' % parts[1]
578 return '/'.join(parts)
579 return '%s/%s' % (parts[0], name)
489 return name.replace('_', '/', 1) 580 return name.replace('_', '/', 1)
490 581
491 def get(self, key): 582 def get(self, key):
492 if key.endswith('.html') or key.endswith('.json') or key.endswith('.idl'): 583 if key.endswith('.html') or key.endswith('.json') or key.endswith('.idl'):
493 path, ext = os.path.splitext(key) 584 path, ext = os.path.splitext(key)
494 else: 585 else:
495 path = key 586 path = key
496 unix_name = model.UnixName(path) 587 unix_name = model.UnixName(path)
497 idl_names = self._idl_names_cache.GetFromFileListing(self._base_path) 588 idl_names = self._idl_names_cache.GetFromFileListing(self._base_path)
498 names = self._names_cache.GetFromFileListing(self._base_path) 589 names = self._names_cache.GetFromFileListing(self._base_path)
499 if unix_name not in names and self._GetAsSubdirectory(unix_name) in names: 590 if unix_name not in names and self._GetAsSubdirectory(unix_name) in names:
500 unix_name = self._GetAsSubdirectory(unix_name) 591 unix_name = self._GetAsSubdirectory(unix_name)
501 592
502 if self._disable_refs: 593 if self._disable_refs:
503 cache, ext = ( 594 cache, ext = (
504 (self._idl_cache_no_refs, '.idl') if (unix_name in idl_names) else 595 (self._idl_cache_no_refs, '.idl') if (unix_name in idl_names) else
505 (self._json_cache_no_refs, '.json')) 596 (self._json_cache_no_refs, '.json'))
506 else: 597 else:
507 cache, ext = ((self._idl_cache, '.idl') if (unix_name in idl_names) else 598 cache, ext = ((self._idl_cache, '.idl') if (unix_name in idl_names) else
508 (self._json_cache, '.json')) 599 (self._json_cache, '.json'))
509 return self._GenerateHandlebarContext( 600 return self._GenerateHandlebarContext(
510 cache.GetFromFile('%s/%s%s' % (self._base_path, unix_name, ext)), 601 cache.GetFromFile('%s/%s%s' % (self._base_path, unix_name, ext)),
511 path) 602 path)
OLDNEW
« no previous file with comments | « no previous file | 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