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

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

Issue 12996003: Dynamically generate a heading for Extension Docs API pages (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Updates to HasAPI in APIDataSource Created 7 years, 8 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 8
9 import compiled_file_system as compiled_fs 9 import compiled_file_system as compiled_fs
10 from file_system import FileNotFoundError 10 from file_system import FileNotFoundError
11 import third_party.json_schema_compiler.json_parse as json_parse 11 import third_party.json_schema_compiler.json_parse as json_parse
12 import third_party.json_schema_compiler.model as model 12 import third_party.json_schema_compiler.model as model
13 import third_party.json_schema_compiler.idl_schema as idl_schema 13 import third_party.json_schema_compiler.idl_schema as idl_schema
14 import third_party.json_schema_compiler.idl_parser as idl_parser 14 import third_party.json_schema_compiler.idl_parser as idl_parser
15 15
16 # Increment this version when there are changes to the data stored in any of 16 # Increment this version when there are changes to the data stored in any of
17 # the caches used by APIDataSource. This would include changes to model.py in 17 # the caches used by APIDataSource. This would include changes to model.py in
18 # JSON schema compiler! This allows the cache to be invalidated without having 18 # JSON schema compiler! This allows the cache to be invalidated without having
19 # to flush memcache on the production server. 19 # to flush memcache on the production server.
20 _VERSION = 15 20 _VERSION = 16
21 21
22 def _RemoveNoDocs(item): 22 def _RemoveNoDocs(item):
23 if json_parse.IsDict(item): 23 if json_parse.IsDict(item):
24 if item.get('nodoc', False): 24 if item.get('nodoc', False):
25 return True 25 return True
26 to_remove = [] 26 to_remove = []
27 for key, value in item.items(): 27 for key, value in item.items():
28 if _RemoveNoDocs(value): 28 if _RemoveNoDocs(value):
29 to_remove.append(key) 29 to_remove.append(key)
30 for k in to_remove: 30 for k in to_remove:
(...skipping 15 matching lines...) Expand all
46 def _FormatValue(value): 46 def _FormatValue(value):
47 """Inserts commas every three digits for integer values. It is magic. 47 """Inserts commas every three digits for integer values. It is magic.
48 """ 48 """
49 s = str(value) 49 s = str(value)
50 return ','.join([s[max(0, i - 3):i] for i in range(len(s), 0, -3)][::-1]) 50 return ','.join([s[max(0, i - 3):i] for i in range(len(s), 0, -3)][::-1])
51 51
52 class _JSCModel(object): 52 class _JSCModel(object):
53 """Uses a Model from the JSON Schema Compiler and generates a dict that 53 """Uses a Model from the JSON Schema Compiler and generates a dict that
54 a Handlebar template can use for a data source. 54 a Handlebar template can use for a data source.
55 """ 55 """
56 def __init__(self, json, ref_resolver, disable_refs): 56 def __init__(self,
57 json,
58 ref_resolver,
59 disable_refs,
60 availability_data_source=None):
57 self._ref_resolver = ref_resolver 61 self._ref_resolver = ref_resolver
58 self._disable_refs = disable_refs 62 self._disable_refs = disable_refs
63 self._availability_data_source = availability_data_source
59 clean_json = copy.deepcopy(json) 64 clean_json = copy.deepcopy(json)
60 if _RemoveNoDocs(clean_json): 65 if _RemoveNoDocs(clean_json):
61 self._namespace = None 66 self._namespace = None
62 else: 67 else:
63 self._namespace = model.Namespace(clean_json, clean_json['namespace']) 68 self._namespace = model.Namespace(clean_json, clean_json['namespace'])
64 69
65 def _FormatDescription(self, description): 70 def _FormatDescription(self, description):
66 if self._disable_refs: 71 if self._disable_refs:
67 return description 72 return description
68 return self._ref_resolver.ResolveAllLinks(description, 73 return self._ref_resolver.ResolveAllLinks(description,
69 namespace=self._namespace.name) 74 namespace=self._namespace.name)
70 75
71 def _GetLink(self, link): 76 def _GetLink(self, link):
72 if self._disable_refs: 77 if self._disable_refs:
73 type_name = link.split('.', 1)[-1] 78 type_name = link.split('.', 1)[-1]
74 return { 'href': '#type-%s' % type_name, 'text': link, 'name': link } 79 return { 'href': '#type-%s' % type_name, 'text': link, 'name': link }
75 return self._ref_resolver.SafeGetLink(link, namespace=self._namespace.name) 80 return self._ref_resolver.SafeGetLink(link, namespace=self._namespace.name)
76 81
77 def ToDict(self): 82 def ToDict(self):
78 if self._namespace is None: 83 if self._namespace is None:
79 return {} 84 return {}
80 return { 85 return {
81 'name': self._namespace.name, 86 'name': self._namespace.name,
87 'description': self._namespace.description,
88 'availability': self._HandleAvailability(),
82 'types': self._GenerateTypes(self._namespace.types.values()), 89 'types': self._GenerateTypes(self._namespace.types.values()),
83 'functions': self._GenerateFunctions(self._namespace.functions), 90 'functions': self._GenerateFunctions(self._namespace.functions),
84 'events': self._GenerateEvents(self._namespace.events), 91 'events': self._GenerateEvents(self._namespace.events),
85 'properties': self._GenerateProperties(self._namespace.properties) 92 'properties': self._GenerateProperties(self._namespace.properties)
86 } 93 }
87 94
95 def _GetAvailability(self):
96 """Returns the earliest version of chrome, represented by a version number,
97 that this api was available in.
98 """
99 if self._availability_data_source is not None:
100 return self._availability_data_source.FindEarliestAvailability(
101 self._namespace.name)
102
103 def _HandleAvailability(self):
104 """Finds the availability for an api, and creates a string describing
105 the availability depending on its original format.
106 """
107 availability = self._namespace.availability
108 availability_string = 'Not currently available'
109 # Check to see if the .json/.idl already contains an availability field.
110 if availability is None:
111 availability = self._GetAvailability()
112
113 if availability is not None:
114 if availability.isdigit():
115 availability_string = 'Google Chrome %s' % availability
116 else:
117 availability_string = ('Google Chrome %s Channel Only' %
118 availability.capitalize())
119 return availability_string
120
88 def _GenerateTypes(self, types): 121 def _GenerateTypes(self, types):
89 return [self._GenerateType(t) for t in types] 122 return [self._GenerateType(t) for t in types]
90 123
91 def _GenerateType(self, type_): 124 def _GenerateType(self, type_):
92 type_dict = { 125 type_dict = {
93 'name': type_.simple_name, 126 'name': type_.simple_name,
94 'description': self._FormatDescription(type_.description), 127 'description': self._FormatDescription(type_.description),
95 'properties': self._GenerateProperties(type_.properties), 128 'properties': self._GenerateProperties(type_.properties),
96 'functions': self._GenerateFunctions(type_.functions), 129 'functions': self._GenerateFunctions(type_.functions),
97 'events': self._GenerateEvents(type_.events), 130 'events': self._GenerateEvents(type_.events),
(...skipping 167 matching lines...) Expand 10 before | Expand all | Expand 10 after
265 def get(self, key): 298 def get(self, key):
266 return self._samples.FilterSamples(key, self._api_name) 299 return self._samples.FilterSamples(key, self._api_name)
267 300
268 class APIDataSource(object): 301 class APIDataSource(object):
269 """This class fetches and loads JSON APIs from the FileSystem passed in with 302 """This class fetches and loads JSON APIs from the FileSystem passed in with
270 |cache_factory|, so the APIs can be plugged into templates. 303 |cache_factory|, so the APIs can be plugged into templates.
271 """ 304 """
272 class Factory(object): 305 class Factory(object):
273 def __init__(self, 306 def __init__(self,
274 cache_factory, 307 cache_factory,
275 base_path): 308 base_path,
309 availability_data_source=None):
276 self._permissions_cache = cache_factory.Create(self._LoadPermissions, 310 self._permissions_cache = cache_factory.Create(self._LoadPermissions,
277 compiled_fs.PERMS, 311 compiled_fs.PERMS,
278 version=_VERSION) 312 version=_VERSION)
279 self._json_cache = cache_factory.Create( 313 self._json_cache = cache_factory.Create(
280 lambda api_name, api: self._LoadJsonAPI(api, False), 314 lambda api_name, api: self._LoadJsonAPI(api, False),
281 compiled_fs.JSON, 315 compiled_fs.JSON,
282 version=_VERSION) 316 version=_VERSION)
283 self._idl_cache = cache_factory.Create( 317 self._idl_cache = cache_factory.Create(
284 lambda api_name, api: self._LoadIdlAPI(api, False), 318 lambda api_name, api: self._LoadIdlAPI(api, False),
285 compiled_fs.IDL, 319 compiled_fs.IDL,
(...skipping 10 matching lines...) Expand all
296 lambda api_name, api: self._LoadIdlAPI(api, True), 330 lambda api_name, api: self._LoadIdlAPI(api, True),
297 compiled_fs.IDL_NO_REFS, 331 compiled_fs.IDL_NO_REFS,
298 version=_VERSION) 332 version=_VERSION)
299 self._idl_names_cache = cache_factory.Create(self._GetIDLNames, 333 self._idl_names_cache = cache_factory.Create(self._GetIDLNames,
300 compiled_fs.IDL_NAMES, 334 compiled_fs.IDL_NAMES,
301 version=_VERSION) 335 version=_VERSION)
302 self._names_cache = cache_factory.Create(self._GetAllNames, 336 self._names_cache = cache_factory.Create(self._GetAllNames,
303 compiled_fs.NAMES, 337 compiled_fs.NAMES,
304 version=_VERSION) 338 version=_VERSION)
305 self._base_path = base_path 339 self._base_path = base_path
306 340 self._availability_data_source = availability_data_source
307 # These must be set later via the SetFooDataSourceFactory methods. 341 # These must be set later via the SetFooDataSourceFactory methods.
308 self._ref_resolver_factory = None 342 self._ref_resolver_factory = None
309 self._samples_data_source_factory = None 343 self._samples_data_source_factory = None
310 344
311 def SetSamplesDataSourceFactory(self, samples_data_source_factory): 345 def SetSamplesDataSourceFactory(self, samples_data_source_factory):
312 self._samples_data_source_factory = samples_data_source_factory 346 self._samples_data_source_factory = samples_data_source_factory
313 347
314 def SetReferenceResolverFactory(self, ref_resolver_factory): 348 def SetReferenceResolverFactory(self, ref_resolver_factory):
315 self._ref_resolver_factory = ref_resolver_factory 349 self._ref_resolver_factory = ref_resolver_factory
316 350
(...skipping 25 matching lines...) Expand all
342 samples, 376 samples,
343 disable_refs) 377 disable_refs)
344 378
345 def _LoadPermissions(self, file_name, json_str): 379 def _LoadPermissions(self, file_name, json_str):
346 return json_parse.Parse(json_str) 380 return json_parse.Parse(json_str)
347 381
348 def _LoadJsonAPI(self, api, disable_refs): 382 def _LoadJsonAPI(self, api, disable_refs):
349 return _JSCModel( 383 return _JSCModel(
350 json_parse.Parse(api)[0], 384 json_parse.Parse(api)[0],
351 self._ref_resolver_factory.Create() if not disable_refs else None, 385 self._ref_resolver_factory.Create() if not disable_refs else None,
352 disable_refs).ToDict() 386 disable_refs,
387 self._availability_data_source).ToDict()
353 388
354 def _LoadIdlAPI(self, api, disable_refs): 389 def _LoadIdlAPI(self, api, disable_refs):
355 idl = idl_parser.IDLParser().ParseData(api) 390 idl = idl_parser.IDLParser().ParseData(api)
356 return _JSCModel( 391 return _JSCModel(
357 idl_schema.IDLSchema(idl).process()[0], 392 idl_schema.IDLSchema(idl).process()[0],
358 self._ref_resolver_factory.Create() if not disable_refs else None, 393 self._ref_resolver_factory.Create() if not disable_refs else None,
359 disable_refs).ToDict() 394 disable_refs,
395 self._availability_data_source).ToDict()
360 396
361 def _GetIDLNames(self, base_dir, apis): 397 def _GetIDLNames(self, base_dir, apis):
362 return [ 398 return [
363 model.UnixName(os.path.splitext(api[len('%s/' % self._base_path):])[0]) 399 model.UnixName(os.path.splitext(api[len('%s/' % self._base_path):])[0])
364 for api in apis if api.endswith('.idl') 400 for api in apis if api.endswith('.idl')
365 ] 401 ]
366 402
367 def _GetAllNames(self, base_dir, apis): 403 def _GetAllNames(self, base_dir, apis):
368 return [ 404 return [
369 model.UnixName(os.path.splitext(api[len('%s/' % self._base_path):])[0]) 405 model.UnixName(os.path.splitext(api[len('%s/' % self._base_path):])[0])
(...skipping 61 matching lines...) Expand 10 before | Expand all | Expand 10 after
431 return feature_data 467 return feature_data
432 468
433 def _GenerateHandlebarContext(self, handlebar_dict, path): 469 def _GenerateHandlebarContext(self, handlebar_dict, path):
434 handlebar_dict['permissions'] = self._GetFeatureData(path) 470 handlebar_dict['permissions'] = self._GetFeatureData(path)
435 handlebar_dict['samples'] = _LazySamplesGetter(path, self._samples) 471 handlebar_dict['samples'] = _LazySamplesGetter(path, self._samples)
436 return handlebar_dict 472 return handlebar_dict
437 473
438 def _GetAsSubdirectory(self, name): 474 def _GetAsSubdirectory(self, name):
439 if name.startswith('experimental_'): 475 if name.startswith('experimental_'):
440 parts = name[len('experimental_'):].split('_', 1) 476 parts = name[len('experimental_'):].split('_', 1)
441 parts[1] = 'experimental_%s' % parts[1] 477 if len(parts) > 1:
442 return '/'.join(parts) 478 parts[1] = 'experimental_%s' % parts[1]
479 return '/'.join(parts)
480 else:
481 return '%s/%s' % (parts[0], name)
443 return name.replace('_', '/', 1) 482 return name.replace('_', '/', 1)
444 483
445 def get(self, key): 484 def _DetermineNamesForGet(self, key):
446 if key.endswith('.html') or key.endswith('.json') or key.endswith('.idl'): 485 if key.endswith('.html') or key.endswith('.json') or key.endswith('.idl'):
447 path, ext = os.path.splitext(key) 486 path, ext = os.path.splitext(key)
448 else: 487 else:
449 path = key 488 path = key
450 unix_name = model.UnixName(path) 489 unix_name = model.UnixName(path)
451 idl_names = self._idl_names_cache.GetFromFileListing(self._base_path)
452 names = self._names_cache.GetFromFileListing(self._base_path) 490 names = self._names_cache.GetFromFileListing(self._base_path)
453 if unix_name not in names and self._GetAsSubdirectory(unix_name) in names: 491 if unix_name not in names and self._GetAsSubdirectory(unix_name) in names:
454 unix_name = self._GetAsSubdirectory(unix_name) 492 unix_name = self._GetAsSubdirectory(unix_name)
493 return (path, unix_name)
455 494
495 def _DetermineCacheForGet(self, unix_name):
496 idl_names = self._idl_names_cache.GetFromFileListing(self._base_path)
456 if self._disable_refs: 497 if self._disable_refs:
457 cache, ext = ( 498 cache, ext = (
458 (self._idl_cache_no_refs, '.idl') if (unix_name in idl_names) else 499 (self._idl_cache_no_refs, '.idl') if (unix_name in idl_names) else
459 (self._json_cache_no_refs, '.json')) 500 (self._json_cache_no_refs, '.json'))
460 else: 501 else:
461 cache, ext = ((self._idl_cache, '.idl') if (unix_name in idl_names) else 502 cache, ext = ((self._idl_cache, '.idl') if (unix_name in idl_names) else
462 (self._json_cache, '.json')) 503 (self._json_cache, '.json'))
504 return (cache, ext)
505
506 def get(self, key):
507 path, unix_name = self._DetermineNamesForGet(key)
508 cache, ext = self._DetermineCacheForGet(unix_name)
463 return self._GenerateHandlebarContext( 509 return self._GenerateHandlebarContext(
464 cache.GetFromFile('%s/%s%s' % (self._base_path, unix_name, ext)), 510 cache.GetFromFile('%s/%s%s' % (self._base_path, unix_name, ext)),
465 path) 511 path)
512
513 def HasAPI(self, key):
514 """Like get(self, key), only doesn't generate and return HandlebarContext.
515 Used for checking existence of an api: cache will raise a FileNotFoundError
516 if an api cannot be located in the cache.
517 """
518 camel_name, unix_name = self._DetermineNamesForGet(key)
519 cache, ext = self._DetermineCacheForGet(unix_name)
520 try:
521 cache.GetFromFile('%s/%s%s' % (self._base_path, camel_name, ext))
522 return True
523 except model.ParseException as e:
524 # Some APIs in older versions trip up the JSC (i.e. v.18 tabs.json
525 # lack a "type" attribute for its "url" property)
526 # If, however, this exception is caught, then the API had been found
527 # and was in the process of being parsed, so we can return True.
528 logging.warning('Caught parse exception for %s: %s' % (unix_name, e))
529 return True
530 except FileNotFoundError:
531 try:
532 cache.GetFromFile('%s/%s%s' % (self._base_path, unix_name, ext))
533 return True
534 except FileNotFoundError:
535 return False
536 except model.ParseException as e:
537 logging.warning('Caught parse exception for %s: %s' % (unix_name, e))
538 return True
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698