summaryrefslogtreecommitdiffstats
path: root/chrome/common/extensions/docs/server2/link_error_detector.py
blob: ee9bc7c5bbb89fb92f1c2ec10cbf4f79df874b0b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

from collections import defaultdict, deque, namedtuple
from HTMLParser import HTMLParser, HTMLParseError
from itertools import groupby
from operator import itemgetter
import posixpath
from urlparse import urlsplit

from file_system_util import CreateURLsFromPaths
from path_util import AssertIsDirectory


Page = namedtuple('Page', 'status, links, anchors, anchor_refs')


def _SplitAnchor(url):
  components = urlsplit(url)
  return components.path, components.fragment


def _Process(path, renderer):
  '''Render the page at |path| using a |renderer| and process the contents of
  that page. Returns a |Page| namedtuple with fields for the http status code
  of the page render, the href of all the links that occurred on the page, all
  of the anchors on the page (ids and names), and all links that contain an
  anchor component.

  If a non-html page is properly rendered, a |Page| with status code 200 and
  all other fields empty is returned.
  '''
  parser = _ContentParser()
  response = renderer(path)

  if response.status != 200:
    return Page(response.status, (), (), ())
  if not path.endswith('.html'):
    return Page(200, (), (), ())

  try:
    parser.feed(str(response.content))
  except HTMLParseError:
    return Page(200, (), (), ())

  links, anchors = parser.links, parser.anchors
  if '/' in path:
    base, _ = path.rsplit('/', 1)
  else:
    base = ''
  edges = []
  anchor_refs = []

  # Convert relative links to absolute links and categorize links as edges
  # or anchor_refs.
  for link in links:
    # Files like experimental_history.html are refered to with the URL
    # experimental.history.html.
    head, last = link.rsplit('/', 1) if '/' in link else ('', link)
    last, anchor = _SplitAnchor(last)

    if last.endswith('.html') and last.count('.') > 1:
      last = last.replace('.', '_', last.count('.') - 1)
      link = posixpath.join(head, last)
      if anchor:
        link = '%s#%s' % (link, anchor)

    if link.startswith('#'):
      anchor_refs.append(link)
    else:
      if link.startswith('/'):
        link = link[1:]
      else:
        link = posixpath.normpath('%s/%s' % (base, link))

      if '#' in link:
        anchor_refs.append(link)
      else:
        edges.append(link)

  return Page(200, edges, anchors, anchor_refs)


class _ContentParser(HTMLParser):
  '''Parse an html file pulling out all links and anchor_refs, where an
  anchor_ref is a link that contains an anchor.
  '''

  def __init__(self):
    HTMLParser.__init__(self)
    self.links = []
    self.anchors = set()

  def handle_starttag(self, tag, raw_attrs):
    attrs = dict(raw_attrs)

    if tag == 'a':
      # Handle special cases for href's that: start with a space, contain
      # just a '.' (period), contain python templating code, are an absolute
      # url, are a zip file, or execute javascript on the page.
      href = attrs.get('href', '').strip()
      if href and not href == '.' and not '{{' in href:
        if not urlsplit(href).scheme in ('http', 'https'):
          if not href.endswith('.zip') and not 'javascript:' in href:
            self.links.append(href)

    if attrs.get('id'):
      self.anchors.add(attrs['id'])
    if attrs.get('name'):
      self.anchors.add(attrs['name'])


class LinkErrorDetector(object):
  '''Finds link errors on the doc server. This includes broken links, those with
  a target page that 404s or contain an anchor that doesn't exist, or pages that
  have no links to them.
  '''

  def __init__(self, file_system, renderer, public_path, root_pages):
    '''Creates a new broken link detector. |renderer| is a callable that takes
    a path and returns a full html page. |public_path| is the path to public
    template files. All URLs in |root_pages| are used as the starting nodes for
    the orphaned page search.
    '''
    AssertIsDirectory(public_path)
    self._file_system = file_system
    self._renderer = renderer
    self._public_path = public_path
    self._pages = defaultdict(lambda: Page(404, (), (), ()))
    self._root_pages = frozenset(root_pages)
    self._always_detached = frozenset((
        'apps/404.html',
        'extensions/404.html',
        'apps/private_apis.html',
        'extensions/private_apis.html'))
    self._redirection_whitelist = frozenset(('extensions/', 'apps/'))

    self._RenderAllPages()

  def _RenderAllPages(self):
    '''Traverses the public templates directory rendering each URL and
    processing the resultant html to pull out all links and anchors.
    '''
    top_level_directories = (
      ('docs/templates/public/', ''),
      ('docs/static/', 'static/'),
      ('docs/examples/', 'extensions/examples/'),
    )

    for dirpath, urlprefix in top_level_directories:
      files = CreateURLsFromPaths(self._file_system, dirpath, urlprefix)
      for url, path in files:
        self._pages[url] = _Process(url, self._renderer)

        if self._pages[url].status != 200:
          print(url, ', a url derived from the path', dirpath +
              ', resulted in a', self._pages[url].status)

  def _FollowRedirections(self, starting_url, limit=4):
    '''Follow redirection until a non-redirectable page is reached. Start at
    |starting_url| which must return a 301 or 302 status code.

    Return a tuple of: the status of rendering |staring_url|, the final url,
    and a list of the pages reached including |starting_url|. If no redirection
    occurred, returns (None, None, None).
    '''
    pages_reached = [starting_url]
    redirect_link = None
    target_page = self._renderer(starting_url)
    original_status = status = target_page.status
    count = 0

    while status in (301, 302):
      if count > limit:
        return None, None, None
      redirect_link = target_page.headers.get('Location')
      target_page = self._renderer(redirect_link)
      status = target_page.status
      pages_reached.append(redirect_link)
      count += 1

    if redirect_link is None:
      return None, None, None

    return original_status, redirect_link, pages_reached

  def _CategorizeBrokenLinks(self, url, page, pages):
    '''Find all broken links on a page and create appropriate notes describing
    why tehy are broken (broken anchor, target redirects, etc). |page| is the
    current page being checked and is the result of rendering |url|. |pages|
    is a callable that takes a path and returns a Page.
    '''
    broken_links = []

    for link in page.links + page.anchor_refs:
      components = urlsplit(link)
      fragment = components.fragment

      if components.path == '':
        if fragment == 'top' or fragment == '':
          continue
        if not fragment in page.anchors:
          broken_links.append((200, url, link, 'target anchor not found'))
      else:
        # Render the target page
        target_page = pages(components.path)

        if target_page.status != 200:
          if components.path in self._redirection_whitelist:
            continue

          status, relink, _ = self._FollowRedirections(components.path)
          if relink:
            broken_links.append((
                status,
                url,
                link,
                'redirects to %s' % relink))
          else:
            broken_links.append((
                target_page.status, url, link, 'target page not found'))

        elif fragment:
          if not fragment in target_page.anchors:
            broken_links.append((
                target_page.status, url, link, 'target anchor not found'))

    return broken_links

  def GetBrokenLinks(self):
    '''Find all broken links. A broken link is a link that leads to a page
    that does not exist (404s), redirects to another page (301 or 302), or
    has an anchor whose target does not exist.

    Returns a list of tuples of four elements: status, url, target_page,
    notes.
    '''
    broken_links = []

    for url in self._pages.keys():
      page = self._pages[url]
      if page.status != 200:
        continue
      broken_links.extend(self._CategorizeBrokenLinks(
          url, page, lambda x: self._pages[x]))

    return broken_links

  def GetOrphanedPages(self):
    '''Crawls the server find all pages that are connected to the pages at
    |seed_url|s. Return the links that are valid on the server but are not in
    part of the connected component containing the |root_pages|. These pages
    are orphans and cannot be reached simply by clicking through the server.
    '''
    pages_to_check = deque(self._root_pages.union(self._always_detached))
    found = set(self._root_pages) | self._always_detached

    while pages_to_check:
      item = pages_to_check.popleft()
      target_page = self._pages[item]

      if target_page.status != 200:
        redirected_page = self._FollowRedirections(item)[1]
        if not redirected_page is None:
          target_page = self._pages[redirected_page]

      for link in target_page.links:
        if link not in found:
          found.add(link)
          pages_to_check.append(link)

    all_urls = set(
        [url for url, page in self._pages.iteritems() if page.status == 200])

    return [url for url in all_urls - found if url.endswith('.html')]


def StringifyBrokenLinks(broken_links):
  '''Prints out broken links in a more readable format.
  '''
  def fixed_width(string, width):
    return "%s%s" % (string, (width - len(string)) * ' ')

  first_col_width = max(len(link[1]) for link in broken_links)
  second_col_width = max(len(link[2]) for link in broken_links)
  target = itemgetter(2)
  output = []

  def pretty_print(link, col_offset=0):
    return "%s -> %s %s" % (
        fixed_width(link[1], first_col_width - col_offset),
        fixed_width(link[2], second_col_width),
        link[3])

  for target, links in groupby(sorted(broken_links, key=target), target):
    links = list(links)
    # Compress messages
    if len(links) > 50 and not links[0][2].startswith('#'):
      message = "Found %d broken links (" % len(links)
      output.append("%s%s)" % (message, pretty_print(links[0], len(message))))
    else:
      for link in links:
        output.append(pretty_print(link))

  return '\n'.join(output)