/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/transport/local.py

Updated from dev

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006 Canonical Ltd
 
2
 
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
 
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
 
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
"""Transport for the local filesystem.
 
18
 
 
19
This is a fairly thin wrapper on regular file IO."""
 
20
 
 
21
import os
 
22
import shutil
 
23
from stat import ST_MODE, S_ISDIR, ST_SIZE
 
24
import tempfile
 
25
import urllib
 
26
 
 
27
from bzrlib.trace import mutter
 
28
from bzrlib.transport import Transport, Server
 
29
from bzrlib.osutils import abspath, realpath, normpath, pathjoin, rename
 
30
 
 
31
 
 
32
class LocalTransport(Transport):
 
33
    """This is the transport agent for local filesystem access."""
 
34
 
 
35
    def __init__(self, base):
 
36
        """Set the base path where files will be stored."""
 
37
        if base.startswith('file://'):
 
38
            base = base[len('file://'):]
 
39
        # realpath is incompatible with symlinks. When we traverse
 
40
        # up we might be able to normpath stuff. RBC 20051003
 
41
        base = normpath(abspath(base))
 
42
        if base[-1] != '/':
 
43
            base = base + '/'
 
44
        super(LocalTransport, self).__init__(base)
 
45
 
 
46
    def should_cache(self):
 
47
        return False
 
48
 
 
49
    def clone(self, offset=None):
 
50
        """Return a new LocalTransport with root at self.base + offset
 
51
        Because the local filesystem does not require a connection, 
 
52
        we can just return a new object.
 
53
        """
 
54
        if offset is None:
 
55
            return LocalTransport(self.base)
 
56
        else:
 
57
            return LocalTransport(self.abspath(offset))
 
58
 
 
59
    def abspath(self, relpath):
 
60
        """Return the full url to the given relative URL.
 
61
        This can be supplied with a string or a list
 
62
        """
 
63
        assert isinstance(relpath, basestring), (type(relpath), relpath)
 
64
        return pathjoin(self.base, urllib.unquote(relpath))
 
65
 
 
66
    def relpath(self, abspath):
 
67
        """Return the local path portion from a given absolute path.
 
68
        """
 
69
        from bzrlib.osutils import relpath
 
70
        if abspath is None:
 
71
            abspath = u'.'
 
72
        if abspath.endswith('/'):
 
73
            abspath = abspath[:-1]
 
74
        return relpath(self.base[:-1], abspath)
 
75
 
 
76
    def has(self, relpath):
 
77
        return os.access(self.abspath(relpath), os.F_OK)
 
78
 
 
79
    def get(self, relpath):
 
80
        """Get the file at the given relative path.
 
81
 
 
82
        :param relpath: The relative path to the file
 
83
        """
 
84
        try:
 
85
            path = self.abspath(relpath)
 
86
            return open(path, 'rb')
 
87
        except (IOError, OSError),e:
 
88
            self._translate_error(e, path)
 
89
 
 
90
    def put(self, relpath, f, mode=None):
 
91
        """Copy the file-like or string object into the location.
 
92
 
 
93
        :param relpath: Location to put the contents, relative to base.
 
94
        :param f:       File-like or string object.
 
95
        """
 
96
        from bzrlib.atomicfile import AtomicFile
 
97
 
 
98
        path = relpath
 
99
        try:
 
100
            path = self.abspath(relpath)
 
101
            fp = AtomicFile(path, 'wb', new_mode=mode)
 
102
        except (IOError, OSError),e:
 
103
            self._translate_error(e, path)
 
104
        try:
 
105
            self._pump(f, fp)
 
106
            fp.commit()
 
107
        finally:
 
108
            fp.close()
 
109
 
 
110
    def iter_files_recursive(self):
 
111
        """Iter the relative paths of files in the transports sub-tree."""
 
112
        queue = list(self.list_dir(u'.'))
 
113
        while queue:
 
114
            relpath = queue.pop(0)
 
115
            st = self.stat(relpath)
 
116
            if S_ISDIR(st[ST_MODE]):
 
117
                for i, basename in enumerate(self.list_dir(relpath)):
 
118
                    queue.insert(i, relpath+'/'+basename)
 
119
            else:
 
120
                yield relpath
 
121
 
 
122
    def mkdir(self, relpath, mode=None):
 
123
        """Create a directory at the given path."""
 
124
        path = relpath
 
125
        try:
 
126
            path = self.abspath(relpath)
 
127
            os.mkdir(path)
 
128
            if mode is not None:
 
129
                os.chmod(path, mode)
 
130
        except (IOError, OSError),e:
 
131
            self._translate_error(e, path)
 
132
 
 
133
    def append(self, relpath, f):
 
134
        """Append the text in the file-like object into the final
 
135
        location.
 
136
        """
 
137
        try:
 
138
            fp = open(self.abspath(relpath), 'ab')
 
139
        except (IOError, OSError),e:
 
140
            self._translate_error(e, relpath)
 
141
        # win32 workaround (tell on an unwritten file returns 0)
 
142
        fp.seek(0, 2)
 
143
        result = fp.tell()
 
144
        self._pump(f, fp)
 
145
        return result
 
146
 
 
147
    def copy(self, rel_from, rel_to):
 
148
        """Copy the item at rel_from to the location at rel_to"""
 
149
        import shutil
 
150
        path_from = self.abspath(rel_from)
 
151
        path_to = self.abspath(rel_to)
 
152
        try:
 
153
            shutil.copy(path_from, path_to)
 
154
        except (IOError, OSError),e:
 
155
            # TODO: What about path_to?
 
156
            self._translate_error(e, path_from)
 
157
 
 
158
    def rename(self, rel_from, rel_to):
 
159
        path_from = self.abspath(rel_from)
 
160
        try:
 
161
            # *don't* call bzrlib.osutils.rename, because we want to 
 
162
            # detect errors on rename
 
163
            os.rename(path_from, self.abspath(rel_to))
 
164
        except (IOError, OSError),e:
 
165
            # TODO: What about path_to?
 
166
            self._translate_error(e, path_from)
 
167
 
 
168
    def move(self, rel_from, rel_to):
 
169
        """Move the item at rel_from to the location at rel_to"""
 
170
        path_from = self.abspath(rel_from)
 
171
        path_to = self.abspath(rel_to)
 
172
 
 
173
        try:
 
174
            # this version will delete the destination if necessary
 
175
            rename(path_from, path_to)
 
176
        except (IOError, OSError),e:
 
177
            # TODO: What about path_to?
 
178
            self._translate_error(e, path_from)
 
179
 
 
180
    def delete(self, relpath):
 
181
        """Delete the item at relpath"""
 
182
        path = relpath
 
183
        try:
 
184
            path = self.abspath(relpath)
 
185
            os.remove(path)
 
186
        except (IOError, OSError),e:
 
187
            # TODO: What about path_to?
 
188
            self._translate_error(e, path)
 
189
 
 
190
    def copy_to(self, relpaths, other, mode=None, pb=None):
 
191
        """Copy a set of entries from self into another Transport.
 
192
 
 
193
        :param relpaths: A list/generator of entries to be copied.
 
194
        """
 
195
        if isinstance(other, LocalTransport):
 
196
            # Both from & to are on the local filesystem
 
197
            # Unfortunately, I can't think of anything faster than just
 
198
            # copying them across, one by one :(
 
199
            import shutil
 
200
 
 
201
            total = self._get_total(relpaths)
 
202
            count = 0
 
203
            for path in relpaths:
 
204
                self._update_pb(pb, 'copy-to', count, total)
 
205
                try:
 
206
                    mypath = self.abspath(path)
 
207
                    otherpath = other.abspath(path)
 
208
                    shutil.copy(mypath, otherpath)
 
209
                    if mode is not None:
 
210
                        os.chmod(otherpath, mode)
 
211
                except (IOError, OSError),e:
 
212
                    self._translate_error(e, path)
 
213
                count += 1
 
214
            return count
 
215
        else:
 
216
            return super(LocalTransport, self).copy_to(relpaths, other, mode=mode, pb=pb)
 
217
 
 
218
    def listable(self):
 
219
        """See Transport.listable."""
 
220
        return True
 
221
 
 
222
    def list_dir(self, relpath):
 
223
        """Return a list of all files at the given location.
 
224
        WARNING: many transports do not support this, so trying avoid using
 
225
        it if at all possible.
 
226
        """
 
227
        path = self.abspath(relpath)
 
228
        try:
 
229
            return [urllib.quote(entry) for entry in os.listdir(path)]
 
230
        except (IOError, OSError), e:
 
231
            self._translate_error(e, path)
 
232
 
 
233
    def stat(self, relpath):
 
234
        """Return the stat information for a file.
 
235
        """
 
236
        path = relpath
 
237
        try:
 
238
            path = self.abspath(relpath)
 
239
            return os.stat(path)
 
240
        except (IOError, OSError),e:
 
241
            self._translate_error(e, path)
 
242
 
 
243
    def lock_read(self, relpath):
 
244
        """Lock the given file for shared (read) access.
 
245
        :return: A lock object, which should be passed to Transport.unlock()
 
246
        """
 
247
        from bzrlib.lock import ReadLock
 
248
        path = relpath
 
249
        try:
 
250
            path = self.abspath(relpath)
 
251
            return ReadLock(path)
 
252
        except (IOError, OSError), e:
 
253
            self._translate_error(e, path)
 
254
 
 
255
    def lock_write(self, relpath):
 
256
        """Lock the given file for exclusive (write) access.
 
257
        WARNING: many transports do not support this, so trying avoid using it
 
258
 
 
259
        :return: A lock object, which should be passed to Transport.unlock()
 
260
        """
 
261
        from bzrlib.lock import WriteLock
 
262
        return WriteLock(self.abspath(relpath))
 
263
 
 
264
    def rmdir(self, relpath):
 
265
        """See Transport.rmdir."""
 
266
        path = relpath
 
267
        try:
 
268
            path = self.abspath(relpath)
 
269
            os.rmdir(path)
 
270
        except (IOError, OSError),e:
 
271
            self._translate_error(e, path)
 
272
 
 
273
 
 
274
class ScratchTransport(LocalTransport):
 
275
    """A transport that works in a temporary dir and cleans up after itself.
 
276
    
 
277
    The dir only exists for the lifetime of the Python object.
 
278
    Obviously you should not put anything precious in it.
 
279
    """
 
280
 
 
281
    def __init__(self, base=None):
 
282
        if base is None:
 
283
            base = tempfile.mkdtemp()
 
284
        super(ScratchTransport, self).__init__(base)
 
285
 
 
286
    def __del__(self):
 
287
        shutil.rmtree(self.base, ignore_errors=True)
 
288
        mutter("%r destroyed" % self)
 
289
 
 
290
 
 
291
class LocalRelpathServer(Server):
 
292
    """A pretend server for local transports, using relpaths."""
 
293
 
 
294
    def get_url(self):
 
295
        """See Transport.Server.get_url."""
 
296
        return "."
 
297
 
 
298
 
 
299
class LocalAbspathServer(Server):
 
300
    """A pretend server for local transports, using absolute paths."""
 
301
 
 
302
    def get_url(self):
 
303
        """See Transport.Server.get_url."""
 
304
        return os.path.abspath("")
 
305
 
 
306
 
 
307
class LocalURLServer(Server):
 
308
    """A pretend server for local transports, using file:// urls."""
 
309
 
 
310
    def get_url(self):
 
311
        """See Transport.Server.get_url."""
 
312
        # FIXME: \ to / on windows
 
313
        return "file://%s" % os.path.abspath("")
 
314
 
 
315
 
 
316
def get_test_permutations():
 
317
    """Return the permutations to be used in testing."""
 
318
    return [(LocalTransport, LocalRelpathServer),
 
319
            (LocalTransport, LocalAbspathServer),
 
320
            (LocalTransport, LocalURLServer),
 
321
            ]