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# 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.
8
9import optparse
10import os
11import re
12
13from docs_server_utils import SanitizeAPIName
14
15def _ReadFile(filename):
16  with open(filename) as f:
17    return f.read()
18
19def _WriteFile(filename, contents):
20  with open(filename, 'w') as f:
21    f.write(contents)
22
23def _Replace(matches, filename):
24  title = matches.group(3)
25  if matches.group(2).count('#') != 1:
26    return '<a%shref=%s>%s</a>' % (matches.group(1),
27                                   matches.group(2),
28                                   title)
29  clean = (matches.group(2).replace('\\', '')
30                           .replace("'", '')
31                           .replace('"', '')
32                           .replace('/', ''))
33  page, link = clean.split('#')
34  if not page:
35    page = '%s.html' % SanitizeAPIName(filename.rsplit(os.sep, 1)[-1])
36  if (not link.startswith('property-') and
37      not link.startswith('type-') and
38      not link.startswith('method-') and
39      not link.startswith('event-')):
40    return '<a%shref=%s>%s</a>' % (matches.group(1),
41                                   matches.group(2),
42                                   title)
43
44  link = re.sub('^(property|type|method|event)-', '', link).replace('-', '.')
45  page = page.replace('.html', '.').replace('_', '.')
46  if matches.group(1) == ' ':
47    padding = ''
48  else:
49    padding = matches.group(1)
50  if link in title:
51    return '%s$(ref:%s%s)' % (padding, page, link)
52  else:
53    return '%s$(ref:%s%s %s)' % (padding, page, link, title)
54
55def _ConvertFile(filename, use_stdout):
56  regex = re.compile(r'<a(.*?)href=(.*?)>(.*?)</a>', flags=re.DOTALL)
57  contents = _ReadFile(filename)
58  contents  = re.sub(regex,
59                     lambda m: _Replace(m, filename),
60                     contents)
61  contents = contents.replace('$(ref:extension.lastError)',
62                              '$(ref:runtime.lastError)')
63  if use_stdout:
64    print contents
65  else:
66    _WriteFile(filename, contents)
67
68if __name__ == '__main__':
69  parser = optparse.OptionParser(
70      description='Converts <a> links to $ref links.',
71      usage='usage: %prog [option] <directory>')
72  parser.add_option('-f', '--file', default='',
73      help='Convert links in single file.')
74  parser.add_option('-o', '--out', action='store_true', default=False,
75      help='Write to stdout.')
76  regex = re.compile(r'<a(.*?)href=(.*?)>(.*?)</a>', flags=re.DOTALL)
77
78  opts, argv = parser.parse_args()
79  if opts.file:
80    _ConvertFile(opts.file, opts.out)
81  else:
82    if len(argv) != 1:
83      parser.print_usage()
84      exit(0)
85    for root, dirs, files in os.walk(argv[0]):
86      for name in files:
87        _ConvertFile(os.path.join(root, name), opts.out)
88