/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

First attempt to merge .dev and resolve the conflicts (but tests are 
failing)

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
 
 
56
 
44
57
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)
 
58
from bzrlib import symbol_versioning
 
59
from bzrlib.symbol_versioning import (
 
60
    deprecated_function,
 
61
    )
53
62
from bzrlib.trace import mutter
54
63
 
55
64
 
63
72
 
64
73
def make_readonly(filename):
65
74
    """Make a filename read-only."""
66
 
    mod = os.stat(filename).st_mode
67
 
    mod = mod & 0777555
68
 
    os.chmod(filename, mod)
 
75
    mod = os.lstat(filename).st_mode
 
76
    if not stat.S_ISLNK(mod):
 
77
        mod = mod & 0777555
 
78
        os.chmod(filename, mod)
69
79
 
70
80
 
71
81
def make_writable(filename):
72
 
    mod = os.stat(filename).st_mode
73
 
    mod = mod | 0200
74
 
    os.chmod(filename, mod)
 
82
    mod = os.lstat(filename).st_mode
 
83
    if not stat.S_ISLNK(mod):
 
84
        mod = mod | 0200
 
85
        os.chmod(filename, mod)
 
86
 
 
87
 
 
88
def minimum_path_selection(paths):
 
89
    """Return the smallset subset of paths which are outside paths.
 
90
 
 
91
    :param paths: A container (and hence not None) of paths.
 
92
    :return: A set of paths sufficient to include everything in paths via
 
93
        is_inside_any, drawn from the paths parameter.
 
94
    """
 
95
    search_paths = set()
 
96
    paths = set(paths)
 
97
    for path in paths:
 
98
        other_paths = paths.difference([path])
 
99
        if not is_inside_any(other_paths, path):
 
100
            # this is a top level path, we must check it.
 
101
            search_paths.add(path)
 
102
    return search_paths
75
103
 
76
104
 
77
105
_QUOTE_RE = None
121
149
    try:
122
150
        return _mapper(_lstat(f).st_mode)
123
151
    except OSError, e:
124
 
        if getattr(e, 'errno', None) == errno.ENOENT:
125
 
            raise bzrlib.errors.NoSuchFile(f)
 
152
        if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
 
153
            raise errors.NoSuchFile(f)
126
154
        raise
127
155
 
128
156
 
136
164
    return umask
137
165
 
138
166
 
 
167
_kind_marker_map = {
 
168
    "file": "",
 
169
    _directory_kind: "/",
 
170
    "symlink": "@",
 
171
    'tree-reference': '+',
 
172
}
 
173
 
 
174
 
139
175
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)
 
176
    try:
 
177
        return _kind_marker_map[kind]
 
178
    except KeyError:
 
179
        raise errors.BzrError('invalid file kind %r' % kind)
 
180
 
148
181
 
149
182
lexists = getattr(os.path, 'lexists', None)
150
183
if lexists is None:
151
184
    def lexists(f):
152
185
        try:
153
 
            if getattr(os, 'lstat') is not None:
154
 
                os.lstat(f)
155
 
            else:
156
 
                os.stat(f)
 
186
            stat = getattr(os, 'lstat', os.stat)
 
187
            stat(f)
157
188
            return True
158
 
        except OSError,e:
 
189
        except OSError, e:
159
190
            if e.errno == errno.ENOENT:
160
191
                return False;
161
192
            else:
162
 
                raise BzrError("lstat/stat of (%r): %r" % (f, e))
 
193
                raise errors.BzrError("lstat/stat of (%r): %r" % (f, e))
163
194
 
164
195
 
165
196
def fancy_rename(old, new, rename_func, unlink_func):
186
217
    file_existed = False
187
218
    try:
188
219
        rename_func(new, tmp_name)
189
 
    except (NoSuchFile,), e:
 
220
    except (errors.NoSuchFile,), e:
190
221
        pass
191
222
    except IOError, e:
192
223
        # RBC 20060103 abstraction leakage: the paramiko SFTP clients rename
203
234
 
204
235
    success = False
205
236
    try:
206
 
        # This may throw an exception, in which case success will
207
 
        # not be set.
208
 
        rename_func(old, new)
209
 
        success = True
 
237
        try:
 
238
            # This may throw an exception, in which case success will
 
239
            # not be set.
 
240
            rename_func(old, new)
 
241
            success = True
 
242
        except (IOError, OSError), e:
 
243
            # source and target may be aliases of each other (e.g. on a
 
244
            # case-insensitive filesystem), so we may have accidentally renamed
 
245
            # source by when we tried to rename target
 
246
            if not (file_existed and e.errno in (None, errno.ENOENT)):
 
247
                raise
210
248
    finally:
211
249
        if file_existed:
212
250
            # If the file used to exist, rename it back into place
221
259
# choke on a Unicode string containing a relative path if
222
260
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
223
261
# string.
224
 
_fs_enc = sys.getfilesystemencoding()
 
262
_fs_enc = sys.getfilesystemencoding() or 'utf-8'
225
263
def _posix_abspath(path):
226
264
    # jam 20060426 rather than encoding to fsencoding
227
265
    # copy posixpath.abspath, but use os.getcwdu instead
252
290
    return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
253
291
 
254
292
 
 
293
def _win98_abspath(path):
 
294
    """Return the absolute version of a path.
 
295
    Windows 98 safe implementation (python reimplementation
 
296
    of Win32 API function GetFullPathNameW)
 
297
    """
 
298
    # Corner cases:
 
299
    #   C:\path     => C:/path
 
300
    #   C:/path     => C:/path
 
301
    #   \\HOST\path => //HOST/path
 
302
    #   //HOST/path => //HOST/path
 
303
    #   path        => C:/cwd/path
 
304
    #   /path       => C:/path
 
305
    path = unicode(path)
 
306
    # check for absolute path
 
307
    drive = _nt_splitdrive(path)[0]
 
308
    if drive == '' and path[:2] not in('//','\\\\'):
 
309
        cwd = os.getcwdu()
 
310
        # we cannot simply os.path.join cwd and path
 
311
        # because os.path.join('C:','/path') produce '/path'
 
312
        # and this is incorrect
 
313
        if path[:1] in ('/','\\'):
 
314
            cwd = _nt_splitdrive(cwd)[0]
 
315
            path = path[1:]
 
316
        path = cwd + '\\' + path
 
317
    return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
 
318
 
 
319
if win32utils.winver == 'Windows 98':
 
320
    _win32_abspath = _win98_abspath
 
321
 
 
322
 
255
323
def _win32_realpath(path):
256
324
    # Real _nt_realpath doesn't have a problem with a unicode cwd
257
325
    return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
292
360
 
293
361
 
294
362
def _mac_getcwd():
295
 
    return unicodedata.normalize('NFKC', os.getcwdu())
 
363
    return unicodedata.normalize('NFC', os.getcwdu())
296
364
 
297
365
 
298
366
# Default is to just use the python builtins, but these can be rebound on
302
370
pathjoin = os.path.join
303
371
normpath = os.path.normpath
304
372
getcwd = os.getcwdu
305
 
mkdtemp = tempfile.mkdtemp
306
373
rename = os.rename
307
374
dirname = os.path.dirname
308
375
basename = os.path.basename
309
 
rmtree = shutil.rmtree
 
376
split = os.path.split
 
377
splitext = os.path.splitext
 
378
# These were already imported into local scope
 
379
# mkdtemp = tempfile.mkdtemp
 
380
# rmtree = shutil.rmtree
310
381
 
311
382
MIN_ABS_PATHLENGTH = 1
312
383
 
326
397
        """Error handler for shutil.rmtree function [for win32]
327
398
        Helps to remove files and dirs marked as read-only.
328
399
        """
329
 
        type_, value = excinfo[:2]
 
400
        exception = excinfo[1]
330
401
        if function in (os.remove, os.rmdir) \
331
 
            and type_ == OSError \
332
 
            and value.errno == errno.EACCES:
333
 
            bzrlib.osutils.make_writable(path)
 
402
            and isinstance(exception, OSError) \
 
403
            and exception.errno == errno.EACCES:
 
404
            make_writable(path)
334
405
            function(path)
335
406
        else:
336
407
            raise
366
437
            mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
367
438
    else:
368
439
        mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
 
440
    if output_encoding == 'cp0':
 
441
        # invalid encoding (cp0 means 'no codepage' on Windows)
 
442
        output_encoding = bzrlib.user_encoding
 
443
        mutter('cp0 is invalid encoding.'
 
444
               ' encoding stdout as bzrlib.user_encoding %r', output_encoding)
 
445
    # check encoding
 
446
    try:
 
447
        codecs.lookup(output_encoding)
 
448
    except LookupError:
 
449
        sys.stderr.write('bzr: warning:'
 
450
                         ' unknown terminal encoding %s.\n'
 
451
                         '  Using encoding %s instead.\n'
 
452
                         % (output_encoding, bzrlib.user_encoding)
 
453
                        )
 
454
        output_encoding = bzrlib.user_encoding
 
455
 
369
456
    return output_encoding
370
457
 
371
458
 
381
468
        return pathjoin(F(p), e)
382
469
 
383
470
 
384
 
def backup_file(fn):
385
 
    """Copy a file to a backup.
386
 
 
387
 
    Backups are named in GNU-style, with a ~ suffix.
388
 
 
389
 
    If the file is already a backup, it's not copied.
390
 
    """
391
 
    if fn[-1] == '~':
392
 
        return
393
 
    bfn = fn + '~'
394
 
 
395
 
    if has_symlinks() and os.path.islink(fn):
396
 
        target = os.readlink(fn)
397
 
        os.symlink(target, bfn)
398
 
        return
399
 
    inf = file(fn, 'rb')
400
 
    try:
401
 
        content = inf.read()
402
 
    finally:
403
 
        inf.close()
404
 
    
405
 
    outf = file(bfn, 'wb')
406
 
    try:
407
 
        outf.write(content)
408
 
    finally:
409
 
        outf.close()
410
 
 
411
 
 
412
471
def isdir(f):
413
472
    """True if f is an accessible directory."""
414
473
    try:
440
499
    
441
500
    The empty string as a dir name is taken as top-of-tree and matches 
442
501
    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
502
    """
457
503
    # XXX: Most callers of this can actually do something smarter by 
458
504
    # looking at the inventory
473
519
    for dirname in dir_list:
474
520
        if is_inside(dirname, fname):
475
521
            return True
476
 
    else:
477
 
        return False
 
522
    return False
478
523
 
479
524
 
480
525
def is_inside_or_parent_of_any(dir_list, fname):
482
527
    for dirname in dir_list:
483
528
        if is_inside(dirname, fname) or is_inside(fname, dirname):
484
529
            return True
 
530
    return False
 
531
 
 
532
 
 
533
def pumpfile(from_file, to_file, read_length=-1, buff_size=32768):
 
534
    """Copy contents of one file to another.
 
535
 
 
536
    The read_length can either be -1 to read to end-of-file (EOF) or
 
537
    it can specify the maximum number of bytes to read.
 
538
 
 
539
    The buff_size represents the maximum size for each read operation
 
540
    performed on from_file.
 
541
 
 
542
    :return: The number of bytes copied.
 
543
    """
 
544
    length = 0
 
545
    if read_length >= 0:
 
546
        # read specified number of bytes
 
547
 
 
548
        while read_length > 0:
 
549
            num_bytes_to_read = min(read_length, buff_size)
 
550
 
 
551
            block = from_file.read(num_bytes_to_read)
 
552
            if not block:
 
553
                # EOF reached
 
554
                break
 
555
            to_file.write(block)
 
556
 
 
557
            actual_bytes_read = len(block)
 
558
            read_length -= actual_bytes_read
 
559
            length += actual_bytes_read
485
560
    else:
486
 
        return False
487
 
 
488
 
 
489
 
def pumpfile(fromfile, tofile):
490
 
    """Copy contents of one file to another."""
491
 
    BUFSIZE = 32768
492
 
    while True:
493
 
        b = fromfile.read(BUFSIZE)
494
 
        if not b:
495
 
            break
496
 
        tofile.write(b)
 
561
        # read to EOF
 
562
        while True:
 
563
            block = from_file.read(buff_size)
 
564
            if not block:
 
565
                # EOF reached
 
566
                break
 
567
            to_file.write(block)
 
568
            length += len(block)
 
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 getattr(f, 'tell', None) is not None:
509
 
        assert f.tell() == 0
 
581
    """Calculate the hexdigest of an open file.
 
582
 
 
583
    The file cursor should be already at the start.
 
584
    """
510
585
    s = sha.new()
511
586
    BUFSIZE = 128<<10
512
587
    while True:
517
592
    return s.hexdigest()
518
593
 
519
594
 
520
 
 
521
 
def sha_strings(strings):
 
595
def sha_file_by_name(fname):
 
596
    """Calculate the SHA1 of a file by reading the full text"""
 
597
    s = sha.new()
 
598
    f = os.open(fname, os.O_RDONLY | O_BINARY)
 
599
    try:
 
600
        while True:
 
601
            b = os.read(f, 1<<16)
 
602
            if not b:
 
603
                return s.hexdigest()
 
604
            s.update(b)
 
605
    finally:
 
606
        os.close(f)
 
607
 
 
608
 
 
609
def sha_strings(strings, _factory=sha.new):
522
610
    """Return the sha-1 of concatenation of strings"""
523
 
    s = sha.new()
 
611
    s = _factory()
524
612
    map(s.update, strings)
525
613
    return s.hexdigest()
526
614
 
527
615
 
528
 
def sha_string(f):
529
 
    s = sha.new()
530
 
    s.update(f)
531
 
    return s.hexdigest()
 
616
def sha_string(f, _factory=sha.new):
 
617
    return _factory(f).hexdigest()
532
618
 
533
619
 
534
620
def fingerprint_file(f):
535
 
    s = sha.new()
536
621
    b = f.read()
537
 
    s.update(b)
538
 
    size = len(b)
539
 
    return {'size': size,
540
 
            'sha1': s.hexdigest()}
 
622
    return {'size': len(b),
 
623
            'sha1': sha.new(b).hexdigest()}
541
624
 
542
625
 
543
626
def compare_files(a, b):
554
637
 
555
638
def local_time_offset(t=None):
556
639
    """Return offset of local zone from GMT, either at present or at time t."""
557
 
    # python2.3 localtime() can't take None
558
640
    if t is None:
559
641
        t = time.time()
560
 
        
561
 
    if time.localtime(t).tm_isdst and time.daylight:
562
 
        return -time.altzone
563
 
    else:
564
 
        return -time.timezone
 
642
    offset = datetime.fromtimestamp(t) - datetime.utcfromtimestamp(t)
 
643
    return offset.days * 86400 + offset.seconds
565
644
 
 
645
weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
566
646
    
567
 
def format_date(t, offset=0, timezone='original', date_fmt=None, 
 
647
def format_date(t, offset=0, timezone='original', date_fmt=None,
568
648
                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
 
    
 
649
    """Return a formatted date string.
 
650
 
 
651
    :param t: Seconds since the epoch.
 
652
    :param offset: Timezone offset in seconds east of utc.
 
653
    :param timezone: How to display the time: 'utc', 'original' for the
 
654
         timezone specified by offset, or 'local' for the process's current
 
655
         timezone.
 
656
    :param show_offset: Whether to append the timezone.
 
657
    :param date_fmt: strftime format.
 
658
    """
573
659
    if timezone == 'utc':
574
660
        tt = time.gmtime(t)
575
661
        offset = 0
581
667
        tt = time.localtime(t)
582
668
        offset = local_time_offset(t)
583
669
    else:
584
 
        raise BzrError("unsupported timezone format %r" % timezone,
585
 
                       ['options are "utc", "original", "local"'])
 
670
        raise errors.UnsupportedTimezoneFormat(timezone)
586
671
    if date_fmt is None:
587
672
        date_fmt = "%a %Y-%m-%d %H:%M:%S"
588
673
    if show_offset:
589
674
        offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
590
675
    else:
591
676
        offset_str = ''
 
677
    # day of week depends on locale, so we do this ourself
 
678
    date_fmt = date_fmt.replace('%a', weekdays[tt[6]])
592
679
    return (time.strftime(date_fmt, tt) +  offset_str)
593
680
 
594
681
 
596
683
    return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
597
684
    
598
685
 
 
686
def format_delta(delta):
 
687
    """Get a nice looking string for a time delta.
 
688
 
 
689
    :param delta: The time difference in seconds, can be positive or negative.
 
690
        positive indicates time in the past, negative indicates time in the
 
691
        future. (usually time.time() - stored_time)
 
692
    :return: String formatted to show approximate resolution
 
693
    """
 
694
    delta = int(delta)
 
695
    if delta >= 0:
 
696
        direction = 'ago'
 
697
    else:
 
698
        direction = 'in the future'
 
699
        delta = -delta
 
700
 
 
701
    seconds = delta
 
702
    if seconds < 90: # print seconds up to 90 seconds
 
703
        if seconds == 1:
 
704
            return '%d second %s' % (seconds, direction,)
 
705
        else:
 
706
            return '%d seconds %s' % (seconds, direction)
 
707
 
 
708
    minutes = int(seconds / 60)
 
709
    seconds -= 60 * minutes
 
710
    if seconds == 1:
 
711
        plural_seconds = ''
 
712
    else:
 
713
        plural_seconds = 's'
 
714
    if minutes < 90: # print minutes, seconds up to 90 minutes
 
715
        if minutes == 1:
 
716
            return '%d minute, %d second%s %s' % (
 
717
                    minutes, seconds, plural_seconds, direction)
 
718
        else:
 
719
            return '%d minutes, %d second%s %s' % (
 
720
                    minutes, seconds, plural_seconds, direction)
 
721
 
 
722
    hours = int(minutes / 60)
 
723
    minutes -= 60 * hours
 
724
    if minutes == 1:
 
725
        plural_minutes = ''
 
726
    else:
 
727
        plural_minutes = 's'
 
728
 
 
729
    if hours == 1:
 
730
        return '%d hour, %d minute%s %s' % (hours, minutes,
 
731
                                            plural_minutes, direction)
 
732
    return '%d hours, %d minute%s %s' % (hours, minutes,
 
733
                                         plural_minutes, direction)
599
734
 
600
735
def filesize(f):
601
736
    """Return size of given open file."""
611
746
except (NotImplementedError, AttributeError):
612
747
    # If python doesn't have os.urandom, or it doesn't work,
613
748
    # then try to first pull random data from /dev/urandom
614
 
    if os.path.exists("/dev/urandom"):
 
749
    try:
615
750
        rand_bytes = file('/dev/urandom', 'rb').read
616
751
    # Otherwise, use this hack as a last resort
617
 
    else:
 
752
    except (IOError, OSError):
618
753
        # not well seeded, but better than nothing
619
754
        def rand_bytes(n):
620
755
            import random
642
777
## decomposition (might be too tricksy though.)
643
778
 
644
779
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)
661
 
 
 
780
    """Turn string into list of parts."""
662
781
    # split on either delimiter because people might use either on
663
782
    # Windows
664
783
    ps = re.split(r'[\\/]', p)
666
785
    rps = []
667
786
    for f in ps:
668
787
        if f == '..':
669
 
            raise BzrError("sorry, %r not allowed in path" % f)
 
788
            raise errors.BzrError("sorry, %r not allowed in path" % f)
670
789
        elif (f == '.') or (f == ''):
671
790
            pass
672
791
        else:
674
793
    return rps
675
794
 
676
795
def joinpath(p):
677
 
    assert isinstance(p, list)
678
796
    for f in p:
679
797
        if (f == '..') or (f is None) or (f == ''):
680
 
            raise BzrError("sorry, %r not allowed in path" % f)
 
798
            raise errors.BzrError("sorry, %r not allowed in path" % f)
681
799
    return pathjoin(*p)
682
800
 
683
801
 
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
802
def split_lines(s):
693
803
    """Split s into lines, but without removing the newline characters."""
694
804
    lines = s.split('\n')
705
815
def link_or_copy(src, dest):
706
816
    """Hardlink a file, or copy it if it can't be hardlinked."""
707
817
    if not hardlinks_good():
708
 
        copyfile(src, dest)
 
818
        shutil.copyfile(src, dest)
709
819
        return
710
820
    try:
711
821
        os.link(src, dest)
712
822
    except (OSError, IOError), e:
713
823
        if e.errno != errno.EXDEV:
714
824
            raise
715
 
        copyfile(src, dest)
716
 
 
717
 
def delete_any(full_path):
 
825
        shutil.copyfile(src, dest)
 
826
 
 
827
 
 
828
# Look Before You Leap (LBYL) is appropriate here instead of Easier to Ask for
 
829
# Forgiveness than Permission (EAFP) because:
 
830
# - root can damage a solaris file system by using unlink,
 
831
# - unlink raises different exceptions on different OSes (linux: EISDIR, win32:
 
832
#   EACCES, OSX: EPERM) when invoked on a directory.
 
833
def delete_any(path):
718
834
    """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)
 
835
    if isdir(path): # Takes care of symlinks
 
836
        os.rmdir(path)
 
837
    else:
 
838
        os.unlink(path)
726
839
 
727
840
 
728
841
def has_symlinks():
730
843
        return True
731
844
    else:
732
845
        return False
733
 
        
 
846
 
 
847
 
 
848
def has_hardlinks():
 
849
    if getattr(os, 'link', None) is not None:
 
850
        return True
 
851
    else:
 
852
        return False
 
853
 
 
854
 
 
855
def host_os_dereferences_symlinks():
 
856
    return (has_symlinks()
 
857
            and sys.platform not in ('cygwin', 'win32'))
 
858
 
734
859
 
735
860
def contains_whitespace(s):
736
861
    """True if there are any whitespace characters in s."""
737
 
    for ch in string.whitespace:
 
862
    # string.whitespace can include '\xa0' in certain locales, because it is
 
863
    # considered "non-breaking-space" as part of ISO-8859-1. But it
 
864
    # 1) Isn't a breaking whitespace
 
865
    # 2) Isn't one of ' \t\r\n' which are characters we sometimes use as
 
866
    #    separators
 
867
    # 3) '\xa0' isn't unicode safe since it is >128.
 
868
 
 
869
    # This should *not* be a unicode set of characters in case the source
 
870
    # string is not a Unicode string. We can auto-up-cast the characters since
 
871
    # they are ascii, but we don't want to auto-up-cast the string in case it
 
872
    # is utf-8
 
873
    for ch in ' \t\n\r\v\f':
738
874
        if ch in s:
739
875
            return True
740
876
    else:
761
897
    avoids that problem.
762
898
    """
763
899
 
764
 
    assert len(base) >= MIN_ABS_PATHLENGTH, ('Length of base must be equal or'
765
 
        ' exceed the platform minimum length (which is %d)' % 
766
 
        MIN_ABS_PATHLENGTH)
 
900
    if len(base) < MIN_ABS_PATHLENGTH:
 
901
        # must have space for e.g. a drive letter
 
902
        raise ValueError('%r is too short to calculate a relative path'
 
903
            % (base,))
767
904
 
768
905
    rp = abspath(path)
769
906
 
776
913
        if tail:
777
914
            s.insert(0, tail)
778
915
    else:
779
 
        raise PathNotChild(rp, base)
 
916
        raise errors.PathNotChild(rp, base)
780
917
 
781
918
    if s:
782
919
        return pathjoin(*s)
797
934
    try:
798
935
        return unicode_or_utf8_string.decode('utf8')
799
936
    except UnicodeDecodeError:
800
 
        raise BzrBadParameterNotUnicode(unicode_or_utf8_string)
 
937
        raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
 
938
 
 
939
 
 
940
def safe_utf8(unicode_or_utf8_string):
 
941
    """Coerce unicode_or_utf8_string to a utf8 string.
 
942
 
 
943
    If it is a str, it is returned.
 
944
    If it is Unicode, it is encoded into a utf-8 string.
 
945
    """
 
946
    if isinstance(unicode_or_utf8_string, str):
 
947
        # TODO: jam 20070209 This is overkill, and probably has an impact on
 
948
        #       performance if we are dealing with lots of apis that want a
 
949
        #       utf-8 revision id
 
950
        try:
 
951
            # Make sure it is a valid utf-8 string
 
952
            unicode_or_utf8_string.decode('utf-8')
 
953
        except UnicodeDecodeError:
 
954
            raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
 
955
        return unicode_or_utf8_string
 
956
    return unicode_or_utf8_string.encode('utf-8')
 
957
 
 
958
 
 
959
_revision_id_warning = ('Unicode revision ids were deprecated in bzr 0.15.'
 
960
                        ' Revision id generators should be creating utf8'
 
961
                        ' revision ids.')
 
962
 
 
963
 
 
964
def safe_revision_id(unicode_or_utf8_string, warn=True):
 
965
    """Revision ids should now be utf8, but at one point they were unicode.
 
966
 
 
967
    :param unicode_or_utf8_string: A possibly Unicode revision_id. (can also be
 
968
        utf8 or None).
 
969
    :param warn: Functions that are sanitizing user data can set warn=False
 
970
    :return: None or a utf8 revision id.
 
971
    """
 
972
    if (unicode_or_utf8_string is None
 
973
        or unicode_or_utf8_string.__class__ == str):
 
974
        return unicode_or_utf8_string
 
975
    if warn:
 
976
        symbol_versioning.warn(_revision_id_warning, DeprecationWarning,
 
977
                               stacklevel=2)
 
978
    return cache_utf8.encode(unicode_or_utf8_string)
 
979
 
 
980
 
 
981
_file_id_warning = ('Unicode file ids were deprecated in bzr 0.15. File id'
 
982
                    ' generators should be creating utf8 file ids.')
 
983
 
 
984
 
 
985
def safe_file_id(unicode_or_utf8_string, warn=True):
 
986
    """File ids should now be utf8, but at one point they were unicode.
 
987
 
 
988
    This is the same as safe_utf8, except it uses the cached encode functions
 
989
    to save a little bit of performance.
 
990
 
 
991
    :param unicode_or_utf8_string: A possibly Unicode file_id. (can also be
 
992
        utf8 or None).
 
993
    :param warn: Functions that are sanitizing user data can set warn=False
 
994
    :return: None or a utf8 file id.
 
995
    """
 
996
    if (unicode_or_utf8_string is None
 
997
        or unicode_or_utf8_string.__class__ == str):
 
998
        return unicode_or_utf8_string
 
999
    if warn:
 
1000
        symbol_versioning.warn(_file_id_warning, DeprecationWarning,
 
1001
                               stacklevel=2)
 
1002
    return cache_utf8.encode(unicode_or_utf8_string)
801
1003
 
802
1004
 
803
1005
_platform_normalizes_filenames = False
821
1023
    On platforms where the system does not normalize filenames 
822
1024
    (Windows, Linux), you have to access a file by its exact path.
823
1025
 
824
 
    Internally, bzr only supports NFC/NFKC normalization, since that is 
 
1026
    Internally, bzr only supports NFC normalization, since that is 
825
1027
    the standard for XML documents.
826
1028
 
827
1029
    So return the normalized path, and a flag indicating if the file
828
1030
    can be accessed by that path.
829
1031
    """
830
1032
 
831
 
    return unicodedata.normalize('NFKC', unicode(path)), True
 
1033
    return unicodedata.normalize('NFC', unicode(path)), True
832
1034
 
833
1035
 
834
1036
def _inaccessible_normalized_filename(path):
835
1037
    __doc__ = _accessible_normalized_filename.__doc__
836
1038
 
837
 
    normalized = unicodedata.normalize('NFKC', unicode(path))
 
1039
    normalized = unicodedata.normalize('NFC', unicode(path))
838
1040
    return normalized, normalized == path
839
1041
 
840
1042
 
847
1049
def terminal_width():
848
1050
    """Return estimated terminal width."""
849
1051
    if sys.platform == 'win32':
850
 
        import bzrlib.win32console
851
 
        return bzrlib.win32console.get_console_size()[0]
 
1052
        return win32utils.get_console_size()[0]
852
1053
    width = 0
853
1054
    try:
854
1055
        import struct, fcntl, termios
872
1073
    return sys.platform != "win32"
873
1074
 
874
1075
 
 
1076
def supports_posix_readonly():
 
1077
    """Return True if 'readonly' has POSIX semantics, False otherwise.
 
1078
 
 
1079
    Notably, a win32 readonly file cannot be deleted, unlike POSIX where the
 
1080
    directory controls creation/deletion, etc.
 
1081
 
 
1082
    And under win32, readonly means that the directory itself cannot be
 
1083
    deleted.  The contents of a readonly directory can be changed, unlike POSIX
 
1084
    where files in readonly directories cannot be added, deleted or renamed.
 
1085
    """
 
1086
    return sys.platform != "win32"
 
1087
 
 
1088
 
875
1089
def set_or_unset_env(env_variable, value):
876
1090
    """Modify the environment, setting or removing the env_variable.
877
1091
 
902
1116
    if sys.platform != "win32":
903
1117
        return
904
1118
    if _validWin32PathRE.match(path) is None:
905
 
        raise IllegalPath(path)
 
1119
        raise errors.IllegalPath(path)
 
1120
 
 
1121
 
 
1122
_WIN32_ERROR_DIRECTORY = 267 # Similar to errno.ENOTDIR
 
1123
 
 
1124
def _is_error_enotdir(e):
 
1125
    """Check if this exception represents ENOTDIR.
 
1126
 
 
1127
    Unfortunately, python is very inconsistent about the exception
 
1128
    here. The cases are:
 
1129
      1) Linux, Mac OSX all versions seem to set errno == ENOTDIR
 
1130
      2) Windows, Python2.4, uses errno == ERROR_DIRECTORY (267)
 
1131
         which is the windows error code.
 
1132
      3) Windows, Python2.5 uses errno == EINVAL and
 
1133
         winerror == ERROR_DIRECTORY
 
1134
 
 
1135
    :param e: An Exception object (expected to be OSError with an errno
 
1136
        attribute, but we should be able to cope with anything)
 
1137
    :return: True if this represents an ENOTDIR error. False otherwise.
 
1138
    """
 
1139
    en = getattr(e, 'errno', None)
 
1140
    if (en == errno.ENOTDIR
 
1141
        or (sys.platform == 'win32'
 
1142
            and (en == _WIN32_ERROR_DIRECTORY
 
1143
                 or (en == errno.EINVAL
 
1144
                     and getattr(e, 'winerror', None) == _WIN32_ERROR_DIRECTORY)
 
1145
        ))):
 
1146
        return True
 
1147
    return False
906
1148
 
907
1149
 
908
1150
def walkdirs(top, prefix=""):
914
1156
    
915
1157
    The data yielded is of the form:
916
1158
    ((directory-relpath, directory-path-from-top),
917
 
    [(relpath, basename, kind, lstat), ...]),
 
1159
    [(relpath, basename, kind, lstat, path-from-top), ...]),
918
1160
     - directory-relpath is the relative path of the directory being returned
919
1161
       with respect to top. prefix is prepended to this.
920
1162
     - directory-path-from-root is the path including top for this directory. 
938
1180
    # depending on top and prefix - i.e. ./foo and foo as a pair leads to
939
1181
    # potentially confusing output. We should make this more robust - but
940
1182
    # not at a speed cost. RBC 20060731
941
 
    lstat = os.lstat
942
 
    pending = []
 
1183
    _lstat = os.lstat
943
1184
    _directory = _directory_kind
944
 
    _listdir = listdir
945
 
    pending = [(prefix, "", _directory, None, top)]
 
1185
    _listdir = os.listdir
 
1186
    _kind_from_mode = _formats.get
 
1187
    pending = [(safe_unicode(prefix), "", _directory, None, safe_unicode(top))]
946
1188
    while pending:
947
 
        dirblock = []
948
 
        currentdir = pending.pop()
949
1189
        # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
950
 
        top = currentdir[4]
951
 
        if currentdir[0]:
952
 
            relroot = currentdir[0] + '/'
953
 
        else:
954
 
            relroot = ""
955
 
        for name in sorted(_listdir(top)):
956
 
            abspath = top + '/' + name
957
 
            statvalue = lstat(abspath)
958
 
            dirblock.append((relroot + name, name,
959
 
                file_kind_from_stat_mode(statvalue.st_mode),
960
 
                statvalue, abspath))
961
 
        yield (currentdir[0], top), dirblock
962
 
        # push the user specified dirs from dirblock
963
 
        for dir in reversed(dirblock):
964
 
            if dir[2] == _directory:
965
 
                pending.append(dir)
 
1190
        relroot, _, _, _, top = pending.pop()
 
1191
        if relroot:
 
1192
            relprefix = relroot + u'/'
 
1193
        else:
 
1194
            relprefix = ''
 
1195
        top_slash = top + u'/'
 
1196
 
 
1197
        dirblock = []
 
1198
        append = dirblock.append
 
1199
        try:
 
1200
            names = sorted(_listdir(top))
 
1201
        except OSError, e:
 
1202
            if not _is_error_enotdir(e):
 
1203
                raise
 
1204
        else:
 
1205
            for name in names:
 
1206
                abspath = top_slash + name
 
1207
                statvalue = _lstat(abspath)
 
1208
                kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
 
1209
                append((relprefix + name, name, kind, statvalue, abspath))
 
1210
        yield (relroot, top), dirblock
 
1211
 
 
1212
        # push the user specified dirs from dirblock
 
1213
        pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
 
1214
 
 
1215
 
 
1216
_real_walkdirs_utf8 = None
 
1217
 
 
1218
def _walkdirs_utf8(top, prefix=""):
 
1219
    """Yield data about all the directories in a tree.
 
1220
 
 
1221
    This yields the same information as walkdirs() only each entry is yielded
 
1222
    in utf-8. On platforms which have a filesystem encoding of utf8 the paths
 
1223
    are returned as exact byte-strings.
 
1224
 
 
1225
    :return: yields a tuple of (dir_info, [file_info])
 
1226
        dir_info is (utf8_relpath, path-from-top)
 
1227
        file_info is (utf8_relpath, utf8_name, kind, lstat, path-from-top)
 
1228
        if top is an absolute path, path-from-top is also an absolute path.
 
1229
        path-from-top might be unicode or utf8, but it is the correct path to
 
1230
        pass to os functions to affect the file in question. (such as os.lstat)
 
1231
    """
 
1232
    global _real_walkdirs_utf8
 
1233
    if _real_walkdirs_utf8 is None:
 
1234
        fs_encoding = _fs_enc.upper()
 
1235
        if win32utils.winver == 'Windows NT':
 
1236
            # Win98 doesn't have unicode apis like FindFirstFileW
 
1237
            # TODO: We possibly could support Win98 by falling back to the
 
1238
            #       original FindFirstFile, and using TCHAR instead of WCHAR,
 
1239
            #       but that gets a bit tricky, and requires custom compiling
 
1240
            #       for win98 anyway.
 
1241
            try:
 
1242
                from bzrlib._walkdirs_win32 import _walkdirs_utf8_win32_find_file
 
1243
            except ImportError:
 
1244
                _real_walkdirs_utf8 = _walkdirs_unicode_to_utf8
 
1245
            else:
 
1246
                _real_walkdirs_utf8 = _walkdirs_utf8_win32_find_file
 
1247
        elif fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
 
1248
            # ANSI_X3.4-1968 is a form of ASCII
 
1249
            _real_walkdirs_utf8 = _walkdirs_unicode_to_utf8
 
1250
        else:
 
1251
            _real_walkdirs_utf8 = _walkdirs_fs_utf8
 
1252
    return _real_walkdirs_utf8(top, prefix=prefix)
 
1253
 
 
1254
 
 
1255
def _walkdirs_fs_utf8(top, prefix=""):
 
1256
    """See _walkdirs_utf8.
 
1257
 
 
1258
    This sub-function is called when we know the filesystem is already in utf8
 
1259
    encoding. So we don't need to transcode filenames.
 
1260
    """
 
1261
    _lstat = os.lstat
 
1262
    _directory = _directory_kind
 
1263
    _listdir = os.listdir
 
1264
    _kind_from_mode = _formats.get
 
1265
 
 
1266
    # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
 
1267
    # But we don't actually uses 1-3 in pending, so set them to None
 
1268
    pending = [(safe_utf8(prefix), None, None, None, safe_utf8(top))]
 
1269
    while pending:
 
1270
        relroot, _, _, _, top = pending.pop()
 
1271
        if relroot:
 
1272
            relprefix = relroot + '/'
 
1273
        else:
 
1274
            relprefix = ''
 
1275
        top_slash = top + '/'
 
1276
 
 
1277
        dirblock = []
 
1278
        append = dirblock.append
 
1279
        for name in sorted(_listdir(top)):
 
1280
            abspath = top_slash + name
 
1281
            statvalue = _lstat(abspath)
 
1282
            kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
 
1283
            append((relprefix + name, name, kind, statvalue, abspath))
 
1284
        yield (relroot, top), dirblock
 
1285
 
 
1286
        # push the user specified dirs from dirblock
 
1287
        pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
 
1288
 
 
1289
 
 
1290
def _walkdirs_unicode_to_utf8(top, prefix=""):
 
1291
    """See _walkdirs_utf8
 
1292
 
 
1293
    Because Win32 has a Unicode api, all of the 'path-from-top' entries will be
 
1294
    Unicode paths.
 
1295
    This is currently the fallback code path when the filesystem encoding is
 
1296
    not UTF-8. It may be better to implement an alternative so that we can
 
1297
    safely handle paths that are not properly decodable in the current
 
1298
    encoding.
 
1299
    """
 
1300
    _utf8_encode = codecs.getencoder('utf8')
 
1301
    _lstat = os.lstat
 
1302
    _directory = _directory_kind
 
1303
    _listdir = os.listdir
 
1304
    _kind_from_mode = _formats.get
 
1305
 
 
1306
    pending = [(safe_utf8(prefix), None, None, None, safe_unicode(top))]
 
1307
    while pending:
 
1308
        relroot, _, _, _, top = pending.pop()
 
1309
        if relroot:
 
1310
            relprefix = relroot + '/'
 
1311
        else:
 
1312
            relprefix = ''
 
1313
        top_slash = top + u'/'
 
1314
 
 
1315
        dirblock = []
 
1316
        append = dirblock.append
 
1317
        for name in sorted(_listdir(top)):
 
1318
            name_utf8 = _utf8_encode(name)[0]
 
1319
            abspath = top_slash + name
 
1320
            statvalue = _lstat(abspath)
 
1321
            kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
 
1322
            append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
 
1323
        yield (relroot, top), dirblock
 
1324
 
 
1325
        # push the user specified dirs from dirblock
 
1326
        pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
966
1327
 
967
1328
 
968
1329
def copy_tree(from_path, to_path, handlers={}):
1025
1386
_cached_user_encoding = None
1026
1387
 
1027
1388
 
1028
 
def get_user_encoding():
 
1389
def get_user_encoding(use_cache=True):
1029
1390
    """Find out what the preferred user encoding is.
1030
1391
 
1031
1392
    This is generally the encoding that is used for command line parameters
1032
1393
    and file contents. This may be different from the terminal encoding
1033
1394
    or the filesystem encoding.
1034
1395
 
 
1396
    :param  use_cache:  Enable cache for detected encoding.
 
1397
                        (This parameter is turned on by default,
 
1398
                        and required only for selftesting)
 
1399
 
1035
1400
    :return: A string defining the preferred user encoding
1036
1401
    """
1037
1402
    global _cached_user_encoding
1038
 
    if _cached_user_encoding is not None:
 
1403
    if _cached_user_encoding is not None and use_cache:
1039
1404
        return _cached_user_encoding
1040
1405
 
1041
1406
    if sys.platform == 'darwin':
1049
1414
        import locale
1050
1415
 
1051
1416
    try:
1052
 
        _cached_user_encoding = locale.getpreferredencoding()
 
1417
        user_encoding = locale.getpreferredencoding()
1053
1418
    except locale.Error, e:
1054
1419
        sys.stderr.write('bzr: warning: %s\n'
1055
1420
                         '  Could not determine what text encoding to use.\n'
1057
1422
                         '  doesn\'t support the locale set by $LANG (%s)\n'
1058
1423
                         "  Continuing with ascii encoding.\n"
1059
1424
                         % (e, os.environ.get('LANG')))
1060
 
 
1061
 
    if _cached_user_encoding is None:
1062
 
        _cached_user_encoding = 'ascii'
1063
 
    return _cached_user_encoding
 
1425
        user_encoding = 'ascii'
 
1426
 
 
1427
    # Windows returns 'cp0' to indicate there is no code page. So we'll just
 
1428
    # treat that as ASCII, and not support printing unicode characters to the
 
1429
    # console.
 
1430
    #
 
1431
    # For python scripts run under vim, we get '', so also treat that as ASCII
 
1432
    if user_encoding in (None, 'cp0', ''):
 
1433
        user_encoding = 'ascii'
 
1434
    else:
 
1435
        # check encoding
 
1436
        try:
 
1437
            codecs.lookup(user_encoding)
 
1438
        except LookupError:
 
1439
            sys.stderr.write('bzr: warning:'
 
1440
                             ' unknown encoding %s.'
 
1441
                             ' Continuing with ascii encoding.\n'
 
1442
                             % user_encoding
 
1443
                            )
 
1444
            user_encoding = 'ascii'
 
1445
 
 
1446
    if use_cache:
 
1447
        _cached_user_encoding = user_encoding
 
1448
 
 
1449
    return user_encoding
 
1450
 
 
1451
 
 
1452
def recv_all(socket, bytes):
 
1453
    """Receive an exact number of bytes.
 
1454
 
 
1455
    Regular Socket.recv() may return less than the requested number of bytes,
 
1456
    dependning on what's in the OS buffer.  MSG_WAITALL is not available
 
1457
    on all platforms, but this should work everywhere.  This will return
 
1458
    less than the requested amount if the remote end closes.
 
1459
 
 
1460
    This isn't optimized and is intended mostly for use in testing.
 
1461
    """
 
1462
    b = ''
 
1463
    while len(b) < bytes:
 
1464
        new = socket.recv(bytes - len(b))
 
1465
        if new == '':
 
1466
            break # eof
 
1467
        b += new
 
1468
    return b
 
1469
 
 
1470
 
 
1471
def send_all(socket, bytes):
 
1472
    """Send all bytes on a socket.
 
1473
 
 
1474
    Regular socket.sendall() can give socket error 10053 on Windows.  This
 
1475
    implementation sends no more than 64k at a time, which avoids this problem.
 
1476
    """
 
1477
    chunk_size = 2**16
 
1478
    for pos in xrange(0, len(bytes), chunk_size):
 
1479
        socket.sendall(bytes[pos:pos+chunk_size])
 
1480
 
 
1481
 
 
1482
def dereference_path(path):
 
1483
    """Determine the real path to a file.
 
1484
 
 
1485
    All parent elements are dereferenced.  But the file itself is not
 
1486
    dereferenced.
 
1487
    :param path: The original path.  May be absolute or relative.
 
1488
    :return: the real path *to* the file
 
1489
    """
 
1490
    parent, base = os.path.split(path)
 
1491
    # The pathjoin for '.' is a workaround for Python bug #1213894.
 
1492
    # (initial path components aren't dereferenced)
 
1493
    return pathjoin(realpath(pathjoin('.', parent)), base)
 
1494
 
 
1495
 
 
1496
def supports_mapi():
 
1497
    """Return True if we can use MAPI to launch a mail client."""
 
1498
    return sys.platform == "win32"
 
1499
 
 
1500
 
 
1501
def resource_string(package, resource_name):
 
1502
    """Load a resource from a package and return it as a string.
 
1503
 
 
1504
    Note: Only packages that start with bzrlib are currently supported.
 
1505
 
 
1506
    This is designed to be a lightweight implementation of resource
 
1507
    loading in a way which is API compatible with the same API from
 
1508
    pkg_resources. See
 
1509
    http://peak.telecommunity.com/DevCenter/PkgResources#basic-resource-access.
 
1510
    If and when pkg_resources becomes a standard library, this routine
 
1511
    can delegate to it.
 
1512
    """
 
1513
    # Check package name is within bzrlib
 
1514
    if package == "bzrlib":
 
1515
        resource_relpath = resource_name
 
1516
    elif package.startswith("bzrlib."):
 
1517
        package = package[len("bzrlib."):].replace('.', os.sep)
 
1518
        resource_relpath = pathjoin(package, resource_name)
 
1519
    else:
 
1520
        raise errors.BzrError('resource package %s not in bzrlib' % package)
 
1521
 
 
1522
    # Map the resource to a file and read its contents
 
1523
    base = dirname(bzrlib.__file__)
 
1524
    if getattr(sys, 'frozen', None):    # bzr.exe
 
1525
        base = abspath(pathjoin(base, '..', '..'))
 
1526
    filename = pathjoin(base, resource_relpath)
 
1527
    return open(filename, 'rU').read()