/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: Andrew Bennetts
  • Date: 2009-12-04 06:13:25 UTC
  • mto: This revision was merged to the branch mainline in revision 4869.
  • Revision ID: andrew.bennetts@canonical.com-20091204061325-8s0wghkp5if1ywiu
Tweaks suggested by John.

Show diffs side-by-side

added added

removed removed

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