/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
4183.6.4 by Martin Pool
Separate out re_compile_checked
1
# Copyright (C) 2005, 2006, 2007, 2009 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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1 by mbp at sourcefrog
import from baz patch-364
16
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
17
import os
18
import re
19
import stat
20
from stat import (S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE,
21
                  S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
22
import sys
23
import time
4574.3.2 by Martin Pool
Change back to python warnings for failure to load extensions
24
import warnings
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
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
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
38
import shutil
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
39
from shutil import (
40
    rmtree,
41
    )
4398.4.3 by Vincent Ladeuil
Detect # cores on win32 and Solaris too.
42
import subprocess
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
3734.2.4 by Vincent Ladeuil
Fix python2.6 deprecation warnings related to hashlib.
56
# sha and md5 modules are deprecated in python2.6 but hashlib is available as
57
# of 2.5
2929.3.1 by Vincent Ladeuil
Fix python2.6 deprecation warnings (still 4 failures 5 errors in test suite).
58
if sys.version_info < (2, 5):
3734.5.2 by Vincent Ladeuil
Martin's review feedback.
59
    import md5 as _mod_md5
60
    md5 = _mod_md5.new
61
    import sha as _mod_sha
62
    sha = _mod_sha.new
2929.3.1 by Vincent Ladeuil
Fix python2.6 deprecation warnings (still 4 failures 5 errors in test suite).
63
else:
64
    from hashlib import (
65
        md5,
66
        sha1 as sha,
67
        )
68
3504.4.1 by John Arbash Meinel
Write an alternative 'walkdirs' implementation that uses win32 apis.
69
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
70
import bzrlib
2309.4.3 by John Arbash Meinel
(broken) change safe_*_id to emit a warning.
71
from bzrlib import symbol_versioning
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
72
1 by mbp at sourcefrog
import from baz patch-364
73
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
74
# On win32, O_BINARY is used to indicate the file should
75
# be opened in binary mode, rather than text mode.
76
# On other platforms, O_BINARY doesn't exist, because
77
# they always open in binary mode, so it is okay to
78
# OR with 0 on those platforms
79
O_BINARY = getattr(os, 'O_BINARY', 0)
80
81
4355.2.2 by Alexander Belchenko
osutils.py: get_unicode_argv function (to obtain unicode command line arguments from sys.argv) moved to the beginning of module based on suggestions from review of John Meinel.
82
def get_unicode_argv():
83
    try:
84
        user_encoding = get_user_encoding()
85
        return [a.decode(user_encoding) for a in sys.argv[1:]]
86
    except UnicodeDecodeError:
87
        raise errors.BzrError(("Parameter '%r' is unsupported by the current "
88
                                                            "encoding." % a))
89
90
1 by mbp at sourcefrog
import from baz patch-364
91
def make_readonly(filename):
92
    """Make a filename read-only."""
2949.6.1 by Alexander Belchenko
windows python has os.lstat
93
    mod = os.lstat(filename).st_mode
2568.1.1 by John Arbash Meinel
(Elliot Murphy) Use os.lstat rather than os.stat for osutils.make_readonly/make_writeable
94
    if not stat.S_ISLNK(mod):
95
        mod = mod & 0777555
96
        os.chmod(filename, mod)
1 by mbp at sourcefrog
import from baz patch-364
97
98
99
def make_writable(filename):
2949.6.1 by Alexander Belchenko
windows python has os.lstat
100
    mod = os.lstat(filename).st_mode
2568.1.1 by John Arbash Meinel
(Elliot Murphy) Use os.lstat rather than os.stat for osutils.make_readonly/make_writeable
101
    if not stat.S_ISLNK(mod):
102
        mod = mod | 0200
103
        os.chmod(filename, mod)
1 by mbp at sourcefrog
import from baz patch-364
104
105
2825.7.1 by Robert Collins
* Partial commits are now approximately 40% faster by walking over the
106
def minimum_path_selection(paths):
107
    """Return the smallset subset of paths which are outside paths.
108
2843.1.1 by Ian Clatworthy
Faster partial commits by walking less data (Robert Collins)
109
    :param paths: A container (and hence not None) of paths.
2825.7.1 by Robert Collins
* Partial commits are now approximately 40% faster by walking over the
110
    :return: A set of paths sufficient to include everything in paths via
4325.3.3 by Johan Walles
Add unit test and fix for minimum_path_selection() vs directory names with
111
        is_inside, drawn from the paths parameter.
2825.7.1 by Robert Collins
* Partial commits are now approximately 40% faster by walking over the
112
    """
4325.3.7 by Johan Walles
Style fixes for minimum_path_selection().
113
    if len(paths) < 2:
114
        return set(paths)
4325.3.3 by Johan Walles
Add unit test and fix for minimum_path_selection() vs directory names with
115
116
    def sort_key(path):
117
        return path.split('/')
118
    sorted_paths = sorted(list(paths), key=sort_key)
119
4325.3.7 by Johan Walles
Style fixes for minimum_path_selection().
120
    search_paths = [sorted_paths[0]]
121
    for path in sorted_paths[1:]:
4325.3.2 by Johan Walles
Use a linear algorithm for osutil.minimum_path_selection().
122
        if not is_inside(search_paths[-1], path):
123
            # This path is unique, add it
124
            search_paths.append(path)
4325.3.7 by Johan Walles
Style fixes for minimum_path_selection().
125
4325.3.2 by Johan Walles
Use a linear algorithm for osutil.minimum_path_selection().
126
    return set(search_paths)
2825.7.1 by Robert Collins
* Partial commits are now approximately 40% faster by walking over the
127
128
1077 by Martin Pool
- avoid compiling REs at module load time
129
_QUOTE_RE = None
969 by Martin Pool
- Add less-sucky is_within_any
130
131
1 by mbp at sourcefrog
import from baz patch-364
132
def quotefn(f):
779 by Martin Pool
- better quotefn for windows: use doublequotes for strings with
133
    """Return a quoted filename filename
134
135
    This previously used backslash quoting, but that works poorly on
136
    Windows."""
137
    # TODO: I'm not really sure this is the best format either.x
1077 by Martin Pool
- avoid compiling REs at module load time
138
    global _QUOTE_RE
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
139
    if _QUOTE_RE is None:
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
140
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
141
779 by Martin Pool
- better quotefn for windows: use doublequotes for strings with
142
    if _QUOTE_RE.search(f):
143
        return '"' + f + '"'
144
    else:
145
        return f
1 by mbp at sourcefrog
import from baz patch-364
146
147
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
148
_directory_kind = 'directory'
149
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
150
def get_umask():
151
    """Return the current umask"""
152
    # Assume that people aren't messing with the umask while running
153
    # XXX: This is not thread safe, but there is no way to get the
154
    #      umask without setting it
155
    umask = os.umask(0)
156
    os.umask(umask)
157
    return umask
158
159
2324.2.1 by Dmitry Vasiliev
kind_marker() optimization
160
_kind_marker_map = {
161
    "file": "",
162
    _directory_kind: "/",
163
    "symlink": "@",
1551.10.30 by Aaron Bentley
Merge from bzr.dev
164
    'tree-reference': '+',
2324.2.1 by Dmitry Vasiliev
kind_marker() optimization
165
}
1551.10.30 by Aaron Bentley
Merge from bzr.dev
166
167
488 by Martin Pool
- new helper function kind_marker()
168
def kind_marker(kind):
2324.2.1 by Dmitry Vasiliev
kind_marker() optimization
169
    try:
170
        return _kind_marker_map[kind]
171
    except KeyError:
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
172
        raise errors.BzrError('invalid file kind %r' % kind)
1 by mbp at sourcefrog
import from baz patch-364
173
2324.2.1 by Dmitry Vasiliev
kind_marker() optimization
174
1732.1.2 by John Arbash Meinel
just use os.path.lexists if it exists
175
lexists = getattr(os.path, 'lexists', None)
176
if lexists is None:
177
    def lexists(f):
178
        try:
2324.2.2 by Dmitry Vasiliev
Fixed lexists() implementation
179
            stat = getattr(os, 'lstat', os.stat)
180
            stat(f)
1732.1.2 by John Arbash Meinel
just use os.path.lexists if it exists
181
            return True
2324.2.2 by Dmitry Vasiliev
Fixed lexists() implementation
182
        except OSError, e:
1732.1.2 by John Arbash Meinel
just use os.path.lexists if it exists
183
            if e.errno == errno.ENOENT:
184
                return False;
185
            else:
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
186
                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
187
1 by mbp at sourcefrog
import from baz patch-364
188
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
189
def fancy_rename(old, new, rename_func, unlink_func):
190
    """A fancy rename, when you don't have atomic rename.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
191
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
192
    :param old: The old path, to rename from
193
    :param new: The new path, to rename to
194
    :param rename_func: The potentially non-atomic rename function
195
    :param unlink_func: A way to delete the target file if the full rename succeeds
196
    """
197
198
    # sftp rename doesn't allow overwriting, so play tricks:
199
    base = os.path.basename(new)
200
    dirname = os.path.dirname(new)
1553.5.22 by Martin Pool
Change fancy_rename to use rand_chars rather than reinvent it.
201
    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.
202
    tmp_name = pathjoin(dirname, tmp_name)
203
204
    # Rename the file out of the way, but keep track if it didn't exist
205
    # We don't want to grab just any exception
206
    # something like EACCES should prevent us from continuing
207
    # The downside is that the rename_func has to throw an exception
208
    # with an errno = ENOENT, or NoSuchFile
209
    file_existed = False
210
    try:
211
        rename_func(new, tmp_name)
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
212
    except (errors.NoSuchFile,), e:
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
213
        pass
1532 by Robert Collins
Merge in John Meinels integration branch.
214
    except IOError, e:
215
        # 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'.
216
        # function raises an IOError with errno is None when a rename fails.
1532 by Robert Collins
Merge in John Meinels integration branch.
217
        # This then gets caught here.
1185.50.37 by John Arbash Meinel
Fixed exception handling for fancy_rename
218
        if e.errno not in (None, errno.ENOENT, errno.ENOTDIR):
1532 by Robert Collins
Merge in John Meinels integration branch.
219
            raise
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
220
    except Exception, e:
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
221
        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.
222
            or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
223
            raise
224
    else:
225
        file_existed = True
226
227
    success = False
228
    try:
2978.8.2 by Alexander Belchenko
teach fancy_rename to handle change case renames in possible case-insensitive filesystem
229
        try:
230
            # This may throw an exception, in which case success will
231
            # not be set.
232
            rename_func(old, new)
233
            success = True
234
        except (IOError, OSError), e:
2978.8.3 by Alexander Belchenko
Aaron's review
235
            # source and target may be aliases of each other (e.g. on a
236
            # case-insensitive filesystem), so we may have accidentally renamed
237
            # source by when we tried to rename target
2978.8.4 by Alexander Belchenko
fancy_rename: lower() test removed.
238
            if not (file_existed and e.errno in (None, errno.ENOENT)):
2978.8.2 by Alexander Belchenko
teach fancy_rename to handle change case renames in possible case-insensitive filesystem
239
                raise
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
240
    finally:
241
        if file_existed:
242
            # If the file used to exist, rename it back into place
243
            # otherwise just delete it from the tmp location
244
            if success:
1551.15.4 by Aaron Bentley
Revert now-unnecessary changes
245
                unlink_func(tmp_name)
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
246
            else:
1185.31.49 by John Arbash Meinel
Some corrections using the new osutils.rename. **ALL TESTS PASS**
247
                rename_func(tmp_name, new)
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
248
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
249
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
250
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
251
# choke on a Unicode string containing a relative path if
252
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
253
# string.
2093.1.1 by John Arbash Meinel
(Bart Teeuwisse) if sys.getfilesystemencoding() is None, use 'utf-8'
254
_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
255
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
256
    # jam 20060426 rather than encoding to fsencoding
257
    # copy posixpath.abspath, but use os.getcwdu instead
258
    if not posixpath.isabs(path):
259
        path = posixpath.join(getcwd(), path)
260
    return posixpath.normpath(path)
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
261
262
263
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
264
    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
265
266
1711.5.2 by John Arbash Meinel
win32 likes to return lowercase drive letters sometimes, and uppercase at other times. normalize this
267
def _win32_fixdrive(path):
268
    """Force drive letters to be consistent.
269
270
    win32 is inconsistent whether it returns lower or upper case
271
    and even if it was consistent the user might type the other
272
    so we force it to uppercase
273
    running python.exe under cmd.exe return capital C:\\
274
    running win32 python inside a cygwin shell returns lowercase c:\\
275
    """
276
    drive, path = _nt_splitdrive(path)
277
    return drive.upper() + path
278
279
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
280
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'
281
    # 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
282
    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
283
284
2279.4.1 by Alexander Belchenko
Reimplementation of ntpath.abspath in Python for Windows98: unicode safe, UNC path safe
285
def _win98_abspath(path):
286
    """Return the absolute version of a path.
287
    Windows 98 safe implementation (python reimplementation
288
    of Win32 API function GetFullPathNameW)
289
    """
290
    # Corner cases:
291
    #   C:\path     => C:/path
292
    #   C:/path     => C:/path
293
    #   \\HOST\path => //HOST/path
294
    #   //HOST/path => //HOST/path
295
    #   path        => C:/cwd/path
296
    #   /path       => C:/path
297
    path = unicode(path)
298
    # check for absolute path
299
    drive = _nt_splitdrive(path)[0]
300
    if drive == '' and path[:2] not in('//','\\\\'):
301
        cwd = os.getcwdu()
302
        # we cannot simply os.path.join cwd and path
303
        # because os.path.join('C:','/path') produce '/path'
304
        # and this is incorrect
305
        if path[:1] in ('/','\\'):
306
            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
307
            path = path[1:]
2279.4.1 by Alexander Belchenko
Reimplementation of ntpath.abspath in Python for Windows98: unicode safe, UNC path safe
308
        path = cwd + '\\' + path
309
    return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
310
311
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
312
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'
313
    # 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
314
    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
315
316
317
def _win32_pathjoin(*args):
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
318
    return _nt_join(*args).replace('\\', '/')
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
319
320
321
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
322
    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
323
324
325
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
326
    return _win32_fixdrive(os.getcwdu().replace('\\', '/'))
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
327
328
329
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
330
    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
331
332
333
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.
334
    """We expect to be able to atomically replace 'new' with old.
335
1711.7.17 by John Arbash Meinel
Delay the extra syscall in _win32_rename until we get a failure.
336
    On win32, if new exists, it must be moved out of the way first,
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
337
    and then deleted.
1711.7.6 by John Arbash Meinel
Change _win32_rename() so that it raises ENOENT *before* it tries any renaming.
338
    """
1711.7.17 by John Arbash Meinel
Delay the extra syscall in _win32_rename until we get a failure.
339
    try:
340
        fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
341
    except OSError, e:
1830.3.15 by John Arbash Meinel
On Mac we get EINVAL when renaming cwd
342
        if e.errno in (errno.EPERM, errno.EACCES, errno.EBUSY, errno.EINVAL):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
343
            # If we try to rename a non-existant file onto cwd, we get
344
            # EPERM or EACCES instead of ENOENT, this will raise ENOENT
1830.3.15 by John Arbash Meinel
On Mac we get EINVAL when renaming cwd
345
            # if the old path doesn't exist, sometimes we get EACCES
346
            # 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.
347
            os.lstat(old)
348
        raise
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
349
350
1830.3.11 by John Arbash Meinel
Create a mac version of 'getcwd()' which normalizes the path.
351
def _mac_getcwd():
3201.1.1 by jameinel
Fix bug #185458, switch from NFKC to NFC and add tests for filenames that would be broken under NFKC
352
    return unicodedata.normalize('NFC', os.getcwdu())
1830.3.11 by John Arbash Meinel
Create a mac version of 'getcwd()' which normalizes the path.
353
354
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
355
# Default is to just use the python builtins, but these can be rebound on
356
# particular platforms.
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
357
abspath = _posix_abspath
358
realpath = _posix_realpath
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
359
pathjoin = os.path.join
360
normpath = os.path.normpath
361
getcwd = os.getcwdu
362
rename = os.rename
363
dirname = os.path.dirname
364
basename = os.path.basename
2215.4.2 by Alexander Belchenko
split and splitext now the part of osutils
365
split = os.path.split
366
splitext = os.path.splitext
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
367
# These were already imported into local scope
368
# mkdtemp = tempfile.mkdtemp
369
# rmtree = shutil.rmtree
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
370
1551.2.53 by abentley
Strip trailing slashes in a platform-sensible way
371
MIN_ABS_PATHLENGTH = 1
372
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
373
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
374
if sys.platform == 'win32':
3224.5.35 by Andrew Bennetts
More improvements suggested by John's review.
375
    if win32utils.winver == 'Windows 98':
376
        abspath = _win98_abspath
377
    else:
378
        abspath = _win32_abspath
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
379
    realpath = _win32_realpath
380
    pathjoin = _win32_pathjoin
381
    normpath = _win32_normpath
382
    getcwd = _win32_getcwd
383
    mkdtemp = _win32_mkdtemp
384
    rename = _win32_rename
385
1551.2.53 by abentley
Strip trailing slashes in a platform-sensible way
386
    MIN_ABS_PATHLENGTH = 3
1532 by Robert Collins
Merge in John Meinels integration branch.
387
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
388
    def _win32_delete_readonly(function, path, excinfo):
389
        """Error handler for shutil.rmtree function [for win32]
390
        Helps to remove files and dirs marked as read-only.
391
        """
2116.5.1 by Henri Wiechers
Fixes osutils.rmtree on Windows with Python 2.5
392
        exception = excinfo[1]
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
393
        if function in (os.remove, os.rmdir) \
2116.5.1 by Henri Wiechers
Fixes osutils.rmtree on Windows with Python 2.5
394
            and isinstance(exception, OSError) \
395
            and exception.errno == errno.EACCES:
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
396
            make_writable(path)
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
397
            function(path)
398
        else:
399
            raise
400
401
    def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
402
        """Replacer for shutil.rmtree: could remove readonly dirs/files"""
403
        return shutil.rmtree(path, ignore_errors, onerror)
4355.2.2 by Alexander Belchenko
osutils.py: get_unicode_argv function (to obtain unicode command line arguments from sys.argv) moved to the beginning of module based on suggestions from review of John Meinel.
404
405
    f = win32utils.get_unicode_argv     # special function or None
406
    if f is not None:
407
        get_unicode_argv = f
408
1830.3.11 by John Arbash Meinel
Create a mac version of 'getcwd()' which normalizes the path.
409
elif sys.platform == 'darwin':
410
    getcwd = _mac_getcwd
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
411
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
412
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.
413
def get_terminal_encoding():
414
    """Find the best encoding for printing to the screen.
415
416
    This attempts to check both sys.stdout and sys.stdin to see
417
    what encoding they are in, and if that fails it falls back to
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
418
    osutils.get_user_encoding().
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.
419
    The problem is that on Windows, locale.getpreferredencoding()
420
    is not the same encoding as that used by the console:
421
    http://mail.python.org/pipermail/python-list/2003-May/162357.html
422
423
    On my standard US Windows XP, the preferred encoding is
424
    cp1252, but the console is cp437
425
    """
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
426
    from bzrlib.trace import mutter
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
    output_encoding = getattr(sys.stdout, 'encoding', None)
428
    if not output_encoding:
429
        input_encoding = getattr(sys.stdin, 'encoding', None)
430
        if not input_encoding:
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
431
            output_encoding = get_user_encoding()
432
            mutter('encoding stdout as osutils.get_user_encoding() %r',
433
                   output_encoding)
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.
434
        else:
435
            output_encoding = input_encoding
436
            mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
437
    else:
438
        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
439
    if output_encoding == 'cp0':
440
        # invalid encoding (cp0 means 'no codepage' on Windows)
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
441
        output_encoding = get_user_encoding()
2127.4.1 by Alexander Belchenko
(jam, bialix) Workaround for cp0 console encoding on Windows
442
        mutter('cp0 is invalid encoding.'
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
443
               ' encoding stdout as osutils.get_user_encoding() %r',
444
               output_encoding)
2192.1.1 by Alexander Belchenko
Before actually using encoding need to check that Python has corresponding codec
445
    # check encoding
446
    try:
447
        codecs.lookup(output_encoding)
448
    except LookupError:
449
        sys.stderr.write('bzr: warning:'
2192.1.9 by Alexander Belchenko
final fix suggested by John Meinel
450
                         ' unknown terminal encoding %s.\n'
2192.1.1 by Alexander Belchenko
Before actually using encoding need to check that Python has corresponding codec
451
                         '  Using encoding %s instead.\n'
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
452
                         % (output_encoding, get_user_encoding())
2192.1.1 by Alexander Belchenko
Before actually using encoding need to check that Python has corresponding codec
453
                        )
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
454
        output_encoding = get_user_encoding()
2192.1.1 by Alexander Belchenko
Before actually using encoding need to check that Python has corresponding codec
455
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.
456
    return output_encoding
457
458
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 \
459
def normalizepath(f):
3287.18.2 by Matt McClure
Reverts to 3290.
460
    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 \
461
        F = realpath
462
    else:
463
        F = abspath
464
    [p,e] = os.path.split(f)
465
    if e == "" or e == "." or e == "..":
466
        return F(f)
467
    else:
468
        return pathjoin(F(p), e)
469
1 by mbp at sourcefrog
import from baz patch-364
470
471
def isdir(f):
472
    """True if f is an accessible directory."""
473
    try:
474
        return S_ISDIR(os.lstat(f)[ST_MODE])
475
    except OSError:
476
        return False
477
478
479
def isfile(f):
480
    """True if f is a regular file."""
481
    try:
482
        return S_ISREG(os.lstat(f)[ST_MODE])
483
    except OSError:
484
        return False
485
1092.2.6 by Robert Collins
symlink support updated to work
486
def islink(f):
487
    """True if f is a symlink."""
488
    try:
489
        return S_ISLNK(os.lstat(f)[ST_MODE])
490
    except OSError:
491
        return False
1 by mbp at sourcefrog
import from baz patch-364
492
485 by Martin Pool
- move commit code into its own module
493
def is_inside(dir, fname):
494
    """True if fname is inside dir.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
495
1185.31.38 by John Arbash Meinel
Changing os.path.normpath to osutils.normpath
496
    The parameters should typically be passed to osutils.normpath first, so
969 by Martin Pool
- Add less-sucky is_within_any
497
    that . and .. and repeated slashes are eliminated, and the separators
498
    are canonical for the platform.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
499
500
    The empty string as a dir name is taken as top-of-tree and matches
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
501
    everything.
485 by Martin Pool
- move commit code into its own module
502
    """
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
503
    # XXX: Most callers of this can actually do something smarter by
969 by Martin Pool
- Add less-sucky is_within_any
504
    # looking at the inventory
972 by Martin Pool
- less dodgy is_inside function
505
    if dir == fname:
506
        return True
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
507
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
508
    if dir == '':
509
        return True
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
510
1185.31.34 by John Arbash Meinel
Removing instances of os.sep
511
    if dir[-1] != '/':
512
        dir += '/'
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
513
972 by Martin Pool
- less dodgy is_inside function
514
    return fname.startswith(dir)
515
485 by Martin Pool
- move commit code into its own module
516
517
def is_inside_any(dir_list, fname):
518
    """True if fname is inside any of given dirs."""
519
    for dirname in dir_list:
520
        if is_inside(dirname, fname):
521
            return True
2324.2.3 by Dmitry Vasiliev
Fixed is_inside_* methods implementation
522
    return False
485 by Martin Pool
- move commit code into its own module
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
2324.2.3 by Dmitry Vasiliev
Fixed is_inside_* methods implementation
530
    return False
1740.3.4 by Jelmer Vernooij
Move inventory to commit builder.
531
532
3956.2.1 by John Arbash Meinel
Add report_activity to osutils.pumpfile
533
def pumpfile(from_file, to_file, read_length=-1, buff_size=32768,
534
             report_activity=None, direction='read'):
2745.5.2 by Robert Collins
* ``bzrlib.transport.Transport.put_file`` now returns the number of bytes
535
    """Copy contents of one file to another.
3408.6.1 by Eric Holmberg
Fix for Bug #215426 in which bzr can cause a MemoryError in socket.recv while
536
537
    The read_length can either be -1 to read to end-of-file (EOF) or
538
    it can specify the maximum number of bytes to read.
539
540
    The buff_size represents the maximum size for each read operation
541
    performed on from_file.
542
3956.2.1 by John Arbash Meinel
Add report_activity to osutils.pumpfile
543
    :param report_activity: Call this as bytes are read, see
544
        Transport._report_activity
545
    :param direction: Will be passed to report_activity
546
2745.5.2 by Robert Collins
* ``bzrlib.transport.Transport.put_file`` now returns the number of bytes
547
    :return: The number of bytes copied.
548
    """
549
    length = 0
3408.6.1 by Eric Holmberg
Fix for Bug #215426 in which bzr can cause a MemoryError in socket.recv while
550
    if read_length >= 0:
551
        # read specified number of bytes
552
553
        while read_length > 0:
554
            num_bytes_to_read = min(read_length, buff_size)
555
556
            block = from_file.read(num_bytes_to_read)
557
            if not block:
558
                # EOF reached
559
                break
3956.2.1 by John Arbash Meinel
Add report_activity to osutils.pumpfile
560
            if report_activity is not None:
561
                report_activity(len(block), direction)
3408.6.1 by Eric Holmberg
Fix for Bug #215426 in which bzr can cause a MemoryError in socket.recv while
562
            to_file.write(block)
563
564
            actual_bytes_read = len(block)
565
            read_length -= actual_bytes_read
566
            length += actual_bytes_read
567
    else:
568
        # read to EOF
569
        while True:
570
            block = from_file.read(buff_size)
571
            if not block:
572
                # EOF reached
573
                break
3956.2.1 by John Arbash Meinel
Add report_activity to osutils.pumpfile
574
            if report_activity is not None:
575
                report_activity(len(block), direction)
3408.6.1 by Eric Holmberg
Fix for Bug #215426 in which bzr can cause a MemoryError in socket.recv while
576
            to_file.write(block)
577
            length += len(block)
2745.5.2 by Robert Collins
* ``bzrlib.transport.Transport.put_file`` now returns the number of bytes
578
    return length
1 by mbp at sourcefrog
import from baz patch-364
579
580
3635.1.2 by Robert Collins
Add osutils.pump_string_file helper function.
581
def pump_string_file(bytes, file_handle, segment_size=None):
582
    """Write bytes to file_handle in many smaller writes.
583
584
    :param bytes: The string to write.
585
    :param file_handle: The file to write to.
586
    """
587
    # Write data in chunks rather than all at once, because very large
588
    # writes fail on some platforms (e.g. Windows with SMB  mounted
589
    # drives).
590
    if not segment_size:
591
        segment_size = 5242880 # 5MB
592
    segments = range(len(bytes) / segment_size + 1)
593
    write = file_handle.write
594
    for segment_index in segments:
595
        segment = buffer(bytes, segment_index * segment_size, segment_size)
596
        write(segment)
597
598
1185.67.7 by Aaron Bentley
Refactored a bit
599
def file_iterator(input_file, readsize=32768):
600
    while True:
601
        b = input_file.read(readsize)
602
        if len(b) == 0:
603
            break
604
        yield b
605
606
1 by mbp at sourcefrog
import from baz patch-364
607
def sha_file(f):
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
608
    """Calculate the hexdigest of an open file.
609
610
    The file cursor should be already at the start.
611
    """
2929.3.1 by Vincent Ladeuil
Fix python2.6 deprecation warnings (still 4 failures 5 errors in test suite).
612
    s = sha()
320 by Martin Pool
- Compute SHA-1 of files in chunks
613
    BUFSIZE = 128<<10
614
    while True:
615
        b = f.read(BUFSIZE)
616
        if not b:
617
            break
618
        s.update(b)
1 by mbp at sourcefrog
import from baz patch-364
619
    return s.hexdigest()
620
621
3368.2.49 by Ian Clatworthy
added osutils.size_sha_file() with tests
622
def size_sha_file(f):
623
    """Calculate the size and hexdigest of an open file.
624
625
    The file cursor should be already at the start and
626
    the caller is responsible for closing the file afterwards.
627
    """
628
    size = 0
629
    s = sha()
630
    BUFSIZE = 128<<10
631
    while True:
632
        b = f.read(BUFSIZE)
633
        if not b:
634
            break
635
        size += len(b)
636
        s.update(b)
637
    return size, s.hexdigest()
638
639
2872.3.1 by Martin Pool
Add -Dhashcache option; clean up dirstate sha1 code
640
def sha_file_by_name(fname):
641
    """Calculate the SHA1 of a file by reading the full text"""
2929.3.1 by Vincent Ladeuil
Fix python2.6 deprecation warnings (still 4 failures 5 errors in test suite).
642
    s = sha()
2922.1.1 by John Arbash Meinel
Fix bug #153493, use O_BINARY when reading files.
643
    f = os.open(fname, os.O_RDONLY | O_BINARY)
2872.3.1 by Martin Pool
Add -Dhashcache option; clean up dirstate sha1 code
644
    try:
2872.3.2 by Martin Pool
Do sha_file_by_name using raw os files rather than file objects; makes this routine about 12osutils.py faster
645
        while True:
646
            b = os.read(f, 1<<16)
647
            if not b:
648
                return s.hexdigest()
649
            s.update(b)
2872.3.1 by Martin Pool
Add -Dhashcache option; clean up dirstate sha1 code
650
    finally:
2872.3.2 by Martin Pool
Do sha_file_by_name using raw os files rather than file objects; makes this routine about 12osutils.py faster
651
        os.close(f)
2872.3.1 by Martin Pool
Add -Dhashcache option; clean up dirstate sha1 code
652
653
2929.3.1 by Vincent Ladeuil
Fix python2.6 deprecation warnings (still 4 failures 5 errors in test suite).
654
def sha_strings(strings, _factory=sha):
1235 by Martin Pool
- split sha_strings into osutils
655
    """Return the sha-1 of concatenation of strings"""
2825.2.1 by Robert Collins
Micro-tweaks to sha routines.
656
    s = _factory()
1235 by Martin Pool
- split sha_strings into osutils
657
    map(s.update, strings)
658
    return s.hexdigest()
659
660
2929.3.1 by Vincent Ladeuil
Fix python2.6 deprecation warnings (still 4 failures 5 errors in test suite).
661
def sha_string(f, _factory=sha):
2825.2.1 by Robert Collins
Micro-tweaks to sha routines.
662
    return _factory(f).hexdigest()
1 by mbp at sourcefrog
import from baz patch-364
663
664
124 by mbp at sourcefrog
- check file text for past revisions is correct
665
def fingerprint_file(f):
126 by mbp at sourcefrog
Use just one big read to fingerprint files
666
    b = f.read()
2825.2.1 by Robert Collins
Micro-tweaks to sha routines.
667
    return {'size': len(b),
2929.3.1 by Vincent Ladeuil
Fix python2.6 deprecation warnings (still 4 failures 5 errors in test suite).
668
            'sha1': sha(b).hexdigest()}
124 by mbp at sourcefrog
- check file text for past revisions is correct
669
670
1 by mbp at sourcefrog
import from baz patch-364
671
def compare_files(a, b):
672
    """Returns true if equal in contents"""
74 by mbp at sourcefrog
compare_files: read in one page at a time rather than
673
    BUFSIZE = 4096
674
    while True:
675
        ai = a.read(BUFSIZE)
676
        bi = b.read(BUFSIZE)
677
        if ai != bi:
678
            return False
679
        if ai == '':
680
            return True
1 by mbp at sourcefrog
import from baz patch-364
681
682
49 by mbp at sourcefrog
fix local-time-offset calculation
683
def local_time_offset(t=None):
684
    """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'.
685
    if t is None:
73 by mbp at sourcefrog
fix time.localtime call for python 2.3
686
        t = time.time()
2215.6.1 by James Henstridge
Don't rely on time.timezone and time.altzone in local_time_offset(),
687
    offset = datetime.fromtimestamp(t) - datetime.utcfromtimestamp(t)
688
    return offset.days * 86400 + offset.seconds
8 by mbp at sourcefrog
store committer's timezone in revision and show
689
3512.3.1 by Martin von Gagern
Hand-selected minimalistic set of changes from my setlocale branch.
690
weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
691
2425.6.2 by Martin Pool
Make timestamps use existing format_date; document that function more
692
def format_date(t, offset=0, timezone='original', date_fmt=None,
3526.5.4 by Martin von Gagern
Use separate function format_local_date for local weekday formats in unicode.
693
                show_offset=True):
2425.6.2 by Martin Pool
Make timestamps use existing format_date; document that function more
694
    """Return a formatted date string.
695
696
    :param t: Seconds since the epoch.
697
    :param offset: Timezone offset in seconds east of utc.
698
    :param timezone: How to display the time: 'utc', 'original' for the
699
         timezone specified by offset, or 'local' for the process's current
700
         timezone.
3526.5.4 by Martin von Gagern
Use separate function format_local_date for local weekday formats in unicode.
701
    :param date_fmt: strftime format.
702
    :param show_offset: Whether to append the timezone.
703
    """
704
    (date_fmt, tt, offset_str) = \
705
               _format_date(t, offset, timezone, date_fmt, show_offset)
706
    date_fmt = date_fmt.replace('%a', weekdays[tt[6]])
707
    date_str = time.strftime(date_fmt, tt)
708
    return date_str + offset_str
709
710
def format_local_date(t, offset=0, timezone='original', date_fmt=None,
711
                      show_offset=True):
712
    """Return an unicode date string formatted according to the current locale.
713
714
    :param t: Seconds since the epoch.
715
    :param offset: Timezone offset in seconds east of utc.
716
    :param timezone: How to display the time: 'utc', 'original' for the
717
         timezone specified by offset, or 'local' for the process's current
718
         timezone.
719
    :param date_fmt: strftime format.
720
    :param show_offset: Whether to append the timezone.
721
    """
722
    (date_fmt, tt, offset_str) = \
723
               _format_date(t, offset, timezone, date_fmt, show_offset)
724
    date_str = time.strftime(date_fmt, tt)
725
    if not isinstance(date_str, unicode):
4385.4.1 by Alexander Belchenko
removed all references to bzrlib.user_encoding
726
        date_str = date_str.decode(get_user_encoding(), 'replace')
3526.5.4 by Martin von Gagern
Use separate function format_local_date for local weekday formats in unicode.
727
    return date_str + offset_str
728
729
def _format_date(t, offset, timezone, date_fmt, show_offset):
8 by mbp at sourcefrog
store committer's timezone in revision and show
730
    if timezone == 'utc':
1 by mbp at sourcefrog
import from baz patch-364
731
        tt = time.gmtime(t)
732
        offset = 0
8 by mbp at sourcefrog
store committer's timezone in revision and show
733
    elif timezone == 'original':
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
734
        if offset is None:
23 by mbp at sourcefrog
format_date: handle revisions with no timezone offset
735
            offset = 0
16 by mbp at sourcefrog
fix inverted calculation for original timezone -> utc
736
        tt = time.gmtime(t + offset)
12 by mbp at sourcefrog
new --timezone option for bzr log
737
    elif timezone == 'local':
1 by mbp at sourcefrog
import from baz patch-364
738
        tt = time.localtime(t)
49 by mbp at sourcefrog
fix local-time-offset calculation
739
        offset = local_time_offset(t)
12 by mbp at sourcefrog
new --timezone option for bzr log
740
    else:
3144.1.1 by Lukáš Lalinský
Fixed error reporting of unsupported timezone format.
741
        raise errors.UnsupportedTimezoneFormat(timezone)
1185.12.24 by Aaron Bentley
Made format_date more flexible
742
    if date_fmt is None:
743
        date_fmt = "%a %Y-%m-%d %H:%M:%S"
744
    if show_offset:
745
        offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
746
    else:
747
        offset_str = ''
3526.5.4 by Martin von Gagern
Use separate function format_local_date for local weekday formats in unicode.
748
    return (date_fmt, tt, offset_str)
1 by mbp at sourcefrog
import from baz patch-364
749
750
751
def compact_date(when):
752
    return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
753
1 by mbp at sourcefrog
import from baz patch-364
754
1957.1.4 by John Arbash Meinel
create a helper for formatting a time delta
755
def format_delta(delta):
756
    """Get a nice looking string for a time delta.
757
758
    :param delta: The time difference in seconds, can be positive or negative.
759
        positive indicates time in the past, negative indicates time in the
760
        future. (usually time.time() - stored_time)
761
    :return: String formatted to show approximate resolution
762
    """
763
    delta = int(delta)
764
    if delta >= 0:
765
        direction = 'ago'
766
    else:
767
        direction = 'in the future'
768
        delta = -delta
769
770
    seconds = delta
771
    if seconds < 90: # print seconds up to 90 seconds
772
        if seconds == 1:
773
            return '%d second %s' % (seconds, direction,)
774
        else:
775
            return '%d seconds %s' % (seconds, direction)
776
777
    minutes = int(seconds / 60)
778
    seconds -= 60 * minutes
779
    if seconds == 1:
780
        plural_seconds = ''
781
    else:
782
        plural_seconds = 's'
783
    if minutes < 90: # print minutes, seconds up to 90 minutes
784
        if minutes == 1:
785
            return '%d minute, %d second%s %s' % (
786
                    minutes, seconds, plural_seconds, direction)
787
        else:
788
            return '%d minutes, %d second%s %s' % (
789
                    minutes, seconds, plural_seconds, direction)
790
791
    hours = int(minutes / 60)
792
    minutes -= 60 * hours
793
    if minutes == 1:
794
        plural_minutes = ''
795
    else:
796
        plural_minutes = 's'
797
798
    if hours == 1:
799
        return '%d hour, %d minute%s %s' % (hours, minutes,
800
                                            plural_minutes, direction)
801
    return '%d hours, %d minute%s %s' % (hours, minutes,
802
                                         plural_minutes, direction)
1 by mbp at sourcefrog
import from baz patch-364
803
804
def filesize(f):
805
    """Return size of given open file."""
806
    return os.fstat(f.fileno())[ST_SIZE]
807
1553.5.5 by Martin Pool
New utility routine rand_chars
808
1185.1.7 by Robert Collins
Nathaniel McCallums patch for urandom friendliness on aix.
809
# Define rand_bytes based on platform.
810
try:
811
    # Python 2.4 and later have os.urandom,
812
    # but it doesn't work on some arches
813
    os.urandom(1)
1 by mbp at sourcefrog
import from baz patch-364
814
    rand_bytes = os.urandom
1185.1.7 by Robert Collins
Nathaniel McCallums patch for urandom friendliness on aix.
815
except (NotImplementedError, AttributeError):
816
    # If python doesn't have os.urandom, or it doesn't work,
817
    # 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()
818
    try:
1185.1.7 by Robert Collins
Nathaniel McCallums patch for urandom friendliness on aix.
819
        rand_bytes = file('/dev/urandom', 'rb').read
820
    # 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()
821
    except (IOError, OSError):
1185.1.7 by Robert Collins
Nathaniel McCallums patch for urandom friendliness on aix.
822
        # not well seeded, but better than nothing
823
        def rand_bytes(n):
824
            import random
825
            s = ''
826
            while n:
827
                s += chr(random.randint(0, 255))
828
                n -= 1
829
            return s
1 by mbp at sourcefrog
import from baz patch-364
830
1553.5.5 by Martin Pool
New utility routine rand_chars
831
832
ALNUM = '0123456789abcdefghijklmnopqrstuvwxyz'
833
def rand_chars(num):
834
    """Return a random string of num alphanumeric characters
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
835
836
    The result only contains lowercase chars because it may be used on
1553.5.5 by Martin Pool
New utility routine rand_chars
837
    case-insensitive filesystems.
838
    """
839
    s = ''
840
    for raw_byte in rand_bytes(num):
841
        s += ALNUM[ord(raw_byte) % 36]
842
    return s
843
844
1 by mbp at sourcefrog
import from baz patch-364
845
## 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.
846
## decomposition (might be too tricksy though.)
1 by mbp at sourcefrog
import from baz patch-364
847
848
def splitpath(p):
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
849
    """Turn string into list of parts."""
271 by Martin Pool
- Windows path fixes
850
    # split on either delimiter because people might use either on
851
    # Windows
852
    ps = re.split(r'[\\/]', p)
853
854
    rps = []
1 by mbp at sourcefrog
import from baz patch-364
855
    for f in ps:
856
        if f == '..':
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
857
            raise errors.BzrError("sorry, %r not allowed in path" % f)
271 by Martin Pool
- Windows path fixes
858
        elif (f == '.') or (f == ''):
859
            pass
860
        else:
861
            rps.append(f)
862
    return rps
1 by mbp at sourcefrog
import from baz patch-364
863
3890.2.4 by John Arbash Meinel
Add a new function that can convert 'chunks' format to a 'lines' format.
864
1 by mbp at sourcefrog
import from baz patch-364
865
def joinpath(p):
866
    for f in p:
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
867
        if (f == '..') or (f is None) or (f == ''):
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
868
            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 \
869
    return pathjoin(*p)
1 by mbp at sourcefrog
import from baz patch-364
870
871
4370.1.1 by Ian Clatworthy
add osutils.parent_directories() API
872
def parent_directories(filename):
4371.1.1 by Ian Clatworthy
(igc) added osutils.parent_directories() (Ian Clatworthy)
873
    """Return the list of parent directories, deepest first.
874
    
875
    For example, parent_directories("a/b/c") -> ["a/b", "a"].
876
    """
4370.1.1 by Ian Clatworthy
add osutils.parent_directories() API
877
    parents = []
878
    parts = splitpath(dirname(filename))
879
    while parts:
880
        parents.append(joinpath(parts))
881
        parts.pop()
882
    return parents
883
884
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
885
_extension_load_failures = []
886
887
888
def failed_to_load_extension(exception):
4574.3.1 by Martin Pool
Give a warning when failing to load _chunks_to_lines_pyx
889
    """Handle failing to load a binary extension.
890
891
    This should be called from the ImportError block guarding the attempt to
892
    import the native extension.  If this function returns, the pure-Python
893
    implementation should be loaded instead::
894
895
    >>> try:
896
    >>>     import bzrlib._fictional_extension_pyx
897
    >>> except ImportError, e:
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
898
    >>>     bzrlib.osutils.failed_to_load_extension(e)
4574.3.1 by Martin Pool
Give a warning when failing to load _chunks_to_lines_pyx
899
    >>>     import bzrlib._fictional_extension_py
900
    """
901
    # NB: This docstring is just an example, not a doctest, because doctest
902
    # currently can't cope with the use of lazy imports in this namespace --
903
    # mbp 20090729
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
904
    
905
    # This currently doesn't report the failure at the time it occurs, because
906
    # they tend to happen very early in startup when we can't check config
907
    # files etc, and also we want to report all failures but not spam the user
908
    # with 10 warnings.
909
    from bzrlib import trace
910
    exception_str = str(exception)
911
    if exception_str not in _extension_load_failures:
912
        trace.mutter("failed to load compiled extension: %s" % exception_str)
913
        _extension_load_failures.append(exception_str)
914
915
916
def report_extension_load_failures():
917
    if not _extension_load_failures:
918
        return
919
    from bzrlib.config import GlobalConfig
920
    if GlobalConfig().get_user_option_as_bool('ignore_missing_extensions'):
921
        return
922
    # the warnings framework should by default show this only once
4574.3.2 by Martin Pool
Change back to python warnings for failure to load extensions
923
    warnings.warn(
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
924
        "bzr: warning: Failed to load compiled extensions: "
4574.3.2 by Martin Pool
Change back to python warnings for failure to load extensions
925
        "%s\n" 
926
        "    Bazaar can run, but performance may be reduced.\n"
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
927
        "    Check Bazaar is correctly installed or set ignore_missing_extensions"
928
        % '\n'.join(_extension_load_failures,))
4574.3.1 by Martin Pool
Give a warning when failing to load _chunks_to_lines_pyx
929
930
3890.2.7 by John Arbash Meinel
A Pyrex extension is about 5x faster than the fastest python code I could write.
931
try:
932
    from bzrlib._chunks_to_lines_pyx import chunks_to_lines
4574.3.1 by Martin Pool
Give a warning when failing to load _chunks_to_lines_pyx
933
except ImportError, e:
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
934
    failed_to_load_extension(e)
3890.2.8 by John Arbash Meinel
Move everything into properly parameterized tests.
935
    from bzrlib._chunks_to_lines_py import chunks_to_lines
3890.2.7 by John Arbash Meinel
A Pyrex extension is about 5x faster than the fastest python code I could write.
936
937
1231 by Martin Pool
- more progress on fetch on top of weaves
938
def split_lines(s):
939
    """Split s into lines, but without removing the newline characters."""
3890.2.18 by John Arbash Meinel
Implement osutils.split_lines() in terms of chunks_to_lines if possible.
940
    # Trivially convert a fulltext into a 'chunked' representation, and let
941
    # chunks_to_lines do the heavy lifting.
942
    if isinstance(s, str):
943
        # chunks_to_lines only supports 8-bit strings
944
        return chunks_to_lines([s])
945
    else:
946
        return _split_lines(s)
947
948
949
def _split_lines(s):
950
    """Split s into lines, but without removing the newline characters.
951
952
    This supports Unicode or plain string objects.
953
    """
1666.1.6 by Robert Collins
Make knit the default format.
954
    lines = s.split('\n')
955
    result = [line + '\n' for line in lines[:-1]]
956
    if lines[-1]:
957
        result.append(lines[-1])
958
    return result
1391 by Robert Collins
merge from integration
959
960
1185.10.4 by Aaron Bentley
Disabled hardlinks on cygwin, mac OS
961
def hardlinks_good():
1185.10.5 by Aaron Bentley
Fixed hardlinks_good test
962
    return sys.platform not in ('win32', 'cygwin', 'darwin')
1185.10.4 by Aaron Bentley
Disabled hardlinks on cygwin, mac OS
963
1185.1.46 by Robert Collins
Aarons branch --basis patch
964
1185.10.3 by Aaron Bentley
Made copy_multi_immutable create hardlinks opportunistically
965
def link_or_copy(src, dest):
966
    """Hardlink a file, or copy it if it can't be hardlinked."""
1185.10.4 by Aaron Bentley
Disabled hardlinks on cygwin, mac OS
967
    if not hardlinks_good():
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
968
        shutil.copyfile(src, dest)
1185.10.3 by Aaron Bentley
Made copy_multi_immutable create hardlinks opportunistically
969
        return
970
    try:
971
        os.link(src, dest)
972
    except (OSError, IOError), e:
973
        if e.errno != errno.EXDEV:
974
            raise
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
975
        shutil.copyfile(src, dest)
1399.1.4 by Robert Collins
move diff and symlink conditionals into inventory.py from diff.py
976
2831.5.2 by Vincent Ladeuil
Review feedback.
977
978
def delete_any(path):
4490.1.1 by Martin Pool
merge fix for forcing readonly deletion, and tweak
979
    """Delete a file, symlink or directory.  
980
    
981
    Will delete even if readonly.
982
    """
4440.1.2 by Craig Hewetson
Fixes made after first code review.
983
    try:
4490.1.1 by Martin Pool
merge fix for forcing readonly deletion, and tweak
984
       _delete_file_or_dir(path)
4440.1.2 by Craig Hewetson
Fixes made after first code review.
985
    except (OSError, IOError), e:
986
        if e.errno in (errno.EPERM, errno.EACCES):
4490.1.1 by Martin Pool
merge fix for forcing readonly deletion, and tweak
987
            # make writable and try again
988
            try:
4440.1.2 by Craig Hewetson
Fixes made after first code review.
989
                make_writable(path)
4490.1.1 by Martin Pool
merge fix for forcing readonly deletion, and tweak
990
            except (OSError, IOError):
4440.1.2 by Craig Hewetson
Fixes made after first code review.
991
                pass
4490.1.1 by Martin Pool
merge fix for forcing readonly deletion, and tweak
992
            _delete_file_or_dir(path)
993
        else:
994
            raise
995
996
997
def _delete_file_or_dir(path):
998
    # Look Before You Leap (LBYL) is appropriate here instead of Easier to Ask for
999
    # Forgiveness than Permission (EAFP) because:
1000
    # - root can damage a solaris file system by using unlink,
1001
    # - unlink raises different exceptions on different OSes (linux: EISDIR, win32:
1002
    #   EACCES, OSX: EPERM) when invoked on a directory.
2831.5.2 by Vincent Ladeuil
Review feedback.
1003
    if isdir(path): # Takes care of symlinks
1004
        os.rmdir(path)
1005
    else:
1006
        os.unlink(path)
1558.12.9 by Aaron Bentley
Handle resolving conflicts with directories properly
1007
1399.1.4 by Robert Collins
move diff and symlink conditionals into inventory.py from diff.py
1008
1009
def has_symlinks():
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
1010
    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
1011
        return True
1012
    else:
1013
        return False
2831.5.2 by Vincent Ladeuil
Review feedback.
1014
1185.16.38 by Martin Pool
- move contains_whitespace and contains_linebreaks to osutils
1015
3136.1.1 by Aaron Bentley
Add support for hardlinks to TreeTransform
1016
def has_hardlinks():
1017
    if getattr(os, 'link', None) is not None:
1018
        return True
1019
    else:
1020
        return False
1021
1022
3287.18.14 by Matt McClure
Extracted a host_os_dereferences_symlinks method.
1023
def host_os_dereferences_symlinks():
1024
    return (has_symlinks()
3287.18.19 by Matt McClure
Changed tested sys.platform value from 'windows' (mistaken) to 'win32'
1025
            and sys.platform not in ('cygwin', 'win32'))
3287.18.14 by Matt McClure
Extracted a host_os_dereferences_symlinks method.
1026
1027
4241.14.14 by Vincent Ladeuil
Test and implements osutils.readlink().
1028
def readlink(abspath):
1029
    """Return a string representing the path to which the symbolic link points.
1030
1031
    :param abspath: The link absolute unicode path.
1032
1033
    This his guaranteed to return the symbolic link in unicode in all python
1034
    versions.
1035
    """
1036
    link = abspath.encode(_fs_enc)
1037
    target = os.readlink(link)
1038
    target = target.decode(_fs_enc)
1039
    return target
1040
1041
1185.16.38 by Martin Pool
- move contains_whitespace and contains_linebreaks to osutils
1042
def contains_whitespace(s):
1043
    """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.
1044
    # string.whitespace can include '\xa0' in certain locales, because it is
1045
    # considered "non-breaking-space" as part of ISO-8859-1. But it
1046
    # 1) Isn't a breaking whitespace
1047
    # 2) Isn't one of ' \t\r\n' which are characters we sometimes use as
1048
    #    separators
1049
    # 3) '\xa0' isn't unicode safe since it is >128.
2249.5.16 by John Arbash Meinel
[merge] bzr.dev 2283
1050
1051
    # This should *not* be a unicode set of characters in case the source
1052
    # string is not a Unicode string. We can auto-up-cast the characters since
1053
    # they are ascii, but we don't want to auto-up-cast the string in case it
1054
    # is utf-8
1055
    for ch in ' \t\n\r\v\f':
1185.16.38 by Martin Pool
- move contains_whitespace and contains_linebreaks to osutils
1056
        if ch in s:
1057
            return True
1058
    else:
1059
        return False
1060
1061
1062
def contains_linebreaks(s):
1063
    """True if there is any vertical whitespace in s."""
1064
    for ch in '\f\n\r':
1065
        if ch in s:
1066
            return True
1067
    else:
1068
        return False
1457.1.2 by Robert Collins
move branch._relpath into osutils as relpath
1069
1070
1071
def relpath(base, path):
1072
    """Return path relative to base, or raise exception.
1073
1074
    The path may be either an absolute path or a path relative to the
1075
    current working directory.
1076
1077
    os.path.commonprefix (python2.4) has a bad bug that it works just
1078
    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.
1079
    avoids that problem.
1080
    """
1685.1.12 by John Arbash Meinel
Some more work to get LocalTransport to only support URLs
1081
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1082
    if len(base) < MIN_ABS_PATHLENGTH:
1083
        # must have space for e.g. a drive letter
1084
        raise ValueError('%r is too short to calculate a relative path'
1085
            % (base,))
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
1086
1685.1.12 by John Arbash Meinel
Some more work to get LocalTransport to only support URLs
1087
    rp = abspath(path)
1457.1.2 by Robert Collins
move branch._relpath into osutils as relpath
1088
1089
    s = []
1685.1.12 by John Arbash Meinel
Some more work to get LocalTransport to only support URLs
1090
    head = rp
4555.2.1 by John Arbash Meinel
Fix bug #394227, osutils.relpath() could get into an infinite loop.
1091
    while True:
1092
        if len(head) <= len(base) and head != base:
1093
            raise errors.PathNotChild(rp, base)
1457.1.2 by Robert Collins
move branch._relpath into osutils as relpath
1094
        if head == base:
1095
            break
4555.2.1 by John Arbash Meinel
Fix bug #394227, osutils.relpath() could get into an infinite loop.
1096
        head, tail = split(head)
1457.1.2 by Robert Collins
move branch._relpath into osutils as relpath
1097
        if tail:
4555.2.1 by John Arbash Meinel
Fix bug #394227, osutils.relpath() could get into an infinite loop.
1098
            s.append(tail)
1457.1.2 by Robert Collins
move branch._relpath into osutils as relpath
1099
1185.31.35 by John Arbash Meinel
Couple small fixes, all tests pass on cygwin.
1100
    if s:
4555.2.3 by John Arbash Meinel
Fix a trivial bug that should have been caught earlier. :)
1101
        return pathjoin(*reversed(s))
1185.31.35 by John Arbash Meinel
Couple small fixes, all tests pass on cygwin.
1102
    else:
1103
        return ''
1185.33.60 by Martin Pool
Use full terminal width for verbose test output.
1104
1105
3794.5.29 by Mark Hammond
cicp_canonical_relpath -> _cicp_canonical_relpath
1106
def _cicp_canonical_relpath(base, path):
3794.5.1 by Mark Hammond
Add canonical_relpath api function
1107
    """Return the canonical path relative to base.
1108
1109
    Like relpath, but on case-insensitive-case-preserving file-systems, this
3794.5.13 by Mark Hammond
Tweaks suggested by Martin
1110
    will return the relpath as stored on the file-system rather than in the
1111
    case specified in the input string, for all existing portions of the path.
1112
3794.5.28 by Mark Hammond
Update comments.
1113
    This will cause O(N) behaviour if called for every path in a tree; if you
1114
    have a number of paths to convert, you should use canonical_relpaths().
3794.5.31 by Mark Hammond
bulk of the simple review comments from igc.
1115
    """
1116
    # TODO: it should be possible to optimize this for Windows by using the
1117
    # win32 API FindFiles function to look for the specified name - but using
1118
    # os.listdir() still gives us the correct, platform agnostic semantics in
1119
    # the short term.
3794.5.13 by Mark Hammond
Tweaks suggested by Martin
1120
3794.5.1 by Mark Hammond
Add canonical_relpath api function
1121
    rel = relpath(base, path)
1122
    # '.' will have been turned into ''
1123
    if not rel:
1124
        return rel
1125
1126
    abs_base = abspath(base)
1127
    current = abs_base
1128
    _listdir = os.listdir
1129
1130
    # use an explicit iterator so we can easily consume the rest on early exit.
3794.5.36 by Mark Hammond
test for, and fix problem with canonical_relpath when the tail does not exist.
1131
    bit_iter = iter(rel.split('/'))
3794.5.1 by Mark Hammond
Add canonical_relpath api function
1132
    for bit in bit_iter:
1133
        lbit = bit.lower()
1134
        for look in _listdir(current):
1135
            if lbit == look.lower():
1136
                current = pathjoin(current, look)
1137
                break
1138
        else:
1139
            # got to the end, nothing matched, so we just return the
1140
            # non-existing bits as they were specified (the filename may be
1141
            # the target of a move, for example).
1142
            current = pathjoin(current, bit, *list(bit_iter))
1143
            break
1144
    return current[len(abs_base)+1:]
1145
3794.5.13 by Mark Hammond
Tweaks suggested by Martin
1146
# XXX - TODO - we need better detection/integration of case-insensitive
4241.9.5 by Vincent Ladeuil
Fix unicode related OSX failures.
1147
# file-systems; Linux often sees FAT32 devices (or NFS-mounted OSX
1148
# filesystems), for example, so could probably benefit from the same basic
1149
# support there.  For now though, only Windows and OSX get that support, and
1150
# they get it for *all* file-systems!
4241.9.2 by Vincent Ladeuil
Fix most of cicp related failures on OSX.
1151
if sys.platform in ('win32', 'darwin'):
3794.5.29 by Mark Hammond
cicp_canonical_relpath -> _cicp_canonical_relpath
1152
    canonical_relpath = _cicp_canonical_relpath
3794.5.1 by Mark Hammond
Add canonical_relpath api function
1153
else:
1154
    canonical_relpath = relpath
1155
3794.5.15 by Mark Hammond
Add canonical_relpaths() as a placeholder for a future caching implementation.
1156
def canonical_relpaths(base, paths):
1157
    """Create an iterable to canonicalize a sequence of relative paths.
1158
1159
    The intent is for this implementation to use a cache, vastly speeding
1160
    up multiple transformations in the same directory.
1161
    """
1162
    # but for now, we haven't optimized...
1163
    return [canonical_relpath(base, p) for p in paths]
3794.5.1 by Mark Hammond
Add canonical_relpath api function
1164
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
1165
def safe_unicode(unicode_or_utf8_string):
1166
    """Coerce unicode_or_utf8_string into unicode.
1167
1168
    If it is unicode, it is returned.
4204.2.1 by Matt Nordhoff
Fix a broken sentence in osutils.safe_unicode's docstring
1169
    Otherwise it is decoded from utf-8. If decoding fails, the exception is
1170
    wrapped in a BzrBadParameterNotUnicode exception.
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
1171
    """
1172
    if isinstance(unicode_or_utf8_string, unicode):
1173
        return unicode_or_utf8_string
1174
    try:
1175
        return unicode_or_utf8_string.decode('utf8')
1176
    except UnicodeDecodeError:
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
1177
        raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
1178
1179
2249.5.8 by John Arbash Meinel
Add osutils.safe_utf8 and safe_revision_id for the new revision_id work.
1180
def safe_utf8(unicode_or_utf8_string):
1181
    """Coerce unicode_or_utf8_string to a utf8 string.
1182
1183
    If it is a str, it is returned.
1184
    If it is Unicode, it is encoded into a utf-8 string.
1185
    """
1186
    if isinstance(unicode_or_utf8_string, str):
1187
        # TODO: jam 20070209 This is overkill, and probably has an impact on
1188
        #       performance if we are dealing with lots of apis that want a
1189
        #       utf-8 revision id
1190
        try:
1191
            # Make sure it is a valid utf-8 string
1192
            unicode_or_utf8_string.decode('utf-8')
1193
        except UnicodeDecodeError:
1194
            raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
1195
        return unicode_or_utf8_string
1196
    return unicode_or_utf8_string.encode('utf-8')
1197
1198
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
1199
_revision_id_warning = ('Unicode revision ids were deprecated in bzr 0.15.'
1200
                        ' Revision id generators should be creating utf8'
1201
                        ' revision ids.')
1202
1203
1204
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.
1205
    """Revision ids should now be utf8, but at one point they were unicode.
1206
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
1207
    :param unicode_or_utf8_string: A possibly Unicode revision_id. (can also be
1208
        utf8 or None).
1209
    :param warn: Functions that are sanitizing user data can set warn=False
1210
    :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.
1211
    """
2309.4.3 by John Arbash Meinel
(broken) change safe_*_id to emit a warning.
1212
    if (unicode_or_utf8_string is None
1213
        or unicode_or_utf8_string.__class__ == str):
1214
        return unicode_or_utf8_string
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
1215
    if warn:
1216
        symbol_versioning.warn(_revision_id_warning, DeprecationWarning,
1217
                               stacklevel=2)
2309.4.3 by John Arbash Meinel
(broken) change safe_*_id to emit a warning.
1218
    return cache_utf8.encode(unicode_or_utf8_string)
1219
1220
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
1221
_file_id_warning = ('Unicode file ids were deprecated in bzr 0.15. File id'
1222
                    ' generators should be creating utf8 file ids.')
1223
1224
1225
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.
1226
    """File ids should now be utf8, but at one point they were unicode.
1227
1228
    This is the same as safe_utf8, except it uses the cached encode functions
1229
    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.
1230
1231
    :param unicode_or_utf8_string: A possibly Unicode file_id. (can also be
1232
        utf8 or None).
1233
    :param warn: Functions that are sanitizing user data can set warn=False
1234
    :return: None or a utf8 file id.
2309.4.3 by John Arbash Meinel
(broken) change safe_*_id to emit a warning.
1235
    """
1236
    if (unicode_or_utf8_string is None
1237
        or unicode_or_utf8_string.__class__ == str):
1238
        return unicode_or_utf8_string
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
1239
    if warn:
1240
        symbol_versioning.warn(_file_id_warning, DeprecationWarning,
1241
                               stacklevel=2)
2309.4.3 by John Arbash Meinel
(broken) change safe_*_id to emit a warning.
1242
    return cache_utf8.encode(unicode_or_utf8_string)
2294.1.4 by John Arbash Meinel
Add safe_file_id as a helper in osutils.
1243
1244
1185.85.75 by John Arbash Meinel
Adding bzrlib.osutils.unicode_filename to handle unicode normalization for file paths.
1245
_platform_normalizes_filenames = False
1246
if sys.platform == 'darwin':
1247
    _platform_normalizes_filenames = True
1248
1249
1250
def normalizes_filenames():
1251
    """Return True if this platform normalizes unicode filenames.
1252
1253
    Mac OSX does, Windows/Linux do not.
1254
    """
1255
    return _platform_normalizes_filenames
1256
1257
1830.3.2 by John Arbash Meinel
normalized_filename is a much better name
1258
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
1259
    """Get the unicode normalized path, and if you can access the file.
1260
1261
    On platforms where the system normalizes filenames (Mac OSX),
1262
    you can access a file by any path which will normalize correctly.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1263
    On platforms where the system does not normalize filenames
1830.3.1 by John Arbash Meinel
Change the return value of unicode_filename, and make it testable on all platforms
1264
    (Windows, Linux), you have to access a file by its exact path.
1265
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1266
    Internally, bzr only supports NFC normalization, since that is
1830.3.1 by John Arbash Meinel
Change the return value of unicode_filename, and make it testable on all platforms
1267
    the standard for XML documents.
1268
1269
    So return the normalized path, and a flag indicating if the file
1270
    can be accessed by that path.
1271
    """
1272
3201.1.1 by jameinel
Fix bug #185458, switch from NFKC to NFC and add tests for filenames that would be broken under NFKC
1273
    return unicodedata.normalize('NFC', unicode(path)), True
1830.3.1 by John Arbash Meinel
Change the return value of unicode_filename, and make it testable on all platforms
1274
1275
1830.3.2 by John Arbash Meinel
normalized_filename is a much better name
1276
def _inaccessible_normalized_filename(path):
1277
    __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
1278
3201.1.1 by jameinel
Fix bug #185458, switch from NFKC to NFC and add tests for filenames that would be broken under NFKC
1279
    normalized = unicodedata.normalize('NFC', unicode(path))
1830.3.1 by John Arbash Meinel
Change the return value of unicode_filename, and make it testable on all platforms
1280
    return normalized, normalized == path
1281
1282
1185.85.75 by John Arbash Meinel
Adding bzrlib.osutils.unicode_filename to handle unicode normalization for file paths.
1283
if _platform_normalizes_filenames:
1830.3.2 by John Arbash Meinel
normalized_filename is a much better name
1284
    normalized_filename = _accessible_normalized_filename
1185.85.75 by John Arbash Meinel
Adding bzrlib.osutils.unicode_filename to handle unicode normalization for file paths.
1285
else:
1830.3.2 by John Arbash Meinel
normalized_filename is a much better name
1286
    normalized_filename = _inaccessible_normalized_filename
1185.85.75 by John Arbash Meinel
Adding bzrlib.osutils.unicode_filename to handle unicode normalization for file paths.
1287
1288
1185.33.60 by Martin Pool
Use full terminal width for verbose test output.
1289
def terminal_width():
1290
    """Return estimated terminal width."""
1704.2.3 by Martin Pool
(win32) Detect terminal width using GetConsoleScreenBufferInfo (Alexander)
1291
    if sys.platform == 'win32':
2245.4.6 by Alexander Belchenko
osutils.py: terminal_width() now use win32utils.get_console_size()
1292
        return win32utils.get_console_size()[0]
1704.2.2 by Martin Pool
Detect terminal width using ioctl
1293
    width = 0
1185.33.60 by Martin Pool
Use full terminal width for verbose test output.
1294
    try:
1704.2.2 by Martin Pool
Detect terminal width using ioctl
1295
        import struct, fcntl, termios
1296
        s = struct.pack('HHHH', 0, 0, 0, 0)
1297
        x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
1298
        width = struct.unpack('HHHH', x)[1]
1299
    except IOError:
1300
        pass
1301
    if width <= 0:
1302
        try:
1303
            width = int(os.environ['COLUMNS'])
1304
        except:
1305
            pass
1306
    if width <= 0:
1307
        width = 80
1308
1309
    return width
1534.7.25 by Aaron Bentley
Added set_executability
1310
1963.1.5 by John Arbash Meinel
Create an osutils helper function for modifying the environment
1311
1534.7.25 by Aaron Bentley
Added set_executability
1312
def supports_executable():
1534.7.160 by Aaron Bentley
Changed implementation of supports_executable
1313
    return sys.platform != "win32"
1551.2.53 by abentley
Strip trailing slashes in a platform-sensible way
1314
1315
1551.10.4 by Aaron Bentley
Update to skip on win32
1316
def supports_posix_readonly():
1317
    """Return True if 'readonly' has POSIX semantics, False otherwise.
1318
1319
    Notably, a win32 readonly file cannot be deleted, unlike POSIX where the
1320
    directory controls creation/deletion, etc.
1321
1322
    And under win32, readonly means that the directory itself cannot be
1323
    deleted.  The contents of a readonly directory can be changed, unlike POSIX
1324
    where files in readonly directories cannot be added, deleted or renamed.
1325
    """
1326
    return sys.platform != "win32"
1327
1328
1963.1.5 by John Arbash Meinel
Create an osutils helper function for modifying the environment
1329
def set_or_unset_env(env_variable, value):
1330
    """Modify the environment, setting or removing the env_variable.
1331
1332
    :param env_variable: The environment variable in question
1333
    :param value: The value to set the environment to. If None, then
1334
        the variable will be removed.
1335
    :return: The original value of the environment variable.
1336
    """
1337
    orig_val = os.environ.get(env_variable)
1338
    if value is None:
1339
        if orig_val is not None:
1340
            del os.environ[env_variable]
1341
    else:
1342
        if isinstance(value, unicode):
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
1343
            value = value.encode(get_user_encoding())
1963.1.5 by John Arbash Meinel
Create an osutils helper function for modifying the environment
1344
        os.environ[env_variable] = value
1345
    return orig_val
1346
1347
1551.2.56 by Aaron Bentley
Better illegal pathname check for Windows
1348
_validWin32PathRE = re.compile(r'^([A-Za-z]:[/\\])?[^:<>*"?\|]*$')
1349
1350
1351
def check_legal_path(path):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1352
    """Check whether the supplied path is legal.
1551.2.56 by Aaron Bentley
Better illegal pathname check for Windows
1353
    This is only required on Windows, so we don't test on other platforms
1354
    right now.
1355
    """
1356
    if sys.platform != "win32":
1357
        return
1358
    if _validWin32PathRE.match(path) is None:
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
1359
        raise errors.IllegalPath(path)
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1360
1361
3596.2.2 by John Arbash Meinel
Factor out the common exception handling looking for ENOTDIR and use it
1362
_WIN32_ERROR_DIRECTORY = 267 # Similar to errno.ENOTDIR
1363
1364
def _is_error_enotdir(e):
1365
    """Check if this exception represents ENOTDIR.
1366
1367
    Unfortunately, python is very inconsistent about the exception
1368
    here. The cases are:
1369
      1) Linux, Mac OSX all versions seem to set errno == ENOTDIR
1370
      2) Windows, Python2.4, uses errno == ERROR_DIRECTORY (267)
1371
         which is the windows error code.
1372
      3) Windows, Python2.5 uses errno == EINVAL and
1373
         winerror == ERROR_DIRECTORY
1374
1375
    :param e: An Exception object (expected to be OSError with an errno
1376
        attribute, but we should be able to cope with anything)
1377
    :return: True if this represents an ENOTDIR error. False otherwise.
1378
    """
1379
    en = getattr(e, 'errno', None)
1380
    if (en == errno.ENOTDIR
1381
        or (sys.platform == 'win32'
1382
            and (en == _WIN32_ERROR_DIRECTORY
1383
                 or (en == errno.EINVAL
1384
                     and getattr(e, 'winerror', None) == _WIN32_ERROR_DIRECTORY)
1385
        ))):
1386
        return True
1387
    return False
1388
1389
1757.2.8 by Robert Collins
Teach walkdirs to walk a subdir of a tree.
1390
def walkdirs(top, prefix=""):
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1391
    """Yield data about all the directories in a tree.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1392
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1393
    This yields all the data about the contents of a directory at a time.
1394
    After each directory has been yielded, if the caller has mutated the list
1395
    to exclude some directories, they are then not descended into.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1396
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1397
    The data yielded is of the form:
1897.1.2 by Robert Collins
cleanup osutils.walkdirs changes after review.
1398
    ((directory-relpath, directory-path-from-top),
2694.4.1 by Alexander Belchenko
trivial fix for docstring of osutils.walkdirs()
1399
    [(relpath, basename, kind, lstat, path-from-top), ...]),
1897.1.2 by Robert Collins
cleanup osutils.walkdirs changes after review.
1400
     - directory-relpath is the relative path of the directory being returned
1401
       with respect to top. prefix is prepended to this.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1402
     - directory-path-from-root is the path including top for this directory.
1897.1.2 by Robert Collins
cleanup osutils.walkdirs changes after review.
1403
       It is suitable for use with os functions.
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
1404
     - relpath is the relative path within the subtree being walked.
1405
     - basename is the basename of the path
1897.1.2 by Robert Collins
cleanup osutils.walkdirs changes after review.
1406
     - 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.
1407
       present within the tree - but it may be recorded as versioned. See
1408
       versioned_kind.
1409
     - lstat is the stat data *if* the file was statted.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1410
     - planned, not implemented:
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
1411
       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.
1412
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1413
    :param prefix: Prefix the relpaths that are yielded with 'prefix'. This
1757.2.16 by Robert Collins
Review comments.
1414
        allows one to walk a subtree but get paths that are relative to a tree
1415
        rooted higher up.
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1416
    :return: an iterator over the dirs.
1417
    """
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
1418
    #TODO there is a bit of a smell where the results of the directory-
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1419
    # summary in this, and the path from the root, may not agree
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
1420
    # depending on top and prefix - i.e. ./foo and foo as a pair leads to
1421
    # potentially confusing output. We should make this more robust - but
1897.1.2 by Robert Collins
cleanup osutils.walkdirs changes after review.
1422
    # 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%
1423
    _lstat = os.lstat
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1424
    _directory = _directory_kind
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
1425
    _listdir = os.listdir
3696.3.5 by Robert Collins
Streamline _walkdirs_utf8 for utf8 file systems, reducing time to traverse a mozilla tree from 1s to .6 seconds. (Robert Collins)
1426
    _kind_from_mode = file_kind_from_stat_mode
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1427
    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.
1428
    while pending:
1429
        # 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%
1430
        relroot, _, _, _, top = pending.pop()
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1431
        if relroot:
1432
            relprefix = relroot + u'/'
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1433
        else:
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1434
            relprefix = ''
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1435
        top_slash = top + u'/'
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1436
1437
        dirblock = []
1438
        append = dirblock.append
3585.2.4 by Robert Collins
* Deleting directories by hand before running ``bzr rm`` will not
1439
        try:
1440
            names = sorted(_listdir(top))
3596.2.2 by John Arbash Meinel
Factor out the common exception handling looking for ENOTDIR and use it
1441
        except OSError, e:
1442
            if not _is_error_enotdir(e):
3585.2.4 by Robert Collins
* Deleting directories by hand before running ``bzr rm`` will not
1443
                raise
1444
        else:
1445
            for name in names:
1446
                abspath = top_slash + name
1447
                statvalue = _lstat(abspath)
3696.3.5 by Robert Collins
Streamline _walkdirs_utf8 for utf8 file systems, reducing time to traverse a mozilla tree from 1s to .6 seconds. (Robert Collins)
1448
                kind = _kind_from_mode(statvalue.st_mode)
3585.2.4 by Robert Collins
* Deleting directories by hand before running ``bzr rm`` will not
1449
                append((relprefix + name, name, kind, statvalue, abspath))
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1450
        yield (relroot, top), dirblock
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1451
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1452
        # push the user specified dirs from dirblock
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1453
        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.
1454
1455
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1456
class DirReader(object):
1457
    """An interface for reading directories."""
1458
1459
    def top_prefix_to_starting_dir(self, top, prefix=""):
1460
        """Converts top and prefix to a starting dir entry
1461
1462
        :param top: A utf8 path
1463
        :param prefix: An optional utf8 path to prefix output relative paths
1464
            with.
1465
        :return: A tuple starting with prefix, and ending with the native
1466
            encoding of top.
1467
        """
1468
        raise NotImplementedError(self.top_prefix_to_starting_dir)
1469
1470
    def read_dir(self, prefix, top):
1471
        """Read a specific dir.
1472
1473
        :param prefix: A utf8 prefix to be preprended to the path basenames.
1474
        :param top: A natively encoded path to read.
3696.3.10 by Robert Collins
Review feedback.
1475
        :return: A list of the directories contents. Each item contains:
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1476
            (utf8_relpath, utf8_name, kind, lstatvalue, native_abspath)
1477
        """
1478
        raise NotImplementedError(self.read_dir)
1479
1480
1481
_selected_dir_reader = None
1482
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1483
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
1484
def _walkdirs_utf8(top, prefix=""):
1485
    """Yield data about all the directories in a tree.
1486
1487
    This yields the same information as walkdirs() only each entry is yielded
1488
    in utf-8. On platforms which have a filesystem encoding of utf8 the paths
1489
    are returned as exact byte-strings.
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1490
1491
    :return: yields a tuple of (dir_info, [file_info])
1492
        dir_info is (utf8_relpath, path-from-top)
1493
        file_info is (utf8_relpath, utf8_name, kind, lstat, path-from-top)
1494
        if top is an absolute path, path-from-top is also an absolute path.
1495
        path-from-top might be unicode or utf8, but it is the correct path to
1496
        pass to os functions to affect the file in question. (such as os.lstat)
1497
    """
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1498
    global _selected_dir_reader
1499
    if _selected_dir_reader is None:
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1500
        fs_encoding = _fs_enc.upper()
3224.5.17 by Andrew Bennetts
Avoid importing win32utils when sys.platform != win32
1501
        if sys.platform == "win32" and win32utils.winver == 'Windows NT':
3557.2.4 by John Arbash Meinel
Cleanup the tests a bit, and add a test that we downgrade if os.name isn't 'nt'
1502
            # Win98 doesn't have unicode apis like FindFirstFileW
1503
            # TODO: We possibly could support Win98 by falling back to the
1504
            #       original FindFirstFile, and using TCHAR instead of WCHAR,
1505
            #       but that gets a bit tricky, and requires custom compiling
1506
            #       for win98 anyway.
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1507
            try:
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1508
                from bzrlib._walkdirs_win32 import Win32ReadDir
1509
                _selected_dir_reader = Win32ReadDir()
4241.14.6 by Vincent Ladeuil
Start DirReader parametrized tests.
1510
            except ImportError:
1511
                pass
1512
        elif fs_encoding in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1513
            # ANSI_X3.4-1968 is a form of ASCII
3696.3.5 by Robert Collins
Streamline _walkdirs_utf8 for utf8 file systems, reducing time to traverse a mozilla tree from 1s to .6 seconds. (Robert Collins)
1514
            try:
1515
                from bzrlib._readdir_pyx import UTF8DirReader
1516
                _selected_dir_reader = UTF8DirReader()
4574.3.6 by Martin Pool
More warnings when failing to load extensions
1517
            except ImportError, e:
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
1518
                failed_to_load_extension(e)
4241.14.6 by Vincent Ladeuil
Start DirReader parametrized tests.
1519
                pass
1520
1521
    if _selected_dir_reader is None:
1522
        # Fallback to the python version
1523
        _selected_dir_reader = UnicodeDirReader()
1524
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1525
    # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1526
    # But we don't actually uses 1-3 in pending, so set them to None
3696.3.5 by Robert Collins
Streamline _walkdirs_utf8 for utf8 file systems, reducing time to traverse a mozilla tree from 1s to .6 seconds. (Robert Collins)
1527
    pending = [[_selected_dir_reader.top_prefix_to_starting_dir(top, prefix)]]
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1528
    read_dir = _selected_dir_reader.read_dir
1529
    _directory = _directory_kind
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
1530
    while pending:
3696.3.5 by Robert Collins
Streamline _walkdirs_utf8 for utf8 file systems, reducing time to traverse a mozilla tree from 1s to .6 seconds. (Robert Collins)
1531
        relroot, _, _, _, top = pending[-1].pop()
1532
        if not pending[-1]:
1533
            pending.pop()
1534
        dirblock = sorted(read_dir(relroot, top))
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1535
        yield (relroot, top), dirblock
1536
        # push the user specified dirs from dirblock
3696.3.5 by Robert Collins
Streamline _walkdirs_utf8 for utf8 file systems, reducing time to traverse a mozilla tree from 1s to .6 seconds. (Robert Collins)
1537
        next = [d for d in reversed(dirblock) if d[2] == _directory]
1538
        if next:
1539
            pending.append(next)
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1540
1541
1542
class UnicodeDirReader(DirReader):
1543
    """A dir reader for non-utf8 file systems, which transcodes."""
1544
1545
    __slots__ = ['_utf8_encode']
1546
1547
    def __init__(self):
1548
        self._utf8_encode = codecs.getencoder('utf8')
1549
1550
    def top_prefix_to_starting_dir(self, top, prefix=""):
1551
        """See DirReader.top_prefix_to_starting_dir."""
1552
        return (safe_utf8(prefix), None, None, None, safe_unicode(top))
1553
1554
    def read_dir(self, prefix, top):
1555
        """Read a single directory from a non-utf8 file system.
1556
1557
        top, and the abspath element in the output are unicode, all other paths
1558
        are utf8. Local disk IO is done via unicode calls to listdir etc.
1559
1560
        This is currently the fallback code path when the filesystem encoding is
1561
        not UTF-8. It may be better to implement an alternative so that we can
1562
        safely handle paths that are not properly decodable in the current
1563
        encoding.
1564
1565
        See DirReader.read_dir for details.
1566
        """
1567
        _utf8_encode = self._utf8_encode
1568
        _lstat = os.lstat
1569
        _listdir = os.listdir
3696.3.5 by Robert Collins
Streamline _walkdirs_utf8 for utf8 file systems, reducing time to traverse a mozilla tree from 1s to .6 seconds. (Robert Collins)
1570
        _kind_from_mode = file_kind_from_stat_mode
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1571
1572
        if prefix:
1573
            relprefix = prefix + '/'
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1574
        else:
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1575
            relprefix = ''
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1576
        top_slash = top + u'/'
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1577
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1578
        dirblock = []
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1579
        append = dirblock.append
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1580
        for name in sorted(_listdir(top)):
3696.3.12 by Robert Collins
Fix PQM test failure.
1581
            try:
1582
                name_utf8 = _utf8_encode(name)[0]
1583
            except UnicodeDecodeError:
1584
                raise errors.BadFilenameEncoding(
1585
                    _utf8_encode(relprefix)[0] + name, _fs_enc)
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1586
            abspath = top_slash + name
1587
            statvalue = _lstat(abspath)
3696.3.5 by Robert Collins
Streamline _walkdirs_utf8 for utf8 file systems, reducing time to traverse a mozilla tree from 1s to .6 seconds. (Robert Collins)
1588
            kind = _kind_from_mode(statvalue.st_mode)
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1589
            append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1590
        return dirblock
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
1591
1592
1907.3.2 by John Arbash Meinel
Updated the copy_tree function to allow overriding functionality.
1593
def copy_tree(from_path, to_path, handlers={}):
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1594
    """Copy all of the entries in from_path into to_path.
1595
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1596
    :param from_path: The base directory to copy.
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1597
    :param to_path: The target directory. If it does not exist, it will
1598
        be created.
1907.3.2 by John Arbash Meinel
Updated the copy_tree function to allow overriding functionality.
1599
    :param handlers: A dictionary of functions, which takes a source and
1600
        destinations for files, directories, etc.
1601
        It is keyed on the file kind, such as 'directory', 'symlink', or 'file'
1602
        'file', 'directory', and 'symlink' should always exist.
1603
        If they are missing, they will be replaced with 'os.mkdir()',
1604
        'os.readlink() + os.symlink()', and 'shutil.copy2()', respectively.
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1605
    """
1606
    # Now, just copy the existing cached tree to the new location
1607
    # We use a cheap trick here.
1608
    # Absolute paths are prefixed with the first parameter
1609
    # relative paths are prefixed with the second.
1610
    # So we can get both the source and target returned
1611
    # without any extra work.
1612
1907.3.2 by John Arbash Meinel
Updated the copy_tree function to allow overriding functionality.
1613
    def copy_dir(source, dest):
1614
        os.mkdir(dest)
1615
1616
    def copy_link(source, dest):
1617
        """Copy the contents of a symlink"""
1618
        link_to = os.readlink(source)
1619
        os.symlink(link_to, dest)
1620
1621
    real_handlers = {'file':shutil.copy2,
1622
                     'symlink':copy_link,
1623
                     'directory':copy_dir,
1624
                    }
1625
    real_handlers.update(handlers)
1626
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1627
    if not os.path.exists(to_path):
1907.3.2 by John Arbash Meinel
Updated the copy_tree function to allow overriding functionality.
1628
        real_handlers['directory'](from_path, to_path)
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1629
1630
    for dir_info, entries in walkdirs(from_path, prefix=to_path):
1631
        for relpath, name, kind, st, abspath in entries:
1907.3.2 by John Arbash Meinel
Updated the copy_tree function to allow overriding functionality.
1632
            real_handlers[kind](abspath, relpath)
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1633
1634
1773.3.1 by Robert Collins
Add path_prefix_key and compare_paths_prefix_order utility functions.
1635
def path_prefix_key(path):
1636
    """Generate a prefix-order path key for path.
1637
1638
    This can be used to sort paths in the same way that walkdirs does.
1639
    """
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.
1640
    return (dirname(path) , path)
1773.3.1 by Robert Collins
Add path_prefix_key and compare_paths_prefix_order utility functions.
1641
1642
1643
def compare_paths_prefix_order(path_a, path_b):
1644
    """Compare path_a and path_b to generate the same order walkdirs uses."""
1645
    key_a = path_prefix_key(path_a)
1646
    key_b = path_prefix_key(path_b)
1647
    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
1648
1649
1650
_cached_user_encoding = None
1651
1652
2192.1.3 by Alexander Belchenko
Tests for osutils.get_user_encoding
1653
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
1654
    """Find out what the preferred user encoding is.
1655
1656
    This is generally the encoding that is used for command line parameters
1657
    and file contents. This may be different from the terminal encoding
1658
    or the filesystem encoding.
1659
2192.1.3 by Alexander Belchenko
Tests for osutils.get_user_encoding
1660
    :param  use_cache:  Enable cache for detected encoding.
1661
                        (This parameter is turned on by default,
1662
                        and required only for selftesting)
1663
1955.2.2 by John Arbash Meinel
Change the name of the test classes (test_lang => test_locale), move the function into osutils.py
1664
    :return: A string defining the preferred user encoding
1665
    """
1666
    global _cached_user_encoding
2192.1.3 by Alexander Belchenko
Tests for osutils.get_user_encoding
1667
    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
1668
        return _cached_user_encoding
1669
1670
    if sys.platform == 'darwin':
3638.3.10 by Vincent Ladeuil
Provides a better default encoding on OSX.
1671
        # python locale.getpreferredencoding() always return
1672
        # 'mac-roman' on darwin. That's a lie.
1955.2.2 by John Arbash Meinel
Change the name of the test classes (test_lang => test_locale), move the function into osutils.py
1673
        sys.platform = 'posix'
1674
        try:
3638.3.10 by Vincent Ladeuil
Provides a better default encoding on OSX.
1675
            if os.environ.get('LANG', None) is None:
1676
                # If LANG is not set, we end up with 'ascii', which is bad
1677
                # ('mac-roman' is more than ascii), so we set a default which
1678
                # will give us UTF-8 (which appears to work in all cases on
1679
                # OSX). Users are still free to override LANG of course, as
1680
                # long as it give us something meaningful. This work-around
1681
                # *may* not be needed with python 3k and/or OSX 10.5, but will
1682
                # work with them too -- vila 20080908
1683
                os.environ['LANG'] = 'en_US.UTF-8'
1955.2.2 by John Arbash Meinel
Change the name of the test classes (test_lang => test_locale), move the function into osutils.py
1684
            import locale
1685
        finally:
1686
            sys.platform = 'darwin'
1687
    else:
1688
        import locale
1689
1690
    try:
2192.1.3 by Alexander Belchenko
Tests for osutils.get_user_encoding
1691
        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
1692
    except locale.Error, e:
1955.2.3 by John Arbash Meinel
Change error message text
1693
        sys.stderr.write('bzr: warning: %s\n'
2001.2.1 by Jelmer Vernooij
Fix typo in encoding warning.
1694
                         '  Could not determine what text encoding to use.\n'
1955.2.3 by John Arbash Meinel
Change error message text
1695
                         '  This error usually means your Python interpreter\n'
1696
                         '  doesn\'t support the locale set by $LANG (%s)\n'
1697
                         "  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
1698
                         % (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
1699
        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
1700
2127.4.1 by Alexander Belchenko
(jam, bialix) Workaround for cp0 console encoding on Windows
1701
    # Windows returns 'cp0' to indicate there is no code page. So we'll just
1702
    # treat that as ASCII, and not support printing unicode characters to the
1703
    # console.
3405.3.1 by Neil Martinsen-Burrell
accept for an encoding to mean ascii
1704
    #
1705
    # For python scripts run under vim, we get '', so also treat that as ASCII
1706
    if user_encoding in (None, 'cp0', ''):
2192.1.3 by Alexander Belchenko
Tests for osutils.get_user_encoding
1707
        user_encoding = 'ascii'
2192.1.1 by Alexander Belchenko
Before actually using encoding need to check that Python has corresponding codec
1708
    else:
1709
        # check encoding
1710
        try:
2192.1.3 by Alexander Belchenko
Tests for osutils.get_user_encoding
1711
            codecs.lookup(user_encoding)
2192.1.1 by Alexander Belchenko
Before actually using encoding need to check that Python has corresponding codec
1712
        except LookupError:
1713
            sys.stderr.write('bzr: warning:'
1714
                             ' unknown encoding %s.'
1715
                             ' Continuing with ascii encoding.\n'
2192.1.3 by Alexander Belchenko
Tests for osutils.get_user_encoding
1716
                             % user_encoding
2192.1.1 by Alexander Belchenko
Before actually using encoding need to check that Python has corresponding codec
1717
                            )
2192.1.3 by Alexander Belchenko
Tests for osutils.get_user_encoding
1718
            user_encoding = 'ascii'
1719
1720
    if use_cache:
1721
        _cached_user_encoding = user_encoding
1722
1723
    return user_encoding
2091.1.1 by Martin Pool
Avoid MSG_WAITALL as it doesn't work on Windows
1724
1725
3626.1.1 by Mark Hammond
Add osutils.get_host_name() to return a unicode hostname to prevent
1726
def get_host_name():
3626.1.4 by John Arbash Meinel
Document the difference in get_host_name, per Robert's request.
1727
    """Return the current unicode host name.
1728
1729
    This is meant to be used in place of socket.gethostname() because that
1730
    behaves inconsistently on different platforms.
1731
    """
3626.1.1 by Mark Hammond
Add osutils.get_host_name() to return a unicode hostname to prevent
1732
    if sys.platform == "win32":
1733
        import win32utils
1734
        return win32utils.get_host_name()
1735
    else:
1736
        import socket
1737
        return socket.gethostname().decode(get_user_encoding())
1738
1739
2091.1.1 by Martin Pool
Avoid MSG_WAITALL as it doesn't work on Windows
1740
def recv_all(socket, bytes):
1741
    """Receive an exact number of bytes.
1742
1743
    Regular Socket.recv() may return less than the requested number of bytes,
1744
    dependning on what's in the OS buffer.  MSG_WAITALL is not available
1745
    on all platforms, but this should work everywhere.  This will return
1746
    less than the requested amount if the remote end closes.
1747
1748
    This isn't optimized and is intended mostly for use in testing.
1749
    """
1750
    b = ''
1751
    while len(b) < bytes:
3923.3.1 by Andrew Bennetts
Quick attempt at adding some EINTR-proofing to smart protocol code.
1752
        new = until_no_eintr(socket.recv, bytes - len(b))
2091.1.1 by Martin Pool
Avoid MSG_WAITALL as it doesn't work on Windows
1753
        if new == '':
1754
            break # eof
1755
        b += new
1756
    return b
1757
3118.2.1 by Andrew Bennetts
(andrew) Fix #115781 by passing no more than 64k at a time to socket.sendall.
1758
3958.1.5 by Andrew Bennetts
Remove unnecessary 'direction' argument to osutils.send_all.
1759
def send_all(socket, bytes, report_activity=None):
3118.2.1 by Andrew Bennetts
(andrew) Fix #115781 by passing no more than 64k at a time to socket.sendall.
1760
    """Send all bytes on a socket.
1761
1762
    Regular socket.sendall() can give socket error 10053 on Windows.  This
1763
    implementation sends no more than 64k at a time, which avoids this problem.
3958.1.1 by Andrew Bennetts
Report traffic on smart media as transport activity.
1764
1765
    :param report_activity: Call this as bytes are read, see
1766
        Transport._report_activity
3118.2.1 by Andrew Bennetts
(andrew) Fix #115781 by passing no more than 64k at a time to socket.sendall.
1767
    """
1768
    chunk_size = 2**16
1769
    for pos in xrange(0, len(bytes), chunk_size):
3958.1.1 by Andrew Bennetts
Report traffic on smart media as transport activity.
1770
        block = bytes[pos:pos+chunk_size]
1771
        if report_activity is not None:
3958.1.5 by Andrew Bennetts
Remove unnecessary 'direction' argument to osutils.send_all.
1772
            report_activity(len(block), 'write')
3958.1.1 by Andrew Bennetts
Report traffic on smart media as transport activity.
1773
        until_no_eintr(socket.sendall, block)
3118.2.1 by Andrew Bennetts
(andrew) Fix #115781 by passing no more than 64k at a time to socket.sendall.
1774
1775
2091.3.7 by Aaron Bentley
Rename real_parent to dereferenced_path
1776
def dereference_path(path):
1777
    """Determine the real path to a file.
1778
1779
    All parent elements are dereferenced.  But the file itself is not
1780
    dereferenced.
1781
    :param path: The original path.  May be absolute or relative.
1782
    :return: the real path *to* the file
1783
    """
2091.3.5 by Aaron Bentley
Move realpath functionality into osutils
1784
    parent, base = os.path.split(path)
1785
    # The pathjoin for '.' is a workaround for Python bug #1213894.
1786
    # (initial path components aren't dereferenced)
1787
    return pathjoin(realpath(pathjoin('.', parent)), base)
2681.3.4 by Lukáš Lalinsky
- Rename 'windows' to 'mapi'
1788
1789
1790
def supports_mapi():
1791
    """Return True if we can use MAPI to launch a mail client."""
1792
    return sys.platform == "win32"
3089.3.8 by Ian Clatworthy
move resource loading into a reusable function
1793
1794
1795
def resource_string(package, resource_name):
1796
    """Load a resource from a package and return it as a string.
1797
1798
    Note: Only packages that start with bzrlib are currently supported.
1799
1800
    This is designed to be a lightweight implementation of resource
1801
    loading in a way which is API compatible with the same API from
1802
    pkg_resources. See
1803
    http://peak.telecommunity.com/DevCenter/PkgResources#basic-resource-access.
1804
    If and when pkg_resources becomes a standard library, this routine
1805
    can delegate to it.
1806
    """
1807
    # Check package name is within bzrlib
1808
    if package == "bzrlib":
1809
        resource_relpath = resource_name
1810
    elif package.startswith("bzrlib."):
1811
        package = package[len("bzrlib."):].replace('.', os.sep)
1812
        resource_relpath = pathjoin(package, resource_name)
1813
    else:
1814
        raise errors.BzrError('resource package %s not in bzrlib' % package)
1815
1816
    # Map the resource to a file and read its contents
1817
    base = dirname(bzrlib.__file__)
1818
    if getattr(sys, 'frozen', None):    # bzr.exe
1819
        base = abspath(pathjoin(base, '..', '..'))
1820
    filename = pathjoin(base, resource_relpath)
1821
    return open(filename, 'rU').read()
1739.2.7 by Robert Collins
Update readdir pyrex source files and usage in line with current practice.
1822
1823
3696.3.5 by Robert Collins
Streamline _walkdirs_utf8 for utf8 file systems, reducing time to traverse a mozilla tree from 1s to .6 seconds. (Robert Collins)
1824
def file_kind_from_stat_mode_thunk(mode):
1825
    global file_kind_from_stat_mode
1826
    if file_kind_from_stat_mode is file_kind_from_stat_mode_thunk:
1827
        try:
1828
            from bzrlib._readdir_pyx import UTF8DirReader
1829
            file_kind_from_stat_mode = UTF8DirReader().kind_from_mode
4574.3.6 by Martin Pool
More warnings when failing to load extensions
1830
        except ImportError, e:
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
1831
            failed_to_load_extension(e)
3696.3.5 by Robert Collins
Streamline _walkdirs_utf8 for utf8 file systems, reducing time to traverse a mozilla tree from 1s to .6 seconds. (Robert Collins)
1832
            from bzrlib._readdir_py import (
3696.4.8 by Robert Collins
Fix up inter_changes with dirstate both C and python.
1833
                _kind_from_mode as file_kind_from_stat_mode
3696.3.5 by Robert Collins
Streamline _walkdirs_utf8 for utf8 file systems, reducing time to traverse a mozilla tree from 1s to .6 seconds. (Robert Collins)
1834
                )
1835
    return file_kind_from_stat_mode(mode)
1836
file_kind_from_stat_mode = file_kind_from_stat_mode_thunk
1837
1838
1839
def file_kind(f, _lstat=os.lstat):
1840
    try:
1841
        return file_kind_from_stat_mode(_lstat(f).st_mode)
1842
    except OSError, e:
1843
        if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
1844
            raise errors.NoSuchFile(f)
1845
        raise
1846
3923.3.1 by Andrew Bennetts
Quick attempt at adding some EINTR-proofing to smart protocol code.
1847
1848
def until_no_eintr(f, *a, **kw):
3923.3.2 by Andrew Bennetts
Use e.errno rather than e.args[0].
1849
    """Run f(*a, **kw), retrying if an EINTR error occurs."""
3923.3.1 by Andrew Bennetts
Quick attempt at adding some EINTR-proofing to smart protocol code.
1850
    # Borrowed from Twisted's twisted.python.util.untilConcludes function.
1851
    while True:
1852
        try:
1853
            return f(*a, **kw)
1854
        except (IOError, OSError), e:
3923.3.2 by Andrew Bennetts
Use e.errno rather than e.args[0].
1855
            if e.errno == errno.EINTR:
3923.3.1 by Andrew Bennetts
Quick attempt at adding some EINTR-proofing to smart protocol code.
1856
                continue
1857
            raise
1858
4183.6.4 by Martin Pool
Separate out re_compile_checked
1859
def re_compile_checked(re_string, flags=0, where=""):
1860
    """Return a compiled re, or raise a sensible error.
4325.3.2 by Johan Walles
Use a linear algorithm for osutil.minimum_path_selection().
1861
4183.6.4 by Martin Pool
Separate out re_compile_checked
1862
    This should only be used when compiling user-supplied REs.
1863
1864
    :param re_string: Text form of regular expression.
1865
    :param flags: eg re.IGNORECASE
4325.3.2 by Johan Walles
Use a linear algorithm for osutil.minimum_path_selection().
1866
    :param where: Message explaining to the user the context where
4183.6.4 by Martin Pool
Separate out re_compile_checked
1867
        it occurred, eg 'log search filter'.
1868
    """
1869
    # from https://bugs.launchpad.net/bzr/+bug/251352
1870
    try:
1871
        re_obj = re.compile(re_string, flags)
1872
        re_obj.search("")
1873
        return re_obj
1874
    except re.error, e:
1875
        if where:
1876
            where = ' in ' + where
1877
        # despite the name 'error' is a type
1878
        raise errors.BzrCommandError('Invalid regular expression%s: %r: %s'
1879
            % (where, re_string, e))
1880
3923.3.1 by Andrew Bennetts
Quick attempt at adding some EINTR-proofing to smart protocol code.
1881
0.16.79 by Aaron Bentley
Remove dependencies on bzrtools
1882
if sys.platform == "win32":
1883
    import msvcrt
1884
    def getchar():
1885
        return msvcrt.getch()
1886
else:
1887
    import tty
1888
    import termios
1889
    def getchar():
1890
        fd = sys.stdin.fileno()
1891
        settings = termios.tcgetattr(fd)
1892
        try:
1893
            tty.setraw(fd)
1894
            ch = sys.stdin.read(1)
1895
        finally:
1896
            termios.tcsetattr(fd, termios.TCSADRAIN, settings)
1897
        return ch
4398.4.3 by Vincent Ladeuil
Detect # cores on win32 and Solaris too.
1898
1899
1900
if sys.platform == 'linux2':
1901
    def _local_concurrency():
1902
        concurrency = None
1903
        prefix = 'processor'
1904
        for line in file('/proc/cpuinfo', 'rb'):
1905
            if line.startswith(prefix):
1906
                concurrency = int(line[line.find(':')+1:]) + 1
1907
        return concurrency
1908
elif sys.platform == 'darwin':
1909
    def _local_concurrency():
1910
        return subprocess.Popen(['sysctl', '-n', 'hw.availcpu'],
1911
                                stdout=subprocess.PIPE).communicate()[0]
4413.1.1 by Matthew Fuller
Catch the number of cores on FreeBSD too.
1912
elif sys.platform[0:7] == 'freebsd':
1913
    def _local_concurrency():
1914
        return subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
1915
                                stdout=subprocess.PIPE).communicate()[0]
4398.4.3 by Vincent Ladeuil
Detect # cores on win32 and Solaris too.
1916
elif sys.platform == 'sunos5':
1917
    def _local_concurrency():
1918
        return subprocess.Popen(['psrinfo', '-p',],
1919
                                stdout=subprocess.PIPE).communicate()[0]
1920
elif sys.platform == "win32":
1921
    def _local_concurrency():
4398.4.4 by Vincent Ladeuil
Fixed as per John's review.
1922
        # This appears to return the number of cores.
4398.4.3 by Vincent Ladeuil
Detect # cores on win32 and Solaris too.
1923
        return os.environ.get('NUMBER_OF_PROCESSORS')
1924
else:
1925
    def _local_concurrency():
1926
        # Who knows ?
1927
        return None
1928
1929
4398.4.4 by Vincent Ladeuil
Fixed as per John's review.
1930
_cached_local_concurrency = None
1931
1932
def local_concurrency(use_cache=True):
4398.4.3 by Vincent Ladeuil
Detect # cores on win32 and Solaris too.
1933
    """Return how many processes can be run concurrently.
1934
1935
    Rely on platform specific implementations and default to 1 (one) if
1936
    anything goes wrong.
1937
    """
4398.4.4 by Vincent Ladeuil
Fixed as per John's review.
1938
    global _cached_local_concurrency
1939
    if _cached_local_concurrency is not None and use_cache:
1940
        return _cached_local_concurrency
1941
4398.4.3 by Vincent Ladeuil
Detect # cores on win32 and Solaris too.
1942
    try:
1943
        concurrency = _local_concurrency()
1944
    except (OSError, IOError):
1945
        concurrency = None
1946
    try:
1947
        concurrency = int(concurrency)
1948
    except (TypeError, ValueError):
1949
        concurrency = 1
4398.4.4 by Vincent Ladeuil
Fixed as per John's review.
1950
    if use_cache:
1951
        _cached_concurrency = concurrency
4398.4.3 by Vincent Ladeuil
Detect # cores on win32 and Solaris too.
1952
    return concurrency