/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: Colin D Bennett
  • Date: 2009-02-12 16:57:39 UTC
  • mto: This revision was merged to the branch mainline in revision 4008.
  • Revision ID: colin@gibibit.com-20090212165739-02xv63odccfmxomw
Generate PDF version of the User Guide.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
 
 
17
 
from __future__ import absolute_import
18
 
 
19
 
import errno
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
20
17
import os
21
18
import re
22
19
import stat
 
20
from stat import (S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE,
 
21
                  S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
23
22
import sys
24
23
import time
 
24
 
 
25
from bzrlib.lazy_import import lazy_import
 
26
lazy_import(globals(), """
25
27
import codecs
26
 
 
27
 
from .lazy_import import lazy_import
28
 
lazy_import(globals(), """
29
28
from datetime import datetime
30
 
import getpass
31
 
import locale
32
 
import ntpath
 
29
import errno
 
30
from ntpath import (abspath as _nt_abspath,
 
31
                    join as _nt_join,
 
32
                    normpath as _nt_normpath,
 
33
                    realpath as _nt_realpath,
 
34
                    splitdrive as _nt_splitdrive,
 
35
                    )
33
36
import posixpath
34
 
import select
35
 
# We need to import both shutil and rmtree as we export the later on posix
36
 
# and need the former on windows
37
37
import shutil
38
 
from shutil import rmtree
39
 
import socket
40
 
import subprocess
41
 
# We need to import both tempfile and mkdtemp as we export the later on posix
42
 
# and need the former on windows
 
38
from shutil import (
 
39
    rmtree,
 
40
    )
43
41
import tempfile
44
 
from tempfile import mkdtemp
 
42
from tempfile import (
 
43
    mkdtemp,
 
44
    )
45
45
import unicodedata
46
46
 
47
 
from breezy import (
48
 
    config,
49
 
    trace,
 
47
from bzrlib import (
 
48
    cache_utf8,
 
49
    errors,
50
50
    win32utils,
51
51
    )
52
 
from breezy.i18n import gettext
53
52
""")
54
53
 
55
 
from .sixish import (
56
 
    PY3,
57
 
    text_type,
58
 
    )
59
 
 
60
 
from hashlib import (
61
 
    md5,
62
 
    sha1 as sha,
63
 
    )
64
 
 
65
 
 
66
 
import breezy
67
 
from . import (
68
 
    _fs_enc,
69
 
    errors,
70
 
    )
71
 
 
72
 
 
73
 
# Cross platform wall-clock time functionality with decent resolution.
74
 
# On Linux ``time.clock`` returns only CPU time. On Windows, ``time.time()``
75
 
# only has a resolution of ~15ms. Note that ``time.clock()`` is not
76
 
# synchronized with ``time.time()``, this is only meant to be used to find
77
 
# delta times by subtracting from another call to this function.
78
 
timer_func = time.time
79
 
if sys.platform == 'win32':
80
 
    timer_func = time.clock
 
54
# sha and md5 modules are deprecated in python2.6 but hashlib is available as
 
55
# of 2.5
 
56
if sys.version_info < (2, 5):
 
57
    import md5 as _mod_md5
 
58
    md5 = _mod_md5.new
 
59
    import sha as _mod_sha
 
60
    sha = _mod_sha.new
 
61
else:
 
62
    from hashlib import (
 
63
        md5,
 
64
        sha1 as sha,
 
65
        )
 
66
 
 
67
 
 
68
import bzrlib
 
69
from bzrlib import symbol_versioning
 
70
 
81
71
 
82
72
# On win32, O_BINARY is used to indicate the file should
83
73
# be opened in binary mode, rather than text mode.
84
74
# On other platforms, O_BINARY doesn't exist, because
85
75
# they always open in binary mode, so it is okay to
86
 
# OR with 0 on those platforms.
87
 
# O_NOINHERIT and O_TEXT exists only on win32 too.
 
76
# OR with 0 on those platforms
88
77
O_BINARY = getattr(os, 'O_BINARY', 0)
89
 
O_TEXT = getattr(os, 'O_TEXT', 0)
90
 
O_NOINHERIT = getattr(os, 'O_NOINHERIT', 0)
91
 
 
92
 
 
93
 
class UnsupportedTimezoneFormat(errors.BzrError):
94
 
 
95
 
    _fmt = ('Unsupported timezone format "%(timezone)s", '
96
 
            'options are "utc", "original", "local".')
97
 
 
98
 
    def __init__(self, timezone):
99
 
        self.timezone = timezone
100
 
 
101
 
 
102
 
def get_unicode_argv():
103
 
    if PY3:
104
 
        return sys.argv[1:]
105
 
    try:
106
 
        user_encoding = get_user_encoding()
107
 
        return [a.decode(user_encoding) for a in sys.argv[1:]]
108
 
    except UnicodeDecodeError:
109
 
        raise errors.BzrError(gettext("Parameter {0!r} encoding is unsupported by {1} "
110
 
                                      "application locale.").format(a, user_encoding))
111
78
 
112
79
 
113
80
def make_readonly(filename):
114
81
    """Make a filename read-only."""
115
82
    mod = os.lstat(filename).st_mode
116
83
    if not stat.S_ISLNK(mod):
117
 
        mod = mod & 0o777555
118
 
        chmod_if_possible(filename, mod)
 
84
        mod = mod & 0777555
 
85
        os.chmod(filename, mod)
119
86
 
120
87
 
121
88
def make_writable(filename):
122
89
    mod = os.lstat(filename).st_mode
123
90
    if not stat.S_ISLNK(mod):
124
 
        mod = mod | 0o200
125
 
        chmod_if_possible(filename, mod)
126
 
 
127
 
 
128
 
def chmod_if_possible(filename, mode):
129
 
    # Set file mode if that can be safely done.
130
 
    # Sometimes even on unix the filesystem won't allow it - see
131
 
    # https://bugs.launchpad.net/bzr/+bug/606537
132
 
    try:
133
 
        # It is probably faster to just do the chmod, rather than
134
 
        # doing a stat, and then trying to compare
135
 
        os.chmod(filename, mode)
136
 
    except (IOError, OSError) as e:
137
 
        # Permission/access denied seems to commonly happen on smbfs; there's
138
 
        # probably no point warning about it.
139
 
        # <https://bugs.launchpad.net/bzr/+bug/606537>
140
 
        if getattr(e, 'errno') in (errno.EPERM, errno.EACCES):
141
 
            trace.mutter("ignore error on chmod of %r: %r" % (
142
 
                filename, e))
143
 
            return
144
 
        raise
 
91
        mod = mod | 0200
 
92
        os.chmod(filename, mod)
145
93
 
146
94
 
147
95
def minimum_path_selection(paths):
149
97
 
150
98
    :param paths: A container (and hence not None) of paths.
151
99
    :return: A set of paths sufficient to include everything in paths via
152
 
        is_inside, drawn from the paths parameter.
 
100
        is_inside_any, drawn from the paths parameter.
153
101
    """
154
 
    if len(paths) < 2:
155
 
        return set(paths)
156
 
 
157
 
    def sort_key(path):
158
 
        if isinstance(path, bytes):
159
 
            return path.split(b'/')
160
 
        else:
161
 
            return path.split('/')
162
 
    sorted_paths = sorted(list(paths), key=sort_key)
163
 
 
164
 
    search_paths = [sorted_paths[0]]
165
 
    for path in sorted_paths[1:]:
166
 
        if not is_inside(search_paths[-1], path):
167
 
            # This path is unique, add it
168
 
            search_paths.append(path)
169
 
 
170
 
    return set(search_paths)
 
102
    search_paths = set()
 
103
    paths = set(paths)
 
104
    for path in paths:
 
105
        other_paths = paths.difference([path])
 
106
        if not is_inside_any(other_paths, path):
 
107
            # this is a top level path, we must check it.
 
108
            search_paths.add(path)
 
109
    return search_paths
171
110
 
172
111
 
173
112
_QUOTE_RE = None
182
121
    global _QUOTE_RE
183
122
    if _QUOTE_RE is None:
184
123
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
185
 
 
 
124
        
186
125
    if _QUOTE_RE.search(f):
187
126
        return '"' + f + '"'
188
127
    else:
191
130
 
192
131
_directory_kind = 'directory'
193
132
 
194
 
 
195
133
def get_umask():
196
134
    """Return the current umask"""
197
135
    # Assume that people aren't messing with the umask while running
214
152
    try:
215
153
        return _kind_marker_map[kind]
216
154
    except KeyError:
217
 
        # Slightly faster than using .get(, '') when the common case is that
218
 
        # kind will be found
219
 
        return ''
 
155
        raise errors.BzrError('invalid file kind %r' % kind)
220
156
 
221
157
 
222
158
lexists = getattr(os.path, 'lexists', None)
226
162
            stat = getattr(os, 'lstat', os.stat)
227
163
            stat(f)
228
164
            return True
229
 
        except OSError as e:
 
165
        except OSError, e:
230
166
            if e.errno == errno.ENOENT:
231
 
                return False
 
167
                return False;
232
168
            else:
233
 
                raise errors.BzrError(
234
 
                    gettext("lstat/stat of ({0!r}): {1!r}").format(f, e))
 
169
                raise errors.BzrError("lstat/stat of (%r): %r" % (f, e))
235
170
 
236
171
 
237
172
def fancy_rename(old, new, rename_func, unlink_func):
238
173
    """A fancy rename, when you don't have atomic rename.
239
 
 
 
174
    
240
175
    :param old: The old path, to rename from
241
176
    :param new: The new path, to rename to
242
177
    :param rename_func: The potentially non-atomic rename function
243
 
    :param unlink_func: A way to delete the target file if the full rename
244
 
        succeeds
 
178
    :param unlink_func: A way to delete the target file if the full rename succeeds
245
179
    """
 
180
 
246
181
    # sftp rename doesn't allow overwriting, so play tricks:
247
182
    base = os.path.basename(new)
248
183
    dirname = os.path.dirname(new)
249
 
    # callers use different encodings for the paths so the following MUST
250
 
    # respect that. We rely on python upcasting to unicode if new is unicode
251
 
    # and keeping a str if not.
252
 
    tmp_name = 'tmp.%s.%.9f.%d.%s' % (base, time.time(),
253
 
                                      os.getpid(), rand_chars(10))
 
184
    tmp_name = u'tmp.%s.%.9f.%d.%s' % (base, time.time(), os.getpid(), rand_chars(10))
254
185
    tmp_name = pathjoin(dirname, tmp_name)
255
186
 
256
187
    # Rename the file out of the way, but keep track if it didn't exist
261
192
    file_existed = False
262
193
    try:
263
194
        rename_func(new, tmp_name)
264
 
    except (errors.NoSuchFile,):
 
195
    except (errors.NoSuchFile,), e:
265
196
        pass
266
 
    except IOError as e:
 
197
    except IOError, e:
267
198
        # RBC 20060103 abstraction leakage: the paramiko SFTP clients rename
268
199
        # function raises an IOError with errno is None when a rename fails.
269
200
        # This then gets caught here.
270
201
        if e.errno not in (None, errno.ENOENT, errno.ENOTDIR):
271
202
            raise
272
 
    except Exception as e:
 
203
    except Exception, e:
273
204
        if (getattr(e, 'errno', None) is None
274
 
                or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
 
205
            or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
275
206
            raise
276
207
    else:
277
208
        file_existed = True
278
209
 
279
210
    success = False
280
211
    try:
281
 
        # This may throw an exception, in which case success will
282
 
        # not be set.
283
 
        rename_func(old, new)
284
 
        success = True
285
 
    except (IOError, OSError) as e:
286
 
        # source and target may be aliases of each other (e.g. on a
287
 
        # case-insensitive filesystem), so we may have accidentally renamed
288
 
        # source by when we tried to rename target
289
 
        if (file_existed and e.errno in (None, errno.ENOENT)
290
 
                and old.lower() == new.lower()):
291
 
            # source and target are the same file on a case-insensitive
292
 
            # filesystem, so we don't generate an exception
293
 
            pass
294
 
        else:
295
 
            raise
 
212
        try:
 
213
            # This may throw an exception, in which case success will
 
214
            # not be set.
 
215
            rename_func(old, new)
 
216
            success = True
 
217
        except (IOError, OSError), e:
 
218
            # source and target may be aliases of each other (e.g. on a
 
219
            # case-insensitive filesystem), so we may have accidentally renamed
 
220
            # source by when we tried to rename target
 
221
            if not (file_existed and e.errno in (None, errno.ENOENT)):
 
222
                raise
296
223
    finally:
297
224
        if file_existed:
298
225
            # If the file used to exist, rename it back into place
307
234
# choke on a Unicode string containing a relative path if
308
235
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
309
236
# string.
 
237
_fs_enc = sys.getfilesystemencoding() or 'utf-8'
310
238
def _posix_abspath(path):
311
239
    # jam 20060426 rather than encoding to fsencoding
312
240
    # copy posixpath.abspath, but use os.getcwdu instead
313
241
    if not posixpath.isabs(path):
314
242
        path = posixpath.join(getcwd(), path)
315
 
    return _posix_normpath(path)
 
243
    return posixpath.normpath(path)
316
244
 
317
245
 
318
246
def _posix_realpath(path):
319
247
    return posixpath.realpath(path.encode(_fs_enc)).decode(_fs_enc)
320
248
 
321
249
 
322
 
def _posix_normpath(path):
323
 
    path = posixpath.normpath(path)
324
 
    # Bug 861008: posixpath.normpath() returns a path normalized according to
325
 
    # the POSIX standard, which stipulates (for compatibility reasons) that two
326
 
    # leading slashes must not be simplified to one, and only if there are 3 or
327
 
    # more should they be simplified as one. So we treat the leading 2 slashes
328
 
    # as a special case here by simply removing the first slash, as we consider
329
 
    # that breaking POSIX compatibility for this obscure feature is acceptable.
330
 
    # This is not a paranoid precaution, as we notably get paths like this when
331
 
    # the repo is hosted at the root of the filesystem, i.e. in "/".
332
 
    if path.startswith('//'):
333
 
        path = path[1:]
334
 
    return path
335
 
 
336
 
 
337
 
def _posix_path_from_environ(key):
338
 
    """Get unicode path from `key` in environment or None if not present
339
 
 
340
 
    Note that posix systems use arbitrary byte strings for filesystem objects,
341
 
    so a path that raises BadFilenameEncoding here may still be accessible.
342
 
    """
343
 
    val = os.environ.get(key, None)
344
 
    if PY3 or val is None:
345
 
        return val
346
 
    try:
347
 
        return val.decode(_fs_enc)
348
 
    except UnicodeDecodeError:
349
 
        # GZ 2011-12-12:Ideally want to include `key` in the exception message
350
 
        raise errors.BadFilenameEncoding(val, _fs_enc)
351
 
 
352
 
 
353
 
def _posix_get_home_dir():
354
 
    """Get the home directory of the current user as a unicode path"""
355
 
    path = posixpath.expanduser("~")
356
 
    try:
357
 
        return path.decode(_fs_enc)
358
 
    except AttributeError:
359
 
        return path
360
 
    except UnicodeDecodeError:
361
 
        raise errors.BadFilenameEncoding(path, _fs_enc)
362
 
 
363
 
 
364
 
def _posix_getuser_unicode():
365
 
    """Get username from environment or password database as unicode"""
366
 
    name = getpass.getuser()
367
 
    if PY3:
368
 
        return name
369
 
    user_encoding = get_user_encoding()
370
 
    try:
371
 
        return name.decode(user_encoding)
372
 
    except UnicodeDecodeError:
373
 
        raise errors.BzrError("Encoding of username %r is unsupported by %s "
374
 
                              "application locale." % (name, user_encoding))
375
 
 
376
 
 
377
250
def _win32_fixdrive(path):
378
251
    """Force drive letters to be consistent.
379
252
 
383
256
    running python.exe under cmd.exe return capital C:\\
384
257
    running win32 python inside a cygwin shell returns lowercase c:\\
385
258
    """
386
 
    drive, path = ntpath.splitdrive(path)
 
259
    drive, path = _nt_splitdrive(path)
387
260
    return drive.upper() + path
388
261
 
389
262
 
390
263
def _win32_abspath(path):
391
 
    # Real ntpath.abspath doesn't have a problem with a unicode cwd
392
 
    return _win32_fixdrive(ntpath.abspath(path).replace('\\', '/'))
 
264
    # Real _nt_abspath doesn't have a problem with a unicode cwd
 
265
    return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
 
266
 
 
267
 
 
268
def _win98_abspath(path):
 
269
    """Return the absolute version of a path.
 
270
    Windows 98 safe implementation (python reimplementation
 
271
    of Win32 API function GetFullPathNameW)
 
272
    """
 
273
    # Corner cases:
 
274
    #   C:\path     => C:/path
 
275
    #   C:/path     => C:/path
 
276
    #   \\HOST\path => //HOST/path
 
277
    #   //HOST/path => //HOST/path
 
278
    #   path        => C:/cwd/path
 
279
    #   /path       => C:/path
 
280
    path = unicode(path)
 
281
    # check for absolute path
 
282
    drive = _nt_splitdrive(path)[0]
 
283
    if drive == '' and path[:2] not in('//','\\\\'):
 
284
        cwd = os.getcwdu()
 
285
        # we cannot simply os.path.join cwd and path
 
286
        # because os.path.join('C:','/path') produce '/path'
 
287
        # and this is incorrect
 
288
        if path[:1] in ('/','\\'):
 
289
            cwd = _nt_splitdrive(cwd)[0]
 
290
            path = path[1:]
 
291
        path = cwd + '\\' + path
 
292
    return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
393
293
 
394
294
 
395
295
def _win32_realpath(path):
396
 
    # Real ntpath.realpath doesn't have a problem with a unicode cwd
397
 
    return _win32_fixdrive(ntpath.realpath(path).replace('\\', '/'))
 
296
    # Real _nt_realpath doesn't have a problem with a unicode cwd
 
297
    return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
398
298
 
399
299
 
400
300
def _win32_pathjoin(*args):
401
 
    return ntpath.join(*args).replace('\\', '/')
 
301
    return _nt_join(*args).replace('\\', '/')
402
302
 
403
303
 
404
304
def _win32_normpath(path):
405
 
    return _win32_fixdrive(ntpath.normpath(path).replace('\\', '/'))
 
305
    return _win32_fixdrive(_nt_normpath(unicode(path)).replace('\\', '/'))
406
306
 
407
307
 
408
308
def _win32_getcwd():
409
 
    return _win32_fixdrive(_getcwd().replace('\\', '/'))
 
309
    return _win32_fixdrive(os.getcwdu().replace('\\', '/'))
410
310
 
411
311
 
412
312
def _win32_mkdtemp(*args, **kwargs):
417
317
    """We expect to be able to atomically replace 'new' with old.
418
318
 
419
319
    On win32, if new exists, it must be moved out of the way first,
420
 
    and then deleted.
 
320
    and then deleted. 
421
321
    """
422
322
    try:
423
323
        fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
424
 
    except OSError as e:
 
324
    except OSError, e:
425
325
        if e.errno in (errno.EPERM, errno.EACCES, errno.EBUSY, errno.EINVAL):
426
 
            # If we try to rename a non-existant file onto cwd, we get
427
 
            # EPERM or EACCES instead of ENOENT, this will raise ENOENT
 
326
            # If we try to rename a non-existant file onto cwd, we get 
 
327
            # EPERM or EACCES instead of ENOENT, this will raise ENOENT 
428
328
            # if the old path doesn't exist, sometimes we get EACCES
429
329
            # On Linux, we seem to get EBUSY, on Mac we get EINVAL
430
330
            os.lstat(old)
432
332
 
433
333
 
434
334
def _mac_getcwd():
435
 
    return unicodedata.normalize('NFC', _getcwd())
436
 
 
437
 
 
438
 
def _rename_wrap_exception(rename_func):
439
 
    """Adds extra information to any exceptions that come from rename().
440
 
 
441
 
    The exception has an updated message and 'old_filename' and 'new_filename'
442
 
    attributes.
443
 
    """
444
 
 
445
 
    def _rename_wrapper(old, new):
446
 
        try:
447
 
            rename_func(old, new)
448
 
        except OSError as e:
449
 
            detailed_error = OSError(e.errno, e.strerror +
450
 
                                     " [occurred when renaming '%s' to '%s']" %
451
 
                                     (old, new))
452
 
            detailed_error.old_filename = old
453
 
            detailed_error.new_filename = new
454
 
            raise detailed_error
455
 
 
456
 
    return _rename_wrapper
457
 
 
458
 
 
459
 
if sys.version_info > (3,):
460
 
    _getcwd = os.getcwd
461
 
else:
462
 
    _getcwd = os.getcwdu
463
 
 
464
 
 
465
 
# Default rename wraps os.rename()
466
 
rename = _rename_wrap_exception(os.rename)
 
335
    return unicodedata.normalize('NFC', os.getcwdu())
 
336
 
467
337
 
468
338
# Default is to just use the python builtins, but these can be rebound on
469
339
# particular platforms.
470
340
abspath = _posix_abspath
471
341
realpath = _posix_realpath
472
342
pathjoin = os.path.join
473
 
normpath = _posix_normpath
474
 
path_from_environ = _posix_path_from_environ
475
 
_get_home_dir = _posix_get_home_dir
476
 
getuser_unicode = _posix_getuser_unicode
477
 
getcwd = _getcwd
 
343
normpath = os.path.normpath
 
344
getcwd = os.getcwdu
 
345
rename = os.rename
478
346
dirname = os.path.dirname
479
347
basename = os.path.basename
480
348
split = os.path.split
481
349
splitext = os.path.splitext
482
 
# These were already lazily imported into local scope
 
350
# These were already imported into local scope
483
351
# mkdtemp = tempfile.mkdtemp
484
352
# rmtree = shutil.rmtree
485
 
lstat = os.lstat
486
 
fstat = os.fstat
487
 
 
488
 
 
489
 
def wrap_stat(st):
490
 
    return st
491
 
 
492
353
 
493
354
MIN_ABS_PATHLENGTH = 1
494
355
 
495
356
 
496
357
if sys.platform == 'win32':
497
 
    abspath = _win32_abspath
 
358
    if win32utils.winver == 'Windows 98':
 
359
        abspath = _win98_abspath
 
360
    else:
 
361
        abspath = _win32_abspath
498
362
    realpath = _win32_realpath
499
363
    pathjoin = _win32_pathjoin
500
364
    normpath = _win32_normpath
501
365
    getcwd = _win32_getcwd
502
366
    mkdtemp = _win32_mkdtemp
503
 
    rename = _rename_wrap_exception(_win32_rename)
504
 
    try:
505
 
        from . import _walkdirs_win32
506
 
    except ImportError:
507
 
        pass
508
 
    else:
509
 
        lstat = _walkdirs_win32.lstat
510
 
        fstat = _walkdirs_win32.fstat
511
 
        wrap_stat = _walkdirs_win32.wrap_stat
 
367
    rename = _win32_rename
512
368
 
513
369
    MIN_ABS_PATHLENGTH = 3
514
370
 
518
374
        """
519
375
        exception = excinfo[1]
520
376
        if function in (os.remove, os.rmdir) \
521
 
                and isinstance(exception, OSError) \
522
 
                and exception.errno == errno.EACCES:
 
377
            and isinstance(exception, OSError) \
 
378
            and exception.errno == errno.EACCES:
523
379
            make_writable(path)
524
380
            function(path)
525
381
        else:
528
384
    def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
529
385
        """Replacer for shutil.rmtree: could remove readonly dirs/files"""
530
386
        return shutil.rmtree(path, ignore_errors, onerror)
531
 
 
532
 
    f = win32utils.get_unicode_argv     # special function or None
533
 
    if f is not None:
534
 
        get_unicode_argv = f
535
 
    path_from_environ = win32utils.get_environ_unicode
536
 
    _get_home_dir = win32utils.get_home_location
537
 
    getuser_unicode = win32utils.get_user_name
538
 
 
539
387
elif sys.platform == 'darwin':
540
388
    getcwd = _mac_getcwd
541
389
 
542
390
 
543
 
def get_terminal_encoding(trace=False):
 
391
def get_terminal_encoding():
544
392
    """Find the best encoding for printing to the screen.
545
393
 
546
394
    This attempts to check both sys.stdout and sys.stdin to see
552
400
 
553
401
    On my standard US Windows XP, the preferred encoding is
554
402
    cp1252, but the console is cp437
555
 
 
556
 
    :param trace: If True trace the selected encoding via mutter().
557
403
    """
558
 
    from .trace import mutter
 
404
    from bzrlib.trace import mutter
559
405
    output_encoding = getattr(sys.stdout, 'encoding', None)
560
406
    if not output_encoding:
561
407
        input_encoding = getattr(sys.stdin, 'encoding', None)
562
408
        if not input_encoding:
563
409
            output_encoding = get_user_encoding()
564
 
            if trace:
565
 
                mutter('encoding stdout as osutils.get_user_encoding() %r',
566
 
                       output_encoding)
 
410
            mutter('encoding stdout as osutils.get_user_encoding() %r',
 
411
                   output_encoding)
567
412
        else:
568
413
            output_encoding = input_encoding
569
 
            if trace:
570
 
                mutter('encoding stdout as sys.stdin encoding %r',
571
 
                       output_encoding)
 
414
            mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
572
415
    else:
573
 
        if trace:
574
 
            mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
 
416
        mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
575
417
    if output_encoding == 'cp0':
576
418
        # invalid encoding (cp0 means 'no codepage' on Windows)
577
419
        output_encoding = get_user_encoding()
578
 
        if trace:
579
 
            mutter('cp0 is invalid encoding.'
580
 
                   ' encoding stdout as osutils.get_user_encoding() %r',
581
 
                   output_encoding)
 
420
        mutter('cp0 is invalid encoding.'
 
421
               ' encoding stdout as osutils.get_user_encoding() %r',
 
422
               output_encoding)
582
423
    # check encoding
583
424
    try:
584
425
        codecs.lookup(output_encoding)
585
426
    except LookupError:
586
 
        sys.stderr.write('brz: warning:'
 
427
        sys.stderr.write('bzr: warning:'
587
428
                         ' unknown terminal encoding %s.\n'
588
429
                         '  Using encoding %s instead.\n'
589
430
                         % (output_encoding, get_user_encoding())
590
 
                         )
 
431
                        )
591
432
        output_encoding = get_user_encoding()
592
433
 
593
434
    return output_encoding
598
439
        F = realpath
599
440
    else:
600
441
        F = abspath
601
 
    [p, e] = os.path.split(f)
 
442
    [p,e] = os.path.split(f)
602
443
    if e == "" or e == "." or e == "..":
603
444
        return F(f)
604
445
    else:
608
449
def isdir(f):
609
450
    """True if f is an accessible directory."""
610
451
    try:
611
 
        return stat.S_ISDIR(os.lstat(f)[stat.ST_MODE])
 
452
        return S_ISDIR(os.lstat(f)[ST_MODE])
612
453
    except OSError:
613
454
        return False
614
455
 
616
457
def isfile(f):
617
458
    """True if f is a regular file."""
618
459
    try:
619
 
        return stat.S_ISREG(os.lstat(f)[stat.ST_MODE])
 
460
        return S_ISREG(os.lstat(f)[ST_MODE])
620
461
    except OSError:
621
462
        return False
622
463
 
623
 
 
624
464
def islink(f):
625
465
    """True if f is a symlink."""
626
466
    try:
627
 
        return stat.S_ISLNK(os.lstat(f)[stat.ST_MODE])
 
467
        return S_ISLNK(os.lstat(f)[ST_MODE])
628
468
    except OSError:
629
469
        return False
630
470
 
631
 
 
632
471
def is_inside(dir, fname):
633
472
    """True if fname is inside dir.
634
 
 
 
473
    
635
474
    The parameters should typically be passed to osutils.normpath first, so
636
475
    that . and .. and repeated slashes are eliminated, and the separators
637
476
    are canonical for the platform.
638
 
 
639
 
    The empty string as a dir name is taken as top-of-tree and matches
 
477
    
 
478
    The empty string as a dir name is taken as top-of-tree and matches 
640
479
    everything.
641
480
    """
642
 
    # XXX: Most callers of this can actually do something smarter by
 
481
    # XXX: Most callers of this can actually do something smarter by 
643
482
    # looking at the inventory
644
483
    if dir == fname:
645
484
        return True
646
 
 
647
 
    if dir in ('', b''):
 
485
    
 
486
    if dir == '':
648
487
        return True
649
488
 
650
 
    if isinstance(dir, bytes):
651
 
        if not dir.endswith(b'/'):
652
 
            dir += b'/'
653
 
    else:
654
 
        if not dir.endswith('/'):
655
 
            dir += '/'
 
489
    if dir[-1] != '/':
 
490
        dir += '/'
656
491
 
657
492
    return fname.startswith(dir)
658
493
 
731
566
    # writes fail on some platforms (e.g. Windows with SMB  mounted
732
567
    # drives).
733
568
    if not segment_size:
734
 
        segment_size = 5242880  # 5MB
735
 
    offsets = range(0, len(bytes), segment_size)
736
 
    view = memoryview(bytes)
 
569
        segment_size = 5242880 # 5MB
 
570
    segments = range(len(bytes) / segment_size + 1)
737
571
    write = file_handle.write
738
 
    for offset in offsets:
739
 
        write(view[offset:offset + segment_size])
 
572
    for segment_index in segments:
 
573
        segment = buffer(bytes, segment_index * segment_size, segment_size)
 
574
        write(segment)
740
575
 
741
576
 
742
577
def file_iterator(input_file, readsize=32768):
747
582
        yield b
748
583
 
749
584
 
750
 
# GZ 2017-09-16: Makes sense in general for hexdigest() result to be text, but
751
 
# used as bytes through most interfaces so encode with this wrapper.
752
 
if PY3:
753
 
    def _hexdigest(hashobj):
754
 
        return hashobj.hexdigest().encode()
755
 
else:
756
 
    def _hexdigest(hashobj):
757
 
        return hashobj.hexdigest()
758
 
 
759
 
 
760
585
def sha_file(f):
761
586
    """Calculate the hexdigest of an open file.
762
587
 
763
588
    The file cursor should be already at the start.
764
589
    """
765
590
    s = sha()
766
 
    BUFSIZE = 128 << 10
767
 
    while True:
768
 
        b = f.read(BUFSIZE)
769
 
        if not b:
770
 
            break
771
 
        s.update(b)
772
 
    return _hexdigest(s)
773
 
 
774
 
 
775
 
def size_sha_file(f):
776
 
    """Calculate the size and hexdigest of an open file.
777
 
 
778
 
    The file cursor should be already at the start and
779
 
    the caller is responsible for closing the file afterwards.
780
 
    """
781
 
    size = 0
782
 
    s = sha()
783
 
    BUFSIZE = 128 << 10
784
 
    while True:
785
 
        b = f.read(BUFSIZE)
786
 
        if not b:
787
 
            break
788
 
        size += len(b)
789
 
        s.update(b)
790
 
    return size, _hexdigest(s)
 
591
    BUFSIZE = 128<<10
 
592
    while True:
 
593
        b = f.read(BUFSIZE)
 
594
        if not b:
 
595
            break
 
596
        s.update(b)
 
597
    return s.hexdigest()
791
598
 
792
599
 
793
600
def sha_file_by_name(fname):
794
601
    """Calculate the SHA1 of a file by reading the full text"""
795
602
    s = sha()
796
 
    f = os.open(fname, os.O_RDONLY | O_BINARY | O_NOINHERIT)
 
603
    f = os.open(fname, os.O_RDONLY | O_BINARY)
797
604
    try:
798
605
        while True:
799
 
            b = os.read(f, 1 << 16)
 
606
            b = os.read(f, 1<<16)
800
607
            if not b:
801
 
                return _hexdigest(s)
 
608
                return s.hexdigest()
802
609
            s.update(b)
803
610
    finally:
804
611
        os.close(f)
807
614
def sha_strings(strings, _factory=sha):
808
615
    """Return the sha-1 of concatenation of strings"""
809
616
    s = _factory()
810
 
    for string in strings:
811
 
        s.update(string)
812
 
    return _hexdigest(s)
 
617
    map(s.update, strings)
 
618
    return s.hexdigest()
813
619
 
814
620
 
815
621
def sha_string(f, _factory=sha):
816
 
    # GZ 2017-09-16: Dodgy if factory is ever not sha, probably shouldn't be.
817
 
    return _hexdigest(_factory(f))
 
622
    return _factory(f).hexdigest()
818
623
 
819
624
 
820
625
def fingerprint_file(f):
821
626
    b = f.read()
822
627
    return {'size': len(b),
823
 
            'sha1': _hexdigest(sha(b))}
 
628
            'sha1': sha(b).hexdigest()}
824
629
 
825
630
 
826
631
def compare_files(a, b):
831
636
        bi = b.read(BUFSIZE)
832
637
        if ai != bi:
833
638
            return False
834
 
        if not ai:
 
639
        if ai == '':
835
640
            return True
836
641
 
837
642
 
842
647
    offset = datetime.fromtimestamp(t) - datetime.utcfromtimestamp(t)
843
648
    return offset.days * 86400 + offset.seconds
844
649
 
845
 
 
846
650
weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
847
 
_default_format_by_weekday_num = [wd + " %Y-%m-%d %H:%M:%S" for wd in weekdays]
848
 
 
849
 
 
 
651
    
850
652
def format_date(t, offset=0, timezone='original', date_fmt=None,
851
653
                show_offset=True):
852
654
    """Return a formatted date string.
860
662
    :param show_offset: Whether to append the timezone.
861
663
    """
862
664
    (date_fmt, tt, offset_str) = \
863
 
        _format_date(t, offset, timezone, date_fmt, show_offset)
 
665
               _format_date(t, offset, timezone, date_fmt, show_offset)
864
666
    date_fmt = date_fmt.replace('%a', weekdays[tt[6]])
865
667
    date_str = time.strftime(date_fmt, tt)
866
668
    return date_str + offset_str
867
669
 
868
 
 
869
 
# Cache of formatted offset strings
870
 
_offset_cache = {}
871
 
 
872
 
 
873
 
def format_date_with_offset_in_original_timezone(t, offset=0,
874
 
                                                 _cache=_offset_cache):
875
 
    """Return a formatted date string in the original timezone.
876
 
 
877
 
    This routine may be faster then format_date.
878
 
 
879
 
    :param t: Seconds since the epoch.
880
 
    :param offset: Timezone offset in seconds east of utc.
881
 
    """
882
 
    if offset is None:
883
 
        offset = 0
884
 
    tt = time.gmtime(t + offset)
885
 
    date_fmt = _default_format_by_weekday_num[tt[6]]
886
 
    date_str = time.strftime(date_fmt, tt)
887
 
    offset_str = _cache.get(offset, None)
888
 
    if offset_str is None:
889
 
        offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
890
 
        _cache[offset] = offset_str
891
 
    return date_str + offset_str
892
 
 
893
 
 
894
670
def format_local_date(t, offset=0, timezone='original', date_fmt=None,
895
671
                      show_offset=True):
896
672
    """Return an unicode date string formatted according to the current locale.
904
680
    :param show_offset: Whether to append the timezone.
905
681
    """
906
682
    (date_fmt, tt, offset_str) = \
907
 
        _format_date(t, offset, timezone, date_fmt, show_offset)
 
683
               _format_date(t, offset, timezone, date_fmt, show_offset)
908
684
    date_str = time.strftime(date_fmt, tt)
909
 
    if not isinstance(date_str, text_type):
910
 
        date_str = date_str.decode(get_user_encoding(), 'replace')
 
685
    if not isinstance(date_str, unicode):
 
686
        date_str = date_str.decode(bzrlib.user_encoding, 'replace')
911
687
    return date_str + offset_str
912
688
 
913
 
 
914
689
def _format_date(t, offset, timezone, date_fmt, show_offset):
915
690
    if timezone == 'utc':
916
691
        tt = time.gmtime(t)
923
698
        tt = time.localtime(t)
924
699
        offset = local_time_offset(t)
925
700
    else:
926
 
        raise UnsupportedTimezoneFormat(timezone)
 
701
        raise errors.UnsupportedTimezoneFormat(timezone)
927
702
    if date_fmt is None:
928
703
        date_fmt = "%a %Y-%m-%d %H:%M:%S"
929
704
    if show_offset:
935
710
 
936
711
def compact_date(when):
937
712
    return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
938
 
 
 
713
    
939
714
 
940
715
def format_delta(delta):
941
716
    """Get a nice looking string for a time delta.
953
728
        delta = -delta
954
729
 
955
730
    seconds = delta
956
 
    if seconds < 90:  # print seconds up to 90 seconds
 
731
    if seconds < 90: # print seconds up to 90 seconds
957
732
        if seconds == 1:
958
733
            return '%d second %s' % (seconds, direction,)
959
734
        else:
965
740
        plural_seconds = ''
966
741
    else:
967
742
        plural_seconds = 's'
968
 
    if minutes < 90:  # print minutes, seconds up to 90 minutes
 
743
    if minutes < 90: # print minutes, seconds up to 90 minutes
969
744
        if minutes == 1:
970
745
            return '%d minute, %d second%s %s' % (
971
 
                minutes, seconds, plural_seconds, direction)
 
746
                    minutes, seconds, plural_seconds, direction)
972
747
        else:
973
748
            return '%d minutes, %d second%s %s' % (
974
 
                minutes, seconds, plural_seconds, direction)
 
749
                    minutes, seconds, plural_seconds, direction)
975
750
 
976
751
    hours = int(minutes / 60)
977
752
    minutes -= 60 * hours
986
761
    return '%d hours, %d minute%s %s' % (hours, minutes,
987
762
                                         plural_minutes, direction)
988
763
 
989
 
 
990
764
def filesize(f):
991
765
    """Return size of given open file."""
992
 
    return os.fstat(f.fileno())[stat.ST_SIZE]
993
 
 
994
 
 
995
 
# Alias os.urandom to support platforms (which?) without /dev/urandom and
996
 
# override if it doesn't work. Avoid checking on windows where there is
997
 
# significant initialisation cost that can be avoided for some bzr calls.
998
 
 
999
 
rand_bytes = os.urandom
1000
 
 
1001
 
if rand_bytes.__module__ != "nt":
 
766
    return os.fstat(f.fileno())[ST_SIZE]
 
767
 
 
768
 
 
769
# Define rand_bytes based on platform.
 
770
try:
 
771
    # Python 2.4 and later have os.urandom,
 
772
    # but it doesn't work on some arches
 
773
    os.urandom(1)
 
774
    rand_bytes = os.urandom
 
775
except (NotImplementedError, AttributeError):
 
776
    # If python doesn't have os.urandom, or it doesn't work,
 
777
    # then try to first pull random data from /dev/urandom
1002
778
    try:
1003
 
        rand_bytes(1)
1004
 
    except NotImplementedError:
 
779
        rand_bytes = file('/dev/urandom', 'rb').read
 
780
    # Otherwise, use this hack as a last resort
 
781
    except (IOError, OSError):
1005
782
        # not well seeded, but better than nothing
1006
783
        def rand_bytes(n):
1007
784
            import random
1013
790
 
1014
791
 
1015
792
ALNUM = '0123456789abcdefghijklmnopqrstuvwxyz'
1016
 
 
1017
 
 
1018
793
def rand_chars(num):
1019
794
    """Return a random string of num alphanumeric characters
1020
 
 
1021
 
    The result only contains lowercase chars because it may be used on
 
795
    
 
796
    The result only contains lowercase chars because it may be used on 
1022
797
    case-insensitive filesystems.
1023
798
    """
1024
799
    s = ''
1025
800
    for raw_byte in rand_bytes(num):
1026
 
        if not PY3:
1027
 
            s += ALNUM[ord(raw_byte) % 36]
1028
 
        else:
1029
 
            s += ALNUM[raw_byte % 36]
 
801
        s += ALNUM[ord(raw_byte) % 36]
1030
802
    return s
1031
803
 
1032
804
 
1033
 
# TODO: We could later have path objects that remember their list
1034
 
# decomposition (might be too tricksy though.)
 
805
## TODO: We could later have path objects that remember their list
 
806
## decomposition (might be too tricksy though.)
1035
807
 
1036
808
def splitpath(p):
1037
809
    """Turn string into list of parts."""
1038
 
    if os.path.sep == '\\':
1039
 
        # split on either delimiter because people might use either on
1040
 
        # Windows
1041
 
        if isinstance(p, bytes):
1042
 
            ps = re.split(b'[\\\\/]', p)
1043
 
        else:
1044
 
            ps = re.split(r'[\\/]', p)
1045
 
    else:
1046
 
        if isinstance(p, bytes):
1047
 
            ps = p.split(b'/')
1048
 
        else:
1049
 
            ps = p.split('/')
 
810
    # split on either delimiter because people might use either on
 
811
    # Windows
 
812
    ps = re.split(r'[\\/]', p)
1050
813
 
1051
814
    rps = []
1052
815
    for f in ps:
1053
 
        if f in ('..', b'..'):
1054
 
            raise errors.BzrError(gettext("sorry, %r not allowed in path") % f)
1055
 
        elif f in ('.', '', b'.', b''):
 
816
        if f == '..':
 
817
            raise errors.BzrError("sorry, %r not allowed in path" % f)
 
818
        elif (f == '.') or (f == ''):
1056
819
            pass
1057
820
        else:
1058
821
            rps.append(f)
1062
825
def joinpath(p):
1063
826
    for f in p:
1064
827
        if (f == '..') or (f is None) or (f == ''):
1065
 
            raise errors.BzrError(gettext("sorry, %r not allowed in path") % f)
 
828
            raise errors.BzrError("sorry, %r not allowed in path" % f)
1066
829
    return pathjoin(*p)
1067
830
 
1068
831
 
1069
 
def parent_directories(filename):
1070
 
    """Return the list of parent directories, deepest first.
1071
 
 
1072
 
    For example, parent_directories("a/b/c") -> ["a/b", "a"].
1073
 
    """
1074
 
    parents = []
1075
 
    parts = splitpath(dirname(filename))
1076
 
    while parts:
1077
 
        parents.append(joinpath(parts))
1078
 
        parts.pop()
1079
 
    return parents
1080
 
 
1081
 
 
1082
 
_extension_load_failures = []
1083
 
 
1084
 
 
1085
 
def failed_to_load_extension(exception):
1086
 
    """Handle failing to load a binary extension.
1087
 
 
1088
 
    This should be called from the ImportError block guarding the attempt to
1089
 
    import the native extension.  If this function returns, the pure-Python
1090
 
    implementation should be loaded instead::
1091
 
 
1092
 
    >>> try:
1093
 
    >>>     import breezy._fictional_extension_pyx
1094
 
    >>> except ImportError, e:
1095
 
    >>>     breezy.osutils.failed_to_load_extension(e)
1096
 
    >>>     import breezy._fictional_extension_py
1097
 
    """
1098
 
    # NB: This docstring is just an example, not a doctest, because doctest
1099
 
    # currently can't cope with the use of lazy imports in this namespace --
1100
 
    # mbp 20090729
1101
 
 
1102
 
    # This currently doesn't report the failure at the time it occurs, because
1103
 
    # they tend to happen very early in startup when we can't check config
1104
 
    # files etc, and also we want to report all failures but not spam the user
1105
 
    # with 10 warnings.
1106
 
    exception_str = str(exception)
1107
 
    if exception_str not in _extension_load_failures:
1108
 
        trace.mutter("failed to load compiled extension: %s" % exception_str)
1109
 
        _extension_load_failures.append(exception_str)
1110
 
 
1111
 
 
1112
 
def report_extension_load_failures():
1113
 
    if not _extension_load_failures:
1114
 
        return
1115
 
    if config.GlobalConfig().suppress_warning('missing_extensions'):
1116
 
        return
1117
 
    # the warnings framework should by default show this only once
1118
 
    from .trace import warning
1119
 
    warning(
1120
 
        "brz: warning: some compiled extensions could not be loaded; "
1121
 
        "see ``brz help missing-extensions``")
1122
 
    # we no longer show the specific missing extensions here, because it makes
1123
 
    # the message too long and scary - see
1124
 
    # https://bugs.launchpad.net/bzr/+bug/430529
1125
 
 
1126
 
 
1127
832
try:
1128
 
    from ._chunks_to_lines_pyx import chunks_to_lines
1129
 
except ImportError as e:
1130
 
    failed_to_load_extension(e)
1131
 
    from ._chunks_to_lines_py import chunks_to_lines
 
833
    from bzrlib._chunks_to_lines_pyx import chunks_to_lines
 
834
except ImportError:
 
835
    from bzrlib._chunks_to_lines_py import chunks_to_lines
1132
836
 
1133
837
 
1134
838
def split_lines(s):
1135
839
    """Split s into lines, but without removing the newline characters."""
1136
840
    # Trivially convert a fulltext into a 'chunked' representation, and let
1137
841
    # chunks_to_lines do the heavy lifting.
1138
 
    if isinstance(s, bytes):
 
842
    if isinstance(s, str):
1139
843
        # chunks_to_lines only supports 8-bit strings
1140
844
        return chunks_to_lines([s])
1141
845
    else:
1147
851
 
1148
852
    This supports Unicode or plain string objects.
1149
853
    """
1150
 
    nl = b'\n' if isinstance(s, bytes) else u'\n'
1151
 
    lines = s.split(nl)
1152
 
    result = [line + nl for line in lines[:-1]]
 
854
    lines = s.split('\n')
 
855
    result = [line + '\n' for line in lines[:-1]]
1153
856
    if lines[-1]:
1154
857
        result.append(lines[-1])
1155
858
    return result
1166
869
        return
1167
870
    try:
1168
871
        os.link(src, dest)
1169
 
    except (OSError, IOError) as e:
 
872
    except (OSError, IOError), e:
1170
873
        if e.errno != errno.EXDEV:
1171
874
            raise
1172
875
        shutil.copyfile(src, dest)
1173
876
 
1174
877
 
 
878
# Look Before You Leap (LBYL) is appropriate here instead of Easier to Ask for
 
879
# Forgiveness than Permission (EAFP) because:
 
880
# - root can damage a solaris file system by using unlink,
 
881
# - unlink raises different exceptions on different OSes (linux: EISDIR, win32:
 
882
#   EACCES, OSX: EPERM) when invoked on a directory.
1175
883
def delete_any(path):
1176
 
    """Delete a file, symlink or directory.
1177
 
 
1178
 
    Will delete even if readonly.
1179
 
    """
1180
 
    try:
1181
 
        _delete_file_or_dir(path)
1182
 
    except (OSError, IOError) as e:
1183
 
        if e.errno in (errno.EPERM, errno.EACCES):
1184
 
            # make writable and try again
1185
 
            try:
1186
 
                make_writable(path)
1187
 
            except (OSError, IOError):
1188
 
                pass
1189
 
            _delete_file_or_dir(path)
1190
 
        else:
1191
 
            raise
1192
 
 
1193
 
 
1194
 
def _delete_file_or_dir(path):
1195
 
    # Look Before You Leap (LBYL) is appropriate here instead of Easier to Ask for
1196
 
    # Forgiveness than Permission (EAFP) because:
1197
 
    # - root can damage a solaris file system by using unlink,
1198
 
    # - unlink raises different exceptions on different OSes (linux: EISDIR, win32:
1199
 
    #   EACCES, OSX: EPERM) when invoked on a directory.
1200
 
    if isdir(path):  # Takes care of symlinks
 
884
    """Delete a file or directory."""
 
885
    if isdir(path): # Takes care of symlinks
1201
886
        os.rmdir(path)
1202
887
    else:
1203
888
        os.unlink(path)
1222
907
            and sys.platform not in ('cygwin', 'win32'))
1223
908
 
1224
909
 
1225
 
def readlink(abspath):
1226
 
    """Return a string representing the path to which the symbolic link points.
1227
 
 
1228
 
    :param abspath: The link absolute unicode path.
1229
 
 
1230
 
    This his guaranteed to return the symbolic link in unicode in all python
1231
 
    versions.
1232
 
    """
1233
 
    link = abspath.encode(_fs_enc)
1234
 
    target = os.readlink(link)
1235
 
    target = target.decode(_fs_enc)
1236
 
    return target
1237
 
 
1238
 
 
1239
910
def contains_whitespace(s):
1240
911
    """True if there are any whitespace characters in s."""
1241
912
    # string.whitespace can include '\xa0' in certain locales, because it is
1245
916
    #    separators
1246
917
    # 3) '\xa0' isn't unicode safe since it is >128.
1247
918
 
1248
 
    if isinstance(s, str):
1249
 
        ws = ' \t\n\r\v\f'
1250
 
    else:
1251
 
        ws = (b' ', b'\t', b'\n', b'\r', b'\v', b'\f')
1252
 
    for ch in ws:
 
919
    # This should *not* be a unicode set of characters in case the source
 
920
    # string is not a Unicode string. We can auto-up-cast the characters since
 
921
    # they are ascii, but we don't want to auto-up-cast the string in case it
 
922
    # is utf-8
 
923
    for ch in ' \t\n\r\v\f':
1253
924
        if ch in s:
1254
925
            return True
1255
926
    else:
1266
937
 
1267
938
 
1268
939
def relpath(base, path):
1269
 
    """Return path relative to base, or raise PathNotChild exception.
 
940
    """Return path relative to base, or raise exception.
1270
941
 
1271
942
    The path may be either an absolute path or a path relative to the
1272
943
    current working directory.
1274
945
    os.path.commonprefix (python2.4) has a bad bug that it works just
1275
946
    on string prefixes, assuming that '/u' is a prefix of '/u2'.  This
1276
947
    avoids that problem.
1277
 
 
1278
 
    NOTE: `base` should not have a trailing slash otherwise you'll get
1279
 
    PathNotChild exceptions regardless of `path`.
1280
948
    """
1281
949
 
1282
950
    if len(base) < MIN_ABS_PATHLENGTH:
1283
951
        # must have space for e.g. a drive letter
1284
 
        raise ValueError(gettext('%r is too short to calculate a relative path')
1285
 
                         % (base,))
 
952
        raise ValueError('%r is too short to calculate a relative path'
 
953
            % (base,))
1286
954
 
1287
955
    rp = abspath(path)
1288
956
 
1289
957
    s = []
1290
958
    head = rp
1291
 
    while True:
1292
 
        if len(head) <= len(base) and head != base:
1293
 
            raise errors.PathNotChild(rp, base)
 
959
    while len(head) >= len(base):
1294
960
        if head == base:
1295
961
            break
1296
 
        head, tail = split(head)
 
962
        head, tail = os.path.split(head)
1297
963
        if tail:
1298
 
            s.append(tail)
 
964
            s.insert(0, tail)
 
965
    else:
 
966
        raise errors.PathNotChild(rp, base)
1299
967
 
1300
968
    if s:
1301
 
        return pathjoin(*reversed(s))
 
969
        return pathjoin(*s)
1302
970
    else:
1303
971
        return ''
1304
972
 
1331
999
    bit_iter = iter(rel.split('/'))
1332
1000
    for bit in bit_iter:
1333
1001
        lbit = bit.lower()
1334
 
        try:
1335
 
            next_entries = _listdir(current)
1336
 
        except OSError:  # enoent, eperm, etc
1337
 
            # We can't find this in the filesystem, so just append the
1338
 
            # remaining bits.
1339
 
            current = pathjoin(current, bit, *list(bit_iter))
1340
 
            break
1341
 
        for look in next_entries:
 
1002
        for look in _listdir(current):
1342
1003
            if lbit == look.lower():
1343
1004
                current = pathjoin(current, look)
1344
1005
                break
1348
1009
            # the target of a move, for example).
1349
1010
            current = pathjoin(current, bit, *list(bit_iter))
1350
1011
            break
1351
 
    return current[len(abs_base):].lstrip('/')
1352
 
 
 
1012
    return current[len(abs_base)+1:]
1353
1013
 
1354
1014
# XXX - TODO - we need better detection/integration of case-insensitive
1355
 
# file-systems; Linux often sees FAT32 devices (or NFS-mounted OSX
1356
 
# filesystems), for example, so could probably benefit from the same basic
1357
 
# support there.  For now though, only Windows and OSX get that support, and
1358
 
# they get it for *all* file-systems!
1359
 
if sys.platform in ('win32', 'darwin'):
 
1015
# file-systems; Linux often sees FAT32 devices, for example, so could
 
1016
# probably benefit from the same basic support there.  For now though, only
 
1017
# Windows gets that support, and it gets it for *all* file-systems!
 
1018
if sys.platform == "win32":
1360
1019
    canonical_relpath = _cicp_canonical_relpath
1361
1020
else:
1362
1021
    canonical_relpath = relpath
1363
1022
 
1364
 
 
1365
1023
def canonical_relpaths(base, paths):
1366
1024
    """Create an iterable to canonicalize a sequence of relative paths.
1367
1025
 
1371
1029
    # but for now, we haven't optimized...
1372
1030
    return [canonical_relpath(base, p) for p in paths]
1373
1031
 
1374
 
 
1375
 
def decode_filename(filename):
1376
 
    """Decode the filename using the filesystem encoding
1377
 
 
1378
 
    If it is unicode, it is returned.
1379
 
    Otherwise it is decoded from the the filesystem's encoding. If decoding
1380
 
    fails, a errors.BadFilenameEncoding exception is raised.
1381
 
    """
1382
 
    if isinstance(filename, text_type):
1383
 
        return filename
1384
 
    try:
1385
 
        return filename.decode(_fs_enc)
1386
 
    except UnicodeDecodeError:
1387
 
        raise errors.BadFilenameEncoding(filename, _fs_enc)
1388
 
 
1389
 
 
1390
1032
def safe_unicode(unicode_or_utf8_string):
1391
1033
    """Coerce unicode_or_utf8_string into unicode.
1392
1034
 
1393
1035
    If it is unicode, it is returned.
1394
 
    Otherwise it is decoded from utf-8. If decoding fails, the exception is
1395
 
    wrapped in a BzrBadParameterNotUnicode exception.
 
1036
    Otherwise it is decoded from utf-8. If a decoding error
 
1037
    occurs, it is wrapped as a If the decoding fails, the exception is wrapped 
 
1038
    as a BzrBadParameter exception.
1396
1039
    """
1397
 
    if isinstance(unicode_or_utf8_string, text_type):
 
1040
    if isinstance(unicode_or_utf8_string, unicode):
1398
1041
        return unicode_or_utf8_string
1399
1042
    try:
1400
1043
        return unicode_or_utf8_string.decode('utf8')
1408
1051
    If it is a str, it is returned.
1409
1052
    If it is Unicode, it is encoded into a utf-8 string.
1410
1053
    """
1411
 
    if isinstance(unicode_or_utf8_string, bytes):
 
1054
    if isinstance(unicode_or_utf8_string, str):
1412
1055
        # TODO: jam 20070209 This is overkill, and probably has an impact on
1413
1056
        #       performance if we are dealing with lots of apis that want a
1414
1057
        #       utf-8 revision id
1421
1064
    return unicode_or_utf8_string.encode('utf-8')
1422
1065
 
1423
1066
 
1424
 
def safe_revision_id(unicode_or_utf8_string):
 
1067
_revision_id_warning = ('Unicode revision ids were deprecated in bzr 0.15.'
 
1068
                        ' Revision id generators should be creating utf8'
 
1069
                        ' revision ids.')
 
1070
 
 
1071
 
 
1072
def safe_revision_id(unicode_or_utf8_string, warn=True):
1425
1073
    """Revision ids should now be utf8, but at one point they were unicode.
1426
1074
 
1427
1075
    :param unicode_or_utf8_string: A possibly Unicode revision_id. (can also be
1428
1076
        utf8 or None).
 
1077
    :param warn: Functions that are sanitizing user data can set warn=False
1429
1078
    :return: None or a utf8 revision id.
1430
1079
    """
1431
1080
    if (unicode_or_utf8_string is None
1432
 
            or unicode_or_utf8_string.__class__ == bytes):
 
1081
        or unicode_or_utf8_string.__class__ == str):
1433
1082
        return unicode_or_utf8_string
1434
 
    raise TypeError('Unicode revision ids are no longer supported. '
1435
 
                    'Revision id generators should be creating utf8 revision '
1436
 
                    'ids.')
1437
 
 
1438
 
 
1439
 
def safe_file_id(unicode_or_utf8_string):
 
1083
    if warn:
 
1084
        symbol_versioning.warn(_revision_id_warning, DeprecationWarning,
 
1085
                               stacklevel=2)
 
1086
    return cache_utf8.encode(unicode_or_utf8_string)
 
1087
 
 
1088
 
 
1089
_file_id_warning = ('Unicode file ids were deprecated in bzr 0.15. File id'
 
1090
                    ' generators should be creating utf8 file ids.')
 
1091
 
 
1092
 
 
1093
def safe_file_id(unicode_or_utf8_string, warn=True):
1440
1094
    """File ids should now be utf8, but at one point they were unicode.
1441
1095
 
1442
1096
    This is the same as safe_utf8, except it uses the cached encode functions
1444
1098
 
1445
1099
    :param unicode_or_utf8_string: A possibly Unicode file_id. (can also be
1446
1100
        utf8 or None).
 
1101
    :param warn: Functions that are sanitizing user data can set warn=False
1447
1102
    :return: None or a utf8 file id.
1448
1103
    """
1449
1104
    if (unicode_or_utf8_string is None
1450
 
            or unicode_or_utf8_string.__class__ == bytes):
 
1105
        or unicode_or_utf8_string.__class__ == str):
1451
1106
        return unicode_or_utf8_string
1452
 
    raise TypeError('Unicode file ids are no longer supported. '
1453
 
                    'File id generators should be creating utf8 file ids.')
 
1107
    if warn:
 
1108
        symbol_versioning.warn(_file_id_warning, DeprecationWarning,
 
1109
                               stacklevel=2)
 
1110
    return cache_utf8.encode(unicode_or_utf8_string)
1454
1111
 
1455
1112
 
1456
1113
_platform_normalizes_filenames = False
1461
1118
def normalizes_filenames():
1462
1119
    """Return True if this platform normalizes unicode filenames.
1463
1120
 
1464
 
    Only Mac OSX.
 
1121
    Mac OSX does, Windows/Linux do not.
1465
1122
    """
1466
1123
    return _platform_normalizes_filenames
1467
1124
 
1471
1128
 
1472
1129
    On platforms where the system normalizes filenames (Mac OSX),
1473
1130
    you can access a file by any path which will normalize correctly.
1474
 
    On platforms where the system does not normalize filenames
1475
 
    (everything else), you have to access a file by its exact path.
 
1131
    On platforms where the system does not normalize filenames 
 
1132
    (Windows, Linux), you have to access a file by its exact path.
1476
1133
 
1477
 
    Internally, bzr only supports NFC normalization, since that is
 
1134
    Internally, bzr only supports NFC normalization, since that is 
1478
1135
    the standard for XML documents.
1479
1136
 
1480
1137
    So return the normalized path, and a flag indicating if the file
1481
1138
    can be accessed by that path.
1482
1139
    """
1483
1140
 
1484
 
    if isinstance(path, bytes):
1485
 
        path = path.decode(sys.getfilesystemencoding())
1486
 
    return unicodedata.normalize('NFC', path), True
 
1141
    return unicodedata.normalize('NFC', unicode(path)), True
1487
1142
 
1488
1143
 
1489
1144
def _inaccessible_normalized_filename(path):
1490
1145
    __doc__ = _accessible_normalized_filename.__doc__
1491
1146
 
1492
 
    if isinstance(path, bytes):
1493
 
        path = path.decode(sys.getfilesystemencoding())
1494
 
    normalized = unicodedata.normalize('NFC', path)
 
1147
    normalized = unicodedata.normalize('NFC', unicode(path))
1495
1148
    return normalized, normalized == path
1496
1149
 
1497
1150
 
1501
1154
    normalized_filename = _inaccessible_normalized_filename
1502
1155
 
1503
1156
 
1504
 
def set_signal_handler(signum, handler, restart_syscall=True):
1505
 
    """A wrapper for signal.signal that also calls siginterrupt(signum, False)
1506
 
    on platforms that support that.
1507
 
 
1508
 
    :param restart_syscall: if set, allow syscalls interrupted by a signal to
1509
 
        automatically restart (by calling `signal.siginterrupt(signum,
1510
 
        False)`).  May be ignored if the feature is not available on this
1511
 
        platform or Python version.
1512
 
    """
1513
 
    try:
1514
 
        import signal
1515
 
        siginterrupt = signal.siginterrupt
1516
 
    except ImportError:
1517
 
        # This python implementation doesn't provide signal support, hence no
1518
 
        # handler exists
1519
 
        return None
1520
 
    except AttributeError:
1521
 
        # siginterrupt doesn't exist on this platform, or for this version
1522
 
        # of Python.
1523
 
        def siginterrupt(signum, flag): return None
1524
 
    if restart_syscall:
1525
 
        def sig_handler(*args):
1526
 
            # Python resets the siginterrupt flag when a signal is
1527
 
            # received.  <http://bugs.python.org/issue8354>
1528
 
            # As a workaround for some cases, set it back the way we want it.
1529
 
            siginterrupt(signum, False)
1530
 
            # Now run the handler function passed to set_signal_handler.
1531
 
            handler(*args)
1532
 
    else:
1533
 
        sig_handler = handler
1534
 
    old_handler = signal.signal(signum, sig_handler)
1535
 
    if restart_syscall:
1536
 
        siginterrupt(signum, False)
1537
 
    return old_handler
1538
 
 
1539
 
 
1540
 
default_terminal_width = 80
1541
 
"""The default terminal width for ttys.
1542
 
 
1543
 
This is defined so that higher levels can share a common fallback value when
1544
 
terminal_width() returns None.
1545
 
"""
1546
 
 
1547
 
# Keep some state so that terminal_width can detect if _terminal_size has
1548
 
# returned a different size since the process started.  See docstring and
1549
 
# comments of terminal_width for details.
1550
 
# _terminal_size_state has 3 possible values: no_data, unchanged, and changed.
1551
 
_terminal_size_state = 'no_data'
1552
 
_first_terminal_size = None
1553
 
 
1554
 
 
1555
1157
def terminal_width():
1556
 
    """Return terminal width.
1557
 
 
1558
 
    None is returned if the width can't established precisely.
1559
 
 
1560
 
    The rules are:
1561
 
    - if BRZ_COLUMNS is set, returns its value
1562
 
    - if there is no controlling terminal, returns None
1563
 
    - query the OS, if the queried size has changed since the last query,
1564
 
      return its value,
1565
 
    - if COLUMNS is set, returns its value,
1566
 
    - if the OS has a value (even though it's never changed), return its value.
1567
 
 
1568
 
    From there, we need to query the OS to get the size of the controlling
1569
 
    terminal.
1570
 
 
1571
 
    On Unices we query the OS by:
1572
 
    - get termios.TIOCGWINSZ
1573
 
    - if an error occurs or a negative value is obtained, returns None
1574
 
 
1575
 
    On Windows we query the OS by:
1576
 
    - win32utils.get_console_size() decides,
1577
 
    - returns None on error (provided default value)
1578
 
    """
1579
 
    # Note to implementors: if changing the rules for determining the width,
1580
 
    # make sure you've considered the behaviour in these cases:
1581
 
    #  - M-x shell in emacs, where $COLUMNS is set and TIOCGWINSZ returns 0,0.
1582
 
    #  - brz log | less, in bash, where $COLUMNS not set and TIOCGWINSZ returns
1583
 
    #    0,0.
1584
 
    #  - (add more interesting cases here, if you find any)
1585
 
    # Some programs implement "Use $COLUMNS (if set) until SIGWINCH occurs",
1586
 
    # but we don't want to register a signal handler because it is impossible
1587
 
    # to do so without risking EINTR errors in Python <= 2.6.5 (see
1588
 
    # <http://bugs.python.org/issue8354>).  Instead we check TIOCGWINSZ every
1589
 
    # time so we can notice if the reported size has changed, which should have
1590
 
    # a similar effect.
1591
 
 
1592
 
    # If BRZ_COLUMNS is set, take it, user is always right
1593
 
    # Except if they specified 0 in which case, impose no limit here
1594
 
    try:
1595
 
        width = int(os.environ['BRZ_COLUMNS'])
1596
 
    except (KeyError, ValueError):
1597
 
        width = None
1598
 
    if width is not None:
1599
 
        if width > 0:
1600
 
            return width
1601
 
        else:
1602
 
            return None
1603
 
 
1604
 
    isatty = getattr(sys.stdout, 'isatty', None)
1605
 
    if isatty is None or not isatty():
1606
 
        # Don't guess, setting BRZ_COLUMNS is the recommended way to override.
1607
 
        return None
1608
 
 
1609
 
    # Query the OS
1610
 
    width, height = os_size = _terminal_size(None, None)
1611
 
    global _first_terminal_size, _terminal_size_state
1612
 
    if _terminal_size_state == 'no_data':
1613
 
        _first_terminal_size = os_size
1614
 
        _terminal_size_state = 'unchanged'
1615
 
    elif (_terminal_size_state == 'unchanged' and
1616
 
          _first_terminal_size != os_size):
1617
 
        _terminal_size_state = 'changed'
1618
 
 
1619
 
    # If the OS claims to know how wide the terminal is, and this value has
1620
 
    # ever changed, use that.
1621
 
    if _terminal_size_state == 'changed':
1622
 
        if width is not None and width > 0:
1623
 
            return width
1624
 
 
1625
 
    # If COLUMNS is set, use it.
1626
 
    try:
1627
 
        return int(os.environ['COLUMNS'])
1628
 
    except (KeyError, ValueError):
1629
 
        pass
1630
 
 
1631
 
    # Finally, use an unchanged size from the OS, if we have one.
1632
 
    if _terminal_size_state == 'unchanged':
1633
 
        if width is not None and width > 0:
1634
 
            return width
1635
 
 
1636
 
    # The width could not be determined.
1637
 
    return None
1638
 
 
1639
 
 
1640
 
def _win32_terminal_size(width, height):
1641
 
    width, height = win32utils.get_console_size(
1642
 
        defaultx=width, defaulty=height)
1643
 
    return width, height
1644
 
 
1645
 
 
1646
 
def _ioctl_terminal_size(width, height):
1647
 
    try:
1648
 
        import struct
1649
 
        import fcntl
1650
 
        import termios
 
1158
    """Return estimated terminal width."""
 
1159
    if sys.platform == 'win32':
 
1160
        return win32utils.get_console_size()[0]
 
1161
    width = 0
 
1162
    try:
 
1163
        import struct, fcntl, termios
1651
1164
        s = struct.pack('HHHH', 0, 0, 0, 0)
1652
1165
        x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
1653
 
        height, width = struct.unpack('HHHH', x)[0:2]
1654
 
    except (IOError, AttributeError):
 
1166
        width = struct.unpack('HHHH', x)[1]
 
1167
    except IOError:
1655
1168
        pass
1656
 
    return width, height
1657
 
 
1658
 
 
1659
 
_terminal_size = None
1660
 
"""Returns the terminal size as (width, height).
1661
 
 
1662
 
:param width: Default value for width.
1663
 
:param height: Default value for height.
1664
 
 
1665
 
This is defined specifically for each OS and query the size of the controlling
1666
 
terminal. If any error occurs, the provided default values should be returned.
1667
 
"""
1668
 
if sys.platform == 'win32':
1669
 
    _terminal_size = _win32_terminal_size
1670
 
else:
1671
 
    _terminal_size = _ioctl_terminal_size
 
1169
    if width <= 0:
 
1170
        try:
 
1171
            width = int(os.environ['COLUMNS'])
 
1172
        except:
 
1173
            pass
 
1174
    if width <= 0:
 
1175
        width = 80
 
1176
 
 
1177
    return width
1672
1178
 
1673
1179
 
1674
1180
def supports_executable():
1701
1207
        if orig_val is not None:
1702
1208
            del os.environ[env_variable]
1703
1209
    else:
1704
 
        if not PY3 and isinstance(value, text_type):
 
1210
        if isinstance(value, unicode):
1705
1211
            value = value.encode(get_user_encoding())
1706
1212
        os.environ[env_variable] = value
1707
1213
    return orig_val
1711
1217
 
1712
1218
 
1713
1219
def check_legal_path(path):
1714
 
    """Check whether the supplied path is legal.
 
1220
    """Check whether the supplied path is legal.  
1715
1221
    This is only required on Windows, so we don't test on other platforms
1716
1222
    right now.
1717
1223
    """
1721
1227
        raise errors.IllegalPath(path)
1722
1228
 
1723
1229
 
1724
 
_WIN32_ERROR_DIRECTORY = 267  # Similar to errno.ENOTDIR
1725
 
 
 
1230
_WIN32_ERROR_DIRECTORY = 267 # Similar to errno.ENOTDIR
1726
1231
 
1727
1232
def _is_error_enotdir(e):
1728
1233
    """Check if this exception represents ENOTDIR.
1740
1245
    :return: True if this represents an ENOTDIR error. False otherwise.
1741
1246
    """
1742
1247
    en = getattr(e, 'errno', None)
1743
 
    if (en == errno.ENOTDIR or
1744
 
        (sys.platform == 'win32' and
1745
 
            (en == _WIN32_ERROR_DIRECTORY or
1746
 
             (en == errno.EINVAL
1747
 
              and getattr(e, 'winerror', None) == _WIN32_ERROR_DIRECTORY)
1748
 
             ))):
 
1248
    if (en == errno.ENOTDIR
 
1249
        or (sys.platform == 'win32'
 
1250
            and (en == _WIN32_ERROR_DIRECTORY
 
1251
                 or (en == errno.EINVAL
 
1252
                     and getattr(e, 'winerror', None) == _WIN32_ERROR_DIRECTORY)
 
1253
        ))):
1749
1254
        return True
1750
1255
    return False
1751
1256
 
1752
1257
 
1753
1258
def walkdirs(top, prefix=""):
1754
1259
    """Yield data about all the directories in a tree.
1755
 
 
 
1260
    
1756
1261
    This yields all the data about the contents of a directory at a time.
1757
1262
    After each directory has been yielded, if the caller has mutated the list
1758
1263
    to exclude some directories, they are then not descended into.
1759
 
 
 
1264
    
1760
1265
    The data yielded is of the form:
1761
1266
    ((directory-relpath, directory-path-from-top),
1762
1267
    [(relpath, basename, kind, lstat, path-from-top), ...]),
1763
1268
     - directory-relpath is the relative path of the directory being returned
1764
1269
       with respect to top. prefix is prepended to this.
1765
 
     - directory-path-from-root is the path including top for this directory.
 
1270
     - directory-path-from-root is the path including top for this directory. 
1766
1271
       It is suitable for use with os functions.
1767
1272
     - relpath is the relative path within the subtree being walked.
1768
1273
     - basename is the basename of the path
1770
1275
       present within the tree - but it may be recorded as versioned. See
1771
1276
       versioned_kind.
1772
1277
     - lstat is the stat data *if* the file was statted.
1773
 
     - planned, not implemented:
 
1278
     - planned, not implemented: 
1774
1279
       path_from_tree_root is the path from the root of the tree.
1775
1280
 
1776
 
    :param prefix: Prefix the relpaths that are yielded with 'prefix'. This
 
1281
    :param prefix: Prefix the relpaths that are yielded with 'prefix'. This 
1777
1282
        allows one to walk a subtree but get paths that are relative to a tree
1778
1283
        rooted higher up.
1779
1284
    :return: an iterator over the dirs.
1780
1285
    """
1781
 
    # TODO there is a bit of a smell where the results of the directory-
1782
 
    # summary in this, and the path from the root, may not agree
 
1286
    #TODO there is a bit of a smell where the results of the directory-
 
1287
    # summary in this, and the path from the root, may not agree 
1783
1288
    # depending on top and prefix - i.e. ./foo and foo as a pair leads to
1784
1289
    # potentially confusing output. We should make this more robust - but
1785
1290
    # not at a speed cost. RBC 20060731
1800
1305
        dirblock = []
1801
1306
        append = dirblock.append
1802
1307
        try:
1803
 
            names = sorted(map(decode_filename, _listdir(top)))
1804
 
        except OSError as e:
 
1308
            names = sorted(_listdir(top))
 
1309
        except OSError, e:
1805
1310
            if not _is_error_enotdir(e):
1806
1311
                raise
1807
1312
        else:
1860
1365
    """
1861
1366
    global _selected_dir_reader
1862
1367
    if _selected_dir_reader is None:
1863
 
        if sys.platform == "win32":
 
1368
        fs_encoding = _fs_enc.upper()
 
1369
        if sys.platform == "win32" and win32utils.winver == 'Windows NT':
 
1370
            # Win98 doesn't have unicode apis like FindFirstFileW
 
1371
            # TODO: We possibly could support Win98 by falling back to the
 
1372
            #       original FindFirstFile, and using TCHAR instead of WCHAR,
 
1373
            #       but that gets a bit tricky, and requires custom compiling
 
1374
            #       for win98 anyway.
1864
1375
            try:
1865
 
                from ._walkdirs_win32 import Win32ReadDir
 
1376
                from bzrlib._walkdirs_win32 import Win32ReadDir
 
1377
            except ImportError:
 
1378
                _selected_dir_reader = UnicodeDirReader()
 
1379
            else:
1866
1380
                _selected_dir_reader = Win32ReadDir()
 
1381
        elif fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
 
1382
            # ANSI_X3.4-1968 is a form of ASCII
 
1383
            _selected_dir_reader = UnicodeDirReader()
 
1384
        else:
 
1385
            try:
 
1386
                from bzrlib._readdir_pyx import UTF8DirReader
1867
1387
            except ImportError:
1868
 
                pass
1869
 
        elif _fs_enc in ('utf-8', 'ascii'):
1870
 
            try:
1871
 
                from ._readdir_pyx import UTF8DirReader
 
1388
                # No optimised code path
 
1389
                _selected_dir_reader = UnicodeDirReader()
 
1390
            else:
1872
1391
                _selected_dir_reader = UTF8DirReader()
1873
 
            except ImportError as e:
1874
 
                failed_to_load_extension(e)
1875
 
                pass
1876
 
 
1877
 
    if _selected_dir_reader is None:
1878
 
        # Fallback to the python version
1879
 
        _selected_dir_reader = UnicodeDirReader()
1880
 
 
1881
1392
    # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1882
1393
    # But we don't actually uses 1-3 in pending, so set them to None
1883
1394
    pending = [[_selected_dir_reader.top_prefix_to_starting_dir(top, prefix)]]
1921
1432
        See DirReader.read_dir for details.
1922
1433
        """
1923
1434
        _utf8_encode = self._utf8_encode
1924
 
 
1925
 
        def _fs_decode(s): return s.decode(_fs_enc)
1926
 
 
1927
 
        def _fs_encode(s): return s.encode(_fs_enc)
1928
1435
        _lstat = os.lstat
1929
1436
        _listdir = os.listdir
1930
1437
        _kind_from_mode = file_kind_from_stat_mode
1931
1438
 
1932
1439
        if prefix:
1933
 
            relprefix = prefix + b'/'
 
1440
            relprefix = prefix + '/'
1934
1441
        else:
1935
 
            relprefix = b''
1936
 
        top_slash = top + '/'
 
1442
            relprefix = ''
 
1443
        top_slash = top + u'/'
1937
1444
 
1938
1445
        dirblock = []
1939
1446
        append = dirblock.append
1940
 
        for name_native in _listdir(top.encode('utf-8')):
 
1447
        for name in sorted(_listdir(top)):
1941
1448
            try:
1942
 
                name = _fs_decode(name_native)
 
1449
                name_utf8 = _utf8_encode(name)[0]
1943
1450
            except UnicodeDecodeError:
1944
1451
                raise errors.BadFilenameEncoding(
1945
 
                    relprefix + name_native, _fs_enc)
1946
 
            name_utf8 = _utf8_encode(name)[0]
 
1452
                    _utf8_encode(relprefix)[0] + name, _fs_enc)
1947
1453
            abspath = top_slash + name
1948
1454
            statvalue = _lstat(abspath)
1949
1455
            kind = _kind_from_mode(statvalue.st_mode)
1950
1456
            append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
1951
 
        return sorted(dirblock)
 
1457
        return dirblock
1952
1458
 
1953
1459
 
1954
1460
def copy_tree(from_path, to_path, handlers={}):
1955
1461
    """Copy all of the entries in from_path into to_path.
1956
1462
 
1957
 
    :param from_path: The base directory to copy.
 
1463
    :param from_path: The base directory to copy. 
1958
1464
    :param to_path: The target directory. If it does not exist, it will
1959
1465
        be created.
1960
1466
    :param handlers: A dictionary of functions, which takes a source and
1979
1485
        link_to = os.readlink(source)
1980
1486
        os.symlink(link_to, dest)
1981
1487
 
1982
 
    real_handlers = {'file': shutil.copy2,
1983
 
                     'symlink': copy_link,
1984
 
                     'directory': copy_dir,
1985
 
                     }
 
1488
    real_handlers = {'file':shutil.copy2,
 
1489
                     'symlink':copy_link,
 
1490
                     'directory':copy_dir,
 
1491
                    }
1986
1492
    real_handlers.update(handlers)
1987
1493
 
1988
1494
    if not os.path.exists(to_path):
1993
1499
            real_handlers[kind](abspath, relpath)
1994
1500
 
1995
1501
 
1996
 
def copy_ownership_from_path(dst, src=None):
1997
 
    """Copy usr/grp ownership from src file/dir to dst file/dir.
1998
 
 
1999
 
    If src is None, the containing directory is used as source. If chown
2000
 
    fails, the error is ignored and a warning is printed.
2001
 
    """
2002
 
    chown = getattr(os, 'chown', None)
2003
 
    if chown is None:
2004
 
        return
2005
 
 
2006
 
    if src is None:
2007
 
        src = os.path.dirname(dst)
2008
 
        if src == '':
2009
 
            src = '.'
2010
 
 
2011
 
    try:
2012
 
        s = os.stat(src)
2013
 
        chown(dst, s.st_uid, s.st_gid)
2014
 
    except OSError:
2015
 
        trace.warning(
2016
 
            'Unable to copy ownership from "%s" to "%s". '
2017
 
            'You may want to set it manually.', src, dst)
2018
 
        trace.log_exception_quietly()
2019
 
 
2020
 
 
2021
1502
def path_prefix_key(path):
2022
1503
    """Generate a prefix-order path key for path.
2023
1504
 
2024
1505
    This can be used to sort paths in the same way that walkdirs does.
2025
1506
    """
2026
 
    return (dirname(path), path)
 
1507
    return (dirname(path) , path)
2027
1508
 
2028
1509
 
2029
1510
def compare_paths_prefix_order(path_a, path_b):
2030
1511
    """Compare path_a and path_b to generate the same order walkdirs uses."""
2031
1512
    key_a = path_prefix_key(path_a)
2032
1513
    key_b = path_prefix_key(path_b)
2033
 
    return (key_a > key_b) - (key_a < key_b)
 
1514
    return cmp(key_a, key_b)
2034
1515
 
2035
1516
 
2036
1517
_cached_user_encoding = None
2037
1518
 
2038
1519
 
2039
 
def get_user_encoding():
 
1520
def get_user_encoding(use_cache=True):
2040
1521
    """Find out what the preferred user encoding is.
2041
1522
 
2042
1523
    This is generally the encoding that is used for command line parameters
2043
1524
    and file contents. This may be different from the terminal encoding
2044
1525
    or the filesystem encoding.
2045
1526
 
 
1527
    :param  use_cache:  Enable cache for detected encoding.
 
1528
                        (This parameter is turned on by default,
 
1529
                        and required only for selftesting)
 
1530
 
2046
1531
    :return: A string defining the preferred user encoding
2047
1532
    """
2048
1533
    global _cached_user_encoding
2049
 
    if _cached_user_encoding is not None:
 
1534
    if _cached_user_encoding is not None and use_cache:
2050
1535
        return _cached_user_encoding
2051
1536
 
2052
 
    if os.name == 'posix' and getattr(locale, 'CODESET', None) is not None:
2053
 
        # Use the existing locale settings and call nl_langinfo directly
2054
 
        # rather than going through getpreferredencoding. This avoids
2055
 
        # <http://bugs.python.org/issue6202> on OSX Python 2.6 and the
2056
 
        # possibility of the setlocale call throwing an error.
2057
 
        user_encoding = locale.nl_langinfo(locale.CODESET)
 
1537
    if sys.platform == 'darwin':
 
1538
        # python locale.getpreferredencoding() always return
 
1539
        # 'mac-roman' on darwin. That's a lie.
 
1540
        sys.platform = 'posix'
 
1541
        try:
 
1542
            if os.environ.get('LANG', None) is None:
 
1543
                # If LANG is not set, we end up with 'ascii', which is bad
 
1544
                # ('mac-roman' is more than ascii), so we set a default which
 
1545
                # will give us UTF-8 (which appears to work in all cases on
 
1546
                # OSX). Users are still free to override LANG of course, as
 
1547
                # long as it give us something meaningful. This work-around
 
1548
                # *may* not be needed with python 3k and/or OSX 10.5, but will
 
1549
                # work with them too -- vila 20080908
 
1550
                os.environ['LANG'] = 'en_US.UTF-8'
 
1551
            import locale
 
1552
        finally:
 
1553
            sys.platform = 'darwin'
2058
1554
    else:
2059
 
        # GZ 2011-12-19: On windows could call GetACP directly instead.
2060
 
        user_encoding = locale.getpreferredencoding(False)
 
1555
        import locale
2061
1556
 
2062
1557
    try:
2063
 
        user_encoding = codecs.lookup(user_encoding).name
2064
 
    except LookupError:
2065
 
        if user_encoding not in ("", "cp0"):
2066
 
            sys.stderr.write('brz: warning:'
 
1558
        user_encoding = locale.getpreferredencoding()
 
1559
    except locale.Error, e:
 
1560
        sys.stderr.write('bzr: warning: %s\n'
 
1561
                         '  Could not determine what text encoding to use.\n'
 
1562
                         '  This error usually means your Python interpreter\n'
 
1563
                         '  doesn\'t support the locale set by $LANG (%s)\n'
 
1564
                         "  Continuing with ascii encoding.\n"
 
1565
                         % (e, os.environ.get('LANG')))
 
1566
        user_encoding = 'ascii'
 
1567
 
 
1568
    # Windows returns 'cp0' to indicate there is no code page. So we'll just
 
1569
    # treat that as ASCII, and not support printing unicode characters to the
 
1570
    # console.
 
1571
    #
 
1572
    # For python scripts run under vim, we get '', so also treat that as ASCII
 
1573
    if user_encoding in (None, 'cp0', ''):
 
1574
        user_encoding = 'ascii'
 
1575
    else:
 
1576
        # check encoding
 
1577
        try:
 
1578
            codecs.lookup(user_encoding)
 
1579
        except LookupError:
 
1580
            sys.stderr.write('bzr: warning:'
2067
1581
                             ' unknown encoding %s.'
2068
1582
                             ' Continuing with ascii encoding.\n'
2069
1583
                             % user_encoding
2070
 
                             )
2071
 
        user_encoding = 'ascii'
2072
 
    else:
2073
 
        # Get 'ascii' when setlocale has not been called or LANG=C or unset.
2074
 
        if user_encoding == 'ascii':
2075
 
            if sys.platform == 'darwin':
2076
 
                # OSX is special-cased in Python to have a UTF-8 filesystem
2077
 
                # encoding and previously had LANG set here if not present.
2078
 
                user_encoding = 'utf-8'
2079
 
            # GZ 2011-12-19: Maybe UTF-8 should be the default in this case
2080
 
            #                for some other posix platforms as well.
2081
 
 
2082
 
    _cached_user_encoding = user_encoding
 
1584
                            )
 
1585
            user_encoding = 'ascii'
 
1586
 
 
1587
    if use_cache:
 
1588
        _cached_user_encoding = user_encoding
 
1589
 
2083
1590
    return user_encoding
2084
1591
 
2085
1592
 
2086
 
def get_diff_header_encoding():
2087
 
    return get_terminal_encoding()
2088
 
 
2089
 
 
2090
1593
def get_host_name():
2091
1594
    """Return the current unicode host name.
2092
1595
 
2094
1597
    behaves inconsistently on different platforms.
2095
1598
    """
2096
1599
    if sys.platform == "win32":
 
1600
        import win32utils
2097
1601
        return win32utils.get_host_name()
2098
1602
    else:
2099
1603
        import socket
2100
 
        if PY3:
2101
 
            return socket.gethostname()
2102
1604
        return socket.gethostname().decode(get_user_encoding())
2103
1605
 
2104
1606
 
2105
 
# We must not read/write any more than 64k at a time from/to a socket so we
2106
 
# don't risk "no buffer space available" errors on some platforms.  Windows in
2107
 
# particular is likely to throw WSAECONNABORTED or WSAENOBUFS if given too much
2108
 
# data at once.
2109
 
MAX_SOCKET_CHUNK = 64 * 1024
2110
 
 
2111
 
_end_of_stream_errors = [errno.ECONNRESET, errno.EPIPE, errno.EINVAL]
2112
 
for _eno in ['WSAECONNRESET', 'WSAECONNABORTED']:
2113
 
    _eno = getattr(errno, _eno, None)
2114
 
    if _eno is not None:
2115
 
        _end_of_stream_errors.append(_eno)
2116
 
del _eno
2117
 
 
2118
 
 
2119
 
def read_bytes_from_socket(sock, report_activity=None,
2120
 
                           max_read_size=MAX_SOCKET_CHUNK):
2121
 
    """Read up to max_read_size of bytes from sock and notify of progress.
2122
 
 
2123
 
    Translates "Connection reset by peer" into file-like EOF (return an
2124
 
    empty string rather than raise an error), and repeats the recv if
2125
 
    interrupted by a signal.
2126
 
    """
2127
 
    while True:
2128
 
        try:
2129
 
            data = sock.recv(max_read_size)
2130
 
        except socket.error as e:
2131
 
            eno = e.args[0]
2132
 
            if eno in _end_of_stream_errors:
2133
 
                # The connection was closed by the other side.  Callers expect
2134
 
                # an empty string to signal end-of-stream.
2135
 
                return b""
2136
 
            elif eno == errno.EINTR:
2137
 
                # Retry the interrupted recv.
2138
 
                continue
2139
 
            raise
2140
 
        else:
2141
 
            if report_activity is not None:
2142
 
                report_activity(len(data), 'read')
2143
 
            return data
2144
 
 
2145
 
 
2146
 
def recv_all(socket, count):
 
1607
def recv_all(socket, bytes):
2147
1608
    """Receive an exact number of bytes.
2148
1609
 
2149
1610
    Regular Socket.recv() may return less than the requested number of bytes,
2150
 
    depending on what's in the OS buffer.  MSG_WAITALL is not available
 
1611
    dependning on what's in the OS buffer.  MSG_WAITALL is not available
2151
1612
    on all platforms, but this should work everywhere.  This will return
2152
1613
    less than the requested amount if the remote end closes.
2153
1614
 
2154
1615
    This isn't optimized and is intended mostly for use in testing.
2155
1616
    """
2156
 
    b = b''
2157
 
    while len(b) < count:
2158
 
        new = read_bytes_from_socket(socket, None, count - len(b))
2159
 
        if new == b'':
2160
 
            break  # eof
 
1617
    b = ''
 
1618
    while len(b) < bytes:
 
1619
        new = until_no_eintr(socket.recv, bytes - len(b))
 
1620
        if new == '':
 
1621
            break # eof
2161
1622
        b += new
2162
1623
    return b
2163
1624
 
2164
1625
 
2165
 
def send_all(sock, bytes, report_activity=None):
 
1626
def send_all(socket, bytes):
2166
1627
    """Send all bytes on a socket.
2167
1628
 
2168
 
    Breaks large blocks in smaller chunks to avoid buffering limitations on
2169
 
    some platforms, and catches EINTR which may be thrown if the send is
2170
 
    interrupted by a signal.
2171
 
 
2172
 
    This is preferred to socket.sendall(), because it avoids portability bugs
2173
 
    and provides activity reporting.
2174
 
 
2175
 
    :param report_activity: Call this as bytes are read, see
2176
 
        Transport._report_activity
 
1629
    Regular socket.sendall() can give socket error 10053 on Windows.  This
 
1630
    implementation sends no more than 64k at a time, which avoids this problem.
2177
1631
    """
2178
 
    sent_total = 0
2179
 
    byte_count = len(bytes)
2180
 
    view = memoryview(bytes)
2181
 
    while sent_total < byte_count:
2182
 
        try:
2183
 
            sent = sock.send(view[sent_total:sent_total + MAX_SOCKET_CHUNK])
2184
 
        except (socket.error, IOError) as e:
2185
 
            if e.args[0] in _end_of_stream_errors:
2186
 
                raise errors.ConnectionReset(
2187
 
                    "Error trying to write to socket", e)
2188
 
            if e.args[0] != errno.EINTR:
2189
 
                raise
2190
 
        else:
2191
 
            if sent == 0:
2192
 
                raise errors.ConnectionReset('Sending to %s returned 0 bytes'
2193
 
                                             % (sock,))
2194
 
            sent_total += sent
2195
 
            if report_activity is not None:
2196
 
                report_activity(sent, 'write')
2197
 
 
2198
 
 
2199
 
def connect_socket(address):
2200
 
    # Slight variation of the socket.create_connection() function (provided by
2201
 
    # python-2.6) that can fail if getaddrinfo returns an empty list. We also
2202
 
    # provide it for previous python versions. Also, we don't use the timeout
2203
 
    # parameter (provided by the python implementation) so we don't implement
2204
 
    # it either).
2205
 
    err = socket.error('getaddrinfo returns an empty list')
2206
 
    host, port = address
2207
 
    for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
2208
 
        af, socktype, proto, canonname, sa = res
2209
 
        sock = None
2210
 
        try:
2211
 
            sock = socket.socket(af, socktype, proto)
2212
 
            sock.connect(sa)
2213
 
            return sock
2214
 
 
2215
 
        except socket.error as e:
2216
 
            err = e
2217
 
            # 'err' is now the most recent error
2218
 
            if sock is not None:
2219
 
                sock.close()
2220
 
    raise err
 
1632
    chunk_size = 2**16
 
1633
    for pos in xrange(0, len(bytes), chunk_size):
 
1634
        until_no_eintr(socket.sendall, bytes[pos:pos+chunk_size])
2221
1635
 
2222
1636
 
2223
1637
def dereference_path(path):
2242
1656
def resource_string(package, resource_name):
2243
1657
    """Load a resource from a package and return it as a string.
2244
1658
 
2245
 
    Note: Only packages that start with breezy are currently supported.
 
1659
    Note: Only packages that start with bzrlib are currently supported.
2246
1660
 
2247
1661
    This is designed to be a lightweight implementation of resource
2248
1662
    loading in a way which is API compatible with the same API from
2251
1665
    If and when pkg_resources becomes a standard library, this routine
2252
1666
    can delegate to it.
2253
1667
    """
2254
 
    # Check package name is within breezy
2255
 
    if package == "breezy":
 
1668
    # Check package name is within bzrlib
 
1669
    if package == "bzrlib":
2256
1670
        resource_relpath = resource_name
2257
 
    elif package.startswith("breezy."):
2258
 
        package = package[len("breezy."):].replace('.', os.sep)
 
1671
    elif package.startswith("bzrlib."):
 
1672
        package = package[len("bzrlib."):].replace('.', os.sep)
2259
1673
        resource_relpath = pathjoin(package, resource_name)
2260
1674
    else:
2261
 
        raise errors.BzrError('resource package %s not in breezy' % package)
 
1675
        raise errors.BzrError('resource package %s not in bzrlib' % package)
2262
1676
 
2263
1677
    # Map the resource to a file and read its contents
2264
 
    base = dirname(breezy.__file__)
 
1678
    base = dirname(bzrlib.__file__)
2265
1679
    if getattr(sys, 'frozen', None):    # bzr.exe
2266
1680
        base = abspath(pathjoin(base, '..', '..'))
2267
 
    with open(pathjoin(base, resource_relpath), "rt") as f:
2268
 
        return f.read()
 
1681
    filename = pathjoin(base, resource_relpath)
 
1682
    return open(filename, 'rU').read()
2269
1683
 
2270
1684
 
2271
1685
def file_kind_from_stat_mode_thunk(mode):
2272
1686
    global file_kind_from_stat_mode
2273
1687
    if file_kind_from_stat_mode is file_kind_from_stat_mode_thunk:
2274
1688
        try:
2275
 
            from ._readdir_pyx import UTF8DirReader
 
1689
            from bzrlib._readdir_pyx import UTF8DirReader
2276
1690
            file_kind_from_stat_mode = UTF8DirReader().kind_from_mode
2277
1691
        except ImportError:
2278
 
            # This is one time where we won't warn that an extension failed to
2279
 
            # load. The extension is never available on Windows anyway.
2280
 
            from ._readdir_py import (
 
1692
            from bzrlib._readdir_py import (
2281
1693
                _kind_from_mode as file_kind_from_stat_mode
2282
1694
                )
2283
1695
    return file_kind_from_stat_mode(mode)
2284
 
 
2285
 
 
2286
1696
file_kind_from_stat_mode = file_kind_from_stat_mode_thunk
2287
1697
 
2288
1698
 
2289
 
def file_stat(f, _lstat=os.lstat):
 
1699
def file_kind(f, _lstat=os.lstat):
2290
1700
    try:
2291
 
        # XXX cache?
2292
 
        return _lstat(f)
2293
 
    except OSError as e:
 
1701
        return file_kind_from_stat_mode(_lstat(f).st_mode)
 
1702
    except OSError, e:
2294
1703
        if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
2295
1704
            raise errors.NoSuchFile(f)
2296
1705
        raise
2297
1706
 
2298
1707
 
2299
 
def file_kind(f, _lstat=os.lstat):
2300
 
    stat_value = file_stat(f, _lstat)
2301
 
    return file_kind_from_stat_mode(stat_value.st_mode)
2302
 
 
2303
 
 
2304
1708
def until_no_eintr(f, *a, **kw):
2305
 
    """Run f(*a, **kw), retrying if an EINTR error occurs.
2306
 
 
2307
 
    WARNING: you must be certain that it is safe to retry the call repeatedly
2308
 
    if EINTR does occur.  This is typically only true for low-level operations
2309
 
    like os.read.  If in any doubt, don't use this.
2310
 
 
2311
 
    Keep in mind that this is not a complete solution to EINTR.  There is
2312
 
    probably code in the Python standard library and other dependencies that
2313
 
    may encounter EINTR if a signal arrives (and there is signal handler for
2314
 
    that signal).  So this function can reduce the impact for IO that breezy
2315
 
    directly controls, but it is not a complete solution.
2316
 
    """
 
1709
    """Run f(*a, **kw), retrying if an EINTR error occurs."""
2317
1710
    # Borrowed from Twisted's twisted.python.util.untilConcludes function.
2318
1711
    while True:
2319
1712
        try:
2320
1713
            return f(*a, **kw)
2321
 
        except (IOError, OSError) as e:
 
1714
        except (IOError, OSError), e:
2322
1715
            if e.errno == errno.EINTR:
2323
1716
                continue
2324
1717
            raise
2325
1718
 
2326
1719
 
2327
1720
if sys.platform == "win32":
 
1721
    import msvcrt
2328
1722
    def getchar():
2329
 
        import msvcrt
2330
1723
        return msvcrt.getch()
2331
1724
else:
 
1725
    import tty
 
1726
    import termios
2332
1727
    def getchar():
2333
 
        import tty
2334
 
        import termios
2335
1728
        fd = sys.stdin.fileno()
2336
1729
        settings = termios.tcgetattr(fd)
2337
1730
        try:
2340
1733
        finally:
2341
1734
            termios.tcsetattr(fd, termios.TCSADRAIN, settings)
2342
1735
        return ch
2343
 
 
2344
 
if sys.platform.startswith('linux'):
2345
 
    def _local_concurrency():
2346
 
        try:
2347
 
            return os.sysconf('SC_NPROCESSORS_ONLN')
2348
 
        except (ValueError, OSError, AttributeError):
2349
 
            return None
2350
 
elif sys.platform == 'darwin':
2351
 
    def _local_concurrency():
2352
 
        return subprocess.Popen(['sysctl', '-n', 'hw.availcpu'],
2353
 
                                stdout=subprocess.PIPE).communicate()[0]
2354
 
elif "bsd" in sys.platform:
2355
 
    def _local_concurrency():
2356
 
        return subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
2357
 
                                stdout=subprocess.PIPE).communicate()[0]
2358
 
elif sys.platform == 'sunos5':
2359
 
    def _local_concurrency():
2360
 
        return subprocess.Popen(['psrinfo', '-p', ],
2361
 
                                stdout=subprocess.PIPE).communicate()[0]
2362
 
elif sys.platform == "win32":
2363
 
    def _local_concurrency():
2364
 
        # This appears to return the number of cores.
2365
 
        return os.environ.get('NUMBER_OF_PROCESSORS')
2366
 
else:
2367
 
    def _local_concurrency():
2368
 
        # Who knows ?
2369
 
        return None
2370
 
 
2371
 
 
2372
 
_cached_local_concurrency = None
2373
 
 
2374
 
 
2375
 
def local_concurrency(use_cache=True):
2376
 
    """Return how many processes can be run concurrently.
2377
 
 
2378
 
    Rely on platform specific implementations and default to 1 (one) if
2379
 
    anything goes wrong.
2380
 
    """
2381
 
    global _cached_local_concurrency
2382
 
 
2383
 
    if _cached_local_concurrency is not None and use_cache:
2384
 
        return _cached_local_concurrency
2385
 
 
2386
 
    concurrency = os.environ.get('BRZ_CONCURRENCY', None)
2387
 
    if concurrency is None:
2388
 
        import multiprocessing
2389
 
        try:
2390
 
            concurrency = multiprocessing.cpu_count()
2391
 
        except NotImplementedError:
2392
 
            # multiprocessing.cpu_count() isn't implemented on all platforms
2393
 
            try:
2394
 
                concurrency = _local_concurrency()
2395
 
            except (OSError, IOError):
2396
 
                pass
2397
 
    try:
2398
 
        concurrency = int(concurrency)
2399
 
    except (TypeError, ValueError):
2400
 
        concurrency = 1
2401
 
    if use_cache:
2402
 
        _cached_local_concurrency = concurrency
2403
 
    return concurrency
2404
 
 
2405
 
 
2406
 
class UnicodeOrBytesToBytesWriter(codecs.StreamWriter):
2407
 
    """A stream writer that doesn't decode str arguments."""
2408
 
 
2409
 
    def __init__(self, encode, stream, errors='strict'):
2410
 
        codecs.StreamWriter.__init__(self, stream, errors)
2411
 
        self.encode = encode
2412
 
 
2413
 
    def write(self, object):
2414
 
        if isinstance(object, str):
2415
 
            self.stream.write(object)
2416
 
        else:
2417
 
            data, _ = self.encode(object, self.errors)
2418
 
            self.stream.write(data)
2419
 
 
2420
 
 
2421
 
if sys.platform == 'win32':
2422
 
    def open_file(filename, mode='r', bufsize=-1):
2423
 
        """This function is used to override the ``open`` builtin.
2424
 
 
2425
 
        But it uses O_NOINHERIT flag so the file handle is not inherited by
2426
 
        child processes.  Deleting or renaming a closed file opened with this
2427
 
        function is not blocking child processes.
2428
 
        """
2429
 
        writing = 'w' in mode
2430
 
        appending = 'a' in mode
2431
 
        updating = '+' in mode
2432
 
        binary = 'b' in mode
2433
 
 
2434
 
        flags = O_NOINHERIT
2435
 
        # see http://msdn.microsoft.com/en-us/library/yeby3zcb%28VS.71%29.aspx
2436
 
        # for flags for each modes.
2437
 
        if binary:
2438
 
            flags |= O_BINARY
2439
 
        else:
2440
 
            flags |= O_TEXT
2441
 
 
2442
 
        if writing:
2443
 
            if updating:
2444
 
                flags |= os.O_RDWR
2445
 
            else:
2446
 
                flags |= os.O_WRONLY
2447
 
            flags |= os.O_CREAT | os.O_TRUNC
2448
 
        elif appending:
2449
 
            if updating:
2450
 
                flags |= os.O_RDWR
2451
 
            else:
2452
 
                flags |= os.O_WRONLY
2453
 
            flags |= os.O_CREAT | os.O_APPEND
2454
 
        else:  # reading
2455
 
            if updating:
2456
 
                flags |= os.O_RDWR
2457
 
            else:
2458
 
                flags |= os.O_RDONLY
2459
 
 
2460
 
        return os.fdopen(os.open(filename, flags), mode, bufsize)
2461
 
else:
2462
 
    open_file = open
2463
 
 
2464
 
 
2465
 
def available_backup_name(base, exists):
2466
 
    """Find a non-existing backup file name.
2467
 
 
2468
 
    This will *not* create anything, this only return a 'free' entry.  This
2469
 
    should be used for checking names in a directory below a locked
2470
 
    tree/branch/repo to avoid race conditions. This is LBYL (Look Before You
2471
 
    Leap) and generally discouraged.
2472
 
 
2473
 
    :param base: The base name.
2474
 
 
2475
 
    :param exists: A callable returning True if the path parameter exists.
2476
 
    """
2477
 
    counter = 1
2478
 
    name = "%s.~%d~" % (base, counter)
2479
 
    while exists(name):
2480
 
        counter += 1
2481
 
        name = "%s.~%d~" % (base, counter)
2482
 
    return name
2483
 
 
2484
 
 
2485
 
def set_fd_cloexec(fd):
2486
 
    """Set a Unix file descriptor's FD_CLOEXEC flag.  Do nothing if platform
2487
 
    support for this is not available.
2488
 
    """
2489
 
    try:
2490
 
        import fcntl
2491
 
        old = fcntl.fcntl(fd, fcntl.F_GETFD)
2492
 
        fcntl.fcntl(fd, fcntl.F_SETFD, old | fcntl.FD_CLOEXEC)
2493
 
    except (ImportError, AttributeError):
2494
 
        # Either the fcntl module or specific constants are not present
2495
 
        pass
2496
 
 
2497
 
 
2498
 
def find_executable_on_path(name):
2499
 
    """Finds an executable on the PATH.
2500
 
 
2501
 
    On Windows, this will try to append each extension in the PATHEXT
2502
 
    environment variable to the name, if it cannot be found with the name
2503
 
    as given.
2504
 
 
2505
 
    :param name: The base name of the executable.
2506
 
    :return: The path to the executable found or None.
2507
 
    """
2508
 
    if sys.platform == 'win32':
2509
 
        exts = os.environ.get('PATHEXT', '').split(os.pathsep)
2510
 
        exts = [ext.lower() for ext in exts]
2511
 
        base, ext = os.path.splitext(name)
2512
 
        if ext != '':
2513
 
            if ext.lower() not in exts:
2514
 
                return None
2515
 
            name = base
2516
 
            exts = [ext]
2517
 
    else:
2518
 
        exts = ['']
2519
 
    path = os.environ.get('PATH')
2520
 
    if path is not None:
2521
 
        path = path.split(os.pathsep)
2522
 
        for ext in exts:
2523
 
            for d in path:
2524
 
                f = os.path.join(d, name) + ext
2525
 
                if os.access(f, os.X_OK):
2526
 
                    return f
2527
 
    if sys.platform == 'win32':
2528
 
        app_path = win32utils.get_app_path(name)
2529
 
        if app_path != name:
2530
 
            return app_path
2531
 
    return None
2532
 
 
2533
 
 
2534
 
def _posix_is_local_pid_dead(pid):
2535
 
    """True if pid doesn't correspond to live process on this machine"""
2536
 
    try:
2537
 
        # Special meaning of unix kill: just check if it's there.
2538
 
        os.kill(pid, 0)
2539
 
    except OSError as e:
2540
 
        if e.errno == errno.ESRCH:
2541
 
            # On this machine, and really not found: as sure as we can be
2542
 
            # that it's dead.
2543
 
            return True
2544
 
        elif e.errno == errno.EPERM:
2545
 
            # exists, though not ours
2546
 
            return False
2547
 
        else:
2548
 
            trace.mutter("os.kill(%d, 0) failed: %s" % (pid, e))
2549
 
            # Don't really know.
2550
 
            return False
2551
 
    else:
2552
 
        # Exists and our process: not dead.
2553
 
        return False
2554
 
 
2555
 
 
2556
 
if sys.platform == "win32":
2557
 
    is_local_pid_dead = win32utils.is_local_pid_dead
2558
 
else:
2559
 
    is_local_pid_dead = _posix_is_local_pid_dead
2560
 
 
2561
 
_maybe_ignored = ['EAGAIN', 'EINTR', 'ENOTSUP', 'EOPNOTSUPP', 'EACCES']
2562
 
_fdatasync_ignored = [getattr(errno, name) for name in _maybe_ignored
2563
 
                      if getattr(errno, name, None) is not None]
2564
 
 
2565
 
 
2566
 
def fdatasync(fileno):
2567
 
    """Flush file contents to disk if possible.
2568
 
 
2569
 
    :param fileno: Integer OS file handle.
2570
 
    :raises TransportNotPossible: If flushing to disk is not possible.
2571
 
    """
2572
 
    fn = getattr(os, 'fdatasync', getattr(os, 'fsync', None))
2573
 
    if fn is not None:
2574
 
        try:
2575
 
            fn(fileno)
2576
 
        except IOError as e:
2577
 
            # See bug #1075108, on some platforms fdatasync exists, but can
2578
 
            # raise ENOTSUP. However, we are calling fdatasync to be helpful
2579
 
            # and reduce the chance of corruption-on-powerloss situations. It
2580
 
            # is not a mandatory call, so it is ok to suppress failures.
2581
 
            trace.mutter("ignoring error calling fdatasync: %s" % (e,))
2582
 
            if getattr(e, 'errno', None) not in _fdatasync_ignored:
2583
 
                raise
2584
 
 
2585
 
 
2586
 
def ensure_empty_directory_exists(path, exception_class):
2587
 
    """Make sure a local directory exists and is empty.
2588
 
 
2589
 
    If it does not exist, it is created.  If it exists and is not empty, an
2590
 
    instance of exception_class is raised.
2591
 
    """
2592
 
    try:
2593
 
        os.mkdir(path)
2594
 
    except OSError as e:
2595
 
        if e.errno != errno.EEXIST:
2596
 
            raise
2597
 
        if os.listdir(path) != []:
2598
 
            raise exception_class(path)
2599
 
 
2600
 
 
2601
 
def is_environment_error(evalue):
2602
 
    """True if exception instance is due to a process environment issue
2603
 
 
2604
 
    This includes OSError and IOError, but also other errors that come from
2605
 
    the operating system or core libraries but are not subclasses of those.
2606
 
    """
2607
 
    if isinstance(evalue, (EnvironmentError, select.error)):
2608
 
        return True
2609
 
    if sys.platform == "win32" and win32utils._is_pywintypes_error(evalue):
2610
 
        return True
2611
 
    return False