1 # Copyright 2013 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
6 from urlparse import urlsplit
8 from file_system import FileNotFoundError
10 class Redirector(object):
11 def __init__(self, compiled_fs_factory, file_system):
12 self._file_system = file_system
13 self._cache = compiled_fs_factory.ForJson(file_system)
15 def Redirect(self, host, path):
16 ''' Check if a path should be redirected, first according to host
17 redirection rules, then from rules in redirects.json files.
19 Returns the path that should be redirected to, or None if no redirection
22 return self._RedirectOldHosts(host, path) or self._RedirectFromConfig(path)
24 def _RedirectFromConfig(self, url):
25 ''' Lookup the redirects configuration file in the directory that contains
26 the requested resource. If no redirection rule is matched, or no
27 configuration file exists, returns None.
29 dirname, filename = posixpath.split(url)
32 rules = self._cache.GetFromFile(
33 posixpath.join(dirname, 'redirects.json')).Get()
34 except FileNotFoundError:
37 redirect = rules.get(filename)
40 if (redirect.startswith('/') or
41 urlsplit(redirect).scheme in ('http', 'https')):
44 return posixpath.normpath(posixpath.join('/', dirname, redirect))
46 def _RedirectOldHosts(self, host, path):
47 ''' Redirect paths from the old code.google.com to the new
48 developer.chrome.com, retaining elements like the channel and https, if
51 if urlsplit(host).hostname != 'code.google.com':
54 path = path.split('/')
55 if path and path[0] == 'chrome':
58 return 'https://developer.chrome.com/' + posixpath.join(*path)
61 ''' Load files during a cron run.
63 for root, dirs, files in self._file_system.Walk(''):
64 if 'redirects.json' in files:
65 self._cache.GetFromFile(posixpath.join(root, 'redirects.json')).Get()