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
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
27
37
from bzrlib.trace import mutter
28
from bzrlib.transport import Transport
29
from bzrlib.osutils import abspath
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
32
45
class LocalTransport(Transport):
35
48
def __init__(self, base):
36
49
"""Set the base path where files will be stored."""
37
if base.startswith('file://'):
39
# realpath is incompatible with symlinks. When we traverse
40
# up we might be able to normpath stuff. RBC 20051003
41
super(LocalTransport, self).__init__(
42
os.path.normpath(abspath(base)))
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)
44
64
def should_cache(self):
55
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)
57
88
def abspath(self, relpath):
58
"""Return the full url to the given relative URL.
59
This can be supplied with a string or a list
89
"""Return the full url to the given relative URL."""
90
# TODO: url escape the result. RBC 20060523.
61
91
assert isinstance(relpath, basestring), (type(relpath), relpath)
62
return os.path.join(self.base, urllib.unquote(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)
64
112
def relpath(self, abspath):
65
113
"""Return the local path portion from a given absolute path.
67
from bzrlib.osutils import relpath
68
115
if abspath is None:
70
return relpath(self.base, abspath)
118
return urlutils.file_relpath(
119
urlutils.strip_trailing_slash(self.base),
120
urlutils.strip_trailing_slash(abspath))
72
122
def has(self, relpath):
73
return os.access(self.abspath(relpath), os.F_OK)
123
return os.access(self._abspath(relpath), os.F_OK)
75
125
def get(self, relpath):
76
126
"""Get the file at the given relative path.
78
128
:param relpath: The relative path to the file
81
path = self.abspath(relpath)
131
path = self._abspath(relpath)
82
132
return open(path, 'rb')
83
133
except (IOError, OSError),e:
84
134
self._translate_error(e, path)
86
def put(self, relpath, f):
87
"""Copy the file-like or string object into the location.
136
def put_file(self, relpath, f, mode=None):
137
"""Copy the file-like object into the location.
89
139
:param relpath: Location to put the contents, relative to base.
90
:param f: File-like or string object.
140
:param f: File-like object.
141
:param mode: The mode for the newly created file,
142
None means just use the default
92
from bzrlib.atomicfile import AtomicFile
96
path = self.abspath(relpath)
97
fp = AtomicFile(path, 'wb')
147
path = self._abspath(relpath)
148
check_legal_path(path)
149
fp = atomicfile.AtomicFile(path, 'wb', new_mode=mode)
98
150
except (IOError, OSError),e:
99
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,
106
259
def iter_files_recursive(self):
107
260
"""Iter the relative paths of files in the transports sub-tree."""
108
261
queue = list(self.list_dir(u'.'))
110
relpath = urllib.quote(queue.pop(0))
263
relpath = queue.pop(0)
111
264
st = self.stat(relpath)
112
265
if S_ISDIR(st[ST_MODE]):
113
266
for i, basename in enumerate(self.list_dir(relpath)):
118
def mkdir(self, 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):
119
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
122
path = self.abspath(relpath)
300
return file_abspath, os.open(file_abspath, _append_flags, local_mode)
124
301
except (IOError, OSError),e:
125
self._translate_error(e, path)
127
def append(self, relpath, f):
128
"""Append the text in the file-like object into the final
131
fp = open(self.abspath(relpath), 'ab')
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)
134
342
def copy(self, rel_from, rel_to):
135
343
"""Copy the item at rel_from to the location at rel_to"""
137
path_from = self.abspath(rel_from)
138
path_to = self.abspath(rel_to)
344
path_from = self._abspath(rel_from)
345
path_to = self._abspath(rel_to)
140
347
shutil.copy(path_from, path_to)
141
348
except (IOError, OSError),e:
142
349
# TODO: What about path_to?
143
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)
145
362
def move(self, rel_from, rel_to):
146
363
"""Move 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)
364
path_from = self._abspath(rel_from)
365
path_to = self._abspath(rel_to)
151
os.rename(path_from, path_to)
368
# this version will delete the destination if necessary
369
rename(path_from, path_to)
152
370
except (IOError, OSError),e:
153
371
# TODO: What about path_to?
154
372
self._translate_error(e, path_from)
172
389
# Both from & to are on the local filesystem
173
390
# Unfortunately, I can't think of anything faster than just
174
391
# copying them across, one by one :(
177
392
total = self._get_total(relpaths)
179
394
for path in relpaths:
180
395
self._update_pb(pb, 'copy-to', count, total)
182
shutil.copy(self.abspath(path), other.abspath(path))
397
mypath = self._abspath(path)
398
otherpath = other._abspath(path)
399
shutil.copy(mypath, otherpath)
401
os.chmod(otherpath, mode)
183
402
except (IOError, OSError),e:
184
403
self._translate_error(e, path)
188
return super(LocalTransport, self).copy_to(relpaths, other, pb=pb)
407
return super(LocalTransport, self).copy_to(relpaths, other, mode=mode, pb=pb)
190
409
def listable(self):
191
410
"""See Transport.listable."""
227
451
:return: A lock object, which should be passed to Transport.unlock()
229
453
from bzrlib.lock import WriteLock
230
return WriteLock(self.abspath(relpath))
233
class ScratchTransport(LocalTransport):
234
"""A transport that works in a temporary dir and cleans up after itself.
236
The dir only exists for the lifetime of the Python object.
237
Obviously you should not put anything precious in it.
240
def __init__(self, base=None):
242
base = tempfile.mkdtemp()
243
super(ScratchTransport, self).__init__(base)
246
shutil.rmtree(self.base, ignore_errors=True)
247
mutter("%r destroyed" % self)
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),