aboutsummaryrefslogtreecommitdiff
path: root/catapult/common/py_vulcanize/py_vulcanize/resource.py
blob: 853dff94437de75f37dd90ac010c72e4ebe5a6bb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""A Resource is a file and its various associated canonical names."""

import codecs
import os


class Resource(object):
  """Represents a file found via a path search."""

  def __init__(self, toplevel_dir, absolute_path, binary=False):
    self.toplevel_dir = toplevel_dir
    self.absolute_path = absolute_path
    self._contents = None
    self._binary = binary

  @property
  def relative_path(self):
    """The path to the file from the top-level directory"""
    return os.path.relpath(self.absolute_path, self.toplevel_dir)

  @property
  def unix_style_relative_path(self):
    return self.relative_path.replace(os.sep, '/')

  @property
  def name(self):
    """The dotted name for this resource based on its relative path."""
    return self.name_from_relative_path(self.relative_path)

  @staticmethod
  def name_from_relative_path(relative_path):
    dirname = os.path.dirname(relative_path)
    basename = os.path.basename(relative_path)
    modname = os.path.splitext(basename)[0]
    if len(dirname):
      name = dirname.replace(os.path.sep, '.') + '.' + modname
    else:
      name = modname
    return name

  @property
  def contents(self):
    if self._contents:
      return self._contents
    if not os.path.exists(self.absolute_path):
      raise Exception('%s not found.' % self.absolute_path)
    if self._binary:
      f = open(self.absolute_path, mode='rb')
    else:
      f = codecs.open(self.absolute_path, mode='r', encoding='utf-8')
    self._contents = f.read()
    f.close()
    return self._contents