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.
13 from docs_server_utils
import SanitizeAPIName
15 def _ReadFile(filename
):
16 with
open(filename
) as f
:
19 def _WriteFile(filename
, contents
):
20 with
open(filename
, 'w') as f
:
23 def _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),
29 clean
= (matches
.group(2).replace('\\', '')
33 page
, link
= clean
.split('#')
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),
44 link
= re
.sub('^(property|type|method|event)-', '', link
).replace('-', '.')
45 page
= page
.replace('.html', '.').replace('_', '.')
46 if matches
.group(1) == ' ':
49 padding
= matches
.group(1)
51 return '%s$(ref:%s%s)' % (padding
, page
, link
)
53 return '%s$(ref:%s%s %s)' % (padding
, page
, link
, title
)
55 def _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
),
61 contents
= contents
.replace('$(ref:extension.lastError)',
62 '$(ref:runtime.lastError)')
66 _WriteFile(filename
, contents
)
68 if __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
)
78 opts
, argv
= parser
.parse_args()
80 _ConvertFile(opts
.file, opts
.out
)
85 for root
, dirs
, files
in os
.walk(argv
[0]):
87 _ConvertFile(os
.path
.join(root
, name
), opts
.out
)