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.
6 # This script converts old-style <a> links to API docs to the new $ref links.
7 # See reference_resolver.py for more info on the format of $ref links.
14 from docs_server_utils import SanitizeAPIName
15 import third_party.json_schema_compiler.model as model
17 def _ReadFile(filename):
18 with open(filename) as f:
21 def _WriteFile(filename, contents):
22 with open(filename, 'w') as f:
25 def _Replace(matches, filename):
26 title = matches.group(3)
27 if matches.group(2).count('#') != 1:
28 return '<a%shref=%s>%s</a>' % (matches.group(1),
31 clean = (matches.group(2).replace('\\', '')
35 page, link = clean.split('#')
37 page = '%s.html' % SanitizeAPIName(filename.rsplit(os.sep, 1)[-1])
38 if (not link.startswith('property-') and
39 not link.startswith('type-') and
40 not link.startswith('method-') and
41 not link.startswith('event-')):
42 return '<a%shref=%s>%s</a>' % (matches.group(1),
46 link = re.sub('^(property|type|method|event)-', '', link).replace('-', '.')
47 page = page.replace('.html', '.').replace('_', '.')
48 if matches.group(1) == ' ':
51 padding = matches.group(1)
53 return '%s$ref:%s%s' % (padding, page, link)
55 return '%s$ref:[%s%s %s]' % (padding, page, link, title)
57 def _ConvertFile(filename, use_stdout):
58 regex = re.compile(r'<a(.*?)href=(.*?)>(.*?)</a>', flags=re.DOTALL)
59 contents = _ReadFile(filename)
60 contents = re.sub(regex,
61 lambda m: _Replace(m, filename),
63 contents = contents.replace('$ref:extension.lastError',
64 '$ref:runtime.lastError')
68 _WriteFile(filename, contents)
70 if __name__ == '__main__':
71 parser = optparse.OptionParser(
72 description='Converts <a> links to $ref links.',
73 usage='usage: %prog [option] <directory>')
74 parser.add_option('-f', '--file', default='',
75 help='Convert links in single file.')
76 parser.add_option('-o', '--out', action='store_true', default=False,
77 help='Write to stdout.')
78 regex = re.compile(r'<a(.*?)href=(.*?)>(.*?)</a>', flags=re.DOTALL)
80 opts, argv = parser.parse_args()
82 _ConvertFile(opts.file, opts.out)
87 for root, dirs, files in os.walk(argv[0]):
89 _ConvertFile(os.path.join(root, name), opts.out)