redirector.py revision 2385ea399aae016c0806a4f9ef3c9cfe3d2a39df
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. 4 5import posixpath 6from urlparse import urlsplit 7 8from file_system import FileNotFoundError 9from third_party.json_schema_compiler.json_parse import Parse 10 11class Redirector(object): 12 def __init__(self, compiled_fs_factory, file_system, root_path): 13 self._root_path = root_path 14 self._file_system = file_system 15 self._cache = compiled_fs_factory.Create( 16 lambda _, rules: Parse(rules), Redirector) 17 18 def Redirect(self, host, path): 19 ''' Check if a path should be redirected, first according to host 20 redirection rules, then from rules in redirects.json files. 21 22 Returns the path that should be redirected to, or None if no redirection 23 should occur. 24 ''' 25 return self._RedirectOldHosts(host, path) or self._RedirectFromConfig(path) 26 27 def _RedirectFromConfig(self, url): 28 ''' Lookup the redirects configuration file in the directory that contains 29 the requested resource. If no redirection rule is matched, or no 30 configuration file exists, returns None. 31 ''' 32 dirname, filename = posixpath.split(url) 33 34 try: 35 rules = self._cache.GetFromFile( 36 posixpath.join(self._root_path, dirname, 'redirects.json')) 37 except FileNotFoundError: 38 return None 39 40 redirect = rules.get(filename) 41 if redirect is None: 42 return None 43 if (redirect.startswith('/') or 44 urlsplit(redirect).scheme in ('http', 'https')): 45 return redirect 46 47 return posixpath.normpath('/' + posixpath.join(dirname, redirect)) 48 49 def _RedirectOldHosts(self, host, path): 50 ''' Redirect paths from the old code.google.com to the new 51 developer.chrome.com, retaining elements like the channel and https, if 52 used. 53 ''' 54 if urlsplit(host).hostname != 'code.google.com': 55 return None 56 57 path = path.split('/') 58 if path and path[0] == 'chrome': 59 path.pop(0) 60 61 return 'https://developer.chrome.com/' + posixpath.join(*path) 62 63 def Cron(self): 64 ''' Load files during a cron run. 65 ''' 66 for root, dirs, files in self._file_system.Walk(self._root_path): 67 if 'redirects.json' in files: 68 self._cache.GetFromFile('%s/redirects.json' % posixpath.join( 69 self._root_path, root).rstrip('/')) 70