summaryrefslogtreecommitdiffstats
path: root/src/engine/SCons/Node/FS.py
blob: fc7b042c839f9354e0fd97e3ff3633dd3179e37d (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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
"""scons.Node.FS

File system nodes.

This initializes a "default_fs" Node with an FS at the current directory
for its own purposes, and for use by scripts or modules looking for the
canonical default.

"""

__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"

import os
import os.path
from SCons.Node import Node
from UserDict import UserDict
import sys

class PathName:
    """This is a string like object with limited capabilities (i.e.,
    cannot always be used interchangeably with strings).  This class
    is used by PathDict to manage case-insensitive path names.  It preserves
    the case of the string with which it was created, but on OS's with
    case insensitive paths, it will hash equal to any case of the same
    path when placed in a dictionary."""

    try:
        convert_path = unicode
    except NameError:
        convert_path = str

    def __init__(self, path_name=''):
        self.data = PathName.convert_path(path_name)
        self.norm_path = os.path.normcase(self.data)

    def __hash__(self):
        return hash(self.norm_path)
    def __cmp__(self, other):
        return cmp(self.norm_path,
                   os.path.normcase(PathName.convert_path(other)))
    def __rcmp__(self, other):
        return cmp(os.path.normcase(PathName.convert_path(other)),
                   self.norm_path)
    def __str__(self):
        return str(self.data)
    def __repr__(self):
        return repr(self.data)

class PathDict(UserDict):
    """This is a dictionary-like class meant to hold items keyed
    by path name.  The difference between this class and a normal
    dictionary is that string or unicode keys will act differently
    on OS's that have case-insensitive path names.  Specifically
    string or unicode keys of different case will be treated as
    equal on the OS's.

    All keys are implicitly converted to PathName objects before
    insertion into the dictionary."""

    def __init__(self, initdict = {}):
        UserDict.__init__(self, initdict)
        old_dict = self.data
        self.data = {}
        for key, val in old_dict.items():
            self.data[PathName(key)] = val

    def __setitem__(self, key, val):
        self.data[PathName(key)] = val

    def __getitem__(self, key):
        return self.data[PathName(key)]

    def __delitem__(self, key):
        del(self.data[PathName(key)])

    if not hasattr(UserDict, 'setdefault'):
        def setdefault(self, key, value):
            try:
                return self.data[PathName(key)]
            except KeyError:
                self.data[PathName(key)] = value
                return value

class FS:
    def __init__(self, path = None):
        """Initialize the Node.FS subsystem.

        The supplied path is the top of the source tree, where we
        expect to find the top-level build file.  If no path is
        supplied, the current directory is the default.

        The path argument must be a valid absolute path.
        """
        if path == None:
            path = os.getcwd()
        self.Root = PathDict()
        self.Top = self.__doLookup(Dir, path)
        self.Top.path = '.'

    def __doLookup(self, fsclass, name, directory=None):
        """This method differs from the File and Dir factory methods in
        one important way: the meaning of the directory parameter.
        In this method, if directory is None or not supplied, the supplied
	name is expected to be an absolute path.  If you try to look up a
	relative path with directory=None, then an AssertionError will be
	raised."""

        head, tail = os.path.split(os.path.normpath(name))
        if not tail:
            # We have reached something that looks like a root
            # of an absolute path.  What we do here is a little
            # weird.  If we are on a UNIX system, everything is
            # well and good, just return the root node.
            #
            # On DOS/Win32 things are strange, since a path
            # starting with a slash is not technically an
            # absolute path, but a path relative to the
            # current drive.  Therefore if we get a path like
            # that, we will return the root Node of the
            # directory parameter.  If the directory parameter is
            # None, raise an exception.

            drive, tail = os.path.splitdrive(head)
            if sys.platform is 'win32' and not drive:
                if not directory:
                    raise OSError, 'No drive letter supplied for absolute path.'
                return directory.root()
            return self.Root.setdefault(drive, Dir(tail))
        if head:
            # Recursively look up our parent directories.
            directory = self.__doLookup(Dir, head, directory)
        else:
            # This path looks like a relative path.  No leading slash or drive
	    # letter.  Therefore, we will look up this path relative to the
	    # supplied top-level directory.
	    assert directory, "Tried to lookup a node by relative path with no top-level directory supplied."
        ret = directory.entries.setdefault(tail, fsclass(tail, directory))
        if not isinstance(ret, fsclass):
            raise TypeError, ret
        return ret

    def __transformPath(self, name, directory):
        """Take care of setting up the correct top-level directory,
        usually in preparation for a call to doLookup().

        If the path name is prepended with a '#', then it is unconditionally
        interpreted as replative to the top-level directory of this FS.

        If directory is None, and name is a relative path,
        then the same applies.
        """
        if name[0] == '#':
            directory = self.Top
            name = os.path.join(os.path.normpath('./'), name[1:])
        elif not directory:
            directory = self.Top
        return (name, directory)
    
    def File(self, name, directory = None):
        """Lookup or create a File node with the specified name.  If
        the name is a relative path (begins with ./, ../, or a file name),
        then it is looked up relative to the supplied directory node,
        or to the top level directory of the FS (supplied at construction
        time) if no directory is supplied.

        This method will raise TypeError if a directory is found at the
        specified path.
        """
        name, directory = self.__transformPath(name, directory)
        return self.__doLookup(File, name, directory)

    def Dir(self, name, directory = None):
        """Lookup or create a Dir node with the specified name.  If
        the name is a relative path (begins with ./, ../, or a file name),
        then it is looked up relative to the supplied directory node,
        or to the top level directory of the FS (supplied at construction
        time) if no directory is supplied.

        This method will raise TypeError if a normal file is found at the
        specified path.
        """
        name, directory = self.__transformPath(name, directory)
        return self.__doLookup(Dir, name, directory)

    

# XXX TODO?
# Annotate with the creator
# is_under
# rel_path
# srcpath / srcdir
# link / is_linked
# linked_targets
# is_accessible

class Dir(Node):
    """A class for directories in a file system.
    """

    def __init__(self, name, directory = None):
        self.entries = PathDict()
        self.entries['.'] = self

        if directory:
            self.entries['..'] = directory
            self.abspath = os.path.join(directory.abspath, name, '')
            if str(directory.path) == '.':
                self.path = os.path.join(name, '')
            else:
                self.path = os.path.join(directory.path, name, '')
        else:
            self.abspath = self.path = name
            self.entries['..'] = None

    def up(self):
        return self.entries['..']

    def root(self):
        if not self.entries['..']:
            return self
        else:
            return self.entries['..'].root()


# XXX TODO?
# rfile
# precious
# no_rfile
# rpath
# rsrcpath
# source_exists
# derived_exists
# is_on_rpath
# local
# base_suf
# suffix
# addsuffix
# accessible
# ignore
# build
# bind
# is_under
# relpath

class File(Node):
    """A class for files in a file system.
    """

    def __init__(self, name, directory):
        self.abspath = os.path.join(directory.abspath, name)
        if str(directory.path) == '.':
            self.path = name
        else:
            self.path = os.path.join(directory.path, name)
        self.parent = directory

    def root(self):
        return self.parent.root()

    def get_contents(self):
        return open(self.path, "r").read()

    def get_timestamp(self):
        return os.path.getmtime(self.path)

    def exists(self):
        return os.path.exists(self.path)


default_fs = FS()