1
# Copyright (C) 2005, 2006 Canonical Ltd
1
# Copyright (C) 2005 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."""
26
from stat import ST_MODE, S_ISDIR, ST_SIZE, S_IMODE
24
from stat import ST_MODE, S_ISDIR, ST_SIZE
34
from bzrlib.osutils import (abspath, realpath, normpath, pathjoin, rename,
35
check_legal_path, rmtree)
36
from bzrlib.symbol_versioning import warn
37
28
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
29
from bzrlib.transport import Transport, register_transport, \
30
TransportError, NoSuchFile, FileExists
31
from bzrlib.osutils import abspath
33
class LocalTransportError(TransportError):
45
37
class LocalTransport(Transport):
75
60
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
62
def abspath(self, relpath):
89
"""Return the full url to the given relative URL."""
90
# TODO: url escape the result. RBC 20060523.
63
"""Return the full url to the given relative URL.
64
This can be supplied with a string or a list
91
66
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)
67
return os.path.join(self.base, urllib.unquote(relpath))
112
69
def relpath(self, abspath):
113
70
"""Return the local path portion from a given absolute path.
72
from bzrlib.osutils import relpath
115
73
if abspath is None:
118
return urlutils.file_relpath(
119
urlutils.strip_trailing_slash(self.base),
120
urlutils.strip_trailing_slash(abspath))
75
return relpath(self.base, abspath)
122
77
def has(self, relpath):
123
return os.access(self._abspath(relpath), os.F_OK)
78
return os.access(self.abspath(relpath), os.F_OK)
125
80
def get(self, relpath):
126
81
"""Get the file at the given relative path.
128
83
:param relpath: The relative path to the file
131
path = self._abspath(relpath)
86
path = self.abspath(relpath)
132
87
return open(path, 'rb')
133
except (IOError, OSError),e:
134
self._translate_error(e, path)
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)
136
def put_file(self, relpath, f, mode=None):
137
"""Copy the file-like object into the location.
93
def put(self, relpath, f):
94
"""Copy the file-like or string object into the location.
139
96
: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
97
:param f: File-like or string object.
99
from bzrlib.atomicfile import AtomicFile
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)
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)
153
109
self._pump(f, fp)
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
114
def iter_files_recursive(self):
260
115
"""Iter the relative paths of files in the transports sub-tree."""
261
116
queue = list(self.list_dir(u'.'))
263
relpath = queue.pop(0)
118
relpath = urllib.quote(queue.pop(0))
264
119
st = self.stat(relpath)
265
120
if S_ISDIR(st[ST_MODE]):
266
121
for i, basename in enumerate(self.list_dir(relpath)):
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):
126
def mkdir(self, relpath):
288
127
"""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)
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')
342
144
def copy(self, rel_from, rel_to):
343
145
"""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)
147
path_from = self.abspath(rel_from)
148
path_to = self.abspath(rel_to)
347
150
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)
152
raise LocalTransportError(orig_error=e)
362
154
def move(self, rel_from, rel_to):
363
155
"""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)
156
path_from = self.abspath(rel_from)
157
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)
160
os.rename(path_from, path_to)
162
raise LocalTransportError(orig_error=e)
374
164
def delete(self, relpath):
375
165
"""Delete the item at relpath"""
378
path = self._abspath(relpath)
380
except (IOError, OSError),e:
381
self._translate_error(e, path)
167
os.remove(self.abspath(relpath))
169
raise LocalTransportError(orig_error=e)
383
def copy_to(self, relpaths, other, mode=None, pb=None):
171
def copy_to(self, relpaths, other, pb=None):
384
172
"""Copy a set of entries from self into another Transport.
386
174
:param relpaths: A list/generator of entries to be copied.
389
177
# Both from & to are on the local filesystem
390
178
# Unfortunately, I can't think of anything faster than just
391
179
# copying them across, one by one :(
392
182
total = self._get_total(relpaths)
394
184
for path in relpaths:
395
185
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)
187
shutil.copy(self.abspath(path), other.abspath(path))
189
if e.errno in (errno.ENOENT, errno.ENOTDIR):
190
raise NoSuchFile('File or directory %r does not exist' % path, orig_error=e)
191
raise LocalTransportError(orig_error=e)
407
return super(LocalTransport, self).copy_to(relpaths, other, mode=mode, pb=pb)
195
return super(LocalTransport, self).copy_to(relpaths, other, pb=pb)
409
197
def listable(self):
410
198
"""See Transport.listable."""
415
203
WARNING: many transports do not support this, so trying avoid using
416
204
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]
207
return os.listdir(self.abspath(relpath))
209
raise LocalTransportError(orig_error=e)
425
211
def stat(self, relpath):
426
212
"""Return the stat information for a file.
430
path = self._abspath(relpath)
432
except (IOError, OSError),e:
433
self._translate_error(e, path)
215
return os.stat(self.abspath(relpath))
217
raise LocalTransportError(orig_error=e)
435
219
def lock_read(self, relpath):
436
220
"""Lock the given file for shared (read) access.
437
221
:return: A lock object, which should be passed to Transport.unlock()
439
223
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)
224
return ReadLock(self.abspath(relpath))
447
226
def lock_write(self, relpath):
448
227
"""Lock the given file for exclusive (write) access.
451
230
:return: A lock object, which should be passed to Transport.unlock()
453
232
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),
233
return WriteLock(self.abspath(relpath))
236
class ScratchTransport(LocalTransport):
237
"""A transport that works in a temporary dir and cleans up after itself.
239
The dir only exists for the lifetime of the Python object.
240
Obviously you should not put anything precious in it.
243
def __init__(self, base=None):
245
base = tempfile.mkdtemp()
246
super(ScratchTransport, self).__init__(base)
249
shutil.rmtree(self.base, ignore_errors=True)
250
mutter("%r destroyed" % self)