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