~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: 2007-10-24 12:49:17 UTC
  • mfrom: (2935.1.1 ianc-integration)
  • Revision ID: pqm@pqm.ubuntu.com-20071024124917-xb75eckyxx6vkrlg
Makefile fixes - hooks.html generation & allow python to be overridden (Ian Clatworthy)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Bazaar -- distributed version control
2
 
#
3
 
# Copyright (C) 2005 by Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
4
2
#
5
3
# This program is free software; you can redistribute it and/or modify
6
4
# it under the terms of the GNU General Public License as published by
17
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
16
 
19
17
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
20
30
import errno
21
31
from ntpath import (abspath as _nt_abspath,
22
32
                    join as _nt_join,
24
34
                    realpath as _nt_realpath,
25
35
                    splitdrive as _nt_splitdrive,
26
36
                    )
27
 
import os
28
 
from os import listdir
29
37
import posixpath
30
 
import re
31
38
import sha
32
39
import shutil
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
 
40
from shutil import (
 
41
    rmtree,
 
42
    )
41
43
import tempfile
 
44
from tempfile import (
 
45
    mkdtemp,
 
46
    )
42
47
import unicodedata
43
48
 
 
49
from bzrlib import (
 
50
    cache_utf8,
 
51
    errors,
 
52
    win32utils,
 
53
    )
 
54
""")
 
55
 
44
56
import bzrlib
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)
 
57
from bzrlib import symbol_versioning
 
58
from bzrlib.symbol_versioning import (
 
59
    deprecated_function,
 
60
    )
53
61
from bzrlib.trace import mutter
54
62
 
55
63
 
60
68
# OR with 0 on those platforms
61
69
O_BINARY = getattr(os, 'O_BINARY', 0)
62
70
 
 
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)
63
74
 
64
75
def make_readonly(filename):
65
76
    """Make a filename read-only."""
66
 
    mod = os.stat(filename).st_mode
67
 
    mod = mod & 0777555
68
 
    os.chmod(filename, mod)
 
77
    mod = lstat(filename).st_mode
 
78
    if not stat.S_ISLNK(mod):
 
79
        mod = mod & 0777555
 
80
        os.chmod(filename, mod)
69
81
 
70
82
 
71
83
def make_writable(filename):
72
 
    mod = os.stat(filename).st_mode
73
 
    mod = mod | 0200
74
 
    os.chmod(filename, mod)
 
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
75
105
 
76
106
 
77
107
_QUOTE_RE = None
84
114
    Windows."""
85
115
    # TODO: I'm not really sure this is the best format either.x
86
116
    global _QUOTE_RE
87
 
    if _QUOTE_RE == None:
 
117
    if _QUOTE_RE is None:
88
118
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
89
119
        
90
120
    if _QUOTE_RE.search(f):
122
152
        return _mapper(_lstat(f).st_mode)
123
153
    except OSError, e:
124
154
        if getattr(e, 'errno', None) == errno.ENOENT:
125
 
            raise bzrlib.errors.NoSuchFile(f)
 
155
            raise errors.NoSuchFile(f)
126
156
        raise
127
157
 
128
158
 
136
166
    return umask
137
167
 
138
168
 
 
169
_kind_marker_map = {
 
170
    "file": "",
 
171
    _directory_kind: "/",
 
172
    "symlink": "@",
 
173
    'tree-reference': '+',
 
174
}
 
175
 
 
176
 
139
177
def kind_marker(kind):
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)
 
178
    try:
 
179
        return _kind_marker_map[kind]
 
180
    except KeyError:
 
181
        raise errors.BzrError('invalid file kind %r' % kind)
 
182
 
148
183
 
149
184
lexists = getattr(os.path, 'lexists', None)
150
185
if lexists is None:
151
186
    def lexists(f):
152
187
        try:
153
 
            if hasattr(os, 'lstat'):
154
 
                os.lstat(f)
155
 
            else:
156
 
                os.stat(f)
 
188
            stat = getattr(os, 'lstat', os.stat)
 
189
            stat(f)
157
190
            return True
158
 
        except OSError,e:
 
191
        except OSError, e:
159
192
            if e.errno == errno.ENOENT:
160
193
                return False;
161
194
            else:
162
 
                raise BzrError("lstat/stat of (%r): %r" % (f, e))
 
195
                raise errors.BzrError("lstat/stat of (%r): %r" % (f, e))
163
196
 
164
197
 
165
198
def fancy_rename(old, new, rename_func, unlink_func):
186
219
    file_existed = False
187
220
    try:
188
221
        rename_func(new, tmp_name)
189
 
    except (NoSuchFile,), e:
 
222
    except (errors.NoSuchFile,), e:
190
223
        pass
191
224
    except IOError, e:
192
225
        # RBC 20060103 abstraction leakage: the paramiko SFTP clients rename
193
 
        # function raises an IOError with errno == None when a rename fails.
 
226
        # function raises an IOError with errno is None when a rename fails.
194
227
        # This then gets caught here.
195
228
        if e.errno not in (None, errno.ENOENT, errno.ENOTDIR):
196
229
            raise
197
230
    except Exception, e:
198
 
        if (not hasattr(e, 'errno') 
 
231
        if (getattr(e, 'errno', None) is None
199
232
            or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
200
233
            raise
201
234
    else:
221
254
# choke on a Unicode string containing a relative path if
222
255
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
223
256
# string.
224
 
_fs_enc = sys.getfilesystemencoding()
 
257
_fs_enc = sys.getfilesystemencoding() or 'utf-8'
225
258
def _posix_abspath(path):
226
259
    # jam 20060426 rather than encoding to fsencoding
227
260
    # copy posixpath.abspath, but use os.getcwdu instead
252
285
    return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
253
286
 
254
287
 
 
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
 
255
318
def _win32_realpath(path):
256
319
    # Real _nt_realpath doesn't have a problem with a unicode cwd
257
320
    return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
302
365
pathjoin = os.path.join
303
366
normpath = os.path.normpath
304
367
getcwd = os.getcwdu
305
 
mkdtemp = tempfile.mkdtemp
306
368
rename = os.rename
307
369
dirname = os.path.dirname
308
370
basename = os.path.basename
309
 
rmtree = shutil.rmtree
 
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
310
376
 
311
377
MIN_ABS_PATHLENGTH = 1
312
378
 
326
392
        """Error handler for shutil.rmtree function [for win32]
327
393
        Helps to remove files and dirs marked as read-only.
328
394
        """
329
 
        type_, value = excinfo[:2]
 
395
        exception = excinfo[1]
330
396
        if function in (os.remove, os.rmdir) \
331
 
            and type_ == OSError \
332
 
            and value.errno == errno.EACCES:
333
 
            bzrlib.osutils.make_writable(path)
 
397
            and isinstance(exception, OSError) \
 
398
            and exception.errno == errno.EACCES:
 
399
            make_writable(path)
334
400
            function(path)
335
401
        else:
336
402
            raise
366
432
            mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
367
433
    else:
368
434
        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
 
369
451
    return output_encoding
370
452
 
371
453
 
372
454
def normalizepath(f):
373
 
    if hasattr(os.path, 'realpath'):
 
455
    if getattr(os.path, 'realpath', None) is not None:
374
456
        F = realpath
375
457
    else:
376
458
        F = abspath
440
522
    
441
523
    The empty string as a dir name is taken as top-of-tree and matches 
442
524
    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
456
525
    """
457
526
    # XXX: Most callers of this can actually do something smarter by 
458
527
    # looking at the inventory
473
542
    for dirname in dir_list:
474
543
        if is_inside(dirname, fname):
475
544
            return True
476
 
    else:
477
 
        return False
 
545
    return False
478
546
 
479
547
 
480
548
def is_inside_or_parent_of_any(dir_list, fname):
482
550
    for dirname in dir_list:
483
551
        if is_inside(dirname, fname) or is_inside(fname, dirname):
484
552
            return True
485
 
    else:
486
 
        return False
 
553
    return False
487
554
 
488
555
 
489
556
def pumpfile(fromfile, tofile):
490
 
    """Copy contents of one file to another."""
 
557
    """Copy contents of one file to another.
 
558
    
 
559
    :return: The number of bytes copied.
 
560
    """
491
561
    BUFSIZE = 32768
 
562
    length = 0
492
563
    while True:
493
564
        b = fromfile.read(BUFSIZE)
494
565
        if not b:
495
566
            break
496
567
        tofile.write(b)
 
568
        length += len(b)
 
569
    return length
497
570
 
498
571
 
499
572
def file_iterator(input_file, readsize=32768):
505
578
 
506
579
 
507
580
def sha_file(f):
508
 
    if hasattr(f, 'tell'):
 
581
    if getattr(f, 'tell', None) is not None:
509
582
        assert f.tell() == 0
510
583
    s = sha.new()
511
584
    BUFSIZE = 128<<10
517
590
    return s.hexdigest()
518
591
 
519
592
 
520
 
 
521
 
def sha_strings(strings):
 
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):
522
608
    """Return the sha-1 of concatenation of strings"""
523
 
    s = sha.new()
 
609
    s = _factory()
524
610
    map(s.update, strings)
525
611
    return s.hexdigest()
526
612
 
527
613
 
528
 
def sha_string(f):
529
 
    s = sha.new()
530
 
    s.update(f)
531
 
    return s.hexdigest()
 
614
def sha_string(f, _factory=sha.new):
 
615
    return _factory(f).hexdigest()
532
616
 
533
617
 
534
618
def fingerprint_file(f):
535
 
    s = sha.new()
536
619
    b = f.read()
537
 
    s.update(b)
538
 
    size = len(b)
539
 
    return {'size': size,
540
 
            'sha1': s.hexdigest()}
 
620
    return {'size': len(b),
 
621
            'sha1': sha.new(b).hexdigest()}
541
622
 
542
623
 
543
624
def compare_files(a, b):
554
635
 
555
636
def local_time_offset(t=None):
556
637
    """Return offset of local zone from GMT, either at present or at time t."""
557
 
    # python2.3 localtime() can't take None
558
 
    if t == None:
 
638
    if t is None:
559
639
        t = time.time()
560
 
        
561
 
    if time.localtime(t).tm_isdst and time.daylight:
562
 
        return -time.altzone
563
 
    else:
564
 
        return -time.timezone
 
640
    offset = datetime.fromtimestamp(t) - datetime.utcfromtimestamp(t)
 
641
    return offset.days * 86400 + offset.seconds
565
642
 
566
643
    
567
 
def format_date(t, offset=0, timezone='original', date_fmt=None, 
 
644
def format_date(t, offset=0, timezone='original', date_fmt=None,
568
645
                show_offset=True):
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
 
    
 
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
    """
573
656
    if timezone == 'utc':
574
657
        tt = time.gmtime(t)
575
658
        offset = 0
576
659
    elif timezone == 'original':
577
 
        if offset == None:
 
660
        if offset is None:
578
661
            offset = 0
579
662
        tt = time.gmtime(t + offset)
580
663
    elif timezone == 'local':
581
664
        tt = time.localtime(t)
582
665
        offset = local_time_offset(t)
583
666
    else:
584
 
        raise BzrError("unsupported timezone format %r" % timezone,
585
 
                       ['options are "utc", "original", "local"'])
 
667
        raise errors.BzrError("unsupported timezone format %r" % timezone,
 
668
                              ['options are "utc", "original", "local"'])
586
669
    if date_fmt is None:
587
670
        date_fmt = "%a %Y-%m-%d %H:%M:%S"
588
671
    if show_offset:
596
679
    return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
597
680
    
598
681
 
 
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)
599
730
 
600
731
def filesize(f):
601
732
    """Return size of given open file."""
611
742
except (NotImplementedError, AttributeError):
612
743
    # If python doesn't have os.urandom, or it doesn't work,
613
744
    # then try to first pull random data from /dev/urandom
614
 
    if os.path.exists("/dev/urandom"):
 
745
    try:
615
746
        rand_bytes = file('/dev/urandom', 'rb').read
616
747
    # Otherwise, use this hack as a last resort
617
 
    else:
 
748
    except (IOError, OSError):
618
749
        # not well seeded, but better than nothing
619
750
        def rand_bytes(n):
620
751
            import random
642
773
## decomposition (might be too tricksy though.)
643
774
 
644
775
def splitpath(p):
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)
 
776
    """Turn string into list of parts."""
 
777
    assert isinstance(p, basestring)
661
778
 
662
779
    # split on either delimiter because people might use either on
663
780
    # Windows
666
783
    rps = []
667
784
    for f in ps:
668
785
        if f == '..':
669
 
            raise BzrError("sorry, %r not allowed in path" % f)
 
786
            raise errors.BzrError("sorry, %r not allowed in path" % f)
670
787
        elif (f == '.') or (f == ''):
671
788
            pass
672
789
        else:
674
791
    return rps
675
792
 
676
793
def joinpath(p):
677
 
    assert isinstance(p, list)
 
794
    assert isinstance(p, (list, tuple))
678
795
    for f in p:
679
 
        if (f == '..') or (f == None) or (f == ''):
680
 
            raise BzrError("sorry, %r not allowed in path" % f)
 
796
        if (f == '..') or (f is None) or (f == ''):
 
797
            raise errors.BzrError("sorry, %r not allowed in path" % f)
681
798
    return pathjoin(*p)
682
799
 
683
800
 
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
 
 
692
801
def split_lines(s):
693
802
    """Split s into lines, but without removing the newline characters."""
694
803
    lines = s.split('\n')
705
814
def link_or_copy(src, dest):
706
815
    """Hardlink a file, or copy it if it can't be hardlinked."""
707
816
    if not hardlinks_good():
708
 
        copyfile(src, dest)
 
817
        shutil.copyfile(src, dest)
709
818
        return
710
819
    try:
711
820
        os.link(src, dest)
712
821
    except (OSError, IOError), e:
713
822
        if e.errno != errno.EXDEV:
714
823
            raise
715
 
        copyfile(src, dest)
716
 
 
717
 
def delete_any(full_path):
 
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):
718
833
    """Delete a file or directory."""
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)
 
834
    if isdir(path): # Takes care of symlinks
 
835
        os.rmdir(path)
 
836
    else:
 
837
        os.unlink(path)
726
838
 
727
839
 
728
840
def has_symlinks():
729
 
    if hasattr(os, 'symlink'):
 
841
    if getattr(os, 'symlink', None) is not None:
730
842
        return True
731
843
    else:
732
844
        return False
733
 
        
 
845
 
734
846
 
735
847
def contains_whitespace(s):
736
848
    """True if there are any whitespace characters in s."""
737
 
    for ch in string.whitespace:
 
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':
738
861
        if ch in s:
739
862
            return True
740
863
    else:
776
899
        if tail:
777
900
            s.insert(0, tail)
778
901
    else:
779
 
        raise PathNotChild(rp, base)
 
902
        raise errors.PathNotChild(rp, base)
780
903
 
781
904
    if s:
782
905
        return pathjoin(*s)
797
920
    try:
798
921
        return unicode_or_utf8_string.decode('utf8')
799
922
    except UnicodeDecodeError:
800
 
        raise BzrBadParameterNotUnicode(unicode_or_utf8_string)
 
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)
801
989
 
802
990
 
803
991
_platform_normalizes_filenames = False
847
1035
def terminal_width():
848
1036
    """Return estimated terminal width."""
849
1037
    if sys.platform == 'win32':
850
 
        import bzrlib.win32console
851
 
        return bzrlib.win32console.get_console_size()[0]
 
1038
        return win32utils.get_console_size()[0]
852
1039
    width = 0
853
1040
    try:
854
1041
        import struct, fcntl, termios
867
1054
 
868
1055
    return width
869
1056
 
 
1057
 
870
1058
def supports_executable():
871
1059
    return sys.platform != "win32"
872
1060
 
873
1061
 
 
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
 
874
1094
_validWin32PathRE = re.compile(r'^([A-Za-z]:[/\\])?[^:<>*"?\|]*$')
875
1095
 
876
1096
 
882
1102
    if sys.platform != "win32":
883
1103
        return
884
1104
    if _validWin32PathRE.match(path) is None:
885
 
        raise IllegalPath(path)
 
1105
        raise errors.IllegalPath(path)
886
1106
 
887
1107
 
888
1108
def walkdirs(top, prefix=""):
894
1114
    
895
1115
    The data yielded is of the form:
896
1116
    ((directory-relpath, directory-path-from-top),
897
 
    [(relpath, basename, kind, lstat), ...]),
 
1117
    [(relpath, basename, kind, lstat, path-from-top), ...]),
898
1118
     - directory-relpath is the relative path of the directory being returned
899
1119
       with respect to top. prefix is prepended to this.
900
1120
     - directory-path-from-root is the path including top for this directory. 
918
1138
    # depending on top and prefix - i.e. ./foo and foo as a pair leads to
919
1139
    # potentially confusing output. We should make this more robust - but
920
1140
    # not at a speed cost. RBC 20060731
921
 
    lstat = os.lstat
922
 
    pending = []
 
1141
    _lstat = os.lstat
923
1142
    _directory = _directory_kind
924
 
    _listdir = listdir
925
 
    pending = [(prefix, "", _directory, None, top)]
 
1143
    _listdir = os.listdir
 
1144
    _kind_from_mode = _formats.get
 
1145
    pending = [(safe_unicode(prefix), "", _directory, None, safe_unicode(top))]
926
1146
    while pending:
927
 
        dirblock = []
928
 
        currentdir = pending.pop()
929
1147
        # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
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)
 
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)
946
1262
 
947
1263
 
948
1264
def copy_tree(from_path, to_path, handlers={}):
1000
1316
    key_a = path_prefix_key(path_a)
1001
1317
    key_b = path_prefix_key(path_b)
1002
1318
    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"