/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

  • Committer: Robert Collins
  • Date: 2009-05-23 20:57:12 UTC
  • mfrom: (4371 +trunk)
  • mto: This revision was merged to the branch mainline in revision 4441.
  • Revision ID: robertc@robertcollins.net-20090523205712-lcwbfqk6vwavinuv
MergeĀ .dev.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2009 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
import os
18
18
import re
77
77
O_BINARY = getattr(os, 'O_BINARY', 0)
78
78
 
79
79
 
 
80
def get_unicode_argv():
 
81
    try:
 
82
        user_encoding = get_user_encoding()
 
83
        return [a.decode(user_encoding) for a in sys.argv[1:]]
 
84
    except UnicodeDecodeError:
 
85
        raise errors.BzrError(("Parameter '%r' is unsupported by the current "
 
86
                                                            "encoding." % a))
 
87
 
 
88
 
80
89
def make_readonly(filename):
81
90
    """Make a filename read-only."""
82
91
    mod = os.lstat(filename).st_mode
97
106
 
98
107
    :param paths: A container (and hence not None) of paths.
99
108
    :return: A set of paths sufficient to include everything in paths via
100
 
        is_inside_any, drawn from the paths parameter.
 
109
        is_inside, drawn from the paths parameter.
101
110
    """
102
 
    search_paths = set()
103
 
    paths = set(paths)
104
 
    for path in paths:
105
 
        other_paths = paths.difference([path])
106
 
        if not is_inside_any(other_paths, path):
107
 
            # this is a top level path, we must check it.
108
 
            search_paths.add(path)
109
 
    return search_paths
 
111
    if len(paths) < 2:
 
112
        return set(paths)
 
113
 
 
114
    def sort_key(path):
 
115
        return path.split('/')
 
116
    sorted_paths = sorted(list(paths), key=sort_key)
 
117
 
 
118
    search_paths = [sorted_paths[0]]
 
119
    for path in sorted_paths[1:]:
 
120
        if not is_inside(search_paths[-1], path):
 
121
            # This path is unique, add it
 
122
            search_paths.append(path)
 
123
 
 
124
    return set(search_paths)
110
125
 
111
126
 
112
127
_QUOTE_RE = None
384
399
    def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
385
400
        """Replacer for shutil.rmtree: could remove readonly dirs/files"""
386
401
        return shutil.rmtree(path, ignore_errors, onerror)
 
402
 
 
403
    f = win32utils.get_unicode_argv     # special function or None
 
404
    if f is not None:
 
405
        get_unicode_argv = f
 
406
 
387
407
elif sys.platform == 'darwin':
388
408
    getcwd = _mac_getcwd
389
409
 
597
617
    return s.hexdigest()
598
618
 
599
619
 
 
620
def size_sha_file(f):
 
621
    """Calculate the size and hexdigest of an open file.
 
622
 
 
623
    The file cursor should be already at the start and
 
624
    the caller is responsible for closing the file afterwards.
 
625
    """
 
626
    size = 0
 
627
    s = sha()
 
628
    BUFSIZE = 128<<10
 
629
    while True:
 
630
        b = f.read(BUFSIZE)
 
631
        if not b:
 
632
            break
 
633
        size += len(b)
 
634
        s.update(b)
 
635
    return size, s.hexdigest()
 
636
 
 
637
 
600
638
def sha_file_by_name(fname):
601
639
    """Calculate the SHA1 of a file by reading the full text"""
602
640
    s = sha()
907
945
            and sys.platform not in ('cygwin', 'win32'))
908
946
 
909
947
 
 
948
def readlink(abspath):
 
949
    """Return a string representing the path to which the symbolic link points.
 
950
 
 
951
    :param abspath: The link absolute unicode path.
 
952
 
 
953
    This his guaranteed to return the symbolic link in unicode in all python
 
954
    versions.
 
955
    """
 
956
    link = abspath.encode(_fs_enc)
 
957
    target = os.readlink(link)
 
958
    target = target.decode(_fs_enc)
 
959
    return target
 
960
 
 
961
 
910
962
def contains_whitespace(s):
911
963
    """True if there are any whitespace characters in s."""
912
964
    # string.whitespace can include '\xa0' in certain locales, because it is
1012
1064
    return current[len(abs_base)+1:]
1013
1065
 
1014
1066
# XXX - TODO - we need better detection/integration of case-insensitive
1015
 
# file-systems; Linux often sees FAT32 devices, for example, so could
1016
 
# probably benefit from the same basic support there.  For now though, only
1017
 
# Windows gets that support, and it gets it for *all* file-systems!
1018
 
if sys.platform == "win32":
 
1067
# file-systems; Linux often sees FAT32 devices (or NFS-mounted OSX
 
1068
# filesystems), for example, so could probably benefit from the same basic
 
1069
# support there.  For now though, only Windows and OSX get that support, and
 
1070
# they get it for *all* file-systems!
 
1071
if sys.platform in ('win32', 'darwin'):
1019
1072
    canonical_relpath = _cicp_canonical_relpath
1020
1073
else:
1021
1074
    canonical_relpath = relpath
1033
1086
    """Coerce unicode_or_utf8_string into unicode.
1034
1087
 
1035
1088
    If it is unicode, it is returned.
1036
 
    Otherwise it is decoded from utf-8. If a decoding error
1037
 
    occurs, it is wrapped as a If the decoding fails, the exception is wrapped
1038
 
    as a BzrBadParameter exception.
 
1089
    Otherwise it is decoded from utf-8. If decoding fails, the exception is
 
1090
    wrapped in a BzrBadParameterNotUnicode exception.
1039
1091
    """
1040
1092
    if isinstance(unicode_or_utf8_string, unicode):
1041
1093
        return unicode_or_utf8_string
1374
1426
            #       for win98 anyway.
1375
1427
            try:
1376
1428
                from bzrlib._walkdirs_win32 import Win32ReadDir
1377
 
            except ImportError:
1378
 
                _selected_dir_reader = UnicodeDirReader()
1379
 
            else:
1380
1429
                _selected_dir_reader = Win32ReadDir()
1381
 
        elif fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
 
1430
            except ImportError:
 
1431
                pass
 
1432
        elif fs_encoding in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
1382
1433
            # ANSI_X3.4-1968 is a form of ASCII
1383
 
            _selected_dir_reader = UnicodeDirReader()
1384
 
        else:
1385
1434
            try:
1386
1435
                from bzrlib._readdir_pyx import UTF8DirReader
1387
 
            except ImportError:
1388
 
                # No optimised code path
1389
 
                _selected_dir_reader = UnicodeDirReader()
1390
 
            else:
1391
1436
                _selected_dir_reader = UTF8DirReader()
 
1437
            except ImportError:
 
1438
                pass
 
1439
 
 
1440
    if _selected_dir_reader is None:
 
1441
        # Fallback to the python version
 
1442
        _selected_dir_reader = UnicodeDirReader()
 
1443
 
1392
1444
    # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1393
1445
    # But we don't actually uses 1-3 in pending, so set them to None
1394
1446
    pending = [[_selected_dir_reader.top_prefix_to_starting_dir(top, prefix)]]
1722
1774
                continue
1723
1775
            raise
1724
1776
 
 
1777
def re_compile_checked(re_string, flags=0, where=""):
 
1778
    """Return a compiled re, or raise a sensible error.
 
1779
 
 
1780
    This should only be used when compiling user-supplied REs.
 
1781
 
 
1782
    :param re_string: Text form of regular expression.
 
1783
    :param flags: eg re.IGNORECASE
 
1784
    :param where: Message explaining to the user the context where
 
1785
        it occurred, eg 'log search filter'.
 
1786
    """
 
1787
    # from https://bugs.launchpad.net/bzr/+bug/251352
 
1788
    try:
 
1789
        re_obj = re.compile(re_string, flags)
 
1790
        re_obj.search("")
 
1791
        return re_obj
 
1792
    except re.error, e:
 
1793
        if where:
 
1794
            where = ' in ' + where
 
1795
        # despite the name 'error' is a type
 
1796
        raise errors.BzrCommandError('Invalid regular expression%s: %r: %s'
 
1797
            % (where, re_string, e))
 
1798
 
1725
1799
 
1726
1800
if sys.platform == "win32":
1727
1801
    import msvcrt