~bzr-pqm/bzr/bzr.dev

1553.5.13 by Martin Pool
New Transport.rename that mustn't overwrite
1
# Copyright (C) 2005, 2006 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
1185.11.19 by John Arbash Meinel
Testing put and append, also testing agaist file-like objects as well as strings.
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
1185.11.19 by John Arbash Meinel
Testing put and append, also testing agaist file-like objects as well as strings.
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
1185.11.19 by John Arbash Meinel
Testing put and append, also testing agaist file-like objects as well as strings.
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
1185.16.72 by Martin Pool
[merge] from robert and fix up tests
16
17
"""Transport for the local filesystem.
18
1755.1.3 by Robert Collins
Fix regression in LocalTransport to allow merging.
19
This is a fairly thin wrapper on regular file IO.
20
"""
907.1.1 by John Arbash Meinel
Reworking the Branch and Store code to support an abstracted filesystem layer.
21
1996.3.17 by John Arbash Meinel
lazy_import plugin and transport/local
22
import os
23
from stat import ST_MODE, S_ISDIR, ST_SIZE, S_IMODE
24
import sys
25
26
from bzrlib.lazy_import import lazy_import
27
lazy_import(globals(), """
1946.1.8 by John Arbash Meinel
Update non_atomic_put to have a create_parent_dir flag
28
import errno
1442.1.42 by Robert Collins
rebuild ScratchBranch on top of ScratchTransport
29
import shutil
30
1908.4.2 by John Arbash Meinel
Delay evaluating PathError.extra, and use fstat() instead of seek + tell, and we can check if we need to chmod(). Saves about 3/90 seconds of commit time
31
from bzrlib import (
1955.3.6 by John Arbash Meinel
Lots of deprecation warnings, but no errors
32
    atomicfile,
1908.4.2 by John Arbash Meinel
Delay evaluating PathError.extra, and use fstat() instead of seek + tell, and we can check if we need to chmod(). Saves about 3/90 seconds of commit time
33
    osutils,
1755.3.7 by John Arbash Meinel
Clean up and write tests for permissions. Now we use fstat which should be cheap, and lets us check the permissions and the file size
34
    urlutils,
1996.3.17 by John Arbash Meinel
lazy_import plugin and transport/local
35
    symbol_versioning,
1908.4.2 by John Arbash Meinel
Delay evaluating PathError.extra, and use fstat() instead of seek + tell, and we can check if we need to chmod(). Saves about 3/90 seconds of commit time
36
    )
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
37
from bzrlib.trace import mutter
2052.6.2 by Robert Collins
Merge bzr.dev.
38
from bzrlib.transport import LateReadError
1996.3.17 by John Arbash Meinel
lazy_import plugin and transport/local
39
""")
40
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
41
from bzrlib.transport import Transport, Server
1755.3.7 by John Arbash Meinel
Clean up and write tests for permissions. Now we use fstat which should be cheap, and lets us check the permissions and the file size
42
43
44
_append_flags = os.O_CREAT | os.O_APPEND | os.O_WRONLY | osutils.O_BINARY
1955.3.27 by John Arbash Meinel
rename non_atomic_put_* to put_*non_atomic, and re-order the functions
45
_put_non_atomic_flags = os.O_CREAT | os.O_TRUNC | os.O_WRONLY | osutils.O_BINARY
907.1.1 by John Arbash Meinel
Reworking the Branch and Store code to support an abstracted filesystem layer.
46
1442.1.42 by Robert Collins
rebuild ScratchBranch on top of ScratchTransport
47
907.1.1 by John Arbash Meinel
Reworking the Branch and Store code to support an abstracted filesystem layer.
48
class LocalTransport(Transport):
49
    """This is the transport agent for local filesystem access."""
50
51
    def __init__(self, base):
52
        """Set the base path where files will be stored."""
1685.1.9 by John Arbash Meinel
Updated LocalTransport so that it's base is now a URL rather than a local path. This helps consistency with all other functions. To do so, I added local_abspath() which returns the local path, and local_path_to/from_url
53
        if not base.startswith('file://'):
1996.3.17 by John Arbash Meinel
lazy_import plugin and transport/local
54
            symbol_versioning.warn(
55
                "Instantiating LocalTransport with a filesystem path"
1685.1.9 by John Arbash Meinel
Updated LocalTransport so that it's base is now a URL rather than a local path. This helps consistency with all other functions. To do so, I added local_abspath() which returns the local path, and local_path_to/from_url
56
                " is deprecated as of bzr 0.8."
57
                " Please use bzrlib.transport.get_transport()"
58
                " or pass in a file:// url.",
59
                 DeprecationWarning,
60
                 stacklevel=2
61
                 )
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
62
            base = urlutils.local_path_to_url(base)
1530.1.3 by Robert Collins
transport implementations now tested consistently.
63
        if base[-1] != '/':
64
            base = base + '/'
65
        super(LocalTransport, self).__init__(base)
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
66
        self._local_base = urlutils.local_path_from_url(base)
907.1.1 by John Arbash Meinel
Reworking the Branch and Store code to support an abstracted filesystem layer.
67
907.1.32 by John Arbash Meinel
Renaming is_remote to should_cache as it is more appropriate.
68
    def should_cache(self):
907.1.22 by John Arbash Meinel
Fixed some encoding issues, added is_remote function for Transport objects.
69
        return False
70
907.1.2 by John Arbash Meinel
Working on making Branch() do all of it's work over a Transport.
71
    def clone(self, offset=None):
72
        """Return a new LocalTransport with root at self.base + offset
73
        Because the local filesystem does not require a connection, 
74
        we can just return a new object.
75
        """
76
        if offset is None:
77
            return LocalTransport(self.base)
78
        else:
2245.6.1 by Alexander Belchenko
win32 UNC path: recursive cloning UNC path to root stops on //HOST, not on //
79
            abspath = self.abspath(offset)
80
            if abspath == 'file://':
81
                # fix upwalk for UNC path
82
                # when clone from //HOST/path updir recursively
83
                # we should stop at least at //HOST part
84
                abspath = self.base
85
            return LocalTransport(abspath)
907.1.2 by John Arbash Meinel
Working on making Branch() do all of it's work over a Transport.
86
1725.2.1 by Robert Collins
Make LocalTransport faster by not normpathing every internal path translation.
87
    def _abspath(self, relative_reference):
88
        """Return a path for use in os calls.
89
90
        Several assumptions are made:
91
         - relative_reference does not contain '..'
92
         - relative_reference is url escaped.
93
        """
1755.1.3 by Robert Collins
Fix regression in LocalTransport to allow merging.
94
        if relative_reference in ('.', ''):
95
            return self._local_base
1755.1.2 by Robert Collins
(robertc, ab)Merge some commit and fetch tuning steps.
96
        return self._local_base + urlutils.unescape(relative_reference)
1725.2.1 by Robert Collins
Make LocalTransport faster by not normpathing every internal path translation.
97
907.1.8 by John Arbash Meinel
Changed the format for abspath. Updated branch to use a hidden _transport
98
    def abspath(self, relpath):
1636.1.1 by Robert Collins
Fix calling relpath() and abspath() on transports at their root.
99
        """Return the full url to the given relative URL."""
1725.2.1 by Robert Collins
Make LocalTransport faster by not normpathing every internal path translation.
100
        # TODO: url escape the result. RBC 20060523.
1185.12.70 by Aaron Bentley
Removed b
101
        assert isinstance(relpath, basestring), (type(relpath), relpath)
1685.1.12 by John Arbash Meinel
Some more work to get LocalTransport to only support URLs
102
        # jam 20060426 Using normpath on the real path, because that ensures
103
        #       proper handling of stuff like
1996.3.17 by John Arbash Meinel
lazy_import plugin and transport/local
104
        path = osutils.normpath(osutils.pathjoin(
105
                    self._local_base, urlutils.unescape(relpath)))
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
106
        return urlutils.local_path_to_url(path)
1685.1.9 by John Arbash Meinel
Updated LocalTransport so that it's base is now a URL rather than a local path. This helps consistency with all other functions. To do so, I added local_abspath() which returns the local path, and local_path_to/from_url
107
108
    def local_abspath(self, relpath):
109
        """Transform the given relative path URL into the actual path on disk
110
111
        This function only exists for the LocalTransport, since it is
112
        the only one that has direct local access.
113
        This is mostly for stuff like WorkingTree which needs to know
114
        the local working directory.
1725.2.9 by Robert Collins
Merge current head.
115
        
116
        This function is quite expensive: it calls realpath which resolves
117
        symlinks.
1685.1.9 by John Arbash Meinel
Updated LocalTransport so that it's base is now a URL rather than a local path. This helps consistency with all other functions. To do so, I added local_abspath() which returns the local path, and local_path_to/from_url
118
        """
119
        absurl = self.abspath(relpath)
120
        # mutter(u'relpath %s => base: %s, absurl %s', relpath, self.base, absurl)
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
121
        return urlutils.local_path_from_url(absurl)
907.1.1 by John Arbash Meinel
Reworking the Branch and Store code to support an abstracted filesystem layer.
122
907.1.24 by John Arbash Meinel
Remote functionality work.
123
    def relpath(self, abspath):
124
        """Return the local path portion from a given absolute path.
125
        """
1442.1.64 by Robert Collins
Branch.open_containing now returns a tuple (Branch, relative-path).
126
        if abspath is None:
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
127
            abspath = u'.'
1551.2.53 by abentley
Strip trailing slashes in a platform-sensible way
128
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
129
        return urlutils.file_relpath(
130
            urlutils.strip_trailing_slash(self.base), 
131
            urlutils.strip_trailing_slash(abspath))
907.1.24 by John Arbash Meinel
Remote functionality work.
132
907.1.1 by John Arbash Meinel
Reworking the Branch and Store code to support an abstracted filesystem layer.
133
    def has(self, relpath):
1725.2.1 by Robert Collins
Make LocalTransport faster by not normpathing every internal path translation.
134
        return os.access(self._abspath(relpath), os.F_OK)
907.1.1 by John Arbash Meinel
Reworking the Branch and Store code to support an abstracted filesystem layer.
135
2164.2.15 by Vincent Ladeuil
Http redirections are not followed by default. Do not use hints
136
    def get(self, relpath):
907.1.1 by John Arbash Meinel
Reworking the Branch and Store code to support an abstracted filesystem layer.
137
        """Get the file at the given relative path.
907.1.20 by John Arbash Meinel
Removed Transport.open(), making get + put encode/decode to utf-8
138
139
        :param relpath: The relative path to the file
140
        """
907.1.48 by John Arbash Meinel
Updated LocalTransport by passing it through the transport_test suite, and got it to pass.
141
        try:
1908.4.11 by John Arbash Meinel
reverting changes to errors.py and local transport.
142
            path = self._abspath(relpath)
907.1.50 by John Arbash Meinel
Removed encode/decode from Transport.put/get, added more exceptions that can be thrown.
143
            return open(path, 'rb')
1185.31.44 by John Arbash Meinel
Cleaned up Exceptions for all transports.
144
        except (IOError, OSError),e:
2052.6.1 by Robert Collins
``Transport.get`` has had its interface made more clear for ease of use.
145
            if e.errno == errno.EISDIR:
146
                return LateReadError(relpath)
1185.31.44 by John Arbash Meinel
Cleaned up Exceptions for all transports.
147
            self._translate_error(e, path)
907.1.20 by John Arbash Meinel
Removed Transport.open(), making get + put encode/decode to utf-8
148
1955.3.6 by John Arbash Meinel
Lots of deprecation warnings, but no errors
149
    def put_file(self, relpath, f, mode=None):
1946.1.4 by John Arbash Meinel
Basic implementation for local transport
150
        """Copy the file-like object into the location.
907.1.20 by John Arbash Meinel
Removed Transport.open(), making get + put encode/decode to utf-8
151
152
        :param relpath: Location to put the contents, relative to base.
1946.1.4 by John Arbash Meinel
Basic implementation for local transport
153
        :param f:       File-like object.
154
        :param mode: The mode for the newly created file, 
155
                     None means just use the default
907.1.20 by John Arbash Meinel
Removed Transport.open(), making get + put encode/decode to utf-8
156
        """
907.1.1 by John Arbash Meinel
Reworking the Branch and Store code to support an abstracted filesystem layer.
157
1185.31.44 by John Arbash Meinel
Cleaned up Exceptions for all transports.
158
        path = relpath
907.1.48 by John Arbash Meinel
Updated LocalTransport by passing it through the transport_test suite, and got it to pass.
159
        try:
1725.2.1 by Robert Collins
Make LocalTransport faster by not normpathing every internal path translation.
160
            path = self._abspath(relpath)
1996.3.17 by John Arbash Meinel
lazy_import plugin and transport/local
161
            osutils.check_legal_path(path)
1955.3.6 by John Arbash Meinel
Lots of deprecation warnings, but no errors
162
            fp = atomicfile.AtomicFile(path, 'wb', new_mode=mode)
1185.31.44 by John Arbash Meinel
Cleaned up Exceptions for all transports.
163
        except (IOError, OSError),e:
164
            self._translate_error(e, path)
907.1.2 by John Arbash Meinel
Working on making Branch() do all of it's work over a Transport.
165
        try:
166
            self._pump(f, fp)
167
            fp.commit()
168
        finally:
169
            fp.close()
170
1955.3.6 by John Arbash Meinel
Lots of deprecation warnings, but no errors
171
    def put_bytes(self, relpath, bytes, mode=None):
172
        """Copy the string into the location.
173
174
        :param relpath: Location to put the contents, relative to base.
175
        :param bytes:   String
176
        """
177
178
        path = relpath
179
        try:
180
            path = self._abspath(relpath)
1996.3.17 by John Arbash Meinel
lazy_import plugin and transport/local
181
            osutils.check_legal_path(path)
1955.3.6 by John Arbash Meinel
Lots of deprecation warnings, but no errors
182
            fp = atomicfile.AtomicFile(path, 'wb', new_mode=mode)
183
        except (IOError, OSError),e:
184
            self._translate_error(e, path)
185
        try:
186
            fp.write(bytes)
187
            fp.commit()
188
        finally:
189
            fp.close()
190
1955.3.27 by John Arbash Meinel
rename non_atomic_put_* to put_*non_atomic, and re-order the functions
191
    def _put_non_atomic_helper(self, relpath, writer,
1955.3.21 by John Arbash Meinel
Update the LocalTransport and SftpTransport to implement non_atomic_*
192
                               mode=None,
1946.2.12 by John Arbash Meinel
Add ability to pass a directory mode to non_atomic_put
193
                               create_parent_dir=False,
194
                               dir_mode=None):
1955.3.27 by John Arbash Meinel
rename non_atomic_put_* to put_*non_atomic, and re-order the functions
195
        """Common functionality information for the put_*_non_atomic.
1955.3.21 by John Arbash Meinel
Update the LocalTransport and SftpTransport to implement non_atomic_*
196
197
        This tracks all the create_parent_dir stuff.
198
199
        :param relpath: the path we are putting to.
200
        :param writer: A function that takes an os level file descriptor
201
            and writes whatever data it needs to write there.
202
        :param mode: The final file mode.
203
        :param create_parent_dir: Should we be creating the parent directory
204
            if it doesn't exist?
1946.1.4 by John Arbash Meinel
Basic implementation for local transport
205
        """
206
        abspath = self._abspath(relpath)
207
        if mode is None:
208
            # os.open() will automatically use the umask
209
            local_mode = 0666
210
        else:
211
            local_mode = mode
212
        try:
1955.3.27 by John Arbash Meinel
rename non_atomic_put_* to put_*non_atomic, and re-order the functions
213
            fd = os.open(abspath, _put_non_atomic_flags, local_mode)
1946.1.4 by John Arbash Meinel
Basic implementation for local transport
214
        except (IOError, OSError),e:
1946.1.8 by John Arbash Meinel
Update non_atomic_put to have a create_parent_dir flag
215
            # We couldn't create the file, maybe we need to create
216
            # the parent directory, and try again
217
            if (not create_parent_dir
218
                or e.errno not in (errno.ENOENT,errno.ENOTDIR)):
219
                self._translate_error(e, relpath)
220
            parent_dir = os.path.dirname(abspath)
221
            if not parent_dir:
222
                self._translate_error(e, relpath)
1946.2.12 by John Arbash Meinel
Add ability to pass a directory mode to non_atomic_put
223
            self._mkdir(parent_dir, mode=dir_mode)
1946.1.8 by John Arbash Meinel
Update non_atomic_put to have a create_parent_dir flag
224
            # We created the parent directory, lets try to open the
225
            # file again
226
            try:
1955.3.27 by John Arbash Meinel
rename non_atomic_put_* to put_*non_atomic, and re-order the functions
227
                fd = os.open(abspath, _put_non_atomic_flags, local_mode)
1946.1.8 by John Arbash Meinel
Update non_atomic_put to have a create_parent_dir flag
228
            except (IOError, OSError), e:
229
                self._translate_error(e, relpath)
1946.1.4 by John Arbash Meinel
Basic implementation for local transport
230
        try:
231
            st = os.fstat(fd)
232
            if mode is not None and mode != S_IMODE(st.st_mode):
233
                # Because of umask, we may still need to chmod the file.
234
                # But in the general case, we won't have to
235
                os.chmod(abspath, mode)
1955.3.21 by John Arbash Meinel
Update the LocalTransport and SftpTransport to implement non_atomic_*
236
            writer(fd)
1946.1.4 by John Arbash Meinel
Basic implementation for local transport
237
        finally:
238
            os.close(fd)
239
1955.3.27 by John Arbash Meinel
rename non_atomic_put_* to put_*non_atomic, and re-order the functions
240
    def put_file_non_atomic(self, relpath, f, mode=None,
1946.2.12 by John Arbash Meinel
Add ability to pass a directory mode to non_atomic_put
241
                            create_parent_dir=False,
242
                            dir_mode=None):
1955.3.21 by John Arbash Meinel
Update the LocalTransport and SftpTransport to implement non_atomic_*
243
        """Copy the file-like object into the target location.
244
245
        This function is not strictly safe to use. It is only meant to
246
        be used when you already know that the target does not exist.
247
        It is not safe, because it will open and truncate the remote
248
        file. So there may be a time when the file has invalid contents.
249
250
        :param relpath: The remote location to put the contents.
251
        :param f:       File-like object.
252
        :param mode:    Possible access permissions for new file.
253
                        None means do not set remote permissions.
254
        :param create_parent_dir: If we cannot create the target file because
255
                        the parent directory does not exist, go ahead and
256
                        create it, and then try again.
257
        """
258
        def writer(fd):
259
            self._pump_to_fd(f, fd)
1955.3.27 by John Arbash Meinel
rename non_atomic_put_* to put_*non_atomic, and re-order the functions
260
        self._put_non_atomic_helper(relpath, writer, mode=mode,
1946.2.12 by John Arbash Meinel
Add ability to pass a directory mode to non_atomic_put
261
                                    create_parent_dir=create_parent_dir,
262
                                    dir_mode=dir_mode)
1955.3.21 by John Arbash Meinel
Update the LocalTransport and SftpTransport to implement non_atomic_*
263
1955.3.27 by John Arbash Meinel
rename non_atomic_put_* to put_*non_atomic, and re-order the functions
264
    def put_bytes_non_atomic(self, relpath, bytes, mode=None,
1946.2.12 by John Arbash Meinel
Add ability to pass a directory mode to non_atomic_put
265
                             create_parent_dir=False, dir_mode=None):
1955.3.21 by John Arbash Meinel
Update the LocalTransport and SftpTransport to implement non_atomic_*
266
        def writer(fd):
267
            os.write(fd, bytes)
1955.3.27 by John Arbash Meinel
rename non_atomic_put_* to put_*non_atomic, and re-order the functions
268
        self._put_non_atomic_helper(relpath, writer, mode=mode,
1946.2.12 by John Arbash Meinel
Add ability to pass a directory mode to non_atomic_put
269
                                    create_parent_dir=create_parent_dir,
270
                                    dir_mode=dir_mode)
1955.3.21 by John Arbash Meinel
Update the LocalTransport and SftpTransport to implement non_atomic_*
271
1442.1.44 by Robert Collins
Many transport related tweaks:
272
    def iter_files_recursive(self):
273
        """Iter the relative paths of files in the transports sub-tree."""
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
274
        queue = list(self.list_dir(u'.'))
1442.1.44 by Robert Collins
Many transport related tweaks:
275
        while queue:
1608.1.1 by Martin Pool
[patch] LocalTransport.list_dir should return url-quoted strings (ddaa)
276
            relpath = queue.pop(0)
1442.1.44 by Robert Collins
Many transport related tweaks:
277
            st = self.stat(relpath)
278
            if S_ISDIR(st[ST_MODE]):
279
                for i, basename in enumerate(self.list_dir(relpath)):
280
                    queue.insert(i, relpath+'/'+basename)
281
            else:
282
                yield relpath
283
1946.2.12 by John Arbash Meinel
Add ability to pass a directory mode to non_atomic_put
284
    def _mkdir(self, abspath, mode=None):
285
        """Create a real directory, filtering through mode"""
286
        if mode is None:
287
            # os.mkdir() will filter through umask
288
            local_mode = 0777
289
        else:
290
            local_mode = mode
907.1.48 by John Arbash Meinel
Updated LocalTransport by passing it through the transport_test suite, and got it to pass.
291
        try:
1946.2.12 by John Arbash Meinel
Add ability to pass a directory mode to non_atomic_put
292
            os.mkdir(abspath, local_mode)
1185.58.2 by John Arbash Meinel
Added mode to the appropriate transport functions, and tests to make sure they work.
293
            if mode is not None:
1755.3.7 by John Arbash Meinel
Clean up and write tests for permissions. Now we use fstat which should be cheap, and lets us check the permissions and the file size
294
                # It is probably faster to just do the chmod, rather than
295
                # doing a stat, and then trying to compare
1946.2.12 by John Arbash Meinel
Add ability to pass a directory mode to non_atomic_put
296
                os.chmod(abspath, mode)
1185.31.44 by John Arbash Meinel
Cleaned up Exceptions for all transports.
297
        except (IOError, OSError),e:
1946.2.12 by John Arbash Meinel
Add ability to pass a directory mode to non_atomic_put
298
            self._translate_error(e, abspath)
299
300
    def mkdir(self, relpath, mode=None):
301
        """Create a directory at the given path."""
302
        self._mkdir(self._abspath(relpath), mode=mode)
907.1.2 by John Arbash Meinel
Working on making Branch() do all of it's work over a Transport.
303
1955.3.15 by John Arbash Meinel
Deprecate 'Transport.append' in favor of Transport.append_file or Transport.append_bytes
304
    def _get_append_file(self, relpath, mode=None):
305
        """Call os.open() for the given relpath"""
1955.3.17 by John Arbash Meinel
Fix some bugs in Transport.append(mode!=None)
306
        file_abspath = self._abspath(relpath)
1755.3.3 by Robert Collins
allow None == 0666 for mode.
307
        if mode is None:
1755.3.9 by John Arbash Meinel
Make AtomicFile not do anything if not supplied a mode, clean up LocalTransport now that we do the right thing for None
308
            # os.open() will automatically use the umask
309
            local_mode = 0666
1755.3.7 by John Arbash Meinel
Clean up and write tests for permissions. Now we use fstat which should be cheap, and lets us check the permissions and the file size
310
        else:
311
            local_mode = mode
1530.1.4 by Robert Collins
integrate Memory tests into transport interface tests.
312
        try:
1955.3.17 by John Arbash Meinel
Fix some bugs in Transport.append(mode!=None)
313
            return file_abspath, os.open(file_abspath, _append_flags, local_mode)
1530.1.4 by Robert Collins
integrate Memory tests into transport interface tests.
314
        except (IOError, OSError),e:
315
            self._translate_error(e, relpath)
1955.3.15 by John Arbash Meinel
Deprecate 'Transport.append' in favor of Transport.append_file or Transport.append_bytes
316
1955.3.17 by John Arbash Meinel
Fix some bugs in Transport.append(mode!=None)
317
    def _check_mode_and_size(self, file_abspath, fd, mode=None):
1955.3.15 by John Arbash Meinel
Deprecate 'Transport.append' in favor of Transport.append_file or Transport.append_bytes
318
        """Check the mode of the file, and return the current size"""
319
        st = os.fstat(fd)
320
        if mode is not None and mode != S_IMODE(st.st_mode):
321
            # Because of umask, we may still need to chmod the file.
322
            # But in the general case, we won't have to
1955.3.17 by John Arbash Meinel
Fix some bugs in Transport.append(mode!=None)
323
            os.chmod(file_abspath, mode)
1955.3.15 by John Arbash Meinel
Deprecate 'Transport.append' in favor of Transport.append_file or Transport.append_bytes
324
        return st.st_size
325
326
    def append_file(self, relpath, f, mode=None):
327
        """Append the text in the file-like object into the final location."""
1955.3.17 by John Arbash Meinel
Fix some bugs in Transport.append(mode!=None)
328
        file_abspath, fd = self._get_append_file(relpath, mode=mode)
1755.3.1 by Robert Collins
Tune the time to build our kernel_like tree : make LocalTransport.put faster, AtomicFile faster, LocalTransport.append faster.
329
        try:
1955.3.17 by John Arbash Meinel
Fix some bugs in Transport.append(mode!=None)
330
            result = self._check_mode_and_size(file_abspath, fd, mode=mode)
1755.3.1 by Robert Collins
Tune the time to build our kernel_like tree : make LocalTransport.put faster, AtomicFile faster, LocalTransport.append faster.
331
            self._pump_to_fd(f, fd)
1711.7.25 by John Arbash Meinel
try/finally to close files, _KnitData was keeping a handle to a file it never used again, and using transport.rename() when it wanted transport.move()
332
        finally:
1755.3.1 by Robert Collins
Tune the time to build our kernel_like tree : make LocalTransport.put faster, AtomicFile faster, LocalTransport.append faster.
333
            os.close(fd)
1563.2.3 by Robert Collins
Change the return signature of transport.append and append_multi to return the length of the pre-append content.
334
        return result
907.1.1 by John Arbash Meinel
Reworking the Branch and Store code to support an abstracted filesystem layer.
335
1955.3.15 by John Arbash Meinel
Deprecate 'Transport.append' in favor of Transport.append_file or Transport.append_bytes
336
    def append_bytes(self, relpath, bytes, mode=None):
337
        """Append the text in the string into the final location."""
1955.3.17 by John Arbash Meinel
Fix some bugs in Transport.append(mode!=None)
338
        file_abspath, fd = self._get_append_file(relpath, mode=mode)
1955.3.15 by John Arbash Meinel
Deprecate 'Transport.append' in favor of Transport.append_file or Transport.append_bytes
339
        try:
1955.3.17 by John Arbash Meinel
Fix some bugs in Transport.append(mode!=None)
340
            result = self._check_mode_and_size(file_abspath, fd, mode=mode)
1955.3.15 by John Arbash Meinel
Deprecate 'Transport.append' in favor of Transport.append_file or Transport.append_bytes
341
            os.write(fd, bytes)
342
        finally:
343
            os.close(fd)
344
        return result
345
1755.3.1 by Robert Collins
Tune the time to build our kernel_like tree : make LocalTransport.put faster, AtomicFile faster, LocalTransport.append faster.
346
    def _pump_to_fd(self, fromfile, to_fd):
347
        """Copy contents of one file to another."""
348
        BUFSIZE = 32768
349
        while True:
350
            b = fromfile.read(BUFSIZE)
351
            if not b:
352
                break
353
            os.write(to_fd, b)
354
907.1.1 by John Arbash Meinel
Reworking the Branch and Store code to support an abstracted filesystem layer.
355
    def copy(self, rel_from, rel_to):
356
        """Copy the item at rel_from to the location at rel_to"""
1725.2.1 by Robert Collins
Make LocalTransport faster by not normpathing every internal path translation.
357
        path_from = self._abspath(rel_from)
358
        path_to = self._abspath(rel_to)
907.1.48 by John Arbash Meinel
Updated LocalTransport by passing it through the transport_test suite, and got it to pass.
359
        try:
360
            shutil.copy(path_from, path_to)
1185.31.44 by John Arbash Meinel
Cleaned up Exceptions for all transports.
361
        except (IOError, OSError),e:
362
            # TODO: What about path_to?
363
            self._translate_error(e, path_from)
907.1.1 by John Arbash Meinel
Reworking the Branch and Store code to support an abstracted filesystem layer.
364
1553.5.13 by Martin Pool
New Transport.rename that mustn't overwrite
365
    def rename(self, rel_from, rel_to):
1725.2.1 by Robert Collins
Make LocalTransport faster by not normpathing every internal path translation.
366
        path_from = self._abspath(rel_from)
1553.5.13 by Martin Pool
New Transport.rename that mustn't overwrite
367
        try:
368
            # *don't* call bzrlib.osutils.rename, because we want to 
369
            # detect errors on rename
1725.2.1 by Robert Collins
Make LocalTransport faster by not normpathing every internal path translation.
370
            os.rename(path_from, self._abspath(rel_to))
1553.5.13 by Martin Pool
New Transport.rename that mustn't overwrite
371
        except (IOError, OSError),e:
372
            # TODO: What about path_to?
373
            self._translate_error(e, path_from)
374
907.1.1 by John Arbash Meinel
Reworking the Branch and Store code to support an abstracted filesystem layer.
375
    def move(self, rel_from, rel_to):
376
        """Move the item at rel_from to the location at rel_to"""
1725.2.1 by Robert Collins
Make LocalTransport faster by not normpathing every internal path translation.
377
        path_from = self._abspath(rel_from)
378
        path_to = self._abspath(rel_to)
907.1.1 by John Arbash Meinel
Reworking the Branch and Store code to support an abstracted filesystem layer.
379
907.1.48 by John Arbash Meinel
Updated LocalTransport by passing it through the transport_test suite, and got it to pass.
380
        try:
1553.5.13 by Martin Pool
New Transport.rename that mustn't overwrite
381
            # this version will delete the destination if necessary
1996.3.17 by John Arbash Meinel
lazy_import plugin and transport/local
382
            osutils.rename(path_from, path_to)
1185.31.44 by John Arbash Meinel
Cleaned up Exceptions for all transports.
383
        except (IOError, OSError),e:
384
            # TODO: What about path_to?
385
            self._translate_error(e, path_from)
907.1.1 by John Arbash Meinel
Reworking the Branch and Store code to support an abstracted filesystem layer.
386
387
    def delete(self, relpath):
388
        """Delete the item at relpath"""
1185.31.44 by John Arbash Meinel
Cleaned up Exceptions for all transports.
389
        path = relpath
907.1.48 by John Arbash Meinel
Updated LocalTransport by passing it through the transport_test suite, and got it to pass.
390
        try:
1725.2.1 by Robert Collins
Make LocalTransport faster by not normpathing every internal path translation.
391
            path = self._abspath(relpath)
1185.31.44 by John Arbash Meinel
Cleaned up Exceptions for all transports.
392
            os.remove(path)
393
        except (IOError, OSError),e:
394
            self._translate_error(e, path)
907.1.1 by John Arbash Meinel
Reworking the Branch and Store code to support an abstracted filesystem layer.
395
2586.1.1 by Robert Collins
* New method ``external_url`` on Transport for obtaining the url to
396
    def external_url(self):
397
        """See bzrlib.transport.Transport.external_url."""
398
        # File URL's are externally usable.
399
        return self.base
400
1185.58.2 by John Arbash Meinel
Added mode to the appropriate transport functions, and tests to make sure they work.
401
    def copy_to(self, relpaths, other, mode=None, pb=None):
907.1.28 by John Arbash Meinel
Added pb to function that were missing, implemented a basic double-dispatch copy_to function.
402
        """Copy a set of entries from self into another Transport.
403
404
        :param relpaths: A list/generator of entries to be copied.
405
        """
406
        if isinstance(other, LocalTransport):
407
            # Both from & to are on the local filesystem
408
            # Unfortunately, I can't think of anything faster than just
409
            # copying them across, one by one :(
410
            total = self._get_total(relpaths)
411
            count = 0
412
            for path in relpaths:
413
                self._update_pb(pb, 'copy-to', count, total)
1185.16.158 by John Arbash Meinel
Added a test that copy_to raises NoSuchFile when a directory is missing (not IOError)
414
                try:
1725.2.1 by Robert Collins
Make LocalTransport faster by not normpathing every internal path translation.
415
                    mypath = self._abspath(path)
416
                    otherpath = other._abspath(path)
1185.58.2 by John Arbash Meinel
Added mode to the appropriate transport functions, and tests to make sure they work.
417
                    shutil.copy(mypath, otherpath)
418
                    if mode is not None:
419
                        os.chmod(otherpath, mode)
1185.31.44 by John Arbash Meinel
Cleaned up Exceptions for all transports.
420
                except (IOError, OSError),e:
421
                    self._translate_error(e, path)
907.1.28 by John Arbash Meinel
Added pb to function that were missing, implemented a basic double-dispatch copy_to function.
422
                count += 1
423
            return count
424
        else:
1185.58.2 by John Arbash Meinel
Added mode to the appropriate transport functions, and tests to make sure they work.
425
            return super(LocalTransport, self).copy_to(relpaths, other, mode=mode, pb=pb)
907.1.28 by John Arbash Meinel
Added pb to function that were missing, implemented a basic double-dispatch copy_to function.
426
1400.1.1 by Robert Collins
implement a basic test for the ui branch command from http servers
427
    def listable(self):
428
        """See Transport.listable."""
429
        return True
907.1.28 by John Arbash Meinel
Added pb to function that were missing, implemented a basic double-dispatch copy_to function.
430
907.1.2 by John Arbash Meinel
Working on making Branch() do all of it's work over a Transport.
431
    def list_dir(self, relpath):
432
        """Return a list of all files at the given location.
433
        WARNING: many transports do not support this, so trying avoid using
434
        it if at all possible.
435
        """
1725.2.1 by Robert Collins
Make LocalTransport faster by not normpathing every internal path translation.
436
        path = self._abspath(relpath)
907.1.48 by John Arbash Meinel
Updated LocalTransport by passing it through the transport_test suite, and got it to pass.
437
        try:
1959.2.1 by John Arbash Meinel
David Allouche: Make transports return escaped paths
438
            entries = os.listdir(path)
1607.1.3 by Robert Collins
Apply David Allouches list_dir quoting fix.
439
        except (IOError, OSError), e:
1185.31.44 by John Arbash Meinel
Cleaned up Exceptions for all transports.
440
            self._translate_error(e, path)
1959.2.1 by John Arbash Meinel
David Allouche: Make transports return escaped paths
441
        return [urlutils.escape(entry) for entry in entries]
907.1.2 by John Arbash Meinel
Working on making Branch() do all of it's work over a Transport.
442
443
    def stat(self, relpath):
444
        """Return the stat information for a file.
445
        """
1185.31.44 by John Arbash Meinel
Cleaned up Exceptions for all transports.
446
        path = relpath
907.1.48 by John Arbash Meinel
Updated LocalTransport by passing it through the transport_test suite, and got it to pass.
447
        try:
1725.2.1 by Robert Collins
Make LocalTransport faster by not normpathing every internal path translation.
448
            path = self._abspath(relpath)
1185.31.44 by John Arbash Meinel
Cleaned up Exceptions for all transports.
449
            return os.stat(path)
450
        except (IOError, OSError),e:
451
            self._translate_error(e, path)
907.1.2 by John Arbash Meinel
Working on making Branch() do all of it's work over a Transport.
452
907.1.24 by John Arbash Meinel
Remote functionality work.
453
    def lock_read(self, relpath):
454
        """Lock the given file for shared (read) access.
455
        :return: A lock object, which should be passed to Transport.unlock()
456
        """
457
        from bzrlib.lock import ReadLock
1185.65.29 by Robert Collins
Implement final review suggestions.
458
        path = relpath
459
        try:
1725.2.1 by Robert Collins
Make LocalTransport faster by not normpathing every internal path translation.
460
            path = self._abspath(relpath)
1185.65.29 by Robert Collins
Implement final review suggestions.
461
            return ReadLock(path)
462
        except (IOError, OSError), e:
463
            self._translate_error(e, path)
907.1.24 by John Arbash Meinel
Remote functionality work.
464
465
    def lock_write(self, relpath):
466
        """Lock the given file for exclusive (write) access.
467
        WARNING: many transports do not support this, so trying avoid using it
468
469
        :return: A lock object, which should be passed to Transport.unlock()
470
        """
471
        from bzrlib.lock import WriteLock
1725.2.1 by Robert Collins
Make LocalTransport faster by not normpathing every internal path translation.
472
        return WriteLock(self._abspath(relpath))
907.1.24 by John Arbash Meinel
Remote functionality work.
473
1534.4.15 by Robert Collins
Remove shutil dependency in upgrade - create a delete_tree method for transports.
474
    def rmdir(self, relpath):
475
        """See Transport.rmdir."""
476
        path = relpath
477
        try:
1725.2.1 by Robert Collins
Make LocalTransport faster by not normpathing every internal path translation.
478
            path = self._abspath(relpath)
1534.4.15 by Robert Collins
Remove shutil dependency in upgrade - create a delete_tree method for transports.
479
            os.rmdir(path)
480
        except (IOError, OSError),e:
481
            self._translate_error(e, path)
1442.1.41 by Robert Collins
move duplicate scratch logic into a scratch transport
482
1608.2.7 by Martin Pool
Rename supports_unix_modebits to _can_roundtrip_unix_modebits for clarity
483
    def _can_roundtrip_unix_modebits(self):
1608.2.5 by Martin Pool
Add Transport.supports_unix_modebits, so tests can
484
        if sys.platform == 'win32':
485
            # anyone else?
486
            return False
487
        else:
488
            return True
489
490
2245.6.2 by Alexander Belchenko
Fix name of emulated Win32LocalTransport as Robert suggested.
491
class EmulatedWin32LocalTransport(LocalTransport):
2245.6.1 by Alexander Belchenko
win32 UNC path: recursive cloning UNC path to root stops on //HOST, not on //
492
    """Special transport for testing Win32 [UNC] paths on non-windows"""
493
494
    def __init__(self, base):
495
        if base[-1] != '/':
496
            base = base + '/'
497
        super(LocalTransport, self).__init__(base)
498
        self._local_base = urlutils._win32_local_path_from_url(base)
499
500
    def abspath(self, relpath):
501
        assert isinstance(relpath, basestring), (type(relpath), relpath)
502
        path = osutils.normpath(osutils.pathjoin(
503
                    self._local_base, urlutils.unescape(relpath)))
504
        return urlutils._win32_local_path_to_url(path)
505
2245.6.3 by Alexander Belchenko
EmulatedWin32LocalTransport should provide their own 'clone' method
506
    def clone(self, offset=None):
507
        """Return a new LocalTransport with root at self.base + offset
508
        Because the local filesystem does not require a connection, 
509
        we can just return a new object.
510
        """
511
        if offset is None:
512
            return EmulatedWin32LocalTransport(self.base)
513
        else:
514
            abspath = self.abspath(offset)
515
            if abspath == 'file://':
516
                # fix upwalk for UNC path
517
                # when clone from //HOST/path updir recursively
518
                # we should stop at least at //HOST part
519
                abspath = self.base
520
            return EmulatedWin32LocalTransport(abspath)
521
2245.6.1 by Alexander Belchenko
win32 UNC path: recursive cloning UNC path to root stops on //HOST, not on //
522
1530.1.3 by Robert Collins
transport implementations now tested consistently.
523
class LocalURLServer(Server):
1951.2.1 by Martin Pool
Change to using LocalURLServer for testing.
524
    """A pretend server for local transports, using file:// urls.
525
    
526
    Of course no actual server is required to access the local filesystem, so
527
    this just exists to tell the test code how to get to it.
528
    """
1530.1.3 by Robert Collins
transport implementations now tested consistently.
529
2018.5.114 by Robert Collins
Commit current test pass improvements.
530
    def setUp(self):
2018.5.44 by Andrew Bennetts
Small changes to help a couple more tests pass.
531
        """Setup the server to service requests.
532
        
533
        :param decorated_transport: ignored by this implementation.
534
        """
535
1530.1.3 by Robert Collins
transport implementations now tested consistently.
536
    def get_url(self):
537
        """See Transport.Server.get_url."""
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
538
        return urlutils.local_path_to_url('')
1530.1.11 by Robert Collins
Push the transport permutations list into each transport module allowing for automatic testing of new modules that are registered as transports.
539
540
541
def get_test_permutations():
542
    """Return the permutations to be used in testing."""
1951.2.1 by Martin Pool
Change to using LocalURLServer for testing.
543
    return [
1530.1.11 by Robert Collins
Push the transport permutations list into each transport module allowing for automatic testing of new modules that are registered as transports.
544
            (LocalTransport, LocalURLServer),
545
            ]