~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: Florian Dorn
  • Date: 2012-04-03 14:49:22 UTC
  • mto: This revision was merged to the branch mainline in revision 6546.
  • Revision ID: florian.dorn@boku.ac.at-20120403144922-b8y59csy8l1rzs5u
updated developer docs

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
1
# Copyright (C) 2005-2011 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
 
from cStringIO import StringIO
 
17
import errno
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
 
                  S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
23
21
import sys
24
22
import time
 
23
import codecs
25
24
 
26
25
from bzrlib.lazy_import import lazy_import
27
26
lazy_import(globals(), """
28
 
import codecs
29
27
from datetime import datetime
30
 
import errno
31
 
from ntpath import (abspath as _nt_abspath,
32
 
                    join as _nt_join,
33
 
                    normpath as _nt_normpath,
34
 
                    realpath as _nt_realpath,
35
 
                    splitdrive as _nt_splitdrive,
36
 
                    )
 
28
import getpass
 
29
import ntpath
37
30
import posixpath
38
 
import sha
 
31
# We need to import both shutil and rmtree as we export the later on posix
 
32
# and need the former on windows
39
33
import shutil
40
 
from shutil import (
41
 
    rmtree,
42
 
    )
 
34
from shutil import rmtree
 
35
import socket
 
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 (
50
44
    cache_utf8,
51
45
    errors,
 
46
    trace,
52
47
    win32utils,
53
48
    )
54
49
""")
55
50
 
 
51
from bzrlib.symbol_versioning import (
 
52
    deprecated_function,
 
53
    deprecated_in,
 
54
    )
 
55
 
 
56
from hashlib import (
 
57
    md5,
 
58
    sha1 as sha,
 
59
    )
 
60
 
56
61
 
57
62
import bzrlib
58
63
from bzrlib import symbol_versioning
59
 
from bzrlib.symbol_versioning import (
60
 
    deprecated_function,
61
 
    )
62
 
from bzrlib.trace import mutter
63
 
 
 
64
 
 
65
 
 
66
# Cross platform wall-clock time functionality with decent resolution.
 
67
# On Linux ``time.clock`` returns only CPU time. On Windows, ``time.time()``
 
68
# only has a resolution of ~15ms. Note that ``time.clock()`` is not
 
69
# synchronized with ``time.time()``, this is only meant to be used to find
 
70
# delta times by subtracting from another call to this function.
 
71
timer_func = time.time
 
72
if sys.platform == 'win32':
 
73
    timer_func = time.clock
64
74
 
65
75
# On win32, O_BINARY is used to indicate the file should
66
76
# be opened in binary mode, rather than text mode.
67
77
# On other platforms, O_BINARY doesn't exist, because
68
78
# they always open in binary mode, so it is okay to
69
 
# OR with 0 on those platforms
 
79
# OR with 0 on those platforms.
 
80
# O_NOINHERIT and O_TEXT exists only on win32 too.
70
81
O_BINARY = getattr(os, 'O_BINARY', 0)
 
82
O_TEXT = getattr(os, 'O_TEXT', 0)
 
83
O_NOINHERIT = getattr(os, 'O_NOINHERIT', 0)
 
84
 
 
85
 
 
86
def get_unicode_argv():
 
87
    try:
 
88
        user_encoding = get_user_encoding()
 
89
        return [a.decode(user_encoding) for a in sys.argv[1:]]
 
90
    except UnicodeDecodeError:
 
91
        raise errors.BzrError("Parameter %r encoding is unsupported by %s "
 
92
            "application locale." % (a, user_encoding))
71
93
 
72
94
 
73
95
def make_readonly(filename):
90
112
 
91
113
    :param paths: A container (and hence not None) of paths.
92
114
    :return: A set of paths sufficient to include everything in paths via
93
 
        is_inside_any, drawn from the paths parameter.
 
115
        is_inside, drawn from the paths parameter.
94
116
    """
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
 
117
    if len(paths) < 2:
 
118
        return set(paths)
 
119
 
 
120
    def sort_key(path):
 
121
        return path.split('/')
 
122
    sorted_paths = sorted(list(paths), key=sort_key)
 
123
 
 
124
    search_paths = [sorted_paths[0]]
 
125
    for path in sorted_paths[1:]:
 
126
        if not is_inside(search_paths[-1], path):
 
127
            # This path is unique, add it
 
128
            search_paths.append(path)
 
129
 
 
130
    return set(search_paths)
103
131
 
104
132
 
105
133
_QUOTE_RE = None
114
142
    global _QUOTE_RE
115
143
    if _QUOTE_RE is None:
116
144
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
117
 
        
 
145
 
118
146
    if _QUOTE_RE.search(f):
119
147
        return '"' + f + '"'
120
148
    else:
123
151
 
124
152
_directory_kind = 'directory'
125
153
 
126
 
_formats = {
127
 
    stat.S_IFDIR:_directory_kind,
128
 
    stat.S_IFCHR:'chardev',
129
 
    stat.S_IFBLK:'block',
130
 
    stat.S_IFREG:'file',
131
 
    stat.S_IFIFO:'fifo',
132
 
    stat.S_IFLNK:'symlink',
133
 
    stat.S_IFSOCK:'socket',
134
 
}
135
 
 
136
 
 
137
 
def file_kind_from_stat_mode(stat_mode, _formats=_formats, _unknown='unknown'):
138
 
    """Generate a file kind from a stat mode. This is used in walkdirs.
139
 
 
140
 
    Its performance is critical: Do not mutate without careful benchmarking.
141
 
    """
142
 
    try:
143
 
        return _formats[stat_mode & 0170000]
144
 
    except KeyError:
145
 
        return _unknown
146
 
 
147
 
 
148
 
def file_kind(f, _lstat=os.lstat, _mapper=file_kind_from_stat_mode):
149
 
    try:
150
 
        return _mapper(_lstat(f).st_mode)
151
 
    except OSError, e:
152
 
        if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
153
 
            raise errors.NoSuchFile(f)
154
 
        raise
155
 
 
156
 
 
157
154
def get_umask():
158
155
    """Return the current umask"""
159
156
    # Assume that people aren't messing with the umask while running
176
173
    try:
177
174
        return _kind_marker_map[kind]
178
175
    except KeyError:
179
 
        raise errors.BzrError('invalid file kind %r' % kind)
 
176
        # Slightly faster than using .get(, '') when the common case is that
 
177
        # kind will be found
 
178
        return ''
180
179
 
181
180
 
182
181
lexists = getattr(os.path, 'lexists', None)
195
194
 
196
195
def fancy_rename(old, new, rename_func, unlink_func):
197
196
    """A fancy rename, when you don't have atomic rename.
198
 
    
 
197
 
199
198
    :param old: The old path, to rename from
200
199
    :param new: The new path, to rename to
201
200
    :param rename_func: The potentially non-atomic rename function
202
 
    :param unlink_func: A way to delete the target file if the full rename succeeds
 
201
    :param unlink_func: A way to delete the target file if the full rename
 
202
        succeeds
203
203
    """
204
 
 
205
204
    # sftp rename doesn't allow overwriting, so play tricks:
206
 
    import random
207
205
    base = os.path.basename(new)
208
206
    dirname = os.path.dirname(new)
209
 
    tmp_name = u'tmp.%s.%.9f.%d.%s' % (base, time.time(), os.getpid(), rand_chars(10))
 
207
    # callers use different encodings for the paths so the following MUST
 
208
    # respect that. We rely on python upcasting to unicode if new is unicode
 
209
    # and keeping a str if not.
 
210
    tmp_name = 'tmp.%s.%.9f.%d.%s' % (base, time.time(),
 
211
                                      os.getpid(), rand_chars(10))
210
212
    tmp_name = pathjoin(dirname, tmp_name)
211
213
 
212
214
    # Rename the file out of the way, but keep track if it didn't exist
232
234
    else:
233
235
        file_existed = True
234
236
 
 
237
    failure_exc = None
235
238
    success = False
236
239
    try:
237
240
        try:
243
246
            # source and target may be aliases of each other (e.g. on a
244
247
            # case-insensitive filesystem), so we may have accidentally renamed
245
248
            # source by when we tried to rename target
246
 
            if not (file_existed and e.errno in (None, errno.ENOENT)):
247
 
                raise
 
249
            failure_exc = sys.exc_info()
 
250
            if (file_existed and e.errno in (None, errno.ENOENT)
 
251
                and old.lower() == new.lower()):
 
252
                # source and target are the same file on a case-insensitive
 
253
                # filesystem, so we don't generate an exception
 
254
                failure_exc = None
248
255
    finally:
249
256
        if file_existed:
250
257
            # If the file used to exist, rename it back into place
253
260
                unlink_func(tmp_name)
254
261
            else:
255
262
                rename_func(tmp_name, new)
 
263
    if failure_exc is not None:
 
264
        raise failure_exc[0], failure_exc[1], failure_exc[2]
256
265
 
257
266
 
258
267
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
281
290
    running python.exe under cmd.exe return capital C:\\
282
291
    running win32 python inside a cygwin shell returns lowercase c:\\
283
292
    """
284
 
    drive, path = _nt_splitdrive(path)
 
293
    drive, path = ntpath.splitdrive(path)
285
294
    return drive.upper() + path
286
295
 
287
296
 
288
297
def _win32_abspath(path):
289
 
    # Real _nt_abspath doesn't have a problem with a unicode cwd
290
 
    return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
 
298
    # Real ntpath.abspath doesn't have a problem with a unicode cwd
 
299
    return _win32_fixdrive(ntpath.abspath(unicode(path)).replace('\\', '/'))
291
300
 
292
301
 
293
302
def _win98_abspath(path):
304
313
    #   /path       => C:/path
305
314
    path = unicode(path)
306
315
    # check for absolute path
307
 
    drive = _nt_splitdrive(path)[0]
 
316
    drive = ntpath.splitdrive(path)[0]
308
317
    if drive == '' and path[:2] not in('//','\\\\'):
309
318
        cwd = os.getcwdu()
310
319
        # we cannot simply os.path.join cwd and path
311
320
        # because os.path.join('C:','/path') produce '/path'
312
321
        # and this is incorrect
313
322
        if path[:1] in ('/','\\'):
314
 
            cwd = _nt_splitdrive(cwd)[0]
 
323
            cwd = ntpath.splitdrive(cwd)[0]
315
324
            path = path[1:]
316
325
        path = cwd + '\\' + path
317
 
    return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
318
 
 
319
 
if win32utils.winver == 'Windows 98':
320
 
    _win32_abspath = _win98_abspath
 
326
    return _win32_fixdrive(ntpath.normpath(path).replace('\\', '/'))
321
327
 
322
328
 
323
329
def _win32_realpath(path):
324
 
    # Real _nt_realpath doesn't have a problem with a unicode cwd
325
 
    return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
 
330
    # Real ntpath.realpath doesn't have a problem with a unicode cwd
 
331
    return _win32_fixdrive(ntpath.realpath(unicode(path)).replace('\\', '/'))
326
332
 
327
333
 
328
334
def _win32_pathjoin(*args):
329
 
    return _nt_join(*args).replace('\\', '/')
 
335
    return ntpath.join(*args).replace('\\', '/')
330
336
 
331
337
 
332
338
def _win32_normpath(path):
333
 
    return _win32_fixdrive(_nt_normpath(unicode(path)).replace('\\', '/'))
 
339
    return _win32_fixdrive(ntpath.normpath(unicode(path)).replace('\\', '/'))
334
340
 
335
341
 
336
342
def _win32_getcwd():
345
351
    """We expect to be able to atomically replace 'new' with old.
346
352
 
347
353
    On win32, if new exists, it must be moved out of the way first,
348
 
    and then deleted. 
 
354
    and then deleted.
349
355
    """
350
356
    try:
351
357
        fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
352
358
    except OSError, e:
353
359
        if e.errno in (errno.EPERM, errno.EACCES, errno.EBUSY, errno.EINVAL):
354
 
            # If we try to rename a non-existant file onto cwd, we get 
355
 
            # EPERM or EACCES instead of ENOENT, this will raise ENOENT 
 
360
            # If we try to rename a non-existant file onto cwd, we get
 
361
            # EPERM or EACCES instead of ENOENT, this will raise ENOENT
356
362
            # if the old path doesn't exist, sometimes we get EACCES
357
363
            # On Linux, we seem to get EBUSY, on Mac we get EINVAL
358
364
            os.lstat(old)
375
381
basename = os.path.basename
376
382
split = os.path.split
377
383
splitext = os.path.splitext
378
 
# These were already imported into local scope
 
384
# These were already lazily imported into local scope
379
385
# mkdtemp = tempfile.mkdtemp
380
386
# rmtree = shutil.rmtree
 
387
lstat = os.lstat
 
388
fstat = os.fstat
 
389
 
 
390
def wrap_stat(st):
 
391
    return st
 
392
 
381
393
 
382
394
MIN_ABS_PATHLENGTH = 1
383
395
 
384
396
 
385
397
if sys.platform == 'win32':
386
 
    abspath = _win32_abspath
 
398
    if win32utils.winver == 'Windows 98':
 
399
        abspath = _win98_abspath
 
400
    else:
 
401
        abspath = _win32_abspath
387
402
    realpath = _win32_realpath
388
403
    pathjoin = _win32_pathjoin
389
404
    normpath = _win32_normpath
390
405
    getcwd = _win32_getcwd
391
406
    mkdtemp = _win32_mkdtemp
392
407
    rename = _win32_rename
 
408
    try:
 
409
        from bzrlib import _walkdirs_win32
 
410
    except ImportError:
 
411
        pass
 
412
    else:
 
413
        lstat = _walkdirs_win32.lstat
 
414
        fstat = _walkdirs_win32.fstat
 
415
        wrap_stat = _walkdirs_win32.wrap_stat
393
416
 
394
417
    MIN_ABS_PATHLENGTH = 3
395
418
 
409
432
    def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
410
433
        """Replacer for shutil.rmtree: could remove readonly dirs/files"""
411
434
        return shutil.rmtree(path, ignore_errors, onerror)
 
435
 
 
436
    f = win32utils.get_unicode_argv     # special function or None
 
437
    if f is not None:
 
438
        get_unicode_argv = f
 
439
 
412
440
elif sys.platform == 'darwin':
413
441
    getcwd = _mac_getcwd
414
442
 
415
443
 
416
 
def get_terminal_encoding():
 
444
def get_terminal_encoding(trace=False):
417
445
    """Find the best encoding for printing to the screen.
418
446
 
419
447
    This attempts to check both sys.stdout and sys.stdin to see
420
448
    what encoding they are in, and if that fails it falls back to
421
 
    bzrlib.user_encoding.
 
449
    osutils.get_user_encoding().
422
450
    The problem is that on Windows, locale.getpreferredencoding()
423
451
    is not the same encoding as that used by the console:
424
452
    http://mail.python.org/pipermail/python-list/2003-May/162357.html
425
453
 
426
454
    On my standard US Windows XP, the preferred encoding is
427
455
    cp1252, but the console is cp437
 
456
 
 
457
    :param trace: If True trace the selected encoding via mutter().
428
458
    """
 
459
    from bzrlib.trace import mutter
429
460
    output_encoding = getattr(sys.stdout, 'encoding', None)
430
461
    if not output_encoding:
431
462
        input_encoding = getattr(sys.stdin, 'encoding', None)
432
463
        if not input_encoding:
433
 
            output_encoding = bzrlib.user_encoding
434
 
            mutter('encoding stdout as bzrlib.user_encoding %r', output_encoding)
 
464
            output_encoding = get_user_encoding()
 
465
            if trace:
 
466
                mutter('encoding stdout as osutils.get_user_encoding() %r',
 
467
                   output_encoding)
435
468
        else:
436
469
            output_encoding = input_encoding
437
 
            mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
 
470
            if trace:
 
471
                mutter('encoding stdout as sys.stdin encoding %r',
 
472
                    output_encoding)
438
473
    else:
439
 
        mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
 
474
        if trace:
 
475
            mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
440
476
    if output_encoding == 'cp0':
441
477
        # invalid encoding (cp0 means 'no codepage' on Windows)
442
 
        output_encoding = bzrlib.user_encoding
443
 
        mutter('cp0 is invalid encoding.'
444
 
               ' encoding stdout as bzrlib.user_encoding %r', output_encoding)
 
478
        output_encoding = get_user_encoding()
 
479
        if trace:
 
480
            mutter('cp0 is invalid encoding.'
 
481
               ' encoding stdout as osutils.get_user_encoding() %r',
 
482
               output_encoding)
445
483
    # check encoding
446
484
    try:
447
485
        codecs.lookup(output_encoding)
449
487
        sys.stderr.write('bzr: warning:'
450
488
                         ' unknown terminal encoding %s.\n'
451
489
                         '  Using encoding %s instead.\n'
452
 
                         % (output_encoding, bzrlib.user_encoding)
 
490
                         % (output_encoding, get_user_encoding())
453
491
                        )
454
 
        output_encoding = bzrlib.user_encoding
 
492
        output_encoding = get_user_encoding()
455
493
 
456
494
    return output_encoding
457
495
 
471
509
def isdir(f):
472
510
    """True if f is an accessible directory."""
473
511
    try:
474
 
        return S_ISDIR(os.lstat(f)[ST_MODE])
 
512
        return stat.S_ISDIR(os.lstat(f)[stat.ST_MODE])
475
513
    except OSError:
476
514
        return False
477
515
 
479
517
def isfile(f):
480
518
    """True if f is a regular file."""
481
519
    try:
482
 
        return S_ISREG(os.lstat(f)[ST_MODE])
 
520
        return stat.S_ISREG(os.lstat(f)[stat.ST_MODE])
483
521
    except OSError:
484
522
        return False
485
523
 
486
524
def islink(f):
487
525
    """True if f is a symlink."""
488
526
    try:
489
 
        return S_ISLNK(os.lstat(f)[ST_MODE])
 
527
        return stat.S_ISLNK(os.lstat(f)[stat.ST_MODE])
490
528
    except OSError:
491
529
        return False
492
530
 
493
531
def is_inside(dir, fname):
494
532
    """True if fname is inside dir.
495
 
    
 
533
 
496
534
    The parameters should typically be passed to osutils.normpath first, so
497
535
    that . and .. and repeated slashes are eliminated, and the separators
498
536
    are canonical for the platform.
499
 
    
500
 
    The empty string as a dir name is taken as top-of-tree and matches 
 
537
 
 
538
    The empty string as a dir name is taken as top-of-tree and matches
501
539
    everything.
502
540
    """
503
 
    # XXX: Most callers of this can actually do something smarter by 
 
541
    # XXX: Most callers of this can actually do something smarter by
504
542
    # looking at the inventory
505
543
    if dir == fname:
506
544
        return True
507
 
    
 
545
 
508
546
    if dir == '':
509
547
        return True
510
548
 
530
568
    return False
531
569
 
532
570
 
533
 
def pumpfile(from_file, to_file, read_length=-1, buff_size=32768):
 
571
def pumpfile(from_file, to_file, read_length=-1, buff_size=32768,
 
572
             report_activity=None, direction='read'):
534
573
    """Copy contents of one file to another.
535
574
 
536
575
    The read_length can either be -1 to read to end-of-file (EOF) or
539
578
    The buff_size represents the maximum size for each read operation
540
579
    performed on from_file.
541
580
 
 
581
    :param report_activity: Call this as bytes are read, see
 
582
        Transport._report_activity
 
583
    :param direction: Will be passed to report_activity
 
584
 
542
585
    :return: The number of bytes copied.
543
586
    """
544
587
    length = 0
552
595
            if not block:
553
596
                # EOF reached
554
597
                break
 
598
            if report_activity is not None:
 
599
                report_activity(len(block), direction)
555
600
            to_file.write(block)
556
601
 
557
602
            actual_bytes_read = len(block)
564
609
            if not block:
565
610
                # EOF reached
566
611
                break
 
612
            if report_activity is not None:
 
613
                report_activity(len(block), direction)
567
614
            to_file.write(block)
568
615
            length += len(block)
569
616
    return length
600
647
 
601
648
    The file cursor should be already at the start.
602
649
    """
603
 
    s = sha.new()
 
650
    s = sha()
604
651
    BUFSIZE = 128<<10
605
652
    while True:
606
653
        b = f.read(BUFSIZE)
610
657
    return s.hexdigest()
611
658
 
612
659
 
 
660
def size_sha_file(f):
 
661
    """Calculate the size and hexdigest of an open file.
 
662
 
 
663
    The file cursor should be already at the start and
 
664
    the caller is responsible for closing the file afterwards.
 
665
    """
 
666
    size = 0
 
667
    s = sha()
 
668
    BUFSIZE = 128<<10
 
669
    while True:
 
670
        b = f.read(BUFSIZE)
 
671
        if not b:
 
672
            break
 
673
        size += len(b)
 
674
        s.update(b)
 
675
    return size, s.hexdigest()
 
676
 
 
677
 
613
678
def sha_file_by_name(fname):
614
679
    """Calculate the SHA1 of a file by reading the full text"""
615
 
    s = sha.new()
616
 
    f = os.open(fname, os.O_RDONLY | O_BINARY)
 
680
    s = sha()
 
681
    f = os.open(fname, os.O_RDONLY | O_BINARY | O_NOINHERIT)
617
682
    try:
618
683
        while True:
619
684
            b = os.read(f, 1<<16)
624
689
        os.close(f)
625
690
 
626
691
 
627
 
def sha_strings(strings, _factory=sha.new):
 
692
def sha_strings(strings, _factory=sha):
628
693
    """Return the sha-1 of concatenation of strings"""
629
694
    s = _factory()
630
695
    map(s.update, strings)
631
696
    return s.hexdigest()
632
697
 
633
698
 
634
 
def sha_string(f, _factory=sha.new):
 
699
def sha_string(f, _factory=sha):
635
700
    return _factory(f).hexdigest()
636
701
 
637
702
 
638
703
def fingerprint_file(f):
639
704
    b = f.read()
640
705
    return {'size': len(b),
641
 
            'sha1': sha.new(b).hexdigest()}
 
706
            'sha1': sha(b).hexdigest()}
642
707
 
643
708
 
644
709
def compare_files(a, b):
661
726
    return offset.days * 86400 + offset.seconds
662
727
 
663
728
weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
664
 
    
 
729
_default_format_by_weekday_num = [wd + " %Y-%m-%d %H:%M:%S" for wd in weekdays]
 
730
 
 
731
 
665
732
def format_date(t, offset=0, timezone='original', date_fmt=None,
666
733
                show_offset=True):
667
734
    """Return a formatted date string.
671
738
    :param timezone: How to display the time: 'utc', 'original' for the
672
739
         timezone specified by offset, or 'local' for the process's current
673
740
         timezone.
674
 
    :param show_offset: Whether to append the timezone.
675
 
    :param date_fmt: strftime format.
676
 
    """
 
741
    :param date_fmt: strftime format.
 
742
    :param show_offset: Whether to append the timezone.
 
743
    """
 
744
    (date_fmt, tt, offset_str) = \
 
745
               _format_date(t, offset, timezone, date_fmt, show_offset)
 
746
    date_fmt = date_fmt.replace('%a', weekdays[tt[6]])
 
747
    date_str = time.strftime(date_fmt, tt)
 
748
    return date_str + offset_str
 
749
 
 
750
 
 
751
# Cache of formatted offset strings
 
752
_offset_cache = {}
 
753
 
 
754
 
 
755
def format_date_with_offset_in_original_timezone(t, offset=0,
 
756
    _cache=_offset_cache):
 
757
    """Return a formatted date string in the original timezone.
 
758
 
 
759
    This routine may be faster then format_date.
 
760
 
 
761
    :param t: Seconds since the epoch.
 
762
    :param offset: Timezone offset in seconds east of utc.
 
763
    """
 
764
    if offset is None:
 
765
        offset = 0
 
766
    tt = time.gmtime(t + offset)
 
767
    date_fmt = _default_format_by_weekday_num[tt[6]]
 
768
    date_str = time.strftime(date_fmt, tt)
 
769
    offset_str = _cache.get(offset, None)
 
770
    if offset_str is None:
 
771
        offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
 
772
        _cache[offset] = offset_str
 
773
    return date_str + offset_str
 
774
 
 
775
 
 
776
def format_local_date(t, offset=0, timezone='original', date_fmt=None,
 
777
                      show_offset=True):
 
778
    """Return an unicode date string formatted according to the current locale.
 
779
 
 
780
    :param t: Seconds since the epoch.
 
781
    :param offset: Timezone offset in seconds east of utc.
 
782
    :param timezone: How to display the time: 'utc', 'original' for the
 
783
         timezone specified by offset, or 'local' for the process's current
 
784
         timezone.
 
785
    :param date_fmt: strftime format.
 
786
    :param show_offset: Whether to append the timezone.
 
787
    """
 
788
    (date_fmt, tt, offset_str) = \
 
789
               _format_date(t, offset, timezone, date_fmt, show_offset)
 
790
    date_str = time.strftime(date_fmt, tt)
 
791
    if not isinstance(date_str, unicode):
 
792
        date_str = date_str.decode(get_user_encoding(), 'replace')
 
793
    return date_str + offset_str
 
794
 
 
795
 
 
796
def _format_date(t, offset, timezone, date_fmt, show_offset):
677
797
    if timezone == 'utc':
678
798
        tt = time.gmtime(t)
679
799
        offset = 0
692
812
        offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
693
813
    else:
694
814
        offset_str = ''
695
 
    # day of week depends on locale, so we do this ourself
696
 
    date_fmt = date_fmt.replace('%a', weekdays[tt[6]])
697
 
    return (time.strftime(date_fmt, tt) +  offset_str)
 
815
    return (date_fmt, tt, offset_str)
698
816
 
699
817
 
700
818
def compact_date(when):
701
819
    return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
702
 
    
 
820
 
703
821
 
704
822
def format_delta(delta):
705
823
    """Get a nice looking string for a time delta.
752
870
 
753
871
def filesize(f):
754
872
    """Return size of given open file."""
755
 
    return os.fstat(f.fileno())[ST_SIZE]
 
873
    return os.fstat(f.fileno())[stat.ST_SIZE]
756
874
 
757
875
 
758
876
# Define rand_bytes based on platform.
781
899
ALNUM = '0123456789abcdefghijklmnopqrstuvwxyz'
782
900
def rand_chars(num):
783
901
    """Return a random string of num alphanumeric characters
784
 
    
785
 
    The result only contains lowercase chars because it may be used on 
 
902
 
 
903
    The result only contains lowercase chars because it may be used on
786
904
    case-insensitive filesystems.
787
905
    """
788
906
    s = ''
810
928
            rps.append(f)
811
929
    return rps
812
930
 
 
931
 
813
932
def joinpath(p):
814
933
    for f in p:
815
934
        if (f == '..') or (f is None) or (f == ''):
817
936
    return pathjoin(*p)
818
937
 
819
938
 
 
939
def parent_directories(filename):
 
940
    """Return the list of parent directories, deepest first.
 
941
 
 
942
    For example, parent_directories("a/b/c") -> ["a/b", "a"].
 
943
    """
 
944
    parents = []
 
945
    parts = splitpath(dirname(filename))
 
946
    while parts:
 
947
        parents.append(joinpath(parts))
 
948
        parts.pop()
 
949
    return parents
 
950
 
 
951
 
 
952
_extension_load_failures = []
 
953
 
 
954
 
 
955
def failed_to_load_extension(exception):
 
956
    """Handle failing to load a binary extension.
 
957
 
 
958
    This should be called from the ImportError block guarding the attempt to
 
959
    import the native extension.  If this function returns, the pure-Python
 
960
    implementation should be loaded instead::
 
961
 
 
962
    >>> try:
 
963
    >>>     import bzrlib._fictional_extension_pyx
 
964
    >>> except ImportError, e:
 
965
    >>>     bzrlib.osutils.failed_to_load_extension(e)
 
966
    >>>     import bzrlib._fictional_extension_py
 
967
    """
 
968
    # NB: This docstring is just an example, not a doctest, because doctest
 
969
    # currently can't cope with the use of lazy imports in this namespace --
 
970
    # mbp 20090729
 
971
 
 
972
    # This currently doesn't report the failure at the time it occurs, because
 
973
    # they tend to happen very early in startup when we can't check config
 
974
    # files etc, and also we want to report all failures but not spam the user
 
975
    # with 10 warnings.
 
976
    exception_str = str(exception)
 
977
    if exception_str not in _extension_load_failures:
 
978
        trace.mutter("failed to load compiled extension: %s" % exception_str)
 
979
        _extension_load_failures.append(exception_str)
 
980
 
 
981
 
 
982
def report_extension_load_failures():
 
983
    if not _extension_load_failures:
 
984
        return
 
985
    from bzrlib.config import GlobalConfig
 
986
    if GlobalConfig().get_user_option_as_bool('ignore_missing_extensions'):
 
987
        return
 
988
    # the warnings framework should by default show this only once
 
989
    from bzrlib.trace import warning
 
990
    warning(
 
991
        "bzr: warning: some compiled extensions could not be loaded; "
 
992
        "see <https://answers.launchpad.net/bzr/+faq/703>")
 
993
    # we no longer show the specific missing extensions here, because it makes
 
994
    # the message too long and scary - see
 
995
    # https://bugs.launchpad.net/bzr/+bug/430529
 
996
 
 
997
 
 
998
try:
 
999
    from bzrlib._chunks_to_lines_pyx import chunks_to_lines
 
1000
except ImportError, e:
 
1001
    failed_to_load_extension(e)
 
1002
    from bzrlib._chunks_to_lines_py import chunks_to_lines
 
1003
 
 
1004
 
820
1005
def split_lines(s):
821
1006
    """Split s into lines, but without removing the newline characters."""
 
1007
    # Trivially convert a fulltext into a 'chunked' representation, and let
 
1008
    # chunks_to_lines do the heavy lifting.
 
1009
    if isinstance(s, str):
 
1010
        # chunks_to_lines only supports 8-bit strings
 
1011
        return chunks_to_lines([s])
 
1012
    else:
 
1013
        return _split_lines(s)
 
1014
 
 
1015
 
 
1016
def _split_lines(s):
 
1017
    """Split s into lines, but without removing the newline characters.
 
1018
 
 
1019
    This supports Unicode or plain string objects.
 
1020
    """
822
1021
    lines = s.split('\n')
823
1022
    result = [line + '\n' for line in lines[:-1]]
824
1023
    if lines[-1]:
843
1042
        shutil.copyfile(src, dest)
844
1043
 
845
1044
 
846
 
# Look Before You Leap (LBYL) is appropriate here instead of Easier to Ask for
847
 
# Forgiveness than Permission (EAFP) because:
848
 
# - root can damage a solaris file system by using unlink,
849
 
# - unlink raises different exceptions on different OSes (linux: EISDIR, win32:
850
 
#   EACCES, OSX: EPERM) when invoked on a directory.
851
1045
def delete_any(path):
852
 
    """Delete a file or directory."""
 
1046
    """Delete a file, symlink or directory.
 
1047
 
 
1048
    Will delete even if readonly.
 
1049
    """
 
1050
    try:
 
1051
       _delete_file_or_dir(path)
 
1052
    except (OSError, IOError), e:
 
1053
        if e.errno in (errno.EPERM, errno.EACCES):
 
1054
            # make writable and try again
 
1055
            try:
 
1056
                make_writable(path)
 
1057
            except (OSError, IOError):
 
1058
                pass
 
1059
            _delete_file_or_dir(path)
 
1060
        else:
 
1061
            raise
 
1062
 
 
1063
 
 
1064
def _delete_file_or_dir(path):
 
1065
    # Look Before You Leap (LBYL) is appropriate here instead of Easier to Ask for
 
1066
    # Forgiveness than Permission (EAFP) because:
 
1067
    # - root can damage a solaris file system by using unlink,
 
1068
    # - unlink raises different exceptions on different OSes (linux: EISDIR, win32:
 
1069
    #   EACCES, OSX: EPERM) when invoked on a directory.
853
1070
    if isdir(path): # Takes care of symlinks
854
1071
        os.rmdir(path)
855
1072
    else:
875
1092
            and sys.platform not in ('cygwin', 'win32'))
876
1093
 
877
1094
 
 
1095
def readlink(abspath):
 
1096
    """Return a string representing the path to which the symbolic link points.
 
1097
 
 
1098
    :param abspath: The link absolute unicode path.
 
1099
 
 
1100
    This his guaranteed to return the symbolic link in unicode in all python
 
1101
    versions.
 
1102
    """
 
1103
    link = abspath.encode(_fs_enc)
 
1104
    target = os.readlink(link)
 
1105
    target = target.decode(_fs_enc)
 
1106
    return target
 
1107
 
 
1108
 
878
1109
def contains_whitespace(s):
879
1110
    """True if there are any whitespace characters in s."""
880
1111
    # string.whitespace can include '\xa0' in certain locales, because it is
905
1136
 
906
1137
 
907
1138
def relpath(base, path):
908
 
    """Return path relative to base, or raise exception.
 
1139
    """Return path relative to base, or raise PathNotChild exception.
909
1140
 
910
1141
    The path may be either an absolute path or a path relative to the
911
1142
    current working directory.
913
1144
    os.path.commonprefix (python2.4) has a bad bug that it works just
914
1145
    on string prefixes, assuming that '/u' is a prefix of '/u2'.  This
915
1146
    avoids that problem.
 
1147
 
 
1148
    NOTE: `base` should not have a trailing slash otherwise you'll get
 
1149
    PathNotChild exceptions regardless of `path`.
916
1150
    """
917
1151
 
918
1152
    if len(base) < MIN_ABS_PATHLENGTH:
924
1158
 
925
1159
    s = []
926
1160
    head = rp
927
 
    while len(head) >= len(base):
 
1161
    while True:
 
1162
        if len(head) <= len(base) and head != base:
 
1163
            raise errors.PathNotChild(rp, base)
928
1164
        if head == base:
929
1165
            break
930
 
        head, tail = os.path.split(head)
 
1166
        head, tail = split(head)
931
1167
        if tail:
932
 
            s.insert(0, tail)
933
 
    else:
934
 
        raise errors.PathNotChild(rp, base)
 
1168
            s.append(tail)
935
1169
 
936
1170
    if s:
937
 
        return pathjoin(*s)
 
1171
        return pathjoin(*reversed(s))
938
1172
    else:
939
1173
        return ''
940
1174
 
941
1175
 
 
1176
def _cicp_canonical_relpath(base, path):
 
1177
    """Return the canonical path relative to base.
 
1178
 
 
1179
    Like relpath, but on case-insensitive-case-preserving file-systems, this
 
1180
    will return the relpath as stored on the file-system rather than in the
 
1181
    case specified in the input string, for all existing portions of the path.
 
1182
 
 
1183
    This will cause O(N) behaviour if called for every path in a tree; if you
 
1184
    have a number of paths to convert, you should use canonical_relpaths().
 
1185
    """
 
1186
    # TODO: it should be possible to optimize this for Windows by using the
 
1187
    # win32 API FindFiles function to look for the specified name - but using
 
1188
    # os.listdir() still gives us the correct, platform agnostic semantics in
 
1189
    # the short term.
 
1190
 
 
1191
    rel = relpath(base, path)
 
1192
    # '.' will have been turned into ''
 
1193
    if not rel:
 
1194
        return rel
 
1195
 
 
1196
    abs_base = abspath(base)
 
1197
    current = abs_base
 
1198
    _listdir = os.listdir
 
1199
 
 
1200
    # use an explicit iterator so we can easily consume the rest on early exit.
 
1201
    bit_iter = iter(rel.split('/'))
 
1202
    for bit in bit_iter:
 
1203
        lbit = bit.lower()
 
1204
        try:
 
1205
            next_entries = _listdir(current)
 
1206
        except OSError: # enoent, eperm, etc
 
1207
            # We can't find this in the filesystem, so just append the
 
1208
            # remaining bits.
 
1209
            current = pathjoin(current, bit, *list(bit_iter))
 
1210
            break
 
1211
        for look in next_entries:
 
1212
            if lbit == look.lower():
 
1213
                current = pathjoin(current, look)
 
1214
                break
 
1215
        else:
 
1216
            # got to the end, nothing matched, so we just return the
 
1217
            # non-existing bits as they were specified (the filename may be
 
1218
            # the target of a move, for example).
 
1219
            current = pathjoin(current, bit, *list(bit_iter))
 
1220
            break
 
1221
    return current[len(abs_base):].lstrip('/')
 
1222
 
 
1223
# XXX - TODO - we need better detection/integration of case-insensitive
 
1224
# file-systems; Linux often sees FAT32 devices (or NFS-mounted OSX
 
1225
# filesystems), for example, so could probably benefit from the same basic
 
1226
# support there.  For now though, only Windows and OSX get that support, and
 
1227
# they get it for *all* file-systems!
 
1228
if sys.platform in ('win32', 'darwin'):
 
1229
    canonical_relpath = _cicp_canonical_relpath
 
1230
else:
 
1231
    canonical_relpath = relpath
 
1232
 
 
1233
def canonical_relpaths(base, paths):
 
1234
    """Create an iterable to canonicalize a sequence of relative paths.
 
1235
 
 
1236
    The intent is for this implementation to use a cache, vastly speeding
 
1237
    up multiple transformations in the same directory.
 
1238
    """
 
1239
    # but for now, we haven't optimized...
 
1240
    return [canonical_relpath(base, p) for p in paths]
 
1241
 
 
1242
 
 
1243
def decode_filename(filename):
 
1244
    """Decode the filename using the filesystem encoding
 
1245
 
 
1246
    If it is unicode, it is returned.
 
1247
    Otherwise it is decoded from the the filesystem's encoding. If decoding
 
1248
    fails, a errors.BadFilenameEncoding exception is raised.
 
1249
    """
 
1250
    if type(filename) is unicode:
 
1251
        return filename
 
1252
    try:
 
1253
        return filename.decode(_fs_enc)
 
1254
    except UnicodeDecodeError:
 
1255
        raise errors.BadFilenameEncoding(filename, _fs_enc)
 
1256
 
 
1257
 
942
1258
def safe_unicode(unicode_or_utf8_string):
943
1259
    """Coerce unicode_or_utf8_string into unicode.
944
1260
 
945
1261
    If it is unicode, it is returned.
946
 
    Otherwise it is decoded from utf-8. If a decoding error
947
 
    occurs, it is wrapped as a If the decoding fails, the exception is wrapped 
948
 
    as a BzrBadParameter exception.
 
1262
    Otherwise it is decoded from utf-8. If decoding fails, the exception is
 
1263
    wrapped in a BzrBadParameterNotUnicode exception.
949
1264
    """
950
1265
    if isinstance(unicode_or_utf8_string, unicode):
951
1266
        return unicode_or_utf8_string
1028
1343
def normalizes_filenames():
1029
1344
    """Return True if this platform normalizes unicode filenames.
1030
1345
 
1031
 
    Mac OSX does, Windows/Linux do not.
 
1346
    Only Mac OSX.
1032
1347
    """
1033
1348
    return _platform_normalizes_filenames
1034
1349
 
1038
1353
 
1039
1354
    On platforms where the system normalizes filenames (Mac OSX),
1040
1355
    you can access a file by any path which will normalize correctly.
1041
 
    On platforms where the system does not normalize filenames 
1042
 
    (Windows, Linux), you have to access a file by its exact path.
 
1356
    On platforms where the system does not normalize filenames
 
1357
    (everything else), you have to access a file by its exact path.
1043
1358
 
1044
 
    Internally, bzr only supports NFC normalization, since that is 
 
1359
    Internally, bzr only supports NFC normalization, since that is
1045
1360
    the standard for XML documents.
1046
1361
 
1047
1362
    So return the normalized path, and a flag indicating if the file
1064
1379
    normalized_filename = _inaccessible_normalized_filename
1065
1380
 
1066
1381
 
 
1382
def set_signal_handler(signum, handler, restart_syscall=True):
 
1383
    """A wrapper for signal.signal that also calls siginterrupt(signum, False)
 
1384
    on platforms that support that.
 
1385
 
 
1386
    :param restart_syscall: if set, allow syscalls interrupted by a signal to
 
1387
        automatically restart (by calling `signal.siginterrupt(signum,
 
1388
        False)`).  May be ignored if the feature is not available on this
 
1389
        platform or Python version.
 
1390
    """
 
1391
    try:
 
1392
        import signal
 
1393
        siginterrupt = signal.siginterrupt
 
1394
    except ImportError:
 
1395
        # This python implementation doesn't provide signal support, hence no
 
1396
        # handler exists
 
1397
        return None
 
1398
    except AttributeError:
 
1399
        # siginterrupt doesn't exist on this platform, or for this version
 
1400
        # of Python.
 
1401
        siginterrupt = lambda signum, flag: None
 
1402
    if restart_syscall:
 
1403
        def sig_handler(*args):
 
1404
            # Python resets the siginterrupt flag when a signal is
 
1405
            # received.  <http://bugs.python.org/issue8354>
 
1406
            # As a workaround for some cases, set it back the way we want it.
 
1407
            siginterrupt(signum, False)
 
1408
            # Now run the handler function passed to set_signal_handler.
 
1409
            handler(*args)
 
1410
    else:
 
1411
        sig_handler = handler
 
1412
    old_handler = signal.signal(signum, sig_handler)
 
1413
    if restart_syscall:
 
1414
        siginterrupt(signum, False)
 
1415
    return old_handler
 
1416
 
 
1417
 
 
1418
default_terminal_width = 80
 
1419
"""The default terminal width for ttys.
 
1420
 
 
1421
This is defined so that higher levels can share a common fallback value when
 
1422
terminal_width() returns None.
 
1423
"""
 
1424
 
 
1425
# Keep some state so that terminal_width can detect if _terminal_size has
 
1426
# returned a different size since the process started.  See docstring and
 
1427
# comments of terminal_width for details.
 
1428
# _terminal_size_state has 3 possible values: no_data, unchanged, and changed.
 
1429
_terminal_size_state = 'no_data'
 
1430
_first_terminal_size = None
 
1431
 
1067
1432
def terminal_width():
1068
 
    """Return estimated terminal width."""
1069
 
    if sys.platform == 'win32':
1070
 
        return win32utils.get_console_size()[0]
1071
 
    width = 0
 
1433
    """Return terminal width.
 
1434
 
 
1435
    None is returned if the width can't established precisely.
 
1436
 
 
1437
    The rules are:
 
1438
    - if BZR_COLUMNS is set, returns its value
 
1439
    - if there is no controlling terminal, returns None
 
1440
    - query the OS, if the queried size has changed since the last query,
 
1441
      return its value,
 
1442
    - if COLUMNS is set, returns its value,
 
1443
    - if the OS has a value (even though it's never changed), return its value.
 
1444
 
 
1445
    From there, we need to query the OS to get the size of the controlling
 
1446
    terminal.
 
1447
 
 
1448
    On Unices we query the OS by:
 
1449
    - get termios.TIOCGWINSZ
 
1450
    - if an error occurs or a negative value is obtained, returns None
 
1451
 
 
1452
    On Windows we query the OS by:
 
1453
    - win32utils.get_console_size() decides,
 
1454
    - returns None on error (provided default value)
 
1455
    """
 
1456
    # Note to implementors: if changing the rules for determining the width,
 
1457
    # make sure you've considered the behaviour in these cases:
 
1458
    #  - M-x shell in emacs, where $COLUMNS is set and TIOCGWINSZ returns 0,0.
 
1459
    #  - bzr log | less, in bash, where $COLUMNS not set and TIOCGWINSZ returns
 
1460
    #    0,0.
 
1461
    #  - (add more interesting cases here, if you find any)
 
1462
    # Some programs implement "Use $COLUMNS (if set) until SIGWINCH occurs",
 
1463
    # but we don't want to register a signal handler because it is impossible
 
1464
    # to do so without risking EINTR errors in Python <= 2.6.5 (see
 
1465
    # <http://bugs.python.org/issue8354>).  Instead we check TIOCGWINSZ every
 
1466
    # time so we can notice if the reported size has changed, which should have
 
1467
    # a similar effect.
 
1468
 
 
1469
    # If BZR_COLUMNS is set, take it, user is always right
 
1470
    # Except if they specified 0 in which case, impose no limit here
 
1471
    try:
 
1472
        width = int(os.environ['BZR_COLUMNS'])
 
1473
    except (KeyError, ValueError):
 
1474
        width = None
 
1475
    if width is not None:
 
1476
        if width > 0:
 
1477
            return width
 
1478
        else:
 
1479
            return None
 
1480
 
 
1481
    isatty = getattr(sys.stdout, 'isatty', None)
 
1482
    if isatty is None or not isatty():
 
1483
        # Don't guess, setting BZR_COLUMNS is the recommended way to override.
 
1484
        return None
 
1485
 
 
1486
    # Query the OS
 
1487
    width, height = os_size = _terminal_size(None, None)
 
1488
    global _first_terminal_size, _terminal_size_state
 
1489
    if _terminal_size_state == 'no_data':
 
1490
        _first_terminal_size = os_size
 
1491
        _terminal_size_state = 'unchanged'
 
1492
    elif (_terminal_size_state == 'unchanged' and
 
1493
          _first_terminal_size != os_size):
 
1494
        _terminal_size_state = 'changed'
 
1495
 
 
1496
    # If the OS claims to know how wide the terminal is, and this value has
 
1497
    # ever changed, use that.
 
1498
    if _terminal_size_state == 'changed':
 
1499
        if width is not None and width > 0:
 
1500
            return width
 
1501
 
 
1502
    # If COLUMNS is set, use it.
 
1503
    try:
 
1504
        return int(os.environ['COLUMNS'])
 
1505
    except (KeyError, ValueError):
 
1506
        pass
 
1507
 
 
1508
    # Finally, use an unchanged size from the OS, if we have one.
 
1509
    if _terminal_size_state == 'unchanged':
 
1510
        if width is not None and width > 0:
 
1511
            return width
 
1512
 
 
1513
    # The width could not be determined.
 
1514
    return None
 
1515
 
 
1516
 
 
1517
def _win32_terminal_size(width, height):
 
1518
    width, height = win32utils.get_console_size(defaultx=width, defaulty=height)
 
1519
    return width, height
 
1520
 
 
1521
 
 
1522
def _ioctl_terminal_size(width, height):
1072
1523
    try:
1073
1524
        import struct, fcntl, termios
1074
1525
        s = struct.pack('HHHH', 0, 0, 0, 0)
1075
1526
        x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
1076
 
        width = struct.unpack('HHHH', x)[1]
1077
 
    except IOError:
 
1527
        height, width = struct.unpack('HHHH', x)[0:2]
 
1528
    except (IOError, AttributeError):
1078
1529
        pass
1079
 
    if width <= 0:
1080
 
        try:
1081
 
            width = int(os.environ['COLUMNS'])
1082
 
        except:
1083
 
            pass
1084
 
    if width <= 0:
1085
 
        width = 80
1086
 
 
1087
 
    return width
 
1530
    return width, height
 
1531
 
 
1532
_terminal_size = None
 
1533
"""Returns the terminal size as (width, height).
 
1534
 
 
1535
:param width: Default value for width.
 
1536
:param height: Default value for height.
 
1537
 
 
1538
This is defined specifically for each OS and query the size of the controlling
 
1539
terminal. If any error occurs, the provided default values should be returned.
 
1540
"""
 
1541
if sys.platform == 'win32':
 
1542
    _terminal_size = _win32_terminal_size
 
1543
else:
 
1544
    _terminal_size = _ioctl_terminal_size
1088
1545
 
1089
1546
 
1090
1547
def supports_executable():
1118
1575
            del os.environ[env_variable]
1119
1576
    else:
1120
1577
        if isinstance(value, unicode):
1121
 
            value = value.encode(bzrlib.user_encoding)
 
1578
            value = value.encode(get_user_encoding())
1122
1579
        os.environ[env_variable] = value
1123
1580
    return orig_val
1124
1581
 
1127
1584
 
1128
1585
 
1129
1586
def check_legal_path(path):
1130
 
    """Check whether the supplied path is legal.  
 
1587
    """Check whether the supplied path is legal.
1131
1588
    This is only required on Windows, so we don't test on other platforms
1132
1589
    right now.
1133
1590
    """
1167
1624
 
1168
1625
def walkdirs(top, prefix=""):
1169
1626
    """Yield data about all the directories in a tree.
1170
 
    
 
1627
 
1171
1628
    This yields all the data about the contents of a directory at a time.
1172
1629
    After each directory has been yielded, if the caller has mutated the list
1173
1630
    to exclude some directories, they are then not descended into.
1174
 
    
 
1631
 
1175
1632
    The data yielded is of the form:
1176
1633
    ((directory-relpath, directory-path-from-top),
1177
1634
    [(relpath, basename, kind, lstat, path-from-top), ...]),
1178
1635
     - directory-relpath is the relative path of the directory being returned
1179
1636
       with respect to top. prefix is prepended to this.
1180
 
     - directory-path-from-root is the path including top for this directory. 
 
1637
     - directory-path-from-root is the path including top for this directory.
1181
1638
       It is suitable for use with os functions.
1182
1639
     - relpath is the relative path within the subtree being walked.
1183
1640
     - basename is the basename of the path
1185
1642
       present within the tree - but it may be recorded as versioned. See
1186
1643
       versioned_kind.
1187
1644
     - lstat is the stat data *if* the file was statted.
1188
 
     - planned, not implemented: 
 
1645
     - planned, not implemented:
1189
1646
       path_from_tree_root is the path from the root of the tree.
1190
1647
 
1191
 
    :param prefix: Prefix the relpaths that are yielded with 'prefix'. This 
 
1648
    :param prefix: Prefix the relpaths that are yielded with 'prefix'. This
1192
1649
        allows one to walk a subtree but get paths that are relative to a tree
1193
1650
        rooted higher up.
1194
1651
    :return: an iterator over the dirs.
1195
1652
    """
1196
1653
    #TODO there is a bit of a smell where the results of the directory-
1197
 
    # summary in this, and the path from the root, may not agree 
 
1654
    # summary in this, and the path from the root, may not agree
1198
1655
    # depending on top and prefix - i.e. ./foo and foo as a pair leads to
1199
1656
    # potentially confusing output. We should make this more robust - but
1200
1657
    # not at a speed cost. RBC 20060731
1201
1658
    _lstat = os.lstat
1202
1659
    _directory = _directory_kind
1203
1660
    _listdir = os.listdir
1204
 
    _kind_from_mode = _formats.get
 
1661
    _kind_from_mode = file_kind_from_stat_mode
1205
1662
    pending = [(safe_unicode(prefix), "", _directory, None, safe_unicode(top))]
1206
1663
    while pending:
1207
1664
        # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1215
1672
        dirblock = []
1216
1673
        append = dirblock.append
1217
1674
        try:
1218
 
            names = sorted(_listdir(top))
 
1675
            names = sorted(map(decode_filename, _listdir(top)))
1219
1676
        except OSError, e:
1220
1677
            if not _is_error_enotdir(e):
1221
1678
                raise
1223
1680
            for name in names:
1224
1681
                abspath = top_slash + name
1225
1682
                statvalue = _lstat(abspath)
1226
 
                kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
 
1683
                kind = _kind_from_mode(statvalue.st_mode)
1227
1684
                append((relprefix + name, name, kind, statvalue, abspath))
1228
1685
        yield (relroot, top), dirblock
1229
1686
 
1231
1688
        pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1232
1689
 
1233
1690
 
1234
 
_real_walkdirs_utf8 = None
 
1691
class DirReader(object):
 
1692
    """An interface for reading directories."""
 
1693
 
 
1694
    def top_prefix_to_starting_dir(self, top, prefix=""):
 
1695
        """Converts top and prefix to a starting dir entry
 
1696
 
 
1697
        :param top: A utf8 path
 
1698
        :param prefix: An optional utf8 path to prefix output relative paths
 
1699
            with.
 
1700
        :return: A tuple starting with prefix, and ending with the native
 
1701
            encoding of top.
 
1702
        """
 
1703
        raise NotImplementedError(self.top_prefix_to_starting_dir)
 
1704
 
 
1705
    def read_dir(self, prefix, top):
 
1706
        """Read a specific dir.
 
1707
 
 
1708
        :param prefix: A utf8 prefix to be preprended to the path basenames.
 
1709
        :param top: A natively encoded path to read.
 
1710
        :return: A list of the directories contents. Each item contains:
 
1711
            (utf8_relpath, utf8_name, kind, lstatvalue, native_abspath)
 
1712
        """
 
1713
        raise NotImplementedError(self.read_dir)
 
1714
 
 
1715
 
 
1716
_selected_dir_reader = None
 
1717
 
1235
1718
 
1236
1719
def _walkdirs_utf8(top, prefix=""):
1237
1720
    """Yield data about all the directories in a tree.
1247
1730
        path-from-top might be unicode or utf8, but it is the correct path to
1248
1731
        pass to os functions to affect the file in question. (such as os.lstat)
1249
1732
    """
1250
 
    global _real_walkdirs_utf8
1251
 
    if _real_walkdirs_utf8 is None:
 
1733
    global _selected_dir_reader
 
1734
    if _selected_dir_reader is None:
1252
1735
        fs_encoding = _fs_enc.upper()
1253
 
        if win32utils.winver == 'Windows NT':
 
1736
        if sys.platform == "win32" and win32utils.winver == 'Windows NT':
1254
1737
            # Win98 doesn't have unicode apis like FindFirstFileW
1255
1738
            # TODO: We possibly could support Win98 by falling back to the
1256
1739
            #       original FindFirstFile, and using TCHAR instead of WCHAR,
1257
1740
            #       but that gets a bit tricky, and requires custom compiling
1258
1741
            #       for win98 anyway.
1259
1742
            try:
1260
 
                from bzrlib._walkdirs_win32 import _walkdirs_utf8_win32_find_file
 
1743
                from bzrlib._walkdirs_win32 import Win32ReadDir
 
1744
                _selected_dir_reader = Win32ReadDir()
1261
1745
            except ImportError:
1262
 
                _real_walkdirs_utf8 = _walkdirs_unicode_to_utf8
1263
 
            else:
1264
 
                _real_walkdirs_utf8 = _walkdirs_utf8_win32_find_file
1265
 
        elif fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
 
1746
                pass
 
1747
        elif fs_encoding in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
1266
1748
            # ANSI_X3.4-1968 is a form of ASCII
1267
 
            _real_walkdirs_utf8 = _walkdirs_unicode_to_utf8
1268
 
        else:
1269
 
            _real_walkdirs_utf8 = _walkdirs_fs_utf8
1270
 
    return _real_walkdirs_utf8(top, prefix=prefix)
1271
 
 
1272
 
 
1273
 
def _walkdirs_fs_utf8(top, prefix=""):
1274
 
    """See _walkdirs_utf8.
1275
 
 
1276
 
    This sub-function is called when we know the filesystem is already in utf8
1277
 
    encoding. So we don't need to transcode filenames.
1278
 
    """
1279
 
    _lstat = os.lstat
1280
 
    _directory = _directory_kind
1281
 
    # Use C accelerated directory listing.
1282
 
    _listdir = _read_dir
1283
 
    _kind_from_mode = _formats.get
 
1749
            try:
 
1750
                from bzrlib._readdir_pyx import UTF8DirReader
 
1751
                _selected_dir_reader = UTF8DirReader()
 
1752
            except ImportError, e:
 
1753
                failed_to_load_extension(e)
 
1754
                pass
 
1755
 
 
1756
    if _selected_dir_reader is None:
 
1757
        # Fallback to the python version
 
1758
        _selected_dir_reader = UnicodeDirReader()
1284
1759
 
1285
1760
    # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1286
1761
    # But we don't actually uses 1-3 in pending, so set them to None
1287
 
    pending = [(safe_utf8(prefix), None, None, None, safe_utf8(top))]
 
1762
    pending = [[_selected_dir_reader.top_prefix_to_starting_dir(top, prefix)]]
 
1763
    read_dir = _selected_dir_reader.read_dir
 
1764
    _directory = _directory_kind
1288
1765
    while pending:
1289
 
        relroot, _, _, _, top = pending.pop()
1290
 
        if relroot:
1291
 
            relprefix = relroot + '/'
1292
 
        else:
1293
 
            relprefix = ''
1294
 
        top_slash = top + '/'
1295
 
 
1296
 
        dirblock = []
1297
 
        append = dirblock.append
1298
 
        # read_dir supplies in should-stat order.
1299
 
        for _, name in sorted(_listdir(top)):
1300
 
            abspath = top_slash + name
1301
 
            statvalue = _lstat(abspath)
1302
 
            kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
1303
 
            append((relprefix + name, name, kind, statvalue, abspath))
1304
 
        dirblock.sort()
 
1766
        relroot, _, _, _, top = pending[-1].pop()
 
1767
        if not pending[-1]:
 
1768
            pending.pop()
 
1769
        dirblock = sorted(read_dir(relroot, top))
1305
1770
        yield (relroot, top), dirblock
1306
 
 
1307
1771
        # push the user specified dirs from dirblock
1308
 
        pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1309
 
 
1310
 
 
1311
 
def _walkdirs_unicode_to_utf8(top, prefix=""):
1312
 
    """See _walkdirs_utf8
1313
 
 
1314
 
    Because Win32 has a Unicode api, all of the 'path-from-top' entries will be
1315
 
    Unicode paths.
1316
 
    This is currently the fallback code path when the filesystem encoding is
1317
 
    not UTF-8. It may be better to implement an alternative so that we can
1318
 
    safely handle paths that are not properly decodable in the current
1319
 
    encoding.
1320
 
    """
1321
 
    _utf8_encode = codecs.getencoder('utf8')
1322
 
    _lstat = os.lstat
1323
 
    _directory = _directory_kind
1324
 
    _listdir = os.listdir
1325
 
    _kind_from_mode = _formats.get
1326
 
 
1327
 
    pending = [(safe_utf8(prefix), None, None, None, safe_unicode(top))]
1328
 
    while pending:
1329
 
        relroot, _, _, _, top = pending.pop()
1330
 
        if relroot:
1331
 
            relprefix = relroot + '/'
 
1772
        next = [d for d in reversed(dirblock) if d[2] == _directory]
 
1773
        if next:
 
1774
            pending.append(next)
 
1775
 
 
1776
 
 
1777
class UnicodeDirReader(DirReader):
 
1778
    """A dir reader for non-utf8 file systems, which transcodes."""
 
1779
 
 
1780
    __slots__ = ['_utf8_encode']
 
1781
 
 
1782
    def __init__(self):
 
1783
        self._utf8_encode = codecs.getencoder('utf8')
 
1784
 
 
1785
    def top_prefix_to_starting_dir(self, top, prefix=""):
 
1786
        """See DirReader.top_prefix_to_starting_dir."""
 
1787
        return (safe_utf8(prefix), None, None, None, safe_unicode(top))
 
1788
 
 
1789
    def read_dir(self, prefix, top):
 
1790
        """Read a single directory from a non-utf8 file system.
 
1791
 
 
1792
        top, and the abspath element in the output are unicode, all other paths
 
1793
        are utf8. Local disk IO is done via unicode calls to listdir etc.
 
1794
 
 
1795
        This is currently the fallback code path when the filesystem encoding is
 
1796
        not UTF-8. It may be better to implement an alternative so that we can
 
1797
        safely handle paths that are not properly decodable in the current
 
1798
        encoding.
 
1799
 
 
1800
        See DirReader.read_dir for details.
 
1801
        """
 
1802
        _utf8_encode = self._utf8_encode
 
1803
        _lstat = os.lstat
 
1804
        _listdir = os.listdir
 
1805
        _kind_from_mode = file_kind_from_stat_mode
 
1806
 
 
1807
        if prefix:
 
1808
            relprefix = prefix + '/'
1332
1809
        else:
1333
1810
            relprefix = ''
1334
1811
        top_slash = top + u'/'
1336
1813
        dirblock = []
1337
1814
        append = dirblock.append
1338
1815
        for name in sorted(_listdir(top)):
1339
 
            name_utf8 = _utf8_encode(name)[0]
 
1816
            try:
 
1817
                name_utf8 = _utf8_encode(name)[0]
 
1818
            except UnicodeDecodeError:
 
1819
                raise errors.BadFilenameEncoding(
 
1820
                    _utf8_encode(relprefix)[0] + name, _fs_enc)
1340
1821
            abspath = top_slash + name
1341
1822
            statvalue = _lstat(abspath)
1342
 
            kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
 
1823
            kind = _kind_from_mode(statvalue.st_mode)
1343
1824
            append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
1344
 
        yield (relroot, top), dirblock
1345
 
 
1346
 
        # push the user specified dirs from dirblock
1347
 
        pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
 
1825
        return dirblock
1348
1826
 
1349
1827
 
1350
1828
def copy_tree(from_path, to_path, handlers={}):
1351
1829
    """Copy all of the entries in from_path into to_path.
1352
1830
 
1353
 
    :param from_path: The base directory to copy. 
 
1831
    :param from_path: The base directory to copy.
1354
1832
    :param to_path: The target directory. If it does not exist, it will
1355
1833
        be created.
1356
1834
    :param handlers: A dictionary of functions, which takes a source and
1389
1867
            real_handlers[kind](abspath, relpath)
1390
1868
 
1391
1869
 
 
1870
def copy_ownership_from_path(dst, src=None):
 
1871
    """Copy usr/grp ownership from src file/dir to dst file/dir.
 
1872
 
 
1873
    If src is None, the containing directory is used as source. If chown
 
1874
    fails, the error is ignored and a warning is printed.
 
1875
    """
 
1876
    chown = getattr(os, 'chown', None)
 
1877
    if chown is None:
 
1878
        return
 
1879
 
 
1880
    if src == None:
 
1881
        src = os.path.dirname(dst)
 
1882
        if src == '':
 
1883
            src = '.'
 
1884
 
 
1885
    try:
 
1886
        s = os.stat(src)
 
1887
        chown(dst, s.st_uid, s.st_gid)
 
1888
    except OSError, e:
 
1889
        trace.warning(
 
1890
            'Unable to copy ownership from "%s" to "%s". '
 
1891
            'You may want to set it manually.', src, dst)
 
1892
        trace.log_exception_quietly()
 
1893
 
 
1894
 
1392
1895
def path_prefix_key(path):
1393
1896
    """Generate a prefix-order path key for path.
1394
1897
 
1425
1928
        return _cached_user_encoding
1426
1929
 
1427
1930
    if sys.platform == 'darwin':
1428
 
        # work around egregious python 2.4 bug
 
1931
        # python locale.getpreferredencoding() always return
 
1932
        # 'mac-roman' on darwin. That's a lie.
1429
1933
        sys.platform = 'posix'
1430
1934
        try:
 
1935
            if os.environ.get('LANG', None) is None:
 
1936
                # If LANG is not set, we end up with 'ascii', which is bad
 
1937
                # ('mac-roman' is more than ascii), so we set a default which
 
1938
                # will give us UTF-8 (which appears to work in all cases on
 
1939
                # OSX). Users are still free to override LANG of course, as
 
1940
                # long as it give us something meaningful. This work-around
 
1941
                # *may* not be needed with python 3k and/or OSX 10.5, but will
 
1942
                # work with them too -- vila 20080908
 
1943
                os.environ['LANG'] = 'en_US.UTF-8'
1431
1944
            import locale
1432
1945
        finally:
1433
1946
            sys.platform = 'darwin'
1470
1983
    return user_encoding
1471
1984
 
1472
1985
 
 
1986
def get_diff_header_encoding():
 
1987
    return get_terminal_encoding()
 
1988
 
 
1989
 
1473
1990
def get_host_name():
1474
1991
    """Return the current unicode host name.
1475
1992
 
1484
2001
        return socket.gethostname().decode(get_user_encoding())
1485
2002
 
1486
2003
 
1487
 
def recv_all(socket, bytes):
 
2004
# We must not read/write any more than 64k at a time from/to a socket so we
 
2005
# don't risk "no buffer space available" errors on some platforms.  Windows in
 
2006
# particular is likely to throw WSAECONNABORTED or WSAENOBUFS if given too much
 
2007
# data at once.
 
2008
MAX_SOCKET_CHUNK = 64 * 1024
 
2009
 
 
2010
_end_of_stream_errors = [errno.ECONNRESET]
 
2011
for _eno in ['WSAECONNRESET', 'WSAECONNABORTED']:
 
2012
    _eno = getattr(errno, _eno, None)
 
2013
    if _eno is not None:
 
2014
        _end_of_stream_errors.append(_eno)
 
2015
del _eno
 
2016
 
 
2017
 
 
2018
def read_bytes_from_socket(sock, report_activity=None,
 
2019
        max_read_size=MAX_SOCKET_CHUNK):
 
2020
    """Read up to max_read_size of bytes from sock and notify of progress.
 
2021
 
 
2022
    Translates "Connection reset by peer" into file-like EOF (return an
 
2023
    empty string rather than raise an error), and repeats the recv if
 
2024
    interrupted by a signal.
 
2025
    """
 
2026
    while 1:
 
2027
        try:
 
2028
            bytes = sock.recv(max_read_size)
 
2029
        except socket.error, e:
 
2030
            eno = e.args[0]
 
2031
            if eno in _end_of_stream_errors:
 
2032
                # The connection was closed by the other side.  Callers expect
 
2033
                # an empty string to signal end-of-stream.
 
2034
                return ""
 
2035
            elif eno == errno.EINTR:
 
2036
                # Retry the interrupted recv.
 
2037
                continue
 
2038
            raise
 
2039
        else:
 
2040
            if report_activity is not None:
 
2041
                report_activity(len(bytes), 'read')
 
2042
            return bytes
 
2043
 
 
2044
 
 
2045
def recv_all(socket, count):
1488
2046
    """Receive an exact number of bytes.
1489
2047
 
1490
2048
    Regular Socket.recv() may return less than the requested number of bytes,
1491
 
    dependning on what's in the OS buffer.  MSG_WAITALL is not available
 
2049
    depending on what's in the OS buffer.  MSG_WAITALL is not available
1492
2050
    on all platforms, but this should work everywhere.  This will return
1493
2051
    less than the requested amount if the remote end closes.
1494
2052
 
1495
2053
    This isn't optimized and is intended mostly for use in testing.
1496
2054
    """
1497
2055
    b = ''
1498
 
    while len(b) < bytes:
1499
 
        new = socket.recv(bytes - len(b))
 
2056
    while len(b) < count:
 
2057
        new = read_bytes_from_socket(socket, None, count - len(b))
1500
2058
        if new == '':
1501
2059
            break # eof
1502
2060
        b += new
1503
2061
    return b
1504
2062
 
1505
2063
 
1506
 
def send_all(socket, bytes):
 
2064
def send_all(sock, bytes, report_activity=None):
1507
2065
    """Send all bytes on a socket.
1508
2066
 
1509
 
    Regular socket.sendall() can give socket error 10053 on Windows.  This
1510
 
    implementation sends no more than 64k at a time, which avoids this problem.
 
2067
    Breaks large blocks in smaller chunks to avoid buffering limitations on
 
2068
    some platforms, and catches EINTR which may be thrown if the send is
 
2069
    interrupted by a signal.
 
2070
 
 
2071
    This is preferred to socket.sendall(), because it avoids portability bugs
 
2072
    and provides activity reporting.
 
2073
 
 
2074
    :param report_activity: Call this as bytes are read, see
 
2075
        Transport._report_activity
1511
2076
    """
1512
 
    chunk_size = 2**16
1513
 
    for pos in xrange(0, len(bytes), chunk_size):
1514
 
        socket.sendall(bytes[pos:pos+chunk_size])
 
2077
    sent_total = 0
 
2078
    byte_count = len(bytes)
 
2079
    while sent_total < byte_count:
 
2080
        try:
 
2081
            sent = sock.send(buffer(bytes, sent_total, MAX_SOCKET_CHUNK))
 
2082
        except socket.error, e:
 
2083
            if e.args[0] != errno.EINTR:
 
2084
                raise
 
2085
        else:
 
2086
            sent_total += sent
 
2087
            report_activity(sent, 'write')
 
2088
 
 
2089
 
 
2090
def connect_socket(address):
 
2091
    # Slight variation of the socket.create_connection() function (provided by
 
2092
    # python-2.6) that can fail if getaddrinfo returns an empty list. We also
 
2093
    # provide it for previous python versions. Also, we don't use the timeout
 
2094
    # parameter (provided by the python implementation) so we don't implement
 
2095
    # it either).
 
2096
    err = socket.error('getaddrinfo returns an empty list')
 
2097
    host, port = address
 
2098
    for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
 
2099
        af, socktype, proto, canonname, sa = res
 
2100
        sock = None
 
2101
        try:
 
2102
            sock = socket.socket(af, socktype, proto)
 
2103
            sock.connect(sa)
 
2104
            return sock
 
2105
 
 
2106
        except socket.error, err:
 
2107
            # 'err' is now the most recent error
 
2108
            if sock is not None:
 
2109
                sock.close()
 
2110
    raise err
1515
2111
 
1516
2112
 
1517
2113
def dereference_path(path):
1558
2154
    base = dirname(bzrlib.__file__)
1559
2155
    if getattr(sys, 'frozen', None):    # bzr.exe
1560
2156
        base = abspath(pathjoin(base, '..', '..'))
1561
 
    filename = pathjoin(base, resource_relpath)
1562
 
    return open(filename, 'rU').read()
1563
 
 
1564
 
 
1565
 
try:
1566
 
    from bzrlib._readdir_pyx import read_dir as _read_dir
1567
 
except ImportError:
1568
 
    from bzrlib._readdir_py import read_dir as _read_dir
 
2157
    f = file(pathjoin(base, resource_relpath), "rU")
 
2158
    try:
 
2159
        return f.read()
 
2160
    finally:
 
2161
        f.close()
 
2162
 
 
2163
def file_kind_from_stat_mode_thunk(mode):
 
2164
    global file_kind_from_stat_mode
 
2165
    if file_kind_from_stat_mode is file_kind_from_stat_mode_thunk:
 
2166
        try:
 
2167
            from bzrlib._readdir_pyx import UTF8DirReader
 
2168
            file_kind_from_stat_mode = UTF8DirReader().kind_from_mode
 
2169
        except ImportError, e:
 
2170
            # This is one time where we won't warn that an extension failed to
 
2171
            # load. The extension is never available on Windows anyway.
 
2172
            from bzrlib._readdir_py import (
 
2173
                _kind_from_mode as file_kind_from_stat_mode
 
2174
                )
 
2175
    return file_kind_from_stat_mode(mode)
 
2176
file_kind_from_stat_mode = file_kind_from_stat_mode_thunk
 
2177
 
 
2178
 
 
2179
def file_kind(f, _lstat=os.lstat):
 
2180
    try:
 
2181
        return file_kind_from_stat_mode(_lstat(f).st_mode)
 
2182
    except OSError, e:
 
2183
        if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
 
2184
            raise errors.NoSuchFile(f)
 
2185
        raise
 
2186
 
 
2187
 
 
2188
def until_no_eintr(f, *a, **kw):
 
2189
    """Run f(*a, **kw), retrying if an EINTR error occurs.
 
2190
 
 
2191
    WARNING: you must be certain that it is safe to retry the call repeatedly
 
2192
    if EINTR does occur.  This is typically only true for low-level operations
 
2193
    like os.read.  If in any doubt, don't use this.
 
2194
 
 
2195
    Keep in mind that this is not a complete solution to EINTR.  There is
 
2196
    probably code in the Python standard library and other dependencies that
 
2197
    may encounter EINTR if a signal arrives (and there is signal handler for
 
2198
    that signal).  So this function can reduce the impact for IO that bzrlib
 
2199
    directly controls, but it is not a complete solution.
 
2200
    """
 
2201
    # Borrowed from Twisted's twisted.python.util.untilConcludes function.
 
2202
    while True:
 
2203
        try:
 
2204
            return f(*a, **kw)
 
2205
        except (IOError, OSError), e:
 
2206
            if e.errno == errno.EINTR:
 
2207
                continue
 
2208
            raise
 
2209
 
 
2210
 
 
2211
@deprecated_function(deprecated_in((2, 2, 0)))
 
2212
def re_compile_checked(re_string, flags=0, where=""):
 
2213
    """Return a compiled re, or raise a sensible error.
 
2214
 
 
2215
    This should only be used when compiling user-supplied REs.
 
2216
 
 
2217
    :param re_string: Text form of regular expression.
 
2218
    :param flags: eg re.IGNORECASE
 
2219
    :param where: Message explaining to the user the context where
 
2220
        it occurred, eg 'log search filter'.
 
2221
    """
 
2222
    # from https://bugs.launchpad.net/bzr/+bug/251352
 
2223
    try:
 
2224
        re_obj = re.compile(re_string, flags)
 
2225
        re_obj.search("")
 
2226
        return re_obj
 
2227
    except errors.InvalidPattern, e:
 
2228
        if where:
 
2229
            where = ' in ' + where
 
2230
        # despite the name 'error' is a type
 
2231
        raise errors.BzrCommandError('Invalid regular expression%s: %s'
 
2232
            % (where, e.msg))
 
2233
 
 
2234
 
 
2235
if sys.platform == "win32":
 
2236
    import msvcrt
 
2237
    def getchar():
 
2238
        return msvcrt.getch()
 
2239
else:
 
2240
    import tty
 
2241
    import termios
 
2242
    def getchar():
 
2243
        fd = sys.stdin.fileno()
 
2244
        settings = termios.tcgetattr(fd)
 
2245
        try:
 
2246
            tty.setraw(fd)
 
2247
            ch = sys.stdin.read(1)
 
2248
        finally:
 
2249
            termios.tcsetattr(fd, termios.TCSADRAIN, settings)
 
2250
        return ch
 
2251
 
 
2252
if sys.platform == 'linux2':
 
2253
    def _local_concurrency():
 
2254
        try:
 
2255
            return os.sysconf('SC_NPROCESSORS_ONLN')
 
2256
        except (ValueError, OSError, AttributeError):
 
2257
            return None
 
2258
elif sys.platform == 'darwin':
 
2259
    def _local_concurrency():
 
2260
        return subprocess.Popen(['sysctl', '-n', 'hw.availcpu'],
 
2261
                                stdout=subprocess.PIPE).communicate()[0]
 
2262
elif "bsd" in sys.platform:
 
2263
    def _local_concurrency():
 
2264
        return subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
 
2265
                                stdout=subprocess.PIPE).communicate()[0]
 
2266
elif sys.platform == 'sunos5':
 
2267
    def _local_concurrency():
 
2268
        return subprocess.Popen(['psrinfo', '-p',],
 
2269
                                stdout=subprocess.PIPE).communicate()[0]
 
2270
elif sys.platform == "win32":
 
2271
    def _local_concurrency():
 
2272
        # This appears to return the number of cores.
 
2273
        return os.environ.get('NUMBER_OF_PROCESSORS')
 
2274
else:
 
2275
    def _local_concurrency():
 
2276
        # Who knows ?
 
2277
        return None
 
2278
 
 
2279
 
 
2280
_cached_local_concurrency = None
 
2281
 
 
2282
def local_concurrency(use_cache=True):
 
2283
    """Return how many processes can be run concurrently.
 
2284
 
 
2285
    Rely on platform specific implementations and default to 1 (one) if
 
2286
    anything goes wrong.
 
2287
    """
 
2288
    global _cached_local_concurrency
 
2289
 
 
2290
    if _cached_local_concurrency is not None and use_cache:
 
2291
        return _cached_local_concurrency
 
2292
 
 
2293
    concurrency = os.environ.get('BZR_CONCURRENCY', None)
 
2294
    if concurrency is None:
 
2295
        try:
 
2296
            import multiprocessing
 
2297
        except ImportError:
 
2298
            # multiprocessing is only available on Python >= 2.6
 
2299
            try:
 
2300
                concurrency = _local_concurrency()
 
2301
            except (OSError, IOError):
 
2302
                pass
 
2303
        else:
 
2304
            concurrency = multiprocessing.cpu_count()
 
2305
    try:
 
2306
        concurrency = int(concurrency)
 
2307
    except (TypeError, ValueError):
 
2308
        concurrency = 1
 
2309
    if use_cache:
 
2310
        _cached_concurrency = concurrency
 
2311
    return concurrency
 
2312
 
 
2313
 
 
2314
class UnicodeOrBytesToBytesWriter(codecs.StreamWriter):
 
2315
    """A stream writer that doesn't decode str arguments."""
 
2316
 
 
2317
    def __init__(self, encode, stream, errors='strict'):
 
2318
        codecs.StreamWriter.__init__(self, stream, errors)
 
2319
        self.encode = encode
 
2320
 
 
2321
    def write(self, object):
 
2322
        if type(object) is str:
 
2323
            self.stream.write(object)
 
2324
        else:
 
2325
            data, _ = self.encode(object, self.errors)
 
2326
            self.stream.write(data)
 
2327
 
 
2328
if sys.platform == 'win32':
 
2329
    def open_file(filename, mode='r', bufsize=-1):
 
2330
        """This function is used to override the ``open`` builtin.
 
2331
 
 
2332
        But it uses O_NOINHERIT flag so the file handle is not inherited by
 
2333
        child processes.  Deleting or renaming a closed file opened with this
 
2334
        function is not blocking child processes.
 
2335
        """
 
2336
        writing = 'w' in mode
 
2337
        appending = 'a' in mode
 
2338
        updating = '+' in mode
 
2339
        binary = 'b' in mode
 
2340
 
 
2341
        flags = O_NOINHERIT
 
2342
        # see http://msdn.microsoft.com/en-us/library/yeby3zcb%28VS.71%29.aspx
 
2343
        # for flags for each modes.
 
2344
        if binary:
 
2345
            flags |= O_BINARY
 
2346
        else:
 
2347
            flags |= O_TEXT
 
2348
 
 
2349
        if writing:
 
2350
            if updating:
 
2351
                flags |= os.O_RDWR
 
2352
            else:
 
2353
                flags |= os.O_WRONLY
 
2354
            flags |= os.O_CREAT | os.O_TRUNC
 
2355
        elif appending:
 
2356
            if updating:
 
2357
                flags |= os.O_RDWR
 
2358
            else:
 
2359
                flags |= os.O_WRONLY
 
2360
            flags |= os.O_CREAT | os.O_APPEND
 
2361
        else: #reading
 
2362
            if updating:
 
2363
                flags |= os.O_RDWR
 
2364
            else:
 
2365
                flags |= os.O_RDONLY
 
2366
 
 
2367
        return os.fdopen(os.open(filename, flags), mode, bufsize)
 
2368
else:
 
2369
    open_file = open
 
2370
 
 
2371
 
 
2372
def getuser_unicode():
 
2373
    """Return the username as unicode.
 
2374
    """
 
2375
    try:
 
2376
        user_encoding = get_user_encoding()
 
2377
        username = getpass.getuser().decode(user_encoding)
 
2378
    except UnicodeDecodeError:
 
2379
        raise errors.BzrError("Can't decode username as %s." % \
 
2380
                user_encoding)
 
2381
    return username
 
2382
 
 
2383
 
 
2384
def available_backup_name(base, exists):
 
2385
    """Find a non-existing backup file name.
 
2386
 
 
2387
    This will *not* create anything, this only return a 'free' entry.  This
 
2388
    should be used for checking names in a directory below a locked
 
2389
    tree/branch/repo to avoid race conditions. This is LBYL (Look Before You
 
2390
    Leap) and generally discouraged.
 
2391
 
 
2392
    :param base: The base name.
 
2393
 
 
2394
    :param exists: A callable returning True if the path parameter exists.
 
2395
    """
 
2396
    counter = 1
 
2397
    name = "%s.~%d~" % (base, counter)
 
2398
    while exists(name):
 
2399
        counter += 1
 
2400
        name = "%s.~%d~" % (base, counter)
 
2401
    return name
 
2402
 
 
2403
 
 
2404
def set_fd_cloexec(fd):
 
2405
    """Set a Unix file descriptor's FD_CLOEXEC flag.  Do nothing if platform
 
2406
    support for this is not available.
 
2407
    """
 
2408
    try:
 
2409
        import fcntl
 
2410
        old = fcntl.fcntl(fd, fcntl.F_GETFD)
 
2411
        fcntl.fcntl(fd, fcntl.F_SETFD, old | fcntl.FD_CLOEXEC)
 
2412
    except (ImportError, AttributeError):
 
2413
        # Either the fcntl module or specific constants are not present
 
2414
        pass
 
2415
 
 
2416
 
 
2417
def find_executable_on_path(name):
 
2418
    """Finds an executable on the PATH.
 
2419
    
 
2420
    On Windows, this will try to append each extension in the PATHEXT
 
2421
    environment variable to the name, if it cannot be found with the name
 
2422
    as given.
 
2423
    
 
2424
    :param name: The base name of the executable.
 
2425
    :return: The path to the executable found or None.
 
2426
    """
 
2427
    path = os.environ.get('PATH')
 
2428
    if path is None:
 
2429
        return None
 
2430
    path = path.split(os.pathsep)
 
2431
    if sys.platform == 'win32':
 
2432
        exts = os.environ.get('PATHEXT', '').split(os.pathsep)
 
2433
        exts = [ext.lower() for ext in exts]
 
2434
        base, ext = os.path.splitext(name)
 
2435
        if ext != '':
 
2436
            if ext.lower() not in exts:
 
2437
                return None
 
2438
            name = base
 
2439
            exts = [ext]
 
2440
    else:
 
2441
        exts = ['']
 
2442
    for ext in exts:
 
2443
        for d in path:
 
2444
            f = os.path.join(d, name) + ext
 
2445
            if os.access(f, os.X_OK):
 
2446
                return f
 
2447
    return None