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

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: Minor Cleanup 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 {}
85 availability = self._HandleAvailability()
not at google - send to devlin 2013/04/02 10:29:39 inline?
epeterson 2013/04/03 01:21:43 Done.
80 return { 86 return {
81 'name': self._namespace.name, 87 'name': self._namespace.name,
88 'description': self._namespace.description,
89 'availability': availability,
82 'types': self._GenerateTypes(self._namespace.types.values()), 90 'types': self._GenerateTypes(self._namespace.types.values()),
83 'functions': self._GenerateFunctions(self._namespace.functions), 91 'functions': self._GenerateFunctions(self._namespace.functions),
84 'events': self._GenerateEvents(self._namespace.events), 92 'events': self._GenerateEvents(self._namespace.events),
85 'properties': self._GenerateProperties(self._namespace.properties) 93 'properties': self._GenerateProperties(self._namespace.properties)
86 } 94 }
87 95
96 def _GetAvailability(self):
97 """Returns the earliest version of chrome, represented by a version number,
98 that this api was available in.
99 """
100 if self._availability_data_source is not None:
not at google - send to devlin 2013/04/02 10:29:39 when is there no availability data source?
epeterson 2013/04/03 01:21:43 Each channel instance has an APIDataSourceFactory
101 return self._availability_data_source.FindEarliestAvailability(
102 self._namespace.name)
103
104 def _HandleAvailability(self):
105 """Finds the availability for an api, and creates a string describing
106 the availability depending on its original format.
107 """
108 availability = self._namespace.availability
109 availability_string = 'Not currently available'
110 # Check to see if the .json/.idl already contains an availability field.
111 if availability is None:
112 availability = self._GetAvailability()
113
114 if availability is not None:
115 if availability.isdigit():
116 availability_string = 'Google Chrome %s' % availability
117 else:
118 availability_string = ('Google Chrome %s Channel Only' %
119 availability.capitalize())
120 return availability_string
not at google - send to devlin 2013/04/02 10:29:39 All of this string logic needs to be embedded in t
not at google - send to devlin 2013/04/02 21:58:16 Ok - so I think it's fine to submit the server cha
121
88 def _GenerateTypes(self, types): 122 def _GenerateTypes(self, types):
89 return [self._GenerateType(t) for t in types] 123 return [self._GenerateType(t) for t in types]
90 124
91 def _GenerateType(self, type_): 125 def _GenerateType(self, type_):
92 type_dict = { 126 type_dict = {
93 'name': type_.simple_name, 127 'name': type_.simple_name,
94 'description': self._FormatDescription(type_.description), 128 'description': self._FormatDescription(type_.description),
95 'properties': self._GenerateProperties(type_.properties), 129 'properties': self._GenerateProperties(type_.properties),
96 'functions': self._GenerateFunctions(type_.functions), 130 'functions': self._GenerateFunctions(type_.functions),
97 'events': self._GenerateEvents(type_.events), 131 'events': self._GenerateEvents(type_.events),
(...skipping 167 matching lines...) Expand 10 before | Expand all | Expand 10 after
265 def get(self, key): 299 def get(self, key):
266 return self._samples.FilterSamples(key, self._api_name) 300 return self._samples.FilterSamples(key, self._api_name)
267 301
268 class APIDataSource(object): 302 class APIDataSource(object):
269 """This class fetches and loads JSON APIs from the FileSystem passed in with 303 """This class fetches and loads JSON APIs from the FileSystem passed in with
270 |cache_factory|, so the APIs can be plugged into templates. 304 |cache_factory|, so the APIs can be plugged into templates.
271 """ 305 """
272 class Factory(object): 306 class Factory(object):
273 def __init__(self, 307 def __init__(self,
274 cache_factory, 308 cache_factory,
275 base_path): 309 base_path,
310 availability_data_source=None):
276 self._permissions_cache = cache_factory.Create(self._LoadPermissions, 311 self._permissions_cache = cache_factory.Create(self._LoadPermissions,
277 compiled_fs.PERMS, 312 compiled_fs.PERMS,
278 version=_VERSION) 313 version=_VERSION)
279 self._json_cache = cache_factory.Create( 314 self._json_cache = cache_factory.Create(
280 lambda api_name, api: self._LoadJsonAPI(api, False), 315 lambda api_name, api: self._LoadJsonAPI(api, False),
281 compiled_fs.JSON, 316 compiled_fs.JSON,
282 version=_VERSION) 317 version=_VERSION)
283 self._idl_cache = cache_factory.Create( 318 self._idl_cache = cache_factory.Create(
284 lambda api_name, api: self._LoadIdlAPI(api, False), 319 lambda api_name, api: self._LoadIdlAPI(api, False),
285 compiled_fs.IDL, 320 compiled_fs.IDL,
(...skipping 10 matching lines...) Expand all
296 lambda api_name, api: self._LoadIdlAPI(api, True), 331 lambda api_name, api: self._LoadIdlAPI(api, True),
297 compiled_fs.IDL_NO_REFS, 332 compiled_fs.IDL_NO_REFS,
298 version=_VERSION) 333 version=_VERSION)
299 self._idl_names_cache = cache_factory.Create(self._GetIDLNames, 334 self._idl_names_cache = cache_factory.Create(self._GetIDLNames,
300 compiled_fs.IDL_NAMES, 335 compiled_fs.IDL_NAMES,
301 version=_VERSION) 336 version=_VERSION)
302 self._names_cache = cache_factory.Create(self._GetAllNames, 337 self._names_cache = cache_factory.Create(self._GetAllNames,
303 compiled_fs.NAMES, 338 compiled_fs.NAMES,
304 version=_VERSION) 339 version=_VERSION)
305 self._base_path = base_path 340 self._base_path = base_path
306 341 self._availability_data_source = availability_data_source
307 # These must be set later via the SetFooDataSourceFactory methods. 342 # These must be set later via the SetFooDataSourceFactory methods.
308 self._ref_resolver_factory = None 343 self._ref_resolver_factory = None
309 self._samples_data_source_factory = None 344 self._samples_data_source_factory = None
310 345
311 def SetSamplesDataSourceFactory(self, samples_data_source_factory): 346 def SetSamplesDataSourceFactory(self, samples_data_source_factory):
312 self._samples_data_source_factory = samples_data_source_factory 347 self._samples_data_source_factory = samples_data_source_factory
313 348
314 def SetReferenceResolverFactory(self, ref_resolver_factory): 349 def SetReferenceResolverFactory(self, ref_resolver_factory):
315 self._ref_resolver_factory = ref_resolver_factory 350 self._ref_resolver_factory = ref_resolver_factory
316 351
(...skipping 25 matching lines...) Expand all
342 samples, 377 samples,
343 disable_refs) 378 disable_refs)
344 379
345 def _LoadPermissions(self, file_name, json_str): 380 def _LoadPermissions(self, file_name, json_str):
346 return json_parse.Parse(json_str) 381 return json_parse.Parse(json_str)
347 382
348 def _LoadJsonAPI(self, api, disable_refs): 383 def _LoadJsonAPI(self, api, disable_refs):
349 return _JSCModel( 384 return _JSCModel(
350 json_parse.Parse(api)[0], 385 json_parse.Parse(api)[0],
351 self._ref_resolver_factory.Create() if not disable_refs else None, 386 self._ref_resolver_factory.Create() if not disable_refs else None,
352 disable_refs).ToDict() 387 disable_refs,
388 self._availability_data_source).ToDict()
353 389
354 def _LoadIdlAPI(self, api, disable_refs): 390 def _LoadIdlAPI(self, api, disable_refs):
355 idl = idl_parser.IDLParser().ParseData(api) 391 idl = idl_parser.IDLParser().ParseData(api)
356 return _JSCModel( 392 return _JSCModel(
357 idl_schema.IDLSchema(idl).process()[0], 393 idl_schema.IDLSchema(idl).process()[0],
358 self._ref_resolver_factory.Create() if not disable_refs else None, 394 self._ref_resolver_factory.Create() if not disable_refs else None,
359 disable_refs).ToDict() 395 disable_refs,
396 self._availability_data_source).ToDict()
360 397
361 def _GetIDLNames(self, base_dir, apis): 398 def _GetIDLNames(self, base_dir, apis):
362 return [ 399 return [
363 model.UnixName(os.path.splitext(api[len('%s/' % self._base_path):])[0]) 400 model.UnixName(os.path.splitext(api[len('%s/' % self._base_path):])[0])
364 for api in apis if api.endswith('.idl') 401 for api in apis if api.endswith('.idl')
365 ] 402 ]
366 403
367 def _GetAllNames(self, base_dir, apis): 404 def _GetAllNames(self, base_dir, apis):
368 return [ 405 return [
369 model.UnixName(os.path.splitext(api[len('%s/' % self._base_path):])[0]) 406 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 468 return feature_data
432 469
433 def _GenerateHandlebarContext(self, handlebar_dict, path): 470 def _GenerateHandlebarContext(self, handlebar_dict, path):
434 handlebar_dict['permissions'] = self._GetFeatureData(path) 471 handlebar_dict['permissions'] = self._GetFeatureData(path)
435 handlebar_dict['samples'] = _LazySamplesGetter(path, self._samples) 472 handlebar_dict['samples'] = _LazySamplesGetter(path, self._samples)
436 return handlebar_dict 473 return handlebar_dict
437 474
438 def _GetAsSubdirectory(self, name): 475 def _GetAsSubdirectory(self, name):
439 if name.startswith('experimental_'): 476 if name.startswith('experimental_'):
440 parts = name[len('experimental_'):].split('_', 1) 477 parts = name[len('experimental_'):].split('_', 1)
441 parts[1] = 'experimental_%s' % parts[1] 478 if len(parts) > 1:
442 return '/'.join(parts) 479 parts[1] = 'experimental_%s' % parts[1]
480 return '/'.join(parts)
481 else:
482 return '%s/%s' % (parts[0], name)
443 return name.replace('_', '/', 1) 483 return name.replace('_', '/', 1)
444 484
445 def get(self, key): 485 def _DetermineNamesForGet(self, key):
446 if key.endswith('.html') or key.endswith('.json') or key.endswith('.idl'): 486 if key.endswith('.html') or key.endswith('.json') or key.endswith('.idl'):
447 path, ext = os.path.splitext(key) 487 path, ext = os.path.splitext(key)
448 else: 488 else:
449 path = key 489 path = key
450 unix_name = model.UnixName(path) 490 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) 491 names = self._names_cache.GetFromFileListing(self._base_path)
453 if unix_name not in names and self._GetAsSubdirectory(unix_name) in names: 492 if unix_name not in names and self._GetAsSubdirectory(unix_name) in names:
454 unix_name = self._GetAsSubdirectory(unix_name) 493 unix_name = self._GetAsSubdirectory(unix_name)
494 return (path, unix_name)
455 495
496 def _DetermineCacheForGet(self, unix_name):
497 idl_names = self._idl_names_cache.GetFromFileListing(self._base_path)
456 if self._disable_refs: 498 if self._disable_refs:
457 cache, ext = ( 499 cache, ext = (
458 (self._idl_cache_no_refs, '.idl') if (unix_name in idl_names) else 500 (self._idl_cache_no_refs, '.idl') if (unix_name in idl_names) else
459 (self._json_cache_no_refs, '.json')) 501 (self._json_cache_no_refs, '.json'))
460 else: 502 else:
461 cache, ext = ((self._idl_cache, '.idl') if (unix_name in idl_names) else 503 cache, ext = ((self._idl_cache, '.idl') if (unix_name in idl_names) else
462 (self._json_cache, '.json')) 504 (self._json_cache, '.json'))
505 return (cache, ext)
506
507 def get(self, key):
508 path, unix_name = self._DetermineNamesForGet(key)
509 cache, ext = self._DetermineCacheForGet(unix_name)
463 return self._GenerateHandlebarContext( 510 return self._GenerateHandlebarContext(
464 cache.GetFromFile('%s/%s%s' % (self._base_path, unix_name, ext)), 511 cache.GetFromFile('%s/%s%s' % (self._base_path, unix_name, ext)),
465 path) 512 path)
513
514 def TryGet(self, key, try_non_unix=False):
not at google - send to devlin 2013/04/02 10:29:39 Note to future self: unclear what this should be r
epeterson 2013/04/03 03:59:57 You're right, it doesn't make sense to return an u
515 """Like get(self, key), only doesn't generate and return HandlebarContext.
516 Used for checking existence of an api: cache will raise a FileNotFoundError
517 if an api cannot be located in the cache.
518 """
519 camel_name, unix_name = self._DetermineNamesForGet(key)
520 cache, ext = self._DetermineCacheForGet(unix_name)
521 try:
522 if try_non_unix is True:
523 return cache.GetFromFile('%s/%s%s' % (self._base_path, camel_name, ext))
524 return cache.GetFromFile('%s/%s%s' % (self._base_path, unix_name, ext))
525 except model.ParseException as e:
526 # Some APIs in older versions trip up the JSC (i.e. v.18 tabs.json lacks
527 # a "type" attribute for its "url" property)
528 logging.warning('Caught parse exception for %s: %s' % (unix_name, e))
529 return {}
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698