Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / third_party / trace-viewer / third_party / tvcm / tvcm / resource.py
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."""
5
6 import os
7
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
13     self._contents = None
14
15   @property
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)
19
20   @property
21   def unix_style_relative_path(self):
22     return self.relative_path.replace(os.sep, '/')
23
24   @property
25   def name(self):
26     """The dotted name for this resource based on its relative path."""
27     return self.name_from_relative_path(self.relative_path)
28
29   @staticmethod
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]
34     if len(dirname):
35       if basename == '__init__.js':
36         name = dirname.replace(os.path.sep, '.')
37       else:
38         name = dirname.replace(os.path.sep, '.') + '.' + modname
39     else:
40       assert basename != '__init__.js'
41       name = modname
42     return name
43
44   @property
45   def contents(self):
46     if self._contents:
47       return self._contents
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()
52     f.close()
53     return self._contents