~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2006-07-02 00:49:15 UTC
  • mfrom: (1706.2.8 bzr.dev.lsprof)
  • Revision ID: pqm@pqm.ubuntu.com-20060702004915-501855cc9fc14e10
(robey) updates for lsprof

Show diffs side-by-side

added added

removed removed

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