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

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

Issue 10826024: Extensions Docs Server: Proper $ref handling (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Created 8 years, 4 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 | Annotate | Revision Log
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 third_party.json_schema_compiler.model as model 9 import third_party.json_schema_compiler.model as model
10 10
11 def _RemoveNoDocs(item): 11 def _RemoveNoDocs(item):
12 if type(item) == dict: 12 if type(item) == dict:
13 if item.get('nodoc', False): 13 if item.get('nodoc', False):
14 return True 14 return True
15 for key, value in item.items(): 15 for key, value in item.items():
16 if _RemoveNoDocs(value): 16 if _RemoveNoDocs(value):
17 del item[key] 17 del item[key]
18 elif type(item) == list: 18 elif type(item) == list:
19 for i in item: 19 for i in item:
20 if _RemoveNoDocs(i): 20 if _RemoveNoDocs(i):
21 item.remove(i) 21 item.remove(i)
22 return False 22 return False
23 23
24 def _GetLinkToRefType(namespace_name, ref_type): 24 def _GetLinkToRefType(namespace_name, ref_type):
25 terms = ref_type.split('.') 25 if ref_type.startswith(namespace_name + '.'):
26 if len(terms) > 1: 26 type_name = ref_type[namespace_name + '.':]
not at google - send to devlin 2012/07/26 03:12:27 is this supposed to be len(namespace_name + '.') ?
cduvall 2012/07/26 17:57:44 Done.
27 text = '.'.join(terms[1:]) 27 return { 'href': '#type-' + type_name, 'text': type_name }
28 href = terms[0] + '.html' + '#type-' + text 28 elif '.' not in ref_type:
29 else: 29 return { 'href': '#type-' + ref_type, 'text': ref_type }
30 href = namespace_name + '.html' + '#type-' +ref_type 30 api, type_name = ref_type.rsplit('.', 1)
31 text = ref_type 31 return { 'href': api + '.html#type-' + type_name, 'text': ref_type }
32 return ({
33 "href": href,
34 "text": text
35 })
36 32
37 def _FormatValue(value): 33 def _FormatValue(value):
38 """Inserts commas every three digits for integer values. It is magic. 34 """Inserts commas every three digits for integer values. It is magic.
39 """ 35 """
40 s = str(value) 36 s = str(value)
41 return ','.join([s[max(0, i - 3):i] for i in range(len(s), 0, -3)][::-1]) 37 return ','.join([s[max(0, i - 3):i] for i in range(len(s), 0, -3)][::-1])
42 38
43 class HandlebarDictGenerator(object): 39 class HandlebarDictGenerator(object):
44 """Uses a Model from the JSON Schema Compiler and generates a dict that 40 """Uses a Model from the JSON Schema Compiler and generates a dict that
45 a Handlebar template can use for a data source. 41 a Handlebar template can use for a data source.
46 """ 42 """
47 def __init__(self, json): 43 def __init__(self, json):
48 clean_json = copy.deepcopy(json) 44 clean_json = copy.deepcopy(json)
49 _RemoveNoDocs(clean_json) 45 _RemoveNoDocs(clean_json)
50 try: 46 try:
51 self._namespace = model.Namespace(clean_json, clean_json['namespace']) 47 self._namespace = model.Namespace(clean_json, clean_json['namespace'])
52 except Exception as e: 48 except Exception as e:
53 logging.info(e) 49 logging.info(e)
54 50
51 def _StripPrefix(self, name):
52 if name.startswith(self._namespace.name + '.'):
53 return name[len(self._namespace.name + '.'):]
54 return name
55
56 def _ReplaceRefsInDescription(self, description):
not at google - send to devlin 2012/07/26 03:12:27 function needs -2 indentation
cduvall 2012/07/26 17:57:44 Done.
57 if description is None or '$ref:' not in description:
58 return description
59 refs = description.split('$ref:')
not at google - send to devlin 2012/07/26 03:12:27 This is awesome. We should convert all those chrom
cduvall 2012/07/26 17:57:44 I shouldn't do this now because it will break the
not at google - send to devlin 2012/07/30 08:04:34 Actually it looks like it _does_ deal with $ref:
60 formatted_description = refs[0]
61 for ref in refs[1:]:
not at google - send to devlin 2012/07/26 03:12:27 I don't think this algorithm works if the descript
cduvall 2012/07/26 17:57:44 I think it does: '$ref:Reffy is cool'.split('$ref
62 ref, rest = ref.split(' ', 1)
63 ref_dict = _GetLinkToRefType(self._namespace.name, ref)
64 formatted_description += ('<a href="' + ref_dict['href'] + '">' +
65 ref_dict['text'] + '</a> ' + rest)
not at google - send to devlin 2012/07/26 03:12:27 use a format string? also, tip: += is inefficient
cduvall 2012/07/26 17:57:44 Done.
66 return formatted_description
67
55 def Generate(self): 68 def Generate(self):
56 try: 69 try:
57 return { 70 return {
58 'name': self._namespace.name, 71 'name': self._namespace.name,
59 'types': map(self._GenerateType, self._namespace.types.values()), 72 'types': map(self._GenerateType, self._namespace.types.values()),
60 'functions': self._GenerateFunctions(self._namespace.functions), 73 'functions': self._GenerateFunctions(self._namespace.functions),
61 'events': map(self._GenerateEvent, self._namespace.events.values()), 74 'events': map(self._GenerateEvent, self._namespace.events.values()),
62 'properties': self._GenerateProperties(self._namespace.properties) 75 'properties': self._GenerateProperties(self._namespace.properties)
63 } 76 }
64 except Exception as e: 77 except Exception as e:
65 logging.info(e) 78 logging.info(e)
66 79
67 def _GenerateType(self, type_): 80 def _GenerateType(self, type_):
68 type_dict = { 81 type_dict = {
69 'name': type_.name, 82 'name': self._StripPrefix(type_.name),
70 'description': type_.description, 83 'description': type_.description,
not at google - send to devlin 2012/07/26 03:12:27 run *all* descriptions of through ReplaceRefsInDes
cduvall 2012/07/26 17:57:44 Done.
71 'properties': self._GenerateProperties(type_.properties), 84 'properties': self._GenerateProperties(type_.properties),
72 'functions': self._GenerateFunctions(type_.functions), 85 'functions': self._GenerateFunctions(type_.functions),
73 'events': map(self._GenerateEvent, type_.events.values()) 86 'events': map(self._GenerateEvent, type_.events.values())
74 } 87 }
75 self._RenderTypeInformation(type_, type_dict) 88 self._RenderTypeInformation(type_, type_dict)
76 return type_dict 89 return type_dict
77 90
78 def _GenerateFunctions(self, functions): 91 def _GenerateFunctions(self, functions):
79 return map(self._GenerateFunction, functions.values()) 92 return map(self._GenerateFunction, functions.values())
80 93
(...skipping 10 matching lines...) Expand all
91 for param in function.params: 104 for param in function.params:
92 function_dict['parameters'].append(self._GenerateProperty(param)) 105 function_dict['parameters'].append(self._GenerateProperty(param))
93 if function_dict['callback']: 106 if function_dict['callback']:
94 function_dict['parameters'].append(function_dict['callback']) 107 function_dict['parameters'].append(function_dict['callback'])
95 if len(function_dict['parameters']) > 0: 108 if len(function_dict['parameters']) > 0:
96 function_dict['parameters'][-1]['last'] = True 109 function_dict['parameters'][-1]['last'] = True
97 return function_dict 110 return function_dict
98 111
99 def _GenerateEvent(self, event): 112 def _GenerateEvent(self, event):
100 event_dict = { 113 event_dict = {
101 'name': event.name, 114 'name': self._StripPrefix(event.name),
102 'description': event.description, 115 'description': event.description,
103 'parameters': map(self._GenerateProperty, event.params) 116 'parameters': map(self._GenerateProperty, event.params)
104 } 117 }
105 if len(event_dict['parameters']) > 0: 118 if len(event_dict['parameters']) > 0:
106 event_dict['parameters'][-1]['last'] = True 119 event_dict['parameters'][-1]['last'] = True
107 return event_dict 120 return event_dict
108 121
109 def _GenerateCallback(self, callback): 122 def _GenerateCallback(self, callback):
110 if not callback: 123 if not callback:
111 return None 124 return None
112 callback_dict = { 125 callback_dict = {
113 'name': 'callback', 126 'name': 'callback',
114 'description': callback.description, 127 'description': callback.description,
115 'simple_type': {'simple_type': 'function'}, 128 'simple_type': {'simple_type': 'function'},
116 'optional': callback.optional, 129 'optional': callback.optional,
117 'parameters': [] 130 'parameters': []
118 } 131 }
119 for param in callback.params: 132 for param in callback.params:
120 callback_dict['parameters'].append(self._GenerateProperty(param)) 133 callback_dict['parameters'].append(self._GenerateProperty(param))
121 if (len(callback_dict['parameters']) > 0): 134 if (len(callback_dict['parameters']) > 0):
122 callback_dict['parameters'][-1]['last'] = True 135 callback_dict['parameters'][-1]['last'] = True
123 return callback_dict 136 return callback_dict
124 137
125 def _GenerateProperties(self, properties): 138 def _GenerateProperties(self, properties):
126 return map(self._GenerateProperty, properties.values()) 139 return map(self._GenerateProperty, properties.values())
127 140
128 def _GenerateProperty(self, property_): 141 def _GenerateProperty(self, property_):
129 property_dict = { 142 property_dict = {
130 'name': property_.name, 143 'name': self._StripPrefix(property_.name),
131 'optional': property_.optional, 144 'optional': property_.optional,
132 'description': property_.description, 145 'description': self._ReplaceRefsInDescription(property_.description),
133 'properties': self._GenerateProperties(property_.properties), 146 'properties': self._GenerateProperties(property_.properties),
134 'functions': self._GenerateFunctions(property_.functions) 147 'functions': self._GenerateFunctions(property_.functions)
135 } 148 }
136 if property_.has_value: 149 if property_.has_value:
137 if isinstance(property_.value, int): 150 if isinstance(property_.value, int):
138 property_dict['value'] = _FormatValue(property_.value) 151 property_dict['value'] = _FormatValue(property_.value)
139 else: 152 else:
140 property_dict['value'] = property_.value 153 property_dict['value'] = property_.value
141 else: 154 else:
142 self._RenderTypeInformation(property_, property_dict) 155 self._RenderTypeInformation(property_, property_dict)
(...skipping 17 matching lines...) Expand all
160 elif property_.type_ == model.PropertyType.ENUM: 173 elif property_.type_ == model.PropertyType.ENUM:
161 dst_dict['enum_values'] = [] 174 dst_dict['enum_values'] = []
162 for enum_value in property_.enum_values: 175 for enum_value in property_.enum_values:
163 dst_dict['enum_values'].append({'name': enum_value}) 176 dst_dict['enum_values'].append({'name': enum_value})
164 if len(dst_dict['enum_values']) > 0: 177 if len(dst_dict['enum_values']) > 0:
165 dst_dict['enum_values'][-1]['last'] = True 178 dst_dict['enum_values'][-1]['last'] = True
166 elif property_.instance_of: 179 elif property_.instance_of:
167 dst_dict['simple_type'] = property_.instance_of.lower() 180 dst_dict['simple_type'] = property_.instance_of.lower()
168 else: 181 else:
169 dst_dict['simple_type'] = property_.type_.name.lower() 182 dst_dict['simple_type'] = property_.type_.name.lower()
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698