/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: Neil Martinsen-Burrell
  • Date: 2009-12-07 21:51:01 UTC
  • mto: This revision was merged to the branch mainline in revision 4910.
  • Revision ID: nmb@wartburg.edu-20091207215101-lv1fyi2blzer4h5j
tweaks based on JAMs review

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Bazaar -- distributed version control
2
 
#
3
 
# Copyright (C) 2005 by Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2009 Canonical Ltd
4
2
#
5
3
# This program is free software; you can redistribute it and/or modify
6
4
# it under the terms of the GNU General Public License as published by
14
12
#
15
13
# You should have received a copy of the GNU General Public License
16
14
# along with this program; if not, write to the Free Software
17
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
 
 
19
 
from cStringIO import StringIO
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
import os
 
18
import re
 
19
import stat
 
20
from stat import (S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE,
 
21
                  S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
 
22
import sys
 
23
import time
 
24
import warnings
 
25
 
 
26
from bzrlib.lazy_import import lazy_import
 
27
lazy_import(globals(), """
 
28
import codecs
 
29
from datetime import datetime
20
30
import errno
21
31
from ntpath import (abspath as _nt_abspath,
22
32
                    join as _nt_join,
24
34
                    realpath as _nt_realpath,
25
35
                    splitdrive as _nt_splitdrive,
26
36
                    )
27
 
import os
28
 
from os import listdir
29
37
import posixpath
30
 
import re
31
 
import sha
32
38
import shutil
33
 
from shutil import copyfile
34
 
import stat
35
 
from stat import (S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE,
36
 
                  S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
37
 
import string
38
 
import sys
39
 
import time
40
 
import types
 
39
from shutil import (
 
40
    rmtree,
 
41
    )
 
42
import subprocess
41
43
import tempfile
 
44
from tempfile import (
 
45
    mkdtemp,
 
46
    )
42
47
import unicodedata
43
48
 
 
49
from bzrlib import (
 
50
    cache_utf8,
 
51
    errors,
 
52
    win32utils,
 
53
    )
 
54
""")
 
55
 
 
56
# sha and md5 modules are deprecated in python2.6 but hashlib is available as
 
57
# of 2.5
 
58
if sys.version_info < (2, 5):
 
59
    import md5 as _mod_md5
 
60
    md5 = _mod_md5.new
 
61
    import sha as _mod_sha
 
62
    sha = _mod_sha.new
 
63
else:
 
64
    from hashlib import (
 
65
        md5,
 
66
        sha1 as sha,
 
67
        )
 
68
 
 
69
 
44
70
import bzrlib
45
 
from bzrlib.errors import (BzrError,
46
 
                           BzrBadParameterNotUnicode,
47
 
                           NoSuchFile,
48
 
                           PathNotChild,
49
 
                           IllegalPath,
50
 
                           )
51
 
from bzrlib.symbol_versioning import (deprecated_function, 
52
 
        zero_nine)
53
 
from bzrlib.trace import mutter
 
71
from bzrlib import symbol_versioning
54
72
 
55
73
 
56
74
# On win32, O_BINARY is used to indicate the file should
61
79
O_BINARY = getattr(os, 'O_BINARY', 0)
62
80
 
63
81
 
 
82
def get_unicode_argv():
 
83
    try:
 
84
        user_encoding = get_user_encoding()
 
85
        return [a.decode(user_encoding) for a in sys.argv[1:]]
 
86
    except UnicodeDecodeError:
 
87
        raise errors.BzrError(("Parameter '%r' is unsupported by the current "
 
88
                                                            "encoding." % a))
 
89
 
 
90
 
64
91
def make_readonly(filename):
65
92
    """Make a filename read-only."""
66
 
    mod = os.stat(filename).st_mode
67
 
    mod = mod & 0777555
68
 
    os.chmod(filename, mod)
 
93
    mod = os.lstat(filename).st_mode
 
94
    if not stat.S_ISLNK(mod):
 
95
        mod = mod & 0777555
 
96
        os.chmod(filename, mod)
69
97
 
70
98
 
71
99
def make_writable(filename):
72
 
    mod = os.stat(filename).st_mode
73
 
    mod = mod | 0200
74
 
    os.chmod(filename, mod)
 
100
    mod = os.lstat(filename).st_mode
 
101
    if not stat.S_ISLNK(mod):
 
102
        mod = mod | 0200
 
103
        os.chmod(filename, mod)
 
104
 
 
105
 
 
106
def minimum_path_selection(paths):
 
107
    """Return the smallset subset of paths which are outside paths.
 
108
 
 
109
    :param paths: A container (and hence not None) of paths.
 
110
    :return: A set of paths sufficient to include everything in paths via
 
111
        is_inside, drawn from the paths parameter.
 
112
    """
 
113
    if len(paths) < 2:
 
114
        return set(paths)
 
115
 
 
116
    def sort_key(path):
 
117
        return path.split('/')
 
118
    sorted_paths = sorted(list(paths), key=sort_key)
 
119
 
 
120
    search_paths = [sorted_paths[0]]
 
121
    for path in sorted_paths[1:]:
 
122
        if not is_inside(search_paths[-1], path):
 
123
            # This path is unique, add it
 
124
            search_paths.append(path)
 
125
 
 
126
    return set(search_paths)
75
127
 
76
128
 
77
129
_QUOTE_RE = None
86
138
    global _QUOTE_RE
87
139
    if _QUOTE_RE is None:
88
140
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
89
 
        
 
141
 
90
142
    if _QUOTE_RE.search(f):
91
143
        return '"' + f + '"'
92
144
    else:
95
147
 
96
148
_directory_kind = 'directory'
97
149
 
98
 
_formats = {
99
 
    stat.S_IFDIR:_directory_kind,
100
 
    stat.S_IFCHR:'chardev',
101
 
    stat.S_IFBLK:'block',
102
 
    stat.S_IFREG:'file',
103
 
    stat.S_IFIFO:'fifo',
104
 
    stat.S_IFLNK:'symlink',
105
 
    stat.S_IFSOCK:'socket',
106
 
}
107
 
 
108
 
 
109
 
def file_kind_from_stat_mode(stat_mode, _formats=_formats, _unknown='unknown'):
110
 
    """Generate a file kind from a stat mode. This is used in walkdirs.
111
 
 
112
 
    Its performance is critical: Do not mutate without careful benchmarking.
113
 
    """
114
 
    try:
115
 
        return _formats[stat_mode & 0170000]
116
 
    except KeyError:
117
 
        return _unknown
118
 
 
119
 
 
120
 
def file_kind(f, _lstat=os.lstat, _mapper=file_kind_from_stat_mode):
121
 
    try:
122
 
        return _mapper(_lstat(f).st_mode)
123
 
    except OSError, e:
124
 
        if getattr(e, 'errno', None) == errno.ENOENT:
125
 
            raise bzrlib.errors.NoSuchFile(f)
126
 
        raise
127
 
 
128
 
 
129
150
def get_umask():
130
151
    """Return the current umask"""
131
152
    # Assume that people aren't messing with the umask while running
136
157
    return umask
137
158
 
138
159
 
 
160
_kind_marker_map = {
 
161
    "file": "",
 
162
    _directory_kind: "/",
 
163
    "symlink": "@",
 
164
    'tree-reference': '+',
 
165
}
 
166
 
 
167
 
139
168
def kind_marker(kind):
140
 
    if kind == 'file':
141
 
        return ''
142
 
    elif kind == _directory_kind:
143
 
        return '/'
144
 
    elif kind == 'symlink':
145
 
        return '@'
146
 
    else:
147
 
        raise BzrError('invalid file kind %r' % kind)
 
169
    try:
 
170
        return _kind_marker_map[kind]
 
171
    except KeyError:
 
172
        raise errors.BzrError('invalid file kind %r' % kind)
 
173
 
148
174
 
149
175
lexists = getattr(os.path, 'lexists', None)
150
176
if lexists is None:
151
177
    def lexists(f):
152
178
        try:
153
 
            if getattr(os, 'lstat') is not None:
154
 
                os.lstat(f)
155
 
            else:
156
 
                os.stat(f)
 
179
            stat = getattr(os, 'lstat', os.stat)
 
180
            stat(f)
157
181
            return True
158
 
        except OSError,e:
 
182
        except OSError, e:
159
183
            if e.errno == errno.ENOENT:
160
184
                return False;
161
185
            else:
162
 
                raise BzrError("lstat/stat of (%r): %r" % (f, e))
 
186
                raise errors.BzrError("lstat/stat of (%r): %r" % (f, e))
163
187
 
164
188
 
165
189
def fancy_rename(old, new, rename_func, unlink_func):
166
190
    """A fancy rename, when you don't have atomic rename.
167
 
    
 
191
 
168
192
    :param old: The old path, to rename from
169
193
    :param new: The new path, to rename to
170
194
    :param rename_func: The potentially non-atomic rename function
172
196
    """
173
197
 
174
198
    # sftp rename doesn't allow overwriting, so play tricks:
175
 
    import random
176
199
    base = os.path.basename(new)
177
200
    dirname = os.path.dirname(new)
178
201
    tmp_name = u'tmp.%s.%.9f.%d.%s' % (base, time.time(), os.getpid(), rand_chars(10))
186
209
    file_existed = False
187
210
    try:
188
211
        rename_func(new, tmp_name)
189
 
    except (NoSuchFile,), e:
 
212
    except (errors.NoSuchFile,), e:
190
213
        pass
191
214
    except IOError, e:
192
215
        # RBC 20060103 abstraction leakage: the paramiko SFTP clients rename
201
224
    else:
202
225
        file_existed = True
203
226
 
 
227
    failure_exc = None
204
228
    success = False
205
229
    try:
206
 
        # This may throw an exception, in which case success will
207
 
        # not be set.
208
 
        rename_func(old, new)
209
 
        success = True
 
230
        try:
 
231
            # This may throw an exception, in which case success will
 
232
            # not be set.
 
233
            rename_func(old, new)
 
234
            success = True
 
235
        except (IOError, OSError), e:
 
236
            # source and target may be aliases of each other (e.g. on a
 
237
            # case-insensitive filesystem), so we may have accidentally renamed
 
238
            # source by when we tried to rename target
 
239
            failure_exc = sys.exc_info()
 
240
            if (file_existed and e.errno in (None, errno.ENOENT)
 
241
                and old.lower() == new.lower()):
 
242
                # source and target are the same file on a case-insensitive
 
243
                # filesystem, so we don't generate an exception
 
244
                failure_exc = None
210
245
    finally:
211
246
        if file_existed:
212
247
            # If the file used to exist, rename it back into place
215
250
                unlink_func(tmp_name)
216
251
            else:
217
252
                rename_func(tmp_name, new)
 
253
    if failure_exc is not None:
 
254
        raise failure_exc[0], failure_exc[1], failure_exc[2]
218
255
 
219
256
 
220
257
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
221
258
# choke on a Unicode string containing a relative path if
222
259
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
223
260
# string.
224
 
_fs_enc = sys.getfilesystemencoding()
 
261
_fs_enc = sys.getfilesystemencoding() or 'utf-8'
225
262
def _posix_abspath(path):
226
263
    # jam 20060426 rather than encoding to fsencoding
227
264
    # copy posixpath.abspath, but use os.getcwdu instead
252
289
    return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
253
290
 
254
291
 
 
292
def _win98_abspath(path):
 
293
    """Return the absolute version of a path.
 
294
    Windows 98 safe implementation (python reimplementation
 
295
    of Win32 API function GetFullPathNameW)
 
296
    """
 
297
    # Corner cases:
 
298
    #   C:\path     => C:/path
 
299
    #   C:/path     => C:/path
 
300
    #   \\HOST\path => //HOST/path
 
301
    #   //HOST/path => //HOST/path
 
302
    #   path        => C:/cwd/path
 
303
    #   /path       => C:/path
 
304
    path = unicode(path)
 
305
    # check for absolute path
 
306
    drive = _nt_splitdrive(path)[0]
 
307
    if drive == '' and path[:2] not in('//','\\\\'):
 
308
        cwd = os.getcwdu()
 
309
        # we cannot simply os.path.join cwd and path
 
310
        # because os.path.join('C:','/path') produce '/path'
 
311
        # and this is incorrect
 
312
        if path[:1] in ('/','\\'):
 
313
            cwd = _nt_splitdrive(cwd)[0]
 
314
            path = path[1:]
 
315
        path = cwd + '\\' + path
 
316
    return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
 
317
 
 
318
 
255
319
def _win32_realpath(path):
256
320
    # Real _nt_realpath doesn't have a problem with a unicode cwd
257
321
    return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
277
341
    """We expect to be able to atomically replace 'new' with old.
278
342
 
279
343
    On win32, if new exists, it must be moved out of the way first,
280
 
    and then deleted. 
 
344
    and then deleted.
281
345
    """
282
346
    try:
283
347
        fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
284
348
    except OSError, e:
285
349
        if e.errno in (errno.EPERM, errno.EACCES, errno.EBUSY, errno.EINVAL):
286
 
            # If we try to rename a non-existant file onto cwd, we get 
287
 
            # EPERM or EACCES instead of ENOENT, this will raise ENOENT 
 
350
            # If we try to rename a non-existant file onto cwd, we get
 
351
            # EPERM or EACCES instead of ENOENT, this will raise ENOENT
288
352
            # if the old path doesn't exist, sometimes we get EACCES
289
353
            # On Linux, we seem to get EBUSY, on Mac we get EINVAL
290
354
            os.lstat(old)
292
356
 
293
357
 
294
358
def _mac_getcwd():
295
 
    return unicodedata.normalize('NFKC', os.getcwdu())
 
359
    return unicodedata.normalize('NFC', os.getcwdu())
296
360
 
297
361
 
298
362
# Default is to just use the python builtins, but these can be rebound on
302
366
pathjoin = os.path.join
303
367
normpath = os.path.normpath
304
368
getcwd = os.getcwdu
305
 
mkdtemp = tempfile.mkdtemp
306
369
rename = os.rename
307
370
dirname = os.path.dirname
308
371
basename = os.path.basename
309
 
rmtree = shutil.rmtree
 
372
split = os.path.split
 
373
splitext = os.path.splitext
 
374
# These were already imported into local scope
 
375
# mkdtemp = tempfile.mkdtemp
 
376
# rmtree = shutil.rmtree
310
377
 
311
378
MIN_ABS_PATHLENGTH = 1
312
379
 
313
380
 
314
381
if sys.platform == 'win32':
315
 
    abspath = _win32_abspath
 
382
    if win32utils.winver == 'Windows 98':
 
383
        abspath = _win98_abspath
 
384
    else:
 
385
        abspath = _win32_abspath
316
386
    realpath = _win32_realpath
317
387
    pathjoin = _win32_pathjoin
318
388
    normpath = _win32_normpath
326
396
        """Error handler for shutil.rmtree function [for win32]
327
397
        Helps to remove files and dirs marked as read-only.
328
398
        """
329
 
        type_, value = excinfo[:2]
 
399
        exception = excinfo[1]
330
400
        if function in (os.remove, os.rmdir) \
331
 
            and type_ == OSError \
332
 
            and value.errno == errno.EACCES:
333
 
            bzrlib.osutils.make_writable(path)
 
401
            and isinstance(exception, OSError) \
 
402
            and exception.errno == errno.EACCES:
 
403
            make_writable(path)
334
404
            function(path)
335
405
        else:
336
406
            raise
338
408
    def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
339
409
        """Replacer for shutil.rmtree: could remove readonly dirs/files"""
340
410
        return shutil.rmtree(path, ignore_errors, onerror)
 
411
 
 
412
    f = win32utils.get_unicode_argv     # special function or None
 
413
    if f is not None:
 
414
        get_unicode_argv = f
 
415
 
341
416
elif sys.platform == 'darwin':
342
417
    getcwd = _mac_getcwd
343
418
 
347
422
 
348
423
    This attempts to check both sys.stdout and sys.stdin to see
349
424
    what encoding they are in, and if that fails it falls back to
350
 
    bzrlib.user_encoding.
 
425
    osutils.get_user_encoding().
351
426
    The problem is that on Windows, locale.getpreferredencoding()
352
427
    is not the same encoding as that used by the console:
353
428
    http://mail.python.org/pipermail/python-list/2003-May/162357.html
355
430
    On my standard US Windows XP, the preferred encoding is
356
431
    cp1252, but the console is cp437
357
432
    """
 
433
    from bzrlib.trace import mutter
358
434
    output_encoding = getattr(sys.stdout, 'encoding', None)
359
435
    if not output_encoding:
360
436
        input_encoding = getattr(sys.stdin, 'encoding', None)
361
437
        if not input_encoding:
362
 
            output_encoding = bzrlib.user_encoding
363
 
            mutter('encoding stdout as bzrlib.user_encoding %r', output_encoding)
 
438
            output_encoding = get_user_encoding()
 
439
            mutter('encoding stdout as osutils.get_user_encoding() %r',
 
440
                   output_encoding)
364
441
        else:
365
442
            output_encoding = input_encoding
366
443
            mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
367
444
    else:
368
445
        mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
 
446
    if output_encoding == 'cp0':
 
447
        # invalid encoding (cp0 means 'no codepage' on Windows)
 
448
        output_encoding = get_user_encoding()
 
449
        mutter('cp0 is invalid encoding.'
 
450
               ' encoding stdout as osutils.get_user_encoding() %r',
 
451
               output_encoding)
 
452
    # check encoding
 
453
    try:
 
454
        codecs.lookup(output_encoding)
 
455
    except LookupError:
 
456
        sys.stderr.write('bzr: warning:'
 
457
                         ' unknown terminal encoding %s.\n'
 
458
                         '  Using encoding %s instead.\n'
 
459
                         % (output_encoding, get_user_encoding())
 
460
                        )
 
461
        output_encoding = get_user_encoding()
 
462
 
369
463
    return output_encoding
370
464
 
371
465
 
381
475
        return pathjoin(F(p), e)
382
476
 
383
477
 
384
 
def backup_file(fn):
385
 
    """Copy a file to a backup.
386
 
 
387
 
    Backups are named in GNU-style, with a ~ suffix.
388
 
 
389
 
    If the file is already a backup, it's not copied.
390
 
    """
391
 
    if fn[-1] == '~':
392
 
        return
393
 
    bfn = fn + '~'
394
 
 
395
 
    if has_symlinks() and os.path.islink(fn):
396
 
        target = os.readlink(fn)
397
 
        os.symlink(target, bfn)
398
 
        return
399
 
    inf = file(fn, 'rb')
400
 
    try:
401
 
        content = inf.read()
402
 
    finally:
403
 
        inf.close()
404
 
    
405
 
    outf = file(bfn, 'wb')
406
 
    try:
407
 
        outf.write(content)
408
 
    finally:
409
 
        outf.close()
410
 
 
411
 
 
412
478
def isdir(f):
413
479
    """True if f is an accessible directory."""
414
480
    try:
433
499
 
434
500
def is_inside(dir, fname):
435
501
    """True if fname is inside dir.
436
 
    
 
502
 
437
503
    The parameters should typically be passed to osutils.normpath first, so
438
504
    that . and .. and repeated slashes are eliminated, and the separators
439
505
    are canonical for the platform.
440
 
    
441
 
    The empty string as a dir name is taken as top-of-tree and matches 
 
506
 
 
507
    The empty string as a dir name is taken as top-of-tree and matches
442
508
    everything.
443
 
    
444
 
    >>> is_inside('src', pathjoin('src', 'foo.c'))
445
 
    True
446
 
    >>> is_inside('src', 'srccontrol')
447
 
    False
448
 
    >>> is_inside('src', pathjoin('src', 'a', 'a', 'a', 'foo.c'))
449
 
    True
450
 
    >>> is_inside('foo.c', 'foo.c')
451
 
    True
452
 
    >>> is_inside('foo.c', '')
453
 
    False
454
 
    >>> is_inside('', 'foo.c')
455
 
    True
456
509
    """
457
 
    # XXX: Most callers of this can actually do something smarter by 
 
510
    # XXX: Most callers of this can actually do something smarter by
458
511
    # looking at the inventory
459
512
    if dir == fname:
460
513
        return True
461
 
    
 
514
 
462
515
    if dir == '':
463
516
        return True
464
517
 
473
526
    for dirname in dir_list:
474
527
        if is_inside(dirname, fname):
475
528
            return True
476
 
    else:
477
 
        return False
 
529
    return False
478
530
 
479
531
 
480
532
def is_inside_or_parent_of_any(dir_list, fname):
482
534
    for dirname in dir_list:
483
535
        if is_inside(dirname, fname) or is_inside(fname, dirname):
484
536
            return True
 
537
    return False
 
538
 
 
539
 
 
540
def pumpfile(from_file, to_file, read_length=-1, buff_size=32768,
 
541
             report_activity=None, direction='read'):
 
542
    """Copy contents of one file to another.
 
543
 
 
544
    The read_length can either be -1 to read to end-of-file (EOF) or
 
545
    it can specify the maximum number of bytes to read.
 
546
 
 
547
    The buff_size represents the maximum size for each read operation
 
548
    performed on from_file.
 
549
 
 
550
    :param report_activity: Call this as bytes are read, see
 
551
        Transport._report_activity
 
552
    :param direction: Will be passed to report_activity
 
553
 
 
554
    :return: The number of bytes copied.
 
555
    """
 
556
    length = 0
 
557
    if read_length >= 0:
 
558
        # read specified number of bytes
 
559
 
 
560
        while read_length > 0:
 
561
            num_bytes_to_read = min(read_length, buff_size)
 
562
 
 
563
            block = from_file.read(num_bytes_to_read)
 
564
            if not block:
 
565
                # EOF reached
 
566
                break
 
567
            if report_activity is not None:
 
568
                report_activity(len(block), direction)
 
569
            to_file.write(block)
 
570
 
 
571
            actual_bytes_read = len(block)
 
572
            read_length -= actual_bytes_read
 
573
            length += actual_bytes_read
485
574
    else:
486
 
        return False
487
 
 
488
 
 
489
 
def pumpfile(fromfile, tofile):
490
 
    """Copy contents of one file to another."""
491
 
    BUFSIZE = 32768
492
 
    while True:
493
 
        b = fromfile.read(BUFSIZE)
494
 
        if not b:
495
 
            break
496
 
        tofile.write(b)
 
575
        # read to EOF
 
576
        while True:
 
577
            block = from_file.read(buff_size)
 
578
            if not block:
 
579
                # EOF reached
 
580
                break
 
581
            if report_activity is not None:
 
582
                report_activity(len(block), direction)
 
583
            to_file.write(block)
 
584
            length += len(block)
 
585
    return length
 
586
 
 
587
 
 
588
def pump_string_file(bytes, file_handle, segment_size=None):
 
589
    """Write bytes to file_handle in many smaller writes.
 
590
 
 
591
    :param bytes: The string to write.
 
592
    :param file_handle: The file to write to.
 
593
    """
 
594
    # Write data in chunks rather than all at once, because very large
 
595
    # writes fail on some platforms (e.g. Windows with SMB  mounted
 
596
    # drives).
 
597
    if not segment_size:
 
598
        segment_size = 5242880 # 5MB
 
599
    segments = range(len(bytes) / segment_size + 1)
 
600
    write = file_handle.write
 
601
    for segment_index in segments:
 
602
        segment = buffer(bytes, segment_index * segment_size, segment_size)
 
603
        write(segment)
497
604
 
498
605
 
499
606
def file_iterator(input_file, readsize=32768):
505
612
 
506
613
 
507
614
def sha_file(f):
508
 
    if getattr(f, 'tell', None) is not None:
509
 
        assert f.tell() == 0
510
 
    s = sha.new()
 
615
    """Calculate the hexdigest of an open file.
 
616
 
 
617
    The file cursor should be already at the start.
 
618
    """
 
619
    s = sha()
511
620
    BUFSIZE = 128<<10
512
621
    while True:
513
622
        b = f.read(BUFSIZE)
517
626
    return s.hexdigest()
518
627
 
519
628
 
520
 
 
521
 
def sha_strings(strings):
 
629
def size_sha_file(f):
 
630
    """Calculate the size and hexdigest of an open file.
 
631
 
 
632
    The file cursor should be already at the start and
 
633
    the caller is responsible for closing the file afterwards.
 
634
    """
 
635
    size = 0
 
636
    s = sha()
 
637
    BUFSIZE = 128<<10
 
638
    while True:
 
639
        b = f.read(BUFSIZE)
 
640
        if not b:
 
641
            break
 
642
        size += len(b)
 
643
        s.update(b)
 
644
    return size, s.hexdigest()
 
645
 
 
646
 
 
647
def sha_file_by_name(fname):
 
648
    """Calculate the SHA1 of a file by reading the full text"""
 
649
    s = sha()
 
650
    f = os.open(fname, os.O_RDONLY | O_BINARY)
 
651
    try:
 
652
        while True:
 
653
            b = os.read(f, 1<<16)
 
654
            if not b:
 
655
                return s.hexdigest()
 
656
            s.update(b)
 
657
    finally:
 
658
        os.close(f)
 
659
 
 
660
 
 
661
def sha_strings(strings, _factory=sha):
522
662
    """Return the sha-1 of concatenation of strings"""
523
 
    s = sha.new()
 
663
    s = _factory()
524
664
    map(s.update, strings)
525
665
    return s.hexdigest()
526
666
 
527
667
 
528
 
def sha_string(f):
529
 
    s = sha.new()
530
 
    s.update(f)
531
 
    return s.hexdigest()
 
668
def sha_string(f, _factory=sha):
 
669
    return _factory(f).hexdigest()
532
670
 
533
671
 
534
672
def fingerprint_file(f):
535
 
    s = sha.new()
536
673
    b = f.read()
537
 
    s.update(b)
538
 
    size = len(b)
539
 
    return {'size': size,
540
 
            'sha1': s.hexdigest()}
 
674
    return {'size': len(b),
 
675
            'sha1': sha(b).hexdigest()}
541
676
 
542
677
 
543
678
def compare_files(a, b):
554
689
 
555
690
def local_time_offset(t=None):
556
691
    """Return offset of local zone from GMT, either at present or at time t."""
557
 
    # python2.3 localtime() can't take None
558
692
    if t is None:
559
693
        t = time.time()
560
 
        
561
 
    if time.localtime(t).tm_isdst and time.daylight:
562
 
        return -time.altzone
563
 
    else:
564
 
        return -time.timezone
565
 
 
566
 
    
567
 
def format_date(t, offset=0, timezone='original', date_fmt=None, 
 
694
    offset = datetime.fromtimestamp(t) - datetime.utcfromtimestamp(t)
 
695
    return offset.days * 86400 + offset.seconds
 
696
 
 
697
weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
 
698
_default_format_by_weekday_num = [wd + " %Y-%m-%d %H:%M:%S" for wd in weekdays]
 
699
 
 
700
 
 
701
def format_date(t, offset=0, timezone='original', date_fmt=None,
568
702
                show_offset=True):
569
 
    ## TODO: Perhaps a global option to use either universal or local time?
570
 
    ## Or perhaps just let people set $TZ?
571
 
    assert isinstance(t, float)
572
 
    
 
703
    """Return a formatted date string.
 
704
 
 
705
    :param t: Seconds since the epoch.
 
706
    :param offset: Timezone offset in seconds east of utc.
 
707
    :param timezone: How to display the time: 'utc', 'original' for the
 
708
         timezone specified by offset, or 'local' for the process's current
 
709
         timezone.
 
710
    :param date_fmt: strftime format.
 
711
    :param show_offset: Whether to append the timezone.
 
712
    """
 
713
    (date_fmt, tt, offset_str) = \
 
714
               _format_date(t, offset, timezone, date_fmt, show_offset)
 
715
    date_fmt = date_fmt.replace('%a', weekdays[tt[6]])
 
716
    date_str = time.strftime(date_fmt, tt)
 
717
    return date_str + offset_str
 
718
 
 
719
 
 
720
# Cache of formatted offset strings
 
721
_offset_cache = {}
 
722
 
 
723
 
 
724
def format_date_with_offset_in_original_timezone(t, offset=0,
 
725
    _cache=_offset_cache):
 
726
    """Return a formatted date string in the original timezone.
 
727
 
 
728
    This routine may be faster then format_date.
 
729
 
 
730
    :param t: Seconds since the epoch.
 
731
    :param offset: Timezone offset in seconds east of utc.
 
732
    """
 
733
    if offset is None:
 
734
        offset = 0
 
735
    tt = time.gmtime(t + offset)
 
736
    date_fmt = _default_format_by_weekday_num[tt[6]]
 
737
    date_str = time.strftime(date_fmt, tt)
 
738
    offset_str = _cache.get(offset, None)
 
739
    if offset_str is None:
 
740
        offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
 
741
        _cache[offset] = offset_str
 
742
    return date_str + offset_str
 
743
 
 
744
 
 
745
def format_local_date(t, offset=0, timezone='original', date_fmt=None,
 
746
                      show_offset=True):
 
747
    """Return an unicode date string formatted according to the current locale.
 
748
 
 
749
    :param t: Seconds since the epoch.
 
750
    :param offset: Timezone offset in seconds east of utc.
 
751
    :param timezone: How to display the time: 'utc', 'original' for the
 
752
         timezone specified by offset, or 'local' for the process's current
 
753
         timezone.
 
754
    :param date_fmt: strftime format.
 
755
    :param show_offset: Whether to append the timezone.
 
756
    """
 
757
    (date_fmt, tt, offset_str) = \
 
758
               _format_date(t, offset, timezone, date_fmt, show_offset)
 
759
    date_str = time.strftime(date_fmt, tt)
 
760
    if not isinstance(date_str, unicode):
 
761
        date_str = date_str.decode(get_user_encoding(), 'replace')
 
762
    return date_str + offset_str
 
763
 
 
764
 
 
765
def _format_date(t, offset, timezone, date_fmt, show_offset):
573
766
    if timezone == 'utc':
574
767
        tt = time.gmtime(t)
575
768
        offset = 0
581
774
        tt = time.localtime(t)
582
775
        offset = local_time_offset(t)
583
776
    else:
584
 
        raise BzrError("unsupported timezone format %r" % timezone,
585
 
                       ['options are "utc", "original", "local"'])
 
777
        raise errors.UnsupportedTimezoneFormat(timezone)
586
778
    if date_fmt is None:
587
779
        date_fmt = "%a %Y-%m-%d %H:%M:%S"
588
780
    if show_offset:
589
781
        offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
590
782
    else:
591
783
        offset_str = ''
592
 
    return (time.strftime(date_fmt, tt) +  offset_str)
 
784
    return (date_fmt, tt, offset_str)
593
785
 
594
786
 
595
787
def compact_date(when):
596
788
    return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
597
 
    
598
 
 
 
789
 
 
790
 
 
791
def format_delta(delta):
 
792
    """Get a nice looking string for a time delta.
 
793
 
 
794
    :param delta: The time difference in seconds, can be positive or negative.
 
795
        positive indicates time in the past, negative indicates time in the
 
796
        future. (usually time.time() - stored_time)
 
797
    :return: String formatted to show approximate resolution
 
798
    """
 
799
    delta = int(delta)
 
800
    if delta >= 0:
 
801
        direction = 'ago'
 
802
    else:
 
803
        direction = 'in the future'
 
804
        delta = -delta
 
805
 
 
806
    seconds = delta
 
807
    if seconds < 90: # print seconds up to 90 seconds
 
808
        if seconds == 1:
 
809
            return '%d second %s' % (seconds, direction,)
 
810
        else:
 
811
            return '%d seconds %s' % (seconds, direction)
 
812
 
 
813
    minutes = int(seconds / 60)
 
814
    seconds -= 60 * minutes
 
815
    if seconds == 1:
 
816
        plural_seconds = ''
 
817
    else:
 
818
        plural_seconds = 's'
 
819
    if minutes < 90: # print minutes, seconds up to 90 minutes
 
820
        if minutes == 1:
 
821
            return '%d minute, %d second%s %s' % (
 
822
                    minutes, seconds, plural_seconds, direction)
 
823
        else:
 
824
            return '%d minutes, %d second%s %s' % (
 
825
                    minutes, seconds, plural_seconds, direction)
 
826
 
 
827
    hours = int(minutes / 60)
 
828
    minutes -= 60 * hours
 
829
    if minutes == 1:
 
830
        plural_minutes = ''
 
831
    else:
 
832
        plural_minutes = 's'
 
833
 
 
834
    if hours == 1:
 
835
        return '%d hour, %d minute%s %s' % (hours, minutes,
 
836
                                            plural_minutes, direction)
 
837
    return '%d hours, %d minute%s %s' % (hours, minutes,
 
838
                                         plural_minutes, direction)
599
839
 
600
840
def filesize(f):
601
841
    """Return size of given open file."""
611
851
except (NotImplementedError, AttributeError):
612
852
    # If python doesn't have os.urandom, or it doesn't work,
613
853
    # then try to first pull random data from /dev/urandom
614
 
    if os.path.exists("/dev/urandom"):
 
854
    try:
615
855
        rand_bytes = file('/dev/urandom', 'rb').read
616
856
    # Otherwise, use this hack as a last resort
617
 
    else:
 
857
    except (IOError, OSError):
618
858
        # not well seeded, but better than nothing
619
859
        def rand_bytes(n):
620
860
            import random
628
868
ALNUM = '0123456789abcdefghijklmnopqrstuvwxyz'
629
869
def rand_chars(num):
630
870
    """Return a random string of num alphanumeric characters
631
 
    
632
 
    The result only contains lowercase chars because it may be used on 
 
871
 
 
872
    The result only contains lowercase chars because it may be used on
633
873
    case-insensitive filesystems.
634
874
    """
635
875
    s = ''
642
882
## decomposition (might be too tricksy though.)
643
883
 
644
884
def splitpath(p):
645
 
    """Turn string into list of parts.
646
 
 
647
 
    >>> splitpath('a')
648
 
    ['a']
649
 
    >>> splitpath('a/b')
650
 
    ['a', 'b']
651
 
    >>> splitpath('a/./b')
652
 
    ['a', 'b']
653
 
    >>> splitpath('a/.b')
654
 
    ['a', '.b']
655
 
    >>> splitpath('a/../b')
656
 
    Traceback (most recent call last):
657
 
    ...
658
 
    BzrError: sorry, '..' not allowed in path
659
 
    """
660
 
    assert isinstance(p, types.StringTypes)
661
 
 
 
885
    """Turn string into list of parts."""
662
886
    # split on either delimiter because people might use either on
663
887
    # Windows
664
888
    ps = re.split(r'[\\/]', p)
666
890
    rps = []
667
891
    for f in ps:
668
892
        if f == '..':
669
 
            raise BzrError("sorry, %r not allowed in path" % f)
 
893
            raise errors.BzrError("sorry, %r not allowed in path" % f)
670
894
        elif (f == '.') or (f == ''):
671
895
            pass
672
896
        else:
673
897
            rps.append(f)
674
898
    return rps
675
899
 
 
900
 
676
901
def joinpath(p):
677
 
    assert isinstance(p, list)
678
902
    for f in p:
679
903
        if (f == '..') or (f is None) or (f == ''):
680
 
            raise BzrError("sorry, %r not allowed in path" % f)
 
904
            raise errors.BzrError("sorry, %r not allowed in path" % f)
681
905
    return pathjoin(*p)
682
906
 
683
907
 
684
 
@deprecated_function(zero_nine)
685
 
def appendpath(p1, p2):
686
 
    if p1 == '':
687
 
        return p2
688
 
    else:
689
 
        return pathjoin(p1, p2)
690
 
    
 
908
def parent_directories(filename):
 
909
    """Return the list of parent directories, deepest first.
 
910
    
 
911
    For example, parent_directories("a/b/c") -> ["a/b", "a"].
 
912
    """
 
913
    parents = []
 
914
    parts = splitpath(dirname(filename))
 
915
    while parts:
 
916
        parents.append(joinpath(parts))
 
917
        parts.pop()
 
918
    return parents
 
919
 
 
920
 
 
921
_extension_load_failures = []
 
922
 
 
923
 
 
924
def failed_to_load_extension(exception):
 
925
    """Handle failing to load a binary extension.
 
926
 
 
927
    This should be called from the ImportError block guarding the attempt to
 
928
    import the native extension.  If this function returns, the pure-Python
 
929
    implementation should be loaded instead::
 
930
 
 
931
    >>> try:
 
932
    >>>     import bzrlib._fictional_extension_pyx
 
933
    >>> except ImportError, e:
 
934
    >>>     bzrlib.osutils.failed_to_load_extension(e)
 
935
    >>>     import bzrlib._fictional_extension_py
 
936
    """
 
937
    # NB: This docstring is just an example, not a doctest, because doctest
 
938
    # currently can't cope with the use of lazy imports in this namespace --
 
939
    # mbp 20090729
 
940
    
 
941
    # This currently doesn't report the failure at the time it occurs, because
 
942
    # they tend to happen very early in startup when we can't check config
 
943
    # files etc, and also we want to report all failures but not spam the user
 
944
    # with 10 warnings.
 
945
    from bzrlib import trace
 
946
    exception_str = str(exception)
 
947
    if exception_str not in _extension_load_failures:
 
948
        trace.mutter("failed to load compiled extension: %s" % exception_str)
 
949
        _extension_load_failures.append(exception_str)
 
950
 
 
951
 
 
952
def report_extension_load_failures():
 
953
    if not _extension_load_failures:
 
954
        return
 
955
    from bzrlib.config import GlobalConfig
 
956
    if GlobalConfig().get_user_option_as_bool('ignore_missing_extensions'):
 
957
        return
 
958
    # the warnings framework should by default show this only once
 
959
    from bzrlib.trace import warning
 
960
    warning(
 
961
        "bzr: warning: some compiled extensions could not be loaded; "
 
962
        "see <https://answers.launchpad.net/bzr/+faq/703>")
 
963
    # we no longer show the specific missing extensions here, because it makes
 
964
    # the message too long and scary - see
 
965
    # https://bugs.launchpad.net/bzr/+bug/430529
 
966
 
 
967
 
 
968
try:
 
969
    from bzrlib._chunks_to_lines_pyx import chunks_to_lines
 
970
except ImportError, e:
 
971
    failed_to_load_extension(e)
 
972
    from bzrlib._chunks_to_lines_py import chunks_to_lines
 
973
 
691
974
 
692
975
def split_lines(s):
693
976
    """Split s into lines, but without removing the newline characters."""
 
977
    # Trivially convert a fulltext into a 'chunked' representation, and let
 
978
    # chunks_to_lines do the heavy lifting.
 
979
    if isinstance(s, str):
 
980
        # chunks_to_lines only supports 8-bit strings
 
981
        return chunks_to_lines([s])
 
982
    else:
 
983
        return _split_lines(s)
 
984
 
 
985
 
 
986
def _split_lines(s):
 
987
    """Split s into lines, but without removing the newline characters.
 
988
 
 
989
    This supports Unicode or plain string objects.
 
990
    """
694
991
    lines = s.split('\n')
695
992
    result = [line + '\n' for line in lines[:-1]]
696
993
    if lines[-1]:
705
1002
def link_or_copy(src, dest):
706
1003
    """Hardlink a file, or copy it if it can't be hardlinked."""
707
1004
    if not hardlinks_good():
708
 
        copyfile(src, dest)
 
1005
        shutil.copyfile(src, dest)
709
1006
        return
710
1007
    try:
711
1008
        os.link(src, dest)
712
1009
    except (OSError, IOError), e:
713
1010
        if e.errno != errno.EXDEV:
714
1011
            raise
715
 
        copyfile(src, dest)
716
 
 
717
 
def delete_any(full_path):
718
 
    """Delete a file or directory."""
 
1012
        shutil.copyfile(src, dest)
 
1013
 
 
1014
 
 
1015
def delete_any(path):
 
1016
    """Delete a file, symlink or directory.  
 
1017
    
 
1018
    Will delete even if readonly.
 
1019
    """
719
1020
    try:
720
 
        os.unlink(full_path)
721
 
    except OSError, e:
722
 
    # We may be renaming a dangling inventory id
723
 
        if e.errno not in (errno.EISDIR, errno.EACCES, errno.EPERM):
 
1021
       _delete_file_or_dir(path)
 
1022
    except (OSError, IOError), e:
 
1023
        if e.errno in (errno.EPERM, errno.EACCES):
 
1024
            # make writable and try again
 
1025
            try:
 
1026
                make_writable(path)
 
1027
            except (OSError, IOError):
 
1028
                pass
 
1029
            _delete_file_or_dir(path)
 
1030
        else:
724
1031
            raise
725
 
        os.rmdir(full_path)
 
1032
 
 
1033
 
 
1034
def _delete_file_or_dir(path):
 
1035
    # Look Before You Leap (LBYL) is appropriate here instead of Easier to Ask for
 
1036
    # Forgiveness than Permission (EAFP) because:
 
1037
    # - root can damage a solaris file system by using unlink,
 
1038
    # - unlink raises different exceptions on different OSes (linux: EISDIR, win32:
 
1039
    #   EACCES, OSX: EPERM) when invoked on a directory.
 
1040
    if isdir(path): # Takes care of symlinks
 
1041
        os.rmdir(path)
 
1042
    else:
 
1043
        os.unlink(path)
726
1044
 
727
1045
 
728
1046
def has_symlinks():
730
1048
        return True
731
1049
    else:
732
1050
        return False
733
 
        
 
1051
 
 
1052
 
 
1053
def has_hardlinks():
 
1054
    if getattr(os, 'link', None) is not None:
 
1055
        return True
 
1056
    else:
 
1057
        return False
 
1058
 
 
1059
 
 
1060
def host_os_dereferences_symlinks():
 
1061
    return (has_symlinks()
 
1062
            and sys.platform not in ('cygwin', 'win32'))
 
1063
 
 
1064
 
 
1065
def readlink(abspath):
 
1066
    """Return a string representing the path to which the symbolic link points.
 
1067
 
 
1068
    :param abspath: The link absolute unicode path.
 
1069
 
 
1070
    This his guaranteed to return the symbolic link in unicode in all python
 
1071
    versions.
 
1072
    """
 
1073
    link = abspath.encode(_fs_enc)
 
1074
    target = os.readlink(link)
 
1075
    target = target.decode(_fs_enc)
 
1076
    return target
 
1077
 
734
1078
 
735
1079
def contains_whitespace(s):
736
1080
    """True if there are any whitespace characters in s."""
737
 
    for ch in string.whitespace:
 
1081
    # string.whitespace can include '\xa0' in certain locales, because it is
 
1082
    # considered "non-breaking-space" as part of ISO-8859-1. But it
 
1083
    # 1) Isn't a breaking whitespace
 
1084
    # 2) Isn't one of ' \t\r\n' which are characters we sometimes use as
 
1085
    #    separators
 
1086
    # 3) '\xa0' isn't unicode safe since it is >128.
 
1087
 
 
1088
    # This should *not* be a unicode set of characters in case the source
 
1089
    # string is not a Unicode string. We can auto-up-cast the characters since
 
1090
    # they are ascii, but we don't want to auto-up-cast the string in case it
 
1091
    # is utf-8
 
1092
    for ch in ' \t\n\r\v\f':
738
1093
        if ch in s:
739
1094
            return True
740
1095
    else:
761
1116
    avoids that problem.
762
1117
    """
763
1118
 
764
 
    assert len(base) >= MIN_ABS_PATHLENGTH, ('Length of base must be equal or'
765
 
        ' exceed the platform minimum length (which is %d)' % 
766
 
        MIN_ABS_PATHLENGTH)
 
1119
    if len(base) < MIN_ABS_PATHLENGTH:
 
1120
        # must have space for e.g. a drive letter
 
1121
        raise ValueError('%r is too short to calculate a relative path'
 
1122
            % (base,))
767
1123
 
768
1124
    rp = abspath(path)
769
1125
 
770
1126
    s = []
771
1127
    head = rp
772
 
    while len(head) >= len(base):
 
1128
    while True:
 
1129
        if len(head) <= len(base) and head != base:
 
1130
            raise errors.PathNotChild(rp, base)
773
1131
        if head == base:
774
1132
            break
775
 
        head, tail = os.path.split(head)
 
1133
        head, tail = split(head)
776
1134
        if tail:
777
 
            s.insert(0, tail)
778
 
    else:
779
 
        raise PathNotChild(rp, base)
 
1135
            s.append(tail)
780
1136
 
781
1137
    if s:
782
 
        return pathjoin(*s)
 
1138
        return pathjoin(*reversed(s))
783
1139
    else:
784
1140
        return ''
785
1141
 
786
1142
 
 
1143
def _cicp_canonical_relpath(base, path):
 
1144
    """Return the canonical path relative to base.
 
1145
 
 
1146
    Like relpath, but on case-insensitive-case-preserving file-systems, this
 
1147
    will return the relpath as stored on the file-system rather than in the
 
1148
    case specified in the input string, for all existing portions of the path.
 
1149
 
 
1150
    This will cause O(N) behaviour if called for every path in a tree; if you
 
1151
    have a number of paths to convert, you should use canonical_relpaths().
 
1152
    """
 
1153
    # TODO: it should be possible to optimize this for Windows by using the
 
1154
    # win32 API FindFiles function to look for the specified name - but using
 
1155
    # os.listdir() still gives us the correct, platform agnostic semantics in
 
1156
    # the short term.
 
1157
 
 
1158
    rel = relpath(base, path)
 
1159
    # '.' will have been turned into ''
 
1160
    if not rel:
 
1161
        return rel
 
1162
 
 
1163
    abs_base = abspath(base)
 
1164
    current = abs_base
 
1165
    _listdir = os.listdir
 
1166
 
 
1167
    # use an explicit iterator so we can easily consume the rest on early exit.
 
1168
    bit_iter = iter(rel.split('/'))
 
1169
    for bit in bit_iter:
 
1170
        lbit = bit.lower()
 
1171
        try:
 
1172
            next_entries = _listdir(current)
 
1173
        except OSError: # enoent, eperm, etc
 
1174
            # We can't find this in the filesystem, so just append the
 
1175
            # remaining bits.
 
1176
            current = pathjoin(current, bit, *list(bit_iter))
 
1177
            break
 
1178
        for look in next_entries:
 
1179
            if lbit == look.lower():
 
1180
                current = pathjoin(current, look)
 
1181
                break
 
1182
        else:
 
1183
            # got to the end, nothing matched, so we just return the
 
1184
            # non-existing bits as they were specified (the filename may be
 
1185
            # the target of a move, for example).
 
1186
            current = pathjoin(current, bit, *list(bit_iter))
 
1187
            break
 
1188
    return current[len(abs_base):].lstrip('/')
 
1189
 
 
1190
# XXX - TODO - we need better detection/integration of case-insensitive
 
1191
# file-systems; Linux often sees FAT32 devices (or NFS-mounted OSX
 
1192
# filesystems), for example, so could probably benefit from the same basic
 
1193
# support there.  For now though, only Windows and OSX get that support, and
 
1194
# they get it for *all* file-systems!
 
1195
if sys.platform in ('win32', 'darwin'):
 
1196
    canonical_relpath = _cicp_canonical_relpath
 
1197
else:
 
1198
    canonical_relpath = relpath
 
1199
 
 
1200
def canonical_relpaths(base, paths):
 
1201
    """Create an iterable to canonicalize a sequence of relative paths.
 
1202
 
 
1203
    The intent is for this implementation to use a cache, vastly speeding
 
1204
    up multiple transformations in the same directory.
 
1205
    """
 
1206
    # but for now, we haven't optimized...
 
1207
    return [canonical_relpath(base, p) for p in paths]
 
1208
 
787
1209
def safe_unicode(unicode_or_utf8_string):
788
1210
    """Coerce unicode_or_utf8_string into unicode.
789
1211
 
790
1212
    If it is unicode, it is returned.
791
 
    Otherwise it is decoded from utf-8. If a decoding error
792
 
    occurs, it is wrapped as a If the decoding fails, the exception is wrapped 
793
 
    as a BzrBadParameter exception.
 
1213
    Otherwise it is decoded from utf-8. If decoding fails, the exception is
 
1214
    wrapped in a BzrBadParameterNotUnicode exception.
794
1215
    """
795
1216
    if isinstance(unicode_or_utf8_string, unicode):
796
1217
        return unicode_or_utf8_string
797
1218
    try:
798
1219
        return unicode_or_utf8_string.decode('utf8')
799
1220
    except UnicodeDecodeError:
800
 
        raise BzrBadParameterNotUnicode(unicode_or_utf8_string)
 
1221
        raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
 
1222
 
 
1223
 
 
1224
def safe_utf8(unicode_or_utf8_string):
 
1225
    """Coerce unicode_or_utf8_string to a utf8 string.
 
1226
 
 
1227
    If it is a str, it is returned.
 
1228
    If it is Unicode, it is encoded into a utf-8 string.
 
1229
    """
 
1230
    if isinstance(unicode_or_utf8_string, str):
 
1231
        # TODO: jam 20070209 This is overkill, and probably has an impact on
 
1232
        #       performance if we are dealing with lots of apis that want a
 
1233
        #       utf-8 revision id
 
1234
        try:
 
1235
            # Make sure it is a valid utf-8 string
 
1236
            unicode_or_utf8_string.decode('utf-8')
 
1237
        except UnicodeDecodeError:
 
1238
            raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
 
1239
        return unicode_or_utf8_string
 
1240
    return unicode_or_utf8_string.encode('utf-8')
 
1241
 
 
1242
 
 
1243
_revision_id_warning = ('Unicode revision ids were deprecated in bzr 0.15.'
 
1244
                        ' Revision id generators should be creating utf8'
 
1245
                        ' revision ids.')
 
1246
 
 
1247
 
 
1248
def safe_revision_id(unicode_or_utf8_string, warn=True):
 
1249
    """Revision ids should now be utf8, but at one point they were unicode.
 
1250
 
 
1251
    :param unicode_or_utf8_string: A possibly Unicode revision_id. (can also be
 
1252
        utf8 or None).
 
1253
    :param warn: Functions that are sanitizing user data can set warn=False
 
1254
    :return: None or a utf8 revision id.
 
1255
    """
 
1256
    if (unicode_or_utf8_string is None
 
1257
        or unicode_or_utf8_string.__class__ == str):
 
1258
        return unicode_or_utf8_string
 
1259
    if warn:
 
1260
        symbol_versioning.warn(_revision_id_warning, DeprecationWarning,
 
1261
                               stacklevel=2)
 
1262
    return cache_utf8.encode(unicode_or_utf8_string)
 
1263
 
 
1264
 
 
1265
_file_id_warning = ('Unicode file ids were deprecated in bzr 0.15. File id'
 
1266
                    ' generators should be creating utf8 file ids.')
 
1267
 
 
1268
 
 
1269
def safe_file_id(unicode_or_utf8_string, warn=True):
 
1270
    """File ids should now be utf8, but at one point they were unicode.
 
1271
 
 
1272
    This is the same as safe_utf8, except it uses the cached encode functions
 
1273
    to save a little bit of performance.
 
1274
 
 
1275
    :param unicode_or_utf8_string: A possibly Unicode file_id. (can also be
 
1276
        utf8 or None).
 
1277
    :param warn: Functions that are sanitizing user data can set warn=False
 
1278
    :return: None or a utf8 file id.
 
1279
    """
 
1280
    if (unicode_or_utf8_string is None
 
1281
        or unicode_or_utf8_string.__class__ == str):
 
1282
        return unicode_or_utf8_string
 
1283
    if warn:
 
1284
        symbol_versioning.warn(_file_id_warning, DeprecationWarning,
 
1285
                               stacklevel=2)
 
1286
    return cache_utf8.encode(unicode_or_utf8_string)
801
1287
 
802
1288
 
803
1289
_platform_normalizes_filenames = False
818
1304
 
819
1305
    On platforms where the system normalizes filenames (Mac OSX),
820
1306
    you can access a file by any path which will normalize correctly.
821
 
    On platforms where the system does not normalize filenames 
 
1307
    On platforms where the system does not normalize filenames
822
1308
    (Windows, Linux), you have to access a file by its exact path.
823
1309
 
824
 
    Internally, bzr only supports NFC/NFKC normalization, since that is 
 
1310
    Internally, bzr only supports NFC normalization, since that is
825
1311
    the standard for XML documents.
826
1312
 
827
1313
    So return the normalized path, and a flag indicating if the file
828
1314
    can be accessed by that path.
829
1315
    """
830
1316
 
831
 
    return unicodedata.normalize('NFKC', unicode(path)), True
 
1317
    return unicodedata.normalize('NFC', unicode(path)), True
832
1318
 
833
1319
 
834
1320
def _inaccessible_normalized_filename(path):
835
1321
    __doc__ = _accessible_normalized_filename.__doc__
836
1322
 
837
 
    normalized = unicodedata.normalize('NFKC', unicode(path))
 
1323
    normalized = unicodedata.normalize('NFC', unicode(path))
838
1324
    return normalized, normalized == path
839
1325
 
840
1326
 
844
1330
    normalized_filename = _inaccessible_normalized_filename
845
1331
 
846
1332
 
 
1333
default_terminal_width = 80
 
1334
"""The default terminal width for ttys.
 
1335
 
 
1336
This is defined so that higher levels can share a common fallback value when
 
1337
terminal_width() returns None.
 
1338
"""
 
1339
 
 
1340
 
847
1341
def terminal_width():
848
 
    """Return estimated terminal width."""
 
1342
    """Return terminal width.
 
1343
 
 
1344
    None is returned if the width can't established precisely.
 
1345
    """
 
1346
 
 
1347
    # If BZR_COLUMNS is set, take it, user is always right
 
1348
    try:
 
1349
        return int(os.environ['BZR_COLUMNS'])
 
1350
    except (KeyError, ValueError):
 
1351
        pass
 
1352
 
 
1353
    isatty = getattr(sys.stdout, 'isatty', None)
 
1354
    if  isatty is None or not isatty():
 
1355
        # Don't guess, setting BZR_COLUMNS is the recommended way to override.
 
1356
        return None
 
1357
 
849
1358
    if sys.platform == 'win32':
850
 
        import bzrlib.win32console
851
 
        return bzrlib.win32console.get_console_size()[0]
852
 
    width = 0
 
1359
        return win32utils.get_console_size(defaultx=None)[0]
 
1360
 
853
1361
    try:
854
1362
        import struct, fcntl, termios
855
1363
        s = struct.pack('HHHH', 0, 0, 0, 0)
856
1364
        x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
857
1365
        width = struct.unpack('HHHH', x)[1]
858
 
    except IOError:
859
 
        pass
860
 
    if width <= 0:
 
1366
    except (IOError, AttributeError):
 
1367
        # If COLUMNS is set, take it
861
1368
        try:
862
 
            width = int(os.environ['COLUMNS'])
863
 
        except:
864
 
            pass
 
1369
            return int(os.environ['COLUMNS'])
 
1370
        except (KeyError, ValueError):
 
1371
            return None
 
1372
 
865
1373
    if width <= 0:
866
 
        width = 80
 
1374
        # Consider invalid values as meaning no width
 
1375
        return None
867
1376
 
868
1377
    return width
869
1378
 
872
1381
    return sys.platform != "win32"
873
1382
 
874
1383
 
 
1384
def supports_posix_readonly():
 
1385
    """Return True if 'readonly' has POSIX semantics, False otherwise.
 
1386
 
 
1387
    Notably, a win32 readonly file cannot be deleted, unlike POSIX where the
 
1388
    directory controls creation/deletion, etc.
 
1389
 
 
1390
    And under win32, readonly means that the directory itself cannot be
 
1391
    deleted.  The contents of a readonly directory can be changed, unlike POSIX
 
1392
    where files in readonly directories cannot be added, deleted or renamed.
 
1393
    """
 
1394
    return sys.platform != "win32"
 
1395
 
 
1396
 
875
1397
def set_or_unset_env(env_variable, value):
876
1398
    """Modify the environment, setting or removing the env_variable.
877
1399
 
886
1408
            del os.environ[env_variable]
887
1409
    else:
888
1410
        if isinstance(value, unicode):
889
 
            value = value.encode(bzrlib.user_encoding)
 
1411
            value = value.encode(get_user_encoding())
890
1412
        os.environ[env_variable] = value
891
1413
    return orig_val
892
1414
 
895
1417
 
896
1418
 
897
1419
def check_legal_path(path):
898
 
    """Check whether the supplied path is legal.  
 
1420
    """Check whether the supplied path is legal.
899
1421
    This is only required on Windows, so we don't test on other platforms
900
1422
    right now.
901
1423
    """
902
1424
    if sys.platform != "win32":
903
1425
        return
904
1426
    if _validWin32PathRE.match(path) is None:
905
 
        raise IllegalPath(path)
 
1427
        raise errors.IllegalPath(path)
 
1428
 
 
1429
 
 
1430
_WIN32_ERROR_DIRECTORY = 267 # Similar to errno.ENOTDIR
 
1431
 
 
1432
def _is_error_enotdir(e):
 
1433
    """Check if this exception represents ENOTDIR.
 
1434
 
 
1435
    Unfortunately, python is very inconsistent about the exception
 
1436
    here. The cases are:
 
1437
      1) Linux, Mac OSX all versions seem to set errno == ENOTDIR
 
1438
      2) Windows, Python2.4, uses errno == ERROR_DIRECTORY (267)
 
1439
         which is the windows error code.
 
1440
      3) Windows, Python2.5 uses errno == EINVAL and
 
1441
         winerror == ERROR_DIRECTORY
 
1442
 
 
1443
    :param e: An Exception object (expected to be OSError with an errno
 
1444
        attribute, but we should be able to cope with anything)
 
1445
    :return: True if this represents an ENOTDIR error. False otherwise.
 
1446
    """
 
1447
    en = getattr(e, 'errno', None)
 
1448
    if (en == errno.ENOTDIR
 
1449
        or (sys.platform == 'win32'
 
1450
            and (en == _WIN32_ERROR_DIRECTORY
 
1451
                 or (en == errno.EINVAL
 
1452
                     and getattr(e, 'winerror', None) == _WIN32_ERROR_DIRECTORY)
 
1453
        ))):
 
1454
        return True
 
1455
    return False
906
1456
 
907
1457
 
908
1458
def walkdirs(top, prefix=""):
909
1459
    """Yield data about all the directories in a tree.
910
 
    
 
1460
 
911
1461
    This yields all the data about the contents of a directory at a time.
912
1462
    After each directory has been yielded, if the caller has mutated the list
913
1463
    to exclude some directories, they are then not descended into.
914
 
    
 
1464
 
915
1465
    The data yielded is of the form:
916
1466
    ((directory-relpath, directory-path-from-top),
917
 
    [(relpath, basename, kind, lstat), ...]),
 
1467
    [(relpath, basename, kind, lstat, path-from-top), ...]),
918
1468
     - directory-relpath is the relative path of the directory being returned
919
1469
       with respect to top. prefix is prepended to this.
920
 
     - directory-path-from-root is the path including top for this directory. 
 
1470
     - directory-path-from-root is the path including top for this directory.
921
1471
       It is suitable for use with os functions.
922
1472
     - relpath is the relative path within the subtree being walked.
923
1473
     - basename is the basename of the path
925
1475
       present within the tree - but it may be recorded as versioned. See
926
1476
       versioned_kind.
927
1477
     - lstat is the stat data *if* the file was statted.
928
 
     - planned, not implemented: 
 
1478
     - planned, not implemented:
929
1479
       path_from_tree_root is the path from the root of the tree.
930
1480
 
931
 
    :param prefix: Prefix the relpaths that are yielded with 'prefix'. This 
 
1481
    :param prefix: Prefix the relpaths that are yielded with 'prefix'. This
932
1482
        allows one to walk a subtree but get paths that are relative to a tree
933
1483
        rooted higher up.
934
1484
    :return: an iterator over the dirs.
935
1485
    """
936
1486
    #TODO there is a bit of a smell where the results of the directory-
937
 
    # summary in this, and the path from the root, may not agree 
 
1487
    # summary in this, and the path from the root, may not agree
938
1488
    # depending on top and prefix - i.e. ./foo and foo as a pair leads to
939
1489
    # potentially confusing output. We should make this more robust - but
940
1490
    # not at a speed cost. RBC 20060731
941
 
    lstat = os.lstat
942
 
    pending = []
 
1491
    _lstat = os.lstat
943
1492
    _directory = _directory_kind
944
 
    _listdir = listdir
945
 
    pending = [(prefix, "", _directory, None, top)]
 
1493
    _listdir = os.listdir
 
1494
    _kind_from_mode = file_kind_from_stat_mode
 
1495
    pending = [(safe_unicode(prefix), "", _directory, None, safe_unicode(top))]
946
1496
    while pending:
947
 
        dirblock = []
948
 
        currentdir = pending.pop()
949
1497
        # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
950
 
        top = currentdir[4]
951
 
        if currentdir[0]:
952
 
            relroot = currentdir[0] + '/'
953
 
        else:
954
 
            relroot = ""
 
1498
        relroot, _, _, _, top = pending.pop()
 
1499
        if relroot:
 
1500
            relprefix = relroot + u'/'
 
1501
        else:
 
1502
            relprefix = ''
 
1503
        top_slash = top + u'/'
 
1504
 
 
1505
        dirblock = []
 
1506
        append = dirblock.append
 
1507
        try:
 
1508
            names = sorted(_listdir(top))
 
1509
        except OSError, e:
 
1510
            if not _is_error_enotdir(e):
 
1511
                raise
 
1512
        else:
 
1513
            for name in names:
 
1514
                abspath = top_slash + name
 
1515
                statvalue = _lstat(abspath)
 
1516
                kind = _kind_from_mode(statvalue.st_mode)
 
1517
                append((relprefix + name, name, kind, statvalue, abspath))
 
1518
        yield (relroot, top), dirblock
 
1519
 
 
1520
        # push the user specified dirs from dirblock
 
1521
        pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
 
1522
 
 
1523
 
 
1524
class DirReader(object):
 
1525
    """An interface for reading directories."""
 
1526
 
 
1527
    def top_prefix_to_starting_dir(self, top, prefix=""):
 
1528
        """Converts top and prefix to a starting dir entry
 
1529
 
 
1530
        :param top: A utf8 path
 
1531
        :param prefix: An optional utf8 path to prefix output relative paths
 
1532
            with.
 
1533
        :return: A tuple starting with prefix, and ending with the native
 
1534
            encoding of top.
 
1535
        """
 
1536
        raise NotImplementedError(self.top_prefix_to_starting_dir)
 
1537
 
 
1538
    def read_dir(self, prefix, top):
 
1539
        """Read a specific dir.
 
1540
 
 
1541
        :param prefix: A utf8 prefix to be preprended to the path basenames.
 
1542
        :param top: A natively encoded path to read.
 
1543
        :return: A list of the directories contents. Each item contains:
 
1544
            (utf8_relpath, utf8_name, kind, lstatvalue, native_abspath)
 
1545
        """
 
1546
        raise NotImplementedError(self.read_dir)
 
1547
 
 
1548
 
 
1549
_selected_dir_reader = None
 
1550
 
 
1551
 
 
1552
def _walkdirs_utf8(top, prefix=""):
 
1553
    """Yield data about all the directories in a tree.
 
1554
 
 
1555
    This yields the same information as walkdirs() only each entry is yielded
 
1556
    in utf-8. On platforms which have a filesystem encoding of utf8 the paths
 
1557
    are returned as exact byte-strings.
 
1558
 
 
1559
    :return: yields a tuple of (dir_info, [file_info])
 
1560
        dir_info is (utf8_relpath, path-from-top)
 
1561
        file_info is (utf8_relpath, utf8_name, kind, lstat, path-from-top)
 
1562
        if top is an absolute path, path-from-top is also an absolute path.
 
1563
        path-from-top might be unicode or utf8, but it is the correct path to
 
1564
        pass to os functions to affect the file in question. (such as os.lstat)
 
1565
    """
 
1566
    global _selected_dir_reader
 
1567
    if _selected_dir_reader is None:
 
1568
        fs_encoding = _fs_enc.upper()
 
1569
        if sys.platform == "win32" and win32utils.winver == 'Windows NT':
 
1570
            # Win98 doesn't have unicode apis like FindFirstFileW
 
1571
            # TODO: We possibly could support Win98 by falling back to the
 
1572
            #       original FindFirstFile, and using TCHAR instead of WCHAR,
 
1573
            #       but that gets a bit tricky, and requires custom compiling
 
1574
            #       for win98 anyway.
 
1575
            try:
 
1576
                from bzrlib._walkdirs_win32 import Win32ReadDir
 
1577
                _selected_dir_reader = Win32ReadDir()
 
1578
            except ImportError:
 
1579
                pass
 
1580
        elif fs_encoding in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
 
1581
            # ANSI_X3.4-1968 is a form of ASCII
 
1582
            try:
 
1583
                from bzrlib._readdir_pyx import UTF8DirReader
 
1584
                _selected_dir_reader = UTF8DirReader()
 
1585
            except ImportError, e:
 
1586
                failed_to_load_extension(e)
 
1587
                pass
 
1588
 
 
1589
    if _selected_dir_reader is None:
 
1590
        # Fallback to the python version
 
1591
        _selected_dir_reader = UnicodeDirReader()
 
1592
 
 
1593
    # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
 
1594
    # But we don't actually uses 1-3 in pending, so set them to None
 
1595
    pending = [[_selected_dir_reader.top_prefix_to_starting_dir(top, prefix)]]
 
1596
    read_dir = _selected_dir_reader.read_dir
 
1597
    _directory = _directory_kind
 
1598
    while pending:
 
1599
        relroot, _, _, _, top = pending[-1].pop()
 
1600
        if not pending[-1]:
 
1601
            pending.pop()
 
1602
        dirblock = sorted(read_dir(relroot, top))
 
1603
        yield (relroot, top), dirblock
 
1604
        # push the user specified dirs from dirblock
 
1605
        next = [d for d in reversed(dirblock) if d[2] == _directory]
 
1606
        if next:
 
1607
            pending.append(next)
 
1608
 
 
1609
 
 
1610
class UnicodeDirReader(DirReader):
 
1611
    """A dir reader for non-utf8 file systems, which transcodes."""
 
1612
 
 
1613
    __slots__ = ['_utf8_encode']
 
1614
 
 
1615
    def __init__(self):
 
1616
        self._utf8_encode = codecs.getencoder('utf8')
 
1617
 
 
1618
    def top_prefix_to_starting_dir(self, top, prefix=""):
 
1619
        """See DirReader.top_prefix_to_starting_dir."""
 
1620
        return (safe_utf8(prefix), None, None, None, safe_unicode(top))
 
1621
 
 
1622
    def read_dir(self, prefix, top):
 
1623
        """Read a single directory from a non-utf8 file system.
 
1624
 
 
1625
        top, and the abspath element in the output are unicode, all other paths
 
1626
        are utf8. Local disk IO is done via unicode calls to listdir etc.
 
1627
 
 
1628
        This is currently the fallback code path when the filesystem encoding is
 
1629
        not UTF-8. It may be better to implement an alternative so that we can
 
1630
        safely handle paths that are not properly decodable in the current
 
1631
        encoding.
 
1632
 
 
1633
        See DirReader.read_dir for details.
 
1634
        """
 
1635
        _utf8_encode = self._utf8_encode
 
1636
        _lstat = os.lstat
 
1637
        _listdir = os.listdir
 
1638
        _kind_from_mode = file_kind_from_stat_mode
 
1639
 
 
1640
        if prefix:
 
1641
            relprefix = prefix + '/'
 
1642
        else:
 
1643
            relprefix = ''
 
1644
        top_slash = top + u'/'
 
1645
 
 
1646
        dirblock = []
 
1647
        append = dirblock.append
955
1648
        for name in sorted(_listdir(top)):
956
 
            abspath = top + '/' + name
957
 
            statvalue = lstat(abspath)
958
 
            dirblock.append((relroot + name, name,
959
 
                file_kind_from_stat_mode(statvalue.st_mode),
960
 
                statvalue, abspath))
961
 
        yield (currentdir[0], top), dirblock
962
 
        # push the user specified dirs from dirblock
963
 
        for dir in reversed(dirblock):
964
 
            if dir[2] == _directory:
965
 
                pending.append(dir)
 
1649
            try:
 
1650
                name_utf8 = _utf8_encode(name)[0]
 
1651
            except UnicodeDecodeError:
 
1652
                raise errors.BadFilenameEncoding(
 
1653
                    _utf8_encode(relprefix)[0] + name, _fs_enc)
 
1654
            abspath = top_slash + name
 
1655
            statvalue = _lstat(abspath)
 
1656
            kind = _kind_from_mode(statvalue.st_mode)
 
1657
            append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
 
1658
        return dirblock
966
1659
 
967
1660
 
968
1661
def copy_tree(from_path, to_path, handlers={}):
969
1662
    """Copy all of the entries in from_path into to_path.
970
1663
 
971
 
    :param from_path: The base directory to copy. 
 
1664
    :param from_path: The base directory to copy.
972
1665
    :param to_path: The target directory. If it does not exist, it will
973
1666
        be created.
974
1667
    :param handlers: A dictionary of functions, which takes a source and
1025
1718
_cached_user_encoding = None
1026
1719
 
1027
1720
 
1028
 
def get_user_encoding():
 
1721
def get_user_encoding(use_cache=True):
1029
1722
    """Find out what the preferred user encoding is.
1030
1723
 
1031
1724
    This is generally the encoding that is used for command line parameters
1032
1725
    and file contents. This may be different from the terminal encoding
1033
1726
    or the filesystem encoding.
1034
1727
 
 
1728
    :param  use_cache:  Enable cache for detected encoding.
 
1729
                        (This parameter is turned on by default,
 
1730
                        and required only for selftesting)
 
1731
 
1035
1732
    :return: A string defining the preferred user encoding
1036
1733
    """
1037
1734
    global _cached_user_encoding
1038
 
    if _cached_user_encoding is not None:
 
1735
    if _cached_user_encoding is not None and use_cache:
1039
1736
        return _cached_user_encoding
1040
1737
 
1041
1738
    if sys.platform == 'darwin':
1042
 
        # work around egregious python 2.4 bug
 
1739
        # python locale.getpreferredencoding() always return
 
1740
        # 'mac-roman' on darwin. That's a lie.
1043
1741
        sys.platform = 'posix'
1044
1742
        try:
 
1743
            if os.environ.get('LANG', None) is None:
 
1744
                # If LANG is not set, we end up with 'ascii', which is bad
 
1745
                # ('mac-roman' is more than ascii), so we set a default which
 
1746
                # will give us UTF-8 (which appears to work in all cases on
 
1747
                # OSX). Users are still free to override LANG of course, as
 
1748
                # long as it give us something meaningful. This work-around
 
1749
                # *may* not be needed with python 3k and/or OSX 10.5, but will
 
1750
                # work with them too -- vila 20080908
 
1751
                os.environ['LANG'] = 'en_US.UTF-8'
1045
1752
            import locale
1046
1753
        finally:
1047
1754
            sys.platform = 'darwin'
1049
1756
        import locale
1050
1757
 
1051
1758
    try:
1052
 
        _cached_user_encoding = locale.getpreferredencoding()
 
1759
        user_encoding = locale.getpreferredencoding()
1053
1760
    except locale.Error, e:
1054
1761
        sys.stderr.write('bzr: warning: %s\n'
1055
1762
                         '  Could not determine what text encoding to use.\n'
1057
1764
                         '  doesn\'t support the locale set by $LANG (%s)\n'
1058
1765
                         "  Continuing with ascii encoding.\n"
1059
1766
                         % (e, os.environ.get('LANG')))
1060
 
 
1061
 
    if _cached_user_encoding is None:
1062
 
        _cached_user_encoding = 'ascii'
1063
 
    return _cached_user_encoding
 
1767
        user_encoding = 'ascii'
 
1768
 
 
1769
    # Windows returns 'cp0' to indicate there is no code page. So we'll just
 
1770
    # treat that as ASCII, and not support printing unicode characters to the
 
1771
    # console.
 
1772
    #
 
1773
    # For python scripts run under vim, we get '', so also treat that as ASCII
 
1774
    if user_encoding in (None, 'cp0', ''):
 
1775
        user_encoding = 'ascii'
 
1776
    else:
 
1777
        # check encoding
 
1778
        try:
 
1779
            codecs.lookup(user_encoding)
 
1780
        except LookupError:
 
1781
            sys.stderr.write('bzr: warning:'
 
1782
                             ' unknown encoding %s.'
 
1783
                             ' Continuing with ascii encoding.\n'
 
1784
                             % user_encoding
 
1785
                            )
 
1786
            user_encoding = 'ascii'
 
1787
 
 
1788
    if use_cache:
 
1789
        _cached_user_encoding = user_encoding
 
1790
 
 
1791
    return user_encoding
 
1792
 
 
1793
 
 
1794
def get_host_name():
 
1795
    """Return the current unicode host name.
 
1796
 
 
1797
    This is meant to be used in place of socket.gethostname() because that
 
1798
    behaves inconsistently on different platforms.
 
1799
    """
 
1800
    if sys.platform == "win32":
 
1801
        import win32utils
 
1802
        return win32utils.get_host_name()
 
1803
    else:
 
1804
        import socket
 
1805
        return socket.gethostname().decode(get_user_encoding())
 
1806
 
 
1807
 
 
1808
def recv_all(socket, bytes):
 
1809
    """Receive an exact number of bytes.
 
1810
 
 
1811
    Regular Socket.recv() may return less than the requested number of bytes,
 
1812
    dependning on what's in the OS buffer.  MSG_WAITALL is not available
 
1813
    on all platforms, but this should work everywhere.  This will return
 
1814
    less than the requested amount if the remote end closes.
 
1815
 
 
1816
    This isn't optimized and is intended mostly for use in testing.
 
1817
    """
 
1818
    b = ''
 
1819
    while len(b) < bytes:
 
1820
        new = until_no_eintr(socket.recv, bytes - len(b))
 
1821
        if new == '':
 
1822
            break # eof
 
1823
        b += new
 
1824
    return b
 
1825
 
 
1826
 
 
1827
def send_all(socket, bytes, report_activity=None):
 
1828
    """Send all bytes on a socket.
 
1829
 
 
1830
    Regular socket.sendall() can give socket error 10053 on Windows.  This
 
1831
    implementation sends no more than 64k at a time, which avoids this problem.
 
1832
 
 
1833
    :param report_activity: Call this as bytes are read, see
 
1834
        Transport._report_activity
 
1835
    """
 
1836
    chunk_size = 2**16
 
1837
    for pos in xrange(0, len(bytes), chunk_size):
 
1838
        block = bytes[pos:pos+chunk_size]
 
1839
        if report_activity is not None:
 
1840
            report_activity(len(block), 'write')
 
1841
        until_no_eintr(socket.sendall, block)
 
1842
 
 
1843
 
 
1844
def dereference_path(path):
 
1845
    """Determine the real path to a file.
 
1846
 
 
1847
    All parent elements are dereferenced.  But the file itself is not
 
1848
    dereferenced.
 
1849
    :param path: The original path.  May be absolute or relative.
 
1850
    :return: the real path *to* the file
 
1851
    """
 
1852
    parent, base = os.path.split(path)
 
1853
    # The pathjoin for '.' is a workaround for Python bug #1213894.
 
1854
    # (initial path components aren't dereferenced)
 
1855
    return pathjoin(realpath(pathjoin('.', parent)), base)
 
1856
 
 
1857
 
 
1858
def supports_mapi():
 
1859
    """Return True if we can use MAPI to launch a mail client."""
 
1860
    return sys.platform == "win32"
 
1861
 
 
1862
 
 
1863
def resource_string(package, resource_name):
 
1864
    """Load a resource from a package and return it as a string.
 
1865
 
 
1866
    Note: Only packages that start with bzrlib are currently supported.
 
1867
 
 
1868
    This is designed to be a lightweight implementation of resource
 
1869
    loading in a way which is API compatible with the same API from
 
1870
    pkg_resources. See
 
1871
    http://peak.telecommunity.com/DevCenter/PkgResources#basic-resource-access.
 
1872
    If and when pkg_resources becomes a standard library, this routine
 
1873
    can delegate to it.
 
1874
    """
 
1875
    # Check package name is within bzrlib
 
1876
    if package == "bzrlib":
 
1877
        resource_relpath = resource_name
 
1878
    elif package.startswith("bzrlib."):
 
1879
        package = package[len("bzrlib."):].replace('.', os.sep)
 
1880
        resource_relpath = pathjoin(package, resource_name)
 
1881
    else:
 
1882
        raise errors.BzrError('resource package %s not in bzrlib' % package)
 
1883
 
 
1884
    # Map the resource to a file and read its contents
 
1885
    base = dirname(bzrlib.__file__)
 
1886
    if getattr(sys, 'frozen', None):    # bzr.exe
 
1887
        base = abspath(pathjoin(base, '..', '..'))
 
1888
    filename = pathjoin(base, resource_relpath)
 
1889
    return open(filename, 'rU').read()
 
1890
 
 
1891
 
 
1892
def file_kind_from_stat_mode_thunk(mode):
 
1893
    global file_kind_from_stat_mode
 
1894
    if file_kind_from_stat_mode is file_kind_from_stat_mode_thunk:
 
1895
        try:
 
1896
            from bzrlib._readdir_pyx import UTF8DirReader
 
1897
            file_kind_from_stat_mode = UTF8DirReader().kind_from_mode
 
1898
        except ImportError, e:
 
1899
            # This is one time where we won't warn that an extension failed to
 
1900
            # load. The extension is never available on Windows anyway.
 
1901
            from bzrlib._readdir_py import (
 
1902
                _kind_from_mode as file_kind_from_stat_mode
 
1903
                )
 
1904
    return file_kind_from_stat_mode(mode)
 
1905
file_kind_from_stat_mode = file_kind_from_stat_mode_thunk
 
1906
 
 
1907
 
 
1908
def file_kind(f, _lstat=os.lstat):
 
1909
    try:
 
1910
        return file_kind_from_stat_mode(_lstat(f).st_mode)
 
1911
    except OSError, e:
 
1912
        if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
 
1913
            raise errors.NoSuchFile(f)
 
1914
        raise
 
1915
 
 
1916
 
 
1917
def until_no_eintr(f, *a, **kw):
 
1918
    """Run f(*a, **kw), retrying if an EINTR error occurs."""
 
1919
    # Borrowed from Twisted's twisted.python.util.untilConcludes function.
 
1920
    while True:
 
1921
        try:
 
1922
            return f(*a, **kw)
 
1923
        except (IOError, OSError), e:
 
1924
            if e.errno == errno.EINTR:
 
1925
                continue
 
1926
            raise
 
1927
 
 
1928
def re_compile_checked(re_string, flags=0, where=""):
 
1929
    """Return a compiled re, or raise a sensible error.
 
1930
 
 
1931
    This should only be used when compiling user-supplied REs.
 
1932
 
 
1933
    :param re_string: Text form of regular expression.
 
1934
    :param flags: eg re.IGNORECASE
 
1935
    :param where: Message explaining to the user the context where
 
1936
        it occurred, eg 'log search filter'.
 
1937
    """
 
1938
    # from https://bugs.launchpad.net/bzr/+bug/251352
 
1939
    try:
 
1940
        re_obj = re.compile(re_string, flags)
 
1941
        re_obj.search("")
 
1942
        return re_obj
 
1943
    except re.error, e:
 
1944
        if where:
 
1945
            where = ' in ' + where
 
1946
        # despite the name 'error' is a type
 
1947
        raise errors.BzrCommandError('Invalid regular expression%s: %r: %s'
 
1948
            % (where, re_string, e))
 
1949
 
 
1950
 
 
1951
if sys.platform == "win32":
 
1952
    import msvcrt
 
1953
    def getchar():
 
1954
        return msvcrt.getch()
 
1955
else:
 
1956
    import tty
 
1957
    import termios
 
1958
    def getchar():
 
1959
        fd = sys.stdin.fileno()
 
1960
        settings = termios.tcgetattr(fd)
 
1961
        try:
 
1962
            tty.setraw(fd)
 
1963
            ch = sys.stdin.read(1)
 
1964
        finally:
 
1965
            termios.tcsetattr(fd, termios.TCSADRAIN, settings)
 
1966
        return ch
 
1967
 
 
1968
 
 
1969
if sys.platform == 'linux2':
 
1970
    def _local_concurrency():
 
1971
        concurrency = None
 
1972
        prefix = 'processor'
 
1973
        for line in file('/proc/cpuinfo', 'rb'):
 
1974
            if line.startswith(prefix):
 
1975
                concurrency = int(line[line.find(':')+1:]) + 1
 
1976
        return concurrency
 
1977
elif sys.platform == 'darwin':
 
1978
    def _local_concurrency():
 
1979
        return subprocess.Popen(['sysctl', '-n', 'hw.availcpu'],
 
1980
                                stdout=subprocess.PIPE).communicate()[0]
 
1981
elif sys.platform[0:7] == 'freebsd':
 
1982
    def _local_concurrency():
 
1983
        return subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
 
1984
                                stdout=subprocess.PIPE).communicate()[0]
 
1985
elif sys.platform == 'sunos5':
 
1986
    def _local_concurrency():
 
1987
        return subprocess.Popen(['psrinfo', '-p',],
 
1988
                                stdout=subprocess.PIPE).communicate()[0]
 
1989
elif sys.platform == "win32":
 
1990
    def _local_concurrency():
 
1991
        # This appears to return the number of cores.
 
1992
        return os.environ.get('NUMBER_OF_PROCESSORS')
 
1993
else:
 
1994
    def _local_concurrency():
 
1995
        # Who knows ?
 
1996
        return None
 
1997
 
 
1998
 
 
1999
_cached_local_concurrency = None
 
2000
 
 
2001
def local_concurrency(use_cache=True):
 
2002
    """Return how many processes can be run concurrently.
 
2003
 
 
2004
    Rely on platform specific implementations and default to 1 (one) if
 
2005
    anything goes wrong.
 
2006
    """
 
2007
    global _cached_local_concurrency
 
2008
 
 
2009
    if _cached_local_concurrency is not None and use_cache:
 
2010
        return _cached_local_concurrency
 
2011
 
 
2012
    concurrency = os.environ.get('BZR_CONCURRENCY', None)
 
2013
    if concurrency is None:
 
2014
        try:
 
2015
            concurrency = _local_concurrency()
 
2016
        except (OSError, IOError):
 
2017
            pass
 
2018
    try:
 
2019
        concurrency = int(concurrency)
 
2020
    except (TypeError, ValueError):
 
2021
        concurrency = 1
 
2022
    if use_cache:
 
2023
        _cached_concurrency = concurrency
 
2024
    return concurrency