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.
26
from stat import ST_MODE, S_ISDIR, ST_SIZE, S_IMODE
34
from bzrlib.osutils import (abspath, realpath, normpath, pathjoin, rename,
35
check_legal_path, rmtree)
36
from bzrlib.symbol_versioning import warn
37
from bzrlib.trace import mutter
38
from bzrlib.transport import Transport, Server
41
_append_flags = os.O_CREAT | os.O_APPEND | os.O_WRONLY | osutils.O_BINARY
42
_put_non_atomic_flags = os.O_CREAT | os.O_TRUNC | os.O_WRONLY | osutils.O_BINARY
45
class LocalTransport(Transport):
46
"""This is the transport agent for local filesystem access."""
48
def __init__(self, base):
49
"""Set the base path where files will be stored."""
50
if not base.startswith('file://'):
51
warn("Instantiating LocalTransport with a filesystem path"
52
" is deprecated as of bzr 0.8."
53
" Please use bzrlib.transport.get_transport()"
54
" or pass in a file:// url.",
58
base = urlutils.local_path_to_url(base)
61
super(LocalTransport, self).__init__(base)
62
self._local_base = urlutils.local_path_from_url(base)
64
def should_cache(self):
67
def clone(self, offset=None):
68
"""Return a new LocalTransport with root at self.base + offset
69
Because the local filesystem does not require a connection,
70
we can just return a new object.
73
return LocalTransport(self.base)
75
return LocalTransport(self.abspath(offset))
77
def _abspath(self, relative_reference):
78
"""Return a path for use in os calls.
80
Several assumptions are made:
81
- relative_reference does not contain '..'
82
- relative_reference is url escaped.
84
if relative_reference in ('.', ''):
85
return self._local_base
86
return self._local_base + urlutils.unescape(relative_reference)
88
def abspath(self, relpath):
89
"""Return the full url to the given relative URL."""
90
# TODO: url escape the result. RBC 20060523.
91
assert isinstance(relpath, basestring), (type(relpath), relpath)
92
# jam 20060426 Using normpath on the real path, because that ensures
93
# proper handling of stuff like
94
path = normpath(pathjoin(self._local_base, urlutils.unescape(relpath)))
95
return urlutils.local_path_to_url(path)
97
def local_abspath(self, relpath):
98
"""Transform the given relative path URL into the actual path on disk
100
This function only exists for the LocalTransport, since it is
101
the only one that has direct local access.
102
This is mostly for stuff like WorkingTree which needs to know
103
the local working directory.
105
This function is quite expensive: it calls realpath which resolves
108
absurl = self.abspath(relpath)
109
# mutter(u'relpath %s => base: %s, absurl %s', relpath, self.base, absurl)
110
return urlutils.local_path_from_url(absurl)
112
def relpath(self, abspath):
113
"""Return the local path portion from a given absolute path.
118
return urlutils.file_relpath(
119
urlutils.strip_trailing_slash(self.base),
120
urlutils.strip_trailing_slash(abspath))
122
def has(self, relpath):
123
return os.access(self._abspath(relpath), os.F_OK)
125
def get(self, relpath):
126
"""Get the file at the given relative path.
128
:param relpath: The relative path to the file
131
path = self._abspath(relpath)
132
return open(path, 'rb')
133
except (IOError, OSError),e:
134
self._translate_error(e, path)
136
def put_file(self, relpath, f, mode=None):
137
"""Copy the file-like object into the location.
139
:param relpath: Location to put the contents, relative to base.
140
:param f: File-like object.
141
:param mode: The mode for the newly created file,
142
None means just use the default
147
path = self._abspath(relpath)
148
check_legal_path(path)
149
fp = atomicfile.AtomicFile(path, 'wb', new_mode=mode)
150
except (IOError, OSError),e:
151
self._translate_error(e, path)
158
def put_bytes(self, relpath, bytes, mode=None):
159
"""Copy the string into the location.
161
:param relpath: Location to put the contents, relative to base.
167
path = self._abspath(relpath)
168
check_legal_path(path)
169
fp = atomicfile.AtomicFile(path, 'wb', new_mode=mode)
170
except (IOError, OSError),e:
171
self._translate_error(e, path)
178
def _put_non_atomic_helper(self, relpath, writer,
180
create_parent_dir=False,
182
"""Common functionality information for the put_*_non_atomic.
184
This tracks all the create_parent_dir stuff.
186
:param relpath: the path we are putting to.
187
:param writer: A function that takes an os level file descriptor
188
and writes whatever data it needs to write there.
189
:param mode: The final file mode.
190
:param create_parent_dir: Should we be creating the parent directory
193
abspath = self._abspath(relpath)
195
# os.open() will automatically use the umask
200
fd = os.open(abspath, _put_non_atomic_flags, local_mode)
201
except (IOError, OSError),e:
202
# We couldn't create the file, maybe we need to create
203
# the parent directory, and try again
204
if (not create_parent_dir
205
or e.errno not in (errno.ENOENT,errno.ENOTDIR)):
206
self._translate_error(e, relpath)
207
parent_dir = os.path.dirname(abspath)
209
self._translate_error(e, relpath)
210
self._mkdir(parent_dir, mode=dir_mode)
211
# We created the parent directory, lets try to open the
214
fd = os.open(abspath, _put_non_atomic_flags, local_mode)
215
except (IOError, OSError), e:
216
self._translate_error(e, relpath)
219
if mode is not None and mode != S_IMODE(st.st_mode):
220
# Because of umask, we may still need to chmod the file.
221
# But in the general case, we won't have to
222
os.chmod(abspath, mode)
227
def put_file_non_atomic(self, relpath, f, mode=None,
228
create_parent_dir=False,
230
"""Copy the file-like object into the target location.
232
This function is not strictly safe to use. It is only meant to
233
be used when you already know that the target does not exist.
234
It is not safe, because it will open and truncate the remote
235
file. So there may be a time when the file has invalid contents.
237
:param relpath: The remote location to put the contents.
238
:param f: File-like object.
239
:param mode: Possible access permissions for new file.
240
None means do not set remote permissions.
241
:param create_parent_dir: If we cannot create the target file because
242
the parent directory does not exist, go ahead and
243
create it, and then try again.
246
self._pump_to_fd(f, fd)
247
self._put_non_atomic_helper(relpath, writer, mode=mode,
248
create_parent_dir=create_parent_dir,
251
def put_bytes_non_atomic(self, relpath, bytes, mode=None,
252
create_parent_dir=False, dir_mode=None):
255
self._put_non_atomic_helper(relpath, writer, mode=mode,
256
create_parent_dir=create_parent_dir,
259
def iter_files_recursive(self):
260
"""Iter the relative paths of files in the transports sub-tree."""
261
queue = list(self.list_dir(u'.'))
263
relpath = queue.pop(0)
264
st = self.stat(relpath)
265
if S_ISDIR(st[ST_MODE]):
266
for i, basename in enumerate(self.list_dir(relpath)):
267
queue.insert(i, relpath+'/'+basename)
271
def _mkdir(self, abspath, mode=None):
272
"""Create a real directory, filtering through mode"""
274
# os.mkdir() will filter through umask
279
os.mkdir(abspath, local_mode)
281
# It is probably faster to just do the chmod, rather than
282
# doing a stat, and then trying to compare
283
os.chmod(abspath, mode)
284
except (IOError, OSError),e:
285
self._translate_error(e, abspath)
287
def mkdir(self, relpath, mode=None):
288
"""Create a directory at the given path."""
289
self._mkdir(self._abspath(relpath), mode=mode)
291
def _get_append_file(self, relpath, mode=None):
292
"""Call os.open() for the given relpath"""
293
file_abspath = self._abspath(relpath)
295
# os.open() will automatically use the umask
300
return file_abspath, os.open(file_abspath, _append_flags, local_mode)
301
except (IOError, OSError),e:
302
self._translate_error(e, relpath)
304
def _check_mode_and_size(self, file_abspath, fd, mode=None):
305
"""Check the mode of the file, and return the current size"""
307
if mode is not None and mode != S_IMODE(st.st_mode):
308
# Because of umask, we may still need to chmod the file.
309
# But in the general case, we won't have to
310
os.chmod(file_abspath, mode)
313
def append_file(self, relpath, f, mode=None):
314
"""Append the text in the file-like object into the final location."""
315
file_abspath, fd = self._get_append_file(relpath, mode=mode)
317
result = self._check_mode_and_size(file_abspath, fd, mode=mode)
318
self._pump_to_fd(f, fd)
323
def append_bytes(self, relpath, bytes, mode=None):
324
"""Append the text in the string into the final location."""
325
file_abspath, fd = self._get_append_file(relpath, mode=mode)
327
result = self._check_mode_and_size(file_abspath, fd, mode=mode)
333
def _pump_to_fd(self, fromfile, to_fd):
334
"""Copy contents of one file to another."""
337
b = fromfile.read(BUFSIZE)
342
def copy(self, rel_from, rel_to):
343
"""Copy the item at rel_from to the location at rel_to"""
344
path_from = self._abspath(rel_from)
345
path_to = self._abspath(rel_to)
347
shutil.copy(path_from, path_to)
348
except (IOError, OSError),e:
349
# TODO: What about path_to?
350
self._translate_error(e, path_from)
352
def rename(self, rel_from, rel_to):
353
path_from = self._abspath(rel_from)
355
# *don't* call bzrlib.osutils.rename, because we want to
356
# detect errors on rename
357
os.rename(path_from, self._abspath(rel_to))
358
except (IOError, OSError),e:
359
# TODO: What about path_to?
360
self._translate_error(e, path_from)
362
def move(self, rel_from, rel_to):
363
"""Move the item at rel_from to the location at rel_to"""
364
path_from = self._abspath(rel_from)
365
path_to = self._abspath(rel_to)
368
# this version will delete the destination if necessary
369
rename(path_from, path_to)
370
except (IOError, OSError),e:
371
# TODO: What about path_to?
372
self._translate_error(e, path_from)
374
def delete(self, relpath):
375
"""Delete the item at relpath"""
378
path = self._abspath(relpath)
380
except (IOError, OSError),e:
381
self._translate_error(e, path)
383
def copy_to(self, relpaths, other, mode=None, pb=None):
384
"""Copy a set of entries from self into another Transport.
386
:param relpaths: A list/generator of entries to be copied.
388
if isinstance(other, LocalTransport):
389
# Both from & to are on the local filesystem
390
# Unfortunately, I can't think of anything faster than just
391
# copying them across, one by one :(
392
total = self._get_total(relpaths)
394
for path in relpaths:
395
self._update_pb(pb, 'copy-to', count, total)
397
mypath = self._abspath(path)
398
otherpath = other._abspath(path)
399
shutil.copy(mypath, otherpath)
401
os.chmod(otherpath, mode)
402
except (IOError, OSError),e:
403
self._translate_error(e, path)
407
return super(LocalTransport, self).copy_to(relpaths, other, mode=mode, pb=pb)
410
"""See Transport.listable."""
413
def list_dir(self, relpath):
414
"""Return a list of all files at the given location.
415
WARNING: many transports do not support this, so trying avoid using
416
it if at all possible.
418
path = self._abspath(relpath)
420
entries = os.listdir(path)
421
except (IOError, OSError), e:
422
self._translate_error(e, path)
423
return [urlutils.escape(entry) for entry in entries]
425
def stat(self, relpath):
426
"""Return the stat information for a file.
430
path = self._abspath(relpath)
432
except (IOError, OSError),e:
433
self._translate_error(e, path)
435
def lock_read(self, relpath):
436
"""Lock the given file for shared (read) access.
437
:return: A lock object, which should be passed to Transport.unlock()
439
from bzrlib.lock import ReadLock
442
path = self._abspath(relpath)
443
return ReadLock(path)
444
except (IOError, OSError), e:
445
self._translate_error(e, path)
447
def lock_write(self, relpath):
448
"""Lock the given file for exclusive (write) access.
449
WARNING: many transports do not support this, so trying avoid using it
451
:return: A lock object, which should be passed to Transport.unlock()
453
from bzrlib.lock import WriteLock
454
return WriteLock(self._abspath(relpath))
456
def rmdir(self, relpath):
457
"""See Transport.rmdir."""
460
path = self._abspath(relpath)
462
except (IOError, OSError),e:
463
self._translate_error(e, path)
465
def _can_roundtrip_unix_modebits(self):
466
if sys.platform == 'win32':
473
class LocalRelpathServer(Server):
474
"""A pretend server for local transports, using relpaths."""
477
"""See Transport.Server.get_url."""
481
class LocalAbspathServer(Server):
482
"""A pretend server for local transports, using absolute paths."""
485
"""See Transport.Server.get_url."""
486
return os.path.abspath("")
489
class LocalURLServer(Server):
490
"""A pretend server for local transports, using file:// urls."""
493
"""See Transport.Server.get_url."""
494
return urlutils.local_path_to_url('')
497
def get_test_permutations():
498
"""Return the permutations to be used in testing."""
499
return [(LocalTransport, LocalRelpathServer),
500
(LocalTransport, LocalAbspathServer),
501
(LocalTransport, LocalURLServer),