/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: Robert Collins
  • Date: 2009-05-12 03:50:39 UTC
  • mto: This revision was merged to the branch mainline in revision 4593.
  • Revision ID: robertc@robertcollins.net-20090512035039-6x0pahpjpkdnm9zb
Note another possible error.

Show diffs side-by-side

added added

removed removed

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