~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: Martin Pool
  • Date: 2008-04-30 08:04:11 UTC
  • mto: This revision was merged to the branch mainline in revision 3396.
  • Revision ID: mbp@sourcefrog.net-20080430080411-imrex2wtwpb9eivj
_format_version_tuple can take a 3-tuple

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
54
54
""")
55
55
 
56
56
import bzrlib
 
57
from bzrlib import symbol_versioning
57
58
from bzrlib.symbol_versioning import (
58
59
    deprecated_function,
59
 
    zero_nine,
 
60
    one_zero,
60
61
    )
61
62
from bzrlib.trace import mutter
62
63
 
71
72
 
72
73
def make_readonly(filename):
73
74
    """Make a filename read-only."""
74
 
    mod = os.stat(filename).st_mode
75
 
    mod = mod & 0777555
76
 
    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)
77
79
 
78
80
 
79
81
def make_writable(filename):
80
 
    mod = os.stat(filename).st_mode
81
 
    mod = mod | 0200
82
 
    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
83
103
 
84
104
 
85
105
_QUOTE_RE = None
129
149
    try:
130
150
        return _mapper(_lstat(f).st_mode)
131
151
    except OSError, e:
132
 
        if getattr(e, 'errno', None) == errno.ENOENT:
 
152
        if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
133
153
            raise errors.NoSuchFile(f)
134
154
        raise
135
155
 
144
164
    return umask
145
165
 
146
166
 
 
167
_kind_marker_map = {
 
168
    "file": "",
 
169
    _directory_kind: "/",
 
170
    "symlink": "@",
 
171
    'tree-reference': '+',
 
172
}
 
173
 
 
174
 
147
175
def kind_marker(kind):
148
 
    if kind == 'file':
149
 
        return ''
150
 
    elif kind == _directory_kind:
151
 
        return '/'
152
 
    elif kind == 'symlink':
153
 
        return '@'
154
 
    else:
 
176
    try:
 
177
        return _kind_marker_map[kind]
 
178
    except KeyError:
155
179
        raise errors.BzrError('invalid file kind %r' % kind)
156
180
 
 
181
 
157
182
lexists = getattr(os.path, 'lexists', None)
158
183
if lexists is None:
159
184
    def lexists(f):
160
185
        try:
161
 
            if getattr(os, 'lstat') is not None:
162
 
                os.lstat(f)
163
 
            else:
164
 
                os.stat(f)
 
186
            stat = getattr(os, 'lstat', os.stat)
 
187
            stat(f)
165
188
            return True
166
 
        except OSError,e:
 
189
        except OSError, e:
167
190
            if e.errno == errno.ENOENT:
168
191
                return False;
169
192
            else:
211
234
 
212
235
    success = False
213
236
    try:
214
 
        # This may throw an exception, in which case success will
215
 
        # not be set.
216
 
        rename_func(old, new)
217
 
        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
218
248
    finally:
219
249
        if file_existed:
220
250
            # If the file used to exist, rename it back into place
330
360
 
331
361
 
332
362
def _mac_getcwd():
333
 
    return unicodedata.normalize('NFKC', os.getcwdu())
 
363
    return unicodedata.normalize('NFC', os.getcwdu())
334
364
 
335
365
 
336
366
# Default is to just use the python builtins, but these can be rebound on
438
468
        return pathjoin(F(p), e)
439
469
 
440
470
 
441
 
def backup_file(fn):
442
 
    """Copy a file to a backup.
443
 
 
444
 
    Backups are named in GNU-style, with a ~ suffix.
445
 
 
446
 
    If the file is already a backup, it's not copied.
447
 
    """
448
 
    if fn[-1] == '~':
449
 
        return
450
 
    bfn = fn + '~'
451
 
 
452
 
    if has_symlinks() and os.path.islink(fn):
453
 
        target = os.readlink(fn)
454
 
        os.symlink(target, bfn)
455
 
        return
456
 
    inf = file(fn, 'rb')
457
 
    try:
458
 
        content = inf.read()
459
 
    finally:
460
 
        inf.close()
461
 
    
462
 
    outf = file(bfn, 'wb')
463
 
    try:
464
 
        outf.write(content)
465
 
    finally:
466
 
        outf.close()
467
 
 
468
 
 
469
471
def isdir(f):
470
472
    """True if f is an accessible directory."""
471
473
    try:
517
519
    for dirname in dir_list:
518
520
        if is_inside(dirname, fname):
519
521
            return True
520
 
    else:
521
 
        return False
 
522
    return False
522
523
 
523
524
 
524
525
def is_inside_or_parent_of_any(dir_list, fname):
526
527
    for dirname in dir_list:
527
528
        if is_inside(dirname, fname) or is_inside(fname, dirname):
528
529
            return True
529
 
    else:
530
 
        return False
 
530
    return False
531
531
 
532
532
 
533
533
def pumpfile(fromfile, tofile):
534
 
    """Copy contents of one file to another."""
 
534
    """Copy contents of one file to another.
 
535
    
 
536
    :return: The number of bytes copied.
 
537
    """
535
538
    BUFSIZE = 32768
 
539
    length = 0
536
540
    while True:
537
541
        b = fromfile.read(BUFSIZE)
538
542
        if not b:
539
543
            break
540
544
        tofile.write(b)
 
545
        length += len(b)
 
546
    return length
541
547
 
542
548
 
543
549
def file_iterator(input_file, readsize=32768):
561
567
    return s.hexdigest()
562
568
 
563
569
 
564
 
 
565
 
def sha_strings(strings):
 
570
def sha_file_by_name(fname):
 
571
    """Calculate the SHA1 of a file by reading the full text"""
 
572
    s = sha.new()
 
573
    f = os.open(fname, os.O_RDONLY | O_BINARY)
 
574
    try:
 
575
        while True:
 
576
            b = os.read(f, 1<<16)
 
577
            if not b:
 
578
                return s.hexdigest()
 
579
            s.update(b)
 
580
    finally:
 
581
        os.close(f)
 
582
 
 
583
 
 
584
def sha_strings(strings, _factory=sha.new):
566
585
    """Return the sha-1 of concatenation of strings"""
567
 
    s = sha.new()
 
586
    s = _factory()
568
587
    map(s.update, strings)
569
588
    return s.hexdigest()
570
589
 
571
590
 
572
 
def sha_string(f):
573
 
    s = sha.new()
574
 
    s.update(f)
575
 
    return s.hexdigest()
 
591
def sha_string(f, _factory=sha.new):
 
592
    return _factory(f).hexdigest()
576
593
 
577
594
 
578
595
def fingerprint_file(f):
579
 
    s = sha.new()
580
596
    b = f.read()
581
 
    s.update(b)
582
 
    size = len(b)
583
 
    return {'size': size,
584
 
            'sha1': s.hexdigest()}
 
597
    return {'size': len(b),
 
598
            'sha1': sha.new(b).hexdigest()}
585
599
 
586
600
 
587
601
def compare_files(a, b):
604
618
    return offset.days * 86400 + offset.seconds
605
619
 
606
620
    
607
 
def format_date(t, offset=0, timezone='original', date_fmt=None, 
 
621
def format_date(t, offset=0, timezone='original', date_fmt=None,
608
622
                show_offset=True):
609
 
    ## TODO: Perhaps a global option to use either universal or local time?
610
 
    ## Or perhaps just let people set $TZ?
611
 
    assert isinstance(t, float)
612
 
    
 
623
    """Return a formatted date string.
 
624
 
 
625
    :param t: Seconds since the epoch.
 
626
    :param offset: Timezone offset in seconds east of utc.
 
627
    :param timezone: How to display the time: 'utc', 'original' for the
 
628
         timezone specified by offset, or 'local' for the process's current
 
629
         timezone.
 
630
    :param show_offset: Whether to append the timezone.
 
631
    :param date_fmt: strftime format.
 
632
    """
613
633
    if timezone == 'utc':
614
634
        tt = time.gmtime(t)
615
635
        offset = 0
621
641
        tt = time.localtime(t)
622
642
        offset = local_time_offset(t)
623
643
    else:
624
 
        raise errors.BzrError("unsupported timezone format %r" % timezone,
625
 
                              ['options are "utc", "original", "local"'])
 
644
        raise errors.UnsupportedTimezoneFormat(timezone)
626
645
    if date_fmt is None:
627
646
        date_fmt = "%a %Y-%m-%d %H:%M:%S"
628
647
    if show_offset:
748
767
    return rps
749
768
 
750
769
def joinpath(p):
751
 
    assert isinstance(p, list)
 
770
    assert isinstance(p, (list, tuple))
752
771
    for f in p:
753
772
        if (f == '..') or (f is None) or (f == ''):
754
773
            raise errors.BzrError("sorry, %r not allowed in path" % f)
755
774
    return pathjoin(*p)
756
775
 
757
776
 
758
 
@deprecated_function(zero_nine)
759
 
def appendpath(p1, p2):
760
 
    if p1 == '':
761
 
        return p2
762
 
    else:
763
 
        return pathjoin(p1, p2)
764
 
    
765
 
 
766
777
def split_lines(s):
767
778
    """Split s into lines, but without removing the newline characters."""
768
779
    lines = s.split('\n')
788
799
            raise
789
800
        shutil.copyfile(src, dest)
790
801
 
791
 
def delete_any(full_path):
 
802
 
 
803
# Look Before You Leap (LBYL) is appropriate here instead of Easier to Ask for
 
804
# Forgiveness than Permission (EAFP) because:
 
805
# - root can damage a solaris file system by using unlink,
 
806
# - unlink raises different exceptions on different OSes (linux: EISDIR, win32:
 
807
#   EACCES, OSX: EPERM) when invoked on a directory.
 
808
def delete_any(path):
792
809
    """Delete a file or directory."""
793
 
    try:
794
 
        os.unlink(full_path)
795
 
    except OSError, e:
796
 
    # We may be renaming a dangling inventory id
797
 
        if e.errno not in (errno.EISDIR, errno.EACCES, errno.EPERM):
798
 
            raise
799
 
        os.rmdir(full_path)
 
810
    if isdir(path): # Takes care of symlinks
 
811
        os.rmdir(path)
 
812
    else:
 
813
        os.unlink(path)
800
814
 
801
815
 
802
816
def has_symlinks():
804
818
        return True
805
819
    else:
806
820
        return False
807
 
        
 
821
 
 
822
 
 
823
def has_hardlinks():
 
824
    if getattr(os, 'link', None) is not None:
 
825
        return True
 
826
    else:
 
827
        return False
 
828
 
808
829
 
809
830
def contains_whitespace(s):
810
831
    """True if there are any whitespace characters in s."""
904
925
    return unicode_or_utf8_string.encode('utf-8')
905
926
 
906
927
 
907
 
def safe_revision_id(unicode_or_utf8_string):
 
928
_revision_id_warning = ('Unicode revision ids were deprecated in bzr 0.15.'
 
929
                        ' Revision id generators should be creating utf8'
 
930
                        ' revision ids.')
 
931
 
 
932
 
 
933
def safe_revision_id(unicode_or_utf8_string, warn=True):
908
934
    """Revision ids should now be utf8, but at one point they were unicode.
909
935
 
 
936
    :param unicode_or_utf8_string: A possibly Unicode revision_id. (can also be
 
937
        utf8 or None).
 
938
    :param warn: Functions that are sanitizing user data can set warn=False
 
939
    :return: None or a utf8 revision id.
 
940
    """
 
941
    if (unicode_or_utf8_string is None
 
942
        or unicode_or_utf8_string.__class__ == str):
 
943
        return unicode_or_utf8_string
 
944
    if warn:
 
945
        symbol_versioning.warn(_revision_id_warning, DeprecationWarning,
 
946
                               stacklevel=2)
 
947
    return cache_utf8.encode(unicode_or_utf8_string)
 
948
 
 
949
 
 
950
_file_id_warning = ('Unicode file ids were deprecated in bzr 0.15. File id'
 
951
                    ' generators should be creating utf8 file ids.')
 
952
 
 
953
 
 
954
def safe_file_id(unicode_or_utf8_string, warn=True):
 
955
    """File ids should now be utf8, but at one point they were unicode.
 
956
 
910
957
    This is the same as safe_utf8, except it uses the cached encode functions
911
958
    to save a little bit of performance.
 
959
 
 
960
    :param unicode_or_utf8_string: A possibly Unicode file_id. (can also be
 
961
        utf8 or None).
 
962
    :param warn: Functions that are sanitizing user data can set warn=False
 
963
    :return: None or a utf8 file id.
912
964
    """
913
 
    if unicode_or_utf8_string is None:
914
 
        return None
915
 
    if isinstance(unicode_or_utf8_string, str):
916
 
        # TODO: jam 20070209 Eventually just remove this check.
917
 
        try:
918
 
            utf8_str = cache_utf8.get_cached_utf8(unicode_or_utf8_string)
919
 
        except UnicodeDecodeError:
920
 
            raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
921
 
        return utf8_str
 
965
    if (unicode_or_utf8_string is None
 
966
        or unicode_or_utf8_string.__class__ == str):
 
967
        return unicode_or_utf8_string
 
968
    if warn:
 
969
        symbol_versioning.warn(_file_id_warning, DeprecationWarning,
 
970
                               stacklevel=2)
922
971
    return cache_utf8.encode(unicode_or_utf8_string)
923
972
 
924
973
 
943
992
    On platforms where the system does not normalize filenames 
944
993
    (Windows, Linux), you have to access a file by its exact path.
945
994
 
946
 
    Internally, bzr only supports NFC/NFKC normalization, since that is 
 
995
    Internally, bzr only supports NFC normalization, since that is 
947
996
    the standard for XML documents.
948
997
 
949
998
    So return the normalized path, and a flag indicating if the file
950
999
    can be accessed by that path.
951
1000
    """
952
1001
 
953
 
    return unicodedata.normalize('NFKC', unicode(path)), True
 
1002
    return unicodedata.normalize('NFC', unicode(path)), True
954
1003
 
955
1004
 
956
1005
def _inaccessible_normalized_filename(path):
957
1006
    __doc__ = _accessible_normalized_filename.__doc__
958
1007
 
959
 
    normalized = unicodedata.normalize('NFKC', unicode(path))
 
1008
    normalized = unicodedata.normalize('NFC', unicode(path))
960
1009
    return normalized, normalized == path
961
1010
 
962
1011
 
1048
1097
    
1049
1098
    The data yielded is of the form:
1050
1099
    ((directory-relpath, directory-path-from-top),
1051
 
    [(relpath, basename, kind, lstat), ...]),
 
1100
    [(relpath, basename, kind, lstat, path-from-top), ...]),
1052
1101
     - directory-relpath is the relative path of the directory being returned
1053
1102
       with respect to top. prefix is prepended to this.
1054
1103
     - directory-path-from-root is the path including top for this directory. 
1072
1121
    # depending on top and prefix - i.e. ./foo and foo as a pair leads to
1073
1122
    # potentially confusing output. We should make this more robust - but
1074
1123
    # not at a speed cost. RBC 20060731
1075
 
    lstat = os.lstat
1076
 
    pending = []
 
1124
    _lstat = os.lstat
1077
1125
    _directory = _directory_kind
1078
1126
    _listdir = os.listdir
1079
 
    pending = [(prefix, "", _directory, None, top)]
 
1127
    _kind_from_mode = _formats.get
 
1128
    pending = [(safe_unicode(prefix), "", _directory, None, safe_unicode(top))]
1080
1129
    while pending:
1081
 
        dirblock = []
1082
 
        currentdir = pending.pop()
1083
1130
        # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1084
 
        top = currentdir[4]
1085
 
        if currentdir[0]:
1086
 
            relroot = currentdir[0] + '/'
1087
 
        else:
1088
 
            relroot = ""
1089
 
        for name in sorted(_listdir(top)):
1090
 
            abspath = top + '/' + name
1091
 
            statvalue = lstat(abspath)
1092
 
            dirblock.append((relroot + name, name,
1093
 
                file_kind_from_stat_mode(statvalue.st_mode),
1094
 
                statvalue, abspath))
1095
 
        yield (currentdir[0], top), dirblock
1096
 
        # push the user specified dirs from dirblock
1097
 
        for dir in reversed(dirblock):
1098
 
            if dir[2] == _directory:
1099
 
                pending.append(dir)
 
1131
        relroot, _, _, _, top = pending.pop()
 
1132
        if relroot:
 
1133
            relprefix = relroot + u'/'
 
1134
        else:
 
1135
            relprefix = ''
 
1136
        top_slash = top + u'/'
 
1137
 
 
1138
        dirblock = []
 
1139
        append = dirblock.append
 
1140
        for name in sorted(_listdir(top)):
 
1141
            abspath = top_slash + name
 
1142
            statvalue = _lstat(abspath)
 
1143
            kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
 
1144
            append((relprefix + name, name, kind, statvalue, abspath))
 
1145
        yield (relroot, top), dirblock
 
1146
 
 
1147
        # push the user specified dirs from dirblock
 
1148
        pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
 
1149
 
 
1150
 
 
1151
def _walkdirs_utf8(top, prefix=""):
 
1152
    """Yield data about all the directories in a tree.
 
1153
 
 
1154
    This yields the same information as walkdirs() only each entry is yielded
 
1155
    in utf-8. On platforms which have a filesystem encoding of utf8 the paths
 
1156
    are returned as exact byte-strings.
 
1157
 
 
1158
    :return: yields a tuple of (dir_info, [file_info])
 
1159
        dir_info is (utf8_relpath, path-from-top)
 
1160
        file_info is (utf8_relpath, utf8_name, kind, lstat, path-from-top)
 
1161
        if top is an absolute path, path-from-top is also an absolute path.
 
1162
        path-from-top might be unicode or utf8, but it is the correct path to
 
1163
        pass to os functions to affect the file in question. (such as os.lstat)
 
1164
    """
 
1165
    fs_encoding = _fs_enc.upper()
 
1166
    if (sys.platform == 'win32' or
 
1167
        fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968')): # ascii
 
1168
        return _walkdirs_unicode_to_utf8(top, prefix=prefix)
 
1169
    else:
 
1170
        return _walkdirs_fs_utf8(top, prefix=prefix)
 
1171
 
 
1172
 
 
1173
def _walkdirs_fs_utf8(top, prefix=""):
 
1174
    """See _walkdirs_utf8.
 
1175
 
 
1176
    This sub-function is called when we know the filesystem is already in utf8
 
1177
    encoding. So we don't need to transcode filenames.
 
1178
    """
 
1179
    _lstat = os.lstat
 
1180
    _directory = _directory_kind
 
1181
    _listdir = os.listdir
 
1182
    _kind_from_mode = _formats.get
 
1183
 
 
1184
    # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
 
1185
    # But we don't actually uses 1-3 in pending, so set them to None
 
1186
    pending = [(safe_utf8(prefix), None, None, None, safe_utf8(top))]
 
1187
    while pending:
 
1188
        relroot, _, _, _, top = pending.pop()
 
1189
        if relroot:
 
1190
            relprefix = relroot + '/'
 
1191
        else:
 
1192
            relprefix = ''
 
1193
        top_slash = top + '/'
 
1194
 
 
1195
        dirblock = []
 
1196
        append = dirblock.append
 
1197
        for name in sorted(_listdir(top)):
 
1198
            abspath = top_slash + name
 
1199
            statvalue = _lstat(abspath)
 
1200
            kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
 
1201
            append((relprefix + name, name, kind, statvalue, abspath))
 
1202
        yield (relroot, top), dirblock
 
1203
 
 
1204
        # push the user specified dirs from dirblock
 
1205
        pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
 
1206
 
 
1207
 
 
1208
def _walkdirs_unicode_to_utf8(top, prefix=""):
 
1209
    """See _walkdirs_utf8
 
1210
 
 
1211
    Because Win32 has a Unicode api, all of the 'path-from-top' entries will be
 
1212
    Unicode paths.
 
1213
    This is currently the fallback code path when the filesystem encoding is
 
1214
    not UTF-8. It may be better to implement an alternative so that we can
 
1215
    safely handle paths that are not properly decodable in the current
 
1216
    encoding.
 
1217
    """
 
1218
    _utf8_encode = codecs.getencoder('utf8')
 
1219
    _lstat = os.lstat
 
1220
    _directory = _directory_kind
 
1221
    _listdir = os.listdir
 
1222
    _kind_from_mode = _formats.get
 
1223
 
 
1224
    pending = [(safe_utf8(prefix), None, None, None, safe_unicode(top))]
 
1225
    while pending:
 
1226
        relroot, _, _, _, top = pending.pop()
 
1227
        if relroot:
 
1228
            relprefix = relroot + '/'
 
1229
        else:
 
1230
            relprefix = ''
 
1231
        top_slash = top + u'/'
 
1232
 
 
1233
        dirblock = []
 
1234
        append = dirblock.append
 
1235
        for name in sorted(_listdir(top)):
 
1236
            name_utf8 = _utf8_encode(name)[0]
 
1237
            abspath = top_slash + name
 
1238
            statvalue = _lstat(abspath)
 
1239
            kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
 
1240
            append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
 
1241
        yield (relroot, top), dirblock
 
1242
 
 
1243
        # push the user specified dirs from dirblock
 
1244
        pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1100
1245
 
1101
1246
 
1102
1247
def copy_tree(from_path, to_path, handlers={}):
1238
1383
        b += new
1239
1384
    return b
1240
1385
 
 
1386
 
 
1387
def send_all(socket, bytes):
 
1388
    """Send all bytes on a socket.
 
1389
 
 
1390
    Regular socket.sendall() can give socket error 10053 on Windows.  This
 
1391
    implementation sends no more than 64k at a time, which avoids this problem.
 
1392
    """
 
1393
    chunk_size = 2**16
 
1394
    for pos in xrange(0, len(bytes), chunk_size):
 
1395
        socket.sendall(bytes[pos:pos+chunk_size])
 
1396
 
 
1397
 
1241
1398
def dereference_path(path):
1242
1399
    """Determine the real path to a file.
1243
1400
 
1250
1407
    # The pathjoin for '.' is a workaround for Python bug #1213894.
1251
1408
    # (initial path components aren't dereferenced)
1252
1409
    return pathjoin(realpath(pathjoin('.', parent)), base)
 
1410
 
 
1411
 
 
1412
def supports_mapi():
 
1413
    """Return True if we can use MAPI to launch a mail client."""
 
1414
    return sys.platform == "win32"
 
1415
 
 
1416
 
 
1417
def resource_string(package, resource_name):
 
1418
    """Load a resource from a package and return it as a string.
 
1419
 
 
1420
    Note: Only packages that start with bzrlib are currently supported.
 
1421
 
 
1422
    This is designed to be a lightweight implementation of resource
 
1423
    loading in a way which is API compatible with the same API from
 
1424
    pkg_resources. See
 
1425
    http://peak.telecommunity.com/DevCenter/PkgResources#basic-resource-access.
 
1426
    If and when pkg_resources becomes a standard library, this routine
 
1427
    can delegate to it.
 
1428
    """
 
1429
    # Check package name is within bzrlib
 
1430
    if package == "bzrlib":
 
1431
        resource_relpath = resource_name
 
1432
    elif package.startswith("bzrlib."):
 
1433
        package = package[len("bzrlib."):].replace('.', os.sep)
 
1434
        resource_relpath = pathjoin(package, resource_name)
 
1435
    else:
 
1436
        raise errors.BzrError('resource package %s not in bzrlib' % package)
 
1437
 
 
1438
    # Map the resource to a file and read its contents
 
1439
    base = dirname(bzrlib.__file__)
 
1440
    if getattr(sys, 'frozen', None):    # bzr.exe
 
1441
        base = abspath(pathjoin(base, '..', '..'))
 
1442
    filename = pathjoin(base, resource_relpath)
 
1443
    return open(filename, 'rU').read()