1
# Copyright (C) 2005, 2006 Canonical Ltd
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.
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.
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
17
"""Transport for the local filesystem.
19
This is a fairly thin wrapper on regular file IO."""
24
from stat import ST_MODE, S_ISDIR, ST_SIZE
28
from bzrlib.trace import mutter
29
from bzrlib.transport import Transport, Server
30
from bzrlib.osutils import abspath, realpath, normpath, pathjoin, rename
33
class LocalTransport(Transport):
34
"""This is the transport agent for local filesystem access."""
36
def __init__(self, base):
37
"""Set the base path where files will be stored."""
38
if base.startswith('file://'):
39
base = base[len('file://'):]
40
# realpath is incompatible with symlinks. When we traverse
41
# up we might be able to normpath stuff. RBC 20051003
42
base = normpath(abspath(base))
45
super(LocalTransport, self).__init__(base)
47
def should_cache(self):
50
def clone(self, offset=None):
51
"""Return a new LocalTransport with root at self.base + offset
52
Because the local filesystem does not require a connection,
53
we can just return a new object.
56
return LocalTransport(self.base)
58
return LocalTransport(self.abspath(offset))
60
def abspath(self, relpath):
61
"""Return the full url to the given relative URL."""
62
assert isinstance(relpath, basestring), (type(relpath), relpath)
63
result = normpath(pathjoin(self.base, urllib.unquote(relpath)))
64
#if result[-1] != '/':
68
def relpath(self, abspath):
69
"""Return the local path portion from a given absolute path.
71
from bzrlib.osutils import relpath
74
if len(abspath) > 1 and abspath.endswith('/'):
75
abspath = abspath[:-1]
80
return relpath(root, abspath)
82
def has(self, relpath):
83
return os.access(self.abspath(relpath), os.F_OK)
85
def get(self, relpath):
86
"""Get the file at the given relative path.
88
:param relpath: The relative path to the file
91
path = self.abspath(relpath)
92
return open(path, 'rb')
93
except (IOError, OSError),e:
94
self._translate_error(e, path)
96
def put(self, relpath, f, mode=None):
97
"""Copy the file-like or string object into the location.
99
:param relpath: Location to put the contents, relative to base.
100
:param f: File-like or string object.
102
from bzrlib.atomicfile import AtomicFile
106
path = self.abspath(relpath)
107
fp = AtomicFile(path, 'wb', new_mode=mode)
108
except (IOError, OSError),e:
109
self._translate_error(e, path)
116
def iter_files_recursive(self):
117
"""Iter the relative paths of files in the transports sub-tree."""
118
queue = list(self.list_dir(u'.'))
120
relpath = queue.pop(0)
121
st = self.stat(relpath)
122
if S_ISDIR(st[ST_MODE]):
123
for i, basename in enumerate(self.list_dir(relpath)):
124
queue.insert(i, relpath+'/'+basename)
128
def mkdir(self, relpath, mode=None):
129
"""Create a directory at the given path."""
132
path = self.abspath(relpath)
136
except (IOError, OSError),e:
137
self._translate_error(e, path)
139
def append(self, relpath, f):
140
"""Append the text in the file-like object into the final
144
fp = open(self.abspath(relpath), 'ab')
145
except (IOError, OSError),e:
146
self._translate_error(e, relpath)
147
# win32 workaround (tell on an unwritten file returns 0)
153
def copy(self, rel_from, rel_to):
154
"""Copy the item at rel_from to the location at rel_to"""
156
path_from = self.abspath(rel_from)
157
path_to = self.abspath(rel_to)
159
shutil.copy(path_from, path_to)
160
except (IOError, OSError),e:
161
# TODO: What about path_to?
162
self._translate_error(e, path_from)
164
def rename(self, rel_from, rel_to):
165
path_from = self.abspath(rel_from)
167
# *don't* call bzrlib.osutils.rename, because we want to
168
# detect errors on rename
169
os.rename(path_from, self.abspath(rel_to))
170
except (IOError, OSError),e:
171
# TODO: What about path_to?
172
self._translate_error(e, path_from)
174
def move(self, rel_from, rel_to):
175
"""Move the item at rel_from to the location at rel_to"""
176
path_from = self.abspath(rel_from)
177
path_to = self.abspath(rel_to)
180
# this version will delete the destination if necessary
181
rename(path_from, path_to)
182
except (IOError, OSError),e:
183
# TODO: What about path_to?
184
self._translate_error(e, path_from)
186
def delete(self, relpath):
187
"""Delete the item at relpath"""
190
path = self.abspath(relpath)
192
except (IOError, OSError),e:
193
# TODO: What about path_to?
194
self._translate_error(e, path)
196
def copy_to(self, relpaths, other, mode=None, pb=None):
197
"""Copy a set of entries from self into another Transport.
199
:param relpaths: A list/generator of entries to be copied.
201
if isinstance(other, LocalTransport):
202
# Both from & to are on the local filesystem
203
# Unfortunately, I can't think of anything faster than just
204
# copying them across, one by one :(
207
total = self._get_total(relpaths)
209
for path in relpaths:
210
self._update_pb(pb, 'copy-to', count, total)
212
mypath = self.abspath(path)
213
otherpath = other.abspath(path)
214
shutil.copy(mypath, otherpath)
216
os.chmod(otherpath, mode)
217
except (IOError, OSError),e:
218
self._translate_error(e, path)
222
return super(LocalTransport, self).copy_to(relpaths, other, mode=mode, pb=pb)
225
"""See Transport.listable."""
228
def list_dir(self, relpath):
229
"""Return a list of all files at the given location.
230
WARNING: many transports do not support this, so trying avoid using
231
it if at all possible.
233
path = self.abspath(relpath)
235
return [urllib.quote(entry) for entry in os.listdir(path)]
236
except (IOError, OSError), e:
237
self._translate_error(e, path)
239
def stat(self, relpath):
240
"""Return the stat information for a file.
244
path = self.abspath(relpath)
246
except (IOError, OSError),e:
247
self._translate_error(e, path)
249
def lock_read(self, relpath):
250
"""Lock the given file for shared (read) access.
251
:return: A lock object, which should be passed to Transport.unlock()
253
from bzrlib.lock import ReadLock
256
path = self.abspath(relpath)
257
return ReadLock(path)
258
except (IOError, OSError), e:
259
self._translate_error(e, path)
261
def lock_write(self, relpath):
262
"""Lock the given file for exclusive (write) access.
263
WARNING: many transports do not support this, so trying avoid using it
265
:return: A lock object, which should be passed to Transport.unlock()
267
from bzrlib.lock import WriteLock
268
return WriteLock(self.abspath(relpath))
270
def rmdir(self, relpath):
271
"""See Transport.rmdir."""
274
path = self.abspath(relpath)
276
except (IOError, OSError),e:
277
self._translate_error(e, path)
279
def _can_roundtrip_unix_modebits(self):
280
if sys.platform == 'win32':
287
class ScratchTransport(LocalTransport):
288
"""A transport that works in a temporary dir and cleans up after itself.
290
The dir only exists for the lifetime of the Python object.
291
Obviously you should not put anything precious in it.
294
def __init__(self, base=None):
296
base = tempfile.mkdtemp()
297
super(ScratchTransport, self).__init__(base)
300
shutil.rmtree(self.base, ignore_errors=True)
301
mutter("%r destroyed" % self)
304
class LocalRelpathServer(Server):
305
"""A pretend server for local transports, using relpaths."""
308
"""See Transport.Server.get_url."""
312
class LocalAbspathServer(Server):
313
"""A pretend server for local transports, using absolute paths."""
316
"""See Transport.Server.get_url."""
317
return os.path.abspath("")
320
class LocalURLServer(Server):
321
"""A pretend server for local transports, using file:// urls."""
324
"""See Transport.Server.get_url."""
325
# FIXME: \ to / on windows
326
return "file://%s" % os.path.abspath("")
329
def get_test_permutations():
330
"""Return the permutations to be used in testing."""
331
return [(LocalTransport, LocalRelpathServer),
332
(LocalTransport, LocalAbspathServer),
333
(LocalTransport, LocalURLServer),