1
# Copyright (C) 2005 Canonical Ltd
1
# Copyright (C) 2005, 2006 Canonical Ltd
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
11
# GNU General Public License for more details.
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
17
"""Transport for the local filesystem.
19
This is a fairly thin wrapper on regular file IO."""
19
This is a fairly thin wrapper on regular file IO.
23
from stat import ST_MODE, S_ISDIR, ST_SIZE, S_IMODE
26
from bzrlib.lazy_import import lazy_import
27
lazy_import(globals(), """
24
from stat import ST_MODE, S_ISDIR, ST_SIZE
28
37
from bzrlib.trace import mutter
29
from bzrlib.transport import Transport, register_transport, \
30
TransportError, NoSuchFile, FileExists
31
from bzrlib.osutils import abspath
33
class LocalTransportError(TransportError):
40
from bzrlib.transport import Transport, Server
43
_append_flags = os.O_CREAT | os.O_APPEND | os.O_WRONLY | osutils.O_BINARY
44
_put_non_atomic_flags = os.O_CREAT | os.O_TRUNC | os.O_WRONLY | osutils.O_BINARY
37
47
class LocalTransport(Transport):
60
78
return LocalTransport(self.abspath(offset))
80
def _abspath(self, relative_reference):
81
"""Return a path for use in os calls.
83
Several assumptions are made:
84
- relative_reference does not contain '..'
85
- relative_reference is url escaped.
87
if relative_reference in ('.', ''):
88
return self._local_base
89
return self._local_base + urlutils.unescape(relative_reference)
62
91
def abspath(self, relpath):
63
"""Return the full url to the given relative URL.
64
This can be supplied with a string or a list
92
"""Return the full url to the given relative URL."""
93
# TODO: url escape the result. RBC 20060523.
94
assert isinstance(relpath, basestring), (type(relpath), relpath)
95
# jam 20060426 Using normpath on the real path, because that ensures
96
# proper handling of stuff like
97
path = osutils.normpath(osutils.pathjoin(
98
self._local_base, urlutils.unescape(relpath)))
99
return urlutils.local_path_to_url(path)
101
def local_abspath(self, relpath):
102
"""Transform the given relative path URL into the actual path on disk
104
This function only exists for the LocalTransport, since it is
105
the only one that has direct local access.
106
This is mostly for stuff like WorkingTree which needs to know
107
the local working directory.
109
This function is quite expensive: it calls realpath which resolves
66
assert isinstance(relpath, basestring)
67
return os.path.join(self.base, urllib.unquote(relpath))
112
absurl = self.abspath(relpath)
113
# mutter(u'relpath %s => base: %s, absurl %s', relpath, self.base, absurl)
114
return urlutils.local_path_from_url(absurl)
69
116
def relpath(self, abspath):
70
117
"""Return the local path portion from a given absolute path.
72
from bzrlib.osutils import relpath
73
119
if abspath is None:
75
return relpath(self.base, abspath)
122
return urlutils.file_relpath(
123
urlutils.strip_trailing_slash(self.base),
124
urlutils.strip_trailing_slash(abspath))
77
126
def has(self, relpath):
78
return os.access(self.abspath(relpath), os.F_OK)
127
return os.access(self._abspath(relpath), os.F_OK)
80
129
def get(self, relpath):
81
130
"""Get the file at the given relative path.
83
132
:param relpath: The relative path to the file
86
path = self.abspath(relpath)
135
path = self._abspath(relpath)
87
136
return open(path, 'rb')
89
if e.errno in (errno.ENOENT, errno.ENOTDIR):
90
raise NoSuchFile('File or directory %r does not exist' % path, orig_error=e)
91
raise LocalTransportError(orig_error=e)
137
except (IOError, OSError),e:
138
self._translate_error(e, path)
93
def put(self, relpath, f):
94
"""Copy the file-like or string object into the location.
140
def put_file(self, relpath, f, mode=None):
141
"""Copy the file-like object into the location.
96
143
:param relpath: Location to put the contents, relative to base.
97
:param f: File-like or string object.
144
:param f: File-like object.
145
:param mode: The mode for the newly created file,
146
None means just use the default
99
from bzrlib.atomicfile import AtomicFile
102
path = self.abspath(relpath)
103
fp = AtomicFile(path, 'wb')
105
if e.errno == errno.ENOENT:
106
raise NoSuchFile('File %r does not exist' % path, orig_error=e)
107
raise LocalTransportError(orig_error=e)
151
path = self._abspath(relpath)
152
osutils.check_legal_path(path)
153
fp = atomicfile.AtomicFile(path, 'wb', new_mode=mode)
154
except (IOError, OSError),e:
155
self._translate_error(e, path)
109
157
self._pump(f, fp)
162
def put_bytes(self, relpath, bytes, mode=None):
163
"""Copy the string into the location.
165
:param relpath: Location to put the contents, relative to base.
171
path = self._abspath(relpath)
172
osutils.check_legal_path(path)
173
fp = atomicfile.AtomicFile(path, 'wb', new_mode=mode)
174
except (IOError, OSError),e:
175
self._translate_error(e, path)
182
def _put_non_atomic_helper(self, relpath, writer,
184
create_parent_dir=False,
186
"""Common functionality information for the put_*_non_atomic.
188
This tracks all the create_parent_dir stuff.
190
:param relpath: the path we are putting to.
191
:param writer: A function that takes an os level file descriptor
192
and writes whatever data it needs to write there.
193
:param mode: The final file mode.
194
:param create_parent_dir: Should we be creating the parent directory
197
abspath = self._abspath(relpath)
199
# os.open() will automatically use the umask
204
fd = os.open(abspath, _put_non_atomic_flags, local_mode)
205
except (IOError, OSError),e:
206
# We couldn't create the file, maybe we need to create
207
# the parent directory, and try again
208
if (not create_parent_dir
209
or e.errno not in (errno.ENOENT,errno.ENOTDIR)):
210
self._translate_error(e, relpath)
211
parent_dir = os.path.dirname(abspath)
213
self._translate_error(e, relpath)
214
self._mkdir(parent_dir, mode=dir_mode)
215
# We created the parent directory, lets try to open the
218
fd = os.open(abspath, _put_non_atomic_flags, local_mode)
219
except (IOError, OSError), e:
220
self._translate_error(e, relpath)
223
if mode is not None and mode != S_IMODE(st.st_mode):
224
# Because of umask, we may still need to chmod the file.
225
# But in the general case, we won't have to
226
os.chmod(abspath, mode)
231
def put_file_non_atomic(self, relpath, f, mode=None,
232
create_parent_dir=False,
234
"""Copy the file-like object into the target location.
236
This function is not strictly safe to use. It is only meant to
237
be used when you already know that the target does not exist.
238
It is not safe, because it will open and truncate the remote
239
file. So there may be a time when the file has invalid contents.
241
:param relpath: The remote location to put the contents.
242
:param f: File-like object.
243
:param mode: Possible access permissions for new file.
244
None means do not set remote permissions.
245
:param create_parent_dir: If we cannot create the target file because
246
the parent directory does not exist, go ahead and
247
create it, and then try again.
250
self._pump_to_fd(f, fd)
251
self._put_non_atomic_helper(relpath, writer, mode=mode,
252
create_parent_dir=create_parent_dir,
255
def put_bytes_non_atomic(self, relpath, bytes, mode=None,
256
create_parent_dir=False, dir_mode=None):
259
self._put_non_atomic_helper(relpath, writer, mode=mode,
260
create_parent_dir=create_parent_dir,
114
263
def iter_files_recursive(self):
115
264
"""Iter the relative paths of files in the transports sub-tree."""
116
queue = list(self.list_dir('.'))
265
queue = list(self.list_dir(u'.'))
118
267
relpath = queue.pop(0)
119
268
st = self.stat(relpath)
126
def mkdir(self, relpath):
275
def _mkdir(self, abspath, mode=None):
276
"""Create a real directory, filtering through mode"""
278
# os.mkdir() will filter through umask
283
os.mkdir(abspath, local_mode)
285
# It is probably faster to just do the chmod, rather than
286
# doing a stat, and then trying to compare
287
os.chmod(abspath, mode)
288
except (IOError, OSError),e:
289
self._translate_error(e, abspath)
291
def mkdir(self, relpath, mode=None):
127
292
"""Create a directory at the given path."""
129
os.mkdir(self.abspath(relpath))
131
if e.errno == errno.EEXIST:
132
raise FileExists(orig_error=e)
133
elif e.errno == errno.ENOENT:
134
raise NoSuchFile(orig_error=e)
135
raise LocalTransportError(orig_error=e)
137
def append(self, relpath, f):
138
"""Append the text in the file-like object into the final
141
fp = open(self.abspath(relpath), 'ab')
293
self._mkdir(self._abspath(relpath), mode=mode)
295
def _get_append_file(self, relpath, mode=None):
296
"""Call os.open() for the given relpath"""
297
file_abspath = self._abspath(relpath)
299
# os.open() will automatically use the umask
304
return file_abspath, os.open(file_abspath, _append_flags, local_mode)
305
except (IOError, OSError),e:
306
self._translate_error(e, relpath)
308
def _check_mode_and_size(self, file_abspath, fd, mode=None):
309
"""Check the mode of the file, and return the current size"""
311
if mode is not None and mode != S_IMODE(st.st_mode):
312
# Because of umask, we may still need to chmod the file.
313
# But in the general case, we won't have to
314
os.chmod(file_abspath, mode)
317
def append_file(self, relpath, f, mode=None):
318
"""Append the text in the file-like object into the final location."""
319
file_abspath, fd = self._get_append_file(relpath, mode=mode)
321
result = self._check_mode_and_size(file_abspath, fd, mode=mode)
322
self._pump_to_fd(f, fd)
327
def append_bytes(self, relpath, bytes, mode=None):
328
"""Append the text in the string into the final location."""
329
file_abspath, fd = self._get_append_file(relpath, mode=mode)
331
result = self._check_mode_and_size(file_abspath, fd, mode=mode)
337
def _pump_to_fd(self, fromfile, to_fd):
338
"""Copy contents of one file to another."""
341
b = fromfile.read(BUFSIZE)
144
346
def copy(self, rel_from, rel_to):
145
347
"""Copy the item at rel_from to the location at rel_to"""
147
path_from = self.abspath(rel_from)
148
path_to = self.abspath(rel_to)
348
path_from = self._abspath(rel_from)
349
path_to = self._abspath(rel_to)
150
351
shutil.copy(path_from, path_to)
152
raise LocalTransportError(orig_error=e)
352
except (IOError, OSError),e:
353
# TODO: What about path_to?
354
self._translate_error(e, path_from)
356
def rename(self, rel_from, rel_to):
357
path_from = self._abspath(rel_from)
359
# *don't* call bzrlib.osutils.rename, because we want to
360
# detect errors on rename
361
os.rename(path_from, self._abspath(rel_to))
362
except (IOError, OSError),e:
363
# TODO: What about path_to?
364
self._translate_error(e, path_from)
154
366
def move(self, rel_from, rel_to):
155
367
"""Move 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)
368
path_from = self._abspath(rel_from)
369
path_to = self._abspath(rel_to)
160
os.rename(path_from, path_to)
162
raise LocalTransportError(orig_error=e)
372
# this version will delete the destination if necessary
373
osutils.rename(path_from, path_to)
374
except (IOError, OSError),e:
375
# TODO: What about path_to?
376
self._translate_error(e, path_from)
164
378
def delete(self, relpath):
165
379
"""Delete the item at relpath"""
167
os.remove(self.abspath(relpath))
169
raise LocalTransportError(orig_error=e)
382
path = self._abspath(relpath)
384
except (IOError, OSError),e:
385
self._translate_error(e, path)
171
def copy_to(self, relpaths, other, pb=None):
387
def copy_to(self, relpaths, other, mode=None, pb=None):
172
388
"""Copy a set of entries from self into another Transport.
174
390
:param relpaths: A list/generator of entries to be copied.
177
393
# Both from & to are on the local filesystem
178
394
# Unfortunately, I can't think of anything faster than just
179
395
# copying them across, one by one :(
182
396
total = self._get_total(relpaths)
184
398
for path in relpaths:
185
399
self._update_pb(pb, 'copy-to', count, total)
186
shutil.copy(self.abspath(path), other.abspath(path))
401
mypath = self._abspath(path)
402
otherpath = other._abspath(path)
403
shutil.copy(mypath, otherpath)
405
os.chmod(otherpath, mode)
406
except (IOError, OSError),e:
407
self._translate_error(e, path)
190
return super(LocalTransport, self).copy_to(relpaths, other, pb=pb)
411
return super(LocalTransport, self).copy_to(relpaths, other, mode=mode, pb=pb)
192
413
def listable(self):
193
414
"""See Transport.listable."""
198
419
WARNING: many transports do not support this, so trying avoid using
199
420
it if at all possible.
422
path = self._abspath(relpath)
202
return os.listdir(self.abspath(relpath))
204
raise LocalTransportError(orig_error=e)
424
entries = os.listdir(path)
425
except (IOError, OSError), e:
426
self._translate_error(e, path)
427
return [urlutils.escape(entry) for entry in entries]
206
429
def stat(self, relpath):
207
430
"""Return the stat information for a file.
210
return os.stat(self.abspath(relpath))
212
raise LocalTransportError(orig_error=e)
434
path = self._abspath(relpath)
436
except (IOError, OSError),e:
437
self._translate_error(e, path)
214
439
def lock_read(self, relpath):
215
440
"""Lock the given file for shared (read) access.
216
441
:return: A lock object, which should be passed to Transport.unlock()
218
443
from bzrlib.lock import ReadLock
219
return ReadLock(self.abspath(relpath))
446
path = self._abspath(relpath)
447
return ReadLock(path)
448
except (IOError, OSError), e:
449
self._translate_error(e, path)
221
451
def lock_write(self, relpath):
222
452
"""Lock the given file for exclusive (write) access.
225
455
:return: A lock object, which should be passed to Transport.unlock()
227
457
from bzrlib.lock import WriteLock
228
return WriteLock(self.abspath(relpath))
231
class ScratchTransport(LocalTransport):
232
"""A transport that works in a temporary dir and cleans up after itself.
458
return WriteLock(self._abspath(relpath))
460
def rmdir(self, relpath):
461
"""See Transport.rmdir."""
464
path = self._abspath(relpath)
466
except (IOError, OSError),e:
467
self._translate_error(e, path)
469
def _can_roundtrip_unix_modebits(self):
470
if sys.platform == 'win32':
477
class LocalURLServer(Server):
478
"""A pretend server for local transports, using file:// urls.
234
The dir only exists for the lifetime of the Python object.
235
Obviously you should not put anything precious in it.
480
Of course no actual server is required to access the local filesystem, so
481
this just exists to tell the test code how to get to it.
238
def __init__(self, base=None):
240
base = tempfile.mkdtemp()
241
super(ScratchTransport, self).__init__(base)
244
shutil.rmtree(self.base, ignore_errors=True)
245
mutter("%r destroyed" % self)
485
"""See Transport.Server.get_url."""
486
return urlutils.local_path_to_url('')
489
def get_test_permutations():
490
"""Return the permutations to be used in testing."""
492
(LocalTransport, LocalURLServer),