/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: Marius Kruger
  • Date: 2008-10-03 20:57:44 UTC
  • mto: This revision was merged to the branch mainline in revision 3809.
  • Revision ID: amanic@gmail.com-20081003205744-o0cdopyj7mum2dkw
* checkouts now use master nick when no explicit nick is set.
* switch updates only explicit nicks.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
from cStringIO import StringIO
 
18
import os
 
19
import re
 
20
import stat
 
21
from stat import (S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE,
 
22
                  S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
 
23
import sys
 
24
import time
 
25
 
 
26
from bzrlib.lazy_import import lazy_import
 
27
lazy_import(globals(), """
 
28
import codecs
 
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 tempfile
 
43
from tempfile import (
 
44
    mkdtemp,
 
45
    )
 
46
import unicodedata
 
47
 
 
48
from bzrlib import (
 
49
    cache_utf8,
 
50
    errors,
 
51
    win32utils,
 
52
    )
 
53
""")
 
54
 
 
55
# sha and md5 modules are deprecated in python2.6 but hashlib is available as
 
56
# of 2.5
 
57
if sys.version_info < (2, 5):
 
58
    import md5 as _mod_md5
 
59
    md5 = _mod_md5.new
 
60
    import sha as _mod_sha
 
61
    sha = _mod_sha.new
 
62
else:
 
63
    from hashlib import (
 
64
        md5,
 
65
        sha1 as sha,
 
66
        )
 
67
 
 
68
 
 
69
import bzrlib
 
70
from bzrlib import symbol_versioning
 
71
from bzrlib.symbol_versioning import (
 
72
    deprecated_function,
 
73
    )
 
74
from bzrlib.trace import mutter
 
75
 
 
76
 
 
77
# On win32, O_BINARY is used to indicate the file should
 
78
# be opened in binary mode, rather than text mode.
 
79
# On other platforms, O_BINARY doesn't exist, because
 
80
# they always open in binary mode, so it is okay to
 
81
# OR with 0 on those platforms
 
82
O_BINARY = getattr(os, 'O_BINARY', 0)
 
83
 
 
84
 
 
85
def make_readonly(filename):
 
86
    """Make a filename read-only."""
 
87
    mod = os.lstat(filename).st_mode
 
88
    if not stat.S_ISLNK(mod):
 
89
        mod = mod & 0777555
 
90
        os.chmod(filename, mod)
 
91
 
 
92
 
 
93
def make_writable(filename):
 
94
    mod = os.lstat(filename).st_mode
 
95
    if not stat.S_ISLNK(mod):
 
96
        mod = mod | 0200
 
97
        os.chmod(filename, mod)
 
98
 
 
99
 
 
100
def minimum_path_selection(paths):
 
101
    """Return the smallset subset of paths which are outside paths.
 
102
 
 
103
    :param paths: A container (and hence not None) of paths.
 
104
    :return: A set of paths sufficient to include everything in paths via
 
105
        is_inside_any, drawn from the paths parameter.
 
106
    """
 
107
    search_paths = set()
 
108
    paths = set(paths)
 
109
    for path in paths:
 
110
        other_paths = paths.difference([path])
 
111
        if not is_inside_any(other_paths, path):
 
112
            # this is a top level path, we must check it.
 
113
            search_paths.add(path)
 
114
    return search_paths
 
115
 
 
116
 
 
117
_QUOTE_RE = None
 
118
 
 
119
 
 
120
def quotefn(f):
 
121
    """Return a quoted filename filename
 
122
 
 
123
    This previously used backslash quoting, but that works poorly on
 
124
    Windows."""
 
125
    # TODO: I'm not really sure this is the best format either.x
 
126
    global _QUOTE_RE
 
127
    if _QUOTE_RE is None:
 
128
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
 
129
        
 
130
    if _QUOTE_RE.search(f):
 
131
        return '"' + f + '"'
 
132
    else:
 
133
        return f
 
134
 
 
135
 
 
136
_directory_kind = 'directory'
 
137
 
 
138
def get_umask():
 
139
    """Return the current umask"""
 
140
    # Assume that people aren't messing with the umask while running
 
141
    # XXX: This is not thread safe, but there is no way to get the
 
142
    #      umask without setting it
 
143
    umask = os.umask(0)
 
144
    os.umask(umask)
 
145
    return umask
 
146
 
 
147
 
 
148
_kind_marker_map = {
 
149
    "file": "",
 
150
    _directory_kind: "/",
 
151
    "symlink": "@",
 
152
    'tree-reference': '+',
 
153
}
 
154
 
 
155
 
 
156
def kind_marker(kind):
 
157
    try:
 
158
        return _kind_marker_map[kind]
 
159
    except KeyError:
 
160
        raise errors.BzrError('invalid file kind %r' % kind)
 
161
 
 
162
 
 
163
lexists = getattr(os.path, 'lexists', None)
 
164
if lexists is None:
 
165
    def lexists(f):
 
166
        try:
 
167
            stat = getattr(os, 'lstat', os.stat)
 
168
            stat(f)
 
169
            return True
 
170
        except OSError, e:
 
171
            if e.errno == errno.ENOENT:
 
172
                return False;
 
173
            else:
 
174
                raise errors.BzrError("lstat/stat of (%r): %r" % (f, e))
 
175
 
 
176
 
 
177
def fancy_rename(old, new, rename_func, unlink_func):
 
178
    """A fancy rename, when you don't have atomic rename.
 
179
    
 
180
    :param old: The old path, to rename from
 
181
    :param new: The new path, to rename to
 
182
    :param rename_func: The potentially non-atomic rename function
 
183
    :param unlink_func: A way to delete the target file if the full rename succeeds
 
184
    """
 
185
 
 
186
    # sftp rename doesn't allow overwriting, so play tricks:
 
187
    import random
 
188
    base = os.path.basename(new)
 
189
    dirname = os.path.dirname(new)
 
190
    tmp_name = u'tmp.%s.%.9f.%d.%s' % (base, time.time(), os.getpid(), rand_chars(10))
 
191
    tmp_name = pathjoin(dirname, tmp_name)
 
192
 
 
193
    # Rename the file out of the way, but keep track if it didn't exist
 
194
    # We don't want to grab just any exception
 
195
    # something like EACCES should prevent us from continuing
 
196
    # The downside is that the rename_func has to throw an exception
 
197
    # with an errno = ENOENT, or NoSuchFile
 
198
    file_existed = False
 
199
    try:
 
200
        rename_func(new, tmp_name)
 
201
    except (errors.NoSuchFile,), e:
 
202
        pass
 
203
    except IOError, e:
 
204
        # RBC 20060103 abstraction leakage: the paramiko SFTP clients rename
 
205
        # function raises an IOError with errno is None when a rename fails.
 
206
        # This then gets caught here.
 
207
        if e.errno not in (None, errno.ENOENT, errno.ENOTDIR):
 
208
            raise
 
209
    except Exception, e:
 
210
        if (getattr(e, 'errno', None) is None
 
211
            or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
 
212
            raise
 
213
    else:
 
214
        file_existed = True
 
215
 
 
216
    success = False
 
217
    try:
 
218
        try:
 
219
            # This may throw an exception, in which case success will
 
220
            # not be set.
 
221
            rename_func(old, new)
 
222
            success = True
 
223
        except (IOError, OSError), e:
 
224
            # source and target may be aliases of each other (e.g. on a
 
225
            # case-insensitive filesystem), so we may have accidentally renamed
 
226
            # source by when we tried to rename target
 
227
            if not (file_existed and e.errno in (None, errno.ENOENT)):
 
228
                raise
 
229
    finally:
 
230
        if file_existed:
 
231
            # If the file used to exist, rename it back into place
 
232
            # otherwise just delete it from the tmp location
 
233
            if success:
 
234
                unlink_func(tmp_name)
 
235
            else:
 
236
                rename_func(tmp_name, new)
 
237
 
 
238
 
 
239
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
 
240
# choke on a Unicode string containing a relative path if
 
241
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
 
242
# string.
 
243
_fs_enc = sys.getfilesystemencoding() or 'utf-8'
 
244
def _posix_abspath(path):
 
245
    # jam 20060426 rather than encoding to fsencoding
 
246
    # copy posixpath.abspath, but use os.getcwdu instead
 
247
    if not posixpath.isabs(path):
 
248
        path = posixpath.join(getcwd(), path)
 
249
    return posixpath.normpath(path)
 
250
 
 
251
 
 
252
def _posix_realpath(path):
 
253
    return posixpath.realpath(path.encode(_fs_enc)).decode(_fs_enc)
 
254
 
 
255
 
 
256
def _win32_fixdrive(path):
 
257
    """Force drive letters to be consistent.
 
258
 
 
259
    win32 is inconsistent whether it returns lower or upper case
 
260
    and even if it was consistent the user might type the other
 
261
    so we force it to uppercase
 
262
    running python.exe under cmd.exe return capital C:\\
 
263
    running win32 python inside a cygwin shell returns lowercase c:\\
 
264
    """
 
265
    drive, path = _nt_splitdrive(path)
 
266
    return drive.upper() + path
 
267
 
 
268
 
 
269
def _win32_abspath(path):
 
270
    # Real _nt_abspath doesn't have a problem with a unicode cwd
 
271
    return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
 
272
 
 
273
 
 
274
def _win98_abspath(path):
 
275
    """Return the absolute version of a path.
 
276
    Windows 98 safe implementation (python reimplementation
 
277
    of Win32 API function GetFullPathNameW)
 
278
    """
 
279
    # Corner cases:
 
280
    #   C:\path     => C:/path
 
281
    #   C:/path     => C:/path
 
282
    #   \\HOST\path => //HOST/path
 
283
    #   //HOST/path => //HOST/path
 
284
    #   path        => C:/cwd/path
 
285
    #   /path       => C:/path
 
286
    path = unicode(path)
 
287
    # check for absolute path
 
288
    drive = _nt_splitdrive(path)[0]
 
289
    if drive == '' and path[:2] not in('//','\\\\'):
 
290
        cwd = os.getcwdu()
 
291
        # we cannot simply os.path.join cwd and path
 
292
        # because os.path.join('C:','/path') produce '/path'
 
293
        # and this is incorrect
 
294
        if path[:1] in ('/','\\'):
 
295
            cwd = _nt_splitdrive(cwd)[0]
 
296
            path = path[1:]
 
297
        path = cwd + '\\' + path
 
298
    return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
 
299
 
 
300
if win32utils.winver == 'Windows 98':
 
301
    _win32_abspath = _win98_abspath
 
302
 
 
303
 
 
304
def _win32_realpath(path):
 
305
    # Real _nt_realpath doesn't have a problem with a unicode cwd
 
306
    return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
 
307
 
 
308
 
 
309
def _win32_pathjoin(*args):
 
310
    return _nt_join(*args).replace('\\', '/')
 
311
 
 
312
 
 
313
def _win32_normpath(path):
 
314
    return _win32_fixdrive(_nt_normpath(unicode(path)).replace('\\', '/'))
 
315
 
 
316
 
 
317
def _win32_getcwd():
 
318
    return _win32_fixdrive(os.getcwdu().replace('\\', '/'))
 
319
 
 
320
 
 
321
def _win32_mkdtemp(*args, **kwargs):
 
322
    return _win32_fixdrive(tempfile.mkdtemp(*args, **kwargs).replace('\\', '/'))
 
323
 
 
324
 
 
325
def _win32_rename(old, new):
 
326
    """We expect to be able to atomically replace 'new' with old.
 
327
 
 
328
    On win32, if new exists, it must be moved out of the way first,
 
329
    and then deleted. 
 
330
    """
 
331
    try:
 
332
        fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
 
333
    except OSError, e:
 
334
        if e.errno in (errno.EPERM, errno.EACCES, errno.EBUSY, errno.EINVAL):
 
335
            # If we try to rename a non-existant file onto cwd, we get 
 
336
            # EPERM or EACCES instead of ENOENT, this will raise ENOENT 
 
337
            # if the old path doesn't exist, sometimes we get EACCES
 
338
            # On Linux, we seem to get EBUSY, on Mac we get EINVAL
 
339
            os.lstat(old)
 
340
        raise
 
341
 
 
342
 
 
343
def _mac_getcwd():
 
344
    return unicodedata.normalize('NFC', os.getcwdu())
 
345
 
 
346
 
 
347
# Default is to just use the python builtins, but these can be rebound on
 
348
# particular platforms.
 
349
abspath = _posix_abspath
 
350
realpath = _posix_realpath
 
351
pathjoin = os.path.join
 
352
normpath = os.path.normpath
 
353
getcwd = os.getcwdu
 
354
rename = os.rename
 
355
dirname = os.path.dirname
 
356
basename = os.path.basename
 
357
split = os.path.split
 
358
splitext = os.path.splitext
 
359
# These were already imported into local scope
 
360
# mkdtemp = tempfile.mkdtemp
 
361
# rmtree = shutil.rmtree
 
362
 
 
363
MIN_ABS_PATHLENGTH = 1
 
364
 
 
365
 
 
366
if sys.platform == 'win32':
 
367
    abspath = _win32_abspath
 
368
    realpath = _win32_realpath
 
369
    pathjoin = _win32_pathjoin
 
370
    normpath = _win32_normpath
 
371
    getcwd = _win32_getcwd
 
372
    mkdtemp = _win32_mkdtemp
 
373
    rename = _win32_rename
 
374
 
 
375
    MIN_ABS_PATHLENGTH = 3
 
376
 
 
377
    def _win32_delete_readonly(function, path, excinfo):
 
378
        """Error handler for shutil.rmtree function [for win32]
 
379
        Helps to remove files and dirs marked as read-only.
 
380
        """
 
381
        exception = excinfo[1]
 
382
        if function in (os.remove, os.rmdir) \
 
383
            and isinstance(exception, OSError) \
 
384
            and exception.errno == errno.EACCES:
 
385
            make_writable(path)
 
386
            function(path)
 
387
        else:
 
388
            raise
 
389
 
 
390
    def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
 
391
        """Replacer for shutil.rmtree: could remove readonly dirs/files"""
 
392
        return shutil.rmtree(path, ignore_errors, onerror)
 
393
elif sys.platform == 'darwin':
 
394
    getcwd = _mac_getcwd
 
395
 
 
396
 
 
397
def get_terminal_encoding():
 
398
    """Find the best encoding for printing to the screen.
 
399
 
 
400
    This attempts to check both sys.stdout and sys.stdin to see
 
401
    what encoding they are in, and if that fails it falls back to
 
402
    bzrlib.user_encoding.
 
403
    The problem is that on Windows, locale.getpreferredencoding()
 
404
    is not the same encoding as that used by the console:
 
405
    http://mail.python.org/pipermail/python-list/2003-May/162357.html
 
406
 
 
407
    On my standard US Windows XP, the preferred encoding is
 
408
    cp1252, but the console is cp437
 
409
    """
 
410
    output_encoding = getattr(sys.stdout, 'encoding', None)
 
411
    if not output_encoding:
 
412
        input_encoding = getattr(sys.stdin, 'encoding', None)
 
413
        if not input_encoding:
 
414
            output_encoding = bzrlib.user_encoding
 
415
            mutter('encoding stdout as bzrlib.user_encoding %r', output_encoding)
 
416
        else:
 
417
            output_encoding = input_encoding
 
418
            mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
 
419
    else:
 
420
        mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
 
421
    if output_encoding == 'cp0':
 
422
        # invalid encoding (cp0 means 'no codepage' on Windows)
 
423
        output_encoding = bzrlib.user_encoding
 
424
        mutter('cp0 is invalid encoding.'
 
425
               ' encoding stdout as bzrlib.user_encoding %r', output_encoding)
 
426
    # check encoding
 
427
    try:
 
428
        codecs.lookup(output_encoding)
 
429
    except LookupError:
 
430
        sys.stderr.write('bzr: warning:'
 
431
                         ' unknown terminal encoding %s.\n'
 
432
                         '  Using encoding %s instead.\n'
 
433
                         % (output_encoding, bzrlib.user_encoding)
 
434
                        )
 
435
        output_encoding = bzrlib.user_encoding
 
436
 
 
437
    return output_encoding
 
438
 
 
439
 
 
440
def normalizepath(f):
 
441
    if getattr(os.path, 'realpath', None) is not None:
 
442
        F = realpath
 
443
    else:
 
444
        F = abspath
 
445
    [p,e] = os.path.split(f)
 
446
    if e == "" or e == "." or e == "..":
 
447
        return F(f)
 
448
    else:
 
449
        return pathjoin(F(p), e)
 
450
 
 
451
 
 
452
def isdir(f):
 
453
    """True if f is an accessible directory."""
 
454
    try:
 
455
        return S_ISDIR(os.lstat(f)[ST_MODE])
 
456
    except OSError:
 
457
        return False
 
458
 
 
459
 
 
460
def isfile(f):
 
461
    """True if f is a regular file."""
 
462
    try:
 
463
        return S_ISREG(os.lstat(f)[ST_MODE])
 
464
    except OSError:
 
465
        return False
 
466
 
 
467
def islink(f):
 
468
    """True if f is a symlink."""
 
469
    try:
 
470
        return S_ISLNK(os.lstat(f)[ST_MODE])
 
471
    except OSError:
 
472
        return False
 
473
 
 
474
def is_inside(dir, fname):
 
475
    """True if fname is inside dir.
 
476
    
 
477
    The parameters should typically be passed to osutils.normpath first, so
 
478
    that . and .. and repeated slashes are eliminated, and the separators
 
479
    are canonical for the platform.
 
480
    
 
481
    The empty string as a dir name is taken as top-of-tree and matches 
 
482
    everything.
 
483
    """
 
484
    # XXX: Most callers of this can actually do something smarter by 
 
485
    # looking at the inventory
 
486
    if dir == fname:
 
487
        return True
 
488
    
 
489
    if dir == '':
 
490
        return True
 
491
 
 
492
    if dir[-1] != '/':
 
493
        dir += '/'
 
494
 
 
495
    return fname.startswith(dir)
 
496
 
 
497
 
 
498
def is_inside_any(dir_list, fname):
 
499
    """True if fname is inside any of given dirs."""
 
500
    for dirname in dir_list:
 
501
        if is_inside(dirname, fname):
 
502
            return True
 
503
    return False
 
504
 
 
505
 
 
506
def is_inside_or_parent_of_any(dir_list, fname):
 
507
    """True if fname is a child or a parent of any of the given files."""
 
508
    for dirname in dir_list:
 
509
        if is_inside(dirname, fname) or is_inside(fname, dirname):
 
510
            return True
 
511
    return False
 
512
 
 
513
 
 
514
def pumpfile(from_file, to_file, read_length=-1, buff_size=32768):
 
515
    """Copy contents of one file to another.
 
516
 
 
517
    The read_length can either be -1 to read to end-of-file (EOF) or
 
518
    it can specify the maximum number of bytes to read.
 
519
 
 
520
    The buff_size represents the maximum size for each read operation
 
521
    performed on from_file.
 
522
 
 
523
    :return: The number of bytes copied.
 
524
    """
 
525
    length = 0
 
526
    if read_length >= 0:
 
527
        # read specified number of bytes
 
528
 
 
529
        while read_length > 0:
 
530
            num_bytes_to_read = min(read_length, buff_size)
 
531
 
 
532
            block = from_file.read(num_bytes_to_read)
 
533
            if not block:
 
534
                # EOF reached
 
535
                break
 
536
            to_file.write(block)
 
537
 
 
538
            actual_bytes_read = len(block)
 
539
            read_length -= actual_bytes_read
 
540
            length += actual_bytes_read
 
541
    else:
 
542
        # read to EOF
 
543
        while True:
 
544
            block = from_file.read(buff_size)
 
545
            if not block:
 
546
                # EOF reached
 
547
                break
 
548
            to_file.write(block)
 
549
            length += len(block)
 
550
    return length
 
551
 
 
552
 
 
553
def pump_string_file(bytes, file_handle, segment_size=None):
 
554
    """Write bytes to file_handle in many smaller writes.
 
555
 
 
556
    :param bytes: The string to write.
 
557
    :param file_handle: The file to write to.
 
558
    """
 
559
    # Write data in chunks rather than all at once, because very large
 
560
    # writes fail on some platforms (e.g. Windows with SMB  mounted
 
561
    # drives).
 
562
    if not segment_size:
 
563
        segment_size = 5242880 # 5MB
 
564
    segments = range(len(bytes) / segment_size + 1)
 
565
    write = file_handle.write
 
566
    for segment_index in segments:
 
567
        segment = buffer(bytes, segment_index * segment_size, segment_size)
 
568
        write(segment)
 
569
 
 
570
 
 
571
def file_iterator(input_file, readsize=32768):
 
572
    while True:
 
573
        b = input_file.read(readsize)
 
574
        if len(b) == 0:
 
575
            break
 
576
        yield b
 
577
 
 
578
 
 
579
def sha_file(f):
 
580
    """Calculate the hexdigest of an open file.
 
581
 
 
582
    The file cursor should be already at the start.
 
583
    """
 
584
    s = sha()
 
585
    BUFSIZE = 128<<10
 
586
    while True:
 
587
        b = f.read(BUFSIZE)
 
588
        if not b:
 
589
            break
 
590
        s.update(b)
 
591
    return s.hexdigest()
 
592
 
 
593
 
 
594
def sha_file_by_name(fname):
 
595
    """Calculate the SHA1 of a file by reading the full text"""
 
596
    s = sha()
 
597
    f = os.open(fname, os.O_RDONLY | O_BINARY)
 
598
    try:
 
599
        while True:
 
600
            b = os.read(f, 1<<16)
 
601
            if not b:
 
602
                return s.hexdigest()
 
603
            s.update(b)
 
604
    finally:
 
605
        os.close(f)
 
606
 
 
607
 
 
608
def sha_strings(strings, _factory=sha):
 
609
    """Return the sha-1 of concatenation of strings"""
 
610
    s = _factory()
 
611
    map(s.update, strings)
 
612
    return s.hexdigest()
 
613
 
 
614
 
 
615
def sha_string(f, _factory=sha):
 
616
    return _factory(f).hexdigest()
 
617
 
 
618
 
 
619
def fingerprint_file(f):
 
620
    b = f.read()
 
621
    return {'size': len(b),
 
622
            'sha1': sha(b).hexdigest()}
 
623
 
 
624
 
 
625
def compare_files(a, b):
 
626
    """Returns true if equal in contents"""
 
627
    BUFSIZE = 4096
 
628
    while True:
 
629
        ai = a.read(BUFSIZE)
 
630
        bi = b.read(BUFSIZE)
 
631
        if ai != bi:
 
632
            return False
 
633
        if ai == '':
 
634
            return True
 
635
 
 
636
 
 
637
def local_time_offset(t=None):
 
638
    """Return offset of local zone from GMT, either at present or at time t."""
 
639
    if t is None:
 
640
        t = time.time()
 
641
    offset = datetime.fromtimestamp(t) - datetime.utcfromtimestamp(t)
 
642
    return offset.days * 86400 + offset.seconds
 
643
 
 
644
weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
 
645
    
 
646
def format_date(t, offset=0, timezone='original', date_fmt=None,
 
647
                show_offset=True):
 
648
    """Return a formatted date string.
 
649
 
 
650
    :param t: Seconds since the epoch.
 
651
    :param offset: Timezone offset in seconds east of utc.
 
652
    :param timezone: How to display the time: 'utc', 'original' for the
 
653
         timezone specified by offset, or 'local' for the process's current
 
654
         timezone.
 
655
    :param show_offset: Whether to append the timezone.
 
656
    :param date_fmt: strftime format.
 
657
    """
 
658
    if timezone == 'utc':
 
659
        tt = time.gmtime(t)
 
660
        offset = 0
 
661
    elif timezone == 'original':
 
662
        if offset is None:
 
663
            offset = 0
 
664
        tt = time.gmtime(t + offset)
 
665
    elif timezone == 'local':
 
666
        tt = time.localtime(t)
 
667
        offset = local_time_offset(t)
 
668
    else:
 
669
        raise errors.UnsupportedTimezoneFormat(timezone)
 
670
    if date_fmt is None:
 
671
        date_fmt = "%a %Y-%m-%d %H:%M:%S"
 
672
    if show_offset:
 
673
        offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
 
674
    else:
 
675
        offset_str = ''
 
676
    # day of week depends on locale, so we do this ourself
 
677
    date_fmt = date_fmt.replace('%a', weekdays[tt[6]])
 
678
    return (time.strftime(date_fmt, tt) +  offset_str)
 
679
 
 
680
 
 
681
def compact_date(when):
 
682
    return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
 
683
    
 
684
 
 
685
def format_delta(delta):
 
686
    """Get a nice looking string for a time delta.
 
687
 
 
688
    :param delta: The time difference in seconds, can be positive or negative.
 
689
        positive indicates time in the past, negative indicates time in the
 
690
        future. (usually time.time() - stored_time)
 
691
    :return: String formatted to show approximate resolution
 
692
    """
 
693
    delta = int(delta)
 
694
    if delta >= 0:
 
695
        direction = 'ago'
 
696
    else:
 
697
        direction = 'in the future'
 
698
        delta = -delta
 
699
 
 
700
    seconds = delta
 
701
    if seconds < 90: # print seconds up to 90 seconds
 
702
        if seconds == 1:
 
703
            return '%d second %s' % (seconds, direction,)
 
704
        else:
 
705
            return '%d seconds %s' % (seconds, direction)
 
706
 
 
707
    minutes = int(seconds / 60)
 
708
    seconds -= 60 * minutes
 
709
    if seconds == 1:
 
710
        plural_seconds = ''
 
711
    else:
 
712
        plural_seconds = 's'
 
713
    if minutes < 90: # print minutes, seconds up to 90 minutes
 
714
        if minutes == 1:
 
715
            return '%d minute, %d second%s %s' % (
 
716
                    minutes, seconds, plural_seconds, direction)
 
717
        else:
 
718
            return '%d minutes, %d second%s %s' % (
 
719
                    minutes, seconds, plural_seconds, direction)
 
720
 
 
721
    hours = int(minutes / 60)
 
722
    minutes -= 60 * hours
 
723
    if minutes == 1:
 
724
        plural_minutes = ''
 
725
    else:
 
726
        plural_minutes = 's'
 
727
 
 
728
    if hours == 1:
 
729
        return '%d hour, %d minute%s %s' % (hours, minutes,
 
730
                                            plural_minutes, direction)
 
731
    return '%d hours, %d minute%s %s' % (hours, minutes,
 
732
                                         plural_minutes, direction)
 
733
 
 
734
def filesize(f):
 
735
    """Return size of given open file."""
 
736
    return os.fstat(f.fileno())[ST_SIZE]
 
737
 
 
738
 
 
739
# Define rand_bytes based on platform.
 
740
try:
 
741
    # Python 2.4 and later have os.urandom,
 
742
    # but it doesn't work on some arches
 
743
    os.urandom(1)
 
744
    rand_bytes = os.urandom
 
745
except (NotImplementedError, AttributeError):
 
746
    # If python doesn't have os.urandom, or it doesn't work,
 
747
    # then try to first pull random data from /dev/urandom
 
748
    try:
 
749
        rand_bytes = file('/dev/urandom', 'rb').read
 
750
    # Otherwise, use this hack as a last resort
 
751
    except (IOError, OSError):
 
752
        # not well seeded, but better than nothing
 
753
        def rand_bytes(n):
 
754
            import random
 
755
            s = ''
 
756
            while n:
 
757
                s += chr(random.randint(0, 255))
 
758
                n -= 1
 
759
            return s
 
760
 
 
761
 
 
762
ALNUM = '0123456789abcdefghijklmnopqrstuvwxyz'
 
763
def rand_chars(num):
 
764
    """Return a random string of num alphanumeric characters
 
765
    
 
766
    The result only contains lowercase chars because it may be used on 
 
767
    case-insensitive filesystems.
 
768
    """
 
769
    s = ''
 
770
    for raw_byte in rand_bytes(num):
 
771
        s += ALNUM[ord(raw_byte) % 36]
 
772
    return s
 
773
 
 
774
 
 
775
## TODO: We could later have path objects that remember their list
 
776
## decomposition (might be too tricksy though.)
 
777
 
 
778
def splitpath(p):
 
779
    """Turn string into list of parts."""
 
780
    # split on either delimiter because people might use either on
 
781
    # Windows
 
782
    ps = re.split(r'[\\/]', p)
 
783
 
 
784
    rps = []
 
785
    for f in ps:
 
786
        if f == '..':
 
787
            raise errors.BzrError("sorry, %r not allowed in path" % f)
 
788
        elif (f == '.') or (f == ''):
 
789
            pass
 
790
        else:
 
791
            rps.append(f)
 
792
    return rps
 
793
 
 
794
def joinpath(p):
 
795
    for f in p:
 
796
        if (f == '..') or (f is None) or (f == ''):
 
797
            raise errors.BzrError("sorry, %r not allowed in path" % f)
 
798
    return pathjoin(*p)
 
799
 
 
800
 
 
801
def split_lines(s):
 
802
    """Split s into lines, but without removing the newline characters."""
 
803
    lines = s.split('\n')
 
804
    result = [line + '\n' for line in lines[:-1]]
 
805
    if lines[-1]:
 
806
        result.append(lines[-1])
 
807
    return result
 
808
 
 
809
 
 
810
def hardlinks_good():
 
811
    return sys.platform not in ('win32', 'cygwin', 'darwin')
 
812
 
 
813
 
 
814
def link_or_copy(src, dest):
 
815
    """Hardlink a file, or copy it if it can't be hardlinked."""
 
816
    if not hardlinks_good():
 
817
        shutil.copyfile(src, dest)
 
818
        return
 
819
    try:
 
820
        os.link(src, dest)
 
821
    except (OSError, IOError), e:
 
822
        if e.errno != errno.EXDEV:
 
823
            raise
 
824
        shutil.copyfile(src, dest)
 
825
 
 
826
 
 
827
# Look Before You Leap (LBYL) is appropriate here instead of Easier to Ask for
 
828
# Forgiveness than Permission (EAFP) because:
 
829
# - root can damage a solaris file system by using unlink,
 
830
# - unlink raises different exceptions on different OSes (linux: EISDIR, win32:
 
831
#   EACCES, OSX: EPERM) when invoked on a directory.
 
832
def delete_any(path):
 
833
    """Delete a file or directory."""
 
834
    if isdir(path): # Takes care of symlinks
 
835
        os.rmdir(path)
 
836
    else:
 
837
        os.unlink(path)
 
838
 
 
839
 
 
840
def has_symlinks():
 
841
    if getattr(os, 'symlink', None) is not None:
 
842
        return True
 
843
    else:
 
844
        return False
 
845
 
 
846
 
 
847
def has_hardlinks():
 
848
    if getattr(os, 'link', None) is not None:
 
849
        return True
 
850
    else:
 
851
        return False
 
852
 
 
853
 
 
854
def host_os_dereferences_symlinks():
 
855
    return (has_symlinks()
 
856
            and sys.platform not in ('cygwin', 'win32'))
 
857
 
 
858
 
 
859
def contains_whitespace(s):
 
860
    """True if there are any whitespace characters in s."""
 
861
    # string.whitespace can include '\xa0' in certain locales, because it is
 
862
    # considered "non-breaking-space" as part of ISO-8859-1. But it
 
863
    # 1) Isn't a breaking whitespace
 
864
    # 2) Isn't one of ' \t\r\n' which are characters we sometimes use as
 
865
    #    separators
 
866
    # 3) '\xa0' isn't unicode safe since it is >128.
 
867
 
 
868
    # This should *not* be a unicode set of characters in case the source
 
869
    # string is not a Unicode string. We can auto-up-cast the characters since
 
870
    # they are ascii, but we don't want to auto-up-cast the string in case it
 
871
    # is utf-8
 
872
    for ch in ' \t\n\r\v\f':
 
873
        if ch in s:
 
874
            return True
 
875
    else:
 
876
        return False
 
877
 
 
878
 
 
879
def contains_linebreaks(s):
 
880
    """True if there is any vertical whitespace in s."""
 
881
    for ch in '\f\n\r':
 
882
        if ch in s:
 
883
            return True
 
884
    else:
 
885
        return False
 
886
 
 
887
 
 
888
def relpath(base, path):
 
889
    """Return path relative to base, or raise exception.
 
890
 
 
891
    The path may be either an absolute path or a path relative to the
 
892
    current working directory.
 
893
 
 
894
    os.path.commonprefix (python2.4) has a bad bug that it works just
 
895
    on string prefixes, assuming that '/u' is a prefix of '/u2'.  This
 
896
    avoids that problem.
 
897
    """
 
898
 
 
899
    if len(base) < MIN_ABS_PATHLENGTH:
 
900
        # must have space for e.g. a drive letter
 
901
        raise ValueError('%r is too short to calculate a relative path'
 
902
            % (base,))
 
903
 
 
904
    rp = abspath(path)
 
905
 
 
906
    s = []
 
907
    head = rp
 
908
    while len(head) >= len(base):
 
909
        if head == base:
 
910
            break
 
911
        head, tail = os.path.split(head)
 
912
        if tail:
 
913
            s.insert(0, tail)
 
914
    else:
 
915
        raise errors.PathNotChild(rp, base)
 
916
 
 
917
    if s:
 
918
        return pathjoin(*s)
 
919
    else:
 
920
        return ''
 
921
 
 
922
 
 
923
def safe_unicode(unicode_or_utf8_string):
 
924
    """Coerce unicode_or_utf8_string into unicode.
 
925
 
 
926
    If it is unicode, it is returned.
 
927
    Otherwise it is decoded from utf-8. If a decoding error
 
928
    occurs, it is wrapped as a If the decoding fails, the exception is wrapped 
 
929
    as a BzrBadParameter exception.
 
930
    """
 
931
    if isinstance(unicode_or_utf8_string, unicode):
 
932
        return unicode_or_utf8_string
 
933
    try:
 
934
        return unicode_or_utf8_string.decode('utf8')
 
935
    except UnicodeDecodeError:
 
936
        raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
 
937
 
 
938
 
 
939
def safe_utf8(unicode_or_utf8_string):
 
940
    """Coerce unicode_or_utf8_string to a utf8 string.
 
941
 
 
942
    If it is a str, it is returned.
 
943
    If it is Unicode, it is encoded into a utf-8 string.
 
944
    """
 
945
    if isinstance(unicode_or_utf8_string, str):
 
946
        # TODO: jam 20070209 This is overkill, and probably has an impact on
 
947
        #       performance if we are dealing with lots of apis that want a
 
948
        #       utf-8 revision id
 
949
        try:
 
950
            # Make sure it is a valid utf-8 string
 
951
            unicode_or_utf8_string.decode('utf-8')
 
952
        except UnicodeDecodeError:
 
953
            raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
 
954
        return unicode_or_utf8_string
 
955
    return unicode_or_utf8_string.encode('utf-8')
 
956
 
 
957
 
 
958
_revision_id_warning = ('Unicode revision ids were deprecated in bzr 0.15.'
 
959
                        ' Revision id generators should be creating utf8'
 
960
                        ' revision ids.')
 
961
 
 
962
 
 
963
def safe_revision_id(unicode_or_utf8_string, warn=True):
 
964
    """Revision ids should now be utf8, but at one point they were unicode.
 
965
 
 
966
    :param unicode_or_utf8_string: A possibly Unicode revision_id. (can also be
 
967
        utf8 or None).
 
968
    :param warn: Functions that are sanitizing user data can set warn=False
 
969
    :return: None or a utf8 revision id.
 
970
    """
 
971
    if (unicode_or_utf8_string is None
 
972
        or unicode_or_utf8_string.__class__ == str):
 
973
        return unicode_or_utf8_string
 
974
    if warn:
 
975
        symbol_versioning.warn(_revision_id_warning, DeprecationWarning,
 
976
                               stacklevel=2)
 
977
    return cache_utf8.encode(unicode_or_utf8_string)
 
978
 
 
979
 
 
980
_file_id_warning = ('Unicode file ids were deprecated in bzr 0.15. File id'
 
981
                    ' generators should be creating utf8 file ids.')
 
982
 
 
983
 
 
984
def safe_file_id(unicode_or_utf8_string, warn=True):
 
985
    """File ids should now be utf8, but at one point they were unicode.
 
986
 
 
987
    This is the same as safe_utf8, except it uses the cached encode functions
 
988
    to save a little bit of performance.
 
989
 
 
990
    :param unicode_or_utf8_string: A possibly Unicode file_id. (can also be
 
991
        utf8 or None).
 
992
    :param warn: Functions that are sanitizing user data can set warn=False
 
993
    :return: None or a utf8 file id.
 
994
    """
 
995
    if (unicode_or_utf8_string is None
 
996
        or unicode_or_utf8_string.__class__ == str):
 
997
        return unicode_or_utf8_string
 
998
    if warn:
 
999
        symbol_versioning.warn(_file_id_warning, DeprecationWarning,
 
1000
                               stacklevel=2)
 
1001
    return cache_utf8.encode(unicode_or_utf8_string)
 
1002
 
 
1003
 
 
1004
_platform_normalizes_filenames = False
 
1005
if sys.platform == 'darwin':
 
1006
    _platform_normalizes_filenames = True
 
1007
 
 
1008
 
 
1009
def normalizes_filenames():
 
1010
    """Return True if this platform normalizes unicode filenames.
 
1011
 
 
1012
    Mac OSX does, Windows/Linux do not.
 
1013
    """
 
1014
    return _platform_normalizes_filenames
 
1015
 
 
1016
 
 
1017
def _accessible_normalized_filename(path):
 
1018
    """Get the unicode normalized path, and if you can access the file.
 
1019
 
 
1020
    On platforms where the system normalizes filenames (Mac OSX),
 
1021
    you can access a file by any path which will normalize correctly.
 
1022
    On platforms where the system does not normalize filenames 
 
1023
    (Windows, Linux), you have to access a file by its exact path.
 
1024
 
 
1025
    Internally, bzr only supports NFC normalization, since that is 
 
1026
    the standard for XML documents.
 
1027
 
 
1028
    So return the normalized path, and a flag indicating if the file
 
1029
    can be accessed by that path.
 
1030
    """
 
1031
 
 
1032
    return unicodedata.normalize('NFC', unicode(path)), True
 
1033
 
 
1034
 
 
1035
def _inaccessible_normalized_filename(path):
 
1036
    __doc__ = _accessible_normalized_filename.__doc__
 
1037
 
 
1038
    normalized = unicodedata.normalize('NFC', unicode(path))
 
1039
    return normalized, normalized == path
 
1040
 
 
1041
 
 
1042
if _platform_normalizes_filenames:
 
1043
    normalized_filename = _accessible_normalized_filename
 
1044
else:
 
1045
    normalized_filename = _inaccessible_normalized_filename
 
1046
 
 
1047
 
 
1048
def terminal_width():
 
1049
    """Return estimated terminal width."""
 
1050
    if sys.platform == 'win32':
 
1051
        return win32utils.get_console_size()[0]
 
1052
    width = 0
 
1053
    try:
 
1054
        import struct, fcntl, termios
 
1055
        s = struct.pack('HHHH', 0, 0, 0, 0)
 
1056
        x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
 
1057
        width = struct.unpack('HHHH', x)[1]
 
1058
    except IOError:
 
1059
        pass
 
1060
    if width <= 0:
 
1061
        try:
 
1062
            width = int(os.environ['COLUMNS'])
 
1063
        except:
 
1064
            pass
 
1065
    if width <= 0:
 
1066
        width = 80
 
1067
 
 
1068
    return width
 
1069
 
 
1070
 
 
1071
def supports_executable():
 
1072
    return sys.platform != "win32"
 
1073
 
 
1074
 
 
1075
def supports_posix_readonly():
 
1076
    """Return True if 'readonly' has POSIX semantics, False otherwise.
 
1077
 
 
1078
    Notably, a win32 readonly file cannot be deleted, unlike POSIX where the
 
1079
    directory controls creation/deletion, etc.
 
1080
 
 
1081
    And under win32, readonly means that the directory itself cannot be
 
1082
    deleted.  The contents of a readonly directory can be changed, unlike POSIX
 
1083
    where files in readonly directories cannot be added, deleted or renamed.
 
1084
    """
 
1085
    return sys.platform != "win32"
 
1086
 
 
1087
 
 
1088
def set_or_unset_env(env_variable, value):
 
1089
    """Modify the environment, setting or removing the env_variable.
 
1090
 
 
1091
    :param env_variable: The environment variable in question
 
1092
    :param value: The value to set the environment to. If None, then
 
1093
        the variable will be removed.
 
1094
    :return: The original value of the environment variable.
 
1095
    """
 
1096
    orig_val = os.environ.get(env_variable)
 
1097
    if value is None:
 
1098
        if orig_val is not None:
 
1099
            del os.environ[env_variable]
 
1100
    else:
 
1101
        if isinstance(value, unicode):
 
1102
            value = value.encode(bzrlib.user_encoding)
 
1103
        os.environ[env_variable] = value
 
1104
    return orig_val
 
1105
 
 
1106
 
 
1107
_validWin32PathRE = re.compile(r'^([A-Za-z]:[/\\])?[^:<>*"?\|]*$')
 
1108
 
 
1109
 
 
1110
def check_legal_path(path):
 
1111
    """Check whether the supplied path is legal.  
 
1112
    This is only required on Windows, so we don't test on other platforms
 
1113
    right now.
 
1114
    """
 
1115
    if sys.platform != "win32":
 
1116
        return
 
1117
    if _validWin32PathRE.match(path) is None:
 
1118
        raise errors.IllegalPath(path)
 
1119
 
 
1120
 
 
1121
_WIN32_ERROR_DIRECTORY = 267 # Similar to errno.ENOTDIR
 
1122
 
 
1123
def _is_error_enotdir(e):
 
1124
    """Check if this exception represents ENOTDIR.
 
1125
 
 
1126
    Unfortunately, python is very inconsistent about the exception
 
1127
    here. The cases are:
 
1128
      1) Linux, Mac OSX all versions seem to set errno == ENOTDIR
 
1129
      2) Windows, Python2.4, uses errno == ERROR_DIRECTORY (267)
 
1130
         which is the windows error code.
 
1131
      3) Windows, Python2.5 uses errno == EINVAL and
 
1132
         winerror == ERROR_DIRECTORY
 
1133
 
 
1134
    :param e: An Exception object (expected to be OSError with an errno
 
1135
        attribute, but we should be able to cope with anything)
 
1136
    :return: True if this represents an ENOTDIR error. False otherwise.
 
1137
    """
 
1138
    en = getattr(e, 'errno', None)
 
1139
    if (en == errno.ENOTDIR
 
1140
        or (sys.platform == 'win32'
 
1141
            and (en == _WIN32_ERROR_DIRECTORY
 
1142
                 or (en == errno.EINVAL
 
1143
                     and getattr(e, 'winerror', None) == _WIN32_ERROR_DIRECTORY)
 
1144
        ))):
 
1145
        return True
 
1146
    return False
 
1147
 
 
1148
 
 
1149
def walkdirs(top, prefix=""):
 
1150
    """Yield data about all the directories in a tree.
 
1151
    
 
1152
    This yields all the data about the contents of a directory at a time.
 
1153
    After each directory has been yielded, if the caller has mutated the list
 
1154
    to exclude some directories, they are then not descended into.
 
1155
    
 
1156
    The data yielded is of the form:
 
1157
    ((directory-relpath, directory-path-from-top),
 
1158
    [(relpath, basename, kind, lstat, path-from-top), ...]),
 
1159
     - directory-relpath is the relative path of the directory being returned
 
1160
       with respect to top. prefix is prepended to this.
 
1161
     - directory-path-from-root is the path including top for this directory. 
 
1162
       It is suitable for use with os functions.
 
1163
     - relpath is the relative path within the subtree being walked.
 
1164
     - basename is the basename of the path
 
1165
     - kind is the kind of the file now. If unknown then the file is not
 
1166
       present within the tree - but it may be recorded as versioned. See
 
1167
       versioned_kind.
 
1168
     - lstat is the stat data *if* the file was statted.
 
1169
     - planned, not implemented: 
 
1170
       path_from_tree_root is the path from the root of the tree.
 
1171
 
 
1172
    :param prefix: Prefix the relpaths that are yielded with 'prefix'. This 
 
1173
        allows one to walk a subtree but get paths that are relative to a tree
 
1174
        rooted higher up.
 
1175
    :return: an iterator over the dirs.
 
1176
    """
 
1177
    #TODO there is a bit of a smell where the results of the directory-
 
1178
    # summary in this, and the path from the root, may not agree 
 
1179
    # depending on top and prefix - i.e. ./foo and foo as a pair leads to
 
1180
    # potentially confusing output. We should make this more robust - but
 
1181
    # not at a speed cost. RBC 20060731
 
1182
    _lstat = os.lstat
 
1183
    _directory = _directory_kind
 
1184
    _listdir = os.listdir
 
1185
    _kind_from_mode = file_kind_from_stat_mode
 
1186
    pending = [(safe_unicode(prefix), "", _directory, None, safe_unicode(top))]
 
1187
    while pending:
 
1188
        # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
 
1189
        relroot, _, _, _, top = pending.pop()
 
1190
        if relroot:
 
1191
            relprefix = relroot + u'/'
 
1192
        else:
 
1193
            relprefix = ''
 
1194
        top_slash = top + u'/'
 
1195
 
 
1196
        dirblock = []
 
1197
        append = dirblock.append
 
1198
        try:
 
1199
            names = sorted(_listdir(top))
 
1200
        except OSError, e:
 
1201
            if not _is_error_enotdir(e):
 
1202
                raise
 
1203
        else:
 
1204
            for name in names:
 
1205
                abspath = top_slash + name
 
1206
                statvalue = _lstat(abspath)
 
1207
                kind = _kind_from_mode(statvalue.st_mode)
 
1208
                append((relprefix + name, name, kind, statvalue, abspath))
 
1209
        yield (relroot, top), dirblock
 
1210
 
 
1211
        # push the user specified dirs from dirblock
 
1212
        pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
 
1213
 
 
1214
 
 
1215
class DirReader(object):
 
1216
    """An interface for reading directories."""
 
1217
 
 
1218
    def top_prefix_to_starting_dir(self, top, prefix=""):
 
1219
        """Converts top and prefix to a starting dir entry
 
1220
 
 
1221
        :param top: A utf8 path
 
1222
        :param prefix: An optional utf8 path to prefix output relative paths
 
1223
            with.
 
1224
        :return: A tuple starting with prefix, and ending with the native
 
1225
            encoding of top.
 
1226
        """
 
1227
        raise NotImplementedError(self.top_prefix_to_starting_dir)
 
1228
 
 
1229
    def read_dir(self, prefix, top):
 
1230
        """Read a specific dir.
 
1231
 
 
1232
        :param prefix: A utf8 prefix to be preprended to the path basenames.
 
1233
        :param top: A natively encoded path to read.
 
1234
        :return: A list of the directories contents. Each item contains:
 
1235
            (utf8_relpath, utf8_name, kind, lstatvalue, native_abspath)
 
1236
        """
 
1237
        raise NotImplementedError(self.read_dir)
 
1238
 
 
1239
 
 
1240
_selected_dir_reader = None
 
1241
 
 
1242
 
 
1243
def _walkdirs_utf8(top, prefix=""):
 
1244
    """Yield data about all the directories in a tree.
 
1245
 
 
1246
    This yields the same information as walkdirs() only each entry is yielded
 
1247
    in utf-8. On platforms which have a filesystem encoding of utf8 the paths
 
1248
    are returned as exact byte-strings.
 
1249
 
 
1250
    :return: yields a tuple of (dir_info, [file_info])
 
1251
        dir_info is (utf8_relpath, path-from-top)
 
1252
        file_info is (utf8_relpath, utf8_name, kind, lstat, path-from-top)
 
1253
        if top is an absolute path, path-from-top is also an absolute path.
 
1254
        path-from-top might be unicode or utf8, but it is the correct path to
 
1255
        pass to os functions to affect the file in question. (such as os.lstat)
 
1256
    """
 
1257
    global _selected_dir_reader
 
1258
    if _selected_dir_reader is None:
 
1259
        fs_encoding = _fs_enc.upper()
 
1260
        if win32utils.winver == 'Windows NT':
 
1261
            # Win98 doesn't have unicode apis like FindFirstFileW
 
1262
            # TODO: We possibly could support Win98 by falling back to the
 
1263
            #       original FindFirstFile, and using TCHAR instead of WCHAR,
 
1264
            #       but that gets a bit tricky, and requires custom compiling
 
1265
            #       for win98 anyway.
 
1266
            try:
 
1267
                from bzrlib._walkdirs_win32 import Win32ReadDir
 
1268
            except ImportError:
 
1269
                _selected_dir_reader = UnicodeDirReader()
 
1270
            else:
 
1271
                _selected_dir_reader = Win32ReadDir()
 
1272
        elif fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
 
1273
            # ANSI_X3.4-1968 is a form of ASCII
 
1274
            _selected_dir_reader = UnicodeDirReader()
 
1275
        else:
 
1276
            try:
 
1277
                from bzrlib._readdir_pyx import UTF8DirReader
 
1278
            except ImportError:
 
1279
                # No optimised code path
 
1280
                _selected_dir_reader = UnicodeDirReader()
 
1281
            else:
 
1282
                _selected_dir_reader = UTF8DirReader()
 
1283
    # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
 
1284
    # But we don't actually uses 1-3 in pending, so set them to None
 
1285
    pending = [[_selected_dir_reader.top_prefix_to_starting_dir(top, prefix)]]
 
1286
    read_dir = _selected_dir_reader.read_dir
 
1287
    _directory = _directory_kind
 
1288
    while pending:
 
1289
        relroot, _, _, _, top = pending[-1].pop()
 
1290
        if not pending[-1]:
 
1291
            pending.pop()
 
1292
        dirblock = sorted(read_dir(relroot, top))
 
1293
        yield (relroot, top), dirblock
 
1294
        # push the user specified dirs from dirblock
 
1295
        next = [d for d in reversed(dirblock) if d[2] == _directory]
 
1296
        if next:
 
1297
            pending.append(next)
 
1298
 
 
1299
 
 
1300
class UnicodeDirReader(DirReader):
 
1301
    """A dir reader for non-utf8 file systems, which transcodes."""
 
1302
 
 
1303
    __slots__ = ['_utf8_encode']
 
1304
 
 
1305
    def __init__(self):
 
1306
        self._utf8_encode = codecs.getencoder('utf8')
 
1307
 
 
1308
    def top_prefix_to_starting_dir(self, top, prefix=""):
 
1309
        """See DirReader.top_prefix_to_starting_dir."""
 
1310
        return (safe_utf8(prefix), None, None, None, safe_unicode(top))
 
1311
 
 
1312
    def read_dir(self, prefix, top):
 
1313
        """Read a single directory from a non-utf8 file system.
 
1314
 
 
1315
        top, and the abspath element in the output are unicode, all other paths
 
1316
        are utf8. Local disk IO is done via unicode calls to listdir etc.
 
1317
 
 
1318
        This is currently the fallback code path when the filesystem encoding is
 
1319
        not UTF-8. It may be better to implement an alternative so that we can
 
1320
        safely handle paths that are not properly decodable in the current
 
1321
        encoding.
 
1322
 
 
1323
        See DirReader.read_dir for details.
 
1324
        """
 
1325
        _utf8_encode = self._utf8_encode
 
1326
        _lstat = os.lstat
 
1327
        _listdir = os.listdir
 
1328
        _kind_from_mode = file_kind_from_stat_mode
 
1329
 
 
1330
        if prefix:
 
1331
            relprefix = prefix + '/'
 
1332
        else:
 
1333
            relprefix = ''
 
1334
        top_slash = top + u'/'
 
1335
 
 
1336
        dirblock = []
 
1337
        append = dirblock.append
 
1338
        for name in sorted(_listdir(top)):
 
1339
            try:
 
1340
                name_utf8 = _utf8_encode(name)[0]
 
1341
            except UnicodeDecodeError:
 
1342
                raise errors.BadFilenameEncoding(
 
1343
                    _utf8_encode(relprefix)[0] + name, _fs_enc)
 
1344
            abspath = top_slash + name
 
1345
            statvalue = _lstat(abspath)
 
1346
            kind = _kind_from_mode(statvalue.st_mode)
 
1347
            append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
 
1348
        return dirblock
 
1349
 
 
1350
 
 
1351
def copy_tree(from_path, to_path, handlers={}):
 
1352
    """Copy all of the entries in from_path into to_path.
 
1353
 
 
1354
    :param from_path: The base directory to copy. 
 
1355
    :param to_path: The target directory. If it does not exist, it will
 
1356
        be created.
 
1357
    :param handlers: A dictionary of functions, which takes a source and
 
1358
        destinations for files, directories, etc.
 
1359
        It is keyed on the file kind, such as 'directory', 'symlink', or 'file'
 
1360
        'file', 'directory', and 'symlink' should always exist.
 
1361
        If they are missing, they will be replaced with 'os.mkdir()',
 
1362
        'os.readlink() + os.symlink()', and 'shutil.copy2()', respectively.
 
1363
    """
 
1364
    # Now, just copy the existing cached tree to the new location
 
1365
    # We use a cheap trick here.
 
1366
    # Absolute paths are prefixed with the first parameter
 
1367
    # relative paths are prefixed with the second.
 
1368
    # So we can get both the source and target returned
 
1369
    # without any extra work.
 
1370
 
 
1371
    def copy_dir(source, dest):
 
1372
        os.mkdir(dest)
 
1373
 
 
1374
    def copy_link(source, dest):
 
1375
        """Copy the contents of a symlink"""
 
1376
        link_to = os.readlink(source)
 
1377
        os.symlink(link_to, dest)
 
1378
 
 
1379
    real_handlers = {'file':shutil.copy2,
 
1380
                     'symlink':copy_link,
 
1381
                     'directory':copy_dir,
 
1382
                    }
 
1383
    real_handlers.update(handlers)
 
1384
 
 
1385
    if not os.path.exists(to_path):
 
1386
        real_handlers['directory'](from_path, to_path)
 
1387
 
 
1388
    for dir_info, entries in walkdirs(from_path, prefix=to_path):
 
1389
        for relpath, name, kind, st, abspath in entries:
 
1390
            real_handlers[kind](abspath, relpath)
 
1391
 
 
1392
 
 
1393
def path_prefix_key(path):
 
1394
    """Generate a prefix-order path key for path.
 
1395
 
 
1396
    This can be used to sort paths in the same way that walkdirs does.
 
1397
    """
 
1398
    return (dirname(path) , path)
 
1399
 
 
1400
 
 
1401
def compare_paths_prefix_order(path_a, path_b):
 
1402
    """Compare path_a and path_b to generate the same order walkdirs uses."""
 
1403
    key_a = path_prefix_key(path_a)
 
1404
    key_b = path_prefix_key(path_b)
 
1405
    return cmp(key_a, key_b)
 
1406
 
 
1407
 
 
1408
_cached_user_encoding = None
 
1409
 
 
1410
 
 
1411
def get_user_encoding(use_cache=True):
 
1412
    """Find out what the preferred user encoding is.
 
1413
 
 
1414
    This is generally the encoding that is used for command line parameters
 
1415
    and file contents. This may be different from the terminal encoding
 
1416
    or the filesystem encoding.
 
1417
 
 
1418
    :param  use_cache:  Enable cache for detected encoding.
 
1419
                        (This parameter is turned on by default,
 
1420
                        and required only for selftesting)
 
1421
 
 
1422
    :return: A string defining the preferred user encoding
 
1423
    """
 
1424
    global _cached_user_encoding
 
1425
    if _cached_user_encoding is not None and use_cache:
 
1426
        return _cached_user_encoding
 
1427
 
 
1428
    if sys.platform == 'darwin':
 
1429
        # python locale.getpreferredencoding() always return
 
1430
        # 'mac-roman' on darwin. That's a lie.
 
1431
        sys.platform = 'posix'
 
1432
        try:
 
1433
            if os.environ.get('LANG', None) is None:
 
1434
                # If LANG is not set, we end up with 'ascii', which is bad
 
1435
                # ('mac-roman' is more than ascii), so we set a default which
 
1436
                # will give us UTF-8 (which appears to work in all cases on
 
1437
                # OSX). Users are still free to override LANG of course, as
 
1438
                # long as it give us something meaningful. This work-around
 
1439
                # *may* not be needed with python 3k and/or OSX 10.5, but will
 
1440
                # work with them too -- vila 20080908
 
1441
                os.environ['LANG'] = 'en_US.UTF-8'
 
1442
            import locale
 
1443
        finally:
 
1444
            sys.platform = 'darwin'
 
1445
    else:
 
1446
        import locale
 
1447
 
 
1448
    try:
 
1449
        user_encoding = locale.getpreferredencoding()
 
1450
    except locale.Error, e:
 
1451
        sys.stderr.write('bzr: warning: %s\n'
 
1452
                         '  Could not determine what text encoding to use.\n'
 
1453
                         '  This error usually means your Python interpreter\n'
 
1454
                         '  doesn\'t support the locale set by $LANG (%s)\n'
 
1455
                         "  Continuing with ascii encoding.\n"
 
1456
                         % (e, os.environ.get('LANG')))
 
1457
        user_encoding = 'ascii'
 
1458
 
 
1459
    # Windows returns 'cp0' to indicate there is no code page. So we'll just
 
1460
    # treat that as ASCII, and not support printing unicode characters to the
 
1461
    # console.
 
1462
    #
 
1463
    # For python scripts run under vim, we get '', so also treat that as ASCII
 
1464
    if user_encoding in (None, 'cp0', ''):
 
1465
        user_encoding = 'ascii'
 
1466
    else:
 
1467
        # check encoding
 
1468
        try:
 
1469
            codecs.lookup(user_encoding)
 
1470
        except LookupError:
 
1471
            sys.stderr.write('bzr: warning:'
 
1472
                             ' unknown encoding %s.'
 
1473
                             ' Continuing with ascii encoding.\n'
 
1474
                             % user_encoding
 
1475
                            )
 
1476
            user_encoding = 'ascii'
 
1477
 
 
1478
    if use_cache:
 
1479
        _cached_user_encoding = user_encoding
 
1480
 
 
1481
    return user_encoding
 
1482
 
 
1483
 
 
1484
def get_host_name():
 
1485
    """Return the current unicode host name.
 
1486
 
 
1487
    This is meant to be used in place of socket.gethostname() because that
 
1488
    behaves inconsistently on different platforms.
 
1489
    """
 
1490
    if sys.platform == "win32":
 
1491
        import win32utils
 
1492
        return win32utils.get_host_name()
 
1493
    else:
 
1494
        import socket
 
1495
        return socket.gethostname().decode(get_user_encoding())
 
1496
 
 
1497
 
 
1498
def recv_all(socket, bytes):
 
1499
    """Receive an exact number of bytes.
 
1500
 
 
1501
    Regular Socket.recv() may return less than the requested number of bytes,
 
1502
    dependning on what's in the OS buffer.  MSG_WAITALL is not available
 
1503
    on all platforms, but this should work everywhere.  This will return
 
1504
    less than the requested amount if the remote end closes.
 
1505
 
 
1506
    This isn't optimized and is intended mostly for use in testing.
 
1507
    """
 
1508
    b = ''
 
1509
    while len(b) < bytes:
 
1510
        new = socket.recv(bytes - len(b))
 
1511
        if new == '':
 
1512
            break # eof
 
1513
        b += new
 
1514
    return b
 
1515
 
 
1516
 
 
1517
def send_all(socket, bytes):
 
1518
    """Send all bytes on a socket.
 
1519
 
 
1520
    Regular socket.sendall() can give socket error 10053 on Windows.  This
 
1521
    implementation sends no more than 64k at a time, which avoids this problem.
 
1522
    """
 
1523
    chunk_size = 2**16
 
1524
    for pos in xrange(0, len(bytes), chunk_size):
 
1525
        socket.sendall(bytes[pos:pos+chunk_size])
 
1526
 
 
1527
 
 
1528
def dereference_path(path):
 
1529
    """Determine the real path to a file.
 
1530
 
 
1531
    All parent elements are dereferenced.  But the file itself is not
 
1532
    dereferenced.
 
1533
    :param path: The original path.  May be absolute or relative.
 
1534
    :return: the real path *to* the file
 
1535
    """
 
1536
    parent, base = os.path.split(path)
 
1537
    # The pathjoin for '.' is a workaround for Python bug #1213894.
 
1538
    # (initial path components aren't dereferenced)
 
1539
    return pathjoin(realpath(pathjoin('.', parent)), base)
 
1540
 
 
1541
 
 
1542
def supports_mapi():
 
1543
    """Return True if we can use MAPI to launch a mail client."""
 
1544
    return sys.platform == "win32"
 
1545
 
 
1546
 
 
1547
def resource_string(package, resource_name):
 
1548
    """Load a resource from a package and return it as a string.
 
1549
 
 
1550
    Note: Only packages that start with bzrlib are currently supported.
 
1551
 
 
1552
    This is designed to be a lightweight implementation of resource
 
1553
    loading in a way which is API compatible with the same API from
 
1554
    pkg_resources. See
 
1555
    http://peak.telecommunity.com/DevCenter/PkgResources#basic-resource-access.
 
1556
    If and when pkg_resources becomes a standard library, this routine
 
1557
    can delegate to it.
 
1558
    """
 
1559
    # Check package name is within bzrlib
 
1560
    if package == "bzrlib":
 
1561
        resource_relpath = resource_name
 
1562
    elif package.startswith("bzrlib."):
 
1563
        package = package[len("bzrlib."):].replace('.', os.sep)
 
1564
        resource_relpath = pathjoin(package, resource_name)
 
1565
    else:
 
1566
        raise errors.BzrError('resource package %s not in bzrlib' % package)
 
1567
 
 
1568
    # Map the resource to a file and read its contents
 
1569
    base = dirname(bzrlib.__file__)
 
1570
    if getattr(sys, 'frozen', None):    # bzr.exe
 
1571
        base = abspath(pathjoin(base, '..', '..'))
 
1572
    filename = pathjoin(base, resource_relpath)
 
1573
    return open(filename, 'rU').read()
 
1574
 
 
1575
 
 
1576
def file_kind_from_stat_mode_thunk(mode):
 
1577
    global file_kind_from_stat_mode
 
1578
    if file_kind_from_stat_mode is file_kind_from_stat_mode_thunk:
 
1579
        try:
 
1580
            from bzrlib._readdir_pyx import UTF8DirReader
 
1581
            file_kind_from_stat_mode = UTF8DirReader().kind_from_mode
 
1582
        except ImportError:
 
1583
            from bzrlib._readdir_py import (
 
1584
                _kind_from_mode as file_kind_from_stat_mode
 
1585
                )
 
1586
    return file_kind_from_stat_mode(mode)
 
1587
file_kind_from_stat_mode = file_kind_from_stat_mode_thunk
 
1588
 
 
1589
 
 
1590
def file_kind(f, _lstat=os.lstat):
 
1591
    try:
 
1592
        return file_kind_from_stat_mode(_lstat(f).st_mode)
 
1593
    except OSError, e:
 
1594
        if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
 
1595
            raise errors.NoSuchFile(f)
 
1596
        raise
 
1597
 
 
1598