~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

(vila) Open 2.4.3 for bug fixes (Vincent Ladeuil)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
1
# Copyright (C) 2005-2011 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
 
17
import errno
17
18
import os
18
19
import re
19
20
import stat
20
 
from stat import (S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE,
21
 
                  S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
22
21
import sys
23
22
import time
 
23
import codecs
24
24
 
25
25
from bzrlib.lazy_import import lazy_import
26
26
lazy_import(globals(), """
27
 
import codecs
28
27
from datetime import datetime
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
 
                    )
 
28
import getpass
 
29
import ntpath
36
30
import posixpath
 
31
# We need to import both shutil and rmtree as we export the later on posix
 
32
# and need the former on windows
37
33
import shutil
38
 
from shutil import (
39
 
    rmtree,
40
 
    )
 
34
from shutil import rmtree
 
35
import socket
 
36
import subprocess
 
37
# We need to import both tempfile and mkdtemp as we export the later on posix
 
38
# and need the former on windows
41
39
import tempfile
42
 
from tempfile import (
43
 
    mkdtemp,
44
 
    )
 
40
from tempfile import mkdtemp
45
41
import unicodedata
46
42
 
47
43
from bzrlib import (
48
44
    cache_utf8,
49
45
    errors,
 
46
    trace,
50
47
    win32utils,
51
48
    )
52
49
""")
53
50
 
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
 
        )
 
51
from bzrlib.symbol_versioning import (
 
52
    deprecated_function,
 
53
    deprecated_in,
 
54
    )
 
55
 
 
56
from hashlib import (
 
57
    md5,
 
58
    sha1 as sha,
 
59
    )
66
60
 
67
61
 
68
62
import bzrlib
69
63
from bzrlib import symbol_versioning
70
64
 
71
65
 
 
66
# Cross platform wall-clock time functionality with decent resolution.
 
67
# On Linux ``time.clock`` returns only CPU time. On Windows, ``time.time()``
 
68
# only has a resolution of ~15ms. Note that ``time.clock()`` is not
 
69
# synchronized with ``time.time()``, this is only meant to be used to find
 
70
# delta times by subtracting from another call to this function.
 
71
timer_func = time.time
 
72
if sys.platform == 'win32':
 
73
    timer_func = time.clock
 
74
 
72
75
# On win32, O_BINARY is used to indicate the file should
73
76
# be opened in binary mode, rather than text mode.
74
77
# On other platforms, O_BINARY doesn't exist, because
75
78
# they always open in binary mode, so it is okay to
76
 
# OR with 0 on those platforms
 
79
# OR with 0 on those platforms.
 
80
# O_NOINHERIT and O_TEXT exists only on win32 too.
77
81
O_BINARY = getattr(os, 'O_BINARY', 0)
 
82
O_TEXT = getattr(os, 'O_TEXT', 0)
 
83
O_NOINHERIT = getattr(os, 'O_NOINHERIT', 0)
 
84
 
 
85
 
 
86
def get_unicode_argv():
 
87
    try:
 
88
        user_encoding = get_user_encoding()
 
89
        return [a.decode(user_encoding) for a in sys.argv[1:]]
 
90
    except UnicodeDecodeError:
 
91
        raise errors.BzrError("Parameter %r encoding is unsupported by %s "
 
92
            "application locale." % (a, user_encoding))
78
93
 
79
94
 
80
95
def make_readonly(filename):
97
112
 
98
113
    :param paths: A container (and hence not None) of paths.
99
114
    :return: A set of paths sufficient to include everything in paths via
100
 
        is_inside_any, drawn from the paths parameter.
 
115
        is_inside, drawn from the paths parameter.
101
116
    """
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
 
117
    if len(paths) < 2:
 
118
        return set(paths)
 
119
 
 
120
    def sort_key(path):
 
121
        return path.split('/')
 
122
    sorted_paths = sorted(list(paths), key=sort_key)
 
123
 
 
124
    search_paths = [sorted_paths[0]]
 
125
    for path in sorted_paths[1:]:
 
126
        if not is_inside(search_paths[-1], path):
 
127
            # This path is unique, add it
 
128
            search_paths.append(path)
 
129
 
 
130
    return set(search_paths)
110
131
 
111
132
 
112
133
_QUOTE_RE = None
152
173
    try:
153
174
        return _kind_marker_map[kind]
154
175
    except KeyError:
155
 
        raise errors.BzrError('invalid file kind %r' % kind)
 
176
        # Slightly faster than using .get(, '') when the common case is that
 
177
        # kind will be found
 
178
        return ''
156
179
 
157
180
 
158
181
lexists = getattr(os.path, 'lexists', None)
175
198
    :param old: The old path, to rename from
176
199
    :param new: The new path, to rename to
177
200
    :param rename_func: The potentially non-atomic rename function
178
 
    :param unlink_func: A way to delete the target file if the full rename succeeds
 
201
    :param unlink_func: A way to delete the target file if the full rename
 
202
        succeeds
179
203
    """
180
 
 
181
204
    # sftp rename doesn't allow overwriting, so play tricks:
182
205
    base = os.path.basename(new)
183
206
    dirname = os.path.dirname(new)
184
 
    tmp_name = u'tmp.%s.%.9f.%d.%s' % (base, time.time(), os.getpid(), rand_chars(10))
 
207
    # callers use different encodings for the paths so the following MUST
 
208
    # respect that. We rely on python upcasting to unicode if new is unicode
 
209
    # and keeping a str if not.
 
210
    tmp_name = 'tmp.%s.%.9f.%d.%s' % (base, time.time(),
 
211
                                      os.getpid(), rand_chars(10))
185
212
    tmp_name = pathjoin(dirname, tmp_name)
186
213
 
187
214
    # Rename the file out of the way, but keep track if it didn't exist
207
234
    else:
208
235
        file_existed = True
209
236
 
 
237
    failure_exc = None
210
238
    success = False
211
239
    try:
212
240
        try:
218
246
            # source and target may be aliases of each other (e.g. on a
219
247
            # case-insensitive filesystem), so we may have accidentally renamed
220
248
            # source by when we tried to rename target
221
 
            if not (file_existed and e.errno in (None, errno.ENOENT)):
222
 
                raise
 
249
            failure_exc = sys.exc_info()
 
250
            if (file_existed and e.errno in (None, errno.ENOENT)
 
251
                and old.lower() == new.lower()):
 
252
                # source and target are the same file on a case-insensitive
 
253
                # filesystem, so we don't generate an exception
 
254
                failure_exc = None
223
255
    finally:
224
256
        if file_existed:
225
257
            # If the file used to exist, rename it back into place
228
260
                unlink_func(tmp_name)
229
261
            else:
230
262
                rename_func(tmp_name, new)
 
263
    if failure_exc is not None:
 
264
        try:
 
265
            raise failure_exc[0], failure_exc[1], failure_exc[2]
 
266
        finally:
 
267
            del failure_exc
231
268
 
232
269
 
233
270
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
240
277
    # copy posixpath.abspath, but use os.getcwdu instead
241
278
    if not posixpath.isabs(path):
242
279
        path = posixpath.join(getcwd(), path)
243
 
    return posixpath.normpath(path)
 
280
    return _posix_normpath(path)
244
281
 
245
282
 
246
283
def _posix_realpath(path):
247
284
    return posixpath.realpath(path.encode(_fs_enc)).decode(_fs_enc)
248
285
 
249
286
 
 
287
def _posix_normpath(path):
 
288
    path = posixpath.normpath(path)
 
289
    # Bug 861008: posixpath.normpath() returns a path normalized according to
 
290
    # the POSIX standard, which stipulates (for compatibility reasons) that two
 
291
    # leading slashes must not be simplified to one, and only if there are 3 or
 
292
    # more should they be simplified as one. So we treat the leading 2 slashes
 
293
    # as a special case here by simply removing the first slash, as we consider
 
294
    # that breaking POSIX compatibility for this obscure feature is acceptable.
 
295
    # This is not a paranoid precaution, as we notably get paths like this when
 
296
    # the repo is hosted at the root of the filesystem, i.e. in "/".    
 
297
    if path.startswith('//'):
 
298
        path = path[1:]
 
299
    return path
 
300
 
 
301
 
250
302
def _win32_fixdrive(path):
251
303
    """Force drive letters to be consistent.
252
304
 
256
308
    running python.exe under cmd.exe return capital C:\\
257
309
    running win32 python inside a cygwin shell returns lowercase c:\\
258
310
    """
259
 
    drive, path = _nt_splitdrive(path)
 
311
    drive, path = ntpath.splitdrive(path)
260
312
    return drive.upper() + path
261
313
 
262
314
 
263
315
def _win32_abspath(path):
264
 
    # Real _nt_abspath doesn't have a problem with a unicode cwd
265
 
    return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
 
316
    # Real ntpath.abspath doesn't have a problem with a unicode cwd
 
317
    return _win32_fixdrive(ntpath.abspath(unicode(path)).replace('\\', '/'))
266
318
 
267
319
 
268
320
def _win98_abspath(path):
279
331
    #   /path       => C:/path
280
332
    path = unicode(path)
281
333
    # check for absolute path
282
 
    drive = _nt_splitdrive(path)[0]
 
334
    drive = ntpath.splitdrive(path)[0]
283
335
    if drive == '' and path[:2] not in('//','\\\\'):
284
336
        cwd = os.getcwdu()
285
337
        # we cannot simply os.path.join cwd and path
286
338
        # because os.path.join('C:','/path') produce '/path'
287
339
        # and this is incorrect
288
340
        if path[:1] in ('/','\\'):
289
 
            cwd = _nt_splitdrive(cwd)[0]
 
341
            cwd = ntpath.splitdrive(cwd)[0]
290
342
            path = path[1:]
291
343
        path = cwd + '\\' + path
292
 
    return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
 
344
    return _win32_fixdrive(ntpath.normpath(path).replace('\\', '/'))
293
345
 
294
346
 
295
347
def _win32_realpath(path):
296
 
    # Real _nt_realpath doesn't have a problem with a unicode cwd
297
 
    return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
 
348
    # Real ntpath.realpath doesn't have a problem with a unicode cwd
 
349
    return _win32_fixdrive(ntpath.realpath(unicode(path)).replace('\\', '/'))
298
350
 
299
351
 
300
352
def _win32_pathjoin(*args):
301
 
    return _nt_join(*args).replace('\\', '/')
 
353
    return ntpath.join(*args).replace('\\', '/')
302
354
 
303
355
 
304
356
def _win32_normpath(path):
305
 
    return _win32_fixdrive(_nt_normpath(unicode(path)).replace('\\', '/'))
 
357
    return _win32_fixdrive(ntpath.normpath(unicode(path)).replace('\\', '/'))
306
358
 
307
359
 
308
360
def _win32_getcwd():
340
392
abspath = _posix_abspath
341
393
realpath = _posix_realpath
342
394
pathjoin = os.path.join
343
 
normpath = os.path.normpath
 
395
normpath = _posix_normpath
344
396
getcwd = os.getcwdu
345
397
rename = os.rename
346
398
dirname = os.path.dirname
347
399
basename = os.path.basename
348
400
split = os.path.split
349
401
splitext = os.path.splitext
350
 
# These were already imported into local scope
 
402
# These were already lazily imported into local scope
351
403
# mkdtemp = tempfile.mkdtemp
352
404
# rmtree = shutil.rmtree
 
405
lstat = os.lstat
 
406
fstat = os.fstat
 
407
 
 
408
def wrap_stat(st):
 
409
    return st
 
410
 
353
411
 
354
412
MIN_ABS_PATHLENGTH = 1
355
413
 
365
423
    getcwd = _win32_getcwd
366
424
    mkdtemp = _win32_mkdtemp
367
425
    rename = _win32_rename
 
426
    try:
 
427
        from bzrlib import _walkdirs_win32
 
428
    except ImportError:
 
429
        pass
 
430
    else:
 
431
        lstat = _walkdirs_win32.lstat
 
432
        fstat = _walkdirs_win32.fstat
 
433
        wrap_stat = _walkdirs_win32.wrap_stat
368
434
 
369
435
    MIN_ABS_PATHLENGTH = 3
370
436
 
384
450
    def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
385
451
        """Replacer for shutil.rmtree: could remove readonly dirs/files"""
386
452
        return shutil.rmtree(path, ignore_errors, onerror)
 
453
 
 
454
    f = win32utils.get_unicode_argv     # special function or None
 
455
    if f is not None:
 
456
        get_unicode_argv = f
 
457
 
387
458
elif sys.platform == 'darwin':
388
459
    getcwd = _mac_getcwd
389
460
 
390
461
 
391
 
def get_terminal_encoding():
 
462
def get_terminal_encoding(trace=False):
392
463
    """Find the best encoding for printing to the screen.
393
464
 
394
465
    This attempts to check both sys.stdout and sys.stdin to see
400
471
 
401
472
    On my standard US Windows XP, the preferred encoding is
402
473
    cp1252, but the console is cp437
 
474
 
 
475
    :param trace: If True trace the selected encoding via mutter().
403
476
    """
404
477
    from bzrlib.trace import mutter
405
478
    output_encoding = getattr(sys.stdout, 'encoding', None)
407
480
        input_encoding = getattr(sys.stdin, 'encoding', None)
408
481
        if not input_encoding:
409
482
            output_encoding = get_user_encoding()
410
 
            mutter('encoding stdout as osutils.get_user_encoding() %r',
 
483
            if trace:
 
484
                mutter('encoding stdout as osutils.get_user_encoding() %r',
411
485
                   output_encoding)
412
486
        else:
413
487
            output_encoding = input_encoding
414
 
            mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
 
488
            if trace:
 
489
                mutter('encoding stdout as sys.stdin encoding %r',
 
490
                    output_encoding)
415
491
    else:
416
 
        mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
 
492
        if trace:
 
493
            mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
417
494
    if output_encoding == 'cp0':
418
495
        # invalid encoding (cp0 means 'no codepage' on Windows)
419
496
        output_encoding = get_user_encoding()
420
 
        mutter('cp0 is invalid encoding.'
 
497
        if trace:
 
498
            mutter('cp0 is invalid encoding.'
421
499
               ' encoding stdout as osutils.get_user_encoding() %r',
422
500
               output_encoding)
423
501
    # check encoding
449
527
def isdir(f):
450
528
    """True if f is an accessible directory."""
451
529
    try:
452
 
        return S_ISDIR(os.lstat(f)[ST_MODE])
 
530
        return stat.S_ISDIR(os.lstat(f)[stat.ST_MODE])
453
531
    except OSError:
454
532
        return False
455
533
 
457
535
def isfile(f):
458
536
    """True if f is a regular file."""
459
537
    try:
460
 
        return S_ISREG(os.lstat(f)[ST_MODE])
 
538
        return stat.S_ISREG(os.lstat(f)[stat.ST_MODE])
461
539
    except OSError:
462
540
        return False
463
541
 
464
542
def islink(f):
465
543
    """True if f is a symlink."""
466
544
    try:
467
 
        return S_ISLNK(os.lstat(f)[ST_MODE])
 
545
        return stat.S_ISLNK(os.lstat(f)[stat.ST_MODE])
468
546
    except OSError:
469
547
        return False
470
548
 
597
675
    return s.hexdigest()
598
676
 
599
677
 
 
678
def size_sha_file(f):
 
679
    """Calculate the size and hexdigest of an open file.
 
680
 
 
681
    The file cursor should be already at the start and
 
682
    the caller is responsible for closing the file afterwards.
 
683
    """
 
684
    size = 0
 
685
    s = sha()
 
686
    BUFSIZE = 128<<10
 
687
    while True:
 
688
        b = f.read(BUFSIZE)
 
689
        if not b:
 
690
            break
 
691
        size += len(b)
 
692
        s.update(b)
 
693
    return size, s.hexdigest()
 
694
 
 
695
 
600
696
def sha_file_by_name(fname):
601
697
    """Calculate the SHA1 of a file by reading the full text"""
602
698
    s = sha()
603
 
    f = os.open(fname, os.O_RDONLY | O_BINARY)
 
699
    f = os.open(fname, os.O_RDONLY | O_BINARY | O_NOINHERIT)
604
700
    try:
605
701
        while True:
606
702
            b = os.read(f, 1<<16)
648
744
    return offset.days * 86400 + offset.seconds
649
745
 
650
746
weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
 
747
_default_format_by_weekday_num = [wd + " %Y-%m-%d %H:%M:%S" for wd in weekdays]
 
748
 
651
749
 
652
750
def format_date(t, offset=0, timezone='original', date_fmt=None,
653
751
                show_offset=True):
667
765
    date_str = time.strftime(date_fmt, tt)
668
766
    return date_str + offset_str
669
767
 
 
768
 
 
769
# Cache of formatted offset strings
 
770
_offset_cache = {}
 
771
 
 
772
 
 
773
def format_date_with_offset_in_original_timezone(t, offset=0,
 
774
    _cache=_offset_cache):
 
775
    """Return a formatted date string in the original timezone.
 
776
 
 
777
    This routine may be faster then format_date.
 
778
 
 
779
    :param t: Seconds since the epoch.
 
780
    :param offset: Timezone offset in seconds east of utc.
 
781
    """
 
782
    if offset is None:
 
783
        offset = 0
 
784
    tt = time.gmtime(t + offset)
 
785
    date_fmt = _default_format_by_weekday_num[tt[6]]
 
786
    date_str = time.strftime(date_fmt, tt)
 
787
    offset_str = _cache.get(offset, None)
 
788
    if offset_str is None:
 
789
        offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
 
790
        _cache[offset] = offset_str
 
791
    return date_str + offset_str
 
792
 
 
793
 
670
794
def format_local_date(t, offset=0, timezone='original', date_fmt=None,
671
795
                      show_offset=True):
672
796
    """Return an unicode date string formatted according to the current locale.
683
807
               _format_date(t, offset, timezone, date_fmt, show_offset)
684
808
    date_str = time.strftime(date_fmt, tt)
685
809
    if not isinstance(date_str, unicode):
686
 
        date_str = date_str.decode(bzrlib.user_encoding, 'replace')
 
810
        date_str = date_str.decode(get_user_encoding(), 'replace')
687
811
    return date_str + offset_str
688
812
 
 
813
 
689
814
def _format_date(t, offset, timezone, date_fmt, show_offset):
690
815
    if timezone == 'utc':
691
816
        tt = time.gmtime(t)
763
888
 
764
889
def filesize(f):
765
890
    """Return size of given open file."""
766
 
    return os.fstat(f.fileno())[ST_SIZE]
 
891
    return os.fstat(f.fileno())[stat.ST_SIZE]
767
892
 
768
893
 
769
894
# Define rand_bytes based on platform.
829
954
    return pathjoin(*p)
830
955
 
831
956
 
 
957
def parent_directories(filename):
 
958
    """Return the list of parent directories, deepest first.
 
959
 
 
960
    For example, parent_directories("a/b/c") -> ["a/b", "a"].
 
961
    """
 
962
    parents = []
 
963
    parts = splitpath(dirname(filename))
 
964
    while parts:
 
965
        parents.append(joinpath(parts))
 
966
        parts.pop()
 
967
    return parents
 
968
 
 
969
 
 
970
_extension_load_failures = []
 
971
 
 
972
 
 
973
def failed_to_load_extension(exception):
 
974
    """Handle failing to load a binary extension.
 
975
 
 
976
    This should be called from the ImportError block guarding the attempt to
 
977
    import the native extension.  If this function returns, the pure-Python
 
978
    implementation should be loaded instead::
 
979
 
 
980
    >>> try:
 
981
    >>>     import bzrlib._fictional_extension_pyx
 
982
    >>> except ImportError, e:
 
983
    >>>     bzrlib.osutils.failed_to_load_extension(e)
 
984
    >>>     import bzrlib._fictional_extension_py
 
985
    """
 
986
    # NB: This docstring is just an example, not a doctest, because doctest
 
987
    # currently can't cope with the use of lazy imports in this namespace --
 
988
    # mbp 20090729
 
989
 
 
990
    # This currently doesn't report the failure at the time it occurs, because
 
991
    # they tend to happen very early in startup when we can't check config
 
992
    # files etc, and also we want to report all failures but not spam the user
 
993
    # with 10 warnings.
 
994
    exception_str = str(exception)
 
995
    if exception_str not in _extension_load_failures:
 
996
        trace.mutter("failed to load compiled extension: %s" % exception_str)
 
997
        _extension_load_failures.append(exception_str)
 
998
 
 
999
 
 
1000
def report_extension_load_failures():
 
1001
    if not _extension_load_failures:
 
1002
        return
 
1003
    from bzrlib.config import GlobalConfig
 
1004
    if GlobalConfig().get_user_option_as_bool('ignore_missing_extensions'):
 
1005
        return
 
1006
    # the warnings framework should by default show this only once
 
1007
    from bzrlib.trace import warning
 
1008
    warning(
 
1009
        "bzr: warning: some compiled extensions could not be loaded; "
 
1010
        "see <https://answers.launchpad.net/bzr/+faq/703>")
 
1011
    # we no longer show the specific missing extensions here, because it makes
 
1012
    # the message too long and scary - see
 
1013
    # https://bugs.launchpad.net/bzr/+bug/430529
 
1014
 
 
1015
 
832
1016
try:
833
1017
    from bzrlib._chunks_to_lines_pyx import chunks_to_lines
834
 
except ImportError:
 
1018
except ImportError, e:
 
1019
    failed_to_load_extension(e)
835
1020
    from bzrlib._chunks_to_lines_py import chunks_to_lines
836
1021
 
837
1022
 
875
1060
        shutil.copyfile(src, dest)
876
1061
 
877
1062
 
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.
883
1063
def delete_any(path):
884
 
    """Delete a file or directory."""
 
1064
    """Delete a file, symlink or directory.
 
1065
 
 
1066
    Will delete even if readonly.
 
1067
    """
 
1068
    try:
 
1069
       _delete_file_or_dir(path)
 
1070
    except (OSError, IOError), e:
 
1071
        if e.errno in (errno.EPERM, errno.EACCES):
 
1072
            # make writable and try again
 
1073
            try:
 
1074
                make_writable(path)
 
1075
            except (OSError, IOError):
 
1076
                pass
 
1077
            _delete_file_or_dir(path)
 
1078
        else:
 
1079
            raise
 
1080
 
 
1081
 
 
1082
def _delete_file_or_dir(path):
 
1083
    # Look Before You Leap (LBYL) is appropriate here instead of Easier to Ask for
 
1084
    # Forgiveness than Permission (EAFP) because:
 
1085
    # - root can damage a solaris file system by using unlink,
 
1086
    # - unlink raises different exceptions on different OSes (linux: EISDIR, win32:
 
1087
    #   EACCES, OSX: EPERM) when invoked on a directory.
885
1088
    if isdir(path): # Takes care of symlinks
886
1089
        os.rmdir(path)
887
1090
    else:
907
1110
            and sys.platform not in ('cygwin', 'win32'))
908
1111
 
909
1112
 
 
1113
def readlink(abspath):
 
1114
    """Return a string representing the path to which the symbolic link points.
 
1115
 
 
1116
    :param abspath: The link absolute unicode path.
 
1117
 
 
1118
    This his guaranteed to return the symbolic link in unicode in all python
 
1119
    versions.
 
1120
    """
 
1121
    link = abspath.encode(_fs_enc)
 
1122
    target = os.readlink(link)
 
1123
    target = target.decode(_fs_enc)
 
1124
    return target
 
1125
 
 
1126
 
910
1127
def contains_whitespace(s):
911
1128
    """True if there are any whitespace characters in s."""
912
1129
    # string.whitespace can include '\xa0' in certain locales, because it is
937
1154
 
938
1155
 
939
1156
def relpath(base, path):
940
 
    """Return path relative to base, or raise exception.
 
1157
    """Return path relative to base, or raise PathNotChild exception.
941
1158
 
942
1159
    The path may be either an absolute path or a path relative to the
943
1160
    current working directory.
945
1162
    os.path.commonprefix (python2.4) has a bad bug that it works just
946
1163
    on string prefixes, assuming that '/u' is a prefix of '/u2'.  This
947
1164
    avoids that problem.
 
1165
 
 
1166
    NOTE: `base` should not have a trailing slash otherwise you'll get
 
1167
    PathNotChild exceptions regardless of `path`.
948
1168
    """
949
1169
 
950
1170
    if len(base) < MIN_ABS_PATHLENGTH:
956
1176
 
957
1177
    s = []
958
1178
    head = rp
959
 
    while len(head) >= len(base):
 
1179
    while True:
 
1180
        if len(head) <= len(base) and head != base:
 
1181
            raise errors.PathNotChild(rp, base)
960
1182
        if head == base:
961
1183
            break
962
 
        head, tail = os.path.split(head)
 
1184
        head, tail = split(head)
963
1185
        if tail:
964
 
            s.insert(0, tail)
965
 
    else:
966
 
        raise errors.PathNotChild(rp, base)
 
1186
            s.append(tail)
967
1187
 
968
1188
    if s:
969
 
        return pathjoin(*s)
 
1189
        return pathjoin(*reversed(s))
970
1190
    else:
971
1191
        return ''
972
1192
 
999
1219
    bit_iter = iter(rel.split('/'))
1000
1220
    for bit in bit_iter:
1001
1221
        lbit = bit.lower()
1002
 
        for look in _listdir(current):
 
1222
        try:
 
1223
            next_entries = _listdir(current)
 
1224
        except OSError: # enoent, eperm, etc
 
1225
            # We can't find this in the filesystem, so just append the
 
1226
            # remaining bits.
 
1227
            current = pathjoin(current, bit, *list(bit_iter))
 
1228
            break
 
1229
        for look in next_entries:
1003
1230
            if lbit == look.lower():
1004
1231
                current = pathjoin(current, look)
1005
1232
                break
1009
1236
            # the target of a move, for example).
1010
1237
            current = pathjoin(current, bit, *list(bit_iter))
1011
1238
            break
1012
 
    return current[len(abs_base)+1:]
 
1239
    return current[len(abs_base):].lstrip('/')
1013
1240
 
1014
1241
# XXX - TODO - we need better detection/integration of case-insensitive
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":
 
1242
# file-systems; Linux often sees FAT32 devices (or NFS-mounted OSX
 
1243
# filesystems), for example, so could probably benefit from the same basic
 
1244
# support there.  For now though, only Windows and OSX get that support, and
 
1245
# they get it for *all* file-systems!
 
1246
if sys.platform in ('win32', 'darwin'):
1019
1247
    canonical_relpath = _cicp_canonical_relpath
1020
1248
else:
1021
1249
    canonical_relpath = relpath
1029
1257
    # but for now, we haven't optimized...
1030
1258
    return [canonical_relpath(base, p) for p in paths]
1031
1259
 
 
1260
 
 
1261
def decode_filename(filename):
 
1262
    """Decode the filename using the filesystem encoding
 
1263
 
 
1264
    If it is unicode, it is returned.
 
1265
    Otherwise it is decoded from the the filesystem's encoding. If decoding
 
1266
    fails, a errors.BadFilenameEncoding exception is raised.
 
1267
    """
 
1268
    if type(filename) is unicode:
 
1269
        return filename
 
1270
    try:
 
1271
        return filename.decode(_fs_enc)
 
1272
    except UnicodeDecodeError:
 
1273
        raise errors.BadFilenameEncoding(filename, _fs_enc)
 
1274
 
 
1275
 
1032
1276
def safe_unicode(unicode_or_utf8_string):
1033
1277
    """Coerce unicode_or_utf8_string into unicode.
1034
1278
 
1035
1279
    If it is unicode, it is returned.
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.
 
1280
    Otherwise it is decoded from utf-8. If decoding fails, the exception is
 
1281
    wrapped in a BzrBadParameterNotUnicode exception.
1039
1282
    """
1040
1283
    if isinstance(unicode_or_utf8_string, unicode):
1041
1284
        return unicode_or_utf8_string
1118
1361
def normalizes_filenames():
1119
1362
    """Return True if this platform normalizes unicode filenames.
1120
1363
 
1121
 
    Mac OSX does, Windows/Linux do not.
 
1364
    Only Mac OSX.
1122
1365
    """
1123
1366
    return _platform_normalizes_filenames
1124
1367
 
1129
1372
    On platforms where the system normalizes filenames (Mac OSX),
1130
1373
    you can access a file by any path which will normalize correctly.
1131
1374
    On platforms where the system does not normalize filenames
1132
 
    (Windows, Linux), you have to access a file by its exact path.
 
1375
    (everything else), you have to access a file by its exact path.
1133
1376
 
1134
1377
    Internally, bzr only supports NFC normalization, since that is
1135
1378
    the standard for XML documents.
1154
1397
    normalized_filename = _inaccessible_normalized_filename
1155
1398
 
1156
1399
 
 
1400
def set_signal_handler(signum, handler, restart_syscall=True):
 
1401
    """A wrapper for signal.signal that also calls siginterrupt(signum, False)
 
1402
    on platforms that support that.
 
1403
 
 
1404
    :param restart_syscall: if set, allow syscalls interrupted by a signal to
 
1405
        automatically restart (by calling `signal.siginterrupt(signum,
 
1406
        False)`).  May be ignored if the feature is not available on this
 
1407
        platform or Python version.
 
1408
    """
 
1409
    try:
 
1410
        import signal
 
1411
        siginterrupt = signal.siginterrupt
 
1412
    except ImportError:
 
1413
        # This python implementation doesn't provide signal support, hence no
 
1414
        # handler exists
 
1415
        return None
 
1416
    except AttributeError:
 
1417
        # siginterrupt doesn't exist on this platform, or for this version
 
1418
        # of Python.
 
1419
        siginterrupt = lambda signum, flag: None
 
1420
    if restart_syscall:
 
1421
        def sig_handler(*args):
 
1422
            # Python resets the siginterrupt flag when a signal is
 
1423
            # received.  <http://bugs.python.org/issue8354>
 
1424
            # As a workaround for some cases, set it back the way we want it.
 
1425
            siginterrupt(signum, False)
 
1426
            # Now run the handler function passed to set_signal_handler.
 
1427
            handler(*args)
 
1428
    else:
 
1429
        sig_handler = handler
 
1430
    old_handler = signal.signal(signum, sig_handler)
 
1431
    if restart_syscall:
 
1432
        siginterrupt(signum, False)
 
1433
    return old_handler
 
1434
 
 
1435
 
 
1436
default_terminal_width = 80
 
1437
"""The default terminal width for ttys.
 
1438
 
 
1439
This is defined so that higher levels can share a common fallback value when
 
1440
terminal_width() returns None.
 
1441
"""
 
1442
 
 
1443
# Keep some state so that terminal_width can detect if _terminal_size has
 
1444
# returned a different size since the process started.  See docstring and
 
1445
# comments of terminal_width for details.
 
1446
# _terminal_size_state has 3 possible values: no_data, unchanged, and changed.
 
1447
_terminal_size_state = 'no_data'
 
1448
_first_terminal_size = None
 
1449
 
1157
1450
def terminal_width():
1158
 
    """Return estimated terminal width."""
1159
 
    if sys.platform == 'win32':
1160
 
        return win32utils.get_console_size()[0]
1161
 
    width = 0
 
1451
    """Return terminal width.
 
1452
 
 
1453
    None is returned if the width can't established precisely.
 
1454
 
 
1455
    The rules are:
 
1456
    - if BZR_COLUMNS is set, returns its value
 
1457
    - if there is no controlling terminal, returns None
 
1458
    - query the OS, if the queried size has changed since the last query,
 
1459
      return its value,
 
1460
    - if COLUMNS is set, returns its value,
 
1461
    - if the OS has a value (even though it's never changed), return its value.
 
1462
 
 
1463
    From there, we need to query the OS to get the size of the controlling
 
1464
    terminal.
 
1465
 
 
1466
    On Unices we query the OS by:
 
1467
    - get termios.TIOCGWINSZ
 
1468
    - if an error occurs or a negative value is obtained, returns None
 
1469
 
 
1470
    On Windows we query the OS by:
 
1471
    - win32utils.get_console_size() decides,
 
1472
    - returns None on error (provided default value)
 
1473
    """
 
1474
    # Note to implementors: if changing the rules for determining the width,
 
1475
    # make sure you've considered the behaviour in these cases:
 
1476
    #  - M-x shell in emacs, where $COLUMNS is set and TIOCGWINSZ returns 0,0.
 
1477
    #  - bzr log | less, in bash, where $COLUMNS not set and TIOCGWINSZ returns
 
1478
    #    0,0.
 
1479
    #  - (add more interesting cases here, if you find any)
 
1480
    # Some programs implement "Use $COLUMNS (if set) until SIGWINCH occurs",
 
1481
    # but we don't want to register a signal handler because it is impossible
 
1482
    # to do so without risking EINTR errors in Python <= 2.6.5 (see
 
1483
    # <http://bugs.python.org/issue8354>).  Instead we check TIOCGWINSZ every
 
1484
    # time so we can notice if the reported size has changed, which should have
 
1485
    # a similar effect.
 
1486
 
 
1487
    # If BZR_COLUMNS is set, take it, user is always right
 
1488
    # Except if they specified 0 in which case, impose no limit here
 
1489
    try:
 
1490
        width = int(os.environ['BZR_COLUMNS'])
 
1491
    except (KeyError, ValueError):
 
1492
        width = None
 
1493
    if width is not None:
 
1494
        if width > 0:
 
1495
            return width
 
1496
        else:
 
1497
            return None
 
1498
 
 
1499
    isatty = getattr(sys.stdout, 'isatty', None)
 
1500
    if isatty is None or not isatty():
 
1501
        # Don't guess, setting BZR_COLUMNS is the recommended way to override.
 
1502
        return None
 
1503
 
 
1504
    # Query the OS
 
1505
    width, height = os_size = _terminal_size(None, None)
 
1506
    global _first_terminal_size, _terminal_size_state
 
1507
    if _terminal_size_state == 'no_data':
 
1508
        _first_terminal_size = os_size
 
1509
        _terminal_size_state = 'unchanged'
 
1510
    elif (_terminal_size_state == 'unchanged' and
 
1511
          _first_terminal_size != os_size):
 
1512
        _terminal_size_state = 'changed'
 
1513
 
 
1514
    # If the OS claims to know how wide the terminal is, and this value has
 
1515
    # ever changed, use that.
 
1516
    if _terminal_size_state == 'changed':
 
1517
        if width is not None and width > 0:
 
1518
            return width
 
1519
 
 
1520
    # If COLUMNS is set, use it.
 
1521
    try:
 
1522
        return int(os.environ['COLUMNS'])
 
1523
    except (KeyError, ValueError):
 
1524
        pass
 
1525
 
 
1526
    # Finally, use an unchanged size from the OS, if we have one.
 
1527
    if _terminal_size_state == 'unchanged':
 
1528
        if width is not None and width > 0:
 
1529
            return width
 
1530
 
 
1531
    # The width could not be determined.
 
1532
    return None
 
1533
 
 
1534
 
 
1535
def _win32_terminal_size(width, height):
 
1536
    width, height = win32utils.get_console_size(defaultx=width, defaulty=height)
 
1537
    return width, height
 
1538
 
 
1539
 
 
1540
def _ioctl_terminal_size(width, height):
1162
1541
    try:
1163
1542
        import struct, fcntl, termios
1164
1543
        s = struct.pack('HHHH', 0, 0, 0, 0)
1165
1544
        x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
1166
 
        width = struct.unpack('HHHH', x)[1]
1167
 
    except IOError:
 
1545
        height, width = struct.unpack('HHHH', x)[0:2]
 
1546
    except (IOError, AttributeError):
1168
1547
        pass
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
 
1548
    return width, height
 
1549
 
 
1550
_terminal_size = None
 
1551
"""Returns the terminal size as (width, height).
 
1552
 
 
1553
:param width: Default value for width.
 
1554
:param height: Default value for height.
 
1555
 
 
1556
This is defined specifically for each OS and query the size of the controlling
 
1557
terminal. If any error occurs, the provided default values should be returned.
 
1558
"""
 
1559
if sys.platform == 'win32':
 
1560
    _terminal_size = _win32_terminal_size
 
1561
else:
 
1562
    _terminal_size = _ioctl_terminal_size
1178
1563
 
1179
1564
 
1180
1565
def supports_executable():
1305
1690
        dirblock = []
1306
1691
        append = dirblock.append
1307
1692
        try:
1308
 
            names = sorted(_listdir(top))
 
1693
            names = sorted(map(decode_filename, _listdir(top)))
1309
1694
        except OSError, e:
1310
1695
            if not _is_error_enotdir(e):
1311
1696
                raise
1374
1759
            #       for win98 anyway.
1375
1760
            try:
1376
1761
                from bzrlib._walkdirs_win32 import Win32ReadDir
1377
 
            except ImportError:
1378
 
                _selected_dir_reader = UnicodeDirReader()
1379
 
            else:
1380
1762
                _selected_dir_reader = Win32ReadDir()
1381
 
        elif fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
 
1763
            except ImportError:
 
1764
                pass
 
1765
        elif fs_encoding in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
1382
1766
            # ANSI_X3.4-1968 is a form of ASCII
1383
 
            _selected_dir_reader = UnicodeDirReader()
1384
 
        else:
1385
1767
            try:
1386
1768
                from bzrlib._readdir_pyx import UTF8DirReader
1387
 
            except ImportError:
1388
 
                # No optimised code path
1389
 
                _selected_dir_reader = UnicodeDirReader()
1390
 
            else:
1391
1769
                _selected_dir_reader = UTF8DirReader()
 
1770
            except ImportError, e:
 
1771
                failed_to_load_extension(e)
 
1772
                pass
 
1773
 
 
1774
    if _selected_dir_reader is None:
 
1775
        # Fallback to the python version
 
1776
        _selected_dir_reader = UnicodeDirReader()
 
1777
 
1392
1778
    # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1393
1779
    # But we don't actually uses 1-3 in pending, so set them to None
1394
1780
    pending = [[_selected_dir_reader.top_prefix_to_starting_dir(top, prefix)]]
1499
1885
            real_handlers[kind](abspath, relpath)
1500
1886
 
1501
1887
 
 
1888
def copy_ownership_from_path(dst, src=None):
 
1889
    """Copy usr/grp ownership from src file/dir to dst file/dir.
 
1890
 
 
1891
    If src is None, the containing directory is used as source. If chown
 
1892
    fails, the error is ignored and a warning is printed.
 
1893
    """
 
1894
    chown = getattr(os, 'chown', None)
 
1895
    if chown is None:
 
1896
        return
 
1897
 
 
1898
    if src == None:
 
1899
        src = os.path.dirname(dst)
 
1900
        if src == '':
 
1901
            src = '.'
 
1902
 
 
1903
    try:
 
1904
        s = os.stat(src)
 
1905
        chown(dst, s.st_uid, s.st_gid)
 
1906
    except OSError, e:
 
1907
        trace.warning(
 
1908
            'Unable to copy ownership from "%s" to "%s". '
 
1909
            'You may want to set it manually.', src, dst)
 
1910
        trace.log_exception_quietly()
 
1911
 
 
1912
 
1502
1913
def path_prefix_key(path):
1503
1914
    """Generate a prefix-order path key for path.
1504
1915
 
1590
2001
    return user_encoding
1591
2002
 
1592
2003
 
 
2004
def get_diff_header_encoding():
 
2005
    return get_terminal_encoding()
 
2006
 
 
2007
 
1593
2008
def get_host_name():
1594
2009
    """Return the current unicode host name.
1595
2010
 
1604
2019
        return socket.gethostname().decode(get_user_encoding())
1605
2020
 
1606
2021
 
1607
 
def recv_all(socket, bytes):
 
2022
# We must not read/write any more than 64k at a time from/to a socket so we
 
2023
# don't risk "no buffer space available" errors on some platforms.  Windows in
 
2024
# particular is likely to throw WSAECONNABORTED or WSAENOBUFS if given too much
 
2025
# data at once.
 
2026
MAX_SOCKET_CHUNK = 64 * 1024
 
2027
 
 
2028
_end_of_stream_errors = [errno.ECONNRESET]
 
2029
for _eno in ['WSAECONNRESET', 'WSAECONNABORTED']:
 
2030
    _eno = getattr(errno, _eno, None)
 
2031
    if _eno is not None:
 
2032
        _end_of_stream_errors.append(_eno)
 
2033
del _eno
 
2034
 
 
2035
 
 
2036
def read_bytes_from_socket(sock, report_activity=None,
 
2037
        max_read_size=MAX_SOCKET_CHUNK):
 
2038
    """Read up to max_read_size of bytes from sock and notify of progress.
 
2039
 
 
2040
    Translates "Connection reset by peer" into file-like EOF (return an
 
2041
    empty string rather than raise an error), and repeats the recv if
 
2042
    interrupted by a signal.
 
2043
    """
 
2044
    while 1:
 
2045
        try:
 
2046
            bytes = sock.recv(max_read_size)
 
2047
        except socket.error, e:
 
2048
            eno = e.args[0]
 
2049
            if eno in _end_of_stream_errors:
 
2050
                # The connection was closed by the other side.  Callers expect
 
2051
                # an empty string to signal end-of-stream.
 
2052
                return ""
 
2053
            elif eno == errno.EINTR:
 
2054
                # Retry the interrupted recv.
 
2055
                continue
 
2056
            raise
 
2057
        else:
 
2058
            if report_activity is not None:
 
2059
                report_activity(len(bytes), 'read')
 
2060
            return bytes
 
2061
 
 
2062
 
 
2063
def recv_all(socket, count):
1608
2064
    """Receive an exact number of bytes.
1609
2065
 
1610
2066
    Regular Socket.recv() may return less than the requested number of bytes,
1611
 
    dependning on what's in the OS buffer.  MSG_WAITALL is not available
 
2067
    depending on what's in the OS buffer.  MSG_WAITALL is not available
1612
2068
    on all platforms, but this should work everywhere.  This will return
1613
2069
    less than the requested amount if the remote end closes.
1614
2070
 
1615
2071
    This isn't optimized and is intended mostly for use in testing.
1616
2072
    """
1617
2073
    b = ''
1618
 
    while len(b) < bytes:
1619
 
        new = until_no_eintr(socket.recv, bytes - len(b))
 
2074
    while len(b) < count:
 
2075
        new = read_bytes_from_socket(socket, None, count - len(b))
1620
2076
        if new == '':
1621
2077
            break # eof
1622
2078
        b += new
1623
2079
    return b
1624
2080
 
1625
2081
 
1626
 
def send_all(socket, bytes, report_activity=None):
 
2082
def send_all(sock, bytes, report_activity=None):
1627
2083
    """Send all bytes on a socket.
1628
2084
 
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.
 
2085
    Breaks large blocks in smaller chunks to avoid buffering limitations on
 
2086
    some platforms, and catches EINTR which may be thrown if the send is
 
2087
    interrupted by a signal.
 
2088
 
 
2089
    This is preferred to socket.sendall(), because it avoids portability bugs
 
2090
    and provides activity reporting.
1631
2091
 
1632
2092
    :param report_activity: Call this as bytes are read, see
1633
2093
        Transport._report_activity
1634
2094
    """
1635
 
    chunk_size = 2**16
1636
 
    for pos in xrange(0, len(bytes), chunk_size):
1637
 
        block = bytes[pos:pos+chunk_size]
1638
 
        if report_activity is not None:
1639
 
            report_activity(len(block), 'write')
1640
 
        until_no_eintr(socket.sendall, block)
 
2095
    sent_total = 0
 
2096
    byte_count = len(bytes)
 
2097
    while sent_total < byte_count:
 
2098
        try:
 
2099
            sent = sock.send(buffer(bytes, sent_total, MAX_SOCKET_CHUNK))
 
2100
        except socket.error, e:
 
2101
            if e.args[0] != errno.EINTR:
 
2102
                raise
 
2103
        else:
 
2104
            sent_total += sent
 
2105
            report_activity(sent, 'write')
 
2106
 
 
2107
 
 
2108
def connect_socket(address):
 
2109
    # Slight variation of the socket.create_connection() function (provided by
 
2110
    # python-2.6) that can fail if getaddrinfo returns an empty list. We also
 
2111
    # provide it for previous python versions. Also, we don't use the timeout
 
2112
    # parameter (provided by the python implementation) so we don't implement
 
2113
    # it either).
 
2114
    err = socket.error('getaddrinfo returns an empty list')
 
2115
    host, port = address
 
2116
    for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
 
2117
        af, socktype, proto, canonname, sa = res
 
2118
        sock = None
 
2119
        try:
 
2120
            sock = socket.socket(af, socktype, proto)
 
2121
            sock.connect(sa)
 
2122
            return sock
 
2123
 
 
2124
        except socket.error, err:
 
2125
            # 'err' is now the most recent error
 
2126
            if sock is not None:
 
2127
                sock.close()
 
2128
    raise err
1641
2129
 
1642
2130
 
1643
2131
def dereference_path(path):
1684
2172
    base = dirname(bzrlib.__file__)
1685
2173
    if getattr(sys, 'frozen', None):    # bzr.exe
1686
2174
        base = abspath(pathjoin(base, '..', '..'))
1687
 
    filename = pathjoin(base, resource_relpath)
1688
 
    return open(filename, 'rU').read()
1689
 
 
 
2175
    f = file(pathjoin(base, resource_relpath), "rU")
 
2176
    try:
 
2177
        return f.read()
 
2178
    finally:
 
2179
        f.close()
1690
2180
 
1691
2181
def file_kind_from_stat_mode_thunk(mode):
1692
2182
    global file_kind_from_stat_mode
1694
2184
        try:
1695
2185
            from bzrlib._readdir_pyx import UTF8DirReader
1696
2186
            file_kind_from_stat_mode = UTF8DirReader().kind_from_mode
1697
 
        except ImportError:
 
2187
        except ImportError, e:
 
2188
            # This is one time where we won't warn that an extension failed to
 
2189
            # load. The extension is never available on Windows anyway.
1698
2190
            from bzrlib._readdir_py import (
1699
2191
                _kind_from_mode as file_kind_from_stat_mode
1700
2192
                )
1712
2204
 
1713
2205
 
1714
2206
def until_no_eintr(f, *a, **kw):
1715
 
    """Run f(*a, **kw), retrying if an EINTR error occurs."""
 
2207
    """Run f(*a, **kw), retrying if an EINTR error occurs.
 
2208
 
 
2209
    WARNING: you must be certain that it is safe to retry the call repeatedly
 
2210
    if EINTR does occur.  This is typically only true for low-level operations
 
2211
    like os.read.  If in any doubt, don't use this.
 
2212
 
 
2213
    Keep in mind that this is not a complete solution to EINTR.  There is
 
2214
    probably code in the Python standard library and other dependencies that
 
2215
    may encounter EINTR if a signal arrives (and there is signal handler for
 
2216
    that signal).  So this function can reduce the impact for IO that bzrlib
 
2217
    directly controls, but it is not a complete solution.
 
2218
    """
1716
2219
    # Borrowed from Twisted's twisted.python.util.untilConcludes function.
1717
2220
    while True:
1718
2221
        try:
1723
2226
            raise
1724
2227
 
1725
2228
 
 
2229
@deprecated_function(deprecated_in((2, 2, 0)))
 
2230
def re_compile_checked(re_string, flags=0, where=""):
 
2231
    """Return a compiled re, or raise a sensible error.
 
2232
 
 
2233
    This should only be used when compiling user-supplied REs.
 
2234
 
 
2235
    :param re_string: Text form of regular expression.
 
2236
    :param flags: eg re.IGNORECASE
 
2237
    :param where: Message explaining to the user the context where
 
2238
        it occurred, eg 'log search filter'.
 
2239
    """
 
2240
    # from https://bugs.launchpad.net/bzr/+bug/251352
 
2241
    try:
 
2242
        re_obj = re.compile(re_string, flags)
 
2243
        re_obj.search("")
 
2244
        return re_obj
 
2245
    except errors.InvalidPattern, e:
 
2246
        if where:
 
2247
            where = ' in ' + where
 
2248
        # despite the name 'error' is a type
 
2249
        raise errors.BzrCommandError('Invalid regular expression%s: %s'
 
2250
            % (where, e.msg))
 
2251
 
 
2252
 
1726
2253
if sys.platform == "win32":
1727
2254
    import msvcrt
1728
2255
    def getchar():
1739
2266
        finally:
1740
2267
            termios.tcsetattr(fd, termios.TCSADRAIN, settings)
1741
2268
        return ch
 
2269
 
 
2270
if sys.platform == 'linux2':
 
2271
    def _local_concurrency():
 
2272
        try:
 
2273
            return os.sysconf('SC_NPROCESSORS_ONLN')
 
2274
        except (ValueError, OSError, AttributeError):
 
2275
            return None
 
2276
elif sys.platform == 'darwin':
 
2277
    def _local_concurrency():
 
2278
        return subprocess.Popen(['sysctl', '-n', 'hw.availcpu'],
 
2279
                                stdout=subprocess.PIPE).communicate()[0]
 
2280
elif "bsd" in sys.platform:
 
2281
    def _local_concurrency():
 
2282
        return subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
 
2283
                                stdout=subprocess.PIPE).communicate()[0]
 
2284
elif sys.platform == 'sunos5':
 
2285
    def _local_concurrency():
 
2286
        return subprocess.Popen(['psrinfo', '-p',],
 
2287
                                stdout=subprocess.PIPE).communicate()[0]
 
2288
elif sys.platform == "win32":
 
2289
    def _local_concurrency():
 
2290
        # This appears to return the number of cores.
 
2291
        return os.environ.get('NUMBER_OF_PROCESSORS')
 
2292
else:
 
2293
    def _local_concurrency():
 
2294
        # Who knows ?
 
2295
        return None
 
2296
 
 
2297
 
 
2298
_cached_local_concurrency = None
 
2299
 
 
2300
def local_concurrency(use_cache=True):
 
2301
    """Return how many processes can be run concurrently.
 
2302
 
 
2303
    Rely on platform specific implementations and default to 1 (one) if
 
2304
    anything goes wrong.
 
2305
    """
 
2306
    global _cached_local_concurrency
 
2307
 
 
2308
    if _cached_local_concurrency is not None and use_cache:
 
2309
        return _cached_local_concurrency
 
2310
 
 
2311
    concurrency = os.environ.get('BZR_CONCURRENCY', None)
 
2312
    if concurrency is None:
 
2313
        try:
 
2314
            import multiprocessing
 
2315
        except ImportError:
 
2316
            # multiprocessing is only available on Python >= 2.6
 
2317
            try:
 
2318
                concurrency = _local_concurrency()
 
2319
            except (OSError, IOError):
 
2320
                pass
 
2321
        else:
 
2322
            concurrency = multiprocessing.cpu_count()
 
2323
    try:
 
2324
        concurrency = int(concurrency)
 
2325
    except (TypeError, ValueError):
 
2326
        concurrency = 1
 
2327
    if use_cache:
 
2328
        _cached_concurrency = concurrency
 
2329
    return concurrency
 
2330
 
 
2331
 
 
2332
class UnicodeOrBytesToBytesWriter(codecs.StreamWriter):
 
2333
    """A stream writer that doesn't decode str arguments."""
 
2334
 
 
2335
    def __init__(self, encode, stream, errors='strict'):
 
2336
        codecs.StreamWriter.__init__(self, stream, errors)
 
2337
        self.encode = encode
 
2338
 
 
2339
    def write(self, object):
 
2340
        if type(object) is str:
 
2341
            self.stream.write(object)
 
2342
        else:
 
2343
            data, _ = self.encode(object, self.errors)
 
2344
            self.stream.write(data)
 
2345
 
 
2346
if sys.platform == 'win32':
 
2347
    def open_file(filename, mode='r', bufsize=-1):
 
2348
        """This function is used to override the ``open`` builtin.
 
2349
 
 
2350
        But it uses O_NOINHERIT flag so the file handle is not inherited by
 
2351
        child processes.  Deleting or renaming a closed file opened with this
 
2352
        function is not blocking child processes.
 
2353
        """
 
2354
        writing = 'w' in mode
 
2355
        appending = 'a' in mode
 
2356
        updating = '+' in mode
 
2357
        binary = 'b' in mode
 
2358
 
 
2359
        flags = O_NOINHERIT
 
2360
        # see http://msdn.microsoft.com/en-us/library/yeby3zcb%28VS.71%29.aspx
 
2361
        # for flags for each modes.
 
2362
        if binary:
 
2363
            flags |= O_BINARY
 
2364
        else:
 
2365
            flags |= O_TEXT
 
2366
 
 
2367
        if writing:
 
2368
            if updating:
 
2369
                flags |= os.O_RDWR
 
2370
            else:
 
2371
                flags |= os.O_WRONLY
 
2372
            flags |= os.O_CREAT | os.O_TRUNC
 
2373
        elif appending:
 
2374
            if updating:
 
2375
                flags |= os.O_RDWR
 
2376
            else:
 
2377
                flags |= os.O_WRONLY
 
2378
            flags |= os.O_CREAT | os.O_APPEND
 
2379
        else: #reading
 
2380
            if updating:
 
2381
                flags |= os.O_RDWR
 
2382
            else:
 
2383
                flags |= os.O_RDONLY
 
2384
 
 
2385
        return os.fdopen(os.open(filename, flags), mode, bufsize)
 
2386
else:
 
2387
    open_file = open
 
2388
 
 
2389
 
 
2390
def getuser_unicode():
 
2391
    """Return the username as unicode.
 
2392
    """
 
2393
    try:
 
2394
        user_encoding = get_user_encoding()
 
2395
        username = getpass.getuser().decode(user_encoding)
 
2396
    except UnicodeDecodeError:
 
2397
        raise errors.BzrError("Can't decode username as %s." % \
 
2398
                user_encoding)
 
2399
    except ImportError, e:
 
2400
        if sys.platform != 'win32':
 
2401
            raise
 
2402
        if str(e) != 'No module named pwd':
 
2403
            raise
 
2404
        # https://bugs.launchpad.net/bzr/+bug/660174
 
2405
        # getpass.getuser() is unable to return username on Windows
 
2406
        # if there is no USERNAME environment variable set.
 
2407
        # That could be true if bzr is running as a service,
 
2408
        # e.g. running `bzr serve` as a service on Windows.
 
2409
        # We should not fail with traceback in this case.
 
2410
        username = u'UNKNOWN'
 
2411
    return username
 
2412
 
 
2413
 
 
2414
def available_backup_name(base, exists):
 
2415
    """Find a non-existing backup file name.
 
2416
 
 
2417
    This will *not* create anything, this only return a 'free' entry.  This
 
2418
    should be used for checking names in a directory below a locked
 
2419
    tree/branch/repo to avoid race conditions. This is LBYL (Look Before You
 
2420
    Leap) and generally discouraged.
 
2421
 
 
2422
    :param base: The base name.
 
2423
 
 
2424
    :param exists: A callable returning True if the path parameter exists.
 
2425
    """
 
2426
    counter = 1
 
2427
    name = "%s.~%d~" % (base, counter)
 
2428
    while exists(name):
 
2429
        counter += 1
 
2430
        name = "%s.~%d~" % (base, counter)
 
2431
    return name
 
2432
 
 
2433
 
 
2434
def set_fd_cloexec(fd):
 
2435
    """Set a Unix file descriptor's FD_CLOEXEC flag.  Do nothing if platform
 
2436
    support for this is not available.
 
2437
    """
 
2438
    try:
 
2439
        import fcntl
 
2440
        old = fcntl.fcntl(fd, fcntl.F_GETFD)
 
2441
        fcntl.fcntl(fd, fcntl.F_SETFD, old | fcntl.FD_CLOEXEC)
 
2442
    except (ImportError, AttributeError):
 
2443
        # Either the fcntl module or specific constants are not present
 
2444
        pass
 
2445
 
 
2446
 
 
2447
def find_executable_on_path(name):
 
2448
    """Finds an executable on the PATH.
 
2449
    
 
2450
    On Windows, this will try to append each extension in the PATHEXT
 
2451
    environment variable to the name, if it cannot be found with the name
 
2452
    as given.
 
2453
    
 
2454
    :param name: The base name of the executable.
 
2455
    :return: The path to the executable found or None.
 
2456
    """
 
2457
    path = os.environ.get('PATH')
 
2458
    if path is None:
 
2459
        return None
 
2460
    path = path.split(os.pathsep)
 
2461
    if sys.platform == 'win32':
 
2462
        exts = os.environ.get('PATHEXT', '').split(os.pathsep)
 
2463
        exts = [ext.lower() for ext in exts]
 
2464
        base, ext = os.path.splitext(name)
 
2465
        if ext != '':
 
2466
            if ext.lower() not in exts:
 
2467
                return None
 
2468
            name = base
 
2469
            exts = [ext]
 
2470
    else:
 
2471
        exts = ['']
 
2472
    for ext in exts:
 
2473
        for d in path:
 
2474
            f = os.path.join(d, name) + ext
 
2475
            if os.access(f, os.X_OK):
 
2476
                return f
 
2477
    return None
 
2478
 
 
2479
 
 
2480
def _posix_is_local_pid_dead(pid):
 
2481
    """True if pid doesn't correspond to live process on this machine"""
 
2482
    try:
 
2483
        # Special meaning of unix kill: just check if it's there.
 
2484
        os.kill(pid, 0)
 
2485
    except OSError, e:
 
2486
        if e.errno == errno.ESRCH:
 
2487
            # On this machine, and really not found: as sure as we can be
 
2488
            # that it's dead.
 
2489
            return True
 
2490
        elif e.errno == errno.EPERM:
 
2491
            # exists, though not ours
 
2492
            return False
 
2493
        else:
 
2494
            mutter("os.kill(%d, 0) failed: %s" % (pid, e))
 
2495
            # Don't really know.
 
2496
            return False
 
2497
    else:
 
2498
        # Exists and our process: not dead.
 
2499
        return False
 
2500
 
 
2501
if sys.platform == "win32":
 
2502
    is_local_pid_dead = win32utils.is_local_pid_dead
 
2503
else:
 
2504
    is_local_pid_dead = _posix_is_local_pid_dead
 
2505
 
 
2506
 
 
2507
def fdatasync(fileno):
 
2508
    """Flush file contents to disk if possible.
 
2509
    
 
2510
    :param fileno: Integer OS file handle.
 
2511
    :raises TransportNotPossible: If flushing to disk is not possible.
 
2512
    """
 
2513
    fn = getattr(os, 'fdatasync', getattr(os, 'fsync', None))
 
2514
    if fn is not None:
 
2515
        fn(fileno)