~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: Robert Collins
  • Date: 2007-04-19 02:27:44 UTC
  • mto: This revision was merged to the branch mainline in revision 2426.
  • Revision ID: robertc@robertcollins.net-20070419022744-pfdqz42kp1wizh43
``make docs`` now creates a man page at ``man1/bzr.1`` fixing bug 107388.
(Robert Collins)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2009 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
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
 
17
from cStringIO import StringIO
17
18
import os
18
19
import re
19
20
import stat
34
35
                    splitdrive as _nt_splitdrive,
35
36
                    )
36
37
import posixpath
 
38
import sha
37
39
import shutil
38
40
from shutil import (
39
41
    rmtree,
51
53
    )
52
54
""")
53
55
 
54
 
# sha and md5 modules are deprecated in python2.6 but hashlib is available as
55
 
# of 2.5
56
 
if sys.version_info < (2, 5):
57
 
    import md5 as _mod_md5
58
 
    md5 = _mod_md5.new
59
 
    import sha as _mod_sha
60
 
    sha = _mod_sha.new
61
 
else:
62
 
    from hashlib import (
63
 
        md5,
64
 
        sha1 as sha,
65
 
        )
66
 
 
67
 
 
68
56
import bzrlib
69
57
from bzrlib import symbol_versioning
 
58
from bzrlib.symbol_versioning import (
 
59
    deprecated_function,
 
60
    zero_nine,
 
61
    )
 
62
from bzrlib.trace import mutter
70
63
 
71
64
 
72
65
# On win32, O_BINARY is used to indicate the file should
77
70
O_BINARY = getattr(os, 'O_BINARY', 0)
78
71
 
79
72
 
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
 
 
89
73
def make_readonly(filename):
90
74
    """Make a filename read-only."""
91
 
    mod = os.lstat(filename).st_mode
92
 
    if not stat.S_ISLNK(mod):
93
 
        mod = mod & 0777555
94
 
        os.chmod(filename, mod)
 
75
    mod = os.stat(filename).st_mode
 
76
    mod = mod & 0777555
 
77
    os.chmod(filename, mod)
95
78
 
96
79
 
97
80
def make_writable(filename):
98
 
    mod = os.lstat(filename).st_mode
99
 
    if not stat.S_ISLNK(mod):
100
 
        mod = mod | 0200
101
 
        os.chmod(filename, mod)
102
 
 
103
 
 
104
 
def minimum_path_selection(paths):
105
 
    """Return the smallset subset of paths which are outside paths.
106
 
 
107
 
    :param paths: A container (and hence not None) of paths.
108
 
    :return: A set of paths sufficient to include everything in paths via
109
 
        is_inside, drawn from the paths parameter.
110
 
    """
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)
 
81
    mod = os.stat(filename).st_mode
 
82
    mod = mod | 0200
 
83
    os.chmod(filename, mod)
125
84
 
126
85
 
127
86
_QUOTE_RE = None
136
95
    global _QUOTE_RE
137
96
    if _QUOTE_RE is None:
138
97
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
139
 
 
 
98
        
140
99
    if _QUOTE_RE.search(f):
141
100
        return '"' + f + '"'
142
101
    else:
145
104
 
146
105
_directory_kind = 'directory'
147
106
 
 
107
_formats = {
 
108
    stat.S_IFDIR:_directory_kind,
 
109
    stat.S_IFCHR:'chardev',
 
110
    stat.S_IFBLK:'block',
 
111
    stat.S_IFREG:'file',
 
112
    stat.S_IFIFO:'fifo',
 
113
    stat.S_IFLNK:'symlink',
 
114
    stat.S_IFSOCK:'socket',
 
115
}
 
116
 
 
117
 
 
118
def file_kind_from_stat_mode(stat_mode, _formats=_formats, _unknown='unknown'):
 
119
    """Generate a file kind from a stat mode. This is used in walkdirs.
 
120
 
 
121
    Its performance is critical: Do not mutate without careful benchmarking.
 
122
    """
 
123
    try:
 
124
        return _formats[stat_mode & 0170000]
 
125
    except KeyError:
 
126
        return _unknown
 
127
 
 
128
 
 
129
def file_kind(f, _lstat=os.lstat, _mapper=file_kind_from_stat_mode):
 
130
    try:
 
131
        return _mapper(_lstat(f).st_mode)
 
132
    except OSError, e:
 
133
        if getattr(e, 'errno', None) == errno.ENOENT:
 
134
            raise errors.NoSuchFile(f)
 
135
        raise
 
136
 
 
137
 
148
138
def get_umask():
149
139
    """Return the current umask"""
150
140
    # Assume that people aren't messing with the umask while running
186
176
 
187
177
def fancy_rename(old, new, rename_func, unlink_func):
188
178
    """A fancy rename, when you don't have atomic rename.
189
 
 
 
179
    
190
180
    :param old: The old path, to rename from
191
181
    :param new: The new path, to rename to
192
182
    :param rename_func: The potentially non-atomic rename function
194
184
    """
195
185
 
196
186
    # sftp rename doesn't allow overwriting, so play tricks:
 
187
    import random
197
188
    base = os.path.basename(new)
198
189
    dirname = os.path.dirname(new)
199
190
    tmp_name = u'tmp.%s.%.9f.%d.%s' % (base, time.time(), os.getpid(), rand_chars(10))
224
215
 
225
216
    success = False
226
217
    try:
227
 
        try:
228
 
            # This may throw an exception, in which case success will
229
 
            # not be set.
230
 
            rename_func(old, new)
231
 
            success = True
232
 
        except (IOError, OSError), e:
233
 
            # source and target may be aliases of each other (e.g. on a
234
 
            # case-insensitive filesystem), so we may have accidentally renamed
235
 
            # source by when we tried to rename target
236
 
            if not (file_existed and e.errno in (None, errno.ENOENT)):
237
 
                raise
 
218
        # This may throw an exception, in which case success will
 
219
        # not be set.
 
220
        rename_func(old, new)
 
221
        success = True
238
222
    finally:
239
223
        if file_existed:
240
224
            # If the file used to exist, rename it back into place
306
290
        path = cwd + '\\' + path
307
291
    return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
308
292
 
 
293
if win32utils.winver == 'Windows 98':
 
294
    _win32_abspath = _win98_abspath
 
295
 
309
296
 
310
297
def _win32_realpath(path):
311
298
    # Real _nt_realpath doesn't have a problem with a unicode cwd
332
319
    """We expect to be able to atomically replace 'new' with old.
333
320
 
334
321
    On win32, if new exists, it must be moved out of the way first,
335
 
    and then deleted.
 
322
    and then deleted. 
336
323
    """
337
324
    try:
338
325
        fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
339
326
    except OSError, e:
340
327
        if e.errno in (errno.EPERM, errno.EACCES, errno.EBUSY, errno.EINVAL):
341
 
            # If we try to rename a non-existant file onto cwd, we get
342
 
            # EPERM or EACCES instead of ENOENT, this will raise ENOENT
 
328
            # If we try to rename a non-existant file onto cwd, we get 
 
329
            # EPERM or EACCES instead of ENOENT, this will raise ENOENT 
343
330
            # if the old path doesn't exist, sometimes we get EACCES
344
331
            # On Linux, we seem to get EBUSY, on Mac we get EINVAL
345
332
            os.lstat(old)
347
334
 
348
335
 
349
336
def _mac_getcwd():
350
 
    return unicodedata.normalize('NFC', os.getcwdu())
 
337
    return unicodedata.normalize('NFKC', os.getcwdu())
351
338
 
352
339
 
353
340
# Default is to just use the python builtins, but these can be rebound on
370
357
 
371
358
 
372
359
if sys.platform == 'win32':
373
 
    if win32utils.winver == 'Windows 98':
374
 
        abspath = _win98_abspath
375
 
    else:
376
 
        abspath = _win32_abspath
 
360
    abspath = _win32_abspath
377
361
    realpath = _win32_realpath
378
362
    pathjoin = _win32_pathjoin
379
363
    normpath = _win32_normpath
399
383
    def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
400
384
        """Replacer for shutil.rmtree: could remove readonly dirs/files"""
401
385
        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
 
 
407
386
elif sys.platform == 'darwin':
408
387
    getcwd = _mac_getcwd
409
388
 
413
392
 
414
393
    This attempts to check both sys.stdout and sys.stdin to see
415
394
    what encoding they are in, and if that fails it falls back to
416
 
    osutils.get_user_encoding().
 
395
    bzrlib.user_encoding.
417
396
    The problem is that on Windows, locale.getpreferredencoding()
418
397
    is not the same encoding as that used by the console:
419
398
    http://mail.python.org/pipermail/python-list/2003-May/162357.html
421
400
    On my standard US Windows XP, the preferred encoding is
422
401
    cp1252, but the console is cp437
423
402
    """
424
 
    from bzrlib.trace import mutter
425
403
    output_encoding = getattr(sys.stdout, 'encoding', None)
426
404
    if not output_encoding:
427
405
        input_encoding = getattr(sys.stdin, 'encoding', None)
428
406
        if not input_encoding:
429
 
            output_encoding = get_user_encoding()
430
 
            mutter('encoding stdout as osutils.get_user_encoding() %r',
431
 
                   output_encoding)
 
407
            output_encoding = bzrlib.user_encoding
 
408
            mutter('encoding stdout as bzrlib.user_encoding %r', output_encoding)
432
409
        else:
433
410
            output_encoding = input_encoding
434
411
            mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
436
413
        mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
437
414
    if output_encoding == 'cp0':
438
415
        # invalid encoding (cp0 means 'no codepage' on Windows)
439
 
        output_encoding = get_user_encoding()
 
416
        output_encoding = bzrlib.user_encoding
440
417
        mutter('cp0 is invalid encoding.'
441
 
               ' encoding stdout as osutils.get_user_encoding() %r',
442
 
               output_encoding)
 
418
               ' encoding stdout as bzrlib.user_encoding %r', output_encoding)
443
419
    # check encoding
444
420
    try:
445
421
        codecs.lookup(output_encoding)
447
423
        sys.stderr.write('bzr: warning:'
448
424
                         ' unknown terminal encoding %s.\n'
449
425
                         '  Using encoding %s instead.\n'
450
 
                         % (output_encoding, get_user_encoding())
 
426
                         % (output_encoding, bzrlib.user_encoding)
451
427
                        )
452
 
        output_encoding = get_user_encoding()
 
428
        output_encoding = bzrlib.user_encoding
453
429
 
454
430
    return output_encoding
455
431
 
466
442
        return pathjoin(F(p), e)
467
443
 
468
444
 
 
445
def backup_file(fn):
 
446
    """Copy a file to a backup.
 
447
 
 
448
    Backups are named in GNU-style, with a ~ suffix.
 
449
 
 
450
    If the file is already a backup, it's not copied.
 
451
    """
 
452
    if fn[-1] == '~':
 
453
        return
 
454
    bfn = fn + '~'
 
455
 
 
456
    if has_symlinks() and os.path.islink(fn):
 
457
        target = os.readlink(fn)
 
458
        os.symlink(target, bfn)
 
459
        return
 
460
    inf = file(fn, 'rb')
 
461
    try:
 
462
        content = inf.read()
 
463
    finally:
 
464
        inf.close()
 
465
    
 
466
    outf = file(bfn, 'wb')
 
467
    try:
 
468
        outf.write(content)
 
469
    finally:
 
470
        outf.close()
 
471
 
 
472
 
469
473
def isdir(f):
470
474
    """True if f is an accessible directory."""
471
475
    try:
490
494
 
491
495
def is_inside(dir, fname):
492
496
    """True if fname is inside dir.
493
 
 
 
497
    
494
498
    The parameters should typically be passed to osutils.normpath first, so
495
499
    that . and .. and repeated slashes are eliminated, and the separators
496
500
    are canonical for the platform.
497
 
 
498
 
    The empty string as a dir name is taken as top-of-tree and matches
 
501
    
 
502
    The empty string as a dir name is taken as top-of-tree and matches 
499
503
    everything.
500
504
    """
501
 
    # XXX: Most callers of this can actually do something smarter by
 
505
    # XXX: Most callers of this can actually do something smarter by 
502
506
    # looking at the inventory
503
507
    if dir == fname:
504
508
        return True
505
 
 
 
509
    
506
510
    if dir == '':
507
511
        return True
508
512
 
528
532
    return False
529
533
 
530
534
 
531
 
def pumpfile(from_file, to_file, read_length=-1, buff_size=32768,
532
 
             report_activity=None, direction='read'):
533
 
    """Copy contents of one file to another.
534
 
 
535
 
    The read_length can either be -1 to read to end-of-file (EOF) or
536
 
    it can specify the maximum number of bytes to read.
537
 
 
538
 
    The buff_size represents the maximum size for each read operation
539
 
    performed on from_file.
540
 
 
541
 
    :param report_activity: Call this as bytes are read, see
542
 
        Transport._report_activity
543
 
    :param direction: Will be passed to report_activity
544
 
 
545
 
    :return: The number of bytes copied.
546
 
    """
547
 
    length = 0
548
 
    if read_length >= 0:
549
 
        # read specified number of bytes
550
 
 
551
 
        while read_length > 0:
552
 
            num_bytes_to_read = min(read_length, buff_size)
553
 
 
554
 
            block = from_file.read(num_bytes_to_read)
555
 
            if not block:
556
 
                # EOF reached
557
 
                break
558
 
            if report_activity is not None:
559
 
                report_activity(len(block), direction)
560
 
            to_file.write(block)
561
 
 
562
 
            actual_bytes_read = len(block)
563
 
            read_length -= actual_bytes_read
564
 
            length += actual_bytes_read
565
 
    else:
566
 
        # read to EOF
567
 
        while True:
568
 
            block = from_file.read(buff_size)
569
 
            if not block:
570
 
                # EOF reached
571
 
                break
572
 
            if report_activity is not None:
573
 
                report_activity(len(block), direction)
574
 
            to_file.write(block)
575
 
            length += len(block)
576
 
    return length
577
 
 
578
 
 
579
 
def pump_string_file(bytes, file_handle, segment_size=None):
580
 
    """Write bytes to file_handle in many smaller writes.
581
 
 
582
 
    :param bytes: The string to write.
583
 
    :param file_handle: The file to write to.
584
 
    """
585
 
    # Write data in chunks rather than all at once, because very large
586
 
    # writes fail on some platforms (e.g. Windows with SMB  mounted
587
 
    # drives).
588
 
    if not segment_size:
589
 
        segment_size = 5242880 # 5MB
590
 
    segments = range(len(bytes) / segment_size + 1)
591
 
    write = file_handle.write
592
 
    for segment_index in segments:
593
 
        segment = buffer(bytes, segment_index * segment_size, segment_size)
594
 
        write(segment)
 
535
def pumpfile(fromfile, tofile):
 
536
    """Copy contents of one file to another."""
 
537
    BUFSIZE = 32768
 
538
    while True:
 
539
        b = fromfile.read(BUFSIZE)
 
540
        if not b:
 
541
            break
 
542
        tofile.write(b)
595
543
 
596
544
 
597
545
def file_iterator(input_file, readsize=32768):
603
551
 
604
552
 
605
553
def sha_file(f):
606
 
    """Calculate the hexdigest of an open file.
607
 
 
608
 
    The file cursor should be already at the start.
609
 
    """
610
 
    s = sha()
 
554
    if getattr(f, 'tell', None) is not None:
 
555
        assert f.tell() == 0
 
556
    s = sha.new()
611
557
    BUFSIZE = 128<<10
612
558
    while True:
613
559
        b = f.read(BUFSIZE)
617
563
    return s.hexdigest()
618
564
 
619
565
 
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
 
 
638
 
def sha_file_by_name(fname):
639
 
    """Calculate the SHA1 of a file by reading the full text"""
640
 
    s = sha()
641
 
    f = os.open(fname, os.O_RDONLY | O_BINARY)
642
 
    try:
643
 
        while True:
644
 
            b = os.read(f, 1<<16)
645
 
            if not b:
646
 
                return s.hexdigest()
647
 
            s.update(b)
648
 
    finally:
649
 
        os.close(f)
650
 
 
651
 
 
652
 
def sha_strings(strings, _factory=sha):
 
566
 
 
567
def sha_strings(strings):
653
568
    """Return the sha-1 of concatenation of strings"""
654
 
    s = _factory()
 
569
    s = sha.new()
655
570
    map(s.update, strings)
656
571
    return s.hexdigest()
657
572
 
658
573
 
659
 
def sha_string(f, _factory=sha):
660
 
    return _factory(f).hexdigest()
 
574
def sha_string(f):
 
575
    s = sha.new()
 
576
    s.update(f)
 
577
    return s.hexdigest()
661
578
 
662
579
 
663
580
def fingerprint_file(f):
 
581
    s = sha.new()
664
582
    b = f.read()
665
 
    return {'size': len(b),
666
 
            'sha1': sha(b).hexdigest()}
 
583
    s.update(b)
 
584
    size = len(b)
 
585
    return {'size': size,
 
586
            'sha1': s.hexdigest()}
667
587
 
668
588
 
669
589
def compare_files(a, b):
685
605
    offset = datetime.fromtimestamp(t) - datetime.utcfromtimestamp(t)
686
606
    return offset.days * 86400 + offset.seconds
687
607
 
688
 
weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
689
 
 
690
 
def format_date(t, offset=0, timezone='original', date_fmt=None,
 
608
    
 
609
def format_date(t, offset=0, timezone='original', date_fmt=None, 
691
610
                show_offset=True):
692
 
    """Return a formatted date string.
693
 
 
694
 
    :param t: Seconds since the epoch.
695
 
    :param offset: Timezone offset in seconds east of utc.
696
 
    :param timezone: How to display the time: 'utc', 'original' for the
697
 
         timezone specified by offset, or 'local' for the process's current
698
 
         timezone.
699
 
    :param date_fmt: strftime format.
700
 
    :param show_offset: Whether to append the timezone.
701
 
    """
702
 
    (date_fmt, tt, offset_str) = \
703
 
               _format_date(t, offset, timezone, date_fmt, show_offset)
704
 
    date_fmt = date_fmt.replace('%a', weekdays[tt[6]])
705
 
    date_str = time.strftime(date_fmt, tt)
706
 
    return date_str + offset_str
707
 
 
708
 
def format_local_date(t, offset=0, timezone='original', date_fmt=None,
709
 
                      show_offset=True):
710
 
    """Return an unicode date string formatted according to the current locale.
711
 
 
712
 
    :param t: Seconds since the epoch.
713
 
    :param offset: Timezone offset in seconds east of utc.
714
 
    :param timezone: How to display the time: 'utc', 'original' for the
715
 
         timezone specified by offset, or 'local' for the process's current
716
 
         timezone.
717
 
    :param date_fmt: strftime format.
718
 
    :param show_offset: Whether to append the timezone.
719
 
    """
720
 
    (date_fmt, tt, offset_str) = \
721
 
               _format_date(t, offset, timezone, date_fmt, show_offset)
722
 
    date_str = time.strftime(date_fmt, tt)
723
 
    if not isinstance(date_str, unicode):
724
 
        date_str = date_str.decode(bzrlib.user_encoding, 'replace')
725
 
    return date_str + offset_str
726
 
 
727
 
def _format_date(t, offset, timezone, date_fmt, show_offset):
 
611
    ## TODO: Perhaps a global option to use either universal or local time?
 
612
    ## Or perhaps just let people set $TZ?
 
613
    assert isinstance(t, float)
 
614
    
728
615
    if timezone == 'utc':
729
616
        tt = time.gmtime(t)
730
617
        offset = 0
736
623
        tt = time.localtime(t)
737
624
        offset = local_time_offset(t)
738
625
    else:
739
 
        raise errors.UnsupportedTimezoneFormat(timezone)
 
626
        raise errors.BzrError("unsupported timezone format %r" % timezone,
 
627
                              ['options are "utc", "original", "local"'])
740
628
    if date_fmt is None:
741
629
        date_fmt = "%a %Y-%m-%d %H:%M:%S"
742
630
    if show_offset:
743
631
        offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
744
632
    else:
745
633
        offset_str = ''
746
 
    return (date_fmt, tt, offset_str)
 
634
    return (time.strftime(date_fmt, tt) +  offset_str)
747
635
 
748
636
 
749
637
def compact_date(when):
750
638
    return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
751
 
 
 
639
    
752
640
 
753
641
def format_delta(delta):
754
642
    """Get a nice looking string for a time delta.
830
718
ALNUM = '0123456789abcdefghijklmnopqrstuvwxyz'
831
719
def rand_chars(num):
832
720
    """Return a random string of num alphanumeric characters
833
 
 
834
 
    The result only contains lowercase chars because it may be used on
 
721
    
 
722
    The result only contains lowercase chars because it may be used on 
835
723
    case-insensitive filesystems.
836
724
    """
837
725
    s = ''
845
733
 
846
734
def splitpath(p):
847
735
    """Turn string into list of parts."""
 
736
    assert isinstance(p, basestring)
 
737
 
848
738
    # split on either delimiter because people might use either on
849
739
    # Windows
850
740
    ps = re.split(r'[\\/]', p)
859
749
            rps.append(f)
860
750
    return rps
861
751
 
862
 
 
863
752
def joinpath(p):
 
753
    assert isinstance(p, (list, tuple))
864
754
    for f in p:
865
755
        if (f == '..') or (f is None) or (f == ''):
866
756
            raise errors.BzrError("sorry, %r not allowed in path" % f)
867
757
    return pathjoin(*p)
868
758
 
869
759
 
870
 
def parent_directories(filename):
871
 
    """Return the list of parent directories, deepest first.
 
760
@deprecated_function(zero_nine)
 
761
def appendpath(p1, p2):
 
762
    if p1 == '':
 
763
        return p2
 
764
    else:
 
765
        return pathjoin(p1, p2)
872
766
    
873
 
    For example, parent_directories("a/b/c") -> ["a/b", "a"].
874
 
    """
875
 
    parents = []
876
 
    parts = splitpath(dirname(filename))
877
 
    while parts:
878
 
        parents.append(joinpath(parts))
879
 
        parts.pop()
880
 
    return parents
881
 
 
882
 
 
883
 
try:
884
 
    from bzrlib._chunks_to_lines_pyx import chunks_to_lines
885
 
except ImportError:
886
 
    from bzrlib._chunks_to_lines_py import chunks_to_lines
887
 
 
888
767
 
889
768
def split_lines(s):
890
769
    """Split s into lines, but without removing the newline characters."""
891
 
    # Trivially convert a fulltext into a 'chunked' representation, and let
892
 
    # chunks_to_lines do the heavy lifting.
893
 
    if isinstance(s, str):
894
 
        # chunks_to_lines only supports 8-bit strings
895
 
        return chunks_to_lines([s])
896
 
    else:
897
 
        return _split_lines(s)
898
 
 
899
 
 
900
 
def _split_lines(s):
901
 
    """Split s into lines, but without removing the newline characters.
902
 
 
903
 
    This supports Unicode or plain string objects.
904
 
    """
905
770
    lines = s.split('\n')
906
771
    result = [line + '\n' for line in lines[:-1]]
907
772
    if lines[-1]:
925
790
            raise
926
791
        shutil.copyfile(src, dest)
927
792
 
928
 
 
929
 
# Look Before You Leap (LBYL) is appropriate here instead of Easier to Ask for
930
 
# Forgiveness than Permission (EAFP) because:
931
 
# - root can damage a solaris file system by using unlink,
932
 
# - unlink raises different exceptions on different OSes (linux: EISDIR, win32:
933
 
#   EACCES, OSX: EPERM) when invoked on a directory.
934
 
def delete_any(path):
 
793
def delete_any(full_path):
935
794
    """Delete a file or directory."""
936
 
    if isdir(path): # Takes care of symlinks
937
 
        os.rmdir(path)
938
 
    else:
939
 
        os.unlink(path)
 
795
    try:
 
796
        os.unlink(full_path)
 
797
    except OSError, e:
 
798
    # We may be renaming a dangling inventory id
 
799
        if e.errno not in (errno.EISDIR, errno.EACCES, errno.EPERM):
 
800
            raise
 
801
        os.rmdir(full_path)
940
802
 
941
803
 
942
804
def has_symlinks():
944
806
        return True
945
807
    else:
946
808
        return False
947
 
 
948
 
 
949
 
def has_hardlinks():
950
 
    if getattr(os, 'link', None) is not None:
951
 
        return True
952
 
    else:
953
 
        return False
954
 
 
955
 
 
956
 
def host_os_dereferences_symlinks():
957
 
    return (has_symlinks()
958
 
            and sys.platform not in ('cygwin', 'win32'))
959
 
 
960
 
 
961
 
def readlink(abspath):
962
 
    """Return a string representing the path to which the symbolic link points.
963
 
 
964
 
    :param abspath: The link absolute unicode path.
965
 
 
966
 
    This his guaranteed to return the symbolic link in unicode in all python
967
 
    versions.
968
 
    """
969
 
    link = abspath.encode(_fs_enc)
970
 
    target = os.readlink(link)
971
 
    target = target.decode(_fs_enc)
972
 
    return target
973
 
 
 
809
        
974
810
 
975
811
def contains_whitespace(s):
976
812
    """True if there are any whitespace characters in s."""
1012
848
    avoids that problem.
1013
849
    """
1014
850
 
1015
 
    if len(base) < MIN_ABS_PATHLENGTH:
1016
 
        # must have space for e.g. a drive letter
1017
 
        raise ValueError('%r is too short to calculate a relative path'
1018
 
            % (base,))
 
851
    assert len(base) >= MIN_ABS_PATHLENGTH, ('Length of base must be equal or'
 
852
        ' exceed the platform minimum length (which is %d)' % 
 
853
        MIN_ABS_PATHLENGTH)
1019
854
 
1020
855
    rp = abspath(path)
1021
856
 
1036
871
        return ''
1037
872
 
1038
873
 
1039
 
def _cicp_canonical_relpath(base, path):
1040
 
    """Return the canonical path relative to base.
1041
 
 
1042
 
    Like relpath, but on case-insensitive-case-preserving file-systems, this
1043
 
    will return the relpath as stored on the file-system rather than in the
1044
 
    case specified in the input string, for all existing portions of the path.
1045
 
 
1046
 
    This will cause O(N) behaviour if called for every path in a tree; if you
1047
 
    have a number of paths to convert, you should use canonical_relpaths().
1048
 
    """
1049
 
    # TODO: it should be possible to optimize this for Windows by using the
1050
 
    # win32 API FindFiles function to look for the specified name - but using
1051
 
    # os.listdir() still gives us the correct, platform agnostic semantics in
1052
 
    # the short term.
1053
 
 
1054
 
    rel = relpath(base, path)
1055
 
    # '.' will have been turned into ''
1056
 
    if not rel:
1057
 
        return rel
1058
 
 
1059
 
    abs_base = abspath(base)
1060
 
    current = abs_base
1061
 
    _listdir = os.listdir
1062
 
 
1063
 
    # use an explicit iterator so we can easily consume the rest on early exit.
1064
 
    bit_iter = iter(rel.split('/'))
1065
 
    for bit in bit_iter:
1066
 
        lbit = bit.lower()
1067
 
        for look in _listdir(current):
1068
 
            if lbit == look.lower():
1069
 
                current = pathjoin(current, look)
1070
 
                break
1071
 
        else:
1072
 
            # got to the end, nothing matched, so we just return the
1073
 
            # non-existing bits as they were specified (the filename may be
1074
 
            # the target of a move, for example).
1075
 
            current = pathjoin(current, bit, *list(bit_iter))
1076
 
            break
1077
 
    return current[len(abs_base)+1:]
1078
 
 
1079
 
# XXX - TODO - we need better detection/integration of case-insensitive
1080
 
# file-systems; Linux often sees FAT32 devices (or NFS-mounted OSX
1081
 
# filesystems), for example, so could probably benefit from the same basic
1082
 
# support there.  For now though, only Windows and OSX get that support, and
1083
 
# they get it for *all* file-systems!
1084
 
if sys.platform in ('win32', 'darwin'):
1085
 
    canonical_relpath = _cicp_canonical_relpath
1086
 
else:
1087
 
    canonical_relpath = relpath
1088
 
 
1089
 
def canonical_relpaths(base, paths):
1090
 
    """Create an iterable to canonicalize a sequence of relative paths.
1091
 
 
1092
 
    The intent is for this implementation to use a cache, vastly speeding
1093
 
    up multiple transformations in the same directory.
1094
 
    """
1095
 
    # but for now, we haven't optimized...
1096
 
    return [canonical_relpath(base, p) for p in paths]
1097
 
 
1098
874
def safe_unicode(unicode_or_utf8_string):
1099
875
    """Coerce unicode_or_utf8_string into unicode.
1100
876
 
1101
877
    If it is unicode, it is returned.
1102
 
    Otherwise it is decoded from utf-8. If decoding fails, the exception is
1103
 
    wrapped in a BzrBadParameterNotUnicode exception.
 
878
    Otherwise it is decoded from utf-8. If a decoding error
 
879
    occurs, it is wrapped as a If the decoding fails, the exception is wrapped 
 
880
    as a BzrBadParameter exception.
1104
881
    """
1105
882
    if isinstance(unicode_or_utf8_string, unicode):
1106
883
        return unicode_or_utf8_string
1193
970
 
1194
971
    On platforms where the system normalizes filenames (Mac OSX),
1195
972
    you can access a file by any path which will normalize correctly.
1196
 
    On platforms where the system does not normalize filenames
 
973
    On platforms where the system does not normalize filenames 
1197
974
    (Windows, Linux), you have to access a file by its exact path.
1198
975
 
1199
 
    Internally, bzr only supports NFC normalization, since that is
 
976
    Internally, bzr only supports NFC/NFKC normalization, since that is 
1200
977
    the standard for XML documents.
1201
978
 
1202
979
    So return the normalized path, and a flag indicating if the file
1203
980
    can be accessed by that path.
1204
981
    """
1205
982
 
1206
 
    return unicodedata.normalize('NFC', unicode(path)), True
 
983
    return unicodedata.normalize('NFKC', unicode(path)), True
1207
984
 
1208
985
 
1209
986
def _inaccessible_normalized_filename(path):
1210
987
    __doc__ = _accessible_normalized_filename.__doc__
1211
988
 
1212
 
    normalized = unicodedata.normalize('NFC', unicode(path))
 
989
    normalized = unicodedata.normalize('NFKC', unicode(path))
1213
990
    return normalized, normalized == path
1214
991
 
1215
992
 
1273
1050
            del os.environ[env_variable]
1274
1051
    else:
1275
1052
        if isinstance(value, unicode):
1276
 
            value = value.encode(get_user_encoding())
 
1053
            value = value.encode(bzrlib.user_encoding)
1277
1054
        os.environ[env_variable] = value
1278
1055
    return orig_val
1279
1056
 
1282
1059
 
1283
1060
 
1284
1061
def check_legal_path(path):
1285
 
    """Check whether the supplied path is legal.
 
1062
    """Check whether the supplied path is legal.  
1286
1063
    This is only required on Windows, so we don't test on other platforms
1287
1064
    right now.
1288
1065
    """
1292
1069
        raise errors.IllegalPath(path)
1293
1070
 
1294
1071
 
1295
 
_WIN32_ERROR_DIRECTORY = 267 # Similar to errno.ENOTDIR
1296
 
 
1297
 
def _is_error_enotdir(e):
1298
 
    """Check if this exception represents ENOTDIR.
1299
 
 
1300
 
    Unfortunately, python is very inconsistent about the exception
1301
 
    here. The cases are:
1302
 
      1) Linux, Mac OSX all versions seem to set errno == ENOTDIR
1303
 
      2) Windows, Python2.4, uses errno == ERROR_DIRECTORY (267)
1304
 
         which is the windows error code.
1305
 
      3) Windows, Python2.5 uses errno == EINVAL and
1306
 
         winerror == ERROR_DIRECTORY
1307
 
 
1308
 
    :param e: An Exception object (expected to be OSError with an errno
1309
 
        attribute, but we should be able to cope with anything)
1310
 
    :return: True if this represents an ENOTDIR error. False otherwise.
1311
 
    """
1312
 
    en = getattr(e, 'errno', None)
1313
 
    if (en == errno.ENOTDIR
1314
 
        or (sys.platform == 'win32'
1315
 
            and (en == _WIN32_ERROR_DIRECTORY
1316
 
                 or (en == errno.EINVAL
1317
 
                     and getattr(e, 'winerror', None) == _WIN32_ERROR_DIRECTORY)
1318
 
        ))):
1319
 
        return True
1320
 
    return False
1321
 
 
1322
 
 
1323
1072
def walkdirs(top, prefix=""):
1324
1073
    """Yield data about all the directories in a tree.
1325
 
 
 
1074
    
1326
1075
    This yields all the data about the contents of a directory at a time.
1327
1076
    After each directory has been yielded, if the caller has mutated the list
1328
1077
    to exclude some directories, they are then not descended into.
1329
 
 
 
1078
    
1330
1079
    The data yielded is of the form:
1331
1080
    ((directory-relpath, directory-path-from-top),
1332
 
    [(relpath, basename, kind, lstat, path-from-top), ...]),
 
1081
    [(directory-relpath, basename, kind, lstat, path-from-top), ...]),
1333
1082
     - directory-relpath is the relative path of the directory being returned
1334
1083
       with respect to top. prefix is prepended to this.
1335
 
     - directory-path-from-root is the path including top for this directory.
 
1084
     - directory-path-from-root is the path including top for this directory. 
1336
1085
       It is suitable for use with os functions.
1337
1086
     - relpath is the relative path within the subtree being walked.
1338
1087
     - basename is the basename of the path
1340
1089
       present within the tree - but it may be recorded as versioned. See
1341
1090
       versioned_kind.
1342
1091
     - lstat is the stat data *if* the file was statted.
1343
 
     - planned, not implemented:
 
1092
     - planned, not implemented: 
1344
1093
       path_from_tree_root is the path from the root of the tree.
1345
1094
 
1346
 
    :param prefix: Prefix the relpaths that are yielded with 'prefix'. This
 
1095
    :param prefix: Prefix the relpaths that are yielded with 'prefix'. This 
1347
1096
        allows one to walk a subtree but get paths that are relative to a tree
1348
1097
        rooted higher up.
1349
1098
    :return: an iterator over the dirs.
1350
1099
    """
1351
1100
    #TODO there is a bit of a smell where the results of the directory-
1352
 
    # summary in this, and the path from the root, may not agree
 
1101
    # summary in this, and the path from the root, may not agree 
1353
1102
    # depending on top and prefix - i.e. ./foo and foo as a pair leads to
1354
1103
    # potentially confusing output. We should make this more robust - but
1355
1104
    # not at a speed cost. RBC 20060731
1356
1105
    _lstat = os.lstat
1357
1106
    _directory = _directory_kind
1358
1107
    _listdir = os.listdir
1359
 
    _kind_from_mode = file_kind_from_stat_mode
 
1108
    _kind_from_mode = _formats.get
1360
1109
    pending = [(safe_unicode(prefix), "", _directory, None, safe_unicode(top))]
1361
1110
    while pending:
1362
1111
        # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1369
1118
 
1370
1119
        dirblock = []
1371
1120
        append = dirblock.append
1372
 
        try:
1373
 
            names = sorted(_listdir(top))
1374
 
        except OSError, e:
1375
 
            if not _is_error_enotdir(e):
1376
 
                raise
1377
 
        else:
1378
 
            for name in names:
1379
 
                abspath = top_slash + name
1380
 
                statvalue = _lstat(abspath)
1381
 
                kind = _kind_from_mode(statvalue.st_mode)
1382
 
                append((relprefix + name, name, kind, statvalue, abspath))
 
1121
        for name in sorted(_listdir(top)):
 
1122
            abspath = top_slash + name
 
1123
            statvalue = _lstat(abspath)
 
1124
            kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
 
1125
            append((relprefix + name, name, kind, statvalue, abspath))
1383
1126
        yield (relroot, top), dirblock
1384
1127
 
1385
1128
        # push the user specified dirs from dirblock
1386
1129
        pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1387
1130
 
1388
1131
 
1389
 
class DirReader(object):
1390
 
    """An interface for reading directories."""
1391
 
 
1392
 
    def top_prefix_to_starting_dir(self, top, prefix=""):
1393
 
        """Converts top and prefix to a starting dir entry
1394
 
 
1395
 
        :param top: A utf8 path
1396
 
        :param prefix: An optional utf8 path to prefix output relative paths
1397
 
            with.
1398
 
        :return: A tuple starting with prefix, and ending with the native
1399
 
            encoding of top.
1400
 
        """
1401
 
        raise NotImplementedError(self.top_prefix_to_starting_dir)
1402
 
 
1403
 
    def read_dir(self, prefix, top):
1404
 
        """Read a specific dir.
1405
 
 
1406
 
        :param prefix: A utf8 prefix to be preprended to the path basenames.
1407
 
        :param top: A natively encoded path to read.
1408
 
        :return: A list of the directories contents. Each item contains:
1409
 
            (utf8_relpath, utf8_name, kind, lstatvalue, native_abspath)
1410
 
        """
1411
 
        raise NotImplementedError(self.read_dir)
1412
 
 
1413
 
 
1414
 
_selected_dir_reader = None
1415
 
 
1416
 
 
1417
1132
def _walkdirs_utf8(top, prefix=""):
1418
1133
    """Yield data about all the directories in a tree.
1419
1134
 
1428
1143
        path-from-top might be unicode or utf8, but it is the correct path to
1429
1144
        pass to os functions to affect the file in question. (such as os.lstat)
1430
1145
    """
1431
 
    global _selected_dir_reader
1432
 
    if _selected_dir_reader is None:
1433
 
        fs_encoding = _fs_enc.upper()
1434
 
        if sys.platform == "win32" and win32utils.winver == 'Windows NT':
1435
 
            # Win98 doesn't have unicode apis like FindFirstFileW
1436
 
            # TODO: We possibly could support Win98 by falling back to the
1437
 
            #       original FindFirstFile, and using TCHAR instead of WCHAR,
1438
 
            #       but that gets a bit tricky, and requires custom compiling
1439
 
            #       for win98 anyway.
1440
 
            try:
1441
 
                from bzrlib._walkdirs_win32 import Win32ReadDir
1442
 
                _selected_dir_reader = Win32ReadDir()
1443
 
            except ImportError:
1444
 
                pass
1445
 
        elif fs_encoding in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
1446
 
            # ANSI_X3.4-1968 is a form of ASCII
1447
 
            try:
1448
 
                from bzrlib._readdir_pyx import UTF8DirReader
1449
 
                _selected_dir_reader = UTF8DirReader()
1450
 
            except ImportError:
1451
 
                pass
1452
 
 
1453
 
    if _selected_dir_reader is None:
1454
 
        # Fallback to the python version
1455
 
        _selected_dir_reader = UnicodeDirReader()
 
1146
    fs_encoding = sys.getfilesystemencoding()
 
1147
    if (sys.platform == 'win32' or
 
1148
        fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968')): # ascii
 
1149
        return _walkdirs_unicode_to_utf8(top, prefix=prefix)
 
1150
    else:
 
1151
        return _walkdirs_fs_utf8(top, prefix=prefix)
 
1152
 
 
1153
 
 
1154
def _walkdirs_fs_utf8(top, prefix=""):
 
1155
    """See _walkdirs_utf8.
 
1156
 
 
1157
    This sub-function is called when we know the filesystem is already in utf8
 
1158
    encoding. So we don't need to transcode filenames.
 
1159
    """
 
1160
    _lstat = os.lstat
 
1161
    _directory = _directory_kind
 
1162
    _listdir = os.listdir
 
1163
    _kind_from_mode = _formats.get
1456
1164
 
1457
1165
    # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1458
1166
    # But we don't actually uses 1-3 in pending, so set them to None
1459
 
    pending = [[_selected_dir_reader.top_prefix_to_starting_dir(top, prefix)]]
1460
 
    read_dir = _selected_dir_reader.read_dir
1461
 
    _directory = _directory_kind
 
1167
    pending = [(safe_utf8(prefix), None, None, None, safe_utf8(top))]
1462
1168
    while pending:
1463
 
        relroot, _, _, _, top = pending[-1].pop()
1464
 
        if not pending[-1]:
1465
 
            pending.pop()
1466
 
        dirblock = sorted(read_dir(relroot, top))
 
1169
        relroot, _, _, _, top = pending.pop()
 
1170
        if relroot:
 
1171
            relprefix = relroot + '/'
 
1172
        else:
 
1173
            relprefix = ''
 
1174
        top_slash = top + '/'
 
1175
 
 
1176
        dirblock = []
 
1177
        append = dirblock.append
 
1178
        for name in sorted(_listdir(top)):
 
1179
            abspath = top_slash + name
 
1180
            statvalue = _lstat(abspath)
 
1181
            kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
 
1182
            append((relprefix + name, name, kind, statvalue, abspath))
1467
1183
        yield (relroot, top), dirblock
 
1184
 
1468
1185
        # push the user specified dirs from dirblock
1469
 
        next = [d for d in reversed(dirblock) if d[2] == _directory]
1470
 
        if next:
1471
 
            pending.append(next)
1472
 
 
1473
 
 
1474
 
class UnicodeDirReader(DirReader):
1475
 
    """A dir reader for non-utf8 file systems, which transcodes."""
1476
 
 
1477
 
    __slots__ = ['_utf8_encode']
1478
 
 
1479
 
    def __init__(self):
1480
 
        self._utf8_encode = codecs.getencoder('utf8')
1481
 
 
1482
 
    def top_prefix_to_starting_dir(self, top, prefix=""):
1483
 
        """See DirReader.top_prefix_to_starting_dir."""
1484
 
        return (safe_utf8(prefix), None, None, None, safe_unicode(top))
1485
 
 
1486
 
    def read_dir(self, prefix, top):
1487
 
        """Read a single directory from a non-utf8 file system.
1488
 
 
1489
 
        top, and the abspath element in the output are unicode, all other paths
1490
 
        are utf8. Local disk IO is done via unicode calls to listdir etc.
1491
 
 
1492
 
        This is currently the fallback code path when the filesystem encoding is
1493
 
        not UTF-8. It may be better to implement an alternative so that we can
1494
 
        safely handle paths that are not properly decodable in the current
1495
 
        encoding.
1496
 
 
1497
 
        See DirReader.read_dir for details.
1498
 
        """
1499
 
        _utf8_encode = self._utf8_encode
1500
 
        _lstat = os.lstat
1501
 
        _listdir = os.listdir
1502
 
        _kind_from_mode = file_kind_from_stat_mode
1503
 
 
1504
 
        if prefix:
1505
 
            relprefix = prefix + '/'
 
1186
        pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
 
1187
 
 
1188
 
 
1189
def _walkdirs_unicode_to_utf8(top, prefix=""):
 
1190
    """See _walkdirs_utf8
 
1191
 
 
1192
    Because Win32 has a Unicode api, all of the 'path-from-top' entries will be
 
1193
    Unicode paths.
 
1194
    This is currently the fallback code path when the filesystem encoding is
 
1195
    not UTF-8. It may be better to implement an alternative so that we can
 
1196
    safely handle paths that are not properly decodable in the current
 
1197
    encoding.
 
1198
    """
 
1199
    _utf8_encode = codecs.getencoder('utf8')
 
1200
    _lstat = os.lstat
 
1201
    _directory = _directory_kind
 
1202
    _listdir = os.listdir
 
1203
    _kind_from_mode = _formats.get
 
1204
 
 
1205
    pending = [(safe_utf8(prefix), None, None, None, safe_unicode(top))]
 
1206
    while pending:
 
1207
        relroot, _, _, _, top = pending.pop()
 
1208
        if relroot:
 
1209
            relprefix = relroot + '/'
1506
1210
        else:
1507
1211
            relprefix = ''
1508
1212
        top_slash = top + u'/'
1510
1214
        dirblock = []
1511
1215
        append = dirblock.append
1512
1216
        for name in sorted(_listdir(top)):
1513
 
            try:
1514
 
                name_utf8 = _utf8_encode(name)[0]
1515
 
            except UnicodeDecodeError:
1516
 
                raise errors.BadFilenameEncoding(
1517
 
                    _utf8_encode(relprefix)[0] + name, _fs_enc)
 
1217
            name_utf8 = _utf8_encode(name)[0]
1518
1218
            abspath = top_slash + name
1519
1219
            statvalue = _lstat(abspath)
1520
 
            kind = _kind_from_mode(statvalue.st_mode)
 
1220
            kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
1521
1221
            append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
1522
 
        return dirblock
 
1222
        yield (relroot, top), dirblock
 
1223
 
 
1224
        # push the user specified dirs from dirblock
 
1225
        pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1523
1226
 
1524
1227
 
1525
1228
def copy_tree(from_path, to_path, handlers={}):
1526
1229
    """Copy all of the entries in from_path into to_path.
1527
1230
 
1528
 
    :param from_path: The base directory to copy.
 
1231
    :param from_path: The base directory to copy. 
1529
1232
    :param to_path: The target directory. If it does not exist, it will
1530
1233
        be created.
1531
1234
    :param handlers: A dictionary of functions, which takes a source and
1600
1303
        return _cached_user_encoding
1601
1304
 
1602
1305
    if sys.platform == 'darwin':
1603
 
        # python locale.getpreferredencoding() always return
1604
 
        # 'mac-roman' on darwin. That's a lie.
 
1306
        # work around egregious python 2.4 bug
1605
1307
        sys.platform = 'posix'
1606
1308
        try:
1607
 
            if os.environ.get('LANG', None) is None:
1608
 
                # If LANG is not set, we end up with 'ascii', which is bad
1609
 
                # ('mac-roman' is more than ascii), so we set a default which
1610
 
                # will give us UTF-8 (which appears to work in all cases on
1611
 
                # OSX). Users are still free to override LANG of course, as
1612
 
                # long as it give us something meaningful. This work-around
1613
 
                # *may* not be needed with python 3k and/or OSX 10.5, but will
1614
 
                # work with them too -- vila 20080908
1615
 
                os.environ['LANG'] = 'en_US.UTF-8'
1616
1309
            import locale
1617
1310
        finally:
1618
1311
            sys.platform = 'darwin'
1633
1326
    # Windows returns 'cp0' to indicate there is no code page. So we'll just
1634
1327
    # treat that as ASCII, and not support printing unicode characters to the
1635
1328
    # console.
1636
 
    #
1637
 
    # For python scripts run under vim, we get '', so also treat that as ASCII
1638
 
    if user_encoding in (None, 'cp0', ''):
 
1329
    if user_encoding in (None, 'cp0'):
1639
1330
        user_encoding = 'ascii'
1640
1331
    else:
1641
1332
        # check encoding
1655
1346
    return user_encoding
1656
1347
 
1657
1348
 
1658
 
def get_host_name():
1659
 
    """Return the current unicode host name.
1660
 
 
1661
 
    This is meant to be used in place of socket.gethostname() because that
1662
 
    behaves inconsistently on different platforms.
1663
 
    """
1664
 
    if sys.platform == "win32":
1665
 
        import win32utils
1666
 
        return win32utils.get_host_name()
1667
 
    else:
1668
 
        import socket
1669
 
        return socket.gethostname().decode(get_user_encoding())
1670
 
 
1671
 
 
1672
1349
def recv_all(socket, bytes):
1673
1350
    """Receive an exact number of bytes.
1674
1351
 
1681
1358
    """
1682
1359
    b = ''
1683
1360
    while len(b) < bytes:
1684
 
        new = until_no_eintr(socket.recv, bytes - len(b))
 
1361
        new = socket.recv(bytes - len(b))
1685
1362
        if new == '':
1686
1363
            break # eof
1687
1364
        b += new
1688
1365
    return b
1689
1366
 
1690
 
 
1691
 
def send_all(socket, bytes, report_activity=None):
1692
 
    """Send all bytes on a socket.
1693
 
 
1694
 
    Regular socket.sendall() can give socket error 10053 on Windows.  This
1695
 
    implementation sends no more than 64k at a time, which avoids this problem.
1696
 
 
1697
 
    :param report_activity: Call this as bytes are read, see
1698
 
        Transport._report_activity
1699
 
    """
1700
 
    chunk_size = 2**16
1701
 
    for pos in xrange(0, len(bytes), chunk_size):
1702
 
        block = bytes[pos:pos+chunk_size]
1703
 
        if report_activity is not None:
1704
 
            report_activity(len(block), 'write')
1705
 
        until_no_eintr(socket.sendall, block)
1706
 
 
1707
 
 
1708
1367
def dereference_path(path):
1709
1368
    """Determine the real path to a file.
1710
1369
 
1717
1376
    # The pathjoin for '.' is a workaround for Python bug #1213894.
1718
1377
    # (initial path components aren't dereferenced)
1719
1378
    return pathjoin(realpath(pathjoin('.', parent)), base)
1720
 
 
1721
 
 
1722
 
def supports_mapi():
1723
 
    """Return True if we can use MAPI to launch a mail client."""
1724
 
    return sys.platform == "win32"
1725
 
 
1726
 
 
1727
 
def resource_string(package, resource_name):
1728
 
    """Load a resource from a package and return it as a string.
1729
 
 
1730
 
    Note: Only packages that start with bzrlib are currently supported.
1731
 
 
1732
 
    This is designed to be a lightweight implementation of resource
1733
 
    loading in a way which is API compatible with the same API from
1734
 
    pkg_resources. See
1735
 
    http://peak.telecommunity.com/DevCenter/PkgResources#basic-resource-access.
1736
 
    If and when pkg_resources becomes a standard library, this routine
1737
 
    can delegate to it.
1738
 
    """
1739
 
    # Check package name is within bzrlib
1740
 
    if package == "bzrlib":
1741
 
        resource_relpath = resource_name
1742
 
    elif package.startswith("bzrlib."):
1743
 
        package = package[len("bzrlib."):].replace('.', os.sep)
1744
 
        resource_relpath = pathjoin(package, resource_name)
1745
 
    else:
1746
 
        raise errors.BzrError('resource package %s not in bzrlib' % package)
1747
 
 
1748
 
    # Map the resource to a file and read its contents
1749
 
    base = dirname(bzrlib.__file__)
1750
 
    if getattr(sys, 'frozen', None):    # bzr.exe
1751
 
        base = abspath(pathjoin(base, '..', '..'))
1752
 
    filename = pathjoin(base, resource_relpath)
1753
 
    return open(filename, 'rU').read()
1754
 
 
1755
 
 
1756
 
def file_kind_from_stat_mode_thunk(mode):
1757
 
    global file_kind_from_stat_mode
1758
 
    if file_kind_from_stat_mode is file_kind_from_stat_mode_thunk:
1759
 
        try:
1760
 
            from bzrlib._readdir_pyx import UTF8DirReader
1761
 
            file_kind_from_stat_mode = UTF8DirReader().kind_from_mode
1762
 
        except ImportError:
1763
 
            from bzrlib._readdir_py import (
1764
 
                _kind_from_mode as file_kind_from_stat_mode
1765
 
                )
1766
 
    return file_kind_from_stat_mode(mode)
1767
 
file_kind_from_stat_mode = file_kind_from_stat_mode_thunk
1768
 
 
1769
 
 
1770
 
def file_kind(f, _lstat=os.lstat):
1771
 
    try:
1772
 
        return file_kind_from_stat_mode(_lstat(f).st_mode)
1773
 
    except OSError, e:
1774
 
        if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
1775
 
            raise errors.NoSuchFile(f)
1776
 
        raise
1777
 
 
1778
 
 
1779
 
def until_no_eintr(f, *a, **kw):
1780
 
    """Run f(*a, **kw), retrying if an EINTR error occurs."""
1781
 
    # Borrowed from Twisted's twisted.python.util.untilConcludes function.
1782
 
    while True:
1783
 
        try:
1784
 
            return f(*a, **kw)
1785
 
        except (IOError, OSError), e:
1786
 
            if e.errno == errno.EINTR:
1787
 
                continue
1788
 
            raise
1789
 
 
1790
 
def re_compile_checked(re_string, flags=0, where=""):
1791
 
    """Return a compiled re, or raise a sensible error.
1792
 
 
1793
 
    This should only be used when compiling user-supplied REs.
1794
 
 
1795
 
    :param re_string: Text form of regular expression.
1796
 
    :param flags: eg re.IGNORECASE
1797
 
    :param where: Message explaining to the user the context where
1798
 
        it occurred, eg 'log search filter'.
1799
 
    """
1800
 
    # from https://bugs.launchpad.net/bzr/+bug/251352
1801
 
    try:
1802
 
        re_obj = re.compile(re_string, flags)
1803
 
        re_obj.search("")
1804
 
        return re_obj
1805
 
    except re.error, e:
1806
 
        if where:
1807
 
            where = ' in ' + where
1808
 
        # despite the name 'error' is a type
1809
 
        raise errors.BzrCommandError('Invalid regular expression%s: %r: %s'
1810
 
            % (where, re_string, e))
1811
 
 
1812
 
 
1813
 
if sys.platform == "win32":
1814
 
    import msvcrt
1815
 
    def getchar():
1816
 
        return msvcrt.getch()
1817
 
else:
1818
 
    import tty
1819
 
    import termios
1820
 
    def getchar():
1821
 
        fd = sys.stdin.fileno()
1822
 
        settings = termios.tcgetattr(fd)
1823
 
        try:
1824
 
            tty.setraw(fd)
1825
 
            ch = sys.stdin.read(1)
1826
 
        finally:
1827
 
            termios.tcsetattr(fd, termios.TCSADRAIN, settings)
1828
 
        return ch