path_canonicalizer.py revision c2e0dbddbe15c98d52c4786dac06cb8952a8ae6d
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 logging
6import os
7from third_party.json_schema_compiler.model import UnixName
8import svn_constants
9
10class PathCanonicalizer(object):
11  '''Transforms paths into their canonical forms. Since the dev server has had
12  many incarnations - e.g. there didn't use to be apps/ - there may be old
13  paths lying around the webs. We try to redirect those to where they are now.
14  '''
15  def __init__(self, channel, compiled_fs_factory):
16    self._channel = channel
17    self._identity_fs = compiled_fs_factory.CreateIdentity(PathCanonicalizer)
18
19  def Canonicalize(self, path):
20    starts_with_channel, path_without_channel = (False, path)
21    if path.startswith('%s/' % self._channel):
22      starts_with_channel, path_without_channel = (
23          True, path[len(self._channel) + 1:])
24
25    if any(path.startswith(prefix)
26           for prefix in ('extensions/', 'apps/', 'static/')):
27      return path
28
29    if '/' in path_without_channel or path_without_channel == '404.html':
30      return path
31
32    apps_templates = self._identity_fs.GetFromFileListing(
33        '/'.join((svn_constants.PUBLIC_TEMPLATE_PATH, 'apps')))
34    extensions_templates = self._identity_fs.GetFromFileListing(
35        '/'.join((svn_constants.PUBLIC_TEMPLATE_PATH, 'extensions')))
36
37    if self._channel is None or not starts_with_channel:
38      apps_path = 'apps/%s' % path_without_channel
39      extensions_path = 'extensions/%s' % path_without_channel
40    else:
41      apps_path = '%s/apps/%s' % (self._channel, path_without_channel)
42      extensions_path = '%s/extensions/%s' % (self._channel,
43                                              path_without_channel)
44
45    unix_path = UnixName(os.path.splitext(path_without_channel)[0])
46    if unix_path in extensions_templates:
47      return extensions_path
48    if unix_path in apps_templates:
49      return apps_path
50    return extensions_path
51