~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: Robert Collins
  • Date: 2005-10-06 22:15:52 UTC
  • mfrom: (1185.13.2)
  • mto: This revision was merged to the branch mainline in revision 1420.
  • Revision ID: robertc@robertcollins.net-20051006221552-9b15c96fa504e0ad
mergeĀ fromĀ upstream

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006 Canonical Ltd
 
1
# Bazaar-NG -- distributed version control
 
2
#
 
3
# Copyright (C) 2005 by Canonical Ltd
2
4
#
3
5
# This program is free software; you can redistribute it and/or modify
4
6
# it under the terms of the GNU General Public License as published by
14
16
# along with this program; if not, write to the Free Software
15
17
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
18
 
 
19
from shutil import copyfile
 
20
from stat import (S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE,
 
21
                  S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
17
22
from cStringIO import StringIO
 
23
import errno
18
24
import os
19
25
import re
20
 
import stat
21
 
from stat import (S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE,
22
 
                  S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
 
26
import sha
23
27
import sys
24
28
import time
25
 
 
26
 
from bzrlib.lazy_import import lazy_import
27
 
lazy_import(globals(), """
28
 
import codecs
29
 
from datetime import datetime
30
 
import errno
31
 
from ntpath import (abspath as _nt_abspath,
32
 
                    join as _nt_join,
33
 
                    normpath as _nt_normpath,
34
 
                    realpath as _nt_realpath,
35
 
                    splitdrive as _nt_splitdrive,
36
 
                    )
37
 
import posixpath
38
 
import sha
39
 
import shutil
40
 
from shutil import (
41
 
    rmtree,
42
 
    )
43
 
import tempfile
44
 
from tempfile import (
45
 
    mkdtemp,
46
 
    )
47
 
import unicodedata
48
 
 
49
 
from bzrlib import (
50
 
    errors,
51
 
    win32utils,
52
 
    )
53
 
""")
 
29
import types
54
30
 
55
31
import bzrlib
56
 
from bzrlib.symbol_versioning import (
57
 
    deprecated_function,
58
 
    zero_nine,
59
 
    )
 
32
from bzrlib.errors import BzrError
60
33
from bzrlib.trace import mutter
61
34
 
62
35
 
63
 
# On win32, O_BINARY is used to indicate the file should
64
 
# be opened in binary mode, rather than text mode.
65
 
# On other platforms, O_BINARY doesn't exist, because
66
 
# they always open in binary mode, so it is okay to
67
 
# OR with 0 on those platforms
68
 
O_BINARY = getattr(os, 'O_BINARY', 0)
69
 
 
70
 
 
71
36
def make_readonly(filename):
72
37
    """Make a filename read-only."""
73
38
    mod = os.stat(filename).st_mode
91
56
    Windows."""
92
57
    # TODO: I'm not really sure this is the best format either.x
93
58
    global _QUOTE_RE
94
 
    if _QUOTE_RE is None:
 
59
    if _QUOTE_RE == None:
95
60
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
96
61
        
97
62
    if _QUOTE_RE.search(f):
100
65
        return f
101
66
 
102
67
 
103
 
_directory_kind = 'directory'
104
 
 
105
 
_formats = {
106
 
    stat.S_IFDIR:_directory_kind,
107
 
    stat.S_IFCHR:'chardev',
108
 
    stat.S_IFBLK:'block',
109
 
    stat.S_IFREG:'file',
110
 
    stat.S_IFIFO:'fifo',
111
 
    stat.S_IFLNK:'symlink',
112
 
    stat.S_IFSOCK:'socket',
113
 
}
114
 
 
115
 
 
116
 
def file_kind_from_stat_mode(stat_mode, _formats=_formats, _unknown='unknown'):
117
 
    """Generate a file kind from a stat mode. This is used in walkdirs.
118
 
 
119
 
    Its performance is critical: Do not mutate without careful benchmarking.
120
 
    """
121
 
    try:
122
 
        return _formats[stat_mode & 0170000]
123
 
    except KeyError:
124
 
        return _unknown
125
 
 
126
 
 
127
 
def file_kind(f, _lstat=os.lstat, _mapper=file_kind_from_stat_mode):
128
 
    try:
129
 
        return _mapper(_lstat(f).st_mode)
130
 
    except OSError, e:
131
 
        if getattr(e, 'errno', None) == errno.ENOENT:
132
 
            raise errors.NoSuchFile(f)
133
 
        raise
134
 
 
135
 
 
136
 
def get_umask():
137
 
    """Return the current umask"""
138
 
    # Assume that people aren't messing with the umask while running
139
 
    # XXX: This is not thread safe, but there is no way to get the
140
 
    #      umask without setting it
141
 
    umask = os.umask(0)
142
 
    os.umask(umask)
143
 
    return umask
 
68
def file_kind(f):
 
69
    mode = os.lstat(f)[ST_MODE]
 
70
    if S_ISREG(mode):
 
71
        return 'file'
 
72
    elif S_ISDIR(mode):
 
73
        return 'directory'
 
74
    elif S_ISLNK(mode):
 
75
        return 'symlink'
 
76
    elif S_ISCHR(mode):
 
77
        return 'chardev'
 
78
    elif S_ISBLK(mode):
 
79
        return 'block'
 
80
    elif S_ISFIFO(mode):
 
81
        return 'fifo'
 
82
    elif S_ISSOCK(mode):
 
83
        return 'socket'
 
84
    else:
 
85
        return 'unknown'
144
86
 
145
87
 
146
88
def kind_marker(kind):
147
89
    if kind == 'file':
148
90
        return ''
149
 
    elif kind == _directory_kind:
 
91
    elif kind == 'directory':
150
92
        return '/'
151
93
    elif kind == 'symlink':
152
94
        return '@'
153
95
    else:
154
 
        raise errors.BzrError('invalid file kind %r' % kind)
155
 
 
156
 
lexists = getattr(os.path, 'lexists', None)
157
 
if lexists is None:
158
 
    def lexists(f):
159
 
        try:
160
 
            if getattr(os, 'lstat') is not None:
161
 
                os.lstat(f)
162
 
            else:
163
 
                os.stat(f)
164
 
            return True
165
 
        except OSError,e:
166
 
            if e.errno == errno.ENOENT:
167
 
                return False;
168
 
            else:
169
 
                raise errors.BzrError("lstat/stat of (%r): %r" % (f, e))
170
 
 
171
 
 
172
 
def fancy_rename(old, new, rename_func, unlink_func):
173
 
    """A fancy rename, when you don't have atomic rename.
174
 
    
175
 
    :param old: The old path, to rename from
176
 
    :param new: The new path, to rename to
177
 
    :param rename_func: The potentially non-atomic rename function
178
 
    :param unlink_func: A way to delete the target file if the full rename succeeds
179
 
    """
180
 
 
181
 
    # sftp rename doesn't allow overwriting, so play tricks:
182
 
    import random
183
 
    base = os.path.basename(new)
184
 
    dirname = os.path.dirname(new)
185
 
    tmp_name = u'tmp.%s.%.9f.%d.%s' % (base, time.time(), os.getpid(), rand_chars(10))
186
 
    tmp_name = pathjoin(dirname, tmp_name)
187
 
 
188
 
    # Rename the file out of the way, but keep track if it didn't exist
189
 
    # We don't want to grab just any exception
190
 
    # something like EACCES should prevent us from continuing
191
 
    # The downside is that the rename_func has to throw an exception
192
 
    # with an errno = ENOENT, or NoSuchFile
193
 
    file_existed = False
194
 
    try:
195
 
        rename_func(new, tmp_name)
196
 
    except (errors.NoSuchFile,), e:
197
 
        pass
198
 
    except IOError, e:
199
 
        # RBC 20060103 abstraction leakage: the paramiko SFTP clients rename
200
 
        # function raises an IOError with errno is None when a rename fails.
201
 
        # This then gets caught here.
202
 
        if e.errno not in (None, errno.ENOENT, errno.ENOTDIR):
203
 
            raise
204
 
    except Exception, e:
205
 
        if (getattr(e, 'errno', None) is None
206
 
            or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
207
 
            raise
208
 
    else:
209
 
        file_existed = True
210
 
 
211
 
    success = False
212
 
    try:
213
 
        # This may throw an exception, in which case success will
214
 
        # not be set.
215
 
        rename_func(old, new)
216
 
        success = True
217
 
    finally:
218
 
        if file_existed:
219
 
            # If the file used to exist, rename it back into place
220
 
            # otherwise just delete it from the tmp location
221
 
            if success:
222
 
                unlink_func(tmp_name)
223
 
            else:
224
 
                rename_func(tmp_name, new)
225
 
 
226
 
 
227
 
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
228
 
# choke on a Unicode string containing a relative path if
229
 
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
230
 
# string.
231
 
_fs_enc = sys.getfilesystemencoding() or 'utf-8'
232
 
def _posix_abspath(path):
233
 
    # jam 20060426 rather than encoding to fsencoding
234
 
    # copy posixpath.abspath, but use os.getcwdu instead
235
 
    if not posixpath.isabs(path):
236
 
        path = posixpath.join(getcwd(), path)
237
 
    return posixpath.normpath(path)
238
 
 
239
 
 
240
 
def _posix_realpath(path):
241
 
    return posixpath.realpath(path.encode(_fs_enc)).decode(_fs_enc)
242
 
 
243
 
 
244
 
def _win32_fixdrive(path):
245
 
    """Force drive letters to be consistent.
246
 
 
247
 
    win32 is inconsistent whether it returns lower or upper case
248
 
    and even if it was consistent the user might type the other
249
 
    so we force it to uppercase
250
 
    running python.exe under cmd.exe return capital C:\\
251
 
    running win32 python inside a cygwin shell returns lowercase c:\\
252
 
    """
253
 
    drive, path = _nt_splitdrive(path)
254
 
    return drive.upper() + path
255
 
 
256
 
 
257
 
def _win32_abspath(path):
258
 
    # Real _nt_abspath doesn't have a problem with a unicode cwd
259
 
    return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
260
 
 
261
 
 
262
 
def _win32_realpath(path):
263
 
    # Real _nt_realpath doesn't have a problem with a unicode cwd
264
 
    return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
265
 
 
266
 
 
267
 
def _win32_pathjoin(*args):
268
 
    return _nt_join(*args).replace('\\', '/')
269
 
 
270
 
 
271
 
def _win32_normpath(path):
272
 
    return _win32_fixdrive(_nt_normpath(unicode(path)).replace('\\', '/'))
273
 
 
274
 
 
275
 
def _win32_getcwd():
276
 
    return _win32_fixdrive(os.getcwdu().replace('\\', '/'))
277
 
 
278
 
 
279
 
def _win32_mkdtemp(*args, **kwargs):
280
 
    return _win32_fixdrive(tempfile.mkdtemp(*args, **kwargs).replace('\\', '/'))
281
 
 
282
 
 
283
 
def _win32_rename(old, new):
284
 
    """We expect to be able to atomically replace 'new' with old.
285
 
 
286
 
    On win32, if new exists, it must be moved out of the way first,
287
 
    and then deleted. 
288
 
    """
289
 
    try:
290
 
        fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
291
 
    except OSError, e:
292
 
        if e.errno in (errno.EPERM, errno.EACCES, errno.EBUSY, errno.EINVAL):
293
 
            # If we try to rename a non-existant file onto cwd, we get 
294
 
            # EPERM or EACCES instead of ENOENT, this will raise ENOENT 
295
 
            # if the old path doesn't exist, sometimes we get EACCES
296
 
            # On Linux, we seem to get EBUSY, on Mac we get EINVAL
297
 
            os.lstat(old)
298
 
        raise
299
 
 
300
 
 
301
 
def _mac_getcwd():
302
 
    return unicodedata.normalize('NFKC', os.getcwdu())
303
 
 
304
 
 
305
 
# Default is to just use the python builtins, but these can be rebound on
306
 
# particular platforms.
307
 
abspath = _posix_abspath
308
 
realpath = _posix_realpath
309
 
pathjoin = os.path.join
310
 
normpath = os.path.normpath
311
 
getcwd = os.getcwdu
312
 
rename = os.rename
313
 
dirname = os.path.dirname
314
 
basename = os.path.basename
315
 
split = os.path.split
316
 
splitext = os.path.splitext
317
 
# These were already imported into local scope
318
 
# mkdtemp = tempfile.mkdtemp
319
 
# rmtree = shutil.rmtree
320
 
 
321
 
MIN_ABS_PATHLENGTH = 1
322
 
 
323
 
 
324
 
if sys.platform == 'win32':
325
 
    abspath = _win32_abspath
326
 
    realpath = _win32_realpath
327
 
    pathjoin = _win32_pathjoin
328
 
    normpath = _win32_normpath
329
 
    getcwd = _win32_getcwd
330
 
    mkdtemp = _win32_mkdtemp
331
 
    rename = _win32_rename
332
 
 
333
 
    MIN_ABS_PATHLENGTH = 3
334
 
 
335
 
    def _win32_delete_readonly(function, path, excinfo):
336
 
        """Error handler for shutil.rmtree function [for win32]
337
 
        Helps to remove files and dirs marked as read-only.
338
 
        """
339
 
        exception = excinfo[1]
340
 
        if function in (os.remove, os.rmdir) \
341
 
            and isinstance(exception, OSError) \
342
 
            and exception.errno == errno.EACCES:
343
 
            make_writable(path)
344
 
            function(path)
345
 
        else:
346
 
            raise
347
 
 
348
 
    def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
349
 
        """Replacer for shutil.rmtree: could remove readonly dirs/files"""
350
 
        return shutil.rmtree(path, ignore_errors, onerror)
351
 
elif sys.platform == 'darwin':
352
 
    getcwd = _mac_getcwd
353
 
 
354
 
 
355
 
def get_terminal_encoding():
356
 
    """Find the best encoding for printing to the screen.
357
 
 
358
 
    This attempts to check both sys.stdout and sys.stdin to see
359
 
    what encoding they are in, and if that fails it falls back to
360
 
    bzrlib.user_encoding.
361
 
    The problem is that on Windows, locale.getpreferredencoding()
362
 
    is not the same encoding as that used by the console:
363
 
    http://mail.python.org/pipermail/python-list/2003-May/162357.html
364
 
 
365
 
    On my standard US Windows XP, the preferred encoding is
366
 
    cp1252, but the console is cp437
367
 
    """
368
 
    output_encoding = getattr(sys.stdout, 'encoding', None)
369
 
    if not output_encoding:
370
 
        input_encoding = getattr(sys.stdin, 'encoding', None)
371
 
        if not input_encoding:
372
 
            output_encoding = bzrlib.user_encoding
373
 
            mutter('encoding stdout as bzrlib.user_encoding %r', output_encoding)
374
 
        else:
375
 
            output_encoding = input_encoding
376
 
            mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
377
 
    else:
378
 
        mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
379
 
    if output_encoding == 'cp0':
380
 
        # invalid encoding (cp0 means 'no codepage' on Windows)
381
 
        output_encoding = bzrlib.user_encoding
382
 
        mutter('cp0 is invalid encoding.'
383
 
               ' encoding stdout as bzrlib.user_encoding %r', output_encoding)
384
 
    # check encoding
385
 
    try:
386
 
        codecs.lookup(output_encoding)
387
 
    except LookupError:
388
 
        sys.stderr.write('bzr: warning:'
389
 
                         ' unknown terminal encoding %s.\n'
390
 
                         '  Using encoding %s instead.\n'
391
 
                         % (output_encoding, bzrlib.user_encoding)
392
 
                        )
393
 
        output_encoding = bzrlib.user_encoding
394
 
 
395
 
    return output_encoding
396
 
 
 
96
        raise BzrError('invalid file kind %r' % kind)
 
97
 
 
98
def lexists(f):
 
99
    try:
 
100
        if hasattr(os, 'lstat'):
 
101
            os.lstat(f)
 
102
        else:
 
103
            os.stat(f)
 
104
        return True
 
105
    except OSError,e:
 
106
        if e.errno == errno.ENOENT:
 
107
            return False;
 
108
        else:
 
109
            raise BzrError("lstat/stat of (%r): %r" % (f, e))
397
110
 
398
111
def normalizepath(f):
399
 
    if getattr(os.path, 'realpath', None) is not None:
400
 
        F = realpath
 
112
    if hasattr(os.path, 'realpath'):
 
113
        F = os.path.realpath
401
114
    else:
402
 
        F = abspath
 
115
        F = os.path.abspath
403
116
    [p,e] = os.path.split(f)
404
117
    if e == "" or e == "." or e == "..":
405
118
        return F(f)
406
119
    else:
407
 
        return pathjoin(F(p), e)
408
 
 
 
120
        return os.path.join(F(p), e)
 
121
    
409
122
 
410
123
def backup_file(fn):
411
124
    """Copy a file to a backup.
418
131
        return
419
132
    bfn = fn + '~'
420
133
 
421
 
    if has_symlinks() and os.path.islink(fn):
422
 
        target = os.readlink(fn)
423
 
        os.symlink(target, bfn)
424
 
        return
425
134
    inf = file(fn, 'rb')
426
135
    try:
427
136
        content = inf.read()
434
143
    finally:
435
144
        outf.close()
436
145
 
 
146
if os.name == 'nt':
 
147
    import shutil
 
148
    rename = shutil.move
 
149
else:
 
150
    rename = os.rename
 
151
 
437
152
 
438
153
def isdir(f):
439
154
    """True if f is an accessible directory."""
460
175
def is_inside(dir, fname):
461
176
    """True if fname is inside dir.
462
177
    
463
 
    The parameters should typically be passed to osutils.normpath first, so
 
178
    The parameters should typically be passed to os.path.normpath first, so
464
179
    that . and .. and repeated slashes are eliminated, and the separators
465
180
    are canonical for the platform.
466
181
    
467
182
    The empty string as a dir name is taken as top-of-tree and matches 
468
183
    everything.
 
184
    
 
185
    >>> is_inside('src', os.path.join('src', 'foo.c'))
 
186
    True
 
187
    >>> is_inside('src', 'srccontrol')
 
188
    False
 
189
    >>> is_inside('src', os.path.join('src', 'a', 'a', 'a', 'foo.c'))
 
190
    True
 
191
    >>> is_inside('foo.c', 'foo.c')
 
192
    True
 
193
    >>> is_inside('foo.c', '')
 
194
    False
 
195
    >>> is_inside('', 'foo.c')
 
196
    True
469
197
    """
470
198
    # XXX: Most callers of this can actually do something smarter by 
471
199
    # looking at the inventory
475
203
    if dir == '':
476
204
        return True
477
205
 
478
 
    if dir[-1] != '/':
479
 
        dir += '/'
 
206
    if dir[-1] != os.sep:
 
207
        dir += os.sep
480
208
 
481
209
    return fname.startswith(dir)
482
210
 
490
218
        return False
491
219
 
492
220
 
493
 
def is_inside_or_parent_of_any(dir_list, fname):
494
 
    """True if fname is a child or a parent of any of the given files."""
495
 
    for dirname in dir_list:
496
 
        if is_inside(dirname, fname) or is_inside(fname, dirname):
497
 
            return True
498
 
    else:
499
 
        return False
500
 
 
501
 
 
502
221
def pumpfile(fromfile, tofile):
503
222
    """Copy contents of one file to another."""
504
 
    BUFSIZE = 32768
505
 
    while True:
506
 
        b = fromfile.read(BUFSIZE)
507
 
        if not b:
508
 
            break
509
 
        tofile.write(b)
510
 
 
511
 
 
512
 
def file_iterator(input_file, readsize=32768):
513
 
    while True:
514
 
        b = input_file.read(readsize)
515
 
        if len(b) == 0:
516
 
            break
517
 
        yield b
 
223
    tofile.write(fromfile.read())
518
224
 
519
225
 
520
226
def sha_file(f):
521
 
    if getattr(f, 'tell', None) is not None:
 
227
    if hasattr(f, 'tell'):
522
228
        assert f.tell() == 0
523
229
    s = sha.new()
524
230
    BUFSIZE = 128<<10
553
259
            'sha1': s.hexdigest()}
554
260
 
555
261
 
 
262
def config_dir():
 
263
    """Return per-user configuration directory.
 
264
 
 
265
    By default this is ~/.bzr.conf/
 
266
    
 
267
    TODO: Global option --config-dir to override this.
 
268
    """
 
269
    return os.path.join(os.path.expanduser("~"), ".bzr.conf")
 
270
 
 
271
 
 
272
def _auto_user_id():
 
273
    """Calculate automatic user identification.
 
274
 
 
275
    Returns (realname, email).
 
276
 
 
277
    Only used when none is set in the environment or the id file.
 
278
 
 
279
    This previously used the FQDN as the default domain, but that can
 
280
    be very slow on machines where DNS is broken.  So now we simply
 
281
    use the hostname.
 
282
    """
 
283
    import socket
 
284
 
 
285
    # XXX: Any good way to get real user name on win32?
 
286
 
 
287
    try:
 
288
        import pwd
 
289
        uid = os.getuid()
 
290
        w = pwd.getpwuid(uid)
 
291
        gecos = w.pw_gecos.decode(bzrlib.user_encoding)
 
292
        username = w.pw_name.decode(bzrlib.user_encoding)
 
293
        comma = gecos.find(',')
 
294
        if comma == -1:
 
295
            realname = gecos
 
296
        else:
 
297
            realname = gecos[:comma]
 
298
        if not realname:
 
299
            realname = username
 
300
 
 
301
    except ImportError:
 
302
        import getpass
 
303
        realname = username = getpass.getuser().decode(bzrlib.user_encoding)
 
304
 
 
305
    return realname, (username + '@' + socket.gethostname())
 
306
 
 
307
 
 
308
def _get_user_id(branch):
 
309
    """Return the full user id from a file or environment variable.
 
310
 
 
311
    e.g. "John Hacker <jhacker@foo.org>"
 
312
 
 
313
    branch
 
314
        A branch to use for a per-branch configuration, or None.
 
315
 
 
316
    The following are searched in order:
 
317
 
 
318
    1. $BZREMAIL
 
319
    2. .bzr/email for this branch.
 
320
    3. ~/.bzr.conf/email
 
321
    4. $EMAIL
 
322
    """
 
323
    v = os.environ.get('BZREMAIL')
 
324
    if v:
 
325
        return v.decode(bzrlib.user_encoding)
 
326
 
 
327
    if branch:
 
328
        try:
 
329
            return (branch.controlfile("email", "r") 
 
330
                    .read()
 
331
                    .decode(bzrlib.user_encoding)
 
332
                    .rstrip("\r\n"))
 
333
        except IOError, e:
 
334
            if e.errno != errno.ENOENT:
 
335
                raise
 
336
        except BzrError, e:
 
337
            pass
 
338
    
 
339
    try:
 
340
        return (open(os.path.join(config_dir(), "email"))
 
341
                .read()
 
342
                .decode(bzrlib.user_encoding)
 
343
                .rstrip("\r\n"))
 
344
    except IOError, e:
 
345
        if e.errno != errno.ENOENT:
 
346
            raise e
 
347
 
 
348
    v = os.environ.get('EMAIL')
 
349
    if v:
 
350
        return v.decode(bzrlib.user_encoding)
 
351
    else:    
 
352
        return None
 
353
 
 
354
 
 
355
def username(branch):
 
356
    """Return email-style username.
 
357
 
 
358
    Something similar to 'Martin Pool <mbp@sourcefrog.net>'
 
359
 
 
360
    TODO: Check it's reasonably well-formed.
 
361
    """
 
362
    v = _get_user_id(branch)
 
363
    if v:
 
364
        return v
 
365
    
 
366
    name, email = _auto_user_id()
 
367
    if name:
 
368
        return '%s <%s>' % (name, email)
 
369
    else:
 
370
        return email
 
371
 
 
372
 
 
373
def user_email(branch):
 
374
    """Return just the email component of a username."""
 
375
    e = _get_user_id(branch)
 
376
    if e:
 
377
        m = re.search(r'[\w+.-]+@[\w+.-]+', e)
 
378
        if not m:
 
379
            raise BzrError("%r doesn't seem to contain "
 
380
                           "a reasonable email address" % e)
 
381
        return m.group(0)
 
382
 
 
383
    return _auto_user_id()[1]
 
384
 
 
385
 
556
386
def compare_files(a, b):
557
387
    """Returns true if equal in contents"""
558
388
    BUFSIZE = 4096
567
397
 
568
398
def local_time_offset(t=None):
569
399
    """Return offset of local zone from GMT, either at present or at time t."""
570
 
    if t is None:
 
400
    # python2.3 localtime() can't take None
 
401
    if t == None:
571
402
        t = time.time()
572
 
    offset = datetime.fromtimestamp(t) - datetime.utcfromtimestamp(t)
573
 
    return offset.days * 86400 + offset.seconds
 
403
        
 
404
    if time.localtime(t).tm_isdst and time.daylight:
 
405
        return -time.altzone
 
406
    else:
 
407
        return -time.timezone
574
408
 
575
409
    
576
 
def format_date(t, offset=0, timezone='original', date_fmt=None, 
577
 
                show_offset=True):
 
410
def format_date(t, offset=0, timezone='original'):
578
411
    ## TODO: Perhaps a global option to use either universal or local time?
579
412
    ## Or perhaps just let people set $TZ?
580
413
    assert isinstance(t, float)
583
416
        tt = time.gmtime(t)
584
417
        offset = 0
585
418
    elif timezone == 'original':
586
 
        if offset is None:
 
419
        if offset == None:
587
420
            offset = 0
588
421
        tt = time.gmtime(t + offset)
589
422
    elif timezone == 'local':
590
423
        tt = time.localtime(t)
591
424
        offset = local_time_offset(t)
592
425
    else:
593
 
        raise errors.BzrError("unsupported timezone format %r" % timezone,
594
 
                              ['options are "utc", "original", "local"'])
595
 
    if date_fmt is None:
596
 
        date_fmt = "%a %Y-%m-%d %H:%M:%S"
597
 
    if show_offset:
598
 
        offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
599
 
    else:
600
 
        offset_str = ''
601
 
    return (time.strftime(date_fmt, tt) +  offset_str)
 
426
        raise BzrError("unsupported timezone format %r" % timezone,
 
427
                       ['options are "utc", "original", "local"'])
 
428
 
 
429
    return (time.strftime("%a %Y-%m-%d %H:%M:%S", tt)
 
430
            + ' %+03d%02d' % (offset / 3600, (offset / 60) % 60))
602
431
 
603
432
 
604
433
def compact_date(when):
605
434
    return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
606
435
    
607
436
 
608
 
def format_delta(delta):
609
 
    """Get a nice looking string for a time delta.
610
 
 
611
 
    :param delta: The time difference in seconds, can be positive or negative.
612
 
        positive indicates time in the past, negative indicates time in the
613
 
        future. (usually time.time() - stored_time)
614
 
    :return: String formatted to show approximate resolution
615
 
    """
616
 
    delta = int(delta)
617
 
    if delta >= 0:
618
 
        direction = 'ago'
619
 
    else:
620
 
        direction = 'in the future'
621
 
        delta = -delta
622
 
 
623
 
    seconds = delta
624
 
    if seconds < 90: # print seconds up to 90 seconds
625
 
        if seconds == 1:
626
 
            return '%d second %s' % (seconds, direction,)
627
 
        else:
628
 
            return '%d seconds %s' % (seconds, direction)
629
 
 
630
 
    minutes = int(seconds / 60)
631
 
    seconds -= 60 * minutes
632
 
    if seconds == 1:
633
 
        plural_seconds = ''
634
 
    else:
635
 
        plural_seconds = 's'
636
 
    if minutes < 90: # print minutes, seconds up to 90 minutes
637
 
        if minutes == 1:
638
 
            return '%d minute, %d second%s %s' % (
639
 
                    minutes, seconds, plural_seconds, direction)
640
 
        else:
641
 
            return '%d minutes, %d second%s %s' % (
642
 
                    minutes, seconds, plural_seconds, direction)
643
 
 
644
 
    hours = int(minutes / 60)
645
 
    minutes -= 60 * hours
646
 
    if minutes == 1:
647
 
        plural_minutes = ''
648
 
    else:
649
 
        plural_minutes = 's'
650
 
 
651
 
    if hours == 1:
652
 
        return '%d hour, %d minute%s %s' % (hours, minutes,
653
 
                                            plural_minutes, direction)
654
 
    return '%d hours, %d minute%s %s' % (hours, minutes,
655
 
                                         plural_minutes, direction)
656
437
 
657
438
def filesize(f):
658
439
    """Return size of given open file."""
659
440
    return os.fstat(f.fileno())[ST_SIZE]
660
441
 
661
 
 
662
442
# Define rand_bytes based on platform.
663
443
try:
664
444
    # Python 2.4 and later have os.urandom,
668
448
except (NotImplementedError, AttributeError):
669
449
    # If python doesn't have os.urandom, or it doesn't work,
670
450
    # then try to first pull random data from /dev/urandom
671
 
    try:
 
451
    if os.path.exists("/dev/urandom"):
672
452
        rand_bytes = file('/dev/urandom', 'rb').read
673
453
    # Otherwise, use this hack as a last resort
674
 
    except (IOError, OSError):
 
454
    else:
675
455
        # not well seeded, but better than nothing
676
456
        def rand_bytes(n):
677
457
            import random
681
461
                n -= 1
682
462
            return s
683
463
 
684
 
 
685
 
ALNUM = '0123456789abcdefghijklmnopqrstuvwxyz'
686
 
def rand_chars(num):
687
 
    """Return a random string of num alphanumeric characters
688
 
    
689
 
    The result only contains lowercase chars because it may be used on 
690
 
    case-insensitive filesystems.
691
 
    """
692
 
    s = ''
693
 
    for raw_byte in rand_bytes(num):
694
 
        s += ALNUM[ord(raw_byte) % 36]
695
 
    return s
696
 
 
697
 
 
698
464
## TODO: We could later have path objects that remember their list
699
465
## decomposition (might be too tricksy though.)
700
466
 
701
467
def splitpath(p):
702
 
    """Turn string into list of parts."""
703
 
    assert isinstance(p, basestring)
 
468
    """Turn string into list of parts.
 
469
 
 
470
    >>> splitpath('a')
 
471
    ['a']
 
472
    >>> splitpath('a/b')
 
473
    ['a', 'b']
 
474
    >>> splitpath('a/./b')
 
475
    ['a', 'b']
 
476
    >>> splitpath('a/.b')
 
477
    ['a', '.b']
 
478
    >>> splitpath('a/../b')
 
479
    Traceback (most recent call last):
 
480
    ...
 
481
    BzrError: sorry, '..' not allowed in path
 
482
    """
 
483
    assert isinstance(p, types.StringTypes)
704
484
 
705
485
    # split on either delimiter because people might use either on
706
486
    # Windows
709
489
    rps = []
710
490
    for f in ps:
711
491
        if f == '..':
712
 
            raise errors.BzrError("sorry, %r not allowed in path" % f)
 
492
            raise BzrError("sorry, %r not allowed in path" % f)
713
493
        elif (f == '.') or (f == ''):
714
494
            pass
715
495
        else:
719
499
def joinpath(p):
720
500
    assert isinstance(p, list)
721
501
    for f in p:
722
 
        if (f == '..') or (f is None) or (f == ''):
723
 
            raise errors.BzrError("sorry, %r not allowed in path" % f)
724
 
    return pathjoin(*p)
725
 
 
726
 
 
727
 
@deprecated_function(zero_nine)
 
502
        if (f == '..') or (f == None) or (f == ''):
 
503
            raise BzrError("sorry, %r not allowed in path" % f)
 
504
    return os.path.join(*p)
 
505
 
 
506
 
728
507
def appendpath(p1, p2):
729
508
    if p1 == '':
730
509
        return p2
731
510
    else:
732
 
        return pathjoin(p1, p2)
 
511
        return os.path.join(p1, p2)
733
512
    
734
513
 
 
514
def _read_config_value(name):
 
515
    """Read a config value from the file ~/.bzr.conf/<name>
 
516
    Return None if the file does not exist"""
 
517
    try:
 
518
        f = file(os.path.join(config_dir(), name), "r")
 
519
        return f.read().decode(bzrlib.user_encoding).rstrip("\r\n")
 
520
    except IOError, e:
 
521
        if e.errno == errno.ENOENT:
 
522
            return None
 
523
        raise
 
524
 
 
525
 
735
526
def split_lines(s):
736
527
    """Split s into lines, but without removing the newline characters."""
737
 
    lines = s.split('\n')
738
 
    result = [line + '\n' for line in lines[:-1]]
739
 
    if lines[-1]:
740
 
        result.append(lines[-1])
741
 
    return result
 
528
    return StringIO(s).readlines()
742
529
 
743
530
 
744
531
def hardlinks_good():
748
535
def link_or_copy(src, dest):
749
536
    """Hardlink a file, or copy it if it can't be hardlinked."""
750
537
    if not hardlinks_good():
751
 
        shutil.copyfile(src, dest)
 
538
        copyfile(src, dest)
752
539
        return
753
540
    try:
754
541
        os.link(src, dest)
755
542
    except (OSError, IOError), e:
756
543
        if e.errno != errno.EXDEV:
757
544
            raise
758
 
        shutil.copyfile(src, dest)
759
 
 
760
 
def delete_any(full_path):
761
 
    """Delete a file or directory."""
762
 
    try:
763
 
        os.unlink(full_path)
764
 
    except OSError, e:
765
 
    # We may be renaming a dangling inventory id
766
 
        if e.errno not in (errno.EISDIR, errno.EACCES, errno.EPERM):
767
 
            raise
768
 
        os.rmdir(full_path)
 
545
        copyfile(src, dest)
769
546
 
770
547
 
771
548
def has_symlinks():
772
 
    if getattr(os, 'symlink', None) is not None:
 
549
    if hasattr(os, 'symlink'):
773
550
        return True
774
551
    else:
775
552
        return False
776
 
        
777
 
 
778
 
def contains_whitespace(s):
779
 
    """True if there are any whitespace characters in s."""
780
 
    # string.whitespace can include '\xa0' in certain locales, because it is
781
 
    # considered "non-breaking-space" as part of ISO-8859-1. But it
782
 
    # 1) Isn't a breaking whitespace
783
 
    # 2) Isn't one of ' \t\r\n' which are characters we sometimes use as
784
 
    #    separators
785
 
    # 3) '\xa0' isn't unicode safe since it is >128.
786
 
    # So we are following textwrap's example and hard-coding our own.
787
 
    # We probably could ignore \v and \f, too.
788
 
    for ch in u' \t\n\r\v\f':
789
 
        if ch in s:
790
 
            return True
791
 
    else:
792
 
        return False
793
 
 
794
 
 
795
 
def contains_linebreaks(s):
796
 
    """True if there is any vertical whitespace in s."""
797
 
    for ch in '\f\n\r':
798
 
        if ch in s:
799
 
            return True
800
 
    else:
801
 
        return False
802
 
 
803
 
 
804
 
def relpath(base, path):
805
 
    """Return path relative to base, or raise exception.
806
 
 
807
 
    The path may be either an absolute path or a path relative to the
808
 
    current working directory.
809
 
 
810
 
    os.path.commonprefix (python2.4) has a bad bug that it works just
811
 
    on string prefixes, assuming that '/u' is a prefix of '/u2'.  This
812
 
    avoids that problem.
813
 
    """
814
 
 
815
 
    assert len(base) >= MIN_ABS_PATHLENGTH, ('Length of base must be equal or'
816
 
        ' exceed the platform minimum length (which is %d)' % 
817
 
        MIN_ABS_PATHLENGTH)
818
 
 
819
 
    rp = abspath(path)
820
 
 
821
 
    s = []
822
 
    head = rp
823
 
    while len(head) >= len(base):
824
 
        if head == base:
825
 
            break
826
 
        head, tail = os.path.split(head)
827
 
        if tail:
828
 
            s.insert(0, tail)
829
 
    else:
830
 
        raise errors.PathNotChild(rp, base)
831
 
 
832
 
    if s:
833
 
        return pathjoin(*s)
834
 
    else:
835
 
        return ''
836
 
 
837
 
 
838
 
def safe_unicode(unicode_or_utf8_string):
839
 
    """Coerce unicode_or_utf8_string into unicode.
840
 
 
841
 
    If it is unicode, it is returned.
842
 
    Otherwise it is decoded from utf-8. If a decoding error
843
 
    occurs, it is wrapped as a If the decoding fails, the exception is wrapped 
844
 
    as a BzrBadParameter exception.
845
 
    """
846
 
    if isinstance(unicode_or_utf8_string, unicode):
847
 
        return unicode_or_utf8_string
848
 
    try:
849
 
        return unicode_or_utf8_string.decode('utf8')
850
 
    except UnicodeDecodeError:
851
 
        raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
852
 
 
853
 
 
854
 
_platform_normalizes_filenames = False
855
 
if sys.platform == 'darwin':
856
 
    _platform_normalizes_filenames = True
857
 
 
858
 
 
859
 
def normalizes_filenames():
860
 
    """Return True if this platform normalizes unicode filenames.
861
 
 
862
 
    Mac OSX does, Windows/Linux do not.
863
 
    """
864
 
    return _platform_normalizes_filenames
865
 
 
866
 
 
867
 
def _accessible_normalized_filename(path):
868
 
    """Get the unicode normalized path, and if you can access the file.
869
 
 
870
 
    On platforms where the system normalizes filenames (Mac OSX),
871
 
    you can access a file by any path which will normalize correctly.
872
 
    On platforms where the system does not normalize filenames 
873
 
    (Windows, Linux), you have to access a file by its exact path.
874
 
 
875
 
    Internally, bzr only supports NFC/NFKC normalization, since that is 
876
 
    the standard for XML documents.
877
 
 
878
 
    So return the normalized path, and a flag indicating if the file
879
 
    can be accessed by that path.
880
 
    """
881
 
 
882
 
    return unicodedata.normalize('NFKC', unicode(path)), True
883
 
 
884
 
 
885
 
def _inaccessible_normalized_filename(path):
886
 
    __doc__ = _accessible_normalized_filename.__doc__
887
 
 
888
 
    normalized = unicodedata.normalize('NFKC', unicode(path))
889
 
    return normalized, normalized == path
890
 
 
891
 
 
892
 
if _platform_normalizes_filenames:
893
 
    normalized_filename = _accessible_normalized_filename
894
 
else:
895
 
    normalized_filename = _inaccessible_normalized_filename
896
 
 
897
 
 
898
 
def terminal_width():
899
 
    """Return estimated terminal width."""
900
 
    if sys.platform == 'win32':
901
 
        return win32utils.get_console_size()[0]
902
 
    width = 0
903
 
    try:
904
 
        import struct, fcntl, termios
905
 
        s = struct.pack('HHHH', 0, 0, 0, 0)
906
 
        x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
907
 
        width = struct.unpack('HHHH', x)[1]
908
 
    except IOError:
909
 
        pass
910
 
    if width <= 0:
911
 
        try:
912
 
            width = int(os.environ['COLUMNS'])
913
 
        except:
914
 
            pass
915
 
    if width <= 0:
916
 
        width = 80
917
 
 
918
 
    return width
919
 
 
920
 
 
921
 
def supports_executable():
922
 
    return sys.platform != "win32"
923
 
 
924
 
 
925
 
def supports_posix_readonly():
926
 
    """Return True if 'readonly' has POSIX semantics, False otherwise.
927
 
 
928
 
    Notably, a win32 readonly file cannot be deleted, unlike POSIX where the
929
 
    directory controls creation/deletion, etc.
930
 
 
931
 
    And under win32, readonly means that the directory itself cannot be
932
 
    deleted.  The contents of a readonly directory can be changed, unlike POSIX
933
 
    where files in readonly directories cannot be added, deleted or renamed.
934
 
    """
935
 
    return sys.platform != "win32"
936
 
 
937
 
 
938
 
def set_or_unset_env(env_variable, value):
939
 
    """Modify the environment, setting or removing the env_variable.
940
 
 
941
 
    :param env_variable: The environment variable in question
942
 
    :param value: The value to set the environment to. If None, then
943
 
        the variable will be removed.
944
 
    :return: The original value of the environment variable.
945
 
    """
946
 
    orig_val = os.environ.get(env_variable)
947
 
    if value is None:
948
 
        if orig_val is not None:
949
 
            del os.environ[env_variable]
950
 
    else:
951
 
        if isinstance(value, unicode):
952
 
            value = value.encode(bzrlib.user_encoding)
953
 
        os.environ[env_variable] = value
954
 
    return orig_val
955
 
 
956
 
 
957
 
_validWin32PathRE = re.compile(r'^([A-Za-z]:[/\\])?[^:<>*"?\|]*$')
958
 
 
959
 
 
960
 
def check_legal_path(path):
961
 
    """Check whether the supplied path is legal.  
962
 
    This is only required on Windows, so we don't test on other platforms
963
 
    right now.
964
 
    """
965
 
    if sys.platform != "win32":
966
 
        return
967
 
    if _validWin32PathRE.match(path) is None:
968
 
        raise errors.IllegalPath(path)
969
 
 
970
 
 
971
 
def walkdirs(top, prefix=""):
972
 
    """Yield data about all the directories in a tree.
973
 
    
974
 
    This yields all the data about the contents of a directory at a time.
975
 
    After each directory has been yielded, if the caller has mutated the list
976
 
    to exclude some directories, they are then not descended into.
977
 
    
978
 
    The data yielded is of the form:
979
 
    ((directory-relpath, directory-path-from-top),
980
 
    [(relpath, basename, kind, lstat), ...]),
981
 
     - directory-relpath is the relative path of the directory being returned
982
 
       with respect to top. prefix is prepended to this.
983
 
     - directory-path-from-root is the path including top for this directory. 
984
 
       It is suitable for use with os functions.
985
 
     - relpath is the relative path within the subtree being walked.
986
 
     - basename is the basename of the path
987
 
     - kind is the kind of the file now. If unknown then the file is not
988
 
       present within the tree - but it may be recorded as versioned. See
989
 
       versioned_kind.
990
 
     - lstat is the stat data *if* the file was statted.
991
 
     - planned, not implemented: 
992
 
       path_from_tree_root is the path from the root of the tree.
993
 
 
994
 
    :param prefix: Prefix the relpaths that are yielded with 'prefix'. This 
995
 
        allows one to walk a subtree but get paths that are relative to a tree
996
 
        rooted higher up.
997
 
    :return: an iterator over the dirs.
998
 
    """
999
 
    #TODO there is a bit of a smell where the results of the directory-
1000
 
    # summary in this, and the path from the root, may not agree 
1001
 
    # depending on top and prefix - i.e. ./foo and foo as a pair leads to
1002
 
    # potentially confusing output. We should make this more robust - but
1003
 
    # not at a speed cost. RBC 20060731
1004
 
    lstat = os.lstat
1005
 
    pending = []
1006
 
    _directory = _directory_kind
1007
 
    _listdir = os.listdir
1008
 
    pending = [(prefix, "", _directory, None, top)]
1009
 
    while pending:
1010
 
        dirblock = []
1011
 
        currentdir = pending.pop()
1012
 
        # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1013
 
        top = currentdir[4]
1014
 
        if currentdir[0]:
1015
 
            relroot = currentdir[0] + '/'
1016
 
        else:
1017
 
            relroot = ""
1018
 
        for name in sorted(_listdir(top)):
1019
 
            abspath = top + '/' + name
1020
 
            statvalue = lstat(abspath)
1021
 
            dirblock.append((relroot + name, name,
1022
 
                file_kind_from_stat_mode(statvalue.st_mode),
1023
 
                statvalue, abspath))
1024
 
        yield (currentdir[0], top), dirblock
1025
 
        # push the user specified dirs from dirblock
1026
 
        for dir in reversed(dirblock):
1027
 
            if dir[2] == _directory:
1028
 
                pending.append(dir)
1029
 
 
1030
 
 
1031
 
def copy_tree(from_path, to_path, handlers={}):
1032
 
    """Copy all of the entries in from_path into to_path.
1033
 
 
1034
 
    :param from_path: The base directory to copy. 
1035
 
    :param to_path: The target directory. If it does not exist, it will
1036
 
        be created.
1037
 
    :param handlers: A dictionary of functions, which takes a source and
1038
 
        destinations for files, directories, etc.
1039
 
        It is keyed on the file kind, such as 'directory', 'symlink', or 'file'
1040
 
        'file', 'directory', and 'symlink' should always exist.
1041
 
        If they are missing, they will be replaced with 'os.mkdir()',
1042
 
        'os.readlink() + os.symlink()', and 'shutil.copy2()', respectively.
1043
 
    """
1044
 
    # Now, just copy the existing cached tree to the new location
1045
 
    # We use a cheap trick here.
1046
 
    # Absolute paths are prefixed with the first parameter
1047
 
    # relative paths are prefixed with the second.
1048
 
    # So we can get both the source and target returned
1049
 
    # without any extra work.
1050
 
 
1051
 
    def copy_dir(source, dest):
1052
 
        os.mkdir(dest)
1053
 
 
1054
 
    def copy_link(source, dest):
1055
 
        """Copy the contents of a symlink"""
1056
 
        link_to = os.readlink(source)
1057
 
        os.symlink(link_to, dest)
1058
 
 
1059
 
    real_handlers = {'file':shutil.copy2,
1060
 
                     'symlink':copy_link,
1061
 
                     'directory':copy_dir,
1062
 
                    }
1063
 
    real_handlers.update(handlers)
1064
 
 
1065
 
    if not os.path.exists(to_path):
1066
 
        real_handlers['directory'](from_path, to_path)
1067
 
 
1068
 
    for dir_info, entries in walkdirs(from_path, prefix=to_path):
1069
 
        for relpath, name, kind, st, abspath in entries:
1070
 
            real_handlers[kind](abspath, relpath)
1071
 
 
1072
 
 
1073
 
def path_prefix_key(path):
1074
 
    """Generate a prefix-order path key for path.
1075
 
 
1076
 
    This can be used to sort paths in the same way that walkdirs does.
1077
 
    """
1078
 
    return (dirname(path) , path)
1079
 
 
1080
 
 
1081
 
def compare_paths_prefix_order(path_a, path_b):
1082
 
    """Compare path_a and path_b to generate the same order walkdirs uses."""
1083
 
    key_a = path_prefix_key(path_a)
1084
 
    key_b = path_prefix_key(path_b)
1085
 
    return cmp(key_a, key_b)
1086
 
 
1087
 
 
1088
 
_cached_user_encoding = None
1089
 
 
1090
 
 
1091
 
def get_user_encoding(use_cache=True):
1092
 
    """Find out what the preferred user encoding is.
1093
 
 
1094
 
    This is generally the encoding that is used for command line parameters
1095
 
    and file contents. This may be different from the terminal encoding
1096
 
    or the filesystem encoding.
1097
 
 
1098
 
    :param  use_cache:  Enable cache for detected encoding.
1099
 
                        (This parameter is turned on by default,
1100
 
                        and required only for selftesting)
1101
 
 
1102
 
    :return: A string defining the preferred user encoding
1103
 
    """
1104
 
    global _cached_user_encoding
1105
 
    if _cached_user_encoding is not None and use_cache:
1106
 
        return _cached_user_encoding
1107
 
 
1108
 
    if sys.platform == 'darwin':
1109
 
        # work around egregious python 2.4 bug
1110
 
        sys.platform = 'posix'
1111
 
        try:
1112
 
            import locale
1113
 
        finally:
1114
 
            sys.platform = 'darwin'
1115
 
    else:
1116
 
        import locale
1117
 
 
1118
 
    try:
1119
 
        user_encoding = locale.getpreferredencoding()
1120
 
    except locale.Error, e:
1121
 
        sys.stderr.write('bzr: warning: %s\n'
1122
 
                         '  Could not determine what text encoding to use.\n'
1123
 
                         '  This error usually means your Python interpreter\n'
1124
 
                         '  doesn\'t support the locale set by $LANG (%s)\n'
1125
 
                         "  Continuing with ascii encoding.\n"
1126
 
                         % (e, os.environ.get('LANG')))
1127
 
        user_encoding = 'ascii'
1128
 
 
1129
 
    # Windows returns 'cp0' to indicate there is no code page. So we'll just
1130
 
    # treat that as ASCII, and not support printing unicode characters to the
1131
 
    # console.
1132
 
    if user_encoding in (None, 'cp0'):
1133
 
        user_encoding = 'ascii'
1134
 
    else:
1135
 
        # check encoding
1136
 
        try:
1137
 
            codecs.lookup(user_encoding)
1138
 
        except LookupError:
1139
 
            sys.stderr.write('bzr: warning:'
1140
 
                             ' unknown encoding %s.'
1141
 
                             ' Continuing with ascii encoding.\n'
1142
 
                             % user_encoding
1143
 
                            )
1144
 
            user_encoding = 'ascii'
1145
 
 
1146
 
    if use_cache:
1147
 
        _cached_user_encoding = user_encoding
1148
 
 
1149
 
    return user_encoding
1150
 
 
1151
 
 
1152
 
def recv_all(socket, bytes):
1153
 
    """Receive an exact number of bytes.
1154
 
 
1155
 
    Regular Socket.recv() may return less than the requested number of bytes,
1156
 
    dependning on what's in the OS buffer.  MSG_WAITALL is not available
1157
 
    on all platforms, but this should work everywhere.  This will return
1158
 
    less than the requested amount if the remote end closes.
1159
 
 
1160
 
    This isn't optimized and is intended mostly for use in testing.
1161
 
    """
1162
 
    b = ''
1163
 
    while len(b) < bytes:
1164
 
        new = socket.recv(bytes - len(b))
1165
 
        if new == '':
1166
 
            break # eof
1167
 
        b += new
1168
 
    return b
1169
 
 
1170
 
def dereference_path(path):
1171
 
    """Determine the real path to a file.
1172
 
 
1173
 
    All parent elements are dereferenced.  But the file itself is not
1174
 
    dereferenced.
1175
 
    :param path: The original path.  May be absolute or relative.
1176
 
    :return: the real path *to* the file
1177
 
    """
1178
 
    parent, base = os.path.split(path)
1179
 
    # The pathjoin for '.' is a workaround for Python bug #1213894.
1180
 
    # (initial path components aren't dereferenced)
1181
 
    return pathjoin(realpath(pathjoin('.', parent)), base)