~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

Some code cleanup passes.

Show diffs side-by-side

added added

removed removed

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