~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2006-08-17 07:52:09 UTC
  • mfrom: (1910.3.4 trivial)
  • Revision ID: pqm@pqm.ubuntu.com-20060817075209-e85a1f9e05ff8b87
(andrew) Trivial fixes to NotImplemented errors.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
1
# Bazaar -- distributed version control
 
2
#
 
3
# Copyright (C) 2005 by Canonical Ltd
2
4
#
3
5
# This program is free software; you can redistribute it and/or modify
4
6
# it under the terms of the GNU General Public License as published by
15
17
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
18
 
17
19
from cStringIO import StringIO
18
 
import os
19
 
import re
20
 
import stat
21
 
from stat import (S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE,
22
 
                  S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
23
 
import sys
24
 
import time
25
 
 
26
 
from bzrlib.lazy_import import lazy_import
27
 
lazy_import(globals(), """
28
 
import codecs
29
 
from datetime import datetime
30
20
import errno
31
21
from ntpath import (abspath as _nt_abspath,
32
22
                    join as _nt_join,
34
24
                    realpath as _nt_realpath,
35
25
                    splitdrive as _nt_splitdrive,
36
26
                    )
 
27
import os
 
28
from os import listdir
37
29
import posixpath
 
30
import re
38
31
import sha
39
32
import shutil
40
 
from shutil import (
41
 
    rmtree,
42
 
    )
 
33
from shutil import copyfile
 
34
import stat
 
35
from stat import (S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE,
 
36
                  S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
 
37
import string
 
38
import sys
 
39
import time
 
40
import types
43
41
import tempfile
44
 
from tempfile import (
45
 
    mkdtemp,
46
 
    )
47
42
import unicodedata
48
43
 
49
 
from bzrlib import (
50
 
    cache_utf8,
51
 
    errors,
52
 
    win32utils,
53
 
    )
54
 
""")
55
 
 
56
44
import bzrlib
57
 
from bzrlib import symbol_versioning
58
 
from bzrlib.symbol_versioning import (
59
 
    deprecated_function,
60
 
    )
 
45
from bzrlib.errors import (BzrError,
 
46
                           BzrBadParameterNotUnicode,
 
47
                           NoSuchFile,
 
48
                           PathNotChild,
 
49
                           IllegalPath,
 
50
                           )
 
51
from bzrlib.symbol_versioning import (deprecated_function, 
 
52
        zero_nine)
61
53
from bzrlib.trace import mutter
62
54
 
63
55
 
68
60
# OR with 0 on those platforms
69
61
O_BINARY = getattr(os, 'O_BINARY', 0)
70
62
 
71
 
# On posix, use lstat instead of stat so that we can
72
 
# operate on broken symlinks. On Windows revert to stat.
73
 
lstat = getattr(os, 'lstat', os.stat)
74
63
 
75
64
def make_readonly(filename):
76
65
    """Make a filename read-only."""
77
 
    mod = lstat(filename).st_mode
78
 
    if not stat.S_ISLNK(mod):
79
 
        mod = mod & 0777555
80
 
        os.chmod(filename, mod)
 
66
    mod = os.stat(filename).st_mode
 
67
    mod = mod & 0777555
 
68
    os.chmod(filename, mod)
81
69
 
82
70
 
83
71
def make_writable(filename):
84
 
    mod = lstat(filename).st_mode
85
 
    if not stat.S_ISLNK(mod):
86
 
        mod = mod | 0200
87
 
        os.chmod(filename, mod)
88
 
 
89
 
 
90
 
def minimum_path_selection(paths):
91
 
    """Return the smallset subset of paths which are outside paths.
92
 
 
93
 
    :param paths: A container (and hence not None) of paths.
94
 
    :return: A set of paths sufficient to include everything in paths via
95
 
        is_inside_any, drawn from the paths parameter.
96
 
    """
97
 
    search_paths = set()
98
 
    paths = set(paths)
99
 
    for path in paths:
100
 
        other_paths = paths.difference([path])
101
 
        if not is_inside_any(other_paths, path):
102
 
            # this is a top level path, we must check it.
103
 
            search_paths.add(path)
104
 
    return search_paths
 
72
    mod = os.stat(filename).st_mode
 
73
    mod = mod | 0200
 
74
    os.chmod(filename, mod)
105
75
 
106
76
 
107
77
_QUOTE_RE = None
114
84
    Windows."""
115
85
    # TODO: I'm not really sure this is the best format either.x
116
86
    global _QUOTE_RE
117
 
    if _QUOTE_RE is None:
 
87
    if _QUOTE_RE == None:
118
88
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
119
89
        
120
90
    if _QUOTE_RE.search(f):
152
122
        return _mapper(_lstat(f).st_mode)
153
123
    except OSError, e:
154
124
        if getattr(e, 'errno', None) == errno.ENOENT:
155
 
            raise errors.NoSuchFile(f)
 
125
            raise bzrlib.errors.NoSuchFile(f)
156
126
        raise
157
127
 
158
128
 
166
136
    return umask
167
137
 
168
138
 
169
 
_kind_marker_map = {
170
 
    "file": "",
171
 
    _directory_kind: "/",
172
 
    "symlink": "@",
173
 
    'tree-reference': '+',
174
 
}
175
 
 
176
 
 
177
139
def kind_marker(kind):
178
 
    try:
179
 
        return _kind_marker_map[kind]
180
 
    except KeyError:
181
 
        raise errors.BzrError('invalid file kind %r' % kind)
182
 
 
 
140
    if kind == 'file':
 
141
        return ''
 
142
    elif kind == _directory_kind:
 
143
        return '/'
 
144
    elif kind == 'symlink':
 
145
        return '@'
 
146
    else:
 
147
        raise BzrError('invalid file kind %r' % kind)
183
148
 
184
149
lexists = getattr(os.path, 'lexists', None)
185
150
if lexists is None:
186
151
    def lexists(f):
187
152
        try:
188
 
            stat = getattr(os, 'lstat', os.stat)
189
 
            stat(f)
 
153
            if hasattr(os, 'lstat'):
 
154
                os.lstat(f)
 
155
            else:
 
156
                os.stat(f)
190
157
            return True
191
 
        except OSError, e:
 
158
        except OSError,e:
192
159
            if e.errno == errno.ENOENT:
193
160
                return False;
194
161
            else:
195
 
                raise errors.BzrError("lstat/stat of (%r): %r" % (f, e))
 
162
                raise BzrError("lstat/stat of (%r): %r" % (f, e))
196
163
 
197
164
 
198
165
def fancy_rename(old, new, rename_func, unlink_func):
219
186
    file_existed = False
220
187
    try:
221
188
        rename_func(new, tmp_name)
222
 
    except (errors.NoSuchFile,), e:
 
189
    except (NoSuchFile,), e:
223
190
        pass
224
191
    except IOError, e:
225
192
        # RBC 20060103 abstraction leakage: the paramiko SFTP clients rename
226
 
        # function raises an IOError with errno is None when a rename fails.
 
193
        # function raises an IOError with errno == None when a rename fails.
227
194
        # This then gets caught here.
228
195
        if e.errno not in (None, errno.ENOENT, errno.ENOTDIR):
229
196
            raise
230
197
    except Exception, e:
231
 
        if (getattr(e, 'errno', None) is None
 
198
        if (not hasattr(e, 'errno') 
232
199
            or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
233
200
            raise
234
201
    else:
254
221
# choke on a Unicode string containing a relative path if
255
222
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
256
223
# string.
257
 
_fs_enc = sys.getfilesystemencoding() or 'utf-8'
 
224
_fs_enc = sys.getfilesystemencoding()
258
225
def _posix_abspath(path):
259
226
    # jam 20060426 rather than encoding to fsencoding
260
227
    # copy posixpath.abspath, but use os.getcwdu instead
285
252
    return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
286
253
 
287
254
 
288
 
def _win98_abspath(path):
289
 
    """Return the absolute version of a path.
290
 
    Windows 98 safe implementation (python reimplementation
291
 
    of Win32 API function GetFullPathNameW)
292
 
    """
293
 
    # Corner cases:
294
 
    #   C:\path     => C:/path
295
 
    #   C:/path     => C:/path
296
 
    #   \\HOST\path => //HOST/path
297
 
    #   //HOST/path => //HOST/path
298
 
    #   path        => C:/cwd/path
299
 
    #   /path       => C:/path
300
 
    path = unicode(path)
301
 
    # check for absolute path
302
 
    drive = _nt_splitdrive(path)[0]
303
 
    if drive == '' and path[:2] not in('//','\\\\'):
304
 
        cwd = os.getcwdu()
305
 
        # we cannot simply os.path.join cwd and path
306
 
        # because os.path.join('C:','/path') produce '/path'
307
 
        # and this is incorrect
308
 
        if path[:1] in ('/','\\'):
309
 
            cwd = _nt_splitdrive(cwd)[0]
310
 
            path = path[1:]
311
 
        path = cwd + '\\' + path
312
 
    return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
313
 
 
314
 
if win32utils.winver == 'Windows 98':
315
 
    _win32_abspath = _win98_abspath
316
 
 
317
 
 
318
255
def _win32_realpath(path):
319
256
    # Real _nt_realpath doesn't have a problem with a unicode cwd
320
257
    return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
365
302
pathjoin = os.path.join
366
303
normpath = os.path.normpath
367
304
getcwd = os.getcwdu
 
305
mkdtemp = tempfile.mkdtemp
368
306
rename = os.rename
369
307
dirname = os.path.dirname
370
308
basename = os.path.basename
371
 
split = os.path.split
372
 
splitext = os.path.splitext
373
 
# These were already imported into local scope
374
 
# mkdtemp = tempfile.mkdtemp
375
 
# rmtree = shutil.rmtree
 
309
rmtree = shutil.rmtree
376
310
 
377
311
MIN_ABS_PATHLENGTH = 1
378
312
 
392
326
        """Error handler for shutil.rmtree function [for win32]
393
327
        Helps to remove files and dirs marked as read-only.
394
328
        """
395
 
        exception = excinfo[1]
 
329
        type_, value = excinfo[:2]
396
330
        if function in (os.remove, os.rmdir) \
397
 
            and isinstance(exception, OSError) \
398
 
            and exception.errno == errno.EACCES:
399
 
            make_writable(path)
 
331
            and type_ == OSError \
 
332
            and value.errno == errno.EACCES:
 
333
            bzrlib.osutils.make_writable(path)
400
334
            function(path)
401
335
        else:
402
336
            raise
432
366
            mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
433
367
    else:
434
368
        mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
435
 
    if output_encoding == 'cp0':
436
 
        # invalid encoding (cp0 means 'no codepage' on Windows)
437
 
        output_encoding = bzrlib.user_encoding
438
 
        mutter('cp0 is invalid encoding.'
439
 
               ' encoding stdout as bzrlib.user_encoding %r', output_encoding)
440
 
    # check encoding
441
 
    try:
442
 
        codecs.lookup(output_encoding)
443
 
    except LookupError:
444
 
        sys.stderr.write('bzr: warning:'
445
 
                         ' unknown terminal encoding %s.\n'
446
 
                         '  Using encoding %s instead.\n'
447
 
                         % (output_encoding, bzrlib.user_encoding)
448
 
                        )
449
 
        output_encoding = bzrlib.user_encoding
450
 
 
451
369
    return output_encoding
452
370
 
453
371
 
454
372
def normalizepath(f):
455
 
    if getattr(os.path, 'realpath', None) is not None:
 
373
    if hasattr(os.path, 'realpath'):
456
374
        F = realpath
457
375
    else:
458
376
        F = abspath
522
440
    
523
441
    The empty string as a dir name is taken as top-of-tree and matches 
524
442
    everything.
 
443
    
 
444
    >>> is_inside('src', pathjoin('src', 'foo.c'))
 
445
    True
 
446
    >>> is_inside('src', 'srccontrol')
 
447
    False
 
448
    >>> is_inside('src', pathjoin('src', 'a', 'a', 'a', 'foo.c'))
 
449
    True
 
450
    >>> is_inside('foo.c', 'foo.c')
 
451
    True
 
452
    >>> is_inside('foo.c', '')
 
453
    False
 
454
    >>> is_inside('', 'foo.c')
 
455
    True
525
456
    """
526
457
    # XXX: Most callers of this can actually do something smarter by 
527
458
    # looking at the inventory
542
473
    for dirname in dir_list:
543
474
        if is_inside(dirname, fname):
544
475
            return True
545
 
    return False
 
476
    else:
 
477
        return False
546
478
 
547
479
 
548
480
def is_inside_or_parent_of_any(dir_list, fname):
550
482
    for dirname in dir_list:
551
483
        if is_inside(dirname, fname) or is_inside(fname, dirname):
552
484
            return True
553
 
    return False
 
485
    else:
 
486
        return False
554
487
 
555
488
 
556
489
def pumpfile(fromfile, tofile):
557
 
    """Copy contents of one file to another.
558
 
    
559
 
    :return: The number of bytes copied.
560
 
    """
 
490
    """Copy contents of one file to another."""
561
491
    BUFSIZE = 32768
562
 
    length = 0
563
492
    while True:
564
493
        b = fromfile.read(BUFSIZE)
565
494
        if not b:
566
495
            break
567
496
        tofile.write(b)
568
 
        length += len(b)
569
 
    return length
570
497
 
571
498
 
572
499
def file_iterator(input_file, readsize=32768):
578
505
 
579
506
 
580
507
def sha_file(f):
581
 
    if getattr(f, 'tell', None) is not None:
 
508
    if hasattr(f, 'tell'):
582
509
        assert f.tell() == 0
583
510
    s = sha.new()
584
511
    BUFSIZE = 128<<10
590
517
    return s.hexdigest()
591
518
 
592
519
 
593
 
def sha_file_by_name(fname):
594
 
    """Calculate the SHA1 of a file by reading the full text"""
595
 
    s = sha.new()
596
 
    f = os.open(fname, os.O_RDONLY | O_BINARY)
597
 
    try:
598
 
        while True:
599
 
            b = os.read(f, 1<<16)
600
 
            if not b:
601
 
                return s.hexdigest()
602
 
            s.update(b)
603
 
    finally:
604
 
        os.close(f)
605
 
 
606
 
 
607
 
def sha_strings(strings, _factory=sha.new):
 
520
 
 
521
def sha_strings(strings):
608
522
    """Return the sha-1 of concatenation of strings"""
609
 
    s = _factory()
 
523
    s = sha.new()
610
524
    map(s.update, strings)
611
525
    return s.hexdigest()
612
526
 
613
527
 
614
 
def sha_string(f, _factory=sha.new):
615
 
    return _factory(f).hexdigest()
 
528
def sha_string(f):
 
529
    s = sha.new()
 
530
    s.update(f)
 
531
    return s.hexdigest()
616
532
 
617
533
 
618
534
def fingerprint_file(f):
 
535
    s = sha.new()
619
536
    b = f.read()
620
 
    return {'size': len(b),
621
 
            'sha1': sha.new(b).hexdigest()}
 
537
    s.update(b)
 
538
    size = len(b)
 
539
    return {'size': size,
 
540
            'sha1': s.hexdigest()}
622
541
 
623
542
 
624
543
def compare_files(a, b):
635
554
 
636
555
def local_time_offset(t=None):
637
556
    """Return offset of local zone from GMT, either at present or at time t."""
638
 
    if t is None:
 
557
    # python2.3 localtime() can't take None
 
558
    if t == None:
639
559
        t = time.time()
640
 
    offset = datetime.fromtimestamp(t) - datetime.utcfromtimestamp(t)
641
 
    return offset.days * 86400 + offset.seconds
 
560
        
 
561
    if time.localtime(t).tm_isdst and time.daylight:
 
562
        return -time.altzone
 
563
    else:
 
564
        return -time.timezone
642
565
 
643
566
    
644
 
def format_date(t, offset=0, timezone='original', date_fmt=None,
 
567
def format_date(t, offset=0, timezone='original', date_fmt=None, 
645
568
                show_offset=True):
646
 
    """Return a formatted date string.
647
 
 
648
 
    :param t: Seconds since the epoch.
649
 
    :param offset: Timezone offset in seconds east of utc.
650
 
    :param timezone: How to display the time: 'utc', 'original' for the
651
 
         timezone specified by offset, or 'local' for the process's current
652
 
         timezone.
653
 
    :param show_offset: Whether to append the timezone.
654
 
    :param date_fmt: strftime format.
655
 
    """
 
569
    ## TODO: Perhaps a global option to use either universal or local time?
 
570
    ## Or perhaps just let people set $TZ?
 
571
    assert isinstance(t, float)
 
572
    
656
573
    if timezone == 'utc':
657
574
        tt = time.gmtime(t)
658
575
        offset = 0
659
576
    elif timezone == 'original':
660
 
        if offset is None:
 
577
        if offset == None:
661
578
            offset = 0
662
579
        tt = time.gmtime(t + offset)
663
580
    elif timezone == 'local':
664
581
        tt = time.localtime(t)
665
582
        offset = local_time_offset(t)
666
583
    else:
667
 
        raise errors.BzrError("unsupported timezone format %r" % timezone,
668
 
                              ['options are "utc", "original", "local"'])
 
584
        raise BzrError("unsupported timezone format %r" % timezone,
 
585
                       ['options are "utc", "original", "local"'])
669
586
    if date_fmt is None:
670
587
        date_fmt = "%a %Y-%m-%d %H:%M:%S"
671
588
    if show_offset:
679
596
    return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
680
597
    
681
598
 
682
 
def format_delta(delta):
683
 
    """Get a nice looking string for a time delta.
684
 
 
685
 
    :param delta: The time difference in seconds, can be positive or negative.
686
 
        positive indicates time in the past, negative indicates time in the
687
 
        future. (usually time.time() - stored_time)
688
 
    :return: String formatted to show approximate resolution
689
 
    """
690
 
    delta = int(delta)
691
 
    if delta >= 0:
692
 
        direction = 'ago'
693
 
    else:
694
 
        direction = 'in the future'
695
 
        delta = -delta
696
 
 
697
 
    seconds = delta
698
 
    if seconds < 90: # print seconds up to 90 seconds
699
 
        if seconds == 1:
700
 
            return '%d second %s' % (seconds, direction,)
701
 
        else:
702
 
            return '%d seconds %s' % (seconds, direction)
703
 
 
704
 
    minutes = int(seconds / 60)
705
 
    seconds -= 60 * minutes
706
 
    if seconds == 1:
707
 
        plural_seconds = ''
708
 
    else:
709
 
        plural_seconds = 's'
710
 
    if minutes < 90: # print minutes, seconds up to 90 minutes
711
 
        if minutes == 1:
712
 
            return '%d minute, %d second%s %s' % (
713
 
                    minutes, seconds, plural_seconds, direction)
714
 
        else:
715
 
            return '%d minutes, %d second%s %s' % (
716
 
                    minutes, seconds, plural_seconds, direction)
717
 
 
718
 
    hours = int(minutes / 60)
719
 
    minutes -= 60 * hours
720
 
    if minutes == 1:
721
 
        plural_minutes = ''
722
 
    else:
723
 
        plural_minutes = 's'
724
 
 
725
 
    if hours == 1:
726
 
        return '%d hour, %d minute%s %s' % (hours, minutes,
727
 
                                            plural_minutes, direction)
728
 
    return '%d hours, %d minute%s %s' % (hours, minutes,
729
 
                                         plural_minutes, direction)
730
599
 
731
600
def filesize(f):
732
601
    """Return size of given open file."""
742
611
except (NotImplementedError, AttributeError):
743
612
    # If python doesn't have os.urandom, or it doesn't work,
744
613
    # then try to first pull random data from /dev/urandom
745
 
    try:
 
614
    if os.path.exists("/dev/urandom"):
746
615
        rand_bytes = file('/dev/urandom', 'rb').read
747
616
    # Otherwise, use this hack as a last resort
748
 
    except (IOError, OSError):
 
617
    else:
749
618
        # not well seeded, but better than nothing
750
619
        def rand_bytes(n):
751
620
            import random
773
642
## decomposition (might be too tricksy though.)
774
643
 
775
644
def splitpath(p):
776
 
    """Turn string into list of parts."""
777
 
    assert isinstance(p, basestring)
 
645
    """Turn string into list of parts.
 
646
 
 
647
    >>> splitpath('a')
 
648
    ['a']
 
649
    >>> splitpath('a/b')
 
650
    ['a', 'b']
 
651
    >>> splitpath('a/./b')
 
652
    ['a', 'b']
 
653
    >>> splitpath('a/.b')
 
654
    ['a', '.b']
 
655
    >>> splitpath('a/../b')
 
656
    Traceback (most recent call last):
 
657
    ...
 
658
    BzrError: sorry, '..' not allowed in path
 
659
    """
 
660
    assert isinstance(p, types.StringTypes)
778
661
 
779
662
    # split on either delimiter because people might use either on
780
663
    # Windows
783
666
    rps = []
784
667
    for f in ps:
785
668
        if f == '..':
786
 
            raise errors.BzrError("sorry, %r not allowed in path" % f)
 
669
            raise BzrError("sorry, %r not allowed in path" % f)
787
670
        elif (f == '.') or (f == ''):
788
671
            pass
789
672
        else:
791
674
    return rps
792
675
 
793
676
def joinpath(p):
794
 
    assert isinstance(p, (list, tuple))
 
677
    assert isinstance(p, list)
795
678
    for f in p:
796
 
        if (f == '..') or (f is None) or (f == ''):
797
 
            raise errors.BzrError("sorry, %r not allowed in path" % f)
 
679
        if (f == '..') or (f == None) or (f == ''):
 
680
            raise BzrError("sorry, %r not allowed in path" % f)
798
681
    return pathjoin(*p)
799
682
 
800
683
 
 
684
@deprecated_function(zero_nine)
 
685
def appendpath(p1, p2):
 
686
    if p1 == '':
 
687
        return p2
 
688
    else:
 
689
        return pathjoin(p1, p2)
 
690
    
 
691
 
801
692
def split_lines(s):
802
693
    """Split s into lines, but without removing the newline characters."""
803
694
    lines = s.split('\n')
814
705
def link_or_copy(src, dest):
815
706
    """Hardlink a file, or copy it if it can't be hardlinked."""
816
707
    if not hardlinks_good():
817
 
        shutil.copyfile(src, dest)
 
708
        copyfile(src, dest)
818
709
        return
819
710
    try:
820
711
        os.link(src, dest)
821
712
    except (OSError, IOError), e:
822
713
        if e.errno != errno.EXDEV:
823
714
            raise
824
 
        shutil.copyfile(src, dest)
825
 
 
826
 
 
827
 
# Look Before You Leap (LBYL) is appropriate here instead of Easier to Ask for
828
 
# Forgiveness than Permission (EAFP) because:
829
 
# - root can damage a solaris file system by using unlink,
830
 
# - unlink raises different exceptions on different OSes (linux: EISDIR, win32:
831
 
#   EACCES, OSX: EPERM) when invoked on a directory.
832
 
def delete_any(path):
 
715
        copyfile(src, dest)
 
716
 
 
717
def delete_any(full_path):
833
718
    """Delete a file or directory."""
834
 
    if isdir(path): # Takes care of symlinks
835
 
        os.rmdir(path)
836
 
    else:
837
 
        os.unlink(path)
 
719
    try:
 
720
        os.unlink(full_path)
 
721
    except OSError, e:
 
722
    # We may be renaming a dangling inventory id
 
723
        if e.errno not in (errno.EISDIR, errno.EACCES, errno.EPERM):
 
724
            raise
 
725
        os.rmdir(full_path)
838
726
 
839
727
 
840
728
def has_symlinks():
841
 
    if getattr(os, 'symlink', None) is not None:
 
729
    if hasattr(os, 'symlink'):
842
730
        return True
843
731
    else:
844
732
        return False
845
 
 
 
733
        
846
734
 
847
735
def contains_whitespace(s):
848
736
    """True if there are any whitespace characters in s."""
849
 
    # string.whitespace can include '\xa0' in certain locales, because it is
850
 
    # considered "non-breaking-space" as part of ISO-8859-1. But it
851
 
    # 1) Isn't a breaking whitespace
852
 
    # 2) Isn't one of ' \t\r\n' which are characters we sometimes use as
853
 
    #    separators
854
 
    # 3) '\xa0' isn't unicode safe since it is >128.
855
 
 
856
 
    # This should *not* be a unicode set of characters in case the source
857
 
    # string is not a Unicode string. We can auto-up-cast the characters since
858
 
    # they are ascii, but we don't want to auto-up-cast the string in case it
859
 
    # is utf-8
860
 
    for ch in ' \t\n\r\v\f':
 
737
    for ch in string.whitespace:
861
738
        if ch in s:
862
739
            return True
863
740
    else:
899
776
        if tail:
900
777
            s.insert(0, tail)
901
778
    else:
902
 
        raise errors.PathNotChild(rp, base)
 
779
        raise PathNotChild(rp, base)
903
780
 
904
781
    if s:
905
782
        return pathjoin(*s)
920
797
    try:
921
798
        return unicode_or_utf8_string.decode('utf8')
922
799
    except UnicodeDecodeError:
923
 
        raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
924
 
 
925
 
 
926
 
def safe_utf8(unicode_or_utf8_string):
927
 
    """Coerce unicode_or_utf8_string to a utf8 string.
928
 
 
929
 
    If it is a str, it is returned.
930
 
    If it is Unicode, it is encoded into a utf-8 string.
931
 
    """
932
 
    if isinstance(unicode_or_utf8_string, str):
933
 
        # TODO: jam 20070209 This is overkill, and probably has an impact on
934
 
        #       performance if we are dealing with lots of apis that want a
935
 
        #       utf-8 revision id
936
 
        try:
937
 
            # Make sure it is a valid utf-8 string
938
 
            unicode_or_utf8_string.decode('utf-8')
939
 
        except UnicodeDecodeError:
940
 
            raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
941
 
        return unicode_or_utf8_string
942
 
    return unicode_or_utf8_string.encode('utf-8')
943
 
 
944
 
 
945
 
_revision_id_warning = ('Unicode revision ids were deprecated in bzr 0.15.'
946
 
                        ' Revision id generators should be creating utf8'
947
 
                        ' revision ids.')
948
 
 
949
 
 
950
 
def safe_revision_id(unicode_or_utf8_string, warn=True):
951
 
    """Revision ids should now be utf8, but at one point they were unicode.
952
 
 
953
 
    :param unicode_or_utf8_string: A possibly Unicode revision_id. (can also be
954
 
        utf8 or None).
955
 
    :param warn: Functions that are sanitizing user data can set warn=False
956
 
    :return: None or a utf8 revision id.
957
 
    """
958
 
    if (unicode_or_utf8_string is None
959
 
        or unicode_or_utf8_string.__class__ == str):
960
 
        return unicode_or_utf8_string
961
 
    if warn:
962
 
        symbol_versioning.warn(_revision_id_warning, DeprecationWarning,
963
 
                               stacklevel=2)
964
 
    return cache_utf8.encode(unicode_or_utf8_string)
965
 
 
966
 
 
967
 
_file_id_warning = ('Unicode file ids were deprecated in bzr 0.15. File id'
968
 
                    ' generators should be creating utf8 file ids.')
969
 
 
970
 
 
971
 
def safe_file_id(unicode_or_utf8_string, warn=True):
972
 
    """File ids should now be utf8, but at one point they were unicode.
973
 
 
974
 
    This is the same as safe_utf8, except it uses the cached encode functions
975
 
    to save a little bit of performance.
976
 
 
977
 
    :param unicode_or_utf8_string: A possibly Unicode file_id. (can also be
978
 
        utf8 or None).
979
 
    :param warn: Functions that are sanitizing user data can set warn=False
980
 
    :return: None or a utf8 file id.
981
 
    """
982
 
    if (unicode_or_utf8_string is None
983
 
        or unicode_or_utf8_string.__class__ == str):
984
 
        return unicode_or_utf8_string
985
 
    if warn:
986
 
        symbol_versioning.warn(_file_id_warning, DeprecationWarning,
987
 
                               stacklevel=2)
988
 
    return cache_utf8.encode(unicode_or_utf8_string)
 
800
        raise BzrBadParameterNotUnicode(unicode_or_utf8_string)
989
801
 
990
802
 
991
803
_platform_normalizes_filenames = False
1035
847
def terminal_width():
1036
848
    """Return estimated terminal width."""
1037
849
    if sys.platform == 'win32':
1038
 
        return win32utils.get_console_size()[0]
 
850
        import bzrlib.win32console
 
851
        return bzrlib.win32console.get_console_size()[0]
1039
852
    width = 0
1040
853
    try:
1041
854
        import struct, fcntl, termios
1054
867
 
1055
868
    return width
1056
869
 
1057
 
 
1058
870
def supports_executable():
1059
871
    return sys.platform != "win32"
1060
872
 
1061
873
 
1062
 
def supports_posix_readonly():
1063
 
    """Return True if 'readonly' has POSIX semantics, False otherwise.
1064
 
 
1065
 
    Notably, a win32 readonly file cannot be deleted, unlike POSIX where the
1066
 
    directory controls creation/deletion, etc.
1067
 
 
1068
 
    And under win32, readonly means that the directory itself cannot be
1069
 
    deleted.  The contents of a readonly directory can be changed, unlike POSIX
1070
 
    where files in readonly directories cannot be added, deleted or renamed.
1071
 
    """
1072
 
    return sys.platform != "win32"
1073
 
 
1074
 
 
1075
 
def set_or_unset_env(env_variable, value):
1076
 
    """Modify the environment, setting or removing the env_variable.
1077
 
 
1078
 
    :param env_variable: The environment variable in question
1079
 
    :param value: The value to set the environment to. If None, then
1080
 
        the variable will be removed.
1081
 
    :return: The original value of the environment variable.
1082
 
    """
1083
 
    orig_val = os.environ.get(env_variable)
1084
 
    if value is None:
1085
 
        if orig_val is not None:
1086
 
            del os.environ[env_variable]
1087
 
    else:
1088
 
        if isinstance(value, unicode):
1089
 
            value = value.encode(bzrlib.user_encoding)
1090
 
        os.environ[env_variable] = value
1091
 
    return orig_val
1092
 
 
1093
 
 
1094
874
_validWin32PathRE = re.compile(r'^([A-Za-z]:[/\\])?[^:<>*"?\|]*$')
1095
875
 
1096
876
 
1102
882
    if sys.platform != "win32":
1103
883
        return
1104
884
    if _validWin32PathRE.match(path) is None:
1105
 
        raise errors.IllegalPath(path)
 
885
        raise IllegalPath(path)
1106
886
 
1107
887
 
1108
888
def walkdirs(top, prefix=""):
1114
894
    
1115
895
    The data yielded is of the form:
1116
896
    ((directory-relpath, directory-path-from-top),
1117
 
    [(relpath, basename, kind, lstat, path-from-top), ...]),
 
897
    [(relpath, basename, kind, lstat), ...]),
1118
898
     - directory-relpath is the relative path of the directory being returned
1119
899
       with respect to top. prefix is prepended to this.
1120
900
     - directory-path-from-root is the path including top for this directory. 
1138
918
    # depending on top and prefix - i.e. ./foo and foo as a pair leads to
1139
919
    # potentially confusing output. We should make this more robust - but
1140
920
    # not at a speed cost. RBC 20060731
1141
 
    _lstat = os.lstat
 
921
    lstat = os.lstat
 
922
    pending = []
1142
923
    _directory = _directory_kind
1143
 
    _listdir = os.listdir
1144
 
    _kind_from_mode = _formats.get
1145
 
    pending = [(safe_unicode(prefix), "", _directory, None, safe_unicode(top))]
 
924
    _listdir = listdir
 
925
    pending = [(prefix, "", _directory, None, top)]
1146
926
    while pending:
 
927
        dirblock = []
 
928
        currentdir = pending.pop()
1147
929
        # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1148
 
        relroot, _, _, _, top = pending.pop()
1149
 
        if relroot:
1150
 
            relprefix = relroot + u'/'
1151
 
        else:
1152
 
            relprefix = ''
1153
 
        top_slash = top + u'/'
1154
 
 
1155
 
        dirblock = []
1156
 
        append = dirblock.append
1157
 
        for name in sorted(_listdir(top)):
1158
 
            abspath = top_slash + name
1159
 
            statvalue = _lstat(abspath)
1160
 
            kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
1161
 
            append((relprefix + name, name, kind, statvalue, abspath))
1162
 
        yield (relroot, top), dirblock
1163
 
 
1164
 
        # push the user specified dirs from dirblock
1165
 
        pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1166
 
 
1167
 
 
1168
 
def _walkdirs_utf8(top, prefix=""):
1169
 
    """Yield data about all the directories in a tree.
1170
 
 
1171
 
    This yields the same information as walkdirs() only each entry is yielded
1172
 
    in utf-8. On platforms which have a filesystem encoding of utf8 the paths
1173
 
    are returned as exact byte-strings.
1174
 
 
1175
 
    :return: yields a tuple of (dir_info, [file_info])
1176
 
        dir_info is (utf8_relpath, path-from-top)
1177
 
        file_info is (utf8_relpath, utf8_name, kind, lstat, path-from-top)
1178
 
        if top is an absolute path, path-from-top is also an absolute path.
1179
 
        path-from-top might be unicode or utf8, but it is the correct path to
1180
 
        pass to os functions to affect the file in question. (such as os.lstat)
1181
 
    """
1182
 
    fs_encoding = _fs_enc.upper()
1183
 
    if (sys.platform == 'win32' or
1184
 
        fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968')): # ascii
1185
 
        return _walkdirs_unicode_to_utf8(top, prefix=prefix)
1186
 
    else:
1187
 
        return _walkdirs_fs_utf8(top, prefix=prefix)
1188
 
 
1189
 
 
1190
 
def _walkdirs_fs_utf8(top, prefix=""):
1191
 
    """See _walkdirs_utf8.
1192
 
 
1193
 
    This sub-function is called when we know the filesystem is already in utf8
1194
 
    encoding. So we don't need to transcode filenames.
1195
 
    """
1196
 
    _lstat = os.lstat
1197
 
    _directory = _directory_kind
1198
 
    _listdir = os.listdir
1199
 
    _kind_from_mode = _formats.get
1200
 
 
1201
 
    # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1202
 
    # But we don't actually uses 1-3 in pending, so set them to None
1203
 
    pending = [(safe_utf8(prefix), None, None, None, safe_utf8(top))]
1204
 
    while pending:
1205
 
        relroot, _, _, _, top = pending.pop()
1206
 
        if relroot:
1207
 
            relprefix = relroot + '/'
1208
 
        else:
1209
 
            relprefix = ''
1210
 
        top_slash = top + '/'
1211
 
 
1212
 
        dirblock = []
1213
 
        append = dirblock.append
1214
 
        for name in sorted(_listdir(top)):
1215
 
            abspath = top_slash + name
1216
 
            statvalue = _lstat(abspath)
1217
 
            kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
1218
 
            append((relprefix + name, name, kind, statvalue, abspath))
1219
 
        yield (relroot, top), dirblock
1220
 
 
1221
 
        # push the user specified dirs from dirblock
1222
 
        pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1223
 
 
1224
 
 
1225
 
def _walkdirs_unicode_to_utf8(top, prefix=""):
1226
 
    """See _walkdirs_utf8
1227
 
 
1228
 
    Because Win32 has a Unicode api, all of the 'path-from-top' entries will be
1229
 
    Unicode paths.
1230
 
    This is currently the fallback code path when the filesystem encoding is
1231
 
    not UTF-8. It may be better to implement an alternative so that we can
1232
 
    safely handle paths that are not properly decodable in the current
1233
 
    encoding.
1234
 
    """
1235
 
    _utf8_encode = codecs.getencoder('utf8')
1236
 
    _lstat = os.lstat
1237
 
    _directory = _directory_kind
1238
 
    _listdir = os.listdir
1239
 
    _kind_from_mode = _formats.get
1240
 
 
1241
 
    pending = [(safe_utf8(prefix), None, None, None, safe_unicode(top))]
1242
 
    while pending:
1243
 
        relroot, _, _, _, top = pending.pop()
1244
 
        if relroot:
1245
 
            relprefix = relroot + '/'
1246
 
        else:
1247
 
            relprefix = ''
1248
 
        top_slash = top + u'/'
1249
 
 
1250
 
        dirblock = []
1251
 
        append = dirblock.append
1252
 
        for name in sorted(_listdir(top)):
1253
 
            name_utf8 = _utf8_encode(name)[0]
1254
 
            abspath = top_slash + name
1255
 
            statvalue = _lstat(abspath)
1256
 
            kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
1257
 
            append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
1258
 
        yield (relroot, top), dirblock
1259
 
 
1260
 
        # push the user specified dirs from dirblock
1261
 
        pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
 
930
        top = currentdir[4]
 
931
        if currentdir[0]:
 
932
            relroot = currentdir[0] + '/'
 
933
        else:
 
934
            relroot = ""
 
935
        for name in sorted(_listdir(top)):
 
936
            abspath = top + '/' + name
 
937
            statvalue = lstat(abspath)
 
938
            dirblock.append((relroot + name, name,
 
939
                file_kind_from_stat_mode(statvalue.st_mode),
 
940
                statvalue, abspath))
 
941
        yield (currentdir[0], top), dirblock
 
942
        # push the user specified dirs from dirblock
 
943
        for dir in reversed(dirblock):
 
944
            if dir[2] == _directory:
 
945
                pending.append(dir)
1262
946
 
1263
947
 
1264
948
def copy_tree(from_path, to_path, handlers={}):
1316
1000
    key_a = path_prefix_key(path_a)
1317
1001
    key_b = path_prefix_key(path_b)
1318
1002
    return cmp(key_a, key_b)
1319
 
 
1320
 
 
1321
 
_cached_user_encoding = None
1322
 
 
1323
 
 
1324
 
def get_user_encoding(use_cache=True):
1325
 
    """Find out what the preferred user encoding is.
1326
 
 
1327
 
    This is generally the encoding that is used for command line parameters
1328
 
    and file contents. This may be different from the terminal encoding
1329
 
    or the filesystem encoding.
1330
 
 
1331
 
    :param  use_cache:  Enable cache for detected encoding.
1332
 
                        (This parameter is turned on by default,
1333
 
                        and required only for selftesting)
1334
 
 
1335
 
    :return: A string defining the preferred user encoding
1336
 
    """
1337
 
    global _cached_user_encoding
1338
 
    if _cached_user_encoding is not None and use_cache:
1339
 
        return _cached_user_encoding
1340
 
 
1341
 
    if sys.platform == 'darwin':
1342
 
        # work around egregious python 2.4 bug
1343
 
        sys.platform = 'posix'
1344
 
        try:
1345
 
            import locale
1346
 
        finally:
1347
 
            sys.platform = 'darwin'
1348
 
    else:
1349
 
        import locale
1350
 
 
1351
 
    try:
1352
 
        user_encoding = locale.getpreferredencoding()
1353
 
    except locale.Error, e:
1354
 
        sys.stderr.write('bzr: warning: %s\n'
1355
 
                         '  Could not determine what text encoding to use.\n'
1356
 
                         '  This error usually means your Python interpreter\n'
1357
 
                         '  doesn\'t support the locale set by $LANG (%s)\n'
1358
 
                         "  Continuing with ascii encoding.\n"
1359
 
                         % (e, os.environ.get('LANG')))
1360
 
        user_encoding = 'ascii'
1361
 
 
1362
 
    # Windows returns 'cp0' to indicate there is no code page. So we'll just
1363
 
    # treat that as ASCII, and not support printing unicode characters to the
1364
 
    # console.
1365
 
    if user_encoding in (None, 'cp0'):
1366
 
        user_encoding = 'ascii'
1367
 
    else:
1368
 
        # check encoding
1369
 
        try:
1370
 
            codecs.lookup(user_encoding)
1371
 
        except LookupError:
1372
 
            sys.stderr.write('bzr: warning:'
1373
 
                             ' unknown encoding %s.'
1374
 
                             ' Continuing with ascii encoding.\n'
1375
 
                             % user_encoding
1376
 
                            )
1377
 
            user_encoding = 'ascii'
1378
 
 
1379
 
    if use_cache:
1380
 
        _cached_user_encoding = user_encoding
1381
 
 
1382
 
    return user_encoding
1383
 
 
1384
 
 
1385
 
def recv_all(socket, bytes):
1386
 
    """Receive an exact number of bytes.
1387
 
 
1388
 
    Regular Socket.recv() may return less than the requested number of bytes,
1389
 
    dependning on what's in the OS buffer.  MSG_WAITALL is not available
1390
 
    on all platforms, but this should work everywhere.  This will return
1391
 
    less than the requested amount if the remote end closes.
1392
 
 
1393
 
    This isn't optimized and is intended mostly for use in testing.
1394
 
    """
1395
 
    b = ''
1396
 
    while len(b) < bytes:
1397
 
        new = socket.recv(bytes - len(b))
1398
 
        if new == '':
1399
 
            break # eof
1400
 
        b += new
1401
 
    return b
1402
 
 
1403
 
def dereference_path(path):
1404
 
    """Determine the real path to a file.
1405
 
 
1406
 
    All parent elements are dereferenced.  But the file itself is not
1407
 
    dereferenced.
1408
 
    :param path: The original path.  May be absolute or relative.
1409
 
    :return: the real path *to* the file
1410
 
    """
1411
 
    parent, base = os.path.split(path)
1412
 
    # The pathjoin for '.' is a workaround for Python bug #1213894.
1413
 
    # (initial path components aren't dereferenced)
1414
 
    return pathjoin(realpath(pathjoin('.', parent)), base)
1415
 
 
1416
 
 
1417
 
def supports_mapi():
1418
 
    """Return True if we can use MAPI to launch a mail client."""
1419
 
    return sys.platform == "win32"