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

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

Issue 10834130: Extensions Docs Server: Doc conversion script - SVN (Closed) Base URL: https://src.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
« no previous file with comments | « no previous file | chrome/common/extensions/docs/server2/converter_html_parser.py » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
Property Changes:
Added: svn:executable
+ *
Added: svn:eol-style
+ LF
OLDNEW
(Empty)
1 #!/usr/bin/env python
2 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
5
6 # Example run from the server2/ directory:
7 # $ converter.py ../static/ ../../api templates/articles/ templates/intros/
8 # templates/public/ static/images/ -r
9
10 import json
11 import optparse
12 import os
13 import re
14 import shutil
15 import subprocess
16 import sys
17
18 sys.path.append(os.path.join(sys.path[0], os.pardir, os.pardir, os.pardir,
19 os.pardir, os.pardir, 'tools'))
20 import json_comment_eater
21
22 from converter_html_parser import HandleDocFamily
23 from docs_server_utils import SanitizeAPIName
24
25 IGNORED_FILES = [
26 # These are custom files.
27 '404',
28 'apps_api_index',
29 'api_index',
30 'experimental',
31 'samples',
32 'index',
33 # These are APIs that should not have docs.
34 'test',
35 'experimental_idltest',
36 ]
37
38 # These are mappings for APIs that have no intros. They are needed because the
39 # names of the JSON files do not give enough information on the actual API name.
40 CUSTOM_MAPPINGS = {
41 'experimental_input_virtual_keyboard': 'experimental_input_virtualKeyboard',
42 'input_ime': 'input_ime'
43 }
44
45 # These are the extension-only APIs that don't have explicit entries in
46 # _permission_features.json, so we can't programmatically figure out that it's
47 # extension-only.
48 # From api_page_generator.js:548.
49 EXTENSIONS_ONLY = [
50 'browserAction',
51 'extension',
52 'input.ime',
53 'omnibox',
54 'pageAction',
55 'scriptBadge',
56 'windows',
57 'experimental.devtools.audits',
58 'experimental.devtools.console',
59 'experimental.discovery',
60 'experimental.infobars',
61 'experimental.offscreenTabs',
62 'experimental.processes',
63 'experimental.speechInput'
64 ]
65
66 def _ReadFile(filename):
67 with open(filename, 'r') as f:
68 return f.read()
69
70 def _WriteFile(filename, data):
71 with open(filename, 'w+') as f:
72 f.write(data)
73
74 def _UnixName(name):
75 """Returns the unix_style name for a given lowerCamelCase string.
76 Shamelessly stolen from json_schema_compiler/model.py.
77 """
78 name = os.path.splitext(name)[0]
79 s1 = re.sub('([a-z])([A-Z])', r'\1_\2', name)
80 s2 = re.sub('([A-Z]+)([A-Z][a-z])', r'\1_\2', s1)
81 return s2.replace('.', '_').lower()
82
83 def _GetDestinations(api_name, api_dir):
84 if api_name in EXTENSIONS_ONLY:
85 return ['extensions']
86 if api_name.startswith('app'):
87 return ['apps']
88 with open(os.path.join(api_dir, '_permission_features.json')) as f:
89 permissions = json.loads(json_comment_eater.Nom(f.read()))
90 permissions_key = api_name.replace('experimental_', '').replace('_', '.')
91 if permissions_key in permissions:
92 return_list = []
93 types = permissions[permissions_key]['extension_types']
94 if ('packaged_app' in types or
95 'hosted_app' in types or
96 'platform_app' in types):
97 return_list.append('apps')
98 if 'extension' in types:
99 return_list.append('extensions')
100 return return_list
101 return ['extensions', 'apps']
102
103 def _ListAllAPIs(dirname):
104 all_files = []
105 for path, dirs, files in os.walk(dirname):
106 if path == '.':
107 all_files.extend([f for f in files
108 if f.endswith('.json') or f.endswith('.idl')])
109 else:
110 all_files.extend([os.path.join(path, f) for f in files
111 if f.endswith('.json') or f.endswith('.idl')])
112 dirname = dirname.rstrip('/') + '/'
113 return [f[len(dirname):] for f in all_files
114 if os.path.splitext(f)[0].split('_')[-1] not in ['private',
115 'internal']]
116
117 def _MakeArticleTemplate(filename, path):
118 return ('{{+partials.standard_%s_article article:intros.%s}}' %
119 (path, filename))
120
121 def _MakeAPITemplate(intro_name, path, api_name, has_intro):
122 if has_intro:
123 return ('{{+partials.standard_%s_api api:apis.%s intro:intros.%s}}' %
124 (path, api_name, intro_name))
125 else:
126 return ('{{+partials.standard_%s_api api:apis.%s}}' %
127 (path, api_name))
128
129 def _GetAPIPath(name, api_dir):
130 api_files = _ListAllAPIs(api_dir)
131 for filename in api_files:
132 if name == _UnixName(SanitizeAPIName(filename)):
133 return _UnixName(filename)
134
135 def _CleanAPIs(source_dir, api_dir, intros_dest, template_dest, exclude):
136 source_files = os.listdir(source_dir)
137 source_files_unix = set(_UnixName(f) for f in source_files)
138 api_files = set(_UnixName(SanitizeAPIName(f)) for f in _ListAllAPIs(api_dir))
139 intros_files = set(_UnixName(f) for f in os.listdir(intros_dest))
140 to_delete = api_files - source_files_unix - set(exclude)
141 for path, dirs, files in os.walk(template_dest):
142 for filename in files:
143 no_ext = os.path.splitext(filename)[0]
144 # Check for changes like appWindow -> app.window.
145 if (_UnixName(filename) in source_files_unix - set(exclude) and
146 no_ext not in source_files):
147 os.remove(os.path.join(path, filename))
148 if _UnixName(filename) in to_delete:
149 try:
150 os.remove(os.path.join(intros_dest, filename))
151 except OSError:
152 pass
153 os.remove(os.path.join(path, filename))
154
155 def _FormatFile(contents, path, name, image_dest, replace, is_api):
156 # Copy all images referenced in the page.
157 for image in re.findall(r'="\.\./images/([^"]*)"', contents):
158 if not replace and os.path.exists(os.path.join(image_dest, image)):
159 continue
160 if '/' in image:
161 try:
162 os.makedirs(os.path.join(image_dest, image.rsplit('/', 1)[0]))
163 except:
164 pass
165 shutil.copy(
166 os.path.join(path, os.pardir, 'images', image),
167 os.path.join(image_dest, image))
168 contents = re.sub(r'<!--.*?(BEGIN|END).*?-->', r'', contents)
169 contents = re.sub(r'\.\./images', r'{{static}}/images', contents)
170 exp = re.compile(r'<div[^>.]*?id="pageData-showTOC"[^>.]*?>.*?</div>',
171 flags=re.DOTALL)
172 contents = re.sub(exp, r'', contents)
173 exp = re.compile(r'<div[^>.]*?id="pageData-name"[^>.]*?>(.*?)</div>',
174 flags=re.DOTALL)
175 if is_api:
176 contents = re.sub(exp, r'', contents)
177 else:
178 contents = re.sub(exp, r'<h1>\1</h1>', contents)
179 contents = contents.strip()
180 contents = HandleDocFamily(contents)
181
182 # Attempt to guess if the page has no title.
183 if '<h1' not in contents and not is_api:
184 title = _UnixName(name)
185 title = ' '.join([part[0].upper() + part[1:] for part in title.split('_')])
186 contents = ('<h1 class="page_title">%s</h1>' % title) + contents
187 return contents
188
189 def _ProcessName(name):
190 processed_name = []
191 if name.startswith('experimental_'):
192 name = name[len('experimental_'):]
193 processed_name.append('experimental_')
194 parts = name.split('_')
195 processed_name.append(parts[0])
196 processed_name.extend([p[0].upper() + p[1:] for p in parts[1:]])
197 return ''.join(processed_name)
198
199 def _MoveAllFiles(source_dir,
200 api_dir,
201 articles_dest,
202 intros_dest,
203 template_dest,
204 image_dest,
205 replace=False,
206 exclude_dir=None,
207 svn=False):
208 if exclude_dir is None:
209 exclude_files = []
210 else:
211 exclude_files = [_UnixName(f) for f in os.listdir(exclude_dir)]
212 exclude_files.extend(IGNORED_FILES)
213 api_files = _ListAllAPIs(api_dir)
214 original_files = []
215 for path, dirs, files in os.walk(template_dest):
216 original_files.extend(files)
217 if replace:
218 _CleanAPIs(source_dir, api_dir, intros_dest, template_dest, exclude_files)
219 files = set(os.listdir(source_dir))
220 unix_files = [_UnixName(f) for f in files]
221 for name in [SanitizeAPIName(f) for f in _ListAllAPIs(api_dir)]:
222 if _UnixName(name) not in unix_files:
223 files.add(name + '.html')
224 for file_ in files:
225 if (_UnixName(file_) in exclude_files or
226 file_.startswith('.') or
227 file_.startswith('_')):
228 continue
229 _MoveSingleFile(source_dir,
230 file_,
231 api_dir,
232 articles_dest,
233 intros_dest,
234 template_dest,
235 image_dest,
236 replace=replace,
237 svn=svn,
238 original_files=original_files)
239
240 def _MoveSingleFile(source_dir,
241 source_file,
242 api_dir,
243 articles_dest,
244 intros_dest,
245 template_dest,
246 image_dest,
247 replace=False,
248 svn=False,
249 original_files=None):
250 unix_name = _UnixName(source_file)
251 is_api = unix_name in [_UnixName(SanitizeAPIName(f))
252 for f in _ListAllAPIs(api_dir)]
253 if unix_name in CUSTOM_MAPPINGS:
254 processed_name = CUSTOM_MAPPINGS[unix_name]
255 else:
256 processed_name = os.path.splitext(source_file)[0].replace('.', '_')
257 if (is_api and
258 '_' in source_file.replace('experimental_', '') and
259 not os.path.exists(os.path.join(source_dir, source_file))):
260 processed_name = _ProcessName(processed_name)
261 if (original_files is None or
262 processed_name + '.html' not in original_files):
263 print 'WARNING: The correct name of this file was guessed:'
264 print
265 print '%s -> %s' % (os.path.splitext(source_file)[0], processed_name)
266 print
267 print ('If this is incorrect, change |CUSTOM_MAPPINGS| in chrome/'
268 'common/extensions/docs/server2/converter.py.')
269 try:
270 static_data = _FormatFile(_ReadFile(os.path.join(source_dir, source_file)),
271 source_dir,
272 source_file,
273 image_dest,
274 replace,
275 is_api)
276 except IOError:
277 static_data = None
278 for path in _GetDestinations(processed_name, api_dir):
279 template_file = os.path.join(template_dest, path, processed_name + '.html')
280 if is_api:
281 template_data = _MakeAPITemplate(processed_name,
282 path,
283 _GetAPIPath(unix_name, api_dir),
284 static_data is not None)
285 static_file = os.path.join(intros_dest, processed_name + '.html')
286 else:
287 template_data = _MakeArticleTemplate(unix_name, path)
288 static_file = os.path.join(articles_dest, processed_name + '.html')
289 if replace or not os.path.exists(template_file):
290 _WriteFile(template_file, template_data)
291 if svn:
292 subprocess.call(['svn',
293 'add',
294 '--force',
295 '--parents',
296 '-q',
297 template_file])
298 if static_data is not None and (replace or not os.path.exists(static_file)):
299 if svn:
300 if os.path.exists(static_file):
301 subprocess.call(['svn', 'rm', '--force', static_file])
302 subprocess.call(['svn',
303 'cp',
304 os.path.join(source_dir, source_file),
305 static_file])
306 _WriteFile(static_file, static_data)
307
308 if __name__ == '__main__':
309 parser = optparse.OptionParser(
310 description='Converts static files from the old documentation system to '
311 'the new one. If run without -f, all the files in |src| will '
312 'be converted.',
313 usage='usage: %prog [options] static_src_dir [-f static_src_file] '
314 'api_dir articles_dest intros_dest template_dest image_dest')
315 parser.add_option('-f',
316 '--file',
317 action='store_true',
318 default=False,
319 help='convert single file')
320 parser.add_option('-s',
321 '--svn',
322 action='store_true',
323 default=False,
324 help='use svn copy to copy intro files')
325 parser.add_option('-e',
326 '--exclude',
327 default=None,
328 help='exclude files matching the names in this dir')
329 parser.add_option('-r',
330 '--replace',
331 action='store_true',
332 default=False,
333 help='replace existing files')
334 (opts, args) = parser.parse_args()
335 if (not opts.file and len(args) != 6) or (opts.file and len(args) != 7):
336 parser.error('incorrect number of arguments.')
337
338 if opts.file:
339 _MoveSingleFile(*args, replace=opts.replace, svn=opts.svn)
340 else:
341 _MoveAllFiles(*args,
342 replace=opts.replace,
343 exclude_dir=opts.exclude,
344 svn=opts.svn)
OLDNEW
« no previous file with comments | « no previous file | chrome/common/extensions/docs/server2/converter_html_parser.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698