/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
2
#
1 by mbp at sourcefrog
import from baz patch-364
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.
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
7
#
1 by mbp at sourcefrog
import from baz patch-364
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.
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
12
#
1 by mbp at sourcefrog
import from baz patch-364
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
16
1390 by Robert Collins
pair programming worx... merge integration and weave
17
from cStringIO import StringIO
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
18
import os
19
import re
20
import stat
21
from stat import (S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE,
22
                  S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
23
import sys
24
import time
25
26
from bzrlib.lazy_import import lazy_import
27
lazy_import(globals(), """
2192.1.1 by Alexander Belchenko
Before actually using encoding need to check that Python has corresponding codec
28
import codecs
2215.6.1 by James Henstridge
Don't rely on time.timezone and time.altzone in local_time_offset(),
29
from datetime import datetime
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
30
import errno
1711.4.5 by John Arbash Meinel
the _posix_* routines should use posixpath not os.path, so tests pass on win32
31
from ntpath import (abspath as _nt_abspath,
32
                    join as _nt_join,
33
                    normpath as _nt_normpath,
34
                    realpath as _nt_realpath,
1711.5.2 by John Arbash Meinel
win32 likes to return lowercase drive letters sometimes, and uppercase at other times. normalize this
35
                    splitdrive as _nt_splitdrive,
1711.4.5 by John Arbash Meinel
the _posix_* routines should use posixpath not os.path, so tests pass on win32
36
                    )
37
import posixpath
1236 by Martin Pool
- fix up imports
38
import sha
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
39
import shutil
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
40
from shutil import (
41
    rmtree,
42
    )
1185.31.40 by John Arbash Meinel
Added osutils.mkdtemp()
43
import tempfile
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
44
from tempfile import (
45
    mkdtemp,
46
    )
1185.85.75 by John Arbash Meinel
Adding bzrlib.osutils.unicode_filename to handle unicode normalization for file paths.
47
import unicodedata
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
48
49
from bzrlib import (
2249.5.16 by John Arbash Meinel
[merge] bzr.dev 2283
50
    cache_utf8,
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
51
    errors,
2245.4.6 by Alexander Belchenko
osutils.py: terminal_width() now use win32utils.get_console_size()
52
    win32utils,
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
53
    )
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
54
""")
1 by mbp at sourcefrog
import from baz patch-364
55
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
56
import bzrlib
2309.4.3 by John Arbash Meinel
(broken) change safe_*_id to emit a warning.
57
from bzrlib import symbol_versioning
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
58
from bzrlib.symbol_versioning import (
59
    deprecated_function,
60
    zero_nine,
61
    )
694 by Martin Pool
- weed out all remaining calls to bailout() and remove the function
62
from bzrlib.trace import mutter
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
63
1 by mbp at sourcefrog
import from baz patch-364
64
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
65
# On win32, O_BINARY is used to indicate the file should
66
# be opened in binary mode, rather than text mode.
67
# On other platforms, O_BINARY doesn't exist, because
68
# they always open in binary mode, so it is okay to
69
# OR with 0 on those platforms
70
O_BINARY = getattr(os, 'O_BINARY', 0)
71
72
1 by mbp at sourcefrog
import from baz patch-364
73
def make_readonly(filename):
74
    """Make a filename read-only."""
75
    mod = os.stat(filename).st_mode
76
    mod = mod & 0777555
77
    os.chmod(filename, mod)
78
79
80
def make_writable(filename):
81
    mod = os.stat(filename).st_mode
82
    mod = mod | 0200
83
    os.chmod(filename, mod)
84
85
1077 by Martin Pool
- avoid compiling REs at module load time
86
_QUOTE_RE = None
969 by Martin Pool
- Add less-sucky is_within_any
87
88
1 by mbp at sourcefrog
import from baz patch-364
89
def quotefn(f):
779 by Martin Pool
- better quotefn for windows: use doublequotes for strings with
90
    """Return a quoted filename filename
91
92
    This previously used backslash quoting, but that works poorly on
93
    Windows."""
94
    # TODO: I'm not really sure this is the best format either.x
1077 by Martin Pool
- avoid compiling REs at module load time
95
    global _QUOTE_RE
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
96
    if _QUOTE_RE is None:
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
97
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
1077 by Martin Pool
- avoid compiling REs at module load time
98
        
779 by Martin Pool
- better quotefn for windows: use doublequotes for strings with
99
    if _QUOTE_RE.search(f):
100
        return '"' + f + '"'
101
    else:
102
        return f
1 by mbp at sourcefrog
import from baz patch-364
103
104
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
105
_directory_kind = 'directory'
106
1732.1.10 by John Arbash Meinel
Updated version of file_kind. Rather than multiple function calls, one mask + dictionary lookup
107
_formats = {
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
108
    stat.S_IFDIR:_directory_kind,
1732.1.10 by John Arbash Meinel
Updated version of file_kind. Rather than multiple function calls, one mask + dictionary lookup
109
    stat.S_IFCHR:'chardev',
110
    stat.S_IFBLK:'block',
111
    stat.S_IFREG:'file',
112
    stat.S_IFIFO:'fifo',
113
    stat.S_IFLNK:'symlink',
114
    stat.S_IFSOCK:'socket',
115
}
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
116
117
118
def file_kind_from_stat_mode(stat_mode, _formats=_formats, _unknown='unknown'):
119
    """Generate a file kind from a stat mode. This is used in walkdirs.
120
121
    Its performance is critical: Do not mutate without careful benchmarking.
122
    """
1732.1.12 by John Arbash Meinel
improve bzrlib.osutils.file_kind performance from 324ms => 275ms
123
    try:
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
124
        return _formats[stat_mode & 0170000]
1732.1.12 by John Arbash Meinel
improve bzrlib.osutils.file_kind performance from 324ms => 275ms
125
    except KeyError:
1732.1.30 by John Arbash Meinel
More file_kind tweaks. Use keyword parameters to make everything a local variable.
126
        return _unknown
488 by Martin Pool
- new helper function kind_marker()
127
128
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
129
def file_kind(f, _lstat=os.lstat, _mapper=file_kind_from_stat_mode):
1757.2.4 by Robert Collins
Teach file_kind about NoSuchFile, reducing duplicate code, and add user files before entering the main loop in smart_add.
130
    try:
131
        return _mapper(_lstat(f).st_mode)
132
    except OSError, e:
133
        if getattr(e, 'errno', None) == errno.ENOENT:
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
134
            raise errors.NoSuchFile(f)
1757.2.4 by Robert Collins
Teach file_kind about NoSuchFile, reducing duplicate code, and add user files before entering the main loop in smart_add.
135
        raise
136
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
137
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
138
def get_umask():
139
    """Return the current umask"""
140
    # Assume that people aren't messing with the umask while running
141
    # XXX: This is not thread safe, but there is no way to get the
142
    #      umask without setting it
143
    umask = os.umask(0)
144
    os.umask(umask)
145
    return umask
146
147
488 by Martin Pool
- new helper function kind_marker()
148
def kind_marker(kind):
149
    if kind == 'file':
150
        return ''
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
151
    elif kind == _directory_kind:
488 by Martin Pool
- new helper function kind_marker()
152
        return '/'
153
    elif kind == 'symlink':
154
        return '@'
155
    else:
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
156
        raise errors.BzrError('invalid file kind %r' % kind)
1 by mbp at sourcefrog
import from baz patch-364
157
1732.1.2 by John Arbash Meinel
just use os.path.lexists if it exists
158
lexists = getattr(os.path, 'lexists', None)
159
if lexists is None:
160
    def lexists(f):
161
        try:
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
162
            if getattr(os, 'lstat') is not None:
1732.1.2 by John Arbash Meinel
just use os.path.lexists if it exists
163
                os.lstat(f)
164
            else:
165
                os.stat(f)
166
            return True
167
        except OSError,e:
168
            if e.errno == errno.ENOENT:
169
                return False;
170
            else:
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
171
                raise errors.BzrError("lstat/stat of (%r): %r" % (f, e))
1732.1.2 by John Arbash Meinel
just use os.path.lexists if it exists
172
1 by mbp at sourcefrog
import from baz patch-364
173
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
174
def fancy_rename(old, new, rename_func, unlink_func):
175
    """A fancy rename, when you don't have atomic rename.
176
    
177
    :param old: The old path, to rename from
178
    :param new: The new path, to rename to
179
    :param rename_func: The potentially non-atomic rename function
180
    :param unlink_func: A way to delete the target file if the full rename succeeds
181
    """
182
183
    # sftp rename doesn't allow overwriting, so play tricks:
184
    import random
185
    base = os.path.basename(new)
186
    dirname = os.path.dirname(new)
1553.5.22 by Martin Pool
Change fancy_rename to use rand_chars rather than reinvent it.
187
    tmp_name = u'tmp.%s.%.9f.%d.%s' % (base, time.time(), os.getpid(), rand_chars(10))
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
188
    tmp_name = pathjoin(dirname, tmp_name)
189
190
    # Rename the file out of the way, but keep track if it didn't exist
191
    # We don't want to grab just any exception
192
    # something like EACCES should prevent us from continuing
193
    # The downside is that the rename_func has to throw an exception
194
    # with an errno = ENOENT, or NoSuchFile
195
    file_existed = False
196
    try:
197
        rename_func(new, tmp_name)
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
198
    except (errors.NoSuchFile,), e:
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
199
        pass
1532 by Robert Collins
Merge in John Meinels integration branch.
200
    except IOError, e:
201
        # RBC 20060103 abstraction leakage: the paramiko SFTP clients rename
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
202
        # function raises an IOError with errno is None when a rename fails.
1532 by Robert Collins
Merge in John Meinels integration branch.
203
        # This then gets caught here.
1185.50.37 by John Arbash Meinel
Fixed exception handling for fancy_rename
204
        if e.errno not in (None, errno.ENOENT, errno.ENOTDIR):
1532 by Robert Collins
Merge in John Meinels integration branch.
205
            raise
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
206
    except Exception, e:
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
207
        if (getattr(e, 'errno', None) is None
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
208
            or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
209
            raise
210
    else:
211
        file_existed = True
212
213
    success = False
214
    try:
215
        # This may throw an exception, in which case success will
216
        # not be set.
217
        rename_func(old, new)
218
        success = True
219
    finally:
220
        if file_existed:
221
            # If the file used to exist, rename it back into place
222
            # otherwise just delete it from the tmp location
223
            if success:
224
                unlink_func(tmp_name)
225
            else:
1185.31.49 by John Arbash Meinel
Some corrections using the new osutils.rename. **ALL TESTS PASS**
226
                rename_func(tmp_name, new)
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
227
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
228
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
229
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
230
# choke on a Unicode string containing a relative path if
231
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
232
# string.
2093.1.1 by John Arbash Meinel
(Bart Teeuwisse) if sys.getfilesystemencoding() is None, use 'utf-8'
233
_fs_enc = sys.getfilesystemencoding() or 'utf-8'
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
234
def _posix_abspath(path):
1711.4.5 by John Arbash Meinel
the _posix_* routines should use posixpath not os.path, so tests pass on win32
235
    # jam 20060426 rather than encoding to fsencoding
236
    # copy posixpath.abspath, but use os.getcwdu instead
237
    if not posixpath.isabs(path):
238
        path = posixpath.join(getcwd(), path)
239
    return posixpath.normpath(path)
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
240
241
242
def _posix_realpath(path):
1711.4.5 by John Arbash Meinel
the _posix_* routines should use posixpath not os.path, so tests pass on win32
243
    return posixpath.realpath(path.encode(_fs_enc)).decode(_fs_enc)
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
244
245
1711.5.2 by John Arbash Meinel
win32 likes to return lowercase drive letters sometimes, and uppercase at other times. normalize this
246
def _win32_fixdrive(path):
247
    """Force drive letters to be consistent.
248
249
    win32 is inconsistent whether it returns lower or upper case
250
    and even if it was consistent the user might type the other
251
    so we force it to uppercase
252
    running python.exe under cmd.exe return capital C:\\
253
    running win32 python inside a cygwin shell returns lowercase c:\\
254
    """
255
    drive, path = _nt_splitdrive(path)
256
    return drive.upper() + path
257
258
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
259
def _win32_abspath(path):
1711.4.6 by John Arbash Meinel
Removing hacks for _win32_abspath, on real win32 abspath handles unicode just fine, it doesn't handle encoding into 'mbcs'
260
    # Real _nt_abspath doesn't have a problem with a unicode cwd
1711.5.2 by John Arbash Meinel
win32 likes to return lowercase drive letters sometimes, and uppercase at other times. normalize this
261
    return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
262
263
2279.4.1 by Alexander Belchenko
Reimplementation of ntpath.abspath in Python for Windows98: unicode safe, UNC path safe
264
def _win98_abspath(path):
265
    """Return the absolute version of a path.
266
    Windows 98 safe implementation (python reimplementation
267
    of Win32 API function GetFullPathNameW)
268
    """
269
    # Corner cases:
270
    #   C:\path     => C:/path
271
    #   C:/path     => C:/path
272
    #   \\HOST\path => //HOST/path
273
    #   //HOST/path => //HOST/path
274
    #   path        => C:/cwd/path
275
    #   /path       => C:/path
276
    path = unicode(path)
277
    # check for absolute path
278
    drive = _nt_splitdrive(path)[0]
279
    if drive == '' and path[:2] not in('//','\\\\'):
280
        cwd = os.getcwdu()
281
        # we cannot simply os.path.join cwd and path
282
        # because os.path.join('C:','/path') produce '/path'
283
        # and this is incorrect
284
        if path[:1] in ('/','\\'):
285
            cwd = _nt_splitdrive(cwd)[0]
2279.4.3 by Alexander Belchenko
win98_abspath: support for running in POSIX environment: cwd path has not drive letter
286
            path = path[1:]
2279.4.1 by Alexander Belchenko
Reimplementation of ntpath.abspath in Python for Windows98: unicode safe, UNC path safe
287
        path = cwd + '\\' + path
288
    return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
289
290
if win32utils.winver == 'Windows 98':
291
    _win32_abspath = _win98_abspath
292
293
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
294
def _win32_realpath(path):
1711.4.6 by John Arbash Meinel
Removing hacks for _win32_abspath, on real win32 abspath handles unicode just fine, it doesn't handle encoding into 'mbcs'
295
    # Real _nt_realpath doesn't have a problem with a unicode cwd
1711.5.2 by John Arbash Meinel
win32 likes to return lowercase drive letters sometimes, and uppercase at other times. normalize this
296
    return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
297
298
299
def _win32_pathjoin(*args):
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
300
    return _nt_join(*args).replace('\\', '/')
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
301
302
303
def _win32_normpath(path):
1711.5.2 by John Arbash Meinel
win32 likes to return lowercase drive letters sometimes, and uppercase at other times. normalize this
304
    return _win32_fixdrive(_nt_normpath(unicode(path)).replace('\\', '/'))
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
305
306
307
def _win32_getcwd():
1711.5.2 by John Arbash Meinel
win32 likes to return lowercase drive letters sometimes, and uppercase at other times. normalize this
308
    return _win32_fixdrive(os.getcwdu().replace('\\', '/'))
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
309
310
311
def _win32_mkdtemp(*args, **kwargs):
1711.5.2 by John Arbash Meinel
win32 likes to return lowercase drive letters sometimes, and uppercase at other times. normalize this
312
    return _win32_fixdrive(tempfile.mkdtemp(*args, **kwargs).replace('\\', '/'))
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
313
314
315
def _win32_rename(old, new):
1711.7.6 by John Arbash Meinel
Change _win32_rename() so that it raises ENOENT *before* it tries any renaming.
316
    """We expect to be able to atomically replace 'new' with old.
317
1711.7.17 by John Arbash Meinel
Delay the extra syscall in _win32_rename until we get a failure.
318
    On win32, if new exists, it must be moved out of the way first,
319
    and then deleted. 
1711.7.6 by John Arbash Meinel
Change _win32_rename() so that it raises ENOENT *before* it tries any renaming.
320
    """
1711.7.17 by John Arbash Meinel
Delay the extra syscall in _win32_rename until we get a failure.
321
    try:
322
        fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
323
    except OSError, e:
1830.3.15 by John Arbash Meinel
On Mac we get EINVAL when renaming cwd
324
        if e.errno in (errno.EPERM, errno.EACCES, errno.EBUSY, errno.EINVAL):
325
            # If we try to rename a non-existant file onto cwd, we get 
326
            # EPERM or EACCES instead of ENOENT, this will raise ENOENT 
327
            # if the old path doesn't exist, sometimes we get EACCES
328
            # On Linux, we seem to get EBUSY, on Mac we get EINVAL
1711.7.17 by John Arbash Meinel
Delay the extra syscall in _win32_rename until we get a failure.
329
            os.lstat(old)
330
        raise
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
331
332
1830.3.11 by John Arbash Meinel
Create a mac version of 'getcwd()' which normalizes the path.
333
def _mac_getcwd():
334
    return unicodedata.normalize('NFKC', os.getcwdu())
335
336
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
337
# Default is to just use the python builtins, but these can be rebound on
338
# particular platforms.
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
339
abspath = _posix_abspath
340
realpath = _posix_realpath
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
341
pathjoin = os.path.join
342
normpath = os.path.normpath
343
getcwd = os.getcwdu
344
rename = os.rename
345
dirname = os.path.dirname
346
basename = os.path.basename
2215.4.2 by Alexander Belchenko
split and splitext now the part of osutils
347
split = os.path.split
348
splitext = os.path.splitext
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
349
# These were already imported into local scope
350
# mkdtemp = tempfile.mkdtemp
351
# rmtree = shutil.rmtree
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
352
1551.2.53 by abentley
Strip trailing slashes in a platform-sensible way
353
MIN_ABS_PATHLENGTH = 1
354
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
355
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
356
if sys.platform == 'win32':
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
357
    abspath = _win32_abspath
358
    realpath = _win32_realpath
359
    pathjoin = _win32_pathjoin
360
    normpath = _win32_normpath
361
    getcwd = _win32_getcwd
362
    mkdtemp = _win32_mkdtemp
363
    rename = _win32_rename
364
1551.2.53 by abentley
Strip trailing slashes in a platform-sensible way
365
    MIN_ABS_PATHLENGTH = 3
1532 by Robert Collins
Merge in John Meinels integration branch.
366
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
367
    def _win32_delete_readonly(function, path, excinfo):
368
        """Error handler for shutil.rmtree function [for win32]
369
        Helps to remove files and dirs marked as read-only.
370
        """
2116.5.1 by Henri Wiechers
Fixes osutils.rmtree on Windows with Python 2.5
371
        exception = excinfo[1]
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
372
        if function in (os.remove, os.rmdir) \
2116.5.1 by Henri Wiechers
Fixes osutils.rmtree on Windows with Python 2.5
373
            and isinstance(exception, OSError) \
374
            and exception.errno == errno.EACCES:
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
375
            make_writable(path)
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
376
            function(path)
377
        else:
378
            raise
379
380
    def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
381
        """Replacer for shutil.rmtree: could remove readonly dirs/files"""
382
        return shutil.rmtree(path, ignore_errors, onerror)
1830.3.11 by John Arbash Meinel
Create a mac version of 'getcwd()' which normalizes the path.
383
elif sys.platform == 'darwin':
384
    getcwd = _mac_getcwd
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
385
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
386
1711.4.10 by John Arbash Meinel
Pull out sys.stdout.encoding handling into a separate function so it can be tested, and used elsewhere.
387
def get_terminal_encoding():
388
    """Find the best encoding for printing to the screen.
389
390
    This attempts to check both sys.stdout and sys.stdin to see
391
    what encoding they are in, and if that fails it falls back to
392
    bzrlib.user_encoding.
393
    The problem is that on Windows, locale.getpreferredencoding()
394
    is not the same encoding as that used by the console:
395
    http://mail.python.org/pipermail/python-list/2003-May/162357.html
396
397
    On my standard US Windows XP, the preferred encoding is
398
    cp1252, but the console is cp437
399
    """
400
    output_encoding = getattr(sys.stdout, 'encoding', None)
401
    if not output_encoding:
402
        input_encoding = getattr(sys.stdin, 'encoding', None)
403
        if not input_encoding:
404
            output_encoding = bzrlib.user_encoding
405
            mutter('encoding stdout as bzrlib.user_encoding %r', output_encoding)
406
        else:
407
            output_encoding = input_encoding
408
            mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
409
    else:
410
        mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
2127.4.1 by Alexander Belchenko
(jam, bialix) Workaround for cp0 console encoding on Windows
411
    if output_encoding == 'cp0':
412
        # invalid encoding (cp0 means 'no codepage' on Windows)
413
        output_encoding = bzrlib.user_encoding
414
        mutter('cp0 is invalid encoding.'
415
               ' encoding stdout as bzrlib.user_encoding %r', output_encoding)
2192.1.1 by Alexander Belchenko
Before actually using encoding need to check that Python has corresponding codec
416
    # check encoding
417
    try:
418
        codecs.lookup(output_encoding)
419
    except LookupError:
420
        sys.stderr.write('bzr: warning:'
2192.1.9 by Alexander Belchenko
final fix suggested by John Meinel
421
                         ' unknown terminal encoding %s.\n'
2192.1.1 by Alexander Belchenko
Before actually using encoding need to check that Python has corresponding codec
422
                         '  Using encoding %s instead.\n'
423
                         % (output_encoding, bzrlib.user_encoding)
424
                        )
425
        output_encoding = bzrlib.user_encoding
426
1711.4.10 by John Arbash Meinel
Pull out sys.stdout.encoding handling into a separate function so it can be tested, and used elsewhere.
427
    return output_encoding
428
429
1185.31.32 by John Arbash Meinel
Updated the bzr sourcecode to use bzrlib.osutils.pathjoin rather than os.path.join to enforce internal use of / instead of \
430
def normalizepath(f):
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
431
    if getattr(os.path, 'realpath', None) is not None:
1185.31.32 by John Arbash Meinel
Updated the bzr sourcecode to use bzrlib.osutils.pathjoin rather than os.path.join to enforce internal use of / instead of \
432
        F = realpath
433
    else:
434
        F = abspath
435
    [p,e] = os.path.split(f)
436
    if e == "" or e == "." or e == "..":
437
        return F(f)
438
    else:
439
        return pathjoin(F(p), e)
440
1 by mbp at sourcefrog
import from baz patch-364
441
779 by Martin Pool
- better quotefn for windows: use doublequotes for strings with
442
def backup_file(fn):
443
    """Copy a file to a backup.
444
445
    Backups are named in GNU-style, with a ~ suffix.
446
447
    If the file is already a backup, it's not copied.
448
    """
449
    if fn[-1] == '~':
450
        return
451
    bfn = fn + '~'
452
1448 by Robert Collins
revert symlinks correctly
453
    if has_symlinks() and os.path.islink(fn):
454
        target = os.readlink(fn)
455
        os.symlink(target, bfn)
456
        return
779 by Martin Pool
- better quotefn for windows: use doublequotes for strings with
457
    inf = file(fn, 'rb')
458
    try:
459
        content = inf.read()
460
    finally:
461
        inf.close()
462
    
463
    outf = file(bfn, 'wb')
464
    try:
465
        outf.write(content)
466
    finally:
467
        outf.close()
468
469
1 by mbp at sourcefrog
import from baz patch-364
470
def isdir(f):
471
    """True if f is an accessible directory."""
472
    try:
473
        return S_ISDIR(os.lstat(f)[ST_MODE])
474
    except OSError:
475
        return False
476
477
478
def isfile(f):
479
    """True if f is a regular file."""
480
    try:
481
        return S_ISREG(os.lstat(f)[ST_MODE])
482
    except OSError:
483
        return False
484
1092.2.6 by Robert Collins
symlink support updated to work
485
def islink(f):
486
    """True if f is a symlink."""
487
    try:
488
        return S_ISLNK(os.lstat(f)[ST_MODE])
489
    except OSError:
490
        return False
1 by mbp at sourcefrog
import from baz patch-364
491
485 by Martin Pool
- move commit code into its own module
492
def is_inside(dir, fname):
493
    """True if fname is inside dir.
969 by Martin Pool
- Add less-sucky is_within_any
494
    
1185.31.38 by John Arbash Meinel
Changing os.path.normpath to osutils.normpath
495
    The parameters should typically be passed to osutils.normpath first, so
969 by Martin Pool
- Add less-sucky is_within_any
496
    that . and .. and repeated slashes are eliminated, and the separators
497
    are canonical for the platform.
498
    
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
499
    The empty string as a dir name is taken as top-of-tree and matches 
500
    everything.
485 by Martin Pool
- move commit code into its own module
501
    """
969 by Martin Pool
- Add less-sucky is_within_any
502
    # XXX: Most callers of this can actually do something smarter by 
503
    # looking at the inventory
972 by Martin Pool
- less dodgy is_inside function
504
    if dir == fname:
505
        return True
506
    
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
507
    if dir == '':
508
        return True
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
509
1185.31.34 by John Arbash Meinel
Removing instances of os.sep
510
    if dir[-1] != '/':
511
        dir += '/'
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
512
972 by Martin Pool
- less dodgy is_inside function
513
    return fname.startswith(dir)
514
485 by Martin Pool
- move commit code into its own module
515
516
def is_inside_any(dir_list, fname):
517
    """True if fname is inside any of given dirs."""
518
    for dirname in dir_list:
519
        if is_inside(dirname, fname):
520
            return True
521
    else:
522
        return False
523
524
1740.3.4 by Jelmer Vernooij
Move inventory to commit builder.
525
def is_inside_or_parent_of_any(dir_list, fname):
526
    """True if fname is a child or a parent of any of the given files."""
527
    for dirname in dir_list:
528
        if is_inside(dirname, fname) or is_inside(fname, dirname):
529
            return True
530
    else:
531
        return False
532
533
1 by mbp at sourcefrog
import from baz patch-364
534
def pumpfile(fromfile, tofile):
535
    """Copy contents of one file to another."""
1185.49.12 by John Arbash Meinel
Changed pumpfile to work on blocks, rather than reading the entire file at once.
536
    BUFSIZE = 32768
537
    while True:
538
        b = fromfile.read(BUFSIZE)
539
        if not b:
540
            break
1185.49.13 by John Arbash Meinel
Removed delayed setup, since it broke some tests. Fixed other small bugs. All tests pass.
541
        tofile.write(b)
1 by mbp at sourcefrog
import from baz patch-364
542
543
1185.67.7 by Aaron Bentley
Refactored a bit
544
def file_iterator(input_file, readsize=32768):
545
    while True:
546
        b = input_file.read(readsize)
547
        if len(b) == 0:
548
            break
549
        yield b
550
551
1 by mbp at sourcefrog
import from baz patch-364
552
def sha_file(f):
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
553
    if getattr(f, 'tell', None) is not None:
1 by mbp at sourcefrog
import from baz patch-364
554
        assert f.tell() == 0
555
    s = sha.new()
320 by Martin Pool
- Compute SHA-1 of files in chunks
556
    BUFSIZE = 128<<10
557
    while True:
558
        b = f.read(BUFSIZE)
559
        if not b:
560
            break
561
        s.update(b)
1 by mbp at sourcefrog
import from baz patch-364
562
    return s.hexdigest()
563
564
1235 by Martin Pool
- split sha_strings into osutils
565
566
def sha_strings(strings):
567
    """Return the sha-1 of concatenation of strings"""
568
    s = sha.new()
569
    map(s.update, strings)
570
    return s.hexdigest()
571
572
1 by mbp at sourcefrog
import from baz patch-364
573
def sha_string(f):
574
    s = sha.new()
575
    s.update(f)
576
    return s.hexdigest()
577
578
124 by mbp at sourcefrog
- check file text for past revisions is correct
579
def fingerprint_file(f):
580
    s = sha.new()
126 by mbp at sourcefrog
Use just one big read to fingerprint files
581
    b = f.read()
582
    s.update(b)
583
    size = len(b)
124 by mbp at sourcefrog
- check file text for past revisions is correct
584
    return {'size': size,
585
            'sha1': s.hexdigest()}
586
587
1 by mbp at sourcefrog
import from baz patch-364
588
def compare_files(a, b):
589
    """Returns true if equal in contents"""
74 by mbp at sourcefrog
compare_files: read in one page at a time rather than
590
    BUFSIZE = 4096
591
    while True:
592
        ai = a.read(BUFSIZE)
593
        bi = b.read(BUFSIZE)
594
        if ai != bi:
595
            return False
596
        if ai == '':
597
            return True
1 by mbp at sourcefrog
import from baz patch-364
598
599
49 by mbp at sourcefrog
fix local-time-offset calculation
600
def local_time_offset(t=None):
601
    """Return offset of local zone from GMT, either at present or at time t."""
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
602
    if t is None:
73 by mbp at sourcefrog
fix time.localtime call for python 2.3
603
        t = time.time()
2215.6.1 by James Henstridge
Don't rely on time.timezone and time.altzone in local_time_offset(),
604
    offset = datetime.fromtimestamp(t) - datetime.utcfromtimestamp(t)
605
    return offset.days * 86400 + offset.seconds
8 by mbp at sourcefrog
store committer's timezone in revision and show
606
607
    
1185.12.24 by Aaron Bentley
Made format_date more flexible
608
def format_date(t, offset=0, timezone='original', date_fmt=None, 
609
                show_offset=True):
1 by mbp at sourcefrog
import from baz patch-364
610
    ## TODO: Perhaps a global option to use either universal or local time?
611
    ## Or perhaps just let people set $TZ?
612
    assert isinstance(t, float)
613
    
8 by mbp at sourcefrog
store committer's timezone in revision and show
614
    if timezone == 'utc':
1 by mbp at sourcefrog
import from baz patch-364
615
        tt = time.gmtime(t)
616
        offset = 0
8 by mbp at sourcefrog
store committer's timezone in revision and show
617
    elif timezone == 'original':
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
618
        if offset is None:
23 by mbp at sourcefrog
format_date: handle revisions with no timezone offset
619
            offset = 0
16 by mbp at sourcefrog
fix inverted calculation for original timezone -> utc
620
        tt = time.gmtime(t + offset)
12 by mbp at sourcefrog
new --timezone option for bzr log
621
    elif timezone == 'local':
1 by mbp at sourcefrog
import from baz patch-364
622
        tt = time.localtime(t)
49 by mbp at sourcefrog
fix local-time-offset calculation
623
        offset = local_time_offset(t)
12 by mbp at sourcefrog
new --timezone option for bzr log
624
    else:
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
625
        raise errors.BzrError("unsupported timezone format %r" % timezone,
626
                              ['options are "utc", "original", "local"'])
1185.12.24 by Aaron Bentley
Made format_date more flexible
627
    if date_fmt is None:
628
        date_fmt = "%a %Y-%m-%d %H:%M:%S"
629
    if show_offset:
630
        offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
631
    else:
632
        offset_str = ''
633
    return (time.strftime(date_fmt, tt) +  offset_str)
1 by mbp at sourcefrog
import from baz patch-364
634
635
636
def compact_date(when):
637
    return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
638
    
639
1957.1.4 by John Arbash Meinel
create a helper for formatting a time delta
640
def format_delta(delta):
641
    """Get a nice looking string for a time delta.
642
643
    :param delta: The time difference in seconds, can be positive or negative.
644
        positive indicates time in the past, negative indicates time in the
645
        future. (usually time.time() - stored_time)
646
    :return: String formatted to show approximate resolution
647
    """
648
    delta = int(delta)
649
    if delta >= 0:
650
        direction = 'ago'
651
    else:
652
        direction = 'in the future'
653
        delta = -delta
654
655
    seconds = delta
656
    if seconds < 90: # print seconds up to 90 seconds
657
        if seconds == 1:
658
            return '%d second %s' % (seconds, direction,)
659
        else:
660
            return '%d seconds %s' % (seconds, direction)
661
662
    minutes = int(seconds / 60)
663
    seconds -= 60 * minutes
664
    if seconds == 1:
665
        plural_seconds = ''
666
    else:
667
        plural_seconds = 's'
668
    if minutes < 90: # print minutes, seconds up to 90 minutes
669
        if minutes == 1:
670
            return '%d minute, %d second%s %s' % (
671
                    minutes, seconds, plural_seconds, direction)
672
        else:
673
            return '%d minutes, %d second%s %s' % (
674
                    minutes, seconds, plural_seconds, direction)
675
676
    hours = int(minutes / 60)
677
    minutes -= 60 * hours
678
    if minutes == 1:
679
        plural_minutes = ''
680
    else:
681
        plural_minutes = 's'
682
683
    if hours == 1:
684
        return '%d hour, %d minute%s %s' % (hours, minutes,
685
                                            plural_minutes, direction)
686
    return '%d hours, %d minute%s %s' % (hours, minutes,
687
                                         plural_minutes, direction)
1 by mbp at sourcefrog
import from baz patch-364
688
689
def filesize(f):
690
    """Return size of given open file."""
691
    return os.fstat(f.fileno())[ST_SIZE]
692
1553.5.5 by Martin Pool
New utility routine rand_chars
693
1185.1.7 by Robert Collins
Nathaniel McCallums patch for urandom friendliness on aix.
694
# Define rand_bytes based on platform.
695
try:
696
    # Python 2.4 and later have os.urandom,
697
    # but it doesn't work on some arches
698
    os.urandom(1)
1 by mbp at sourcefrog
import from baz patch-364
699
    rand_bytes = os.urandom
1185.1.7 by Robert Collins
Nathaniel McCallums patch for urandom friendliness on aix.
700
except (NotImplementedError, AttributeError):
701
    # If python doesn't have os.urandom, or it doesn't work,
702
    # then try to first pull random data from /dev/urandom
2067.1.1 by John Arbash Meinel
Catch an exception while opening /dev/urandom rather than using os.path.exists()
703
    try:
1185.1.7 by Robert Collins
Nathaniel McCallums patch for urandom friendliness on aix.
704
        rand_bytes = file('/dev/urandom', 'rb').read
705
    # Otherwise, use this hack as a last resort
2067.1.1 by John Arbash Meinel
Catch an exception while opening /dev/urandom rather than using os.path.exists()
706
    except (IOError, OSError):
1185.1.7 by Robert Collins
Nathaniel McCallums patch for urandom friendliness on aix.
707
        # not well seeded, but better than nothing
708
        def rand_bytes(n):
709
            import random
710
            s = ''
711
            while n:
712
                s += chr(random.randint(0, 255))
713
                n -= 1
714
            return s
1 by mbp at sourcefrog
import from baz patch-364
715
1553.5.5 by Martin Pool
New utility routine rand_chars
716
717
ALNUM = '0123456789abcdefghijklmnopqrstuvwxyz'
718
def rand_chars(num):
719
    """Return a random string of num alphanumeric characters
720
    
721
    The result only contains lowercase chars because it may be used on 
722
    case-insensitive filesystems.
723
    """
724
    s = ''
725
    for raw_byte in rand_bytes(num):
726
        s += ALNUM[ord(raw_byte) % 36]
727
    return s
728
729
1 by mbp at sourcefrog
import from baz patch-364
730
## TODO: We could later have path objects that remember their list
1759.2.2 by Jelmer Vernooij
Revert some of my spelling fixes and fix some typos after review by Aaron.
731
## decomposition (might be too tricksy though.)
1 by mbp at sourcefrog
import from baz patch-364
732
733
def splitpath(p):
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
734
    """Turn string into list of parts."""
735
    assert isinstance(p, basestring)
271 by Martin Pool
- Windows path fixes
736
737
    # split on either delimiter because people might use either on
738
    # Windows
739
    ps = re.split(r'[\\/]', p)
740
741
    rps = []
1 by mbp at sourcefrog
import from baz patch-364
742
    for f in ps:
743
        if f == '..':
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
744
            raise errors.BzrError("sorry, %r not allowed in path" % f)
271 by Martin Pool
- Windows path fixes
745
        elif (f == '.') or (f == ''):
746
            pass
747
        else:
748
            rps.append(f)
749
    return rps
1 by mbp at sourcefrog
import from baz patch-364
750
751
def joinpath(p):
2255.7.40 by Robert Collins
Tweak pathjoin to be correct in its assertion about parameter types.
752
    assert isinstance(p, (list, tuple))
1 by mbp at sourcefrog
import from baz patch-364
753
    for f in p:
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
754
        if (f == '..') or (f is None) or (f == ''):
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
755
            raise errors.BzrError("sorry, %r not allowed in path" % f)
1185.31.32 by John Arbash Meinel
Updated the bzr sourcecode to use bzrlib.osutils.pathjoin rather than os.path.join to enforce internal use of / instead of \
756
    return pathjoin(*p)
1 by mbp at sourcefrog
import from baz patch-364
757
758
1732.1.1 by John Arbash Meinel
deprecating appendpath, it does exactly what pathjoin does
759
@deprecated_function(zero_nine)
1 by mbp at sourcefrog
import from baz patch-364
760
def appendpath(p1, p2):
761
    if p1 == '':
762
        return p2
763
    else:
1185.31.32 by John Arbash Meinel
Updated the bzr sourcecode to use bzrlib.osutils.pathjoin rather than os.path.join to enforce internal use of / instead of \
764
        return pathjoin(p1, p2)
1 by mbp at sourcefrog
import from baz patch-364
765
    
766
1231 by Martin Pool
- more progress on fetch on top of weaves
767
def split_lines(s):
768
    """Split s into lines, but without removing the newline characters."""
1666.1.6 by Robert Collins
Make knit the default format.
769
    lines = s.split('\n')
770
    result = [line + '\n' for line in lines[:-1]]
771
    if lines[-1]:
772
        result.append(lines[-1])
773
    return result
1391 by Robert Collins
merge from integration
774
775
1185.10.4 by Aaron Bentley
Disabled hardlinks on cygwin, mac OS
776
def hardlinks_good():
1185.10.5 by Aaron Bentley
Fixed hardlinks_good test
777
    return sys.platform not in ('win32', 'cygwin', 'darwin')
1185.10.4 by Aaron Bentley
Disabled hardlinks on cygwin, mac OS
778
1185.1.46 by Robert Collins
Aarons branch --basis patch
779
1185.10.3 by Aaron Bentley
Made copy_multi_immutable create hardlinks opportunistically
780
def link_or_copy(src, dest):
781
    """Hardlink a file, or copy it if it can't be hardlinked."""
1185.10.4 by Aaron Bentley
Disabled hardlinks on cygwin, mac OS
782
    if not hardlinks_good():
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
783
        shutil.copyfile(src, dest)
1185.10.3 by Aaron Bentley
Made copy_multi_immutable create hardlinks opportunistically
784
        return
785
    try:
786
        os.link(src, dest)
787
    except (OSError, IOError), e:
788
        if e.errno != errno.EXDEV:
789
            raise
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
790
        shutil.copyfile(src, dest)
1399.1.4 by Robert Collins
move diff and symlink conditionals into inventory.py from diff.py
791
1558.12.9 by Aaron Bentley
Handle resolving conflicts with directories properly
792
def delete_any(full_path):
793
    """Delete a file or directory."""
794
    try:
795
        os.unlink(full_path)
796
    except OSError, e:
797
    # We may be renaming a dangling inventory id
798
        if e.errno not in (errno.EISDIR, errno.EACCES, errno.EPERM):
799
            raise
800
        os.rmdir(full_path)
801
1399.1.4 by Robert Collins
move diff and symlink conditionals into inventory.py from diff.py
802
803
def has_symlinks():
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
804
    if getattr(os, 'symlink', None) is not None:
1399.1.4 by Robert Collins
move diff and symlink conditionals into inventory.py from diff.py
805
        return True
806
    else:
807
        return False
1185.16.38 by Martin Pool
- move contains_whitespace and contains_linebreaks to osutils
808
        
809
810
def contains_whitespace(s):
811
    """True if there are any whitespace characters in s."""
2249.2.1 by John Arbash Meinel
(John Arbash Meinel) hard-code the whitespace chars to avoid problems in some locales.
812
    # string.whitespace can include '\xa0' in certain locales, because it is
813
    # considered "non-breaking-space" as part of ISO-8859-1. But it
814
    # 1) Isn't a breaking whitespace
815
    # 2) Isn't one of ' \t\r\n' which are characters we sometimes use as
816
    #    separators
817
    # 3) '\xa0' isn't unicode safe since it is >128.
2249.5.16 by John Arbash Meinel
[merge] bzr.dev 2283
818
819
    # This should *not* be a unicode set of characters in case the source
820
    # string is not a Unicode string. We can auto-up-cast the characters since
821
    # they are ascii, but we don't want to auto-up-cast the string in case it
822
    # is utf-8
823
    for ch in ' \t\n\r\v\f':
1185.16.38 by Martin Pool
- move contains_whitespace and contains_linebreaks to osutils
824
        if ch in s:
825
            return True
826
    else:
827
        return False
828
829
830
def contains_linebreaks(s):
831
    """True if there is any vertical whitespace in s."""
832
    for ch in '\f\n\r':
833
        if ch in s:
834
            return True
835
    else:
836
        return False
1457.1.2 by Robert Collins
move branch._relpath into osutils as relpath
837
838
839
def relpath(base, path):
840
    """Return path relative to base, or raise exception.
841
842
    The path may be either an absolute path or a path relative to the
843
    current working directory.
844
845
    os.path.commonprefix (python2.4) has a bad bug that it works just
846
    on string prefixes, assuming that '/u' is a prefix of '/u2'.  This
1636.1.1 by Robert Collins
Fix calling relpath() and abspath() on transports at their root.
847
    avoids that problem.
848
    """
1685.1.12 by John Arbash Meinel
Some more work to get LocalTransport to only support URLs
849
1551.2.53 by abentley
Strip trailing slashes in a platform-sensible way
850
    assert len(base) >= MIN_ABS_PATHLENGTH, ('Length of base must be equal or'
851
        ' exceed the platform minimum length (which is %d)' % 
852
        MIN_ABS_PATHLENGTH)
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
853
1685.1.12 by John Arbash Meinel
Some more work to get LocalTransport to only support URLs
854
    rp = abspath(path)
1457.1.2 by Robert Collins
move branch._relpath into osutils as relpath
855
856
    s = []
1685.1.12 by John Arbash Meinel
Some more work to get LocalTransport to only support URLs
857
    head = rp
1457.1.2 by Robert Collins
move branch._relpath into osutils as relpath
858
    while len(head) >= len(base):
859
        if head == base:
860
            break
861
        head, tail = os.path.split(head)
862
        if tail:
863
            s.insert(0, tail)
864
    else:
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
865
        raise errors.PathNotChild(rp, base)
1457.1.2 by Robert Collins
move branch._relpath into osutils as relpath
866
1185.31.35 by John Arbash Meinel
Couple small fixes, all tests pass on cygwin.
867
    if s:
868
        return pathjoin(*s)
869
    else:
870
        return ''
1185.33.60 by Martin Pool
Use full terminal width for verbose test output.
871
872
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
873
def safe_unicode(unicode_or_utf8_string):
874
    """Coerce unicode_or_utf8_string into unicode.
875
876
    If it is unicode, it is returned.
877
    Otherwise it is decoded from utf-8. If a decoding error
878
    occurs, it is wrapped as a If the decoding fails, the exception is wrapped 
879
    as a BzrBadParameter exception.
880
    """
881
    if isinstance(unicode_or_utf8_string, unicode):
882
        return unicode_or_utf8_string
883
    try:
884
        return unicode_or_utf8_string.decode('utf8')
885
    except UnicodeDecodeError:
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
886
        raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
887
888
2249.5.8 by John Arbash Meinel
Add osutils.safe_utf8 and safe_revision_id for the new revision_id work.
889
def safe_utf8(unicode_or_utf8_string):
890
    """Coerce unicode_or_utf8_string to a utf8 string.
891
892
    If it is a str, it is returned.
893
    If it is Unicode, it is encoded into a utf-8 string.
894
    """
895
    if isinstance(unicode_or_utf8_string, str):
896
        # TODO: jam 20070209 This is overkill, and probably has an impact on
897
        #       performance if we are dealing with lots of apis that want a
898
        #       utf-8 revision id
899
        try:
900
            # Make sure it is a valid utf-8 string
901
            unicode_or_utf8_string.decode('utf-8')
902
        except UnicodeDecodeError:
903
            raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
904
        return unicode_or_utf8_string
905
    return unicode_or_utf8_string.encode('utf-8')
906
907
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
908
_revision_id_warning = ('Unicode revision ids were deprecated in bzr 0.15.'
909
                        ' Revision id generators should be creating utf8'
910
                        ' revision ids.')
911
912
913
def safe_revision_id(unicode_or_utf8_string, warn=True):
2249.5.8 by John Arbash Meinel
Add osutils.safe_utf8 and safe_revision_id for the new revision_id work.
914
    """Revision ids should now be utf8, but at one point they were unicode.
915
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
916
    :param unicode_or_utf8_string: A possibly Unicode revision_id. (can also be
917
        utf8 or None).
918
    :param warn: Functions that are sanitizing user data can set warn=False
919
    :return: None or a utf8 revision id.
2249.5.8 by John Arbash Meinel
Add osutils.safe_utf8 and safe_revision_id for the new revision_id work.
920
    """
2309.4.3 by John Arbash Meinel
(broken) change safe_*_id to emit a warning.
921
    if (unicode_or_utf8_string is None
922
        or unicode_or_utf8_string.__class__ == str):
923
        return unicode_or_utf8_string
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
924
    if warn:
925
        symbol_versioning.warn(_revision_id_warning, DeprecationWarning,
926
                               stacklevel=2)
2309.4.3 by John Arbash Meinel
(broken) change safe_*_id to emit a warning.
927
    return cache_utf8.encode(unicode_or_utf8_string)
928
929
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
930
_file_id_warning = ('Unicode file ids were deprecated in bzr 0.15. File id'
931
                    ' generators should be creating utf8 file ids.')
932
933
934
def safe_file_id(unicode_or_utf8_string, warn=True):
2309.4.3 by John Arbash Meinel
(broken) change safe_*_id to emit a warning.
935
    """File ids should now be utf8, but at one point they were unicode.
936
937
    This is the same as safe_utf8, except it uses the cached encode functions
938
    to save a little bit of performance.
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
939
940
    :param unicode_or_utf8_string: A possibly Unicode file_id. (can also be
941
        utf8 or None).
942
    :param warn: Functions that are sanitizing user data can set warn=False
943
    :return: None or a utf8 file id.
2309.4.3 by John Arbash Meinel
(broken) change safe_*_id to emit a warning.
944
    """
945
    if (unicode_or_utf8_string is None
946
        or unicode_or_utf8_string.__class__ == str):
947
        return unicode_or_utf8_string
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
948
    if warn:
949
        symbol_versioning.warn(_file_id_warning, DeprecationWarning,
950
                               stacklevel=2)
2309.4.3 by John Arbash Meinel
(broken) change safe_*_id to emit a warning.
951
    return cache_utf8.encode(unicode_or_utf8_string)
2294.1.4 by John Arbash Meinel
Add safe_file_id as a helper in osutils.
952
953
1185.85.75 by John Arbash Meinel
Adding bzrlib.osutils.unicode_filename to handle unicode normalization for file paths.
954
_platform_normalizes_filenames = False
955
if sys.platform == 'darwin':
956
    _platform_normalizes_filenames = True
957
958
959
def normalizes_filenames():
960
    """Return True if this platform normalizes unicode filenames.
961
962
    Mac OSX does, Windows/Linux do not.
963
    """
964
    return _platform_normalizes_filenames
965
966
1830.3.2 by John Arbash Meinel
normalized_filename is a much better name
967
def _accessible_normalized_filename(path):
1830.3.1 by John Arbash Meinel
Change the return value of unicode_filename, and make it testable on all platforms
968
    """Get the unicode normalized path, and if you can access the file.
969
970
    On platforms where the system normalizes filenames (Mac OSX),
971
    you can access a file by any path which will normalize correctly.
972
    On platforms where the system does not normalize filenames 
973
    (Windows, Linux), you have to access a file by its exact path.
974
975
    Internally, bzr only supports NFC/NFKC normalization, since that is 
976
    the standard for XML documents.
977
978
    So return the normalized path, and a flag indicating if the file
979
    can be accessed by that path.
980
    """
981
1830.3.8 by John Arbash Meinel
unicodedata.normalize requires unicode strings
982
    return unicodedata.normalize('NFKC', unicode(path)), True
1830.3.1 by John Arbash Meinel
Change the return value of unicode_filename, and make it testable on all platforms
983
984
1830.3.2 by John Arbash Meinel
normalized_filename is a much better name
985
def _inaccessible_normalized_filename(path):
986
    __doc__ = _accessible_normalized_filename.__doc__
1830.3.1 by John Arbash Meinel
Change the return value of unicode_filename, and make it testable on all platforms
987
1830.3.8 by John Arbash Meinel
unicodedata.normalize requires unicode strings
988
    normalized = unicodedata.normalize('NFKC', unicode(path))
1830.3.1 by John Arbash Meinel
Change the return value of unicode_filename, and make it testable on all platforms
989
    return normalized, normalized == path
990
991
1185.85.75 by John Arbash Meinel
Adding bzrlib.osutils.unicode_filename to handle unicode normalization for file paths.
992
if _platform_normalizes_filenames:
1830.3.2 by John Arbash Meinel
normalized_filename is a much better name
993
    normalized_filename = _accessible_normalized_filename
1185.85.75 by John Arbash Meinel
Adding bzrlib.osutils.unicode_filename to handle unicode normalization for file paths.
994
else:
1830.3.2 by John Arbash Meinel
normalized_filename is a much better name
995
    normalized_filename = _inaccessible_normalized_filename
1185.85.75 by John Arbash Meinel
Adding bzrlib.osutils.unicode_filename to handle unicode normalization for file paths.
996
997
1185.33.60 by Martin Pool
Use full terminal width for verbose test output.
998
def terminal_width():
999
    """Return estimated terminal width."""
1704.2.3 by Martin Pool
(win32) Detect terminal width using GetConsoleScreenBufferInfo (Alexander)
1000
    if sys.platform == 'win32':
2245.4.6 by Alexander Belchenko
osutils.py: terminal_width() now use win32utils.get_console_size()
1001
        return win32utils.get_console_size()[0]
1704.2.2 by Martin Pool
Detect terminal width using ioctl
1002
    width = 0
1185.33.60 by Martin Pool
Use full terminal width for verbose test output.
1003
    try:
1704.2.2 by Martin Pool
Detect terminal width using ioctl
1004
        import struct, fcntl, termios
1005
        s = struct.pack('HHHH', 0, 0, 0, 0)
1006
        x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
1007
        width = struct.unpack('HHHH', x)[1]
1008
    except IOError:
1009
        pass
1010
    if width <= 0:
1011
        try:
1012
            width = int(os.environ['COLUMNS'])
1013
        except:
1014
            pass
1015
    if width <= 0:
1016
        width = 80
1017
1018
    return width
1534.7.25 by Aaron Bentley
Added set_executability
1019
1963.1.5 by John Arbash Meinel
Create an osutils helper function for modifying the environment
1020
1534.7.25 by Aaron Bentley
Added set_executability
1021
def supports_executable():
1534.7.160 by Aaron Bentley
Changed implementation of supports_executable
1022
    return sys.platform != "win32"
1551.2.53 by abentley
Strip trailing slashes in a platform-sensible way
1023
1024
1551.10.4 by Aaron Bentley
Update to skip on win32
1025
def supports_posix_readonly():
1026
    """Return True if 'readonly' has POSIX semantics, False otherwise.
1027
1028
    Notably, a win32 readonly file cannot be deleted, unlike POSIX where the
1029
    directory controls creation/deletion, etc.
1030
1031
    And under win32, readonly means that the directory itself cannot be
1032
    deleted.  The contents of a readonly directory can be changed, unlike POSIX
1033
    where files in readonly directories cannot be added, deleted or renamed.
1034
    """
1035
    return sys.platform != "win32"
1036
1037
1963.1.5 by John Arbash Meinel
Create an osutils helper function for modifying the environment
1038
def set_or_unset_env(env_variable, value):
1039
    """Modify the environment, setting or removing the env_variable.
1040
1041
    :param env_variable: The environment variable in question
1042
    :param value: The value to set the environment to. If None, then
1043
        the variable will be removed.
1044
    :return: The original value of the environment variable.
1045
    """
1046
    orig_val = os.environ.get(env_variable)
1047
    if value is None:
1048
        if orig_val is not None:
1049
            del os.environ[env_variable]
1050
    else:
1051
        if isinstance(value, unicode):
1052
            value = value.encode(bzrlib.user_encoding)
1053
        os.environ[env_variable] = value
1054
    return orig_val
1055
1056
1551.2.56 by Aaron Bentley
Better illegal pathname check for Windows
1057
_validWin32PathRE = re.compile(r'^([A-Za-z]:[/\\])?[^:<>*"?\|]*$')
1058
1059
1060
def check_legal_path(path):
1061
    """Check whether the supplied path is legal.  
1062
    This is only required on Windows, so we don't test on other platforms
1063
    right now.
1064
    """
1065
    if sys.platform != "win32":
1066
        return
1067
    if _validWin32PathRE.match(path) is None:
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
1068
        raise errors.IllegalPath(path)
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1069
1070
1757.2.8 by Robert Collins
Teach walkdirs to walk a subdir of a tree.
1071
def walkdirs(top, prefix=""):
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1072
    """Yield data about all the directories in a tree.
1073
    
1074
    This yields all the data about the contents of a directory at a time.
1075
    After each directory has been yielded, if the caller has mutated the list
1076
    to exclude some directories, they are then not descended into.
1077
    
1078
    The data yielded is of the form:
1897.1.2 by Robert Collins
cleanup osutils.walkdirs changes after review.
1079
    ((directory-relpath, directory-path-from-top),
2255.7.26 by John Arbash Meinel
correct the docstring for walkdirs.
1080
    [(directory-relpath, basename, kind, lstat, path-from-top), ...]),
1897.1.2 by Robert Collins
cleanup osutils.walkdirs changes after review.
1081
     - directory-relpath is the relative path of the directory being returned
1082
       with respect to top. prefix is prepended to this.
1083
     - directory-path-from-root is the path including top for this directory. 
1084
       It is suitable for use with os functions.
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
1085
     - relpath is the relative path within the subtree being walked.
1086
     - basename is the basename of the path
1897.1.2 by Robert Collins
cleanup osutils.walkdirs changes after review.
1087
     - kind is the kind of the file now. If unknown then the file is not
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
1088
       present within the tree - but it may be recorded as versioned. See
1089
       versioned_kind.
1090
     - lstat is the stat data *if* the file was statted.
1091
     - planned, not implemented: 
1092
       path_from_tree_root is the path from the root of the tree.
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1093
1757.2.16 by Robert Collins
Review comments.
1094
    :param prefix: Prefix the relpaths that are yielded with 'prefix'. This 
1095
        allows one to walk a subtree but get paths that are relative to a tree
1096
        rooted higher up.
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1097
    :return: an iterator over the dirs.
1098
    """
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
1099
    #TODO there is a bit of a smell where the results of the directory-
1100
    # summary in this, and the path from the root, may not agree 
1101
    # depending on top and prefix - i.e. ./foo and foo as a pair leads to
1102
    # potentially confusing output. We should make this more robust - but
1897.1.2 by Robert Collins
cleanup osutils.walkdirs changes after review.
1103
    # not at a speed cost. RBC 20060731
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1104
    _lstat = os.lstat
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1105
    _directory = _directory_kind
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
1106
    _listdir = os.listdir
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1107
    _kind_from_mode = _formats.get
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1108
    pending = [(safe_unicode(prefix), "", _directory, None, safe_unicode(top))]
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1109
    while pending:
1110
        # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1111
        relroot, _, _, _, top = pending.pop()
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1112
        if relroot:
1113
            relprefix = relroot + u'/'
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1114
        else:
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1115
            relprefix = ''
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1116
        top_slash = top + u'/'
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1117
1118
        dirblock = []
1119
        append = dirblock.append
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1120
        for name in sorted(_listdir(top)):
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1121
            abspath = top_slash + name
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1122
            statvalue = _lstat(abspath)
1123
            kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
1124
            append((relprefix + name, name, kind, statvalue, abspath))
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1125
        yield (relroot, top), dirblock
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1126
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1127
        # push the user specified dirs from dirblock
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1128
        pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1773.3.1 by Robert Collins
Add path_prefix_key and compare_paths_prefix_order utility functions.
1129
1130
2255.7.27 by John Arbash Meinel
Add a _walkdirs_utf8 which returns utf8 paths instead of Unicode. Approx 20% faster in walking utf8 filesystems
1131
def _walkdirs_utf8(top, prefix=""):
1132
    """Yield data about all the directories in a tree.
1133
1134
    This yields the same information as walkdirs() only each entry is yielded
1135
    in utf-8. On platforms which have a filesystem encoding of utf8 the paths
1136
    are returned as exact byte-strings.
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1137
1138
    :return: yields a tuple of (dir_info, [file_info])
1139
        dir_info is (utf8_relpath, path-from-top)
1140
        file_info is (utf8_relpath, utf8_name, kind, lstat, path-from-top)
1141
        if top is an absolute path, path-from-top is also an absolute path.
1142
        path-from-top might be unicode or utf8, but it is the correct path to
1143
        pass to os functions to affect the file in question. (such as os.lstat)
1144
    """
1145
    fs_encoding = sys.getfilesystemencoding()
1146
    if (sys.platform == 'win32' or
1147
        fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968')): # ascii
1148
        return _walkdirs_unicode_to_utf8(top, prefix=prefix)
1149
    else:
1150
        return _walkdirs_fs_utf8(top, prefix=prefix)
1151
1152
1153
def _walkdirs_fs_utf8(top, prefix=""):
1154
    """See _walkdirs_utf8.
1155
1156
    This sub-function is called when we know the filesystem is already in utf8
1157
    encoding. So we don't need to transcode filenames.
2255.7.27 by John Arbash Meinel
Add a _walkdirs_utf8 which returns utf8 paths instead of Unicode. Approx 20% faster in walking utf8 filesystems
1158
    """
1159
    _lstat = os.lstat
1160
    _directory = _directory_kind
1161
    _listdir = os.listdir
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1162
    _kind_from_mode = _formats.get
2255.7.27 by John Arbash Meinel
Add a _walkdirs_utf8 which returns utf8 paths instead of Unicode. Approx 20% faster in walking utf8 filesystems
1163
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1164
    # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1165
    # But we don't actually uses 1-3 in pending, so set them to None
1166
    pending = [(safe_utf8(prefix), None, None, None, safe_utf8(top))]
2255.7.27 by John Arbash Meinel
Add a _walkdirs_utf8 which returns utf8 paths instead of Unicode. Approx 20% faster in walking utf8 filesystems
1167
    while pending:
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1168
        relroot, _, _, _, top = pending.pop()
1169
        if relroot:
1170
            relprefix = relroot + '/'
2255.7.27 by John Arbash Meinel
Add a _walkdirs_utf8 which returns utf8 paths instead of Unicode. Approx 20% faster in walking utf8 filesystems
1171
        else:
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1172
            relprefix = ''
2255.7.27 by John Arbash Meinel
Add a _walkdirs_utf8 which returns utf8 paths instead of Unicode. Approx 20% faster in walking utf8 filesystems
1173
        top_slash = top + '/'
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1174
2255.7.27 by John Arbash Meinel
Add a _walkdirs_utf8 which returns utf8 paths instead of Unicode. Approx 20% faster in walking utf8 filesystems
1175
        dirblock = []
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1176
        append = dirblock.append
2255.7.27 by John Arbash Meinel
Add a _walkdirs_utf8 which returns utf8 paths instead of Unicode. Approx 20% faster in walking utf8 filesystems
1177
        for name in sorted(_listdir(top)):
1178
            abspath = top_slash + name
1179
            statvalue = _lstat(abspath)
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1180
            kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
1181
            append((relprefix + name, name, kind, statvalue, abspath))
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1182
        yield (relroot, top), dirblock
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1183
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1184
        # push the user specified dirs from dirblock
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1185
        pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1186
1187
1188
def _walkdirs_unicode_to_utf8(top, prefix=""):
1189
    """See _walkdirs_utf8
1190
1191
    Because Win32 has a Unicode api, all of the 'path-from-top' entries will be
1192
    Unicode paths.
1193
    This is currently the fallback code path when the filesystem encoding is
1194
    not UTF-8. It may be better to implement an alternative so that we can
1195
    safely handle paths that are not properly decodable in the current
1196
    encoding.
1197
    """
1198
    _utf8_encode = codecs.getencoder('utf8')
1199
    _lstat = os.lstat
1200
    _directory = _directory_kind
1201
    _listdir = os.listdir
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1202
    _kind_from_mode = _formats.get
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1203
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1204
    pending = [(safe_utf8(prefix), None, None, None, safe_unicode(top))]
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1205
    while pending:
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1206
        relroot, _, _, _, top = pending.pop()
1207
        if relroot:
1208
            relprefix = relroot + '/'
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1209
        else:
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1210
            relprefix = ''
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1211
        top_slash = top + u'/'
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1212
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1213
        dirblock = []
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1214
        append = dirblock.append
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1215
        for name in sorted(_listdir(top)):
1216
            name_utf8 = _utf8_encode(name)[0]
1217
            abspath = top_slash + name
1218
            statvalue = _lstat(abspath)
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1219
            kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
1220
            append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
2255.7.27 by John Arbash Meinel
Add a _walkdirs_utf8 which returns utf8 paths instead of Unicode. Approx 20% faster in walking utf8 filesystems
1221
        yield (relroot, top), dirblock
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1222
2255.7.27 by John Arbash Meinel
Add a _walkdirs_utf8 which returns utf8 paths instead of Unicode. Approx 20% faster in walking utf8 filesystems
1223
        # push the user specified dirs from dirblock
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1224
        pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
2255.7.27 by John Arbash Meinel
Add a _walkdirs_utf8 which returns utf8 paths instead of Unicode. Approx 20% faster in walking utf8 filesystems
1225
1226
1907.3.2 by John Arbash Meinel
Updated the copy_tree function to allow overriding functionality.
1227
def copy_tree(from_path, to_path, handlers={}):
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1228
    """Copy all of the entries in from_path into to_path.
1229
1230
    :param from_path: The base directory to copy. 
1231
    :param to_path: The target directory. If it does not exist, it will
1232
        be created.
1907.3.2 by John Arbash Meinel
Updated the copy_tree function to allow overriding functionality.
1233
    :param handlers: A dictionary of functions, which takes a source and
1234
        destinations for files, directories, etc.
1235
        It is keyed on the file kind, such as 'directory', 'symlink', or 'file'
1236
        'file', 'directory', and 'symlink' should always exist.
1237
        If they are missing, they will be replaced with 'os.mkdir()',
1238
        'os.readlink() + os.symlink()', and 'shutil.copy2()', respectively.
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1239
    """
1240
    # Now, just copy the existing cached tree to the new location
1241
    # We use a cheap trick here.
1242
    # Absolute paths are prefixed with the first parameter
1243
    # relative paths are prefixed with the second.
1244
    # So we can get both the source and target returned
1245
    # without any extra work.
1246
1907.3.2 by John Arbash Meinel
Updated the copy_tree function to allow overriding functionality.
1247
    def copy_dir(source, dest):
1248
        os.mkdir(dest)
1249
1250
    def copy_link(source, dest):
1251
        """Copy the contents of a symlink"""
1252
        link_to = os.readlink(source)
1253
        os.symlink(link_to, dest)
1254
1255
    real_handlers = {'file':shutil.copy2,
1256
                     'symlink':copy_link,
1257
                     'directory':copy_dir,
1258
                    }
1259
    real_handlers.update(handlers)
1260
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1261
    if not os.path.exists(to_path):
1907.3.2 by John Arbash Meinel
Updated the copy_tree function to allow overriding functionality.
1262
        real_handlers['directory'](from_path, to_path)
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1263
1264
    for dir_info, entries in walkdirs(from_path, prefix=to_path):
1265
        for relpath, name, kind, st, abspath in entries:
1907.3.2 by John Arbash Meinel
Updated the copy_tree function to allow overriding functionality.
1266
            real_handlers[kind](abspath, relpath)
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1267
1268
1773.3.1 by Robert Collins
Add path_prefix_key and compare_paths_prefix_order utility functions.
1269
def path_prefix_key(path):
1270
    """Generate a prefix-order path key for path.
1271
1272
    This can be used to sort paths in the same way that walkdirs does.
1273
    """
1773.3.2 by Robert Collins
New corner case from John Meinel, showing up the need to check the directory lexographically outside of a single tree's root. Fixed.
1274
    return (dirname(path) , path)
1773.3.1 by Robert Collins
Add path_prefix_key and compare_paths_prefix_order utility functions.
1275
1276
1277
def compare_paths_prefix_order(path_a, path_b):
1278
    """Compare path_a and path_b to generate the same order walkdirs uses."""
1279
    key_a = path_prefix_key(path_a)
1280
    key_b = path_prefix_key(path_b)
1281
    return cmp(key_a, key_b)
1955.2.2 by John Arbash Meinel
Change the name of the test classes (test_lang => test_locale), move the function into osutils.py
1282
1283
1284
_cached_user_encoding = None
1285
1286
2192.1.3 by Alexander Belchenko
Tests for osutils.get_user_encoding
1287
def get_user_encoding(use_cache=True):
1955.2.2 by John Arbash Meinel
Change the name of the test classes (test_lang => test_locale), move the function into osutils.py
1288
    """Find out what the preferred user encoding is.
1289
1290
    This is generally the encoding that is used for command line parameters
1291
    and file contents. This may be different from the terminal encoding
1292
    or the filesystem encoding.
1293
2192.1.3 by Alexander Belchenko
Tests for osutils.get_user_encoding
1294
    :param  use_cache:  Enable cache for detected encoding.
1295
                        (This parameter is turned on by default,
1296
                        and required only for selftesting)
1297
1955.2.2 by John Arbash Meinel
Change the name of the test classes (test_lang => test_locale), move the function into osutils.py
1298
    :return: A string defining the preferred user encoding
1299
    """
1300
    global _cached_user_encoding
2192.1.3 by Alexander Belchenko
Tests for osutils.get_user_encoding
1301
    if _cached_user_encoding is not None and use_cache:
1955.2.2 by John Arbash Meinel
Change the name of the test classes (test_lang => test_locale), move the function into osutils.py
1302
        return _cached_user_encoding
1303
1304
    if sys.platform == 'darwin':
1305
        # work around egregious python 2.4 bug
1306
        sys.platform = 'posix'
1307
        try:
1308
            import locale
1309
        finally:
1310
            sys.platform = 'darwin'
1311
    else:
1312
        import locale
1313
1314
    try:
2192.1.3 by Alexander Belchenko
Tests for osutils.get_user_encoding
1315
        user_encoding = locale.getpreferredencoding()
1955.2.2 by John Arbash Meinel
Change the name of the test classes (test_lang => test_locale), move the function into osutils.py
1316
    except locale.Error, e:
1955.2.3 by John Arbash Meinel
Change error message text
1317
        sys.stderr.write('bzr: warning: %s\n'
2001.2.1 by Jelmer Vernooij
Fix typo in encoding warning.
1318
                         '  Could not determine what text encoding to use.\n'
1955.2.3 by John Arbash Meinel
Change error message text
1319
                         '  This error usually means your Python interpreter\n'
1320
                         '  doesn\'t support the locale set by $LANG (%s)\n'
1321
                         "  Continuing with ascii encoding.\n"
1955.2.2 by John Arbash Meinel
Change the name of the test classes (test_lang => test_locale), move the function into osutils.py
1322
                         % (e, os.environ.get('LANG')))
2192.1.7 by Alexander Belchenko
get_user_encoding: if locale.Error raised we need to set user_encoding to 'ascii' as warning says
1323
        user_encoding = 'ascii'
1955.2.2 by John Arbash Meinel
Change the name of the test classes (test_lang => test_locale), move the function into osutils.py
1324
2127.4.1 by Alexander Belchenko
(jam, bialix) Workaround for cp0 console encoding on Windows
1325
    # Windows returns 'cp0' to indicate there is no code page. So we'll just
1326
    # treat that as ASCII, and not support printing unicode characters to the
1327
    # console.
2192.1.3 by Alexander Belchenko
Tests for osutils.get_user_encoding
1328
    if user_encoding in (None, 'cp0'):
1329
        user_encoding = 'ascii'
2192.1.1 by Alexander Belchenko
Before actually using encoding need to check that Python has corresponding codec
1330
    else:
1331
        # check encoding
1332
        try:
2192.1.3 by Alexander Belchenko
Tests for osutils.get_user_encoding
1333
            codecs.lookup(user_encoding)
2192.1.1 by Alexander Belchenko
Before actually using encoding need to check that Python has corresponding codec
1334
        except LookupError:
1335
            sys.stderr.write('bzr: warning:'
1336
                             ' unknown encoding %s.'
1337
                             ' Continuing with ascii encoding.\n'
2192.1.3 by Alexander Belchenko
Tests for osutils.get_user_encoding
1338
                             % user_encoding
2192.1.1 by Alexander Belchenko
Before actually using encoding need to check that Python has corresponding codec
1339
                            )
2192.1.3 by Alexander Belchenko
Tests for osutils.get_user_encoding
1340
            user_encoding = 'ascii'
1341
1342
    if use_cache:
1343
        _cached_user_encoding = user_encoding
1344
1345
    return user_encoding
2091.1.1 by Martin Pool
Avoid MSG_WAITALL as it doesn't work on Windows
1346
1347
1348
def recv_all(socket, bytes):
1349
    """Receive an exact number of bytes.
1350
1351
    Regular Socket.recv() may return less than the requested number of bytes,
1352
    dependning on what's in the OS buffer.  MSG_WAITALL is not available
1353
    on all platforms, but this should work everywhere.  This will return
1354
    less than the requested amount if the remote end closes.
1355
1356
    This isn't optimized and is intended mostly for use in testing.
1357
    """
1358
    b = ''
1359
    while len(b) < bytes:
1360
        new = socket.recv(bytes - len(b))
1361
        if new == '':
1362
            break # eof
1363
        b += new
1364
    return b
1365
2091.3.7 by Aaron Bentley
Rename real_parent to dereferenced_path
1366
def dereference_path(path):
1367
    """Determine the real path to a file.
1368
1369
    All parent elements are dereferenced.  But the file itself is not
1370
    dereferenced.
1371
    :param path: The original path.  May be absolute or relative.
1372
    :return: the real path *to* the file
1373
    """
2091.3.5 by Aaron Bentley
Move realpath functionality into osutils
1374
    parent, base = os.path.split(path)
1375
    # The pathjoin for '.' is a workaround for Python bug #1213894.
1376
    # (initial path components aren't dereferenced)
1377
    return pathjoin(realpath(pathjoin('.', parent)), base)