~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: Vincent Ladeuil
  • Date: 2010-03-05 08:55:12 UTC
  • mfrom: (4797.2.27 2.1-integration)
  • mto: This revision was merged to the branch mainline in revision 5075.
  • Revision ID: v.ladeuil+lp@free.fr-20100305085512-rsguvvb02fbyx7zj
Merge 2.1 into bzr.dev including fixes for #524560 and #449776

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Bazaar-NG -- distributed version control
2
 
#
3
 
# Copyright (C) 2005 by Canonical Ltd
 
1
# Copyright (C) 2005-2010 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
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
16
 
19
 
from shutil import copyfile
 
17
import os
 
18
import re
 
19
import stat
20
20
from stat import (S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE,
21
21
                  S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
22
 
from cStringIO import StringIO
23
 
import errno
24
 
import os
25
 
import re
26
 
import sha
27
 
import string
28
22
import sys
29
23
import time
30
 
import types
 
24
import codecs
 
25
import warnings
 
26
 
 
27
from bzrlib.lazy_import import lazy_import
 
28
lazy_import(globals(), """
 
29
from datetime import datetime
 
30
import errno
 
31
from ntpath import (abspath as _nt_abspath,
 
32
                    join as _nt_join,
 
33
                    normpath as _nt_normpath,
 
34
                    realpath as _nt_realpath,
 
35
                    splitdrive as _nt_splitdrive,
 
36
                    )
 
37
import posixpath
 
38
import shutil
 
39
from shutil import (
 
40
    rmtree,
 
41
    )
 
42
import signal
 
43
import subprocess
 
44
import tempfile
 
45
from tempfile import (
 
46
    mkdtemp,
 
47
    )
 
48
import unicodedata
 
49
 
 
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
 
31
70
 
32
71
import bzrlib
33
 
from bzrlib.config import config_dir, _get_user_id
34
 
from bzrlib.errors import BzrError
35
 
from bzrlib.trace import mutter
 
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))
36
102
 
37
103
 
38
104
def make_readonly(filename):
39
105
    """Make a filename read-only."""
40
 
    mod = os.stat(filename).st_mode
41
 
    mod = mod & 0777555
42
 
    os.chmod(filename, mod)
 
106
    mod = os.lstat(filename).st_mode
 
107
    if not stat.S_ISLNK(mod):
 
108
        mod = mod & 0777555
 
109
        os.chmod(filename, mod)
43
110
 
44
111
 
45
112
def make_writable(filename):
46
 
    mod = os.stat(filename).st_mode
47
 
    mod = mod | 0200
48
 
    os.chmod(filename, mod)
 
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)
49
140
 
50
141
 
51
142
_QUOTE_RE = None
58
149
    Windows."""
59
150
    # TODO: I'm not really sure this is the best format either.x
60
151
    global _QUOTE_RE
61
 
    if _QUOTE_RE == None:
 
152
    if _QUOTE_RE is None:
62
153
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
63
 
        
 
154
 
64
155
    if _QUOTE_RE.search(f):
65
156
        return '"' + f + '"'
66
157
    else:
67
158
        return f
68
159
 
69
160
 
70
 
def file_kind(f):
71
 
    mode = os.lstat(f)[ST_MODE]
72
 
    if S_ISREG(mode):
73
 
        return 'file'
74
 
    elif S_ISDIR(mode):
75
 
        return 'directory'
76
 
    elif S_ISLNK(mode):
77
 
        return 'symlink'
78
 
    elif S_ISCHR(mode):
79
 
        return 'chardev'
80
 
    elif S_ISBLK(mode):
81
 
        return 'block'
82
 
    elif S_ISFIFO(mode):
83
 
        return 'fifo'
84
 
    elif S_ISSOCK(mode):
85
 
        return 'socket'
86
 
    else:
87
 
        return 'unknown'
 
161
_directory_kind = 'directory'
 
162
 
 
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': '+',
 
178
}
88
179
 
89
180
 
90
181
def kind_marker(kind):
91
 
    if kind == 'file':
 
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
92
187
        return ''
93
 
    elif kind == 'directory':
94
 
        return '/'
95
 
    elif kind == 'symlink':
96
 
        return '@'
97
 
    else:
98
 
        raise BzrError('invalid file kind %r' % kind)
99
 
 
100
 
def lexists(f):
101
 
    try:
102
 
        if hasattr(os, 'lstat'):
103
 
            os.lstat(f)
104
 
        else:
105
 
            os.stat(f)
106
 
        return True
107
 
    except OSError,e:
108
 
        if e.errno == errno.ENOENT:
109
 
            return False;
110
 
        else:
111
 
            raise BzrError("lstat/stat of (%r): %r" % (f, e))
 
188
 
 
189
 
 
190
lexists = getattr(os.path, 'lexists', None)
 
191
if lexists is None:
 
192
    def lexists(f):
 
193
        try:
 
194
            stat = getattr(os, 'lstat', os.stat)
 
195
            stat(f)
 
196
            return True
 
197
        except OSError, e:
 
198
            if e.errno == errno.ENOENT:
 
199
                return False;
 
200
            else:
 
201
                raise errors.BzrError("lstat/stat of (%r): %r" % (f, e))
 
202
 
 
203
 
 
204
def fancy_rename(old, new, rename_func, unlink_func):
 
205
    """A fancy rename, when you don't have atomic rename.
 
206
 
 
207
    :param old: The old path, to rename from
 
208
    :param new: The new path, to rename to
 
209
    :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
 
212
    """
 
213
    # sftp rename doesn't allow overwriting, so play tricks:
 
214
    base = os.path.basename(new)
 
215
    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))
 
221
    tmp_name = pathjoin(dirname, tmp_name)
 
222
 
 
223
    # Rename the file out of the way, but keep track if it didn't exist
 
224
    # We don't want to grab just any exception
 
225
    # something like EACCES should prevent us from continuing
 
226
    # The downside is that the rename_func has to throw an exception
 
227
    # with an errno = ENOENT, or NoSuchFile
 
228
    file_existed = False
 
229
    try:
 
230
        rename_func(new, tmp_name)
 
231
    except (errors.NoSuchFile,), e:
 
232
        pass
 
233
    except IOError, e:
 
234
        # RBC 20060103 abstraction leakage: the paramiko SFTP clients rename
 
235
        # function raises an IOError with errno is None when a rename fails.
 
236
        # This then gets caught here.
 
237
        if e.errno not in (None, errno.ENOENT, errno.ENOTDIR):
 
238
            raise
 
239
    except Exception, e:
 
240
        if (getattr(e, 'errno', None) is None
 
241
            or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
 
242
            raise
 
243
    else:
 
244
        file_existed = True
 
245
 
 
246
    failure_exc = None
 
247
    success = False
 
248
    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
 
264
    finally:
 
265
        if file_existed:
 
266
            # If the file used to exist, rename it back into place
 
267
            # otherwise just delete it from the tmp location
 
268
            if success:
 
269
                unlink_func(tmp_name)
 
270
            else:
 
271
                rename_func(tmp_name, new)
 
272
    if failure_exc is not None:
 
273
        raise failure_exc[0], failure_exc[1], failure_exc[2]
 
274
 
 
275
 
 
276
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
 
277
# choke on a Unicode string containing a relative path if
 
278
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
 
279
# string.
 
280
_fs_enc = sys.getfilesystemencoding() or 'utf-8'
 
281
def _posix_abspath(path):
 
282
    # jam 20060426 rather than encoding to fsencoding
 
283
    # copy posixpath.abspath, but use os.getcwdu instead
 
284
    if not posixpath.isabs(path):
 
285
        path = posixpath.join(getcwd(), path)
 
286
    return posixpath.normpath(path)
 
287
 
 
288
 
 
289
def _posix_realpath(path):
 
290
    return posixpath.realpath(path.encode(_fs_enc)).decode(_fs_enc)
 
291
 
 
292
 
 
293
def _win32_fixdrive(path):
 
294
    """Force drive letters to be consistent.
 
295
 
 
296
    win32 is inconsistent whether it returns lower or upper case
 
297
    and even if it was consistent the user might type the other
 
298
    so we force it to uppercase
 
299
    running python.exe under cmd.exe return capital C:\\
 
300
    running win32 python inside a cygwin shell returns lowercase c:\\
 
301
    """
 
302
    drive, path = _nt_splitdrive(path)
 
303
    return drive.upper() + path
 
304
 
 
305
 
 
306
def _win32_abspath(path):
 
307
    # Real _nt_abspath doesn't have a problem with a unicode cwd
 
308
    return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
 
309
 
 
310
 
 
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
def _win32_realpath(path):
 
339
    # Real _nt_realpath doesn't have a problem with a unicode cwd
 
340
    return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
 
341
 
 
342
 
 
343
def _win32_pathjoin(*args):
 
344
    return _nt_join(*args).replace('\\', '/')
 
345
 
 
346
 
 
347
def _win32_normpath(path):
 
348
    return _win32_fixdrive(_nt_normpath(unicode(path)).replace('\\', '/'))
 
349
 
 
350
 
 
351
def _win32_getcwd():
 
352
    return _win32_fixdrive(os.getcwdu().replace('\\', '/'))
 
353
 
 
354
 
 
355
def _win32_mkdtemp(*args, **kwargs):
 
356
    return _win32_fixdrive(tempfile.mkdtemp(*args, **kwargs).replace('\\', '/'))
 
357
 
 
358
 
 
359
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())
 
379
 
 
380
 
 
381
# Default is to just use the python builtins, but these can be rebound on
 
382
# particular platforms.
 
383
abspath = _posix_abspath
 
384
realpath = _posix_realpath
 
385
pathjoin = os.path.join
 
386
normpath = os.path.normpath
 
387
getcwd = os.getcwdu
 
388
rename = os.rename
 
389
dirname = os.path.dirname
 
390
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
 
396
 
 
397
MIN_ABS_PATHLENGTH = 1
 
398
 
 
399
 
 
400
if sys.platform == 'win32':
 
401
    if win32utils.winver == 'Windows 98':
 
402
        abspath = _win98_abspath
 
403
    else:
 
404
        abspath = _win32_abspath
 
405
    realpath = _win32_realpath
 
406
    pathjoin = _win32_pathjoin
 
407
    normpath = _win32_normpath
 
408
    getcwd = _win32_getcwd
 
409
    mkdtemp = _win32_mkdtemp
 
410
    rename = _win32_rename
 
411
 
 
412
    MIN_ABS_PATHLENGTH = 3
 
413
 
 
414
    def _win32_delete_readonly(function, path, excinfo):
 
415
        """Error handler for shutil.rmtree function [for win32]
 
416
        Helps to remove files and dirs marked as read-only.
 
417
        """
 
418
        exception = excinfo[1]
 
419
        if function in (os.remove, os.rmdir) \
 
420
            and isinstance(exception, OSError) \
 
421
            and exception.errno == errno.EACCES:
 
422
            make_writable(path)
 
423
            function(path)
 
424
        else:
 
425
            raise
 
426
 
 
427
    def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
 
428
        """Replacer for shutil.rmtree: could remove readonly dirs/files"""
 
429
        return shutil.rmtree(path, ignore_errors, onerror)
 
430
 
 
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
 
 
439
def get_terminal_encoding():
 
440
    """Find the best encoding for printing to the screen.
 
441
 
 
442
    This attempts to check both sys.stdout and sys.stdin to see
 
443
    what encoding they are in, and if that fails it falls back to
 
444
    osutils.get_user_encoding().
 
445
    The problem is that on Windows, locale.getpreferredencoding()
 
446
    is not the same encoding as that used by the console:
 
447
    http://mail.python.org/pipermail/python-list/2003-May/162357.html
 
448
 
 
449
    On my standard US Windows XP, the preferred encoding is
 
450
    cp1252, but the console is cp437
 
451
    """
 
452
    from bzrlib.trace import mutter
 
453
    output_encoding = getattr(sys.stdout, 'encoding', None)
 
454
    if not output_encoding:
 
455
        input_encoding = getattr(sys.stdin, 'encoding', None)
 
456
        if not input_encoding:
 
457
            output_encoding = get_user_encoding()
 
458
            mutter('encoding stdout as osutils.get_user_encoding() %r',
 
459
                   output_encoding)
 
460
        else:
 
461
            output_encoding = input_encoding
 
462
            mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
 
463
    else:
 
464
        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
    return output_encoding
 
483
 
112
484
 
113
485
def normalizepath(f):
114
 
    if hasattr(os.path, 'realpath'):
115
 
        F = os.path.realpath
 
486
    if getattr(os.path, 'realpath', None) is not None:
 
487
        F = realpath
116
488
    else:
117
 
        F = os.path.abspath
 
489
        F = abspath
118
490
    [p,e] = os.path.split(f)
119
491
    if e == "" or e == "." or e == "..":
120
492
        return F(f)
121
493
    else:
122
 
        return os.path.join(F(p), e)
123
 
    
124
 
 
125
 
def backup_file(fn):
126
 
    """Copy a file to a backup.
127
 
 
128
 
    Backups are named in GNU-style, with a ~ suffix.
129
 
 
130
 
    If the file is already a backup, it's not copied.
131
 
    """
132
 
    if fn[-1] == '~':
133
 
        return
134
 
    bfn = fn + '~'
135
 
 
136
 
    if has_symlinks() and os.path.islink(fn):
137
 
        target = os.readlink(fn)
138
 
        os.symlink(target, bfn)
139
 
        return
140
 
    inf = file(fn, 'rb')
141
 
    try:
142
 
        content = inf.read()
143
 
    finally:
144
 
        inf.close()
145
 
    
146
 
    outf = file(bfn, 'wb')
147
 
    try:
148
 
        outf.write(content)
149
 
    finally:
150
 
        outf.close()
151
 
 
152
 
if os.name == 'nt':
153
 
    import shutil
154
 
    rename = shutil.move
155
 
else:
156
 
    rename = os.rename
 
494
        return pathjoin(F(p), e)
157
495
 
158
496
 
159
497
def isdir(f):
180
518
 
181
519
def is_inside(dir, fname):
182
520
    """True if fname is inside dir.
183
 
    
184
 
    The parameters should typically be passed to os.path.normpath first, so
 
521
 
 
522
    The parameters should typically be passed to osutils.normpath first, so
185
523
    that . and .. and repeated slashes are eliminated, and the separators
186
524
    are canonical for the platform.
187
 
    
188
 
    The empty string as a dir name is taken as top-of-tree and matches 
 
525
 
 
526
    The empty string as a dir name is taken as top-of-tree and matches
189
527
    everything.
190
 
    
191
 
    >>> is_inside('src', os.path.join('src', 'foo.c'))
192
 
    True
193
 
    >>> is_inside('src', 'srccontrol')
194
 
    False
195
 
    >>> is_inside('src', os.path.join('src', 'a', 'a', 'a', 'foo.c'))
196
 
    True
197
 
    >>> is_inside('foo.c', 'foo.c')
198
 
    True
199
 
    >>> is_inside('foo.c', '')
200
 
    False
201
 
    >>> is_inside('', 'foo.c')
202
 
    True
203
528
    """
204
 
    # XXX: Most callers of this can actually do something smarter by 
 
529
    # XXX: Most callers of this can actually do something smarter by
205
530
    # looking at the inventory
206
531
    if dir == fname:
207
532
        return True
208
 
    
 
533
 
209
534
    if dir == '':
210
535
        return True
211
536
 
212
 
    if dir[-1] != os.sep:
213
 
        dir += os.sep
 
537
    if dir[-1] != '/':
 
538
        dir += '/'
214
539
 
215
540
    return fname.startswith(dir)
216
541
 
220
545
    for dirname in dir_list:
221
546
        if is_inside(dirname, fname):
222
547
            return True
 
548
    return False
 
549
 
 
550
 
 
551
def is_inside_or_parent_of_any(dir_list, fname):
 
552
    """True if fname is a child or a parent of any of the given files."""
 
553
    for dirname in dir_list:
 
554
        if is_inside(dirname, fname) or is_inside(fname, dirname):
 
555
            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
223
593
    else:
224
 
        return False
225
 
 
226
 
 
227
 
def pumpfile(fromfile, tofile):
228
 
    """Copy contents of one file to another."""
229
 
    tofile.write(fromfile.read())
 
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)
 
623
 
 
624
 
 
625
def file_iterator(input_file, readsize=32768):
 
626
    while True:
 
627
        b = input_file.read(readsize)
 
628
        if len(b) == 0:
 
629
            break
 
630
        yield b
230
631
 
231
632
 
232
633
def sha_file(f):
233
 
    if hasattr(f, 'tell'):
234
 
        assert f.tell() == 0
235
 
    s = sha.new()
 
634
    """Calculate the hexdigest of an open file.
 
635
 
 
636
    The file cursor should be already at the start.
 
637
    """
 
638
    s = sha()
236
639
    BUFSIZE = 128<<10
237
640
    while True:
238
641
        b = f.read(BUFSIZE)
242
645
    return s.hexdigest()
243
646
 
244
647
 
245
 
 
246
 
def sha_strings(strings):
 
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):
247
681
    """Return the sha-1 of concatenation of strings"""
248
 
    s = sha.new()
 
682
    s = _factory()
249
683
    map(s.update, strings)
250
684
    return s.hexdigest()
251
685
 
252
686
 
253
 
def sha_string(f):
254
 
    s = sha.new()
255
 
    s.update(f)
256
 
    return s.hexdigest()
 
687
def sha_string(f, _factory=sha):
 
688
    return _factory(f).hexdigest()
257
689
 
258
690
 
259
691
def fingerprint_file(f):
260
 
    s = sha.new()
261
692
    b = f.read()
262
 
    s.update(b)
263
 
    size = len(b)
264
 
    return {'size': size,
265
 
            'sha1': s.hexdigest()}
 
693
    return {'size': len(b),
 
694
            'sha1': sha(b).hexdigest()}
266
695
 
267
696
 
268
697
def compare_files(a, b):
279
708
 
280
709
def local_time_offset(t=None):
281
710
    """Return offset of local zone from GMT, either at present or at time t."""
282
 
    # python2.3 localtime() can't take None
283
 
    if t == None:
 
711
    if t is None:
284
712
        t = time.time()
285
 
        
286
 
    if time.localtime(t).tm_isdst and time.daylight:
287
 
        return -time.altzone
288
 
    else:
289
 
        return -time.timezone
290
 
 
291
 
    
292
 
def format_date(t, offset=0, timezone='original'):
293
 
    ## TODO: Perhaps a global option to use either universal or local time?
294
 
    ## Or perhaps just let people set $TZ?
295
 
    assert isinstance(t, float)
296
 
    
 
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,
 
721
                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):
297
785
    if timezone == 'utc':
298
786
        tt = time.gmtime(t)
299
787
        offset = 0
300
788
    elif timezone == 'original':
301
 
        if offset == None:
 
789
        if offset is None:
302
790
            offset = 0
303
791
        tt = time.gmtime(t + offset)
304
792
    elif timezone == 'local':
305
793
        tt = time.localtime(t)
306
794
        offset = local_time_offset(t)
307
795
    else:
308
 
        raise BzrError("unsupported timezone format %r" % timezone,
309
 
                       ['options are "utc", "original", "local"'])
310
 
 
311
 
    return (time.strftime("%a %Y-%m-%d %H:%M:%S", tt)
312
 
            + ' %+03d%02d' % (offset / 3600, (offset / 60) % 60))
 
796
        raise errors.UnsupportedTimezoneFormat(timezone)
 
797
    if date_fmt is None:
 
798
        date_fmt = "%a %Y-%m-%d %H:%M:%S"
 
799
    if show_offset:
 
800
        offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
 
801
    else:
 
802
        offset_str = ''
 
803
    return (date_fmt, tt, offset_str)
313
804
 
314
805
 
315
806
def compact_date(when):
316
807
    return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
317
 
    
318
 
 
 
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)
319
858
 
320
859
def filesize(f):
321
860
    """Return size of given open file."""
322
861
    return os.fstat(f.fileno())[ST_SIZE]
323
862
 
 
863
 
324
864
# Define rand_bytes based on platform.
325
865
try:
326
866
    # Python 2.4 and later have os.urandom,
330
870
except (NotImplementedError, AttributeError):
331
871
    # If python doesn't have os.urandom, or it doesn't work,
332
872
    # then try to first pull random data from /dev/urandom
333
 
    if os.path.exists("/dev/urandom"):
 
873
    try:
334
874
        rand_bytes = file('/dev/urandom', 'rb').read
335
875
    # Otherwise, use this hack as a last resort
336
 
    else:
 
876
    except (IOError, OSError):
337
877
        # not well seeded, but better than nothing
338
878
        def rand_bytes(n):
339
879
            import random
343
883
                n -= 1
344
884
            return s
345
885
 
 
886
 
 
887
ALNUM = '0123456789abcdefghijklmnopqrstuvwxyz'
 
888
def rand_chars(num):
 
889
    """Return a random string of num alphanumeric characters
 
890
 
 
891
    The result only contains lowercase chars because it may be used on
 
892
    case-insensitive filesystems.
 
893
    """
 
894
    s = ''
 
895
    for raw_byte in rand_bytes(num):
 
896
        s += ALNUM[ord(raw_byte) % 36]
 
897
    return s
 
898
 
 
899
 
346
900
## TODO: We could later have path objects that remember their list
347
901
## decomposition (might be too tricksy though.)
348
902
 
349
903
def splitpath(p):
350
 
    """Turn string into list of parts.
351
 
 
352
 
    >>> splitpath('a')
353
 
    ['a']
354
 
    >>> splitpath('a/b')
355
 
    ['a', 'b']
356
 
    >>> splitpath('a/./b')
357
 
    ['a', 'b']
358
 
    >>> splitpath('a/.b')
359
 
    ['a', '.b']
360
 
    >>> splitpath('a/../b')
361
 
    Traceback (most recent call last):
362
 
    ...
363
 
    BzrError: sorry, '..' not allowed in path
364
 
    """
365
 
    assert isinstance(p, types.StringTypes)
366
 
 
 
904
    """Turn string into list of parts."""
367
905
    # split on either delimiter because people might use either on
368
906
    # Windows
369
907
    ps = re.split(r'[\\/]', p)
371
909
    rps = []
372
910
    for f in ps:
373
911
        if f == '..':
374
 
            raise BzrError("sorry, %r not allowed in path" % f)
 
912
            raise errors.BzrError("sorry, %r not allowed in path" % f)
375
913
        elif (f == '.') or (f == ''):
376
914
            pass
377
915
        else:
378
916
            rps.append(f)
379
917
    return rps
380
918
 
 
919
 
381
920
def joinpath(p):
382
 
    assert isinstance(p, list)
383
921
    for f in p:
384
 
        if (f == '..') or (f == None) or (f == ''):
385
 
            raise BzrError("sorry, %r not allowed in path" % f)
386
 
    return os.path.join(*p)
387
 
 
388
 
 
389
 
def appendpath(p1, p2):
390
 
    if p1 == '':
391
 
        return p2
392
 
    else:
393
 
        return os.path.join(p1, p2)
394
 
    
 
922
        if (f == '..') or (f is None) or (f == ''):
 
923
            raise errors.BzrError("sorry, %r not allowed in path" % f)
 
924
    return pathjoin(*p)
 
925
 
 
926
 
 
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
 
395
993
 
396
994
def split_lines(s):
397
995
    """Split s into lines, but without removing the newline characters."""
398
 
    return StringIO(s).readlines()
 
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
    lines = s.split('\n')
 
1011
    result = [line + '\n' for line in lines[:-1]]
 
1012
    if lines[-1]:
 
1013
        result.append(lines[-1])
 
1014
    return result
399
1015
 
400
1016
 
401
1017
def hardlinks_good():
405
1021
def link_or_copy(src, dest):
406
1022
    """Hardlink a file, or copy it if it can't be hardlinked."""
407
1023
    if not hardlinks_good():
408
 
        copyfile(src, dest)
 
1024
        shutil.copyfile(src, dest)
409
1025
        return
410
1026
    try:
411
1027
        os.link(src, dest)
412
1028
    except (OSError, IOError), e:
413
1029
        if e.errno != errno.EXDEV:
414
1030
            raise
415
 
        copyfile(src, dest)
 
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
    """
 
1039
    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:
 
1050
            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)
416
1063
 
417
1064
 
418
1065
def has_symlinks():
419
 
    if hasattr(os, 'symlink'):
420
 
        return True
421
 
    else:
422
 
        return False
423
 
        
 
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
 
424
1097
 
425
1098
def contains_whitespace(s):
426
1099
    """True if there are any whitespace characters in s."""
427
 
    for ch in string.whitespace:
 
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':
428
1112
        if ch in s:
429
1113
            return True
430
1114
    else:
438
1122
            return True
439
1123
    else:
440
1124
        return False
 
1125
 
 
1126
 
 
1127
def relpath(base, path):
 
1128
    """Return path relative to base, or raise exception.
 
1129
 
 
1130
    The path may be either an absolute path or a path relative to the
 
1131
    current working directory.
 
1132
 
 
1133
    os.path.commonprefix (python2.4) has a bad bug that it works just
 
1134
    on string prefixes, assuming that '/u' is a prefix of '/u2'.  This
 
1135
    avoids that problem.
 
1136
    """
 
1137
 
 
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,))
 
1142
 
 
1143
    rp = abspath(path)
 
1144
 
 
1145
    s = []
 
1146
    head = rp
 
1147
    while True:
 
1148
        if len(head) <= len(base) and head != base:
 
1149
            raise errors.PathNotChild(rp, base)
 
1150
        if head == base:
 
1151
            break
 
1152
        head, tail = split(head)
 
1153
        if tail:
 
1154
            s.append(tail)
 
1155
 
 
1156
    if s:
 
1157
        return pathjoin(*reversed(s))
 
1158
    else:
 
1159
        return ''
 
1160
 
 
1161
 
 
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
def safe_unicode(unicode_or_utf8_string):
 
1229
    """Coerce unicode_or_utf8_string into unicode.
 
1230
 
 
1231
    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.
 
1234
    """
 
1235
    if isinstance(unicode_or_utf8_string, unicode):
 
1236
        return unicode_or_utf8_string
 
1237
    try:
 
1238
        return unicode_or_utf8_string.decode('utf8')
 
1239
    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)
 
1306
 
 
1307
 
 
1308
_platform_normalizes_filenames = False
 
1309
if sys.platform == 'darwin':
 
1310
    _platform_normalizes_filenames = True
 
1311
 
 
1312
 
 
1313
def normalizes_filenames():
 
1314
    """Return True if this platform normalizes unicode filenames.
 
1315
 
 
1316
    Mac OSX does, Windows/Linux do not.
 
1317
    """
 
1318
    return _platform_normalizes_filenames
 
1319
 
 
1320
 
 
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
if _platform_normalizes_filenames:
 
1347
    normalized_filename = _accessible_normalized_filename
 
1348
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
"""
 
1358
 
 
1359
 
 
1360
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):
 
1416
    try:
 
1417
        import struct, fcntl, termios
 
1418
        s = struct.pack('HHHH', 0, 0, 0, 0)
 
1419
        x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
 
1420
        height, width = struct.unpack('HHHH', x)[0:2]
 
1421
    except (IOError, AttributeError):
 
1422
        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
 
1457
            pass
 
1458
        else:
 
1459
            signal.signal(signal.SIGWINCH, _terminal_size_changed)
 
1460
        _registered_sigwinch = True
 
1461
 
 
1462
 
 
1463
def supports_executable():
 
1464
    return sys.platform != "win32"
 
1465
 
 
1466
 
 
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
_validWin32PathRE = re.compile(r'^([A-Za-z]:[/\\])?[^:<>*"?\|]*$')
 
1500
 
 
1501
 
 
1502
def check_legal_path(path):
 
1503
    """Check whether the supplied path is legal.
 
1504
    This is only required on Windows, so we don't test on other platforms
 
1505
    right now.
 
1506
    """
 
1507
    if sys.platform != "win32":
 
1508
        return
 
1509
    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
 
1539
 
 
1540
 
 
1541
def walkdirs(top, prefix=""):
 
1542
    """Yield data about all the directories in a tree.
 
1543
 
 
1544
    This yields all the data about the contents of a directory at a time.
 
1545
    After each directory has been yielded, if the caller has mutated the list
 
1546
    to exclude some directories, they are then not descended into.
 
1547
 
 
1548
    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.
 
1563
 
 
1564
    :param prefix: Prefix the relpaths that are yielded with 'prefix'. This
 
1565
        allows one to walk a subtree but get paths that are relative to a tree
 
1566
        rooted higher up.
 
1567
    :return: an iterator over the dirs.
 
1568
    """
 
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
 
1575
    _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))]
 
1579
    while pending:
 
1580
        # 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
 
1731
        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)
 
1784
 
 
1785
 
 
1786
def path_prefix_key(path):
 
1787
    """Generate a prefix-order path key for path.
 
1788
 
 
1789
    This can be used to sort paths in the same way that walkdirs does.
 
1790
    """
 
1791
    return (dirname(path) , path)
 
1792
 
 
1793
 
 
1794
def compare_paths_prefix_order(path_a, path_b):
 
1795
    """Compare path_a and path_b to generate the same order walkdirs uses."""
 
1796
    key_a = path_prefix_key(path_a)
 
1797
    key_b = path_prefix_key(path_b)
 
1798
    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