/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: Vincent Ladeuil
  • Date: 2009-12-23 16:02:27 UTC
  • mto: (4597.3.46 description)
  • mto: This revision was merged to the branch mainline in revision 5009.
  • Revision ID: v.ladeuil+lp@free.fr-20091223160227-g74kl2zokg92zsmk
doc/es/user-guide/resolving_conflicts.txt is really the translation of
bzrlib/help-topics/en/conflicts.txt.

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