Add doclib/fix-links.py to temporarily fix/remove bad doxygen links
[senf.git] / doclib / fix-links.py
1 #!/usr/bin/python
2
3 import sys,os.path,fnmatch, HTMLParser, getopt
4
5 class HTMLFilter(HTMLParser.HTMLParser):
6
7     def __init__(self, out=None):
8         HTMLParser.HTMLParser.__init__(self)
9         self._out = out
10         self._collect = False
11         self._data = ""
12
13     def startCollect(self):
14         self._collect = True
15         self._data = ""
16
17     def endCollect(self):
18         self._collect = False
19         return self._data
20
21     def collecting(self):
22         return self._collect
23
24     def handle_starttag(self,tag,attrs):
25         m = getattr(self,'_s_'+tag.upper(),None)
26         if m:
27             m(attrs)
28         else:
29             self.emit_starttag(tag,attrs)
30
31     def handle_endtag(self,tag):
32         m = getattr(self,'_e_'+tag.upper(),None)
33         if m:
34             m()
35         else:
36             self.emit_endtag(tag)
37
38     def handle_data(self,data):
39         if self._collect:
40             self._data += data
41         if self._out:
42             self._out.write(data)
43
44     def handle_charref(self,name):
45         self.handle_data(name)
46
47     def handle_entityref(self,name):
48         self.handle_data(name)
49
50     def emit_starttag(self,tag,attrs):
51         self.handle_data('<%s%s>' % (tag, "".join([' %s="%s"' % attr for attr in attrs])))
52
53     def emit_endtag(self,tag):
54         self.handle_data('</%s>' % tag)
55
56
57 class AnchorIndex:
58
59     def __init__(self, skipdirs = ('.svn',)):
60         self._anchors = {}
61         self._skipdirs = skipdirs
62
63     def build(self):
64         sys.stderr.write("Building anchor index ")
65         nf = 0
66         for dirname, subdirs, files in os.walk('.'):
67             for d in self._skipdirs:
68                 if d in subdirs:
69                     subdirs.remove(d)
70             for f in fnmatch.filter(files,'*.html'):
71                 nf += 1
72                 path = os.path.normpath(os.path.join(dirname, f))
73                 self._addAnchor(f, path)
74                 self._extractAnchors(path)
75         sys.stderr.write(" Done.\n")
76         dups = 0
77         for k in self._anchors.keys():
78             if not self._anchors[k]:
79                 dups += 1
80                 del self._anchors[k]
81         sys.stderr.write("%d unique anchors in %d files (%d duplicates)\n"
82                          % (len(self._anchors), nf, dups))
83
84     def _addAnchor(self, anchor, path):
85         if self._anchors.has_key(anchor):
86             self._anchors[anchor] = None
87         else:
88             self._anchors[anchor] = path
89             if len(self._anchors) % 100 == 0:
90                 sys.stderr.write('.')
91
92     def __getitem__(self, key):
93         return self._anchors.get(key)
94
95     class AnchorExtractor(HTMLFilter):
96
97         def __init__(self):
98             HTMLFilter.__init__(self)
99             self._anchors = {}
100
101         def _s_A(self,attrs):
102             attrs = dict(attrs)
103             if attrs.has_key('name'):
104                 self._anchors[attrs['name']] = None
105
106         def anchors(self):
107             return self._anchors.keys()
108
109     def _extractAnchors(self, f):
110         extractor = AnchorIndex.AnchorExtractor()
111         extractor.feed(file(f).read())
112         extractor.close()
113         for anchor in extractor.anchors():
114             self._addAnchor(anchor, f)
115
116
117 class LinkFixer:
118
119     def __init__(self, skipdirs=('.svn',)):
120         self._index = AnchorIndex(skipdirs)
121
122     def init(self):
123         self._index.build()
124         self._files = 0
125         self._found = 0
126         self._fixed = 0
127
128     class LinkFilter(HTMLFilter):
129
130         def __init__(self, index, key, topdir, out):
131             HTMLFilter.__init__(self, out)
132             self._index = index
133             self._key = key
134             self._topdir = topdir
135             self._skip_a = False
136             self._found = 0
137             self._fixed = 0
138
139         def _s_A(self, attrs):
140             self._skip_a = False
141             if self._key in dict(attrs).get('href',''):
142                 self._found += 1
143                 ix = [ i for i, attr in enumerate(attrs) if attr[0] == 'href' ][0]
144                 target = attrs[ix][1]
145                 if '#' in target:
146                     anchor = target.split('#')[1]
147                     target = self._index[anchor]
148                     if target:
149                         target = '%s#%s' % (target, anchor)
150                 else:
151                     target = self._index[os.path.split(target)[1]]
152                 if target:
153                     self._fixed += 1
154                     attrs[ix] = ('href', os.path.join(self._topdir,target))
155                 else:
156                     self._skip_a = True
157                     return
158             self.emit_starttag('a',attrs)
159
160         def _e_A(self):
161             if self._skip_a:
162                 self._skip_a = False
163             else:
164                 self.emit_endtag('a')
165
166         def stats(self):
167             return (self._found, self._fixed)
168
169     def fix(self, path, target):
170         self._files += 1
171         data = file(path).read()
172         filt = LinkFixer.LinkFilter(self._index,
173                                     target,
174                                     "../" * (len(os.path.split(path)[0].split("/"))),
175                                     file(path,"w"))
176         filt.feed(data)
177         filt.close()
178         self._found += filt.stats()[0]
179         self._fixed += filt.stats()[1]
180
181     def stats(self):
182         return (self._files, self._found, self._fixed)
183     
184
185 (opts, args) = getopt.getopt(sys.argv[1:], "s:")
186 if len(args) != 2:
187     sys.stderr.write("""Usage:
188         fix-links.py [-s skip-dir]... <errrorX.txt> <errorAX.txt>
189
190 Process the 'errorX.txt' and 'errorAX.txt' files as generated by
191 'linklint': Check all invalid links and try to find the correct
192 target. If a target is found, the link is changed accordingly,
193 otherwise the link is removed.
194
195 To find anchors, fix-links.py generates a complete index of all
196 anchors defined in any HTML file in the current directory or some
197 subdirectory. The directories named 'skiped-dir' (at any level) will
198 not be scanned for '*.html' files.
199 """)
200     sys.exit(1)
201
202 skipdirs = [ val for opt, val in opts if opt == '-s' ]
203
204 fixer = LinkFixer(skipdirs)
205 fixer.init()
206
207 target = None
208 for l in file(args[0]):
209     l = l.rstrip()
210     if l.startswith('/'):
211         target = '#' + os.path.split(l)[1]
212     elif l.startswith('    /') and not l.endswith('/'):
213         sys.stderr.write("%s\n" % l)
214         fixer.fix(l[5:], target)
215
216 for l in file(args[1]):
217     l = l.rstrip()
218     if l.startswith('/'):
219         target = l.split('#')[1]
220     elif l.startswith('    /') and not l.endswith('/'):
221         sys.stderr.write("%s\n" % l)
222         fixer.fix(l[5:], target)
223
224 files, found, fixed = fixer.stats()
225
226 sys.stderr.write("""
227 Files processed : %5d
228 Links processed : %5d
229 Links fixed     : %5d
230 Links removed   : %5d
231 """ % (files, found, fixed, found-fixed))