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 """A Resource is a file and its various associated canonical names."""
8 class Resource(object):
9 """Represents a file found via a path search."""
10 def __init__(self, toplevel_dir, absolute_path):
11 self.toplevel_dir = toplevel_dir
12 self.absolute_path = absolute_path
16 def relative_path(self):
17 """The path to the file from the top-level directory"""
18 return os.path.relpath(self.absolute_path, self.toplevel_dir)
21 def unix_style_relative_path(self):
22 return self.relative_path.replace(os.sep, '/')
26 """The dotted name for this resource based on its relative path."""
27 return self.name_from_relative_path(self.relative_path)
30 def name_from_relative_path(relative_path):
31 dirname = os.path.dirname(relative_path)
32 basename = os.path.basename(relative_path)
33 modname = os.path.splitext(basename)[0]
35 if basename == '__init__.js':
36 name = dirname.replace(os.path.sep, '.')
38 name = dirname.replace(os.path.sep, '.') + '.' + modname
40 assert basename != '__init__.js'
48 if not os.path.exists(self.absolute_path):
49 raise Exception('%s not found.' % self.absolute_path)
50 f = open(self.absolute_path, 'rb')
51 self._contents = f.read()