~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: Martin Pool
  • Date: 2010-08-13 07:56:06 UTC
  • mfrom: (5050.17.4 2.2)
  • mto: (5050.17.6 2.2)
  • mto: This revision was merged to the branch mainline in revision 5379.
  • Revision ID: mbp@sourcefrog.net-20100813075606-8zgmov3ezwans2zo
merge bzr 2.2

Show diffs side-by-side

added added

removed removed

Lines of Context:
18
18
import os
19
19
import re
20
20
import stat
21
 
from stat import S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE
22
21
import sys
23
22
import time
24
23
import codecs
27
26
lazy_import(globals(), """
28
27
from datetime import datetime
29
28
import getpass
30
 
from ntpath import (abspath as _nt_abspath,
31
 
                    join as _nt_join,
32
 
                    normpath as _nt_normpath,
33
 
                    realpath as _nt_realpath,
34
 
                    splitdrive as _nt_splitdrive,
35
 
                    )
 
29
import ntpath
36
30
import posixpath
 
31
# We need to import both shutil and rmtree as we export the later on posix
 
32
# and need the former on windows
37
33
import shutil
38
 
from shutil import (
39
 
    rmtree,
40
 
    )
 
34
from shutil import rmtree
41
35
import socket
42
36
import subprocess
 
37
# We need to import both tempfile and mkdtemp as we export the later on posix
 
38
# and need the former on windows
43
39
import tempfile
44
 
from tempfile import (
45
 
    mkdtemp,
46
 
    )
 
40
from tempfile import mkdtemp
47
41
import unicodedata
48
42
 
49
43
from bzrlib import (
304
298
    running python.exe under cmd.exe return capital C:\\
305
299
    running win32 python inside a cygwin shell returns lowercase c:\\
306
300
    """
307
 
    drive, path = _nt_splitdrive(path)
 
301
    drive, path = ntpath.splitdrive(path)
308
302
    return drive.upper() + path
309
303
 
310
304
 
311
305
def _win32_abspath(path):
312
 
    # Real _nt_abspath doesn't have a problem with a unicode cwd
313
 
    return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
 
306
    # Real ntpath.abspath doesn't have a problem with a unicode cwd
 
307
    return _win32_fixdrive(ntpath.abspath(unicode(path)).replace('\\', '/'))
314
308
 
315
309
 
316
310
def _win98_abspath(path):
327
321
    #   /path       => C:/path
328
322
    path = unicode(path)
329
323
    # check for absolute path
330
 
    drive = _nt_splitdrive(path)[0]
 
324
    drive = ntpath.splitdrive(path)[0]
331
325
    if drive == '' and path[:2] not in('//','\\\\'):
332
326
        cwd = os.getcwdu()
333
327
        # we cannot simply os.path.join cwd and path
334
328
        # because os.path.join('C:','/path') produce '/path'
335
329
        # and this is incorrect
336
330
        if path[:1] in ('/','\\'):
337
 
            cwd = _nt_splitdrive(cwd)[0]
 
331
            cwd = ntpath.splitdrive(cwd)[0]
338
332
            path = path[1:]
339
333
        path = cwd + '\\' + path
340
 
    return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
 
334
    return _win32_fixdrive(ntpath.normpath(path).replace('\\', '/'))
341
335
 
342
336
 
343
337
def _win32_realpath(path):
344
 
    # Real _nt_realpath doesn't have a problem with a unicode cwd
345
 
    return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
 
338
    # Real ntpath.realpath doesn't have a problem with a unicode cwd
 
339
    return _win32_fixdrive(ntpath.realpath(unicode(path)).replace('\\', '/'))
346
340
 
347
341
 
348
342
def _win32_pathjoin(*args):
349
 
    return _nt_join(*args).replace('\\', '/')
 
343
    return ntpath.join(*args).replace('\\', '/')
350
344
 
351
345
 
352
346
def _win32_normpath(path):
353
 
    return _win32_fixdrive(_nt_normpath(unicode(path)).replace('\\', '/'))
 
347
    return _win32_fixdrive(ntpath.normpath(unicode(path)).replace('\\', '/'))
354
348
 
355
349
 
356
350
def _win32_getcwd():
395
389
basename = os.path.basename
396
390
split = os.path.split
397
391
splitext = os.path.splitext
398
 
# These were already imported into local scope
 
392
# These were already lazily imported into local scope
399
393
# mkdtemp = tempfile.mkdtemp
400
394
# rmtree = shutil.rmtree
401
395
 
441
435
    getcwd = _mac_getcwd
442
436
 
443
437
 
444
 
def get_terminal_encoding():
 
438
def get_terminal_encoding(trace=False):
445
439
    """Find the best encoding for printing to the screen.
446
440
 
447
441
    This attempts to check both sys.stdout and sys.stdin to see
453
447
 
454
448
    On my standard US Windows XP, the preferred encoding is
455
449
    cp1252, but the console is cp437
 
450
 
 
451
    :param trace: If True trace the selected encoding via mutter().
456
452
    """
457
453
    from bzrlib.trace import mutter
458
454
    output_encoding = getattr(sys.stdout, 'encoding', None)
460
456
        input_encoding = getattr(sys.stdin, 'encoding', None)
461
457
        if not input_encoding:
462
458
            output_encoding = get_user_encoding()
463
 
            mutter('encoding stdout as osutils.get_user_encoding() %r',
 
459
            if trace:
 
460
                mutter('encoding stdout as osutils.get_user_encoding() %r',
464
461
                   output_encoding)
465
462
        else:
466
463
            output_encoding = input_encoding
467
 
            mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
 
464
            if trace:
 
465
                mutter('encoding stdout as sys.stdin encoding %r',
 
466
                    output_encoding)
468
467
    else:
469
 
        mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
 
468
        if trace:
 
469
            mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
470
470
    if output_encoding == 'cp0':
471
471
        # invalid encoding (cp0 means 'no codepage' on Windows)
472
472
        output_encoding = get_user_encoding()
473
 
        mutter('cp0 is invalid encoding.'
 
473
        if trace:
 
474
            mutter('cp0 is invalid encoding.'
474
475
               ' encoding stdout as osutils.get_user_encoding() %r',
475
476
               output_encoding)
476
477
    # check encoding
502
503
def isdir(f):
503
504
    """True if f is an accessible directory."""
504
505
    try:
505
 
        return S_ISDIR(os.lstat(f)[ST_MODE])
 
506
        return stat.S_ISDIR(os.lstat(f)[stat.ST_MODE])
506
507
    except OSError:
507
508
        return False
508
509
 
510
511
def isfile(f):
511
512
    """True if f is a regular file."""
512
513
    try:
513
 
        return S_ISREG(os.lstat(f)[ST_MODE])
 
514
        return stat.S_ISREG(os.lstat(f)[stat.ST_MODE])
514
515
    except OSError:
515
516
        return False
516
517
 
517
518
def islink(f):
518
519
    """True if f is a symlink."""
519
520
    try:
520
 
        return S_ISLNK(os.lstat(f)[ST_MODE])
 
521
        return stat.S_ISLNK(os.lstat(f)[stat.ST_MODE])
521
522
    except OSError:
522
523
        return False
523
524
 
863
864
 
864
865
def filesize(f):
865
866
    """Return size of given open file."""
866
 
    return os.fstat(f.fileno())[ST_SIZE]
 
867
    return os.fstat(f.fileno())[stat.ST_SIZE]
867
868
 
868
869
 
869
870
# Define rand_bytes based on platform.
931
932
 
932
933
def parent_directories(filename):
933
934
    """Return the list of parent directories, deepest first.
934
 
    
 
935
 
935
936
    For example, parent_directories("a/b/c") -> ["a/b", "a"].
936
937
    """
937
938
    parents = []
961
962
    # NB: This docstring is just an example, not a doctest, because doctest
962
963
    # currently can't cope with the use of lazy imports in this namespace --
963
964
    # mbp 20090729
964
 
    
 
965
 
965
966
    # This currently doesn't report the failure at the time it occurs, because
966
967
    # they tend to happen very early in startup when we can't check config
967
968
    # files etc, and also we want to report all failures but not spam the user
1037
1038
 
1038
1039
 
1039
1040
def delete_any(path):
1040
 
    """Delete a file, symlink or directory.  
1041
 
    
 
1041
    """Delete a file, symlink or directory.
 
1042
 
1042
1043
    Will delete even if readonly.
1043
1044
    """
1044
1045
    try:
1233
1234
    # but for now, we haven't optimized...
1234
1235
    return [canonical_relpath(base, p) for p in paths]
1235
1236
 
 
1237
 
 
1238
def decode_filename(filename):
 
1239
    """Decode the filename using the filesystem encoding
 
1240
 
 
1241
    If it is unicode, it is returned.
 
1242
    Otherwise it is decoded from the the filesystem's encoding. If decoding
 
1243
    fails, a errors.BadFilenameEncoding exception is raised.
 
1244
    """
 
1245
    if type(filename) is unicode:
 
1246
        return filename
 
1247
    try:
 
1248
        return filename.decode(_fs_enc)
 
1249
    except UnicodeDecodeError:
 
1250
        raise errors.BadFilenameEncoding(filename, _fs_enc)
 
1251
 
 
1252
 
1236
1253
def safe_unicode(unicode_or_utf8_string):
1237
1254
    """Coerce unicode_or_utf8_string into unicode.
1238
1255
 
1321
1338
def normalizes_filenames():
1322
1339
    """Return True if this platform normalizes unicode filenames.
1323
1340
 
1324
 
    Mac OSX does, Windows/Linux do not.
 
1341
    Only Mac OSX.
1325
1342
    """
1326
1343
    return _platform_normalizes_filenames
1327
1344
 
1332
1349
    On platforms where the system normalizes filenames (Mac OSX),
1333
1350
    you can access a file by any path which will normalize correctly.
1334
1351
    On platforms where the system does not normalize filenames
1335
 
    (Windows, Linux), you have to access a file by its exact path.
 
1352
    (everything else), you have to access a file by its exact path.
1336
1353
 
1337
1354
    Internally, bzr only supports NFC normalization, since that is
1338
1355
    the standard for XML documents.
1644
1661
        dirblock = []
1645
1662
        append = dirblock.append
1646
1663
        try:
1647
 
            names = sorted(_listdir(top))
 
1664
            names = sorted(map(decode_filename, _listdir(top)))
1648
1665
        except OSError, e:
1649
1666
            if not _is_error_enotdir(e):
1650
1667
                raise
1952
1969
    return user_encoding
1953
1970
 
1954
1971
 
 
1972
def get_diff_header_encoding():
 
1973
    return get_terminal_encoding()
 
1974
 
 
1975
 
1955
1976
def get_host_name():
1956
1977
    """Return the current unicode host name.
1957
1978
 
2020
2041
 
2021
2042
def send_all(sock, bytes, report_activity=None):
2022
2043
    """Send all bytes on a socket.
2023
 
 
 
2044
 
2024
2045
    Breaks large blocks in smaller chunks to avoid buffering limitations on
2025
2046
    some platforms, and catches EINTR which may be thrown if the send is
2026
2047
    interrupted by a signal.
2027
2048
 
2028
2049
    This is preferred to socket.sendall(), because it avoids portability bugs
2029
2050
    and provides activity reporting.
2030
 
 
 
2051
 
2031
2052
    :param report_activity: Call this as bytes are read, see
2032
2053
        Transport._report_activity
2033
2054
    """
2121
2142
 
2122
2143
def until_no_eintr(f, *a, **kw):
2123
2144
    """Run f(*a, **kw), retrying if an EINTR error occurs.
2124
 
    
 
2145
 
2125
2146
    WARNING: you must be certain that it is safe to retry the call repeatedly
2126
2147
    if EINTR does occur.  This is typically only true for low-level operations
2127
2148
    like os.read.  If in any doubt, don't use this.
2142
2163
            raise
2143
2164
 
2144
2165
 
 
2166
@deprecated_function(deprecated_in((2, 2, 0)))
2145
2167
def re_compile_checked(re_string, flags=0, where=""):
2146
2168
    """Return a compiled re, or raise a sensible error.
2147
2169
 
2157
2179
        re_obj = re.compile(re_string, flags)
2158
2180
        re_obj.search("")
2159
2181
        return re_obj
2160
 
    except re.error, e:
 
2182
    except errors.InvalidPattern, e:
2161
2183
        if where:
2162
2184
            where = ' in ' + where
2163
2185
        # despite the name 'error' is a type
2164
 
        raise errors.BzrCommandError('Invalid regular expression%s: %r: %s'
2165
 
            % (where, re_string, e))
 
2186
        raise errors.BzrCommandError('Invalid regular expression%s: %s'
 
2187
            % (where, e.msg))
2166
2188
 
2167
2189
 
2168
2190
if sys.platform == "win32":
2258
2280
if sys.platform == 'win32':
2259
2281
    def open_file(filename, mode='r', bufsize=-1):
2260
2282
        """This function is used to override the ``open`` builtin.
2261
 
        
 
2283
 
2262
2284
        But it uses O_NOINHERIT flag so the file handle is not inherited by
2263
2285
        child processes.  Deleting or renaming a closed file opened with this
2264
2286
        function is not blocking child processes.