/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
5594.1.1 by Vincent Ladeuil
Fix socketpair-based SSH transport leaking socket into other child processes
1
# Copyright (C) 2005-2011 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
6379.6.1 by Jelmer Vernooij
Import absolute_import in a few places.
17
from __future__ import absolute_import
18
5225.1.1 by Andrew Bennetts
Don't lazy_import errno in osutils; it's a builtin module, and that lazy_import is implicated in a FreeBSD builder failure.
19
import errno
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
20
import os
21
import re
22
import stat
23
import sys
24
import time
5051.2.1 by Benjamin Peterson
move codecs import out of lazy section since it is used on module import
25
import codecs
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
26
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
27
from .lazy_import import lazy_import
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
28
lazy_import(globals(), """
2215.6.1 by James Henstridge
Don't rely on time.timezone and time.altzone in local_time_offset(),
29
from datetime import datetime
6621.1.1 by Florent Gallaire
Fix for Windows and 32-bit platforms buggy gmtime().
30
from datetime import timedelta
5187.2.7 by Parth Malwankar
moved getuser_unicode to osutils.
31
import getpass
6383.1.1 by Martin Packman
Simplify get_user_encoding by avoiding locale hacks and assuming setlocale has been called
32
import locale
5273.1.2 by Vincent Ladeuil
Cleanup imports in osutils.py.
33
import ntpath
1711.4.5 by John Arbash Meinel
the _posix_* routines should use posixpath not os.path, so tests pass on win32
34
import posixpath
6336.2.1 by Martin Packman
Add is_environment_error() and switch trace to using it
35
import select
5273.1.11 by Vincent Ladeuil
Really fix and better explain why we need both the module and the symbol.
36
# We need to import both shutil and rmtree as we export the later on posix
37
# and need the former on windows
38
import shutil
5273.1.10 by Vincent Ladeuil
Fixed as per jam's review.
39
from shutil import rmtree
5011.3.4 by Andrew Bennetts
Reinstate osutils.until_no_eintr and .send_all, reapply until_no_eintr in SmartSimplePipesClientMedium.read_bytes.
40
import socket
4398.4.3 by Vincent Ladeuil
Detect # cores on win32 and Solaris too.
41
import subprocess
5273.1.11 by Vincent Ladeuil
Really fix and better explain why we need both the module and the symbol.
42
# We need to import both tempfile and mkdtemp as we export the later on posix
43
# and need the former on windows
44
import tempfile
45
from tempfile import mkdtemp
1185.85.75 by John Arbash Meinel
Adding bzrlib.osutils.unicode_filename to handle unicode normalization for file paths.
46
import unicodedata
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
47
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
48
from breezy import (
6059.4.2 by Vincent Ladeuil
Migrate ignore_missing_extensions to stack-based config.
49
    config,
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
50
    errors,
5011.3.16 by Andrew Bennetts
Merge lp:bzr.
51
    trace,
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
    )
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
54
from breezy.i18n import gettext
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
55
""")
1 by mbp at sourcefrog
import from baz patch-364
56
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
57
from .sixish import (
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
58
    PY3,
59
    text_type,
60
    )
5011.3.3 by Martin
Reintroduce EINTR handling only for socket object functions and general cleanup
61
5848.2.1 by John Arbash Meinel
Break compatibility with python <2.6.
62
from hashlib import (
63
    md5,
64
    sha1 as sha,
65
    )
2929.3.1 by Vincent Ladeuil
Fix python2.6 deprecation warnings (still 4 failures 5 errors in test suite).
66
3504.4.1 by John Arbash Meinel
Write an alternative 'walkdirs' implementation that uses win32 apis.
67
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
68
import breezy
6630.1.1 by Jelmer Vernooij
Remove deprecated functionality.
69
from . import _fs_enc
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
70
1 by mbp at sourcefrog
import from baz patch-364
71
4889.2.5 by John Arbash Meinel
Review feedback from Andrew.
72
# Cross platform wall-clock time functionality with decent resolution.
73
# On Linux ``time.clock`` returns only CPU time. On Windows, ``time.time()``
74
# only has a resolution of ~15ms. Note that ``time.clock()`` is not
75
# synchronized with ``time.time()``, this is only meant to be used to find
76
# delta times by subtracting from another call to this function.
4889.2.1 by John Arbash Meinel
Make -Dhpss log debug information for the server process.
77
timer_func = time.time
78
if sys.platform == 'win32':
79
    timer_func = time.clock
80
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
81
# On win32, O_BINARY is used to indicate the file should
82
# be opened in binary mode, rather than text mode.
83
# On other platforms, O_BINARY doesn't exist, because
84
# they always open in binary mode, so it is okay to
4634.140.12 by INADA Naoki
small clean up.
85
# OR with 0 on those platforms.
86
# O_NOINHERIT and O_TEXT exists only on win32 too.
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
87
O_BINARY = getattr(os, 'O_BINARY', 0)
4634.140.12 by INADA Naoki
small clean up.
88
O_TEXT = getattr(os, 'O_TEXT', 0)
4634.140.1 by INADA Naoki
Avoids child process inherits file handles on win32. by using os.fdopen and os.open with O_NOINHERIT instead of builtin open.
89
O_NOINHERIT = getattr(os, 'O_NOINHERIT', 0)
90
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
91
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.
92
def get_unicode_argv():
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
93
    if PY3:
94
        return sys.argv[1:]
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.
95
    try:
96
        user_encoding = get_user_encoding()
5274.4.8 by Jason Spashett
Reverse merge -r 5280..5279
97
        return [a.decode(user_encoding) for a in sys.argv[1:]]
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.
98
    except UnicodeDecodeError:
6138.3.8 by Jonathan Riddell
more error gettext()ing
99
        raise errors.BzrError(gettext("Parameter {0!r} encoding is unsupported by {1} "
100
            "application locale.").format(a, user_encoding))
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.
101
102
1 by mbp at sourcefrog
import from baz patch-364
103
def make_readonly(filename):
104
    """Make a filename read-only."""
2949.6.1 by Alexander Belchenko
windows python has os.lstat
105
    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
106
    if not stat.S_ISLNK(mod):
6619.3.14 by Jelmer Vernooij
Convert some octal numbers to new notations.
107
        mod = mod & 0o777555
6015.50.1 by Martin Pool
Use a chmod wrapper to cope with eperm from chmod
108
        chmod_if_possible(filename, mod)
1 by mbp at sourcefrog
import from baz patch-364
109
110
111
def make_writable(filename):
2949.6.1 by Alexander Belchenko
windows python has os.lstat
112
    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
113
    if not stat.S_ISLNK(mod):
6619.3.14 by Jelmer Vernooij
Convert some octal numbers to new notations.
114
        mod = mod | 0o200
6015.50.1 by Martin Pool
Use a chmod wrapper to cope with eperm from chmod
115
        chmod_if_possible(filename, mod)
116
117
118
def chmod_if_possible(filename, mode):
119
    # Set file mode if that can be safely done.
120
    # Sometimes even on unix the filesystem won't allow it - see
121
    # https://bugs.launchpad.net/bzr/+bug/606537
122
    try:
123
        # It is probably faster to just do the chmod, rather than
124
        # doing a stat, and then trying to compare
125
        os.chmod(filename, mode)
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
126
    except (IOError, OSError) as e:
6015.50.2 by Martin Pool
Also suppress EACCES from chmod
127
        # Permission/access denied seems to commonly happen on smbfs; there's
128
        # probably no point warning about it.
6015.50.1 by Martin Pool
Use a chmod wrapper to cope with eperm from chmod
129
        # <https://bugs.launchpad.net/bzr/+bug/606537>
6015.50.2 by Martin Pool
Also suppress EACCES from chmod
130
        if getattr(e, 'errno') in (errno.EPERM, errno.EACCES):
6015.50.3 by Martin Pool
More correct trace message when squelching chmod errors
131
            trace.mutter("ignore error on chmod of %r: %r" % (
132
                filename, e))
6015.50.1 by Martin Pool
Use a chmod wrapper to cope with eperm from chmod
133
            return
134
        raise
1 by mbp at sourcefrog
import from baz patch-364
135
136
2825.7.1 by Robert Collins
* Partial commits are now approximately 40% faster by walking over the
137
def minimum_path_selection(paths):
138
    """Return the smallset subset of paths which are outside paths.
139
2843.1.1 by Ian Clatworthy
Faster partial commits by walking less data (Robert Collins)
140
    :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
141
    :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
142
        is_inside, drawn from the paths parameter.
2825.7.1 by Robert Collins
* Partial commits are now approximately 40% faster by walking over the
143
    """
4325.3.7 by Johan Walles
Style fixes for minimum_path_selection().
144
    if len(paths) < 2:
145
        return set(paths)
4325.3.3 by Johan Walles
Add unit test and fix for minimum_path_selection() vs directory names with
146
147
    def sort_key(path):
148
        return path.split('/')
149
    sorted_paths = sorted(list(paths), key=sort_key)
150
4325.3.7 by Johan Walles
Style fixes for minimum_path_selection().
151
    search_paths = [sorted_paths[0]]
152
    for path in sorted_paths[1:]:
4325.3.2 by Johan Walles
Use a linear algorithm for osutil.minimum_path_selection().
153
        if not is_inside(search_paths[-1], path):
154
            # This path is unique, add it
155
            search_paths.append(path)
4325.3.7 by Johan Walles
Style fixes for minimum_path_selection().
156
4325.3.2 by Johan Walles
Use a linear algorithm for osutil.minimum_path_selection().
157
    return set(search_paths)
2825.7.1 by Robert Collins
* Partial commits are now approximately 40% faster by walking over the
158
159
1077 by Martin Pool
- avoid compiling REs at module load time
160
_QUOTE_RE = None
969 by Martin Pool
- Add less-sucky is_within_any
161
162
1 by mbp at sourcefrog
import from baz patch-364
163
def quotefn(f):
779 by Martin Pool
- better quotefn for windows: use doublequotes for strings with
164
    """Return a quoted filename filename
165
166
    This previously used backslash quoting, but that works poorly on
167
    Windows."""
168
    # TODO: I'm not really sure this is the best format either.x
1077 by Martin Pool
- avoid compiling REs at module load time
169
    global _QUOTE_RE
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
170
    if _QUOTE_RE is None:
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
171
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
172
779 by Martin Pool
- better quotefn for windows: use doublequotes for strings with
173
    if _QUOTE_RE.search(f):
174
        return '"' + f + '"'
175
    else:
176
        return f
1 by mbp at sourcefrog
import from baz patch-364
177
178
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
179
_directory_kind = 'directory'
180
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
181
def get_umask():
182
    """Return the current umask"""
183
    # Assume that people aren't messing with the umask while running
184
    # XXX: This is not thread safe, but there is no way to get the
185
    #      umask without setting it
186
    umask = os.umask(0)
187
    os.umask(umask)
188
    return umask
189
190
2324.2.1 by Dmitry Vasiliev
kind_marker() optimization
191
_kind_marker_map = {
192
    "file": "",
193
    _directory_kind: "/",
194
    "symlink": "@",
1551.10.30 by Aaron Bentley
Merge from bzr.dev
195
    'tree-reference': '+',
2324.2.1 by Dmitry Vasiliev
kind_marker() optimization
196
}
1551.10.30 by Aaron Bentley
Merge from bzr.dev
197
198
488 by Martin Pool
- new helper function kind_marker()
199
def kind_marker(kind):
2324.2.1 by Dmitry Vasiliev
kind_marker() optimization
200
    try:
201
        return _kind_marker_map[kind]
202
    except KeyError:
5024.1.2 by John Arbash Meinel
Switch so that all unknown files get an empty marker, rather than failing.
203
        # Slightly faster than using .get(, '') when the common case is that
204
        # kind will be found
205
        return ''
1 by mbp at sourcefrog
import from baz patch-364
206
2324.2.1 by Dmitry Vasiliev
kind_marker() optimization
207
1732.1.2 by John Arbash Meinel
just use os.path.lexists if it exists
208
lexists = getattr(os.path, 'lexists', None)
209
if lexists is None:
210
    def lexists(f):
211
        try:
2324.2.2 by Dmitry Vasiliev
Fixed lexists() implementation
212
            stat = getattr(os, 'lstat', os.stat)
213
            stat(f)
1732.1.2 by John Arbash Meinel
just use os.path.lexists if it exists
214
            return True
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
215
        except OSError as e:
1732.1.2 by John Arbash Meinel
just use os.path.lexists if it exists
216
            if e.errno == errno.ENOENT:
217
                return False;
218
            else:
6138.3.8 by Jonathan Riddell
more error gettext()ing
219
                raise errors.BzrError(gettext("lstat/stat of ({0!r}): {1!r}").format(f, e))
1732.1.2 by John Arbash Meinel
just use os.path.lexists if it exists
220
1 by mbp at sourcefrog
import from baz patch-364
221
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
222
def fancy_rename(old, new, rename_func, unlink_func):
223
    """A fancy rename, when you don't have atomic rename.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
224
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
225
    :param old: The old path, to rename from
226
    :param new: The new path, to rename to
227
    :param rename_func: The potentially non-atomic rename function
4935.1.1 by Vincent Ladeuil
Support Unicode paths for ftp transport (encoded as utf8).
228
    :param unlink_func: A way to delete the target file if the full rename
229
        succeeds
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
230
    """
231
    # sftp rename doesn't allow overwriting, so play tricks:
232
    base = os.path.basename(new)
233
    dirname = os.path.dirname(new)
4935.1.3 by Vincent Ladeuil
Better fix for fancy_rename respecting callers file encoding.
234
    # callers use different encodings for the paths so the following MUST
235
    # respect that. We rely on python upcasting to unicode if new is unicode
236
    # and keeping a str if not.
237
    tmp_name = 'tmp.%s.%.9f.%d.%s' % (base, time.time(),
238
                                      os.getpid(), rand_chars(10))
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
239
    tmp_name = pathjoin(dirname, tmp_name)
240
241
    # Rename the file out of the way, but keep track if it didn't exist
242
    # We don't want to grab just any exception
243
    # something like EACCES should prevent us from continuing
244
    # The downside is that the rename_func has to throw an exception
245
    # with an errno = ENOENT, or NoSuchFile
246
    file_existed = False
247
    try:
248
        rename_func(new, tmp_name)
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
249
    except (errors.NoSuchFile,) as e:
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
250
        pass
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
251
    except IOError as e:
1532 by Robert Collins
Merge in John Meinels integration branch.
252
        # 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'.
253
        # function raises an IOError with errno is None when a rename fails.
1532 by Robert Collins
Merge in John Meinels integration branch.
254
        # This then gets caught here.
1185.50.37 by John Arbash Meinel
Fixed exception handling for fancy_rename
255
        if e.errno not in (None, errno.ENOENT, errno.ENOTDIR):
1532 by Robert Collins
Merge in John Meinels integration branch.
256
            raise
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
257
    except Exception as e:
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
258
        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.
259
            or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
260
            raise
261
    else:
262
        file_existed = True
263
264
    success = False
265
    try:
6619.3.27 by Martin
Unify try/except/finally block to avoid reraise complexity
266
        # This may throw an exception, in which case success will
267
        # not be set.
268
        rename_func(old, new)
269
        success = True
270
    except (IOError, OSError) as e:
271
        # source and target may be aliases of each other (e.g. on a
272
        # case-insensitive filesystem), so we may have accidentally renamed
273
        # source by when we tried to rename target
274
        if (file_existed and e.errno in (None, errno.ENOENT)
275
            and old.lower() == new.lower()):
276
            # source and target are the same file on a case-insensitive
277
            # filesystem, so we don't generate an exception
278
            pass
279
        else:
280
            raise
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
281
    finally:
282
        if file_existed:
283
            # If the file used to exist, rename it back into place
284
            # otherwise just delete it from the tmp location
285
            if success:
1551.15.4 by Aaron Bentley
Revert now-unnecessary changes
286
                unlink_func(tmp_name)
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
287
            else:
1185.31.49 by John Arbash Meinel
Some corrections using the new osutils.rename. **ALL TESTS PASS**
288
                rename_func(tmp_name, new)
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
289
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
290
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
291
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
292
# choke on a Unicode string containing a relative path if
293
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
294
# string.
295
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
296
    # jam 20060426 rather than encoding to fsencoding
297
    # copy posixpath.abspath, but use os.getcwdu instead
298
    if not posixpath.isabs(path):
299
        path = posixpath.join(getcwd(), path)
6015.39.2 by Florian Vichot
Fixed an infinite loop when creating a repo at the root of the filesystem,
300
    return _posix_normpath(path)
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
301
302
303
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
304
    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
305
306
6015.39.2 by Florian Vichot
Fixed an infinite loop when creating a repo at the root of the filesystem,
307
def _posix_normpath(path):
308
    path = posixpath.normpath(path)
309
    # Bug 861008: posixpath.normpath() returns a path normalized according to
310
    # the POSIX standard, which stipulates (for compatibility reasons) that two
311
    # leading slashes must not be simplified to one, and only if there are 3 or
312
    # more should they be simplified as one. So we treat the leading 2 slashes
313
    # as a special case here by simply removing the first slash, as we consider
314
    # that breaking POSIX compatibility for this obscure feature is acceptable.
315
    # This is not a paranoid precaution, as we notably get paths like this when
316
    # the repo is hosted at the root of the filesystem, i.e. in "/".    
317
    if path.startswith('//'):
318
        path = path[1:]
319
    return path
320
321
6362.2.1 by Martin Packman
Add path_from_environ function for getting unicode paths from envvars
322
def _posix_path_from_environ(key):
323
    """Get unicode path from `key` in environment or None if not present
324
325
    Note that posix systems use arbitrary byte strings for filesystem objects,
326
    so a path that raises BadFilenameEncoding here may still be accessible.
327
    """
328
    val = os.environ.get(key, None)
329
    if val is None:
330
        return val
331
    try:
332
        return val.decode(_fs_enc)
333
    except UnicodeDecodeError:
334
        # GZ 2011-12-12:Ideally want to include `key` in the exception message
335
        raise errors.BadFilenameEncoding(val, _fs_enc)
336
337
6437.26.1 by Martin Packman
Add and test osutils._get_home_dir for unicode access to home location across platforms
338
def _posix_get_home_dir():
339
    """Get the home directory of the current user as a unicode path"""
340
    path = posixpath.expanduser("~")
341
    try:
342
        return path.decode(_fs_enc)
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
343
    except AttributeError:
344
        return path
6437.26.1 by Martin Packman
Add and test osutils._get_home_dir for unicode access to home location across platforms
345
    except UnicodeDecodeError:
346
        raise errors.BadFilenameEncoding(path, _fs_enc)
347
348
6362.2.4 by Martin Packman
Use native functions for getting username avoiding bug 660174 entirely
349
def _posix_getuser_unicode():
350
    """Get username from environment or password database as unicode"""
351
    name = getpass.getuser()
352
    user_encoding = get_user_encoding()
353
    try:
354
        return name.decode(user_encoding)
355
    except UnicodeDecodeError:
356
        raise errors.BzrError("Encoding of username %r is unsupported by %s "
357
            "application locale." % (name, user_encoding))
358
359
1711.5.2 by John Arbash Meinel
win32 likes to return lowercase drive letters sometimes, and uppercase at other times. normalize this
360
def _win32_fixdrive(path):
361
    """Force drive letters to be consistent.
362
363
    win32 is inconsistent whether it returns lower or upper case
364
    and even if it was consistent the user might type the other
365
    so we force it to uppercase
366
    running python.exe under cmd.exe return capital C:\\
367
    running win32 python inside a cygwin shell returns lowercase c:\\
368
    """
5273.1.2 by Vincent Ladeuil
Cleanup imports in osutils.py.
369
    drive, path = ntpath.splitdrive(path)
1711.5.2 by John Arbash Meinel
win32 likes to return lowercase drive letters sometimes, and uppercase at other times. normalize this
370
    return drive.upper() + path
371
372
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
373
def _win32_abspath(path):
5273.1.2 by Vincent Ladeuil
Cleanup imports in osutils.py.
374
    # Real ntpath.abspath doesn't have a problem with a unicode cwd
375
    return _win32_fixdrive(ntpath.abspath(unicode(path)).replace('\\', '/'))
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
376
377
2279.4.1 by Alexander Belchenko
Reimplementation of ntpath.abspath in Python for Windows98: unicode safe, UNC path safe
378
def _win98_abspath(path):
379
    """Return the absolute version of a path.
380
    Windows 98 safe implementation (python reimplementation
381
    of Win32 API function GetFullPathNameW)
382
    """
383
    # Corner cases:
384
    #   C:\path     => C:/path
385
    #   C:/path     => C:/path
386
    #   \\HOST\path => //HOST/path
387
    #   //HOST/path => //HOST/path
388
    #   path        => C:/cwd/path
389
    #   /path       => C:/path
390
    path = unicode(path)
391
    # check for absolute path
5273.1.2 by Vincent Ladeuil
Cleanup imports in osutils.py.
392
    drive = ntpath.splitdrive(path)[0]
2279.4.1 by Alexander Belchenko
Reimplementation of ntpath.abspath in Python for Windows98: unicode safe, UNC path safe
393
    if drive == '' and path[:2] not in('//','\\\\'):
6619.3.26 by Martin
Fix fallout from 2to3 getcwdu transformation and other test uses
394
        cwd = _getcwd()
2279.4.1 by Alexander Belchenko
Reimplementation of ntpath.abspath in Python for Windows98: unicode safe, UNC path safe
395
        # we cannot simply os.path.join cwd and path
396
        # because os.path.join('C:','/path') produce '/path'
397
        # and this is incorrect
398
        if path[:1] in ('/','\\'):
5273.1.2 by Vincent Ladeuil
Cleanup imports in osutils.py.
399
            cwd = ntpath.splitdrive(cwd)[0]
2279.4.3 by Alexander Belchenko
win98_abspath: support for running in POSIX environment: cwd path has not drive letter
400
            path = path[1:]
2279.4.1 by Alexander Belchenko
Reimplementation of ntpath.abspath in Python for Windows98: unicode safe, UNC path safe
401
        path = cwd + '\\' + path
5273.1.2 by Vincent Ladeuil
Cleanup imports in osutils.py.
402
    return _win32_fixdrive(ntpath.normpath(path).replace('\\', '/'))
2279.4.1 by Alexander Belchenko
Reimplementation of ntpath.abspath in Python for Windows98: unicode safe, UNC path safe
403
404
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
405
def _win32_realpath(path):
5273.1.2 by Vincent Ladeuil
Cleanup imports in osutils.py.
406
    # Real ntpath.realpath doesn't have a problem with a unicode cwd
407
    return _win32_fixdrive(ntpath.realpath(unicode(path)).replace('\\', '/'))
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
408
409
410
def _win32_pathjoin(*args):
5273.1.2 by Vincent Ladeuil
Cleanup imports in osutils.py.
411
    return ntpath.join(*args).replace('\\', '/')
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
412
413
414
def _win32_normpath(path):
5273.1.2 by Vincent Ladeuil
Cleanup imports in osutils.py.
415
    return _win32_fixdrive(ntpath.normpath(unicode(path)).replace('\\', '/'))
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
416
417
418
def _win32_getcwd():
6619.3.26 by Martin
Fix fallout from 2to3 getcwdu transformation and other test uses
419
    return _win32_fixdrive(_getcwd().replace('\\', '/'))
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
420
421
422
def _win32_mkdtemp(*args, **kwargs):
5331.3.1 by Martin
Avoid infinite recursion with _win32_mkdtemp by using module namespaced name
423
    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
424
425
426
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.
427
    """We expect to be able to atomically replace 'new' with old.
428
1711.7.17 by John Arbash Meinel
Delay the extra syscall in _win32_rename until we get a failure.
429
    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
430
    and then deleted.
1711.7.6 by John Arbash Meinel
Change _win32_rename() so that it raises ENOENT *before* it tries any renaming.
431
    """
1711.7.17 by John Arbash Meinel
Delay the extra syscall in _win32_rename until we get a failure.
432
    try:
5186.2.11 by Martin Pool
_win32_rename no longer relies on _wrapped_rename
433
        fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
434
    except OSError as e:
1830.3.15 by John Arbash Meinel
On Mac we get EINVAL when renaming cwd
435
        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
436
            # If we try to rename a non-existant file onto cwd, we get
437
            # 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
438
            # if the old path doesn't exist, sometimes we get EACCES
439
            # 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.
440
            os.lstat(old)
441
        raise
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
442
443
1830.3.11 by John Arbash Meinel
Create a mac version of 'getcwd()' which normalizes the path.
444
def _mac_getcwd():
6619.3.26 by Martin
Fix fallout from 2to3 getcwdu transformation and other test uses
445
    return unicodedata.normalize('NFC', _getcwd())
1830.3.11 by John Arbash Meinel
Create a mac version of 'getcwd()' which normalizes the path.
446
447
6468.6.1 by Ross Lagerwall
Change osutils.rename to extend any exception information given from os.rename.
448
def _rename_wrap_exception(rename_func):
449
    """Adds extra information to any exceptions that come from rename().
450
451
    The exception has an updated message and 'old_filename' and 'new_filename'
452
    attributes.
453
    """
454
455
    def _rename_wrapper(old, new):
456
        try:
457
            rename_func(old, new)
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
458
        except OSError as e:
6468.6.1 by Ross Lagerwall
Change osutils.rename to extend any exception information given from os.rename.
459
            detailed_error = OSError(e.errno, e.strerror +
460
                                " [occurred when renaming '%s' to '%s']" %
461
                                (old, new))
462
            detailed_error.old_filename = old
463
            detailed_error.new_filename = new
464
            raise detailed_error
465
466
    return _rename_wrapper
467
6619.3.26 by Martin
Fix fallout from 2to3 getcwdu transformation and other test uses
468
469
if sys.version_info > (3,):
470
    _getcwd = os.getcwd
471
else:
472
    _getcwd = os.getcwdu
473
474
6468.6.1 by Ross Lagerwall
Change osutils.rename to extend any exception information given from os.rename.
475
# Default rename wraps os.rename()
476
rename = _rename_wrap_exception(os.rename)
477
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
478
# Default is to just use the python builtins, but these can be rebound on
479
# particular platforms.
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
480
abspath = _posix_abspath
481
realpath = _posix_realpath
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
482
pathjoin = os.path.join
6015.39.2 by Florian Vichot
Fixed an infinite loop when creating a repo at the root of the filesystem,
483
normpath = _posix_normpath
6362.2.1 by Martin Packman
Add path_from_environ function for getting unicode paths from envvars
484
path_from_environ = _posix_path_from_environ
6437.26.1 by Martin Packman
Add and test osutils._get_home_dir for unicode access to home location across platforms
485
_get_home_dir = _posix_get_home_dir
6362.2.4 by Martin Packman
Use native functions for getting username avoiding bug 660174 entirely
486
getuser_unicode = _posix_getuser_unicode
6619.3.26 by Martin
Fix fallout from 2to3 getcwdu transformation and other test uses
487
getcwd = _getcwd
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
488
dirname = os.path.dirname
489
basename = os.path.basename
2215.4.2 by Alexander Belchenko
split and splitext now the part of osutils
490
split = os.path.split
491
splitext = os.path.splitext
5273.1.10 by Vincent Ladeuil
Fixed as per jam's review.
492
# These were already lazily imported into local scope
493
# mkdtemp = tempfile.mkdtemp
494
# rmtree = shutil.rmtree
5609.29.5 by John Arbash Meinel
Fix bug #740932. Transform should update the sha cache.
495
lstat = os.lstat
496
fstat = os.fstat
497
498
def wrap_stat(st):
499
    return st
500
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
501
1551.2.53 by abentley
Strip trailing slashes in a platform-sensible way
502
MIN_ABS_PATHLENGTH = 1
503
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
504
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
505
if sys.platform == 'win32':
3224.5.35 by Andrew Bennetts
More improvements suggested by John's review.
506
    if win32utils.winver == 'Windows 98':
507
        abspath = _win98_abspath
508
    else:
509
        abspath = _win32_abspath
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
510
    realpath = _win32_realpath
511
    pathjoin = _win32_pathjoin
512
    normpath = _win32_normpath
513
    getcwd = _win32_getcwd
514
    mkdtemp = _win32_mkdtemp
6468.6.1 by Ross Lagerwall
Change osutils.rename to extend any exception information given from os.rename.
515
    rename = _rename_wrap_exception(_win32_rename)
5609.29.5 by John Arbash Meinel
Fix bug #740932. Transform should update the sha cache.
516
    try:
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
517
        from . import _walkdirs_win32
5609.29.5 by John Arbash Meinel
Fix bug #740932. Transform should update the sha cache.
518
    except ImportError:
519
        pass
520
    else:
521
        lstat = _walkdirs_win32.lstat
522
        fstat = _walkdirs_win32.fstat
523
        wrap_stat = _walkdirs_win32.wrap_stat
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
524
1551.2.53 by abentley
Strip trailing slashes in a platform-sensible way
525
    MIN_ABS_PATHLENGTH = 3
1532 by Robert Collins
Merge in John Meinels integration branch.
526
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
527
    def _win32_delete_readonly(function, path, excinfo):
528
        """Error handler for shutil.rmtree function [for win32]
529
        Helps to remove files and dirs marked as read-only.
530
        """
2116.5.1 by Henri Wiechers
Fixes osutils.rmtree on Windows with Python 2.5
531
        exception = excinfo[1]
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
532
        if function in (os.remove, os.rmdir) \
2116.5.1 by Henri Wiechers
Fixes osutils.rmtree on Windows with Python 2.5
533
            and isinstance(exception, OSError) \
534
            and exception.errno == errno.EACCES:
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
535
            make_writable(path)
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
536
            function(path)
537
        else:
538
            raise
539
540
    def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
541
        """Replacer for shutil.rmtree: could remove readonly dirs/files"""
542
        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.
543
544
    f = win32utils.get_unicode_argv     # special function or None
545
    if f is not None:
546
        get_unicode_argv = f
6362.2.1 by Martin Packman
Add path_from_environ function for getting unicode paths from envvars
547
    path_from_environ = win32utils.get_environ_unicode
6437.26.1 by Martin Packman
Add and test osutils._get_home_dir for unicode access to home location across platforms
548
    _get_home_dir = win32utils.get_home_location
6362.2.4 by Martin Packman
Use native functions for getting username avoiding bug 660174 entirely
549
    getuser_unicode = win32utils.get_user_name
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.
550
1830.3.11 by John Arbash Meinel
Create a mac version of 'getcwd()' which normalizes the path.
551
elif sys.platform == 'darwin':
552
    getcwd = _mac_getcwd
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
553
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
554
5320.2.4 by Robert Collins
``bzrlib.osutils.get_terminal_encoding`` will now only mutter its
555
def get_terminal_encoding(trace=False):
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.
556
    """Find the best encoding for printing to the screen.
557
558
    This attempts to check both sys.stdout and sys.stdin to see
559
    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.
560
    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.
561
    The problem is that on Windows, locale.getpreferredencoding()
562
    is not the same encoding as that used by the console:
563
    http://mail.python.org/pipermail/python-list/2003-May/162357.html
564
565
    On my standard US Windows XP, the preferred encoding is
566
    cp1252, but the console is cp437
5320.2.4 by Robert Collins
``bzrlib.osutils.get_terminal_encoding`` will now only mutter its
567
568
    :param trace: If True trace the selected encoding via 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.
569
    """
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
570
    from .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.
571
    output_encoding = getattr(sys.stdout, 'encoding', None)
572
    if not output_encoding:
573
        input_encoding = getattr(sys.stdin, 'encoding', None)
574
        if not input_encoding:
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
575
            output_encoding = get_user_encoding()
5320.2.4 by Robert Collins
``bzrlib.osutils.get_terminal_encoding`` will now only mutter its
576
            if trace:
577
                mutter('encoding stdout as osutils.get_user_encoding() %r',
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
578
                   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.
579
        else:
580
            output_encoding = input_encoding
5320.2.4 by Robert Collins
``bzrlib.osutils.get_terminal_encoding`` will now only mutter its
581
            if trace:
582
                mutter('encoding stdout as sys.stdin encoding %r',
583
                    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.
584
    else:
5320.2.4 by Robert Collins
``bzrlib.osutils.get_terminal_encoding`` will now only mutter its
585
        if trace:
586
            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
587
    if output_encoding == 'cp0':
588
        # 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.
589
        output_encoding = get_user_encoding()
5320.2.4 by Robert Collins
``bzrlib.osutils.get_terminal_encoding`` will now only mutter its
590
        if trace:
591
            mutter('cp0 is invalid encoding.'
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
592
               ' encoding stdout as osutils.get_user_encoding() %r',
593
               output_encoding)
2192.1.1 by Alexander Belchenko
Before actually using encoding need to check that Python has corresponding codec
594
    # check encoding
595
    try:
596
        codecs.lookup(output_encoding)
597
    except LookupError:
6622.1.4 by Jelmer Vernooij
Fix some more tests.
598
        sys.stderr.write('brz: warning:'
2192.1.9 by Alexander Belchenko
final fix suggested by John Meinel
599
                         ' unknown terminal encoding %s.\n'
2192.1.1 by Alexander Belchenko
Before actually using encoding need to check that Python has corresponding codec
600
                         '  Using encoding %s instead.\n'
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
601
                         % (output_encoding, get_user_encoding())
2192.1.1 by Alexander Belchenko
Before actually using encoding need to check that Python has corresponding codec
602
                        )
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
603
        output_encoding = get_user_encoding()
2192.1.1 by Alexander Belchenko
Before actually using encoding need to check that Python has corresponding codec
604
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.
605
    return output_encoding
606
607
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 \
608
def normalizepath(f):
3287.18.2 by Matt McClure
Reverts to 3290.
609
    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 \
610
        F = realpath
611
    else:
612
        F = abspath
613
    [p,e] = os.path.split(f)
614
    if e == "" or e == "." or e == "..":
615
        return F(f)
616
    else:
617
        return pathjoin(F(p), e)
618
1 by mbp at sourcefrog
import from baz patch-364
619
620
def isdir(f):
621
    """True if f is an accessible directory."""
622
    try:
5273.1.2 by Vincent Ladeuil
Cleanup imports in osutils.py.
623
        return stat.S_ISDIR(os.lstat(f)[stat.ST_MODE])
1 by mbp at sourcefrog
import from baz patch-364
624
    except OSError:
625
        return False
626
627
628
def isfile(f):
629
    """True if f is a regular file."""
630
    try:
5273.1.2 by Vincent Ladeuil
Cleanup imports in osutils.py.
631
        return stat.S_ISREG(os.lstat(f)[stat.ST_MODE])
1 by mbp at sourcefrog
import from baz patch-364
632
    except OSError:
633
        return False
634
1092.2.6 by Robert Collins
symlink support updated to work
635
def islink(f):
636
    """True if f is a symlink."""
637
    try:
5273.1.2 by Vincent Ladeuil
Cleanup imports in osutils.py.
638
        return stat.S_ISLNK(os.lstat(f)[stat.ST_MODE])
1092.2.6 by Robert Collins
symlink support updated to work
639
    except OSError:
640
        return False
1 by mbp at sourcefrog
import from baz patch-364
641
485 by Martin Pool
- move commit code into its own module
642
def is_inside(dir, fname):
643
    """True if fname is inside dir.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
644
1185.31.38 by John Arbash Meinel
Changing os.path.normpath to osutils.normpath
645
    The parameters should typically be passed to osutils.normpath first, so
969 by Martin Pool
- Add less-sucky is_within_any
646
    that . and .. and repeated slashes are eliminated, and the separators
647
    are canonical for the platform.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
648
649
    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
650
    everything.
485 by Martin Pool
- move commit code into its own module
651
    """
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
652
    # XXX: Most callers of this can actually do something smarter by
969 by Martin Pool
- Add less-sucky is_within_any
653
    # looking at the inventory
972 by Martin Pool
- less dodgy is_inside function
654
    if dir == fname:
655
        return True
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
656
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
657
    if dir == '':
658
        return True
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
659
1185.31.34 by John Arbash Meinel
Removing instances of os.sep
660
    if dir[-1] != '/':
661
        dir += '/'
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
662
972 by Martin Pool
- less dodgy is_inside function
663
    return fname.startswith(dir)
664
485 by Martin Pool
- move commit code into its own module
665
666
def is_inside_any(dir_list, fname):
667
    """True if fname is inside any of given dirs."""
668
    for dirname in dir_list:
669
        if is_inside(dirname, fname):
670
            return True
2324.2.3 by Dmitry Vasiliev
Fixed is_inside_* methods implementation
671
    return False
485 by Martin Pool
- move commit code into its own module
672
673
1740.3.4 by Jelmer Vernooij
Move inventory to commit builder.
674
def is_inside_or_parent_of_any(dir_list, fname):
675
    """True if fname is a child or a parent of any of the given files."""
676
    for dirname in dir_list:
677
        if is_inside(dirname, fname) or is_inside(fname, dirname):
678
            return True
2324.2.3 by Dmitry Vasiliev
Fixed is_inside_* methods implementation
679
    return False
1740.3.4 by Jelmer Vernooij
Move inventory to commit builder.
680
681
3956.2.1 by John Arbash Meinel
Add report_activity to osutils.pumpfile
682
def pumpfile(from_file, to_file, read_length=-1, buff_size=32768,
683
             report_activity=None, direction='read'):
2745.5.2 by Robert Collins
* ``bzrlib.transport.Transport.put_file`` now returns the number of bytes
684
    """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
685
686
    The read_length can either be -1 to read to end-of-file (EOF) or
687
    it can specify the maximum number of bytes to read.
688
689
    The buff_size represents the maximum size for each read operation
690
    performed on from_file.
691
3956.2.1 by John Arbash Meinel
Add report_activity to osutils.pumpfile
692
    :param report_activity: Call this as bytes are read, see
693
        Transport._report_activity
694
    :param direction: Will be passed to report_activity
695
2745.5.2 by Robert Collins
* ``bzrlib.transport.Transport.put_file`` now returns the number of bytes
696
    :return: The number of bytes copied.
697
    """
698
    length = 0
3408.6.1 by Eric Holmberg
Fix for Bug #215426 in which bzr can cause a MemoryError in socket.recv while
699
    if read_length >= 0:
700
        # read specified number of bytes
701
702
        while read_length > 0:
703
            num_bytes_to_read = min(read_length, buff_size)
704
705
            block = from_file.read(num_bytes_to_read)
706
            if not block:
707
                # EOF reached
708
                break
3956.2.1 by John Arbash Meinel
Add report_activity to osutils.pumpfile
709
            if report_activity is not None:
710
                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
711
            to_file.write(block)
712
713
            actual_bytes_read = len(block)
714
            read_length -= actual_bytes_read
715
            length += actual_bytes_read
716
    else:
717
        # read to EOF
718
        while True:
719
            block = from_file.read(buff_size)
720
            if not block:
721
                # EOF reached
722
                break
3956.2.1 by John Arbash Meinel
Add report_activity to osutils.pumpfile
723
            if report_activity is not None:
724
                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
725
            to_file.write(block)
726
            length += len(block)
2745.5.2 by Robert Collins
* ``bzrlib.transport.Transport.put_file`` now returns the number of bytes
727
    return length
1 by mbp at sourcefrog
import from baz patch-364
728
729
3635.1.2 by Robert Collins
Add osutils.pump_string_file helper function.
730
def pump_string_file(bytes, file_handle, segment_size=None):
731
    """Write bytes to file_handle in many smaller writes.
732
733
    :param bytes: The string to write.
734
    :param file_handle: The file to write to.
735
    """
736
    # Write data in chunks rather than all at once, because very large
737
    # writes fail on some platforms (e.g. Windows with SMB  mounted
738
    # drives).
739
    if not segment_size:
740
        segment_size = 5242880 # 5MB
6632.1.1 by Martin
Change uses of buffer to memoryview
741
    offsets = range(0, len(bytes), segment_size)
742
    view = memoryview(bytes)
3635.1.2 by Robert Collins
Add osutils.pump_string_file helper function.
743
    write = file_handle.write
6632.1.1 by Martin
Change uses of buffer to memoryview
744
    for offset in offsets:
745
        write(view[offset:offset+segment_size])
3635.1.2 by Robert Collins
Add osutils.pump_string_file helper function.
746
747
1185.67.7 by Aaron Bentley
Refactored a bit
748
def file_iterator(input_file, readsize=32768):
749
    while True:
750
        b = input_file.read(readsize)
751
        if len(b) == 0:
752
            break
753
        yield b
754
755
1 by mbp at sourcefrog
import from baz patch-364
756
def sha_file(f):
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
757
    """Calculate the hexdigest of an open file.
758
759
    The file cursor should be already at the start.
760
    """
2929.3.1 by Vincent Ladeuil
Fix python2.6 deprecation warnings (still 4 failures 5 errors in test suite).
761
    s = sha()
320 by Martin Pool
- Compute SHA-1 of files in chunks
762
    BUFSIZE = 128<<10
763
    while True:
764
        b = f.read(BUFSIZE)
765
        if not b:
766
            break
767
        s.update(b)
1 by mbp at sourcefrog
import from baz patch-364
768
    return s.hexdigest()
769
770
3368.2.49 by Ian Clatworthy
added osutils.size_sha_file() with tests
771
def size_sha_file(f):
772
    """Calculate the size and hexdigest of an open file.
773
774
    The file cursor should be already at the start and
775
    the caller is responsible for closing the file afterwards.
776
    """
777
    size = 0
778
    s = sha()
779
    BUFSIZE = 128<<10
780
    while True:
781
        b = f.read(BUFSIZE)
782
        if not b:
783
            break
784
        size += len(b)
785
        s.update(b)
786
    return size, s.hexdigest()
787
788
2872.3.1 by Martin Pool
Add -Dhashcache option; clean up dirstate sha1 code
789
def sha_file_by_name(fname):
790
    """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).
791
    s = sha()
4634.140.1 by INADA Naoki
Avoids child process inherits file handles on win32. by using os.fdopen and os.open with O_NOINHERIT instead of builtin open.
792
    f = os.open(fname, os.O_RDONLY | O_BINARY | O_NOINHERIT)
2872.3.1 by Martin Pool
Add -Dhashcache option; clean up dirstate sha1 code
793
    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
794
        while True:
795
            b = os.read(f, 1<<16)
796
            if not b:
797
                return s.hexdigest()
798
            s.update(b)
2872.3.1 by Martin Pool
Add -Dhashcache option; clean up dirstate sha1 code
799
    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
800
        os.close(f)
2872.3.1 by Martin Pool
Add -Dhashcache option; clean up dirstate sha1 code
801
802
2929.3.1 by Vincent Ladeuil
Fix python2.6 deprecation warnings (still 4 failures 5 errors in test suite).
803
def sha_strings(strings, _factory=sha):
1235 by Martin Pool
- split sha_strings into osutils
804
    """Return the sha-1 of concatenation of strings"""
2825.2.1 by Robert Collins
Micro-tweaks to sha routines.
805
    s = _factory()
6631.3.1 by Martin
Run 2to3 map fixer and refactor after
806
    for string in strings:
807
        s.update(string)
1235 by Martin Pool
- split sha_strings into osutils
808
    return s.hexdigest()
809
810
2929.3.1 by Vincent Ladeuil
Fix python2.6 deprecation warnings (still 4 failures 5 errors in test suite).
811
def sha_string(f, _factory=sha):
2825.2.1 by Robert Collins
Micro-tweaks to sha routines.
812
    return _factory(f).hexdigest()
1 by mbp at sourcefrog
import from baz patch-364
813
814
124 by mbp at sourcefrog
- check file text for past revisions is correct
815
def fingerprint_file(f):
126 by mbp at sourcefrog
Use just one big read to fingerprint files
816
    b = f.read()
2825.2.1 by Robert Collins
Micro-tweaks to sha routines.
817
    return {'size': len(b),
2929.3.1 by Vincent Ladeuil
Fix python2.6 deprecation warnings (still 4 failures 5 errors in test suite).
818
            'sha1': sha(b).hexdigest()}
124 by mbp at sourcefrog
- check file text for past revisions is correct
819
820
1 by mbp at sourcefrog
import from baz patch-364
821
def compare_files(a, b):
822
    """Returns true if equal in contents"""
74 by mbp at sourcefrog
compare_files: read in one page at a time rather than
823
    BUFSIZE = 4096
824
    while True:
825
        ai = a.read(BUFSIZE)
826
        bi = b.read(BUFSIZE)
827
        if ai != bi:
828
            return False
829
        if ai == '':
830
            return True
1 by mbp at sourcefrog
import from baz patch-364
831
832
6621.1.1 by Florent Gallaire
Fix for Windows and 32-bit platforms buggy gmtime().
833
def gmtime(seconds=None):
834
    """Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.
835
    GMT). When 'seconds' is not passed in, convert the current time instead.
836
    Handy replacement for time.gmtime() buggy on Windows and 32-bit platforms.
837
    """
838
    if seconds is None:
839
        seconds = time.time()
840
    return (datetime(1970, 1, 1) + timedelta(seconds=seconds)).timetuple()
841
842
49 by mbp at sourcefrog
fix local-time-offset calculation
843
def local_time_offset(t=None):
844
    """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'.
845
    if t is None:
73 by mbp at sourcefrog
fix time.localtime call for python 2.3
846
        t = time.time()
2215.6.1 by James Henstridge
Don't rely on time.timezone and time.altzone in local_time_offset(),
847
    offset = datetime.fromtimestamp(t) - datetime.utcfromtimestamp(t)
848
    return offset.days * 86400 + offset.seconds
8 by mbp at sourcefrog
store committer's timezone in revision and show
849
3512.3.1 by Martin von Gagern
Hand-selected minimalistic set of changes from my setlocale branch.
850
weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
4379.4.1 by Ian Clatworthy
make log --long faster
851
_default_format_by_weekday_num = [wd + " %Y-%m-%d %H:%M:%S" for wd in weekdays]
852
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
853
2425.6.2 by Martin Pool
Make timestamps use existing format_date; document that function more
854
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.
855
                show_offset=True):
2425.6.2 by Martin Pool
Make timestamps use existing format_date; document that function more
856
    """Return a formatted date string.
857
858
    :param t: Seconds since the epoch.
859
    :param offset: Timezone offset in seconds east of utc.
860
    :param timezone: How to display the time: 'utc', 'original' for the
861
         timezone specified by offset, or 'local' for the process's current
862
         timezone.
3526.5.4 by Martin von Gagern
Use separate function format_local_date for local weekday formats in unicode.
863
    :param date_fmt: strftime format.
864
    :param show_offset: Whether to append the timezone.
865
    """
866
    (date_fmt, tt, offset_str) = \
867
               _format_date(t, offset, timezone, date_fmt, show_offset)
868
    date_fmt = date_fmt.replace('%a', weekdays[tt[6]])
869
    date_str = time.strftime(date_fmt, tt)
870
    return date_str + offset_str
871
4379.4.1 by Ian Clatworthy
make log --long faster
872
873
# Cache of formatted offset strings
874
_offset_cache = {}
875
876
4379.4.2 by Ian Clatworthy
add NEWS item and tests for new date formatting API
877
def format_date_with_offset_in_original_timezone(t, offset=0,
4379.4.1 by Ian Clatworthy
make log --long faster
878
    _cache=_offset_cache):
879
    """Return a formatted date string in the original timezone.
880
881
    This routine may be faster then format_date.
882
883
    :param t: Seconds since the epoch.
884
    :param offset: Timezone offset in seconds east of utc.
885
    """
886
    if offset is None:
887
        offset = 0
6621.1.1 by Florent Gallaire
Fix for Windows and 32-bit platforms buggy gmtime().
888
    tt = gmtime(t + offset)
4379.4.1 by Ian Clatworthy
make log --long faster
889
    date_fmt = _default_format_by_weekday_num[tt[6]]
890
    date_str = time.strftime(date_fmt, tt)
891
    offset_str = _cache.get(offset, None)
892
    if offset_str is None:
893
        offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
894
        _cache[offset] = offset_str
895
    return date_str + offset_str
896
897
3526.5.4 by Martin von Gagern
Use separate function format_local_date for local weekday formats in unicode.
898
def format_local_date(t, offset=0, timezone='original', date_fmt=None,
899
                      show_offset=True):
900
    """Return an unicode date string formatted according to the current locale.
901
902
    :param t: Seconds since the epoch.
903
    :param offset: Timezone offset in seconds east of utc.
904
    :param timezone: How to display the time: 'utc', 'original' for the
905
         timezone specified by offset, or 'local' for the process's current
906
         timezone.
907
    :param date_fmt: strftime format.
908
    :param show_offset: Whether to append the timezone.
909
    """
910
    (date_fmt, tt, offset_str) = \
911
               _format_date(t, offset, timezone, date_fmt, show_offset)
912
    date_str = time.strftime(date_fmt, tt)
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
913
    if not isinstance(date_str, text_type):
4385.4.1 by Alexander Belchenko
removed all references to bzrlib.user_encoding
914
        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.
915
    return date_str + offset_str
916
4379.4.1 by Ian Clatworthy
make log --long faster
917
3526.5.4 by Martin von Gagern
Use separate function format_local_date for local weekday formats in unicode.
918
def _format_date(t, offset, timezone, date_fmt, show_offset):
8 by mbp at sourcefrog
store committer's timezone in revision and show
919
    if timezone == 'utc':
6621.1.1 by Florent Gallaire
Fix for Windows and 32-bit platforms buggy gmtime().
920
        tt = gmtime(t)
1 by mbp at sourcefrog
import from baz patch-364
921
        offset = 0
8 by mbp at sourcefrog
store committer's timezone in revision and show
922
    elif timezone == 'original':
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
923
        if offset is None:
23 by mbp at sourcefrog
format_date: handle revisions with no timezone offset
924
            offset = 0
6621.1.1 by Florent Gallaire
Fix for Windows and 32-bit platforms buggy gmtime().
925
        tt = gmtime(t + offset)
12 by mbp at sourcefrog
new --timezone option for bzr log
926
    elif timezone == 'local':
1 by mbp at sourcefrog
import from baz patch-364
927
        tt = time.localtime(t)
49 by mbp at sourcefrog
fix local-time-offset calculation
928
        offset = local_time_offset(t)
12 by mbp at sourcefrog
new --timezone option for bzr log
929
    else:
3144.1.1 by Lukáš Lalinský
Fixed error reporting of unsupported timezone format.
930
        raise errors.UnsupportedTimezoneFormat(timezone)
1185.12.24 by Aaron Bentley
Made format_date more flexible
931
    if date_fmt is None:
932
        date_fmt = "%a %Y-%m-%d %H:%M:%S"
933
    if show_offset:
934
        offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
935
    else:
936
        offset_str = ''
3526.5.4 by Martin von Gagern
Use separate function format_local_date for local weekday formats in unicode.
937
    return (date_fmt, tt, offset_str)
1 by mbp at sourcefrog
import from baz patch-364
938
939
940
def compact_date(when):
6621.1.1 by Florent Gallaire
Fix for Windows and 32-bit platforms buggy gmtime().
941
    return time.strftime('%Y%m%d%H%M%S', gmtime(when))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
942
1 by mbp at sourcefrog
import from baz patch-364
943
1957.1.4 by John Arbash Meinel
create a helper for formatting a time delta
944
def format_delta(delta):
945
    """Get a nice looking string for a time delta.
946
947
    :param delta: The time difference in seconds, can be positive or negative.
948
        positive indicates time in the past, negative indicates time in the
949
        future. (usually time.time() - stored_time)
950
    :return: String formatted to show approximate resolution
951
    """
952
    delta = int(delta)
953
    if delta >= 0:
954
        direction = 'ago'
955
    else:
956
        direction = 'in the future'
957
        delta = -delta
958
959
    seconds = delta
960
    if seconds < 90: # print seconds up to 90 seconds
961
        if seconds == 1:
962
            return '%d second %s' % (seconds, direction,)
963
        else:
964
            return '%d seconds %s' % (seconds, direction)
965
966
    minutes = int(seconds / 60)
967
    seconds -= 60 * minutes
968
    if seconds == 1:
969
        plural_seconds = ''
970
    else:
971
        plural_seconds = 's'
972
    if minutes < 90: # print minutes, seconds up to 90 minutes
973
        if minutes == 1:
974
            return '%d minute, %d second%s %s' % (
975
                    minutes, seconds, plural_seconds, direction)
976
        else:
977
            return '%d minutes, %d second%s %s' % (
978
                    minutes, seconds, plural_seconds, direction)
979
980
    hours = int(minutes / 60)
981
    minutes -= 60 * hours
982
    if minutes == 1:
983
        plural_minutes = ''
984
    else:
985
        plural_minutes = 's'
986
987
    if hours == 1:
988
        return '%d hour, %d minute%s %s' % (hours, minutes,
989
                                            plural_minutes, direction)
990
    return '%d hours, %d minute%s %s' % (hours, minutes,
991
                                         plural_minutes, direction)
1 by mbp at sourcefrog
import from baz patch-364
992
993
def filesize(f):
994
    """Return size of given open file."""
5273.1.2 by Vincent Ladeuil
Cleanup imports in osutils.py.
995
    return os.fstat(f.fileno())[stat.ST_SIZE]
1 by mbp at sourcefrog
import from baz patch-364
996
1553.5.5 by Martin Pool
New utility routine rand_chars
997
6419.1.1 by Martin Packman
Simplify urandom alias osutils.rand_bytes based on present realities
998
# Alias os.urandom to support platforms (which?) without /dev/urandom and 
999
# override if it doesn't work. Avoid checking on windows where there is
1000
# significant initialisation cost that can be avoided for some bzr calls.
1001
1002
rand_bytes = os.urandom
1003
1004
if rand_bytes.__module__ != "nt":
2067.1.1 by John Arbash Meinel
Catch an exception while opening /dev/urandom rather than using os.path.exists()
1005
    try:
6419.1.1 by Martin Packman
Simplify urandom alias osutils.rand_bytes based on present realities
1006
        rand_bytes(1)
1007
    except NotImplementedError:
1185.1.7 by Robert Collins
Nathaniel McCallums patch for urandom friendliness on aix.
1008
        # not well seeded, but better than nothing
1009
        def rand_bytes(n):
1010
            import random
1011
            s = ''
1012
            while n:
1013
                s += chr(random.randint(0, 255))
1014
                n -= 1
1015
            return s
1 by mbp at sourcefrog
import from baz patch-364
1016
1553.5.5 by Martin Pool
New utility routine rand_chars
1017
1018
ALNUM = '0123456789abcdefghijklmnopqrstuvwxyz'
1019
def rand_chars(num):
1020
    """Return a random string of num alphanumeric characters
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1021
1022
    The result only contains lowercase chars because it may be used on
1553.5.5 by Martin Pool
New utility routine rand_chars
1023
    case-insensitive filesystems.
1024
    """
1025
    s = ''
1026
    for raw_byte in rand_bytes(num):
1027
        s += ALNUM[ord(raw_byte) % 36]
1028
    return s
1029
1030
1 by mbp at sourcefrog
import from baz patch-364
1031
## 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.
1032
## decomposition (might be too tricksy though.)
1 by mbp at sourcefrog
import from baz patch-364
1033
1034
def splitpath(p):
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
1035
    """Turn string into list of parts."""
271 by Martin Pool
- Windows path fixes
1036
    # split on either delimiter because people might use either on
1037
    # Windows
1038
    ps = re.split(r'[\\/]', p)
1039
1040
    rps = []
1 by mbp at sourcefrog
import from baz patch-364
1041
    for f in ps:
1042
        if f == '..':
6138.3.8 by Jonathan Riddell
more error gettext()ing
1043
            raise errors.BzrError(gettext("sorry, %r not allowed in path") % f)
271 by Martin Pool
- Windows path fixes
1044
        elif (f == '.') or (f == ''):
1045
            pass
1046
        else:
1047
            rps.append(f)
1048
    return rps
1 by mbp at sourcefrog
import from baz patch-364
1049
3890.2.4 by John Arbash Meinel
Add a new function that can convert 'chunks' format to a 'lines' format.
1050
1 by mbp at sourcefrog
import from baz patch-364
1051
def joinpath(p):
1052
    for f in p:
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
1053
        if (f == '..') or (f is None) or (f == ''):
6138.3.8 by Jonathan Riddell
more error gettext()ing
1054
            raise errors.BzrError(gettext("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 \
1055
    return pathjoin(*p)
1 by mbp at sourcefrog
import from baz patch-364
1056
1057
4370.1.1 by Ian Clatworthy
add osutils.parent_directories() API
1058
def parent_directories(filename):
4371.1.1 by Ian Clatworthy
(igc) added osutils.parent_directories() (Ian Clatworthy)
1059
    """Return the list of parent directories, deepest first.
5279.2.7 by Eric Moritz
1. deleted trailing whitespace
1060
4371.1.1 by Ian Clatworthy
(igc) added osutils.parent_directories() (Ian Clatworthy)
1061
    For example, parent_directories("a/b/c") -> ["a/b", "a"].
1062
    """
4370.1.1 by Ian Clatworthy
add osutils.parent_directories() API
1063
    parents = []
1064
    parts = splitpath(dirname(filename))
1065
    while parts:
1066
        parents.append(joinpath(parts))
1067
        parts.pop()
1068
    return parents
1069
1070
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
1071
_extension_load_failures = []
1072
1073
1074
def failed_to_load_extension(exception):
4574.3.1 by Martin Pool
Give a warning when failing to load _chunks_to_lines_pyx
1075
    """Handle failing to load a binary extension.
1076
1077
    This should be called from the ImportError block guarding the attempt to
1078
    import the native extension.  If this function returns, the pure-Python
1079
    implementation should be loaded instead::
1080
1081
    >>> try:
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1082
    >>>     import breezy._fictional_extension_pyx
4574.3.1 by Martin Pool
Give a warning when failing to load _chunks_to_lines_pyx
1083
    >>> except ImportError, e:
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1084
    >>>     breezy.osutils.failed_to_load_extension(e)
1085
    >>>     import breezy._fictional_extension_py
4574.3.1 by Martin Pool
Give a warning when failing to load _chunks_to_lines_pyx
1086
    """
1087
    # NB: This docstring is just an example, not a doctest, because doctest
1088
    # currently can't cope with the use of lazy imports in this namespace --
1089
    # mbp 20090729
5279.2.7 by Eric Moritz
1. deleted trailing whitespace
1090
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
1091
    # This currently doesn't report the failure at the time it occurs, because
1092
    # they tend to happen very early in startup when we can't check config
1093
    # files etc, and also we want to report all failures but not spam the user
1094
    # with 10 warnings.
1095
    exception_str = str(exception)
1096
    if exception_str not in _extension_load_failures:
5523.2.3 by Parth Malwankar
message is now shown to the user but is not too scary.
1097
        trace.mutter("failed to load compiled extension: %s" % exception_str)
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
1098
        _extension_load_failures.append(exception_str)
1099
1100
1101
def report_extension_load_failures():
1102
    if not _extension_load_failures:
1103
        return
6059.4.2 by Vincent Ladeuil
Migrate ignore_missing_extensions to stack-based config.
1104
    if config.GlobalStack().get('ignore_missing_extensions'):
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
1105
        return
1106
    # the warnings framework should by default show this only once
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
1107
    from .trace import warning
4695.4.1 by Martin Pool
Give a shorter/cleaner message for missing extensions
1108
    warning(
6622.1.4 by Jelmer Vernooij
Fix some more tests.
1109
        "brz: warning: some compiled extensions could not be loaded; "
4695.4.1 by Martin Pool
Give a shorter/cleaner message for missing extensions
1110
        "see <https://answers.launchpad.net/bzr/+faq/703>")
1111
    # we no longer show the specific missing extensions here, because it makes
1112
    # the message too long and scary - see
1113
    # https://bugs.launchpad.net/bzr/+bug/430529
4574.3.1 by Martin Pool
Give a warning when failing to load _chunks_to_lines_pyx
1114
1115
3890.2.7 by John Arbash Meinel
A Pyrex extension is about 5x faster than the fastest python code I could write.
1116
try:
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
1117
    from ._chunks_to_lines_pyx import chunks_to_lines
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
1118
except ImportError as e:
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
1119
    failed_to_load_extension(e)
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
1120
    from ._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.
1121
1122
1231 by Martin Pool
- more progress on fetch on top of weaves
1123
def split_lines(s):
1124
    """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.
1125
    # Trivially convert a fulltext into a 'chunked' representation, and let
1126
    # chunks_to_lines do the heavy lifting.
1127
    if isinstance(s, str):
1128
        # chunks_to_lines only supports 8-bit strings
1129
        return chunks_to_lines([s])
1130
    else:
1131
        return _split_lines(s)
1132
1133
1134
def _split_lines(s):
1135
    """Split s into lines, but without removing the newline characters.
1136
1137
    This supports Unicode or plain string objects.
1138
    """
1666.1.6 by Robert Collins
Make knit the default format.
1139
    lines = s.split('\n')
1140
    result = [line + '\n' for line in lines[:-1]]
1141
    if lines[-1]:
1142
        result.append(lines[-1])
1143
    return result
1391 by Robert Collins
merge from integration
1144
1145
1185.10.4 by Aaron Bentley
Disabled hardlinks on cygwin, mac OS
1146
def hardlinks_good():
1185.10.5 by Aaron Bentley
Fixed hardlinks_good test
1147
    return sys.platform not in ('win32', 'cygwin', 'darwin')
1185.10.4 by Aaron Bentley
Disabled hardlinks on cygwin, mac OS
1148
1185.1.46 by Robert Collins
Aarons branch --basis patch
1149
1185.10.3 by Aaron Bentley
Made copy_multi_immutable create hardlinks opportunistically
1150
def link_or_copy(src, dest):
1151
    """Hardlink a file, or copy it if it can't be hardlinked."""
1185.10.4 by Aaron Bentley
Disabled hardlinks on cygwin, mac OS
1152
    if not hardlinks_good():
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
1153
        shutil.copyfile(src, dest)
1185.10.3 by Aaron Bentley
Made copy_multi_immutable create hardlinks opportunistically
1154
        return
1155
    try:
1156
        os.link(src, dest)
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
1157
    except (OSError, IOError) as e:
1185.10.3 by Aaron Bentley
Made copy_multi_immutable create hardlinks opportunistically
1158
        if e.errno != errno.EXDEV:
1159
            raise
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
1160
        shutil.copyfile(src, dest)
1399.1.4 by Robert Collins
move diff and symlink conditionals into inventory.py from diff.py
1161
2831.5.2 by Vincent Ladeuil
Review feedback.
1162
1163
def delete_any(path):
5279.2.7 by Eric Moritz
1. deleted trailing whitespace
1164
    """Delete a file, symlink or directory.
1165
4490.1.1 by Martin Pool
merge fix for forcing readonly deletion, and tweak
1166
    Will delete even if readonly.
1167
    """
4440.1.2 by Craig Hewetson
Fixes made after first code review.
1168
    try:
4490.1.1 by Martin Pool
merge fix for forcing readonly deletion, and tweak
1169
       _delete_file_or_dir(path)
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
1170
    except (OSError, IOError) as e:
4440.1.2 by Craig Hewetson
Fixes made after first code review.
1171
        if e.errno in (errno.EPERM, errno.EACCES):
4490.1.1 by Martin Pool
merge fix for forcing readonly deletion, and tweak
1172
            # make writable and try again
1173
            try:
4440.1.2 by Craig Hewetson
Fixes made after first code review.
1174
                make_writable(path)
4490.1.1 by Martin Pool
merge fix for forcing readonly deletion, and tweak
1175
            except (OSError, IOError):
4440.1.2 by Craig Hewetson
Fixes made after first code review.
1176
                pass
4490.1.1 by Martin Pool
merge fix for forcing readonly deletion, and tweak
1177
            _delete_file_or_dir(path)
1178
        else:
1179
            raise
1180
1181
1182
def _delete_file_or_dir(path):
1183
    # Look Before You Leap (LBYL) is appropriate here instead of Easier to Ask for
1184
    # Forgiveness than Permission (EAFP) because:
1185
    # - root can damage a solaris file system by using unlink,
1186
    # - unlink raises different exceptions on different OSes (linux: EISDIR, win32:
1187
    #   EACCES, OSX: EPERM) when invoked on a directory.
2831.5.2 by Vincent Ladeuil
Review feedback.
1188
    if isdir(path): # Takes care of symlinks
1189
        os.rmdir(path)
1190
    else:
1191
        os.unlink(path)
1558.12.9 by Aaron Bentley
Handle resolving conflicts with directories properly
1192
1399.1.4 by Robert Collins
move diff and symlink conditionals into inventory.py from diff.py
1193
1194
def has_symlinks():
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
1195
    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
1196
        return True
1197
    else:
1198
        return False
2831.5.2 by Vincent Ladeuil
Review feedback.
1199
1185.16.38 by Martin Pool
- move contains_whitespace and contains_linebreaks to osutils
1200
3136.1.1 by Aaron Bentley
Add support for hardlinks to TreeTransform
1201
def has_hardlinks():
1202
    if getattr(os, 'link', None) is not None:
1203
        return True
1204
    else:
1205
        return False
1206
1207
3287.18.14 by Matt McClure
Extracted a host_os_dereferences_symlinks method.
1208
def host_os_dereferences_symlinks():
1209
    return (has_symlinks()
3287.18.19 by Matt McClure
Changed tested sys.platform value from 'windows' (mistaken) to 'win32'
1210
            and sys.platform not in ('cygwin', 'win32'))
3287.18.14 by Matt McClure
Extracted a host_os_dereferences_symlinks method.
1211
1212
4241.14.14 by Vincent Ladeuil
Test and implements osutils.readlink().
1213
def readlink(abspath):
1214
    """Return a string representing the path to which the symbolic link points.
1215
1216
    :param abspath: The link absolute unicode path.
1217
1218
    This his guaranteed to return the symbolic link in unicode in all python
1219
    versions.
1220
    """
1221
    link = abspath.encode(_fs_enc)
1222
    target = os.readlink(link)
1223
    target = target.decode(_fs_enc)
1224
    return target
1225
1226
1185.16.38 by Martin Pool
- move contains_whitespace and contains_linebreaks to osutils
1227
def contains_whitespace(s):
1228
    """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.
1229
    # string.whitespace can include '\xa0' in certain locales, because it is
1230
    # considered "non-breaking-space" as part of ISO-8859-1. But it
1231
    # 1) Isn't a breaking whitespace
1232
    # 2) Isn't one of ' \t\r\n' which are characters we sometimes use as
1233
    #    separators
1234
    # 3) '\xa0' isn't unicode safe since it is >128.
2249.5.16 by John Arbash Meinel
[merge] bzr.dev 2283
1235
1236
    # This should *not* be a unicode set of characters in case the source
1237
    # string is not a Unicode string. We can auto-up-cast the characters since
1238
    # they are ascii, but we don't want to auto-up-cast the string in case it
1239
    # is utf-8
1240
    for ch in ' \t\n\r\v\f':
1185.16.38 by Martin Pool
- move contains_whitespace and contains_linebreaks to osutils
1241
        if ch in s:
1242
            return True
1243
    else:
1244
        return False
1245
1246
1247
def contains_linebreaks(s):
1248
    """True if there is any vertical whitespace in s."""
1249
    for ch in '\f\n\r':
1250
        if ch in s:
1251
            return True
1252
    else:
1253
        return False
1457.1.2 by Robert Collins
move branch._relpath into osutils as relpath
1254
1255
1256
def relpath(base, path):
5193.2.1 by Alexander Belchenko
update docstring for osutils.relpath() function.
1257
    """Return path relative to base, or raise PathNotChild exception.
1457.1.2 by Robert Collins
move branch._relpath into osutils as relpath
1258
1259
    The path may be either an absolute path or a path relative to the
1260
    current working directory.
1261
1262
    os.path.commonprefix (python2.4) has a bad bug that it works just
1263
    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.
1264
    avoids that problem.
5193.2.1 by Alexander Belchenko
update docstring for osutils.relpath() function.
1265
5193.2.2 by Alexander Belchenko
update wording based on spiv's review.
1266
    NOTE: `base` should not have a trailing slash otherwise you'll get
1267
    PathNotChild exceptions regardless of `path`.
1636.1.1 by Robert Collins
Fix calling relpath() and abspath() on transports at their root.
1268
    """
1685.1.12 by John Arbash Meinel
Some more work to get LocalTransport to only support URLs
1269
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1270
    if len(base) < MIN_ABS_PATHLENGTH:
1271
        # must have space for e.g. a drive letter
6138.3.8 by Jonathan Riddell
more error gettext()ing
1272
        raise ValueError(gettext('%r is too short to calculate a relative path')
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1273
            % (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
1274
1685.1.12 by John Arbash Meinel
Some more work to get LocalTransport to only support URLs
1275
    rp = abspath(path)
1457.1.2 by Robert Collins
move branch._relpath into osutils as relpath
1276
1277
    s = []
1685.1.12 by John Arbash Meinel
Some more work to get LocalTransport to only support URLs
1278
    head = rp
4555.2.1 by John Arbash Meinel
Fix bug #394227, osutils.relpath() could get into an infinite loop.
1279
    while True:
1280
        if len(head) <= len(base) and head != base:
1281
            raise errors.PathNotChild(rp, base)
1457.1.2 by Robert Collins
move branch._relpath into osutils as relpath
1282
        if head == base:
1283
            break
4555.2.1 by John Arbash Meinel
Fix bug #394227, osutils.relpath() could get into an infinite loop.
1284
        head, tail = split(head)
1457.1.2 by Robert Collins
move branch._relpath into osutils as relpath
1285
        if tail:
4555.2.1 by John Arbash Meinel
Fix bug #394227, osutils.relpath() could get into an infinite loop.
1286
            s.append(tail)
1457.1.2 by Robert Collins
move branch._relpath into osutils as relpath
1287
1185.31.35 by John Arbash Meinel
Couple small fixes, all tests pass on cygwin.
1288
    if s:
4555.2.3 by John Arbash Meinel
Fix a trivial bug that should have been caught earlier. :)
1289
        return pathjoin(*reversed(s))
1185.31.35 by John Arbash Meinel
Couple small fixes, all tests pass on cygwin.
1290
    else:
1291
        return ''
1185.33.60 by Martin Pool
Use full terminal width for verbose test output.
1292
1293
3794.5.29 by Mark Hammond
cicp_canonical_relpath -> _cicp_canonical_relpath
1294
def _cicp_canonical_relpath(base, path):
3794.5.1 by Mark Hammond
Add canonical_relpath api function
1295
    """Return the canonical path relative to base.
1296
1297
    Like relpath, but on case-insensitive-case-preserving file-systems, this
3794.5.13 by Mark Hammond
Tweaks suggested by Martin
1298
    will return the relpath as stored on the file-system rather than in the
1299
    case specified in the input string, for all existing portions of the path.
1300
3794.5.28 by Mark Hammond
Update comments.
1301
    This will cause O(N) behaviour if called for every path in a tree; if you
1302
    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.
1303
    """
1304
    # TODO: it should be possible to optimize this for Windows by using the
1305
    # win32 API FindFiles function to look for the specified name - but using
1306
    # os.listdir() still gives us the correct, platform agnostic semantics in
1307
    # the short term.
3794.5.13 by Mark Hammond
Tweaks suggested by Martin
1308
3794.5.1 by Mark Hammond
Add canonical_relpath api function
1309
    rel = relpath(base, path)
1310
    # '.' will have been turned into ''
1311
    if not rel:
1312
        return rel
1313
1314
    abs_base = abspath(base)
1315
    current = abs_base
1316
    _listdir = os.listdir
1317
1318
    # 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.
1319
    bit_iter = iter(rel.split('/'))
3794.5.1 by Mark Hammond
Add canonical_relpath api function
1320
    for bit in bit_iter:
1321
        lbit = bit.lower()
4634.70.2 by John Arbash Meinel
Fix bug #322807, teach cicp_canonical_relpath how to handle
1322
        try:
1323
            next_entries = _listdir(current)
4634.70.3 by John Arbash Meinel
Clean up some terminology, catch a double _listdir request, thanks spiv.
1324
        except OSError: # enoent, eperm, etc
1325
            # We can't find this in the filesystem, so just append the
1326
            # remaining bits.
4634.70.2 by John Arbash Meinel
Fix bug #322807, teach cicp_canonical_relpath how to handle
1327
            current = pathjoin(current, bit, *list(bit_iter))
1328
            break
4634.70.3 by John Arbash Meinel
Clean up some terminology, catch a double _listdir request, thanks spiv.
1329
        for look in next_entries:
3794.5.1 by Mark Hammond
Add canonical_relpath api function
1330
            if lbit == look.lower():
1331
                current = pathjoin(current, look)
1332
                break
1333
        else:
1334
            # got to the end, nothing matched, so we just return the
1335
            # non-existing bits as they were specified (the filename may be
1336
            # the target of a move, for example).
1337
            current = pathjoin(current, bit, *list(bit_iter))
1338
            break
4634.70.2 by John Arbash Meinel
Fix bug #322807, teach cicp_canonical_relpath how to handle
1339
    return current[len(abs_base):].lstrip('/')
3794.5.1 by Mark Hammond
Add canonical_relpath api function
1340
3794.5.13 by Mark Hammond
Tweaks suggested by Martin
1341
# XXX - TODO - we need better detection/integration of case-insensitive
4241.9.5 by Vincent Ladeuil
Fix unicode related OSX failures.
1342
# file-systems; Linux often sees FAT32 devices (or NFS-mounted OSX
1343
# filesystems), for example, so could probably benefit from the same basic
1344
# support there.  For now though, only Windows and OSX get that support, and
1345
# they get it for *all* file-systems!
4241.9.2 by Vincent Ladeuil
Fix most of cicp related failures on OSX.
1346
if sys.platform in ('win32', 'darwin'):
3794.5.29 by Mark Hammond
cicp_canonical_relpath -> _cicp_canonical_relpath
1347
    canonical_relpath = _cicp_canonical_relpath
3794.5.1 by Mark Hammond
Add canonical_relpath api function
1348
else:
1349
    canonical_relpath = relpath
1350
3794.5.15 by Mark Hammond
Add canonical_relpaths() as a placeholder for a future caching implementation.
1351
def canonical_relpaths(base, paths):
1352
    """Create an iterable to canonicalize a sequence of relative paths.
1353
1354
    The intent is for this implementation to use a cache, vastly speeding
1355
    up multiple transformations in the same directory.
1356
    """
1357
    # but for now, we haven't optimized...
1358
    return [canonical_relpath(base, p) for p in paths]
3794.5.1 by Mark Hammond
Add canonical_relpath api function
1359
5279.2.7 by Eric Moritz
1. deleted trailing whitespace
1360
1361
def decode_filename(filename):
1362
    """Decode the filename using the filesystem encoding
1363
1364
    If it is unicode, it is returned.
1365
    Otherwise it is decoded from the the filesystem's encoding. If decoding
1366
    fails, a errors.BadFilenameEncoding exception is raised.
1367
    """
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
1368
    if isinstance(filename, text_type):
5279.2.4 by Eric Moritz
Added the filename_decode
1369
        return filename
5279.2.7 by Eric Moritz
1. deleted trailing whitespace
1370
    try:
1371
        return filename.decode(_fs_enc)
1372
    except UnicodeDecodeError:
1373
        raise errors.BadFilenameEncoding(filename, _fs_enc)
1374
5279.2.4 by Eric Moritz
Added the filename_decode
1375
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
1376
def safe_unicode(unicode_or_utf8_string):
1377
    """Coerce unicode_or_utf8_string into unicode.
1378
1379
    If it is unicode, it is returned.
4204.2.1 by Matt Nordhoff
Fix a broken sentence in osutils.safe_unicode's docstring
1380
    Otherwise it is decoded from utf-8. If decoding fails, the exception is
1381
    wrapped in a BzrBadParameterNotUnicode exception.
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
1382
    """
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
1383
    if isinstance(unicode_or_utf8_string, text_type):
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
1384
        return unicode_or_utf8_string
1385
    try:
1386
        return unicode_or_utf8_string.decode('utf8')
1387
    except UnicodeDecodeError:
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
1388
        raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
1389
1390
2249.5.8 by John Arbash Meinel
Add osutils.safe_utf8 and safe_revision_id for the new revision_id work.
1391
def safe_utf8(unicode_or_utf8_string):
1392
    """Coerce unicode_or_utf8_string to a utf8 string.
1393
1394
    If it is a str, it is returned.
1395
    If it is Unicode, it is encoded into a utf-8 string.
1396
    """
1397
    if isinstance(unicode_or_utf8_string, str):
1398
        # TODO: jam 20070209 This is overkill, and probably has an impact on
1399
        #       performance if we are dealing with lots of apis that want a
1400
        #       utf-8 revision id
1401
        try:
1402
            # Make sure it is a valid utf-8 string
1403
            unicode_or_utf8_string.decode('utf-8')
1404
        except UnicodeDecodeError:
1405
            raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
1406
        return unicode_or_utf8_string
1407
    return unicode_or_utf8_string.encode('utf-8')
1408
1409
6630.1.1 by Jelmer Vernooij
Remove deprecated functionality.
1410
def safe_revision_id(unicode_or_utf8_string):
2249.5.8 by John Arbash Meinel
Add osutils.safe_utf8 and safe_revision_id for the new revision_id work.
1411
    """Revision ids should now be utf8, but at one point they were unicode.
1412
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
1413
    :param unicode_or_utf8_string: A possibly Unicode revision_id. (can also be
1414
        utf8 or None).
1415
    :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.
1416
    """
2309.4.3 by John Arbash Meinel
(broken) change safe_*_id to emit a warning.
1417
    if (unicode_or_utf8_string is None
1418
        or unicode_or_utf8_string.__class__ == str):
1419
        return unicode_or_utf8_string
6630.1.1 by Jelmer Vernooij
Remove deprecated functionality.
1420
    raise TypeError('Unicode revision ids are no longer supported. '
1421
                    'Revision id generators should be creating utf8 revision '
1422
                    'ids.')
1423
1424
1425
def safe_file_id(unicode_or_utf8_string):
2309.4.3 by John Arbash Meinel
(broken) change safe_*_id to emit a warning.
1426
    """File ids should now be utf8, but at one point they were unicode.
1427
1428
    This is the same as safe_utf8, except it uses the cached encode functions
1429
    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.
1430
1431
    :param unicode_or_utf8_string: A possibly Unicode file_id. (can also be
1432
        utf8 or None).
1433
    :return: None or a utf8 file id.
2309.4.3 by John Arbash Meinel
(broken) change safe_*_id to emit a warning.
1434
    """
1435
    if (unicode_or_utf8_string is None
1436
        or unicode_or_utf8_string.__class__ == str):
1437
        return unicode_or_utf8_string
6630.1.1 by Jelmer Vernooij
Remove deprecated functionality.
1438
    raise TypeError('Unicode file ids are no longer supported. '
1439
                    'File id generators should be creating utf8 file ids.')
2294.1.4 by John Arbash Meinel
Add safe_file_id as a helper in osutils.
1440
1441
1185.85.75 by John Arbash Meinel
Adding bzrlib.osutils.unicode_filename to handle unicode normalization for file paths.
1442
_platform_normalizes_filenames = False
1443
if sys.platform == 'darwin':
1444
    _platform_normalizes_filenames = True
1445
1446
1447
def normalizes_filenames():
1448
    """Return True if this platform normalizes unicode filenames.
1449
5283.2.1 by Martin Pool
Additional platform name tweaks
1450
    Only Mac OSX.
1185.85.75 by John Arbash Meinel
Adding bzrlib.osutils.unicode_filename to handle unicode normalization for file paths.
1451
    """
1452
    return _platform_normalizes_filenames
1453
1454
1830.3.2 by John Arbash Meinel
normalized_filename is a much better name
1455
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
1456
    """Get the unicode normalized path, and if you can access the file.
1457
1458
    On platforms where the system normalizes filenames (Mac OSX),
1459
    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
1460
    On platforms where the system does not normalize filenames
5283.2.1 by Martin Pool
Additional platform name tweaks
1461
    (everything else), you have to access a file by its exact path.
1830.3.1 by John Arbash Meinel
Change the return value of unicode_filename, and make it testable on all platforms
1462
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1463
    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
1464
    the standard for XML documents.
1465
1466
    So return the normalized path, and a flag indicating if the file
1467
    can be accessed by that path.
1468
    """
1469
3201.1.1 by jameinel
Fix bug #185458, switch from NFKC to NFC and add tests for filenames that would be broken under NFKC
1470
    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
1471
1472
1830.3.2 by John Arbash Meinel
normalized_filename is a much better name
1473
def _inaccessible_normalized_filename(path):
1474
    __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
1475
3201.1.1 by jameinel
Fix bug #185458, switch from NFKC to NFC and add tests for filenames that would be broken under NFKC
1476
    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
1477
    return normalized, normalized == path
1478
1479
1185.85.75 by John Arbash Meinel
Adding bzrlib.osutils.unicode_filename to handle unicode normalization for file paths.
1480
if _platform_normalizes_filenames:
1830.3.2 by John Arbash Meinel
normalized_filename is a much better name
1481
    normalized_filename = _accessible_normalized_filename
1185.85.75 by John Arbash Meinel
Adding bzrlib.osutils.unicode_filename to handle unicode normalization for file paths.
1482
else:
1830.3.2 by John Arbash Meinel
normalized_filename is a much better name
1483
    normalized_filename = _inaccessible_normalized_filename
1185.85.75 by John Arbash Meinel
Adding bzrlib.osutils.unicode_filename to handle unicode normalization for file paths.
1484
1485
4634.142.2 by Andrew Bennetts
Make calling siginterrupt in set_signal_handler conditional on a restart_syscall param (default True), and add missing import.
1486
def set_signal_handler(signum, handler, restart_syscall=True):
4634.142.1 by Andrew Bennetts
Add osutils.set_signal_handler to call signal.siginterrupt where possible, and use it in bzrlib.
1487
    """A wrapper for signal.signal that also calls siginterrupt(signum, False)
1488
    on platforms that support that.
4634.142.2 by Andrew Bennetts
Make calling siginterrupt in set_signal_handler conditional on a restart_syscall param (default True), and add missing import.
1489
1490
    :param restart_syscall: if set, allow syscalls interrupted by a signal to
1491
        automatically restart (by calling `signal.siginterrupt(signum,
1492
        False)`).  May be ignored if the feature is not available on this
1493
        platform or Python version.
4634.142.1 by Andrew Bennetts
Add osutils.set_signal_handler to call signal.siginterrupt where possible, and use it in bzrlib.
1494
    """
5141.4.1 by Andrew Bennetts
Reset siginterrupt every time we handle a signal.
1495
    try:
5169.2.2 by Vincent Ladeuil
Just rely on python to tell us what it supports.
1496
        import signal
5141.4.1 by Andrew Bennetts
Reset siginterrupt every time we handle a signal.
1497
        siginterrupt = signal.siginterrupt
5169.2.2 by Vincent Ladeuil
Just rely on python to tell us what it supports.
1498
    except ImportError:
1499
        # This python implementation doesn't provide signal support, hence no
1500
        # handler exists
1501
        return None
5141.4.1 by Andrew Bennetts
Reset siginterrupt every time we handle a signal.
1502
    except AttributeError:
1503
        # siginterrupt doesn't exist on this platform, or for this version
1504
        # of Python.
1505
        siginterrupt = lambda signum, flag: None
4634.142.2 by Andrew Bennetts
Make calling siginterrupt in set_signal_handler conditional on a restart_syscall param (default True), and add missing import.
1506
    if restart_syscall:
5141.4.1 by Andrew Bennetts
Reset siginterrupt every time we handle a signal.
1507
        def sig_handler(*args):
1508
            # Python resets the siginterrupt flag when a signal is
5141.4.3 by Andrew Bennetts
Link to Python bug in comment.
1509
            # received.  <http://bugs.python.org/issue8354>
1510
            # As a workaround for some cases, set it back the way we want it.
4634.142.2 by Andrew Bennetts
Make calling siginterrupt in set_signal_handler conditional on a restart_syscall param (default True), and add missing import.
1511
            siginterrupt(signum, False)
5141.4.1 by Andrew Bennetts
Reset siginterrupt every time we handle a signal.
1512
            # Now run the handler function passed to set_signal_handler.
1513
            handler(*args)
1514
    else:
1515
        sig_handler = handler
1516
    old_handler = signal.signal(signum, sig_handler)
1517
    if restart_syscall:
1518
        siginterrupt(signum, False)
4634.142.1 by Andrew Bennetts
Add osutils.set_signal_handler to call signal.siginterrupt where possible, and use it in bzrlib.
1519
    return old_handler
1520
1521
4747.3.6 by Vincent Ladeuil
terminal_width can now returns None.
1522
default_terminal_width = 80
1523
"""The default terminal width for ttys.
1524
1525
This is defined so that higher levels can share a common fallback value when
1526
terminal_width() returns None.
1527
"""
1528
4797.54.2 by Andrew Bennetts
Try to preserve the 'use COLUMNS until SIGWINCH' behaviour without using SIGWINCH, to keep the behaviour in 2.1 as stable as possible.
1529
# Keep some state so that terminal_width can detect if _terminal_size has
1530
# returned a different size since the process started.  See docstring and
1531
# comments of terminal_width for details.
1532
# _terminal_size_state has 3 possible values: no_data, unchanged, and changed.
1533
_terminal_size_state = 'no_data'
1534
_first_terminal_size = None
4747.3.6 by Vincent Ladeuil
terminal_width can now returns None.
1535
1185.33.60 by Martin Pool
Use full terminal width for verbose test output.
1536
def terminal_width():
4747.3.6 by Vincent Ladeuil
terminal_width can now returns None.
1537
    """Return terminal width.
1538
1539
    None is returned if the width can't established precisely.
4747.4.5 by Vincent Ladeuil
More robusts tests for osutils.terminal_width().
1540
1541
    The rules are:
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
1542
    - if BRZ_COLUMNS is set, returns its value
4747.4.5 by Vincent Ladeuil
More robusts tests for osutils.terminal_width().
1543
    - if there is no controlling terminal, returns None
4797.54.2 by Andrew Bennetts
Try to preserve the 'use COLUMNS until SIGWINCH' behaviour without using SIGWINCH, to keep the behaviour in 2.1 as stable as possible.
1544
    - query the OS, if the queried size has changed since the last query,
1545
      return its value,
4747.4.5 by Vincent Ladeuil
More robusts tests for osutils.terminal_width().
1546
    - if COLUMNS is set, returns its value,
4797.54.2 by Andrew Bennetts
Try to preserve the 'use COLUMNS until SIGWINCH' behaviour without using SIGWINCH, to keep the behaviour in 2.1 as stable as possible.
1547
    - if the OS has a value (even though it's never changed), return its value.
4747.4.5 by Vincent Ladeuil
More robusts tests for osutils.terminal_width().
1548
1549
    From there, we need to query the OS to get the size of the controlling
1550
    terminal.
1551
4797.54.2 by Andrew Bennetts
Try to preserve the 'use COLUMNS until SIGWINCH' behaviour without using SIGWINCH, to keep the behaviour in 2.1 as stable as possible.
1552
    On Unices we query the OS by:
4747.4.5 by Vincent Ladeuil
More robusts tests for osutils.terminal_width().
1553
    - get termios.TIOCGWINSZ
1554
    - if an error occurs or a negative value is obtained, returns None
1555
4797.54.2 by Andrew Bennetts
Try to preserve the 'use COLUMNS until SIGWINCH' behaviour without using SIGWINCH, to keep the behaviour in 2.1 as stable as possible.
1556
    On Windows we query the OS by:
4747.4.5 by Vincent Ladeuil
More robusts tests for osutils.terminal_width().
1557
    - win32utils.get_console_size() decides,
1558
    - returns None on error (provided default value)
4747.3.6 by Vincent Ladeuil
terminal_width can now returns None.
1559
    """
4797.54.2 by Andrew Bennetts
Try to preserve the 'use COLUMNS until SIGWINCH' behaviour without using SIGWINCH, to keep the behaviour in 2.1 as stable as possible.
1560
    # Note to implementors: if changing the rules for determining the width,
1561
    # make sure you've considered the behaviour in these cases:
1562
    #  - M-x shell in emacs, where $COLUMNS is set and TIOCGWINSZ returns 0,0.
6622.1.30 by Jelmer Vernooij
Some more test fixes.
1563
    #  - brz log | less, in bash, where $COLUMNS not set and TIOCGWINSZ returns
4797.54.2 by Andrew Bennetts
Try to preserve the 'use COLUMNS until SIGWINCH' behaviour without using SIGWINCH, to keep the behaviour in 2.1 as stable as possible.
1564
    #    0,0.
1565
    #  - (add more interesting cases here, if you find any)
1566
    # Some programs implement "Use $COLUMNS (if set) until SIGWINCH occurs",
1567
    # but we don't want to register a signal handler because it is impossible
1568
    # to do so without risking EINTR errors in Python <= 2.6.5 (see
1569
    # <http://bugs.python.org/issue8354>).  Instead we check TIOCGWINSZ every
1570
    # time so we can notice if the reported size has changed, which should have
1571
    # a similar effect.
4747.3.4 by Vincent Ladeuil
Add tests, introduce explicit default values, always respect COLUMNS.
1572
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
1573
    # If BRZ_COLUMNS is set, take it, user is always right
5582.7.1 by Neil Martinsen-Burrell
allow BZR_COLUMNS to be 0
1574
    # Except if they specified 0 in which case, impose no limit here
4747.3.7 by Vincent Ladeuil
Introduce BZR_COLUMNS since COLUMNS behaviour is too obscure.
1575
    try:
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
1576
        width = int(os.environ['BRZ_COLUMNS'])
4747.3.7 by Vincent Ladeuil
Introduce BZR_COLUMNS since COLUMNS behaviour is too obscure.
1577
    except (KeyError, ValueError):
5582.7.1 by Neil Martinsen-Burrell
allow BZR_COLUMNS to be 0
1578
        width = None
1579
    if width is not None:
1580
        if width > 0:
1581
            return width
1582
        else:
1583
            return None
4747.3.7 by Vincent Ladeuil
Introduce BZR_COLUMNS since COLUMNS behaviour is too obscure.
1584
4747.3.3 by Vincent Ladeuil
More complete fix (previous one changed the focus).
1585
    isatty = getattr(sys.stdout, 'isatty', None)
4797.54.1 by Andrew Bennetts
Remove the SIGWINCH signal handler.
1586
    if isatty is None or not isatty():
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
1587
        # Don't guess, setting BRZ_COLUMNS is the recommended way to override.
4747.3.6 by Vincent Ladeuil
terminal_width can now returns None.
1588
        return None
4747.3.1 by Joke de Buhr
Prevent linebreaks in output if it's not connected to a tty.
1589
4797.54.2 by Andrew Bennetts
Try to preserve the 'use COLUMNS until SIGWINCH' behaviour without using SIGWINCH, to keep the behaviour in 2.1 as stable as possible.
1590
    # Query the OS
1591
    width, height = os_size = _terminal_size(None, None)
1592
    global _first_terminal_size, _terminal_size_state
1593
    if _terminal_size_state == 'no_data':
1594
        _first_terminal_size = os_size
1595
        _terminal_size_state = 'unchanged'
1596
    elif (_terminal_size_state == 'unchanged' and
1597
          _first_terminal_size != os_size):
1598
        _terminal_size_state = 'changed'
1599
1600
    # If the OS claims to know how wide the terminal is, and this value has
1601
    # ever changed, use that.
1602
    if _terminal_size_state == 'changed':
1603
        if width is not None and width > 0:
1604
            return width
4797.54.1 by Andrew Bennetts
Remove the SIGWINCH signal handler.
1605
1606
    # If COLUMNS is set, use it.
4747.4.3 by Vincent Ladeuil
Re-fix the priority order since there is a known valid case.
1607
    try:
1608
        return int(os.environ['COLUMNS'])
1609
    except (KeyError, ValueError):
1610
        pass
1611
4797.54.2 by Andrew Bennetts
Try to preserve the 'use COLUMNS until SIGWINCH' behaviour without using SIGWINCH, to keep the behaviour in 2.1 as stable as possible.
1612
    # Finally, use an unchanged size from the OS, if we have one.
1613
    if _terminal_size_state == 'unchanged':
1614
        if width is not None and width > 0:
1615
            return width
1616
1617
    # The width could not be determined.
4797.54.1 by Andrew Bennetts
Remove the SIGWINCH signal handler.
1618
    return None
4747.4.5 by Vincent Ladeuil
More robusts tests for osutils.terminal_width().
1619
1620
1621
def _win32_terminal_size(width, height):
1622
    width, height = win32utils.get_console_size(defaultx=width, defaulty=height)
1623
    return width, height
1624
1625
1626
def _ioctl_terminal_size(width, height):
1185.33.60 by Martin Pool
Use full terminal width for verbose test output.
1627
    try:
1704.2.2 by Martin Pool
Detect terminal width using ioctl
1628
        import struct, fcntl, termios
1629
        s = struct.pack('HHHH', 0, 0, 0, 0)
1630
        x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
4747.4.6 by Vincent Ladeuil
Fix parameter order.
1631
        height, width = struct.unpack('HHHH', x)[0:2]
4747.3.4 by Vincent Ladeuil
Add tests, introduce explicit default values, always respect COLUMNS.
1632
    except (IOError, AttributeError):
4747.4.5 by Vincent Ladeuil
More robusts tests for osutils.terminal_width().
1633
        pass
1634
    return width, height
1635
1636
_terminal_size = None
1637
"""Returns the terminal size as (width, height).
1638
1639
:param width: Default value for width.
1640
:param height: Default value for height.
1641
1642
This is defined specifically for each OS and query the size of the controlling
1643
terminal. If any error occurs, the provided default values should be returned.
1644
"""
1645
if sys.platform == 'win32':
1646
    _terminal_size = _win32_terminal_size
1647
else:
1648
    _terminal_size = _ioctl_terminal_size
1534.7.25 by Aaron Bentley
Added set_executability
1649
1963.1.5 by John Arbash Meinel
Create an osutils helper function for modifying the environment
1650
1534.7.25 by Aaron Bentley
Added set_executability
1651
def supports_executable():
1534.7.160 by Aaron Bentley
Changed implementation of supports_executable
1652
    return sys.platform != "win32"
1551.2.53 by abentley
Strip trailing slashes in a platform-sensible way
1653
1654
1551.10.4 by Aaron Bentley
Update to skip on win32
1655
def supports_posix_readonly():
1656
    """Return True if 'readonly' has POSIX semantics, False otherwise.
1657
1658
    Notably, a win32 readonly file cannot be deleted, unlike POSIX where the
1659
    directory controls creation/deletion, etc.
1660
1661
    And under win32, readonly means that the directory itself cannot be
1662
    deleted.  The contents of a readonly directory can be changed, unlike POSIX
1663
    where files in readonly directories cannot be added, deleted or renamed.
1664
    """
1665
    return sys.platform != "win32"
1666
1667
1963.1.5 by John Arbash Meinel
Create an osutils helper function for modifying the environment
1668
def set_or_unset_env(env_variable, value):
1669
    """Modify the environment, setting or removing the env_variable.
1670
1671
    :param env_variable: The environment variable in question
1672
    :param value: The value to set the environment to. If None, then
1673
        the variable will be removed.
1674
    :return: The original value of the environment variable.
1675
    """
1676
    orig_val = os.environ.get(env_variable)
1677
    if value is None:
1678
        if orig_val is not None:
1679
            del os.environ[env_variable]
1680
    else:
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
1681
        if not PY3 and isinstance(value, text_type):
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
1682
            value = value.encode(get_user_encoding())
1963.1.5 by John Arbash Meinel
Create an osutils helper function for modifying the environment
1683
        os.environ[env_variable] = value
1684
    return orig_val
1685
1686
1551.2.56 by Aaron Bentley
Better illegal pathname check for Windows
1687
_validWin32PathRE = re.compile(r'^([A-Za-z]:[/\\])?[^:<>*"?\|]*$')
1688
1689
1690
def check_legal_path(path):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1691
    """Check whether the supplied path is legal.
1551.2.56 by Aaron Bentley
Better illegal pathname check for Windows
1692
    This is only required on Windows, so we don't test on other platforms
1693
    right now.
1694
    """
1695
    if sys.platform != "win32":
1696
        return
1697
    if _validWin32PathRE.match(path) is None:
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
1698
        raise errors.IllegalPath(path)
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1699
1700
3596.2.2 by John Arbash Meinel
Factor out the common exception handling looking for ENOTDIR and use it
1701
_WIN32_ERROR_DIRECTORY = 267 # Similar to errno.ENOTDIR
1702
1703
def _is_error_enotdir(e):
1704
    """Check if this exception represents ENOTDIR.
1705
1706
    Unfortunately, python is very inconsistent about the exception
1707
    here. The cases are:
1708
      1) Linux, Mac OSX all versions seem to set errno == ENOTDIR
1709
      2) Windows, Python2.4, uses errno == ERROR_DIRECTORY (267)
1710
         which is the windows error code.
1711
      3) Windows, Python2.5 uses errno == EINVAL and
1712
         winerror == ERROR_DIRECTORY
1713
1714
    :param e: An Exception object (expected to be OSError with an errno
1715
        attribute, but we should be able to cope with anything)
1716
    :return: True if this represents an ENOTDIR error. False otherwise.
1717
    """
1718
    en = getattr(e, 'errno', None)
1719
    if (en == errno.ENOTDIR
1720
        or (sys.platform == 'win32'
1721
            and (en == _WIN32_ERROR_DIRECTORY
1722
                 or (en == errno.EINVAL
1723
                     and getattr(e, 'winerror', None) == _WIN32_ERROR_DIRECTORY)
1724
        ))):
1725
        return True
1726
    return False
1727
1728
1757.2.8 by Robert Collins
Teach walkdirs to walk a subdir of a tree.
1729
def walkdirs(top, prefix=""):
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1730
    """Yield data about all the directories in a tree.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1731
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1732
    This yields all the data about the contents of a directory at a time.
1733
    After each directory has been yielded, if the caller has mutated the list
1734
    to exclude some directories, they are then not descended into.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1735
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1736
    The data yielded is of the form:
1897.1.2 by Robert Collins
cleanup osutils.walkdirs changes after review.
1737
    ((directory-relpath, directory-path-from-top),
2694.4.1 by Alexander Belchenko
trivial fix for docstring of osutils.walkdirs()
1738
    [(relpath, basename, kind, lstat, path-from-top), ...]),
1897.1.2 by Robert Collins
cleanup osutils.walkdirs changes after review.
1739
     - directory-relpath is the relative path of the directory being returned
1740
       with respect to top. prefix is prepended to this.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1741
     - directory-path-from-root is the path including top for this directory.
1897.1.2 by Robert Collins
cleanup osutils.walkdirs changes after review.
1742
       It is suitable for use with os functions.
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
1743
     - relpath is the relative path within the subtree being walked.
1744
     - basename is the basename of the path
1897.1.2 by Robert Collins
cleanup osutils.walkdirs changes after review.
1745
     - 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.
1746
       present within the tree - but it may be recorded as versioned. See
1747
       versioned_kind.
1748
     - lstat is the stat data *if* the file was statted.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1749
     - planned, not implemented:
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
1750
       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.
1751
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1752
    :param prefix: Prefix the relpaths that are yielded with 'prefix'. This
1757.2.16 by Robert Collins
Review comments.
1753
        allows one to walk a subtree but get paths that are relative to a tree
1754
        rooted higher up.
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1755
    :return: an iterator over the dirs.
1756
    """
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
1757
    #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
1758
    # 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.
1759
    # depending on top and prefix - i.e. ./foo and foo as a pair leads to
1760
    # potentially confusing output. We should make this more robust - but
1897.1.2 by Robert Collins
cleanup osutils.walkdirs changes after review.
1761
    # 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%
1762
    _lstat = os.lstat
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1763
    _directory = _directory_kind
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
1764
    _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)
1765
    _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.
1766
    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.
1767
    while pending:
1768
        # 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%
1769
        relroot, _, _, _, top = pending.pop()
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1770
        if relroot:
1771
            relprefix = relroot + u'/'
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1772
        else:
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1773
            relprefix = ''
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1774
        top_slash = top + u'/'
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1775
1776
        dirblock = []
1777
        append = dirblock.append
3585.2.4 by Robert Collins
* Deleting directories by hand before running ``bzr rm`` will not
1778
        try:
5279.2.7 by Eric Moritz
1. deleted trailing whitespace
1779
            names = sorted(map(decode_filename, _listdir(top)))
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
1780
        except OSError as e:
3596.2.2 by John Arbash Meinel
Factor out the common exception handling looking for ENOTDIR and use it
1781
            if not _is_error_enotdir(e):
3585.2.4 by Robert Collins
* Deleting directories by hand before running ``bzr rm`` will not
1782
                raise
1783
        else:
1784
            for name in names:
1785
                abspath = top_slash + name
1786
                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)
1787
                kind = _kind_from_mode(statvalue.st_mode)
3585.2.4 by Robert Collins
* Deleting directories by hand before running ``bzr rm`` will not
1788
                append((relprefix + name, name, kind, statvalue, abspath))
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1789
        yield (relroot, top), dirblock
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1790
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1791
        # push the user specified dirs from dirblock
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1792
        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.
1793
1794
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1795
class DirReader(object):
1796
    """An interface for reading directories."""
1797
1798
    def top_prefix_to_starting_dir(self, top, prefix=""):
1799
        """Converts top and prefix to a starting dir entry
1800
1801
        :param top: A utf8 path
1802
        :param prefix: An optional utf8 path to prefix output relative paths
1803
            with.
1804
        :return: A tuple starting with prefix, and ending with the native
1805
            encoding of top.
1806
        """
1807
        raise NotImplementedError(self.top_prefix_to_starting_dir)
1808
1809
    def read_dir(self, prefix, top):
1810
        """Read a specific dir.
1811
1812
        :param prefix: A utf8 prefix to be preprended to the path basenames.
1813
        :param top: A natively encoded path to read.
3696.3.10 by Robert Collins
Review feedback.
1814
        :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.
1815
            (utf8_relpath, utf8_name, kind, lstatvalue, native_abspath)
1816
        """
1817
        raise NotImplementedError(self.read_dir)
1818
1819
1820
_selected_dir_reader = None
1821
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1822
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
1823
def _walkdirs_utf8(top, prefix=""):
1824
    """Yield data about all the directories in a tree.
1825
1826
    This yields the same information as walkdirs() only each entry is yielded
1827
    in utf-8. On platforms which have a filesystem encoding of utf8 the paths
1828
    are returned as exact byte-strings.
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1829
1830
    :return: yields a tuple of (dir_info, [file_info])
1831
        dir_info is (utf8_relpath, path-from-top)
1832
        file_info is (utf8_relpath, utf8_name, kind, lstat, path-from-top)
1833
        if top is an absolute path, path-from-top is also an absolute path.
1834
        path-from-top might be unicode or utf8, but it is the correct path to
1835
        pass to os functions to affect the file in question. (such as os.lstat)
1836
    """
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1837
    global _selected_dir_reader
1838
    if _selected_dir_reader is None:
3224.5.17 by Andrew Bennetts
Avoid importing win32utils when sys.platform != win32
1839
        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'
1840
            # Win98 doesn't have unicode apis like FindFirstFileW
1841
            # TODO: We possibly could support Win98 by falling back to the
1842
            #       original FindFirstFile, and using TCHAR instead of WCHAR,
1843
            #       but that gets a bit tricky, and requires custom compiling
1844
            #       for win98 anyway.
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1845
            try:
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
1846
                from ._walkdirs_win32 import Win32ReadDir
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1847
                _selected_dir_reader = Win32ReadDir()
4241.14.6 by Vincent Ladeuil
Start DirReader parametrized tests.
1848
            except ImportError:
1849
                pass
6352.3.4 by Martin Packman
Minor tweaks including normalising _fs_enc value
1850
        elif _fs_enc in ('utf-8', '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)
1851
            try:
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
1852
                from ._readdir_pyx import UTF8DirReader
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)
1853
                _selected_dir_reader = UTF8DirReader()
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
1854
            except ImportError as e:
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
1855
                failed_to_load_extension(e)
4241.14.6 by Vincent Ladeuil
Start DirReader parametrized tests.
1856
                pass
1857
1858
    if _selected_dir_reader is None:
1859
        # Fallback to the python version
1860
        _selected_dir_reader = UnicodeDirReader()
1861
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1862
    # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1863
    # 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)
1864
    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.
1865
    read_dir = _selected_dir_reader.read_dir
1866
    _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
1867
    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)
1868
        relroot, _, _, _, top = pending[-1].pop()
1869
        if not pending[-1]:
1870
            pending.pop()
1871
        dirblock = sorted(read_dir(relroot, top))
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1872
        yield (relroot, top), dirblock
1873
        # 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)
1874
        next = [d for d in reversed(dirblock) if d[2] == _directory]
1875
        if next:
1876
            pending.append(next)
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1877
1878
1879
class UnicodeDirReader(DirReader):
1880
    """A dir reader for non-utf8 file systems, which transcodes."""
1881
1882
    __slots__ = ['_utf8_encode']
1883
1884
    def __init__(self):
1885
        self._utf8_encode = codecs.getencoder('utf8')
1886
1887
    def top_prefix_to_starting_dir(self, top, prefix=""):
1888
        """See DirReader.top_prefix_to_starting_dir."""
1889
        return (safe_utf8(prefix), None, None, None, safe_unicode(top))
1890
1891
    def read_dir(self, prefix, top):
1892
        """Read a single directory from a non-utf8 file system.
1893
1894
        top, and the abspath element in the output are unicode, all other paths
1895
        are utf8. Local disk IO is done via unicode calls to listdir etc.
1896
1897
        This is currently the fallback code path when the filesystem encoding is
1898
        not UTF-8. It may be better to implement an alternative so that we can
1899
        safely handle paths that are not properly decodable in the current
1900
        encoding.
1901
1902
        See DirReader.read_dir for details.
1903
        """
1904
        _utf8_encode = self._utf8_encode
1905
        _lstat = os.lstat
1906
        _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)
1907
        _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.
1908
1909
        if prefix:
1910
            relprefix = prefix + '/'
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1911
        else:
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1912
            relprefix = ''
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1913
        top_slash = top + u'/'
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1914
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1915
        dirblock = []
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1916
        append = dirblock.append
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1917
        for name in sorted(_listdir(top)):
3696.3.12 by Robert Collins
Fix PQM test failure.
1918
            try:
1919
                name_utf8 = _utf8_encode(name)[0]
1920
            except UnicodeDecodeError:
1921
                raise errors.BadFilenameEncoding(
1922
                    _utf8_encode(relprefix)[0] + name, _fs_enc)
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1923
            abspath = top_slash + name
1924
            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)
1925
            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%
1926
            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.
1927
        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
1928
1929
1907.3.2 by John Arbash Meinel
Updated the copy_tree function to allow overriding functionality.
1930
def copy_tree(from_path, to_path, handlers={}):
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1931
    """Copy all of the entries in from_path into to_path.
1932
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1933
    :param from_path: The base directory to copy.
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1934
    :param to_path: The target directory. If it does not exist, it will
1935
        be created.
1907.3.2 by John Arbash Meinel
Updated the copy_tree function to allow overriding functionality.
1936
    :param handlers: A dictionary of functions, which takes a source and
1937
        destinations for files, directories, etc.
1938
        It is keyed on the file kind, such as 'directory', 'symlink', or 'file'
1939
        'file', 'directory', and 'symlink' should always exist.
1940
        If they are missing, they will be replaced with 'os.mkdir()',
1941
        'os.readlink() + os.symlink()', and 'shutil.copy2()', respectively.
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1942
    """
1943
    # Now, just copy the existing cached tree to the new location
1944
    # We use a cheap trick here.
1945
    # Absolute paths are prefixed with the first parameter
1946
    # relative paths are prefixed with the second.
1947
    # So we can get both the source and target returned
1948
    # without any extra work.
1949
1907.3.2 by John Arbash Meinel
Updated the copy_tree function to allow overriding functionality.
1950
    def copy_dir(source, dest):
1951
        os.mkdir(dest)
1952
1953
    def copy_link(source, dest):
1954
        """Copy the contents of a symlink"""
1955
        link_to = os.readlink(source)
1956
        os.symlink(link_to, dest)
1957
1958
    real_handlers = {'file':shutil.copy2,
1959
                     'symlink':copy_link,
1960
                     'directory':copy_dir,
1961
                    }
1962
    real_handlers.update(handlers)
1963
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1964
    if not os.path.exists(to_path):
1907.3.2 by John Arbash Meinel
Updated the copy_tree function to allow overriding functionality.
1965
        real_handlers['directory'](from_path, to_path)
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1966
1967
    for dir_info, entries in walkdirs(from_path, prefix=to_path):
1968
        for relpath, name, kind, st, abspath in entries:
1907.3.2 by John Arbash Meinel
Updated the copy_tree function to allow overriding functionality.
1969
            real_handlers[kind](abspath, relpath)
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1970
1971
5116.2.6 by Parth Malwankar
renamed copy_ownership to copy_ownership_from_path.
1972
def copy_ownership_from_path(dst, src=None):
5051.4.11 by Parth Malwankar
closed Martins review comments.
1973
    """Copy usr/grp ownership from src file/dir to dst file/dir.
1974
1975
    If src is None, the containing directory is used as source. If chown
1976
    fails, the error is ignored and a warning is printed.
1977
    """
5074.4.6 by John Arbash Meinel
Unbreak bzr on windows.
1978
    chown = getattr(os, 'chown', None)
1979
    if chown is None:
1980
        return
5051.4.9 by Parth Malwankar
removed parent_dir.
1981
1982
    if src == None:
1983
        src = os.path.dirname(dst)
1984
        if src == '':
1985
            src = '.'
1986
4634.143.4 by Parth Malwankar
added parent_dir and mkdir to osutils. osutils.mkdir optionally
1987
    try:
4634.143.1 by Parth Malwankar
default .bazaar, .bzr.log and .bazaar/bazaar.conf retain
1988
        s = os.stat(src)
5074.4.6 by John Arbash Meinel
Unbreak bzr on windows.
1989
        chown(dst, s.st_uid, s.st_gid)
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
1990
    except OSError as e:
5523.2.3 by Parth Malwankar
message is now shown to the user but is not too scary.
1991
        trace.warning(
1992
            'Unable to copy ownership from "%s" to "%s". '
1993
            'You may want to set it manually.', src, dst)
1994
        trace.log_exception_quietly()
4634.143.4 by Parth Malwankar
added parent_dir and mkdir to osutils. osutils.mkdir optionally
1995
1996
1773.3.1 by Robert Collins
Add path_prefix_key and compare_paths_prefix_order utility functions.
1997
def path_prefix_key(path):
1998
    """Generate a prefix-order path key for path.
1999
2000
    This can be used to sort paths in the same way that walkdirs does.
2001
    """
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.
2002
    return (dirname(path) , path)
1773.3.1 by Robert Collins
Add path_prefix_key and compare_paths_prefix_order utility functions.
2003
2004
2005
def compare_paths_prefix_order(path_a, path_b):
2006
    """Compare path_a and path_b to generate the same order walkdirs uses."""
2007
    key_a = path_prefix_key(path_a)
2008
    key_b = path_prefix_key(path_b)
2009
    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
2010
2011
2012
_cached_user_encoding = None
2013
2014
6630.1.1 by Jelmer Vernooij
Remove deprecated functionality.
2015
def get_user_encoding():
1955.2.2 by John Arbash Meinel
Change the name of the test classes (test_lang => test_locale), move the function into osutils.py
2016
    """Find out what the preferred user encoding is.
2017
2018
    This is generally the encoding that is used for command line parameters
2019
    and file contents. This may be different from the terminal encoding
2020
    or the filesystem encoding.
2021
2022
    :return: A string defining the preferred user encoding
2023
    """
2024
    global _cached_user_encoding
6383.1.3 by Martin Packman
Deprecate public use_cache parameter in favour of test specific override
2025
    if _cached_user_encoding is not None:
1955.2.2 by John Arbash Meinel
Change the name of the test classes (test_lang => test_locale), move the function into osutils.py
2026
        return _cached_user_encoding
2027
6383.1.1 by Martin Packman
Simplify get_user_encoding by avoiding locale hacks and assuming setlocale has been called
2028
    if os.name == 'posix' and getattr(locale, 'CODESET', None) is not None:
2029
        # Use the existing locale settings and call nl_langinfo directly
2030
        # rather than going through getpreferredencoding. This avoids
2031
        # <http://bugs.python.org/issue6202> on OSX Python 2.6 and the
2032
        # possibility of the setlocale call throwing an error.
2033
        user_encoding = locale.nl_langinfo(locale.CODESET)
1955.2.2 by John Arbash Meinel
Change the name of the test classes (test_lang => test_locale), move the function into osutils.py
2034
    else:
6383.1.1 by Martin Packman
Simplify get_user_encoding by avoiding locale hacks and assuming setlocale has been called
2035
        # GZ 2011-12-19: On windows could call GetACP directly instead.
6383.1.4 by Martin Packman
Simplify tests a little and make it clear setlocale is not being used
2036
        user_encoding = locale.getpreferredencoding(False)
1955.2.2 by John Arbash Meinel
Change the name of the test classes (test_lang => test_locale), move the function into osutils.py
2037
6383.1.1 by Martin Packman
Simplify get_user_encoding by avoiding locale hacks and assuming setlocale has been called
2038
    try:
2039
        user_encoding = codecs.lookup(user_encoding).name
2040
    except LookupError:
2041
        if user_encoding not in ("", "cp0"):
6622.1.4 by Jelmer Vernooij
Fix some more tests.
2042
            sys.stderr.write('brz: warning:'
2192.1.1 by Alexander Belchenko
Before actually using encoding need to check that Python has corresponding codec
2043
                             ' unknown encoding %s.'
2044
                             ' Continuing with ascii encoding.\n'
2192.1.3 by Alexander Belchenko
Tests for osutils.get_user_encoding
2045
                             % user_encoding
2192.1.1 by Alexander Belchenko
Before actually using encoding need to check that Python has corresponding codec
2046
                            )
6383.1.1 by Martin Packman
Simplify get_user_encoding by avoiding locale hacks and assuming setlocale has been called
2047
        user_encoding = 'ascii'
2048
    else:
2049
        # Get 'ascii' when setlocale has not been called or LANG=C or unset.
2050
        if user_encoding == 'ascii':
2051
            if sys.platform == 'darwin':
2052
                # OSX is special-cased in Python to have a UTF-8 filesystem
2053
                # encoding and previously had LANG set here if not present.
2054
                user_encoding = 'utf-8'
2055
            # GZ 2011-12-19: Maybe UTF-8 should be the default in this case
2056
            #                for some other posix platforms as well.
2192.1.3 by Alexander Belchenko
Tests for osutils.get_user_encoding
2057
6383.1.3 by Martin Packman
Deprecate public use_cache parameter in favour of test specific override
2058
    _cached_user_encoding = user_encoding
2192.1.3 by Alexander Belchenko
Tests for osutils.get_user_encoding
2059
    return user_encoding
2091.1.1 by Martin Pool
Avoid MSG_WAITALL as it doesn't work on Windows
2060
2061
4797.57.10 by Alexander Belchenko
path_encoding selection logic extracted as helper function
2062
def get_diff_header_encoding():
5258.1.5 by Alexander Belchenko
tweak requested by Martin Pool: use terminal encoding for diff headers on all platforms
2063
    return get_terminal_encoding()
4797.57.10 by Alexander Belchenko
path_encoding selection logic extracted as helper function
2064
2065
3626.1.1 by Mark Hammond
Add osutils.get_host_name() to return a unicode hostname to prevent
2066
def get_host_name():
3626.1.4 by John Arbash Meinel
Document the difference in get_host_name, per Robert's request.
2067
    """Return the current unicode host name.
2068
2069
    This is meant to be used in place of socket.gethostname() because that
2070
    behaves inconsistently on different platforms.
2071
    """
3626.1.1 by Mark Hammond
Add osutils.get_host_name() to return a unicode hostname to prevent
2072
    if sys.platform == "win32":
2073
        return win32utils.get_host_name()
2074
    else:
2075
        import socket
2076
        return socket.gethostname().decode(get_user_encoding())
2077
2078
5011.3.11 by Andrew Bennetts
Consolidate changes, try to minimise unnecessary changes and tidy up those that kept.
2079
# We must not read/write any more than 64k at a time from/to a socket so we
2080
# don't risk "no buffer space available" errors on some platforms.  Windows in
2081
# particular is likely to throw WSAECONNABORTED or WSAENOBUFS if given too much
2082
# data at once.
2083
MAX_SOCKET_CHUNK = 64 * 1024
2084
6437.74.2 by John Arbash Meinel
Push the change down into osutils.send_all. Needs tests at that level.
2085
_end_of_stream_errors = [errno.ECONNRESET, errno.EPIPE, errno.EINVAL]
5599.3.1 by John Arbash Meinel
Consider WSAECONNABORTED to be an end-of-stream as well as WSAECONNRESET.
2086
for _eno in ['WSAECONNRESET', 'WSAECONNABORTED']:
2087
    _eno = getattr(errno, _eno, None)
2088
    if _eno is not None:
2089
        _end_of_stream_errors.append(_eno)
2090
del _eno
2091
2092
5011.3.12 by Andrew Bennetts
Make report_activity param of read_bytes_from_socket optional.
2093
def read_bytes_from_socket(sock, report_activity=None,
5011.3.11 by Andrew Bennetts
Consolidate changes, try to minimise unnecessary changes and tidy up those that kept.
2094
        max_read_size=MAX_SOCKET_CHUNK):
2095
    """Read up to max_read_size of bytes from sock and notify of progress.
2096
2097
    Translates "Connection reset by peer" into file-like EOF (return an
2098
    empty string rather than raise an error), and repeats the recv if
2099
    interrupted by a signal.
2100
    """
6619.3.18 by Jelmer Vernooij
Run 2to3 idioms fixer.
2101
    while True:
5011.3.11 by Andrew Bennetts
Consolidate changes, try to minimise unnecessary changes and tidy up those that kept.
2102
        try:
2103
            bytes = sock.recv(max_read_size)
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
2104
        except socket.error as e:
5011.3.11 by Andrew Bennetts
Consolidate changes, try to minimise unnecessary changes and tidy up those that kept.
2105
            eno = e.args[0]
5599.3.1 by John Arbash Meinel
Consider WSAECONNABORTED to be an end-of-stream as well as WSAECONNRESET.
2106
            if eno in _end_of_stream_errors:
5011.3.11 by Andrew Bennetts
Consolidate changes, try to minimise unnecessary changes and tidy up those that kept.
2107
                # The connection was closed by the other side.  Callers expect
2108
                # an empty string to signal end-of-stream.
2109
                return ""
2110
            elif eno == errno.EINTR:
2111
                # Retry the interrupted recv.
2112
                continue
2113
            raise
2114
        else:
5011.3.12 by Andrew Bennetts
Make report_activity param of read_bytes_from_socket optional.
2115
            if report_activity is not None:
2116
                report_activity(len(bytes), 'read')
5011.3.11 by Andrew Bennetts
Consolidate changes, try to minimise unnecessary changes and tidy up those that kept.
2117
            return bytes
2118
2119
2120
def recv_all(socket, count):
2121
    """Receive an exact number of bytes.
2122
2123
    Regular Socket.recv() may return less than the requested number of bytes,
2124
    depending on what's in the OS buffer.  MSG_WAITALL is not available
2125
    on all platforms, but this should work everywhere.  This will return
2126
    less than the requested amount if the remote end closes.
2127
2128
    This isn't optimized and is intended mostly for use in testing.
2129
    """
2130
    b = ''
2131
    while len(b) < count:
5011.3.12 by Andrew Bennetts
Make report_activity param of read_bytes_from_socket optional.
2132
        new = read_bytes_from_socket(socket, None, count - len(b))
5011.3.11 by Andrew Bennetts
Consolidate changes, try to minimise unnecessary changes and tidy up those that kept.
2133
        if new == '':
2134
            break # eof
2135
        b += new
2136
    return b
2137
5011.3.4 by Andrew Bennetts
Reinstate osutils.until_no_eintr and .send_all, reapply until_no_eintr in SmartSimplePipesClientMedium.read_bytes.
2138
2139
def send_all(sock, bytes, report_activity=None):
2140
    """Send all bytes on a socket.
5279.2.7 by Eric Moritz
1. deleted trailing whitespace
2141
5011.3.4 by Andrew Bennetts
Reinstate osutils.until_no_eintr and .send_all, reapply until_no_eintr in SmartSimplePipesClientMedium.read_bytes.
2142
    Breaks large blocks in smaller chunks to avoid buffering limitations on
2143
    some platforms, and catches EINTR which may be thrown if the send is
2144
    interrupted by a signal.
2145
5011.3.11 by Andrew Bennetts
Consolidate changes, try to minimise unnecessary changes and tidy up those that kept.
2146
    This is preferred to socket.sendall(), because it avoids portability bugs
2147
    and provides activity reporting.
5279.2.7 by Eric Moritz
1. deleted trailing whitespace
2148
5011.3.4 by Andrew Bennetts
Reinstate osutils.until_no_eintr and .send_all, reapply until_no_eintr in SmartSimplePipesClientMedium.read_bytes.
2149
    :param report_activity: Call this as bytes are read, see
2150
        Transport._report_activity
2151
    """
2152
    sent_total = 0
2153
    byte_count = len(bytes)
6632.1.1 by Martin
Change uses of buffer to memoryview
2154
    view = memoryview(bytes)
5011.3.4 by Andrew Bennetts
Reinstate osutils.until_no_eintr and .send_all, reapply until_no_eintr in SmartSimplePipesClientMedium.read_bytes.
2155
    while sent_total < byte_count:
2156
        try:
6632.1.1 by Martin
Change uses of buffer to memoryview
2157
            sent = sock.send(view[sent_total:sent_total+MAX_SOCKET_CHUNK])
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
2158
        except (socket.error, IOError) as e:
6437.74.2 by John Arbash Meinel
Push the change down into osutils.send_all. Needs tests at that level.
2159
            if e.args[0] in _end_of_stream_errors:
2160
                raise errors.ConnectionReset(
2161
                    "Error trying to write to socket", e)
5011.3.4 by Andrew Bennetts
Reinstate osutils.until_no_eintr and .send_all, reapply until_no_eintr in SmartSimplePipesClientMedium.read_bytes.
2162
            if e.args[0] != errno.EINTR:
2163
                raise
2164
        else:
6437.73.1 by John Arbash Meinel
Fix bug #1047309. Treat a series of no-bytes-sent as a ECONNRESET failure.
2165
            if sent == 0:
6437.73.2 by John Arbash Meinel
simplify the fix. Sending 0 bytes seems to always indicate that we have a closed connection.
2166
                raise errors.ConnectionReset('Sending to %s returned 0 bytes'
2167
                                             % (sock,))
5011.3.4 by Andrew Bennetts
Reinstate osutils.until_no_eintr and .send_all, reapply until_no_eintr in SmartSimplePipesClientMedium.read_bytes.
2168
            sent_total += sent
6437.73.1 by John Arbash Meinel
Fix bug #1047309. Treat a series of no-bytes-sent as a ECONNRESET failure.
2169
            if report_activity is not None:
2170
                report_activity(sent, 'write')
3118.2.1 by Andrew Bennetts
(andrew) Fix #115781 by passing no more than 64k at a time to socket.sendall.
2171
5247.5.14 by Vincent Ladeuil
Fix the helper again, the python one is bogus :-/
2172
5247.5.29 by Vincent Ladeuil
Fixed as per jam's review.
2173
def connect_socket(address):
2174
    # Slight variation of the socket.create_connection() function (provided by
2175
    # python-2.6) that can fail if getaddrinfo returns an empty list. We also
2176
    # provide it for previous python versions. Also, we don't use the timeout
2177
    # parameter (provided by the python implementation) so we don't implement
2178
    # it either).
5247.5.14 by Vincent Ladeuil
Fix the helper again, the python one is bogus :-/
2179
    err = socket.error('getaddrinfo returns an empty list')
2180
    host, port = address
2181
    for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
2182
        af, socktype, proto, canonname, sa = res
2183
        sock = None
2184
        try:
2185
            sock = socket.socket(af, socktype, proto)
2186
            sock.connect(sa)
2187
            return sock
2188
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
2189
        except socket.error as err:
5247.5.14 by Vincent Ladeuil
Fix the helper again, the python one is bogus :-/
2190
            # 'err' is now the most recent error
2191
            if sock is not None:
2192
                sock.close()
2193
    raise err
5247.3.7 by Vincent Ladeuil
Provide connect_socket (socket.create_connection) for pythons older than 2.6.
2194
3118.2.1 by Andrew Bennetts
(andrew) Fix #115781 by passing no more than 64k at a time to socket.sendall.
2195
2091.3.7 by Aaron Bentley
Rename real_parent to dereferenced_path
2196
def dereference_path(path):
2197
    """Determine the real path to a file.
2198
2199
    All parent elements are dereferenced.  But the file itself is not
2200
    dereferenced.
2201
    :param path: The original path.  May be absolute or relative.
2202
    :return: the real path *to* the file
2203
    """
2091.3.5 by Aaron Bentley
Move realpath functionality into osutils
2204
    parent, base = os.path.split(path)
2205
    # The pathjoin for '.' is a workaround for Python bug #1213894.
2206
    # (initial path components aren't dereferenced)
2207
    return pathjoin(realpath(pathjoin('.', parent)), base)
2681.3.4 by Lukáš Lalinsky
- Rename 'windows' to 'mapi'
2208
2209
2210
def supports_mapi():
2211
    """Return True if we can use MAPI to launch a mail client."""
2212
    return sys.platform == "win32"
3089.3.8 by Ian Clatworthy
move resource loading into a reusable function
2213
2214
2215
def resource_string(package, resource_name):
2216
    """Load a resource from a package and return it as a string.
2217
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2218
    Note: Only packages that start with breezy are currently supported.
3089.3.8 by Ian Clatworthy
move resource loading into a reusable function
2219
2220
    This is designed to be a lightweight implementation of resource
2221
    loading in a way which is API compatible with the same API from
2222
    pkg_resources. See
2223
    http://peak.telecommunity.com/DevCenter/PkgResources#basic-resource-access.
2224
    If and when pkg_resources becomes a standard library, this routine
2225
    can delegate to it.
2226
    """
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2227
    # Check package name is within breezy
2228
    if package == "breezy":
3089.3.8 by Ian Clatworthy
move resource loading into a reusable function
2229
        resource_relpath = resource_name
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2230
    elif package.startswith("breezy."):
2231
        package = package[len("breezy."):].replace('.', os.sep)
3089.3.8 by Ian Clatworthy
move resource loading into a reusable function
2232
        resource_relpath = pathjoin(package, resource_name)
2233
    else:
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2234
        raise errors.BzrError('resource package %s not in breezy' % package)
3089.3.8 by Ian Clatworthy
move resource loading into a reusable function
2235
2236
    # Map the resource to a file and read its contents
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2237
    base = dirname(breezy.__file__)
3089.3.8 by Ian Clatworthy
move resource loading into a reusable function
2238
    if getattr(sys, 'frozen', None):    # bzr.exe
2239
        base = abspath(pathjoin(base, '..', '..'))
4708.2.2 by Martin
Workingtree changes sitting around since November, more explict closing of files in bzrlib
2240
    f = file(pathjoin(base, resource_relpath), "rU")
2241
    try:
2242
        return f.read()
2243
    finally:
2244
        f.close()
1739.2.7 by Robert Collins
Update readdir pyrex source files and usage in line with current practice.
2245
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)
2246
def file_kind_from_stat_mode_thunk(mode):
2247
    global file_kind_from_stat_mode
2248
    if file_kind_from_stat_mode is file_kind_from_stat_mode_thunk:
2249
        try:
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
2250
            from ._readdir_pyx import UTF8DirReader
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)
2251
            file_kind_from_stat_mode = UTF8DirReader().kind_from_mode
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
2252
        except ImportError as e:
4694.2.1 by John Arbash Meinel
Fix bug #430645, don't issue a warning when failing to import _readdir_pyx the second time.
2253
            # This is one time where we won't warn that an extension failed to
2254
            # load. The extension is never available on Windows anyway.
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
2255
            from ._readdir_py import (
3696.4.8 by Robert Collins
Fix up inter_changes with dirstate both C and python.
2256
                _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)
2257
                )
2258
    return file_kind_from_stat_mode(mode)
2259
file_kind_from_stat_mode = file_kind_from_stat_mode_thunk
2260
6046.2.6 by Shannon Weyrick
Add file_stat, and make file_kind use it. file_stat can potentially cache results.
2261
def file_stat(f, _lstat=os.lstat):
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)
2262
    try:
6046.2.6 by Shannon Weyrick
Add file_stat, and make file_kind use it. file_stat can potentially cache results.
2263
        # XXX cache?
2264
        return _lstat(f)
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
2265
    except OSError as 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)
2266
        if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
2267
            raise errors.NoSuchFile(f)
2268
        raise
2269
6046.2.6 by Shannon Weyrick
Add file_stat, and make file_kind use it. file_stat can potentially cache results.
2270
def file_kind(f, _lstat=os.lstat):
2271
    stat_value = file_stat(f, _lstat)
2272
    return file_kind_from_stat_mode(stat_value.st_mode)
3923.3.1 by Andrew Bennetts
Quick attempt at adding some EINTR-proofing to smart protocol code.
2273
5011.3.4 by Andrew Bennetts
Reinstate osutils.until_no_eintr and .send_all, reapply until_no_eintr in SmartSimplePipesClientMedium.read_bytes.
2274
def until_no_eintr(f, *a, **kw):
2275
    """Run f(*a, **kw), retrying if an EINTR error occurs.
5279.2.7 by Eric Moritz
1. deleted trailing whitespace
2276
5011.3.4 by Andrew Bennetts
Reinstate osutils.until_no_eintr and .send_all, reapply until_no_eintr in SmartSimplePipesClientMedium.read_bytes.
2277
    WARNING: you must be certain that it is safe to retry the call repeatedly
2278
    if EINTR does occur.  This is typically only true for low-level operations
2279
    like os.read.  If in any doubt, don't use this.
5011.3.5 by Andrew Bennetts
Expand until_no_eintr's docstring more with some explanation for why it is not a complete solution.
2280
2281
    Keep in mind that this is not a complete solution to EINTR.  There is
2282
    probably code in the Python standard library and other dependencies that
2283
    may encounter EINTR if a signal arrives (and there is signal handler for
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2284
    that signal).  So this function can reduce the impact for IO that breezy
5011.3.5 by Andrew Bennetts
Expand until_no_eintr's docstring more with some explanation for why it is not a complete solution.
2285
    directly controls, but it is not a complete solution.
5011.3.4 by Andrew Bennetts
Reinstate osutils.until_no_eintr and .send_all, reapply until_no_eintr in SmartSimplePipesClientMedium.read_bytes.
2286
    """
2287
    # Borrowed from Twisted's twisted.python.util.untilConcludes function.
2288
    while True:
2289
        try:
2290
            return f(*a, **kw)
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
2291
        except (IOError, OSError) as e:
5011.3.4 by Andrew Bennetts
Reinstate osutils.until_no_eintr and .send_all, reapply until_no_eintr in SmartSimplePipesClientMedium.read_bytes.
2292
            if e.errno == errno.EINTR:
2293
                continue
2294
            raise
2295
2296
0.16.79 by Aaron Bentley
Remove dependencies on bzrtools
2297
if sys.platform == "win32":
2298
    def getchar():
6379.1.1 by Jelmer Vernooij
Avoid importing tty and termios if we don't have to.
2299
        import msvcrt
0.16.79 by Aaron Bentley
Remove dependencies on bzrtools
2300
        return msvcrt.getch()
2301
else:
2302
    def getchar():
6379.1.1 by Jelmer Vernooij
Avoid importing tty and termios if we don't have to.
2303
        import tty
2304
        import termios
0.16.79 by Aaron Bentley
Remove dependencies on bzrtools
2305
        fd = sys.stdin.fileno()
2306
        settings = termios.tcgetattr(fd)
2307
        try:
2308
            tty.setraw(fd)
2309
            ch = sys.stdin.read(1)
2310
        finally:
2311
            termios.tcsetattr(fd, termios.TCSADRAIN, settings)
2312
        return ch
4398.4.3 by Vincent Ladeuil
Detect # cores on win32 and Solaris too.
2313
6057.1.1 by Martin Pool
Python can now report a platform of 'linux3' on kernel 3, but it's basically the same
2314
if sys.platform.startswith('linux'):
4398.4.3 by Vincent Ladeuil
Detect # cores on win32 and Solaris too.
2315
    def _local_concurrency():
5677.1.2 by Jelmer Vernooij
Use os.sysconf to get the number of CPUs on Linux. Use sysctl to get the number of CPUs on all *BSDs, not just FreeBSD.
2316
        try:
2317
            return os.sysconf('SC_NPROCESSORS_ONLN')
2318
        except (ValueError, OSError, AttributeError):
2319
            return None
4398.4.3 by Vincent Ladeuil
Detect # cores on win32 and Solaris too.
2320
elif sys.platform == 'darwin':
2321
    def _local_concurrency():
2322
        return subprocess.Popen(['sysctl', '-n', 'hw.availcpu'],
2323
                                stdout=subprocess.PIPE).communicate()[0]
5677.1.2 by Jelmer Vernooij
Use os.sysconf to get the number of CPUs on Linux. Use sysctl to get the number of CPUs on all *BSDs, not just FreeBSD.
2324
elif "bsd" in sys.platform:
4413.1.1 by Matthew Fuller
Catch the number of cores on FreeBSD too.
2325
    def _local_concurrency():
2326
        return subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
2327
                                stdout=subprocess.PIPE).communicate()[0]
4398.4.3 by Vincent Ladeuil
Detect # cores on win32 and Solaris too.
2328
elif sys.platform == 'sunos5':
2329
    def _local_concurrency():
2330
        return subprocess.Popen(['psrinfo', '-p',],
2331
                                stdout=subprocess.PIPE).communicate()[0]
2332
elif sys.platform == "win32":
2333
    def _local_concurrency():
4398.4.4 by Vincent Ladeuil
Fixed as per John's review.
2334
        # This appears to return the number of cores.
4398.4.3 by Vincent Ladeuil
Detect # cores on win32 and Solaris too.
2335
        return os.environ.get('NUMBER_OF_PROCESSORS')
2336
else:
2337
    def _local_concurrency():
2338
        # Who knows ?
2339
        return None
2340
2341
4398.4.4 by Vincent Ladeuil
Fixed as per John's review.
2342
_cached_local_concurrency = None
2343
2344
def local_concurrency(use_cache=True):
4398.4.3 by Vincent Ladeuil
Detect # cores on win32 and Solaris too.
2345
    """Return how many processes can be run concurrently.
2346
2347
    Rely on platform specific implementations and default to 1 (one) if
2348
    anything goes wrong.
2349
    """
4398.4.4 by Vincent Ladeuil
Fixed as per John's review.
2350
    global _cached_local_concurrency
4766.3.4 by Matt Nordhoff
Change the environment variable to a global option.
2351
4398.4.4 by Vincent Ladeuil
Fixed as per John's review.
2352
    if _cached_local_concurrency is not None and use_cache:
2353
        return _cached_local_concurrency
2354
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
2355
    concurrency = os.environ.get('BRZ_CONCURRENCY', None)
4766.3.7 by Vincent Ladeuil
Mix BZR_CONCURRENCY and --concurrency so both are available.
2356
    if concurrency is None:
2357
        try:
5677.1.3 by Jelmer Vernooij
Use try/import rather than checking python version strings.
2358
            import multiprocessing
6241.1.2 by Jelmer Vernooij
Simplify try/finally.
2359
            concurrency = multiprocessing.cpu_count()
2360
        except (ImportError, NotImplementedError):
5677.1.3 by Jelmer Vernooij
Use try/import rather than checking python version strings.
2361
            # multiprocessing is only available on Python >= 2.6
6241.1.2 by Jelmer Vernooij
Simplify try/finally.
2362
            # and multiprocessing.cpu_count() isn't implemented on all
2363
            # platforms
5677.1.3 by Jelmer Vernooij
Use try/import rather than checking python version strings.
2364
            try:
2365
                concurrency = _local_concurrency()
2366
            except (OSError, IOError):
2367
                pass
4398.4.3 by Vincent Ladeuil
Detect # cores on win32 and Solaris too.
2368
    try:
2369
        concurrency = int(concurrency)
2370
    except (TypeError, ValueError):
2371
        concurrency = 1
4398.4.4 by Vincent Ladeuil
Fixed as per John's review.
2372
    if use_cache:
2373
        _cached_concurrency = concurrency
4398.4.3 by Vincent Ladeuil
Detect # cores on win32 and Solaris too.
2374
    return concurrency
4794.1.12 by Robert Collins
Create a StreamWriter helper that doesn't trigger implicit decode('ascii') on write(a_str).
2375
2376
4794.1.15 by Robert Collins
Review feedback.
2377
class UnicodeOrBytesToBytesWriter(codecs.StreamWriter):
4794.1.12 by Robert Collins
Create a StreamWriter helper that doesn't trigger implicit decode('ascii') on write(a_str).
2378
    """A stream writer that doesn't decode str arguments."""
2379
4794.1.21 by Robert Collins
Python 2.4 doesn't use CodecInfo, so do a type check on the result of codecs.lookup.
2380
    def __init__(self, encode, stream, errors='strict'):
4794.1.12 by Robert Collins
Create a StreamWriter helper that doesn't trigger implicit decode('ascii') on write(a_str).
2381
        codecs.StreamWriter.__init__(self, stream, errors)
4794.1.21 by Robert Collins
Python 2.4 doesn't use CodecInfo, so do a type check on the result of codecs.lookup.
2382
        self.encode = encode
4794.1.12 by Robert Collins
Create a StreamWriter helper that doesn't trigger implicit decode('ascii') on write(a_str).
2383
2384
    def write(self, object):
6619.3.18 by Jelmer Vernooij
Run 2to3 idioms fixer.
2385
        if isinstance(object, str):
4794.1.12 by Robert Collins
Create a StreamWriter helper that doesn't trigger implicit decode('ascii') on write(a_str).
2386
            self.stream.write(object)
2387
        else:
2388
            data, _ = self.encode(object, self.errors)
2389
            self.stream.write(data)
4797.2.27 by Vincent Ladeuil
Merge 2.0 into 2.1 including fix for #524560
2390
4634.140.4 by INADA Naoki
Fix easy miss in previous commit.
2391
if sys.platform == 'win32':
4634.140.10 by INADA Naoki
Change name from osutils.open to osutils.open_file
2392
    def open_file(filename, mode='r', bufsize=-1):
4634.140.13 by Vincent Ladeuil
Fix some typos and add a NEWS entry.
2393
        """This function is used to override the ``open`` builtin.
5279.2.7 by Eric Moritz
1. deleted trailing whitespace
2394
4634.140.13 by Vincent Ladeuil
Fix some typos and add a NEWS entry.
2395
        But it uses O_NOINHERIT flag so the file handle is not inherited by
2396
        child processes.  Deleting or renaming a closed file opened with this
2397
        function is not blocking child processes.
4634.140.6 by INADA Naoki
Add comment to osutils.open()
2398
        """
4634.140.9 by INADA Naoki
Revert to previous implementation using os.fdopen(os.open())
2399
        writing = 'w' in mode
2400
        appending = 'a' in mode
2401
        updating = '+' in mode
2402
        binary = 'b' in mode
2403
4634.140.12 by INADA Naoki
small clean up.
2404
        flags = O_NOINHERIT
4634.140.9 by INADA Naoki
Revert to previous implementation using os.fdopen(os.open())
2405
        # see http://msdn.microsoft.com/en-us/library/yeby3zcb%28VS.71%29.aspx
2406
        # for flags for each modes.
2407
        if binary:
4634.140.12 by INADA Naoki
small clean up.
2408
            flags |= O_BINARY
4634.140.9 by INADA Naoki
Revert to previous implementation using os.fdopen(os.open())
2409
        else:
4634.140.12 by INADA Naoki
small clean up.
2410
            flags |= O_TEXT
4634.140.9 by INADA Naoki
Revert to previous implementation using os.fdopen(os.open())
2411
2412
        if writing:
2413
            if updating:
2414
                flags |= os.O_RDWR
2415
            else:
2416
                flags |= os.O_WRONLY
2417
            flags |= os.O_CREAT | os.O_TRUNC
2418
        elif appending:
2419
            if updating:
2420
                flags |= os.O_RDWR
2421
            else:
2422
                flags |= os.O_WRONLY
2423
            flags |= os.O_CREAT | os.O_APPEND
2424
        else: #reading
2425
            if updating:
2426
                flags |= os.O_RDWR
2427
            else:
2428
                flags |= os.O_RDONLY
2429
2430
        return os.fdopen(os.open(filename, flags), mode, bufsize)
4634.140.2 by INADA Naoki
Add osutils.open() that uses O_NOINHERIT on Win32.
2431
else:
4634.140.10 by INADA Naoki
Change name from osutils.open to osutils.open_file
2432
    open_file = open
5187.2.7 by Parth Malwankar
moved getuser_unicode to osutils.
2433
2434
5409.5.3 by Vincent Ladeuil
Implement osutils.available_backup_name.
2435
def available_backup_name(base, exists):
2436
    """Find a non-existing backup file name.
2437
5409.5.6 by Vincent Ladeuil
Add NEWS entry, tweak osutils.available_backup_name docstring.
2438
    This will *not* create anything, this only return a 'free' entry.  This
2439
    should be used for checking names in a directory below a locked
5409.5.8 by Vincent Ladeuil
Be more explicit about race conditions and LBYL being discouraged
2440
    tree/branch/repo to avoid race conditions. This is LBYL (Look Before You
2441
    Leap) and generally discouraged.
5409.5.3 by Vincent Ladeuil
Implement osutils.available_backup_name.
2442
2443
    :param base: The base name.
5409.5.8 by Vincent Ladeuil
Be more explicit about race conditions and LBYL being discouraged
2444
2445
    :param exists: A callable returning True if the path parameter exists.
5409.5.3 by Vincent Ladeuil
Implement osutils.available_backup_name.
2446
    """
2447
    counter = 1
2448
    name = "%s.~%d~" % (base, counter)
2449
    while exists(name):
2450
        counter += 1
5409.1.7 by Vincent Ladeuil
First orphaning implementation (some tests lacking).
2451
        name = "%s.~%d~" % (base, counter)
5409.5.3 by Vincent Ladeuil
Implement osutils.available_backup_name.
2452
    return name
5321.1.79 by Gordon Tyler
Added is_executable_on_path to osutils based on _probe from ExecutableFeature.
2453
2454
5582.6.1 by Max Bowsher
Fix socketpair-based SSH transport leaking socket into other child processes.
2455
def set_fd_cloexec(fd):
2456
    """Set a Unix file descriptor's FD_CLOEXEC flag.  Do nothing if platform
2457
    support for this is not available.
2458
    """
2459
    try:
2460
        import fcntl
2461
        old = fcntl.fcntl(fd, fcntl.F_GETFD)
2462
        fcntl.fcntl(fd, fcntl.F_SETFD, old | fcntl.FD_CLOEXEC)
2463
    except (ImportError, AttributeError):
2464
        # Either the fcntl module or specific constants are not present
2465
        pass
5321.1.114 by Gordon Tyler
Merged from bzr.dev.
2466
2467
5321.1.80 by Gordon Tyler
Changed is_executable_on_path to find_executable_on_path to make it more useful.
2468
def find_executable_on_path(name):
2469
    """Finds an executable on the PATH.
5321.1.79 by Gordon Tyler
Added is_executable_on_path to osutils based on _probe from ExecutableFeature.
2470
    
2471
    On Windows, this will try to append each extension in the PATHEXT
2472
    environment variable to the name, if it cannot be found with the name
2473
    as given.
2474
    
2475
    :param name: The base name of the executable.
5321.1.80 by Gordon Tyler
Changed is_executable_on_path to find_executable_on_path to make it more useful.
2476
    :return: The path to the executable found or None.
5321.1.79 by Gordon Tyler
Added is_executable_on_path to osutils based on _probe from ExecutableFeature.
2477
    """
5321.1.105 by Gordon Tyler
Fixed find_executable_on_path to only check PATHEXT on win32.
2478
    if sys.platform == 'win32':
2479
        exts = os.environ.get('PATHEXT', '').split(os.pathsep)
5321.1.106 by Gordon Tyler
Fixed find_executable_on_path to properly test for executable-ness on win32 and not split the PATH for each extension in PATHEXT.
2480
        exts = [ext.lower() for ext in exts]
2481
        base, ext = os.path.splitext(name)
2482
        if ext != '':
2483
            if ext.lower() not in exts:
2484
                return None
2485
            name = base
2486
            exts = [ext]
5321.1.105 by Gordon Tyler
Fixed find_executable_on_path to only check PATHEXT on win32.
2487
    else:
2488
        exts = ['']
6437.44.1 by Gordon Tyler
Backport of fix for bug 939605 to bzr 2.5 series.
2489
    path = os.environ.get('PATH')
2490
    if path is not None:
2491
        path = path.split(os.pathsep)
2492
        for ext in exts:
2493
            for d in path:
2494
                f = os.path.join(d, name) + ext
2495
                if os.access(f, os.X_OK):
2496
                    return f
2497
    if sys.platform == 'win32':
2498
        app_path = win32utils.get_app_path(name)
2499
        if app_path != name:
2500
            return app_path
5321.1.80 by Gordon Tyler
Changed is_executable_on_path to find_executable_on_path to make it more useful.
2501
    return None
5425.5.2 by Martin
Split pid deadness detection code out into osutils
2502
2503
2504
def _posix_is_local_pid_dead(pid):
5425.5.4 by Martin
Get docstring of _posix_is_local_pid_dead the right way round
2505
    """True if pid doesn't correspond to live process on this machine"""
5425.5.2 by Martin
Split pid deadness detection code out into osutils
2506
    try:
2507
        # Special meaning of unix kill: just check if it's there.
2508
        os.kill(pid, 0)
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
2509
    except OSError as e:
5425.5.2 by Martin
Split pid deadness detection code out into osutils
2510
        if e.errno == errno.ESRCH:
2511
            # On this machine, and really not found: as sure as we can be
2512
            # that it's dead.
2513
            return True
2514
        elif e.errno == errno.EPERM:
2515
            # exists, though not ours
2516
            return False
2517
        else:
5425.4.20 by Martin Pool
Suppress failures from os.kill when just using it to check for process liveness
2518
            mutter("os.kill(%d, 0) failed: %s" % (pid, e))
2519
            # Don't really know.
2520
            return False
5425.5.2 by Martin
Split pid deadness detection code out into osutils
2521
    else:
2522
        # Exists and our process: not dead.
2523
        return False
2524
5425.5.5 by Martin
Quick implementation of dead process detection on win32
2525
if sys.platform == "win32":
2526
    is_local_pid_dead = win32utils.is_local_pid_dead
2527
else:
2528
    is_local_pid_dead = _posix_is_local_pid_dead
6006.4.8 by Martin Pool
Use fsync when fdatasync is not available
2529
6015.60.4 by John Arbash Meinel
Found it called EOPNOTSUPP on a platform, include that spelling as well.
2530
_maybe_ignored = ['EAGAIN', 'EINTR', 'ENOTSUP', 'EOPNOTSUPP', 'EACCES']
2531
_fdatasync_ignored = [getattr(errno, name) for name in _maybe_ignored
6015.60.3 by John Arbash Meinel
only squelch known errors per vila.
2532
                      if getattr(errno, name, None) is not None]
6006.4.8 by Martin Pool
Use fsync when fdatasync is not available
2533
6015.60.4 by John Arbash Meinel
Found it called EOPNOTSUPP on a platform, include that spelling as well.
2534
6006.4.8 by Martin Pool
Use fsync when fdatasync is not available
2535
def fdatasync(fileno):
2536
    """Flush file contents to disk if possible.
2537
    
2538
    :param fileno: Integer OS file handle.
2539
    :raises TransportNotPossible: If flushing to disk is not possible.
2540
    """
2541
    fn = getattr(os, 'fdatasync', getattr(os, 'fsync', None))
2542
    if fn is not None:
6015.60.2 by John Arbash Meinel
Fix bug #1075108.
2543
        try:
2544
            fn(fileno)
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
2545
        except IOError as e:
6015.60.2 by John Arbash Meinel
Fix bug #1075108.
2546
            # See bug #1075108, on some platforms fdatasync exists, but can
2547
            # raise ENOTSUP. However, we are calling fdatasync to be helpful
2548
            # and reduce the chance of corruption-on-powerloss situations. It
2549
            # is not a mandatory call, so it is ok to suppress failures.
2550
            trace.mutter("ignoring error calling fdatasync: %s" % (e,))
6015.60.3 by John Arbash Meinel
only squelch known errors per vila.
2551
            if getattr(e, 'errno', None) not in _fdatasync_ignored:
2552
                raise
6336.2.1 by Martin Packman
Add is_environment_error() and switch trace to using it
2553
2554
6015.51.1 by Martin Pool
Tolerate empty limbo and pending-deletion directories
2555
def ensure_empty_directory_exists(path, exception_class):
2556
    """Make sure a local directory exists and is empty.
2557
    
2558
    If it does not exist, it is created.  If it exists and is not empty, an
2559
    instance of exception_class is raised.
2560
    """
2561
    try:
2562
        os.mkdir(path)
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
2563
    except OSError as e:
6015.51.1 by Martin Pool
Tolerate empty limbo and pending-deletion directories
2564
        if e.errno != errno.EEXIST:
2565
            raise
2566
        if os.listdir(path) != []:
2567
            raise exception_class(path)
6344.1.1 by Martin Packman
Merge 2.4 into bzr.dev
2568
2569
6336.2.1 by Martin Packman
Add is_environment_error() and switch trace to using it
2570
def is_environment_error(evalue):
2571
    """True if exception instance is due to a process environment issue
2572
2573
    This includes OSError and IOError, but also other errors that come from
2574
    the operating system or core libraries but are not subclasses of those.
2575
    """
2576
    if isinstance(evalue, (EnvironmentError, select.error)):
2577
        return True
2578
    if sys.platform == "win32" and win32utils._is_pywintypes_error(evalue):
2579
        return True
2580
    return False