~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

(jameinel) Allow 'bzr serve' to interpret SIGHUP as a graceful shutdown.
 (bug #795025) (John A Meinel)

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,
 
45
    config,
49
46
    errors,
 
47
    trace,
50
48
    win32utils,
51
49
    )
 
50
from bzrlib.i18n import gettext
52
51
""")
53
52
 
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
 
        )
 
53
from bzrlib.symbol_versioning import (
 
54
    deprecated_function,
 
55
    deprecated_in,
 
56
    )
 
57
 
 
58
from hashlib import (
 
59
    md5,
 
60
    sha1 as sha,
 
61
    )
66
62
 
67
63
 
68
64
import bzrlib
69
65
from bzrlib import symbol_versioning
70
66
 
71
67
 
 
68
# Cross platform wall-clock time functionality with decent resolution.
 
69
# On Linux ``time.clock`` returns only CPU time. On Windows, ``time.time()``
 
70
# only has a resolution of ~15ms. Note that ``time.clock()`` is not
 
71
# synchronized with ``time.time()``, this is only meant to be used to find
 
72
# delta times by subtracting from another call to this function.
 
73
timer_func = time.time
 
74
if sys.platform == 'win32':
 
75
    timer_func = time.clock
 
76
 
72
77
# On win32, O_BINARY is used to indicate the file should
73
78
# be opened in binary mode, rather than text mode.
74
79
# On other platforms, O_BINARY doesn't exist, because
75
80
# they always open in binary mode, so it is okay to
76
 
# OR with 0 on those platforms
 
81
# OR with 0 on those platforms.
 
82
# O_NOINHERIT and O_TEXT exists only on win32 too.
77
83
O_BINARY = getattr(os, 'O_BINARY', 0)
 
84
O_TEXT = getattr(os, 'O_TEXT', 0)
 
85
O_NOINHERIT = getattr(os, 'O_NOINHERIT', 0)
 
86
 
 
87
 
 
88
def get_unicode_argv():
 
89
    try:
 
90
        user_encoding = get_user_encoding()
 
91
        return [a.decode(user_encoding) for a in sys.argv[1:]]
 
92
    except UnicodeDecodeError:
 
93
        raise errors.BzrError(gettext("Parameter {0!r} encoding is unsupported by {1} "
 
94
            "application locale.").format(a, user_encoding))
78
95
 
79
96
 
80
97
def make_readonly(filename):
97
114
 
98
115
    :param paths: A container (and hence not None) of paths.
99
116
    :return: A set of paths sufficient to include everything in paths via
100
 
        is_inside_any, drawn from the paths parameter.
 
117
        is_inside, drawn from the paths parameter.
101
118
    """
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
 
119
    if len(paths) < 2:
 
120
        return set(paths)
 
121
 
 
122
    def sort_key(path):
 
123
        return path.split('/')
 
124
    sorted_paths = sorted(list(paths), key=sort_key)
 
125
 
 
126
    search_paths = [sorted_paths[0]]
 
127
    for path in sorted_paths[1:]:
 
128
        if not is_inside(search_paths[-1], path):
 
129
            # This path is unique, add it
 
130
            search_paths.append(path)
 
131
 
 
132
    return set(search_paths)
110
133
 
111
134
 
112
135
_QUOTE_RE = None
121
144
    global _QUOTE_RE
122
145
    if _QUOTE_RE is None:
123
146
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
124
 
        
 
147
 
125
148
    if _QUOTE_RE.search(f):
126
149
        return '"' + f + '"'
127
150
    else:
152
175
    try:
153
176
        return _kind_marker_map[kind]
154
177
    except KeyError:
155
 
        raise errors.BzrError('invalid file kind %r' % kind)
 
178
        # Slightly faster than using .get(, '') when the common case is that
 
179
        # kind will be found
 
180
        return ''
156
181
 
157
182
 
158
183
lexists = getattr(os.path, 'lexists', None)
166
191
            if e.errno == errno.ENOENT:
167
192
                return False;
168
193
            else:
169
 
                raise errors.BzrError("lstat/stat of (%r): %r" % (f, e))
 
194
                raise errors.BzrError(gettext("lstat/stat of ({0!r}): {1!r}").format(f, e))
170
195
 
171
196
 
172
197
def fancy_rename(old, new, rename_func, unlink_func):
173
198
    """A fancy rename, when you don't have atomic rename.
174
 
    
 
199
 
175
200
    :param old: The old path, to rename from
176
201
    :param new: The new path, to rename to
177
202
    :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
 
203
    :param unlink_func: A way to delete the target file if the full rename
 
204
        succeeds
179
205
    """
180
 
 
181
206
    # sftp rename doesn't allow overwriting, so play tricks:
182
207
    base = os.path.basename(new)
183
208
    dirname = os.path.dirname(new)
184
 
    tmp_name = u'tmp.%s.%.9f.%d.%s' % (base, time.time(), os.getpid(), rand_chars(10))
 
209
    # callers use different encodings for the paths so the following MUST
 
210
    # respect that. We rely on python upcasting to unicode if new is unicode
 
211
    # and keeping a str if not.
 
212
    tmp_name = 'tmp.%s.%.9f.%d.%s' % (base, time.time(),
 
213
                                      os.getpid(), rand_chars(10))
185
214
    tmp_name = pathjoin(dirname, tmp_name)
186
215
 
187
216
    # Rename the file out of the way, but keep track if it didn't exist
207
236
    else:
208
237
        file_existed = True
209
238
 
 
239
    failure_exc = None
210
240
    success = False
211
241
    try:
212
242
        try:
218
248
            # source and target may be aliases of each other (e.g. on a
219
249
            # case-insensitive filesystem), so we may have accidentally renamed
220
250
            # source by when we tried to rename target
221
 
            if not (file_existed and e.errno in (None, errno.ENOENT)):
222
 
                raise
 
251
            failure_exc = sys.exc_info()
 
252
            if (file_existed and e.errno in (None, errno.ENOENT)
 
253
                and old.lower() == new.lower()):
 
254
                # source and target are the same file on a case-insensitive
 
255
                # filesystem, so we don't generate an exception
 
256
                failure_exc = None
223
257
    finally:
224
258
        if file_existed:
225
259
            # If the file used to exist, rename it back into place
228
262
                unlink_func(tmp_name)
229
263
            else:
230
264
                rename_func(tmp_name, new)
 
265
    if failure_exc is not None:
 
266
        try:
 
267
            raise failure_exc[0], failure_exc[1], failure_exc[2]
 
268
        finally:
 
269
            del failure_exc
231
270
 
232
271
 
233
272
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
256
295
    running python.exe under cmd.exe return capital C:\\
257
296
    running win32 python inside a cygwin shell returns lowercase c:\\
258
297
    """
259
 
    drive, path = _nt_splitdrive(path)
 
298
    drive, path = ntpath.splitdrive(path)
260
299
    return drive.upper() + path
261
300
 
262
301
 
263
302
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('\\', '/'))
 
303
    # Real ntpath.abspath doesn't have a problem with a unicode cwd
 
304
    return _win32_fixdrive(ntpath.abspath(unicode(path)).replace('\\', '/'))
266
305
 
267
306
 
268
307
def _win98_abspath(path):
279
318
    #   /path       => C:/path
280
319
    path = unicode(path)
281
320
    # check for absolute path
282
 
    drive = _nt_splitdrive(path)[0]
 
321
    drive = ntpath.splitdrive(path)[0]
283
322
    if drive == '' and path[:2] not in('//','\\\\'):
284
323
        cwd = os.getcwdu()
285
324
        # we cannot simply os.path.join cwd and path
286
325
        # because os.path.join('C:','/path') produce '/path'
287
326
        # and this is incorrect
288
327
        if path[:1] in ('/','\\'):
289
 
            cwd = _nt_splitdrive(cwd)[0]
 
328
            cwd = ntpath.splitdrive(cwd)[0]
290
329
            path = path[1:]
291
330
        path = cwd + '\\' + path
292
 
    return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
 
331
    return _win32_fixdrive(ntpath.normpath(path).replace('\\', '/'))
293
332
 
294
333
 
295
334
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('\\', '/'))
 
335
    # Real ntpath.realpath doesn't have a problem with a unicode cwd
 
336
    return _win32_fixdrive(ntpath.realpath(unicode(path)).replace('\\', '/'))
298
337
 
299
338
 
300
339
def _win32_pathjoin(*args):
301
 
    return _nt_join(*args).replace('\\', '/')
 
340
    return ntpath.join(*args).replace('\\', '/')
302
341
 
303
342
 
304
343
def _win32_normpath(path):
305
 
    return _win32_fixdrive(_nt_normpath(unicode(path)).replace('\\', '/'))
 
344
    return _win32_fixdrive(ntpath.normpath(unicode(path)).replace('\\', '/'))
306
345
 
307
346
 
308
347
def _win32_getcwd():
317
356
    """We expect to be able to atomically replace 'new' with old.
318
357
 
319
358
    On win32, if new exists, it must be moved out of the way first,
320
 
    and then deleted. 
 
359
    and then deleted.
321
360
    """
322
361
    try:
323
362
        fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
324
363
    except OSError, e:
325
364
        if e.errno in (errno.EPERM, errno.EACCES, errno.EBUSY, errno.EINVAL):
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 
 
365
            # If we try to rename a non-existant file onto cwd, we get
 
366
            # EPERM or EACCES instead of ENOENT, this will raise ENOENT
328
367
            # if the old path doesn't exist, sometimes we get EACCES
329
368
            # On Linux, we seem to get EBUSY, on Mac we get EINVAL
330
369
            os.lstat(old)
347
386
basename = os.path.basename
348
387
split = os.path.split
349
388
splitext = os.path.splitext
350
 
# These were already imported into local scope
 
389
# These were already lazily imported into local scope
351
390
# mkdtemp = tempfile.mkdtemp
352
391
# rmtree = shutil.rmtree
 
392
lstat = os.lstat
 
393
fstat = os.fstat
 
394
 
 
395
def wrap_stat(st):
 
396
    return st
 
397
 
353
398
 
354
399
MIN_ABS_PATHLENGTH = 1
355
400
 
365
410
    getcwd = _win32_getcwd
366
411
    mkdtemp = _win32_mkdtemp
367
412
    rename = _win32_rename
 
413
    try:
 
414
        from bzrlib import _walkdirs_win32
 
415
    except ImportError:
 
416
        pass
 
417
    else:
 
418
        lstat = _walkdirs_win32.lstat
 
419
        fstat = _walkdirs_win32.fstat
 
420
        wrap_stat = _walkdirs_win32.wrap_stat
368
421
 
369
422
    MIN_ABS_PATHLENGTH = 3
370
423
 
384
437
    def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
385
438
        """Replacer for shutil.rmtree: could remove readonly dirs/files"""
386
439
        return shutil.rmtree(path, ignore_errors, onerror)
 
440
 
 
441
    f = win32utils.get_unicode_argv     # special function or None
 
442
    if f is not None:
 
443
        get_unicode_argv = f
 
444
 
387
445
elif sys.platform == 'darwin':
388
446
    getcwd = _mac_getcwd
389
447
 
390
448
 
391
 
def get_terminal_encoding():
 
449
def get_terminal_encoding(trace=False):
392
450
    """Find the best encoding for printing to the screen.
393
451
 
394
452
    This attempts to check both sys.stdout and sys.stdin to see
400
458
 
401
459
    On my standard US Windows XP, the preferred encoding is
402
460
    cp1252, but the console is cp437
 
461
 
 
462
    :param trace: If True trace the selected encoding via mutter().
403
463
    """
404
464
    from bzrlib.trace import mutter
405
465
    output_encoding = getattr(sys.stdout, 'encoding', None)
407
467
        input_encoding = getattr(sys.stdin, 'encoding', None)
408
468
        if not input_encoding:
409
469
            output_encoding = get_user_encoding()
410
 
            mutter('encoding stdout as osutils.get_user_encoding() %r',
 
470
            if trace:
 
471
                mutter('encoding stdout as osutils.get_user_encoding() %r',
411
472
                   output_encoding)
412
473
        else:
413
474
            output_encoding = input_encoding
414
 
            mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
 
475
            if trace:
 
476
                mutter('encoding stdout as sys.stdin encoding %r',
 
477
                    output_encoding)
415
478
    else:
416
 
        mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
 
479
        if trace:
 
480
            mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
417
481
    if output_encoding == 'cp0':
418
482
        # invalid encoding (cp0 means 'no codepage' on Windows)
419
483
        output_encoding = get_user_encoding()
420
 
        mutter('cp0 is invalid encoding.'
 
484
        if trace:
 
485
            mutter('cp0 is invalid encoding.'
421
486
               ' encoding stdout as osutils.get_user_encoding() %r',
422
487
               output_encoding)
423
488
    # check encoding
449
514
def isdir(f):
450
515
    """True if f is an accessible directory."""
451
516
    try:
452
 
        return S_ISDIR(os.lstat(f)[ST_MODE])
 
517
        return stat.S_ISDIR(os.lstat(f)[stat.ST_MODE])
453
518
    except OSError:
454
519
        return False
455
520
 
457
522
def isfile(f):
458
523
    """True if f is a regular file."""
459
524
    try:
460
 
        return S_ISREG(os.lstat(f)[ST_MODE])
 
525
        return stat.S_ISREG(os.lstat(f)[stat.ST_MODE])
461
526
    except OSError:
462
527
        return False
463
528
 
464
529
def islink(f):
465
530
    """True if f is a symlink."""
466
531
    try:
467
 
        return S_ISLNK(os.lstat(f)[ST_MODE])
 
532
        return stat.S_ISLNK(os.lstat(f)[stat.ST_MODE])
468
533
    except OSError:
469
534
        return False
470
535
 
471
536
def is_inside(dir, fname):
472
537
    """True if fname is inside dir.
473
 
    
 
538
 
474
539
    The parameters should typically be passed to osutils.normpath first, so
475
540
    that . and .. and repeated slashes are eliminated, and the separators
476
541
    are canonical for the platform.
477
 
    
478
 
    The empty string as a dir name is taken as top-of-tree and matches 
 
542
 
 
543
    The empty string as a dir name is taken as top-of-tree and matches
479
544
    everything.
480
545
    """
481
 
    # XXX: Most callers of this can actually do something smarter by 
 
546
    # XXX: Most callers of this can actually do something smarter by
482
547
    # looking at the inventory
483
548
    if dir == fname:
484
549
        return True
485
 
    
 
550
 
486
551
    if dir == '':
487
552
        return True
488
553
 
597
662
    return s.hexdigest()
598
663
 
599
664
 
 
665
def size_sha_file(f):
 
666
    """Calculate the size and hexdigest of an open file.
 
667
 
 
668
    The file cursor should be already at the start and
 
669
    the caller is responsible for closing the file afterwards.
 
670
    """
 
671
    size = 0
 
672
    s = sha()
 
673
    BUFSIZE = 128<<10
 
674
    while True:
 
675
        b = f.read(BUFSIZE)
 
676
        if not b:
 
677
            break
 
678
        size += len(b)
 
679
        s.update(b)
 
680
    return size, s.hexdigest()
 
681
 
 
682
 
600
683
def sha_file_by_name(fname):
601
684
    """Calculate the SHA1 of a file by reading the full text"""
602
685
    s = sha()
603
 
    f = os.open(fname, os.O_RDONLY | O_BINARY)
 
686
    f = os.open(fname, os.O_RDONLY | O_BINARY | O_NOINHERIT)
604
687
    try:
605
688
        while True:
606
689
            b = os.read(f, 1<<16)
648
731
    return offset.days * 86400 + offset.seconds
649
732
 
650
733
weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
651
 
    
 
734
_default_format_by_weekday_num = [wd + " %Y-%m-%d %H:%M:%S" for wd in weekdays]
 
735
 
 
736
 
652
737
def format_date(t, offset=0, timezone='original', date_fmt=None,
653
738
                show_offset=True):
654
739
    """Return a formatted date string.
667
752
    date_str = time.strftime(date_fmt, tt)
668
753
    return date_str + offset_str
669
754
 
 
755
 
 
756
# Cache of formatted offset strings
 
757
_offset_cache = {}
 
758
 
 
759
 
 
760
def format_date_with_offset_in_original_timezone(t, offset=0,
 
761
    _cache=_offset_cache):
 
762
    """Return a formatted date string in the original timezone.
 
763
 
 
764
    This routine may be faster then format_date.
 
765
 
 
766
    :param t: Seconds since the epoch.
 
767
    :param offset: Timezone offset in seconds east of utc.
 
768
    """
 
769
    if offset is None:
 
770
        offset = 0
 
771
    tt = time.gmtime(t + offset)
 
772
    date_fmt = _default_format_by_weekday_num[tt[6]]
 
773
    date_str = time.strftime(date_fmt, tt)
 
774
    offset_str = _cache.get(offset, None)
 
775
    if offset_str is None:
 
776
        offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
 
777
        _cache[offset] = offset_str
 
778
    return date_str + offset_str
 
779
 
 
780
 
670
781
def format_local_date(t, offset=0, timezone='original', date_fmt=None,
671
782
                      show_offset=True):
672
783
    """Return an unicode date string formatted according to the current locale.
683
794
               _format_date(t, offset, timezone, date_fmt, show_offset)
684
795
    date_str = time.strftime(date_fmt, tt)
685
796
    if not isinstance(date_str, unicode):
686
 
        date_str = date_str.decode(bzrlib.user_encoding, 'replace')
 
797
        date_str = date_str.decode(get_user_encoding(), 'replace')
687
798
    return date_str + offset_str
688
799
 
 
800
 
689
801
def _format_date(t, offset, timezone, date_fmt, show_offset):
690
802
    if timezone == 'utc':
691
803
        tt = time.gmtime(t)
710
822
 
711
823
def compact_date(when):
712
824
    return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
713
 
    
 
825
 
714
826
 
715
827
def format_delta(delta):
716
828
    """Get a nice looking string for a time delta.
763
875
 
764
876
def filesize(f):
765
877
    """Return size of given open file."""
766
 
    return os.fstat(f.fileno())[ST_SIZE]
 
878
    return os.fstat(f.fileno())[stat.ST_SIZE]
767
879
 
768
880
 
769
881
# Define rand_bytes based on platform.
792
904
ALNUM = '0123456789abcdefghijklmnopqrstuvwxyz'
793
905
def rand_chars(num):
794
906
    """Return a random string of num alphanumeric characters
795
 
    
796
 
    The result only contains lowercase chars because it may be used on 
 
907
 
 
908
    The result only contains lowercase chars because it may be used on
797
909
    case-insensitive filesystems.
798
910
    """
799
911
    s = ''
814
926
    rps = []
815
927
    for f in ps:
816
928
        if f == '..':
817
 
            raise errors.BzrError("sorry, %r not allowed in path" % f)
 
929
            raise errors.BzrError(gettext("sorry, %r not allowed in path") % f)
818
930
        elif (f == '.') or (f == ''):
819
931
            pass
820
932
        else:
825
937
def joinpath(p):
826
938
    for f in p:
827
939
        if (f == '..') or (f is None) or (f == ''):
828
 
            raise errors.BzrError("sorry, %r not allowed in path" % f)
 
940
            raise errors.BzrError(gettext("sorry, %r not allowed in path") % f)
829
941
    return pathjoin(*p)
830
942
 
831
943
 
 
944
def parent_directories(filename):
 
945
    """Return the list of parent directories, deepest first.
 
946
 
 
947
    For example, parent_directories("a/b/c") -> ["a/b", "a"].
 
948
    """
 
949
    parents = []
 
950
    parts = splitpath(dirname(filename))
 
951
    while parts:
 
952
        parents.append(joinpath(parts))
 
953
        parts.pop()
 
954
    return parents
 
955
 
 
956
 
 
957
_extension_load_failures = []
 
958
 
 
959
 
 
960
def failed_to_load_extension(exception):
 
961
    """Handle failing to load a binary extension.
 
962
 
 
963
    This should be called from the ImportError block guarding the attempt to
 
964
    import the native extension.  If this function returns, the pure-Python
 
965
    implementation should be loaded instead::
 
966
 
 
967
    >>> try:
 
968
    >>>     import bzrlib._fictional_extension_pyx
 
969
    >>> except ImportError, e:
 
970
    >>>     bzrlib.osutils.failed_to_load_extension(e)
 
971
    >>>     import bzrlib._fictional_extension_py
 
972
    """
 
973
    # NB: This docstring is just an example, not a doctest, because doctest
 
974
    # currently can't cope with the use of lazy imports in this namespace --
 
975
    # mbp 20090729
 
976
 
 
977
    # This currently doesn't report the failure at the time it occurs, because
 
978
    # they tend to happen very early in startup when we can't check config
 
979
    # files etc, and also we want to report all failures but not spam the user
 
980
    # with 10 warnings.
 
981
    exception_str = str(exception)
 
982
    if exception_str not in _extension_load_failures:
 
983
        trace.mutter("failed to load compiled extension: %s" % exception_str)
 
984
        _extension_load_failures.append(exception_str)
 
985
 
 
986
 
 
987
def report_extension_load_failures():
 
988
    if not _extension_load_failures:
 
989
        return
 
990
    if config.GlobalStack().get('ignore_missing_extensions'):
 
991
        return
 
992
    # the warnings framework should by default show this only once
 
993
    from bzrlib.trace import warning
 
994
    warning(
 
995
        "bzr: warning: some compiled extensions could not be loaded; "
 
996
        "see <https://answers.launchpad.net/bzr/+faq/703>")
 
997
    # we no longer show the specific missing extensions here, because it makes
 
998
    # the message too long and scary - see
 
999
    # https://bugs.launchpad.net/bzr/+bug/430529
 
1000
 
 
1001
 
832
1002
try:
833
1003
    from bzrlib._chunks_to_lines_pyx import chunks_to_lines
834
 
except ImportError:
 
1004
except ImportError, e:
 
1005
    failed_to_load_extension(e)
835
1006
    from bzrlib._chunks_to_lines_py import chunks_to_lines
836
1007
 
837
1008
 
875
1046
        shutil.copyfile(src, dest)
876
1047
 
877
1048
 
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
1049
def delete_any(path):
884
 
    """Delete a file or directory."""
 
1050
    """Delete a file, symlink or directory.
 
1051
 
 
1052
    Will delete even if readonly.
 
1053
    """
 
1054
    try:
 
1055
       _delete_file_or_dir(path)
 
1056
    except (OSError, IOError), e:
 
1057
        if e.errno in (errno.EPERM, errno.EACCES):
 
1058
            # make writable and try again
 
1059
            try:
 
1060
                make_writable(path)
 
1061
            except (OSError, IOError):
 
1062
                pass
 
1063
            _delete_file_or_dir(path)
 
1064
        else:
 
1065
            raise
 
1066
 
 
1067
 
 
1068
def _delete_file_or_dir(path):
 
1069
    # Look Before You Leap (LBYL) is appropriate here instead of Easier to Ask for
 
1070
    # Forgiveness than Permission (EAFP) because:
 
1071
    # - root can damage a solaris file system by using unlink,
 
1072
    # - unlink raises different exceptions on different OSes (linux: EISDIR, win32:
 
1073
    #   EACCES, OSX: EPERM) when invoked on a directory.
885
1074
    if isdir(path): # Takes care of symlinks
886
1075
        os.rmdir(path)
887
1076
    else:
907
1096
            and sys.platform not in ('cygwin', 'win32'))
908
1097
 
909
1098
 
 
1099
def readlink(abspath):
 
1100
    """Return a string representing the path to which the symbolic link points.
 
1101
 
 
1102
    :param abspath: The link absolute unicode path.
 
1103
 
 
1104
    This his guaranteed to return the symbolic link in unicode in all python
 
1105
    versions.
 
1106
    """
 
1107
    link = abspath.encode(_fs_enc)
 
1108
    target = os.readlink(link)
 
1109
    target = target.decode(_fs_enc)
 
1110
    return target
 
1111
 
 
1112
 
910
1113
def contains_whitespace(s):
911
1114
    """True if there are any whitespace characters in s."""
912
1115
    # string.whitespace can include '\xa0' in certain locales, because it is
937
1140
 
938
1141
 
939
1142
def relpath(base, path):
940
 
    """Return path relative to base, or raise exception.
 
1143
    """Return path relative to base, or raise PathNotChild exception.
941
1144
 
942
1145
    The path may be either an absolute path or a path relative to the
943
1146
    current working directory.
945
1148
    os.path.commonprefix (python2.4) has a bad bug that it works just
946
1149
    on string prefixes, assuming that '/u' is a prefix of '/u2'.  This
947
1150
    avoids that problem.
 
1151
 
 
1152
    NOTE: `base` should not have a trailing slash otherwise you'll get
 
1153
    PathNotChild exceptions regardless of `path`.
948
1154
    """
949
1155
 
950
1156
    if len(base) < MIN_ABS_PATHLENGTH:
951
1157
        # must have space for e.g. a drive letter
952
 
        raise ValueError('%r is too short to calculate a relative path'
 
1158
        raise ValueError(gettext('%r is too short to calculate a relative path')
953
1159
            % (base,))
954
1160
 
955
1161
    rp = abspath(path)
956
1162
 
957
1163
    s = []
958
1164
    head = rp
959
 
    while len(head) >= len(base):
 
1165
    while True:
 
1166
        if len(head) <= len(base) and head != base:
 
1167
            raise errors.PathNotChild(rp, base)
960
1168
        if head == base:
961
1169
            break
962
 
        head, tail = os.path.split(head)
 
1170
        head, tail = split(head)
963
1171
        if tail:
964
 
            s.insert(0, tail)
965
 
    else:
966
 
        raise errors.PathNotChild(rp, base)
 
1172
            s.append(tail)
967
1173
 
968
1174
    if s:
969
 
        return pathjoin(*s)
 
1175
        return pathjoin(*reversed(s))
970
1176
    else:
971
1177
        return ''
972
1178
 
999
1205
    bit_iter = iter(rel.split('/'))
1000
1206
    for bit in bit_iter:
1001
1207
        lbit = bit.lower()
1002
 
        for look in _listdir(current):
 
1208
        try:
 
1209
            next_entries = _listdir(current)
 
1210
        except OSError: # enoent, eperm, etc
 
1211
            # We can't find this in the filesystem, so just append the
 
1212
            # remaining bits.
 
1213
            current = pathjoin(current, bit, *list(bit_iter))
 
1214
            break
 
1215
        for look in next_entries:
1003
1216
            if lbit == look.lower():
1004
1217
                current = pathjoin(current, look)
1005
1218
                break
1009
1222
            # the target of a move, for example).
1010
1223
            current = pathjoin(current, bit, *list(bit_iter))
1011
1224
            break
1012
 
    return current[len(abs_base)+1:]
 
1225
    return current[len(abs_base):].lstrip('/')
1013
1226
 
1014
1227
# 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":
 
1228
# file-systems; Linux often sees FAT32 devices (or NFS-mounted OSX
 
1229
# filesystems), for example, so could probably benefit from the same basic
 
1230
# support there.  For now though, only Windows and OSX get that support, and
 
1231
# they get it for *all* file-systems!
 
1232
if sys.platform in ('win32', 'darwin'):
1019
1233
    canonical_relpath = _cicp_canonical_relpath
1020
1234
else:
1021
1235
    canonical_relpath = relpath
1029
1243
    # but for now, we haven't optimized...
1030
1244
    return [canonical_relpath(base, p) for p in paths]
1031
1245
 
 
1246
 
 
1247
def decode_filename(filename):
 
1248
    """Decode the filename using the filesystem encoding
 
1249
 
 
1250
    If it is unicode, it is returned.
 
1251
    Otherwise it is decoded from the the filesystem's encoding. If decoding
 
1252
    fails, a errors.BadFilenameEncoding exception is raised.
 
1253
    """
 
1254
    if type(filename) is unicode:
 
1255
        return filename
 
1256
    try:
 
1257
        return filename.decode(_fs_enc)
 
1258
    except UnicodeDecodeError:
 
1259
        raise errors.BadFilenameEncoding(filename, _fs_enc)
 
1260
 
 
1261
 
1032
1262
def safe_unicode(unicode_or_utf8_string):
1033
1263
    """Coerce unicode_or_utf8_string into unicode.
1034
1264
 
1035
1265
    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.
 
1266
    Otherwise it is decoded from utf-8. If decoding fails, the exception is
 
1267
    wrapped in a BzrBadParameterNotUnicode exception.
1039
1268
    """
1040
1269
    if isinstance(unicode_or_utf8_string, unicode):
1041
1270
        return unicode_or_utf8_string
1118
1347
def normalizes_filenames():
1119
1348
    """Return True if this platform normalizes unicode filenames.
1120
1349
 
1121
 
    Mac OSX does, Windows/Linux do not.
 
1350
    Only Mac OSX.
1122
1351
    """
1123
1352
    return _platform_normalizes_filenames
1124
1353
 
1128
1357
 
1129
1358
    On platforms where the system normalizes filenames (Mac OSX),
1130
1359
    you can access a file by any path which will normalize correctly.
1131
 
    On platforms where the system does not normalize filenames 
1132
 
    (Windows, Linux), you have to access a file by its exact path.
 
1360
    On platforms where the system does not normalize filenames
 
1361
    (everything else), you have to access a file by its exact path.
1133
1362
 
1134
 
    Internally, bzr only supports NFC normalization, since that is 
 
1363
    Internally, bzr only supports NFC normalization, since that is
1135
1364
    the standard for XML documents.
1136
1365
 
1137
1366
    So return the normalized path, and a flag indicating if the file
1154
1383
    normalized_filename = _inaccessible_normalized_filename
1155
1384
 
1156
1385
 
 
1386
def set_signal_handler(signum, handler, restart_syscall=True):
 
1387
    """A wrapper for signal.signal that also calls siginterrupt(signum, False)
 
1388
    on platforms that support that.
 
1389
 
 
1390
    :param restart_syscall: if set, allow syscalls interrupted by a signal to
 
1391
        automatically restart (by calling `signal.siginterrupt(signum,
 
1392
        False)`).  May be ignored if the feature is not available on this
 
1393
        platform or Python version.
 
1394
    """
 
1395
    try:
 
1396
        import signal
 
1397
        siginterrupt = signal.siginterrupt
 
1398
    except ImportError:
 
1399
        # This python implementation doesn't provide signal support, hence no
 
1400
        # handler exists
 
1401
        return None
 
1402
    except AttributeError:
 
1403
        # siginterrupt doesn't exist on this platform, or for this version
 
1404
        # of Python.
 
1405
        siginterrupt = lambda signum, flag: None
 
1406
    if restart_syscall:
 
1407
        def sig_handler(*args):
 
1408
            # Python resets the siginterrupt flag when a signal is
 
1409
            # received.  <http://bugs.python.org/issue8354>
 
1410
            # As a workaround for some cases, set it back the way we want it.
 
1411
            siginterrupt(signum, False)
 
1412
            # Now run the handler function passed to set_signal_handler.
 
1413
            handler(*args)
 
1414
    else:
 
1415
        sig_handler = handler
 
1416
    old_handler = signal.signal(signum, sig_handler)
 
1417
    if restart_syscall:
 
1418
        siginterrupt(signum, False)
 
1419
    return old_handler
 
1420
 
 
1421
 
 
1422
default_terminal_width = 80
 
1423
"""The default terminal width for ttys.
 
1424
 
 
1425
This is defined so that higher levels can share a common fallback value when
 
1426
terminal_width() returns None.
 
1427
"""
 
1428
 
 
1429
# Keep some state so that terminal_width can detect if _terminal_size has
 
1430
# returned a different size since the process started.  See docstring and
 
1431
# comments of terminal_width for details.
 
1432
# _terminal_size_state has 3 possible values: no_data, unchanged, and changed.
 
1433
_terminal_size_state = 'no_data'
 
1434
_first_terminal_size = None
 
1435
 
1157
1436
def terminal_width():
1158
 
    """Return estimated terminal width."""
1159
 
    if sys.platform == 'win32':
1160
 
        return win32utils.get_console_size()[0]
1161
 
    width = 0
 
1437
    """Return terminal width.
 
1438
 
 
1439
    None is returned if the width can't established precisely.
 
1440
 
 
1441
    The rules are:
 
1442
    - if BZR_COLUMNS is set, returns its value
 
1443
    - if there is no controlling terminal, returns None
 
1444
    - query the OS, if the queried size has changed since the last query,
 
1445
      return its value,
 
1446
    - if COLUMNS is set, returns its value,
 
1447
    - if the OS has a value (even though it's never changed), return its value.
 
1448
 
 
1449
    From there, we need to query the OS to get the size of the controlling
 
1450
    terminal.
 
1451
 
 
1452
    On Unices we query the OS by:
 
1453
    - get termios.TIOCGWINSZ
 
1454
    - if an error occurs or a negative value is obtained, returns None
 
1455
 
 
1456
    On Windows we query the OS by:
 
1457
    - win32utils.get_console_size() decides,
 
1458
    - returns None on error (provided default value)
 
1459
    """
 
1460
    # Note to implementors: if changing the rules for determining the width,
 
1461
    # make sure you've considered the behaviour in these cases:
 
1462
    #  - M-x shell in emacs, where $COLUMNS is set and TIOCGWINSZ returns 0,0.
 
1463
    #  - bzr log | less, in bash, where $COLUMNS not set and TIOCGWINSZ returns
 
1464
    #    0,0.
 
1465
    #  - (add more interesting cases here, if you find any)
 
1466
    # Some programs implement "Use $COLUMNS (if set) until SIGWINCH occurs",
 
1467
    # but we don't want to register a signal handler because it is impossible
 
1468
    # to do so without risking EINTR errors in Python <= 2.6.5 (see
 
1469
    # <http://bugs.python.org/issue8354>).  Instead we check TIOCGWINSZ every
 
1470
    # time so we can notice if the reported size has changed, which should have
 
1471
    # a similar effect.
 
1472
 
 
1473
    # If BZR_COLUMNS is set, take it, user is always right
 
1474
    # Except if they specified 0 in which case, impose no limit here
 
1475
    try:
 
1476
        width = int(os.environ['BZR_COLUMNS'])
 
1477
    except (KeyError, ValueError):
 
1478
        width = None
 
1479
    if width is not None:
 
1480
        if width > 0:
 
1481
            return width
 
1482
        else:
 
1483
            return None
 
1484
 
 
1485
    isatty = getattr(sys.stdout, 'isatty', None)
 
1486
    if isatty is None or not isatty():
 
1487
        # Don't guess, setting BZR_COLUMNS is the recommended way to override.
 
1488
        return None
 
1489
 
 
1490
    # Query the OS
 
1491
    width, height = os_size = _terminal_size(None, None)
 
1492
    global _first_terminal_size, _terminal_size_state
 
1493
    if _terminal_size_state == 'no_data':
 
1494
        _first_terminal_size = os_size
 
1495
        _terminal_size_state = 'unchanged'
 
1496
    elif (_terminal_size_state == 'unchanged' and
 
1497
          _first_terminal_size != os_size):
 
1498
        _terminal_size_state = 'changed'
 
1499
 
 
1500
    # If the OS claims to know how wide the terminal is, and this value has
 
1501
    # ever changed, use that.
 
1502
    if _terminal_size_state == 'changed':
 
1503
        if width is not None and width > 0:
 
1504
            return width
 
1505
 
 
1506
    # If COLUMNS is set, use it.
 
1507
    try:
 
1508
        return int(os.environ['COLUMNS'])
 
1509
    except (KeyError, ValueError):
 
1510
        pass
 
1511
 
 
1512
    # Finally, use an unchanged size from the OS, if we have one.
 
1513
    if _terminal_size_state == 'unchanged':
 
1514
        if width is not None and width > 0:
 
1515
            return width
 
1516
 
 
1517
    # The width could not be determined.
 
1518
    return None
 
1519
 
 
1520
 
 
1521
def _win32_terminal_size(width, height):
 
1522
    width, height = win32utils.get_console_size(defaultx=width, defaulty=height)
 
1523
    return width, height
 
1524
 
 
1525
 
 
1526
def _ioctl_terminal_size(width, height):
1162
1527
    try:
1163
1528
        import struct, fcntl, termios
1164
1529
        s = struct.pack('HHHH', 0, 0, 0, 0)
1165
1530
        x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
1166
 
        width = struct.unpack('HHHH', x)[1]
1167
 
    except IOError:
 
1531
        height, width = struct.unpack('HHHH', x)[0:2]
 
1532
    except (IOError, AttributeError):
1168
1533
        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
 
1534
    return width, height
 
1535
 
 
1536
_terminal_size = None
 
1537
"""Returns the terminal size as (width, height).
 
1538
 
 
1539
:param width: Default value for width.
 
1540
:param height: Default value for height.
 
1541
 
 
1542
This is defined specifically for each OS and query the size of the controlling
 
1543
terminal. If any error occurs, the provided default values should be returned.
 
1544
"""
 
1545
if sys.platform == 'win32':
 
1546
    _terminal_size = _win32_terminal_size
 
1547
else:
 
1548
    _terminal_size = _ioctl_terminal_size
1178
1549
 
1179
1550
 
1180
1551
def supports_executable():
1217
1588
 
1218
1589
 
1219
1590
def check_legal_path(path):
1220
 
    """Check whether the supplied path is legal.  
 
1591
    """Check whether the supplied path is legal.
1221
1592
    This is only required on Windows, so we don't test on other platforms
1222
1593
    right now.
1223
1594
    """
1257
1628
 
1258
1629
def walkdirs(top, prefix=""):
1259
1630
    """Yield data about all the directories in a tree.
1260
 
    
 
1631
 
1261
1632
    This yields all the data about the contents of a directory at a time.
1262
1633
    After each directory has been yielded, if the caller has mutated the list
1263
1634
    to exclude some directories, they are then not descended into.
1264
 
    
 
1635
 
1265
1636
    The data yielded is of the form:
1266
1637
    ((directory-relpath, directory-path-from-top),
1267
1638
    [(relpath, basename, kind, lstat, path-from-top), ...]),
1268
1639
     - directory-relpath is the relative path of the directory being returned
1269
1640
       with respect to top. prefix is prepended to this.
1270
 
     - directory-path-from-root is the path including top for this directory. 
 
1641
     - directory-path-from-root is the path including top for this directory.
1271
1642
       It is suitable for use with os functions.
1272
1643
     - relpath is the relative path within the subtree being walked.
1273
1644
     - basename is the basename of the path
1275
1646
       present within the tree - but it may be recorded as versioned. See
1276
1647
       versioned_kind.
1277
1648
     - lstat is the stat data *if* the file was statted.
1278
 
     - planned, not implemented: 
 
1649
     - planned, not implemented:
1279
1650
       path_from_tree_root is the path from the root of the tree.
1280
1651
 
1281
 
    :param prefix: Prefix the relpaths that are yielded with 'prefix'. This 
 
1652
    :param prefix: Prefix the relpaths that are yielded with 'prefix'. This
1282
1653
        allows one to walk a subtree but get paths that are relative to a tree
1283
1654
        rooted higher up.
1284
1655
    :return: an iterator over the dirs.
1285
1656
    """
1286
1657
    #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 
 
1658
    # summary in this, and the path from the root, may not agree
1288
1659
    # depending on top and prefix - i.e. ./foo and foo as a pair leads to
1289
1660
    # potentially confusing output. We should make this more robust - but
1290
1661
    # not at a speed cost. RBC 20060731
1305
1676
        dirblock = []
1306
1677
        append = dirblock.append
1307
1678
        try:
1308
 
            names = sorted(_listdir(top))
 
1679
            names = sorted(map(decode_filename, _listdir(top)))
1309
1680
        except OSError, e:
1310
1681
            if not _is_error_enotdir(e):
1311
1682
                raise
1374
1745
            #       for win98 anyway.
1375
1746
            try:
1376
1747
                from bzrlib._walkdirs_win32 import Win32ReadDir
1377
 
            except ImportError:
1378
 
                _selected_dir_reader = UnicodeDirReader()
1379
 
            else:
1380
1748
                _selected_dir_reader = Win32ReadDir()
1381
 
        elif fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
 
1749
            except ImportError:
 
1750
                pass
 
1751
        elif fs_encoding in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
1382
1752
            # ANSI_X3.4-1968 is a form of ASCII
1383
 
            _selected_dir_reader = UnicodeDirReader()
1384
 
        else:
1385
1753
            try:
1386
1754
                from bzrlib._readdir_pyx import UTF8DirReader
1387
 
            except ImportError:
1388
 
                # No optimised code path
1389
 
                _selected_dir_reader = UnicodeDirReader()
1390
 
            else:
1391
1755
                _selected_dir_reader = UTF8DirReader()
 
1756
            except ImportError, e:
 
1757
                failed_to_load_extension(e)
 
1758
                pass
 
1759
 
 
1760
    if _selected_dir_reader is None:
 
1761
        # Fallback to the python version
 
1762
        _selected_dir_reader = UnicodeDirReader()
 
1763
 
1392
1764
    # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1393
1765
    # But we don't actually uses 1-3 in pending, so set them to None
1394
1766
    pending = [[_selected_dir_reader.top_prefix_to_starting_dir(top, prefix)]]
1460
1832
def copy_tree(from_path, to_path, handlers={}):
1461
1833
    """Copy all of the entries in from_path into to_path.
1462
1834
 
1463
 
    :param from_path: The base directory to copy. 
 
1835
    :param from_path: The base directory to copy.
1464
1836
    :param to_path: The target directory. If it does not exist, it will
1465
1837
        be created.
1466
1838
    :param handlers: A dictionary of functions, which takes a source and
1499
1871
            real_handlers[kind](abspath, relpath)
1500
1872
 
1501
1873
 
 
1874
def copy_ownership_from_path(dst, src=None):
 
1875
    """Copy usr/grp ownership from src file/dir to dst file/dir.
 
1876
 
 
1877
    If src is None, the containing directory is used as source. If chown
 
1878
    fails, the error is ignored and a warning is printed.
 
1879
    """
 
1880
    chown = getattr(os, 'chown', None)
 
1881
    if chown is None:
 
1882
        return
 
1883
 
 
1884
    if src == None:
 
1885
        src = os.path.dirname(dst)
 
1886
        if src == '':
 
1887
            src = '.'
 
1888
 
 
1889
    try:
 
1890
        s = os.stat(src)
 
1891
        chown(dst, s.st_uid, s.st_gid)
 
1892
    except OSError, e:
 
1893
        trace.warning(
 
1894
            'Unable to copy ownership from "%s" to "%s". '
 
1895
            'You may want to set it manually.', src, dst)
 
1896
        trace.log_exception_quietly()
 
1897
 
 
1898
 
1502
1899
def path_prefix_key(path):
1503
1900
    """Generate a prefix-order path key for path.
1504
1901
 
1590
1987
    return user_encoding
1591
1988
 
1592
1989
 
 
1990
def get_diff_header_encoding():
 
1991
    return get_terminal_encoding()
 
1992
 
 
1993
 
1593
1994
def get_host_name():
1594
1995
    """Return the current unicode host name.
1595
1996
 
1604
2005
        return socket.gethostname().decode(get_user_encoding())
1605
2006
 
1606
2007
 
1607
 
def recv_all(socket, bytes):
 
2008
# We must not read/write any more than 64k at a time from/to a socket so we
 
2009
# don't risk "no buffer space available" errors on some platforms.  Windows in
 
2010
# particular is likely to throw WSAECONNABORTED or WSAENOBUFS if given too much
 
2011
# data at once.
 
2012
MAX_SOCKET_CHUNK = 64 * 1024
 
2013
 
 
2014
_end_of_stream_errors = [errno.ECONNRESET]
 
2015
for _eno in ['WSAECONNRESET', 'WSAECONNABORTED']:
 
2016
    _eno = getattr(errno, _eno, None)
 
2017
    if _eno is not None:
 
2018
        _end_of_stream_errors.append(_eno)
 
2019
del _eno
 
2020
 
 
2021
 
 
2022
def read_bytes_from_socket(sock, report_activity=None,
 
2023
        max_read_size=MAX_SOCKET_CHUNK):
 
2024
    """Read up to max_read_size of bytes from sock and notify of progress.
 
2025
 
 
2026
    Translates "Connection reset by peer" into file-like EOF (return an
 
2027
    empty string rather than raise an error), and repeats the recv if
 
2028
    interrupted by a signal.
 
2029
    """
 
2030
    while 1:
 
2031
        try:
 
2032
            bytes = sock.recv(max_read_size)
 
2033
        except socket.error, e:
 
2034
            eno = e.args[0]
 
2035
            if eno in _end_of_stream_errors:
 
2036
                # The connection was closed by the other side.  Callers expect
 
2037
                # an empty string to signal end-of-stream.
 
2038
                return ""
 
2039
            elif eno == errno.EINTR:
 
2040
                # Retry the interrupted recv.
 
2041
                continue
 
2042
            raise
 
2043
        else:
 
2044
            if report_activity is not None:
 
2045
                report_activity(len(bytes), 'read')
 
2046
            return bytes
 
2047
 
 
2048
 
 
2049
def recv_all(socket, count):
1608
2050
    """Receive an exact number of bytes.
1609
2051
 
1610
2052
    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
 
2053
    depending on what's in the OS buffer.  MSG_WAITALL is not available
1612
2054
    on all platforms, but this should work everywhere.  This will return
1613
2055
    less than the requested amount if the remote end closes.
1614
2056
 
1615
2057
    This isn't optimized and is intended mostly for use in testing.
1616
2058
    """
1617
2059
    b = ''
1618
 
    while len(b) < bytes:
1619
 
        new = until_no_eintr(socket.recv, bytes - len(b))
 
2060
    while len(b) < count:
 
2061
        new = read_bytes_from_socket(socket, None, count - len(b))
1620
2062
        if new == '':
1621
2063
            break # eof
1622
2064
        b += new
1623
2065
    return b
1624
2066
 
1625
2067
 
1626
 
def send_all(socket, bytes):
 
2068
def send_all(sock, bytes, report_activity=None):
1627
2069
    """Send all bytes on a socket.
1628
2070
 
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.
 
2071
    Breaks large blocks in smaller chunks to avoid buffering limitations on
 
2072
    some platforms, and catches EINTR which may be thrown if the send is
 
2073
    interrupted by a signal.
 
2074
 
 
2075
    This is preferred to socket.sendall(), because it avoids portability bugs
 
2076
    and provides activity reporting.
 
2077
 
 
2078
    :param report_activity: Call this as bytes are read, see
 
2079
        Transport._report_activity
1631
2080
    """
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])
 
2081
    sent_total = 0
 
2082
    byte_count = len(bytes)
 
2083
    while sent_total < byte_count:
 
2084
        try:
 
2085
            sent = sock.send(buffer(bytes, sent_total, MAX_SOCKET_CHUNK))
 
2086
        except socket.error, e:
 
2087
            if e.args[0] != errno.EINTR:
 
2088
                raise
 
2089
        else:
 
2090
            sent_total += sent
 
2091
            report_activity(sent, 'write')
 
2092
 
 
2093
 
 
2094
def connect_socket(address):
 
2095
    # Slight variation of the socket.create_connection() function (provided by
 
2096
    # python-2.6) that can fail if getaddrinfo returns an empty list. We also
 
2097
    # provide it for previous python versions. Also, we don't use the timeout
 
2098
    # parameter (provided by the python implementation) so we don't implement
 
2099
    # it either).
 
2100
    err = socket.error('getaddrinfo returns an empty list')
 
2101
    host, port = address
 
2102
    for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
 
2103
        af, socktype, proto, canonname, sa = res
 
2104
        sock = None
 
2105
        try:
 
2106
            sock = socket.socket(af, socktype, proto)
 
2107
            sock.connect(sa)
 
2108
            return sock
 
2109
 
 
2110
        except socket.error, err:
 
2111
            # 'err' is now the most recent error
 
2112
            if sock is not None:
 
2113
                sock.close()
 
2114
    raise err
1635
2115
 
1636
2116
 
1637
2117
def dereference_path(path):
1678
2158
    base = dirname(bzrlib.__file__)
1679
2159
    if getattr(sys, 'frozen', None):    # bzr.exe
1680
2160
        base = abspath(pathjoin(base, '..', '..'))
1681
 
    filename = pathjoin(base, resource_relpath)
1682
 
    return open(filename, 'rU').read()
1683
 
 
 
2161
    f = file(pathjoin(base, resource_relpath), "rU")
 
2162
    try:
 
2163
        return f.read()
 
2164
    finally:
 
2165
        f.close()
1684
2166
 
1685
2167
def file_kind_from_stat_mode_thunk(mode):
1686
2168
    global file_kind_from_stat_mode
1688
2170
        try:
1689
2171
            from bzrlib._readdir_pyx import UTF8DirReader
1690
2172
            file_kind_from_stat_mode = UTF8DirReader().kind_from_mode
1691
 
        except ImportError:
 
2173
        except ImportError, e:
 
2174
            # This is one time where we won't warn that an extension failed to
 
2175
            # load. The extension is never available on Windows anyway.
1692
2176
            from bzrlib._readdir_py import (
1693
2177
                _kind_from_mode as file_kind_from_stat_mode
1694
2178
                )
1695
2179
    return file_kind_from_stat_mode(mode)
1696
2180
file_kind_from_stat_mode = file_kind_from_stat_mode_thunk
1697
2181
 
1698
 
 
1699
 
def file_kind(f, _lstat=os.lstat):
 
2182
def file_stat(f, _lstat=os.lstat):
1700
2183
    try:
1701
 
        return file_kind_from_stat_mode(_lstat(f).st_mode)
 
2184
        # XXX cache?
 
2185
        return _lstat(f)
1702
2186
    except OSError, e:
1703
2187
        if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
1704
2188
            raise errors.NoSuchFile(f)
1705
2189
        raise
1706
2190
 
 
2191
def file_kind(f, _lstat=os.lstat):
 
2192
    stat_value = file_stat(f, _lstat)
 
2193
    return file_kind_from_stat_mode(stat_value.st_mode)
1707
2194
 
1708
2195
def until_no_eintr(f, *a, **kw):
1709
 
    """Run f(*a, **kw), retrying if an EINTR error occurs."""
 
2196
    """Run f(*a, **kw), retrying if an EINTR error occurs.
 
2197
 
 
2198
    WARNING: you must be certain that it is safe to retry the call repeatedly
 
2199
    if EINTR does occur.  This is typically only true for low-level operations
 
2200
    like os.read.  If in any doubt, don't use this.
 
2201
 
 
2202
    Keep in mind that this is not a complete solution to EINTR.  There is
 
2203
    probably code in the Python standard library and other dependencies that
 
2204
    may encounter EINTR if a signal arrives (and there is signal handler for
 
2205
    that signal).  So this function can reduce the impact for IO that bzrlib
 
2206
    directly controls, but it is not a complete solution.
 
2207
    """
1710
2208
    # Borrowed from Twisted's twisted.python.util.untilConcludes function.
1711
2209
    while True:
1712
2210
        try:
1717
2215
            raise
1718
2216
 
1719
2217
 
 
2218
@deprecated_function(deprecated_in((2, 2, 0)))
 
2219
def re_compile_checked(re_string, flags=0, where=""):
 
2220
    """Return a compiled re, or raise a sensible error.
 
2221
 
 
2222
    This should only be used when compiling user-supplied REs.
 
2223
 
 
2224
    :param re_string: Text form of regular expression.
 
2225
    :param flags: eg re.IGNORECASE
 
2226
    :param where: Message explaining to the user the context where
 
2227
        it occurred, eg 'log search filter'.
 
2228
    """
 
2229
    # from https://bugs.launchpad.net/bzr/+bug/251352
 
2230
    try:
 
2231
        re_obj = re.compile(re_string, flags)
 
2232
        re_obj.search("")
 
2233
        return re_obj
 
2234
    except errors.InvalidPattern, e:
 
2235
        if where:
 
2236
            where = ' in ' + where
 
2237
        # despite the name 'error' is a type
 
2238
        raise errors.BzrCommandError('Invalid regular expression%s: %s'
 
2239
            % (where, e.msg))
 
2240
 
 
2241
 
1720
2242
if sys.platform == "win32":
1721
2243
    import msvcrt
1722
2244
    def getchar():
1733
2255
        finally:
1734
2256
            termios.tcsetattr(fd, termios.TCSADRAIN, settings)
1735
2257
        return ch
 
2258
 
 
2259
if sys.platform.startswith('linux'):
 
2260
    def _local_concurrency():
 
2261
        try:
 
2262
            return os.sysconf('SC_NPROCESSORS_ONLN')
 
2263
        except (ValueError, OSError, AttributeError):
 
2264
            return None
 
2265
elif sys.platform == 'darwin':
 
2266
    def _local_concurrency():
 
2267
        return subprocess.Popen(['sysctl', '-n', 'hw.availcpu'],
 
2268
                                stdout=subprocess.PIPE).communicate()[0]
 
2269
elif "bsd" in sys.platform:
 
2270
    def _local_concurrency():
 
2271
        return subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
 
2272
                                stdout=subprocess.PIPE).communicate()[0]
 
2273
elif sys.platform == 'sunos5':
 
2274
    def _local_concurrency():
 
2275
        return subprocess.Popen(['psrinfo', '-p',],
 
2276
                                stdout=subprocess.PIPE).communicate()[0]
 
2277
elif sys.platform == "win32":
 
2278
    def _local_concurrency():
 
2279
        # This appears to return the number of cores.
 
2280
        return os.environ.get('NUMBER_OF_PROCESSORS')
 
2281
else:
 
2282
    def _local_concurrency():
 
2283
        # Who knows ?
 
2284
        return None
 
2285
 
 
2286
 
 
2287
_cached_local_concurrency = None
 
2288
 
 
2289
def local_concurrency(use_cache=True):
 
2290
    """Return how many processes can be run concurrently.
 
2291
 
 
2292
    Rely on platform specific implementations and default to 1 (one) if
 
2293
    anything goes wrong.
 
2294
    """
 
2295
    global _cached_local_concurrency
 
2296
 
 
2297
    if _cached_local_concurrency is not None and use_cache:
 
2298
        return _cached_local_concurrency
 
2299
 
 
2300
    concurrency = os.environ.get('BZR_CONCURRENCY', None)
 
2301
    if concurrency is None:
 
2302
        try:
 
2303
            import multiprocessing
 
2304
        except ImportError:
 
2305
            # multiprocessing is only available on Python >= 2.6
 
2306
            try:
 
2307
                concurrency = _local_concurrency()
 
2308
            except (OSError, IOError):
 
2309
                pass
 
2310
        else:
 
2311
            concurrency = multiprocessing.cpu_count()
 
2312
    try:
 
2313
        concurrency = int(concurrency)
 
2314
    except (TypeError, ValueError):
 
2315
        concurrency = 1
 
2316
    if use_cache:
 
2317
        _cached_concurrency = concurrency
 
2318
    return concurrency
 
2319
 
 
2320
 
 
2321
class UnicodeOrBytesToBytesWriter(codecs.StreamWriter):
 
2322
    """A stream writer that doesn't decode str arguments."""
 
2323
 
 
2324
    def __init__(self, encode, stream, errors='strict'):
 
2325
        codecs.StreamWriter.__init__(self, stream, errors)
 
2326
        self.encode = encode
 
2327
 
 
2328
    def write(self, object):
 
2329
        if type(object) is str:
 
2330
            self.stream.write(object)
 
2331
        else:
 
2332
            data, _ = self.encode(object, self.errors)
 
2333
            self.stream.write(data)
 
2334
 
 
2335
if sys.platform == 'win32':
 
2336
    def open_file(filename, mode='r', bufsize=-1):
 
2337
        """This function is used to override the ``open`` builtin.
 
2338
 
 
2339
        But it uses O_NOINHERIT flag so the file handle is not inherited by
 
2340
        child processes.  Deleting or renaming a closed file opened with this
 
2341
        function is not blocking child processes.
 
2342
        """
 
2343
        writing = 'w' in mode
 
2344
        appending = 'a' in mode
 
2345
        updating = '+' in mode
 
2346
        binary = 'b' in mode
 
2347
 
 
2348
        flags = O_NOINHERIT
 
2349
        # see http://msdn.microsoft.com/en-us/library/yeby3zcb%28VS.71%29.aspx
 
2350
        # for flags for each modes.
 
2351
        if binary:
 
2352
            flags |= O_BINARY
 
2353
        else:
 
2354
            flags |= O_TEXT
 
2355
 
 
2356
        if writing:
 
2357
            if updating:
 
2358
                flags |= os.O_RDWR
 
2359
            else:
 
2360
                flags |= os.O_WRONLY
 
2361
            flags |= os.O_CREAT | os.O_TRUNC
 
2362
        elif appending:
 
2363
            if updating:
 
2364
                flags |= os.O_RDWR
 
2365
            else:
 
2366
                flags |= os.O_WRONLY
 
2367
            flags |= os.O_CREAT | os.O_APPEND
 
2368
        else: #reading
 
2369
            if updating:
 
2370
                flags |= os.O_RDWR
 
2371
            else:
 
2372
                flags |= os.O_RDONLY
 
2373
 
 
2374
        return os.fdopen(os.open(filename, flags), mode, bufsize)
 
2375
else:
 
2376
    open_file = open
 
2377
 
 
2378
 
 
2379
def getuser_unicode():
 
2380
    """Return the username as unicode.
 
2381
    """
 
2382
    try:
 
2383
        user_encoding = get_user_encoding()
 
2384
        username = getpass.getuser().decode(user_encoding)
 
2385
    except UnicodeDecodeError:
 
2386
        raise errors.BzrError("Can't decode username as %s." % \
 
2387
                user_encoding)
 
2388
    except ImportError, e:
 
2389
        if sys.platform != 'win32':
 
2390
            raise
 
2391
        if str(e) != 'No module named pwd':
 
2392
            raise
 
2393
        # https://bugs.launchpad.net/bzr/+bug/660174
 
2394
        # getpass.getuser() is unable to return username on Windows
 
2395
        # if there is no USERNAME environment variable set.
 
2396
        # That could be true if bzr is running as a service,
 
2397
        # e.g. running `bzr serve` as a service on Windows.
 
2398
        # We should not fail with traceback in this case.
 
2399
        username = u'UNKNOWN'
 
2400
    return username
 
2401
 
 
2402
 
 
2403
def available_backup_name(base, exists):
 
2404
    """Find a non-existing backup file name.
 
2405
 
 
2406
    This will *not* create anything, this only return a 'free' entry.  This
 
2407
    should be used for checking names in a directory below a locked
 
2408
    tree/branch/repo to avoid race conditions. This is LBYL (Look Before You
 
2409
    Leap) and generally discouraged.
 
2410
 
 
2411
    :param base: The base name.
 
2412
 
 
2413
    :param exists: A callable returning True if the path parameter exists.
 
2414
    """
 
2415
    counter = 1
 
2416
    name = "%s.~%d~" % (base, counter)
 
2417
    while exists(name):
 
2418
        counter += 1
 
2419
        name = "%s.~%d~" % (base, counter)
 
2420
    return name
 
2421
 
 
2422
 
 
2423
def set_fd_cloexec(fd):
 
2424
    """Set a Unix file descriptor's FD_CLOEXEC flag.  Do nothing if platform
 
2425
    support for this is not available.
 
2426
    """
 
2427
    try:
 
2428
        import fcntl
 
2429
        old = fcntl.fcntl(fd, fcntl.F_GETFD)
 
2430
        fcntl.fcntl(fd, fcntl.F_SETFD, old | fcntl.FD_CLOEXEC)
 
2431
    except (ImportError, AttributeError):
 
2432
        # Either the fcntl module or specific constants are not present
 
2433
        pass
 
2434
 
 
2435
 
 
2436
def find_executable_on_path(name):
 
2437
    """Finds an executable on the PATH.
 
2438
    
 
2439
    On Windows, this will try to append each extension in the PATHEXT
 
2440
    environment variable to the name, if it cannot be found with the name
 
2441
    as given.
 
2442
    
 
2443
    :param name: The base name of the executable.
 
2444
    :return: The path to the executable found or None.
 
2445
    """
 
2446
    path = os.environ.get('PATH')
 
2447
    if path is None:
 
2448
        return None
 
2449
    path = path.split(os.pathsep)
 
2450
    if sys.platform == 'win32':
 
2451
        exts = os.environ.get('PATHEXT', '').split(os.pathsep)
 
2452
        exts = [ext.lower() for ext in exts]
 
2453
        base, ext = os.path.splitext(name)
 
2454
        if ext != '':
 
2455
            if ext.lower() not in exts:
 
2456
                return None
 
2457
            name = base
 
2458
            exts = [ext]
 
2459
    else:
 
2460
        exts = ['']
 
2461
    for ext in exts:
 
2462
        for d in path:
 
2463
            f = os.path.join(d, name) + ext
 
2464
            if os.access(f, os.X_OK):
 
2465
                return f
 
2466
    return None
 
2467
 
 
2468
 
 
2469
def _posix_is_local_pid_dead(pid):
 
2470
    """True if pid doesn't correspond to live process on this machine"""
 
2471
    try:
 
2472
        # Special meaning of unix kill: just check if it's there.
 
2473
        os.kill(pid, 0)
 
2474
    except OSError, e:
 
2475
        if e.errno == errno.ESRCH:
 
2476
            # On this machine, and really not found: as sure as we can be
 
2477
            # that it's dead.
 
2478
            return True
 
2479
        elif e.errno == errno.EPERM:
 
2480
            # exists, though not ours
 
2481
            return False
 
2482
        else:
 
2483
            mutter("os.kill(%d, 0) failed: %s" % (pid, e))
 
2484
            # Don't really know.
 
2485
            return False
 
2486
    else:
 
2487
        # Exists and our process: not dead.
 
2488
        return False
 
2489
 
 
2490
if sys.platform == "win32":
 
2491
    is_local_pid_dead = win32utils.is_local_pid_dead
 
2492
else:
 
2493
    is_local_pid_dead = _posix_is_local_pid_dead
 
2494
 
 
2495
 
 
2496
def fdatasync(fileno):
 
2497
    """Flush file contents to disk if possible.
 
2498
    
 
2499
    :param fileno: Integer OS file handle.
 
2500
    :raises TransportNotPossible: If flushing to disk is not possible.
 
2501
    """
 
2502
    fn = getattr(os, 'fdatasync', getattr(os, 'fsync', None))
 
2503
    if fn is not None:
 
2504
        fn(fileno)