file_system.py revision b2df76ea8fec9e32f6f3718986dba0d95315b29c
1# Copyright (c) 2012 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 os
6
7class FileNotFoundError(Exception):
8  def __init__(self, filename):
9    Exception.__init__(self, filename)
10
11class StatInfo(object):
12  '''The result of calling Stat on a FileSystem.
13  '''
14  def __init__(self, version, child_versions=None):
15    self.version = version
16    self.child_versions = child_versions
17
18  def __eq__(self, other):
19    return (self.version == other.version and
20            self.child_versions == other.child_versions)
21
22  def __ne__(self, other):
23    return not (self == other)
24
25  def __str__(self):
26    return '{version: %s, child_versions: %s}' % (self.version,
27                                                  self.child_versions)
28
29  def __repr__(self):
30    return str(self)
31
32def ToUnicode(data):
33  '''Returns the str |data| as a unicode object. It's expected to be utf8, but
34  there are also latin-1 encodings in there for some reason. Fall back to that.
35  '''
36  try:
37    return unicode(data, 'utf-8')
38  except:
39    return unicode(data, 'latin-1')
40
41class FileSystem(object):
42  '''A FileSystem interface that can read files and directories.
43  '''
44
45  def Read(self, paths, binary=False):
46    '''Reads each file in paths and returns a dictionary mapping the path to the
47    contents. If a path in paths ends with a '/', it is assumed to be a
48    directory, and a list of files in the directory is mapped to the path.
49
50    If binary=False, the contents of each file will be unicode parsed as utf-8,
51    and failing that as latin-1 (some extension docs use latin-1). If
52    binary=True then the contents will be a str.
53    '''
54    raise NotImplementedError()
55
56  def ReadSingle(self, path, binary=False):
57    '''Reads a single file from the FileSystem.
58    '''
59    return self.Read([path], binary=binary).Get()[path]
60
61  # TODO(cduvall): Allow Stat to take a list of paths like Read.
62  def Stat(self, path):
63    '''Returns a |StatInfo| object containing the version of |path|. If |path|
64    is a directory, |StatInfo| will have the versions of all the children of
65    the directory in |StatInfo.child_versions|.
66    '''
67    raise NotImplementedError()
68
69  def GetIdentity(self):
70    '''The identity of the file system, exposed for caching classes to
71    namespace their caches. this will usually depend on the configuration of
72    that file system - e.g. a LocalFileSystem with a base path of /var is
73    different to that of a SubversionFileSystem with a base path of /bar, is
74    different to a LocalFileSystem with a base path of /usr.
75    '''
76    raise NotImplementedError()
77