/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: Martin Pool
  • Date: 2007-04-19 08:03:19 UTC
  • mto: This revision was merged to the branch mainline in revision 2461.
  • Revision ID: mbp@sourcefrog.net-20070419080319-amc7f3frr64lxolq
Make timestamps use existing format_date; document that function more

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
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
4
2
#
5
3
# This program is free software; you can redistribute it and/or modify
6
4
# it under the terms of the GNU General Public License as published by
16
14
# along with this program; if not, write to the Free Software
17
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
16
 
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)
22
17
from cStringIO import StringIO
23
 
import errno
24
18
import os
25
19
import re
26
 
import sha
27
 
import string
 
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)
28
23
import sys
29
24
import time
30
 
import types
 
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
    )
31
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
""")
32
55
 
33
56
import bzrlib
34
 
from bzrlib.errors import (BzrError,
35
 
                           BzrBadParameterNotUnicode,
36
 
                           NoSuchFile,
37
 
                           PathNotChild,
38
 
                           )
 
57
from bzrlib import symbol_versioning
 
58
from bzrlib.symbol_versioning import (
 
59
    deprecated_function,
 
60
    zero_nine,
 
61
    )
39
62
from bzrlib.trace import mutter
40
63
 
41
64
 
 
65
# On win32, O_BINARY is used to indicate the file should
 
66
# be opened in binary mode, rather than text mode.
 
67
# On other platforms, O_BINARY doesn't exist, because
 
68
# they always open in binary mode, so it is okay to
 
69
# OR with 0 on those platforms
 
70
O_BINARY = getattr(os, 'O_BINARY', 0)
 
71
 
 
72
 
42
73
def make_readonly(filename):
43
74
    """Make a filename read-only."""
44
75
    mod = os.stat(filename).st_mode
62
93
    Windows."""
63
94
    # TODO: I'm not really sure this is the best format either.x
64
95
    global _QUOTE_RE
65
 
    if _QUOTE_RE == None:
 
96
    if _QUOTE_RE is None:
66
97
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
67
98
        
68
99
    if _QUOTE_RE.search(f):
71
102
        return f
72
103
 
73
104
 
74
 
def file_kind(f):
75
 
    mode = os.lstat(f)[ST_MODE]
76
 
    if S_ISREG(mode):
77
 
        return 'file'
78
 
    elif S_ISDIR(mode):
79
 
        return 'directory'
80
 
    elif S_ISLNK(mode):
81
 
        return 'symlink'
82
 
    elif S_ISCHR(mode):
83
 
        return 'chardev'
84
 
    elif S_ISBLK(mode):
85
 
        return 'block'
86
 
    elif S_ISFIFO(mode):
87
 
        return 'fifo'
88
 
    elif S_ISSOCK(mode):
89
 
        return 'socket'
90
 
    else:
91
 
        return 'unknown'
 
105
_directory_kind = 'directory'
 
106
 
 
107
_formats = {
 
108
    stat.S_IFDIR:_directory_kind,
 
109
    stat.S_IFCHR:'chardev',
 
110
    stat.S_IFBLK:'block',
 
111
    stat.S_IFREG:'file',
 
112
    stat.S_IFIFO:'fifo',
 
113
    stat.S_IFLNK:'symlink',
 
114
    stat.S_IFSOCK:'socket',
 
115
}
 
116
 
 
117
 
 
118
def file_kind_from_stat_mode(stat_mode, _formats=_formats, _unknown='unknown'):
 
119
    """Generate a file kind from a stat mode. This is used in walkdirs.
 
120
 
 
121
    Its performance is critical: Do not mutate without careful benchmarking.
 
122
    """
 
123
    try:
 
124
        return _formats[stat_mode & 0170000]
 
125
    except KeyError:
 
126
        return _unknown
 
127
 
 
128
 
 
129
def file_kind(f, _lstat=os.lstat, _mapper=file_kind_from_stat_mode):
 
130
    try:
 
131
        return _mapper(_lstat(f).st_mode)
 
132
    except OSError, e:
 
133
        if getattr(e, 'errno', None) == errno.ENOENT:
 
134
            raise errors.NoSuchFile(f)
 
135
        raise
 
136
 
 
137
 
 
138
def get_umask():
 
139
    """Return the current umask"""
 
140
    # Assume that people aren't messing with the umask while running
 
141
    # XXX: This is not thread safe, but there is no way to get the
 
142
    #      umask without setting it
 
143
    umask = os.umask(0)
 
144
    os.umask(umask)
 
145
    return umask
 
146
 
 
147
 
 
148
_kind_marker_map = {
 
149
    "file": "",
 
150
    _directory_kind: "/",
 
151
    "symlink": "@",
 
152
    'tree-reference': '+',
 
153
}
92
154
 
93
155
 
94
156
def kind_marker(kind):
95
 
    if kind == 'file':
96
 
        return ''
97
 
    elif kind == 'directory':
98
 
        return '/'
99
 
    elif kind == 'symlink':
100
 
        return '@'
101
 
    else:
102
 
        raise BzrError('invalid file kind %r' % kind)
103
 
 
104
 
def lexists(f):
105
 
    if hasattr(os.path, 'lexists'):
106
 
        return os.path.lexists(f)
107
157
    try:
108
 
        if hasattr(os, 'lstat'):
109
 
            os.lstat(f)
110
 
        else:
111
 
            os.stat(f)
112
 
        return True
113
 
    except OSError,e:
114
 
        if e.errno == errno.ENOENT:
115
 
            return False;
116
 
        else:
117
 
            raise BzrError("lstat/stat of (%r): %r" % (f, e))
 
158
        return _kind_marker_map[kind]
 
159
    except KeyError:
 
160
        raise errors.BzrError('invalid file kind %r' % kind)
 
161
 
 
162
 
 
163
lexists = getattr(os.path, 'lexists', None)
 
164
if lexists is None:
 
165
    def lexists(f):
 
166
        try:
 
167
            stat = getattr(os, 'lstat', os.stat)
 
168
            stat(f)
 
169
            return True
 
170
        except OSError, e:
 
171
            if e.errno == errno.ENOENT:
 
172
                return False;
 
173
            else:
 
174
                raise errors.BzrError("lstat/stat of (%r): %r" % (f, e))
 
175
 
118
176
 
119
177
def fancy_rename(old, new, rename_func, unlink_func):
120
178
    """A fancy rename, when you don't have atomic rename.
140
198
    file_existed = False
141
199
    try:
142
200
        rename_func(new, tmp_name)
143
 
    except (NoSuchFile,), e:
 
201
    except (errors.NoSuchFile,), e:
144
202
        pass
145
203
    except IOError, e:
146
204
        # RBC 20060103 abstraction leakage: the paramiko SFTP clients rename
147
 
        # function raises an IOError with errno == None when a rename fails.
 
205
        # function raises an IOError with errno is None when a rename fails.
148
206
        # This then gets caught here.
149
207
        if e.errno not in (None, errno.ENOENT, errno.ENOTDIR):
150
208
            raise
151
209
    except Exception, e:
152
 
        if (not hasattr(e, 'errno') 
 
210
        if (getattr(e, 'errno', None) is None
153
211
            or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
154
212
            raise
155
213
    else:
170
228
            else:
171
229
                rename_func(tmp_name, new)
172
230
 
173
 
# Default is to just use the python builtins
174
 
abspath = os.path.abspath
175
 
realpath = os.path.realpath
 
231
 
 
232
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
 
233
# choke on a Unicode string containing a relative path if
 
234
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
 
235
# string.
 
236
_fs_enc = sys.getfilesystemencoding() or 'utf-8'
 
237
def _posix_abspath(path):
 
238
    # jam 20060426 rather than encoding to fsencoding
 
239
    # copy posixpath.abspath, but use os.getcwdu instead
 
240
    if not posixpath.isabs(path):
 
241
        path = posixpath.join(getcwd(), path)
 
242
    return posixpath.normpath(path)
 
243
 
 
244
 
 
245
def _posix_realpath(path):
 
246
    return posixpath.realpath(path.encode(_fs_enc)).decode(_fs_enc)
 
247
 
 
248
 
 
249
def _win32_fixdrive(path):
 
250
    """Force drive letters to be consistent.
 
251
 
 
252
    win32 is inconsistent whether it returns lower or upper case
 
253
    and even if it was consistent the user might type the other
 
254
    so we force it to uppercase
 
255
    running python.exe under cmd.exe return capital C:\\
 
256
    running win32 python inside a cygwin shell returns lowercase c:\\
 
257
    """
 
258
    drive, path = _nt_splitdrive(path)
 
259
    return drive.upper() + path
 
260
 
 
261
 
 
262
def _win32_abspath(path):
 
263
    # Real _nt_abspath doesn't have a problem with a unicode cwd
 
264
    return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
 
265
 
 
266
 
 
267
def _win98_abspath(path):
 
268
    """Return the absolute version of a path.
 
269
    Windows 98 safe implementation (python reimplementation
 
270
    of Win32 API function GetFullPathNameW)
 
271
    """
 
272
    # Corner cases:
 
273
    #   C:\path     => C:/path
 
274
    #   C:/path     => C:/path
 
275
    #   \\HOST\path => //HOST/path
 
276
    #   //HOST/path => //HOST/path
 
277
    #   path        => C:/cwd/path
 
278
    #   /path       => C:/path
 
279
    path = unicode(path)
 
280
    # check for absolute path
 
281
    drive = _nt_splitdrive(path)[0]
 
282
    if drive == '' and path[:2] not in('//','\\\\'):
 
283
        cwd = os.getcwdu()
 
284
        # we cannot simply os.path.join cwd and path
 
285
        # because os.path.join('C:','/path') produce '/path'
 
286
        # and this is incorrect
 
287
        if path[:1] in ('/','\\'):
 
288
            cwd = _nt_splitdrive(cwd)[0]
 
289
            path = path[1:]
 
290
        path = cwd + '\\' + path
 
291
    return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
 
292
 
 
293
if win32utils.winver == 'Windows 98':
 
294
    _win32_abspath = _win98_abspath
 
295
 
 
296
 
 
297
def _win32_realpath(path):
 
298
    # Real _nt_realpath doesn't have a problem with a unicode cwd
 
299
    return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
 
300
 
 
301
 
 
302
def _win32_pathjoin(*args):
 
303
    return _nt_join(*args).replace('\\', '/')
 
304
 
 
305
 
 
306
def _win32_normpath(path):
 
307
    return _win32_fixdrive(_nt_normpath(unicode(path)).replace('\\', '/'))
 
308
 
 
309
 
 
310
def _win32_getcwd():
 
311
    return _win32_fixdrive(os.getcwdu().replace('\\', '/'))
 
312
 
 
313
 
 
314
def _win32_mkdtemp(*args, **kwargs):
 
315
    return _win32_fixdrive(tempfile.mkdtemp(*args, **kwargs).replace('\\', '/'))
 
316
 
 
317
 
 
318
def _win32_rename(old, new):
 
319
    """We expect to be able to atomically replace 'new' with old.
 
320
 
 
321
    On win32, if new exists, it must be moved out of the way first,
 
322
    and then deleted. 
 
323
    """
 
324
    try:
 
325
        fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
 
326
    except OSError, e:
 
327
        if e.errno in (errno.EPERM, errno.EACCES, errno.EBUSY, errno.EINVAL):
 
328
            # If we try to rename a non-existant file onto cwd, we get 
 
329
            # EPERM or EACCES instead of ENOENT, this will raise ENOENT 
 
330
            # if the old path doesn't exist, sometimes we get EACCES
 
331
            # On Linux, we seem to get EBUSY, on Mac we get EINVAL
 
332
            os.lstat(old)
 
333
        raise
 
334
 
 
335
 
 
336
def _mac_getcwd():
 
337
    return unicodedata.normalize('NFKC', os.getcwdu())
 
338
 
 
339
 
 
340
# Default is to just use the python builtins, but these can be rebound on
 
341
# particular platforms.
 
342
abspath = _posix_abspath
 
343
realpath = _posix_realpath
176
344
pathjoin = os.path.join
177
345
normpath = os.path.normpath
178
346
getcwd = os.getcwdu
179
 
mkdtemp = tempfile.mkdtemp
180
347
rename = os.rename
181
348
dirname = os.path.dirname
182
349
basename = os.path.basename
183
 
 
184
 
if os.name == "posix":
185
 
    # In Python 2.4.2 and older, os.path.abspath and os.path.realpath
186
 
    # choke on a Unicode string containing a relative path if
187
 
    # os.getcwd() returns a non-sys.getdefaultencoding()-encoded
188
 
    # string.
189
 
    _fs_enc = sys.getfilesystemencoding()
190
 
    def abspath(path):
191
 
        return os.path.abspath(path.encode(_fs_enc)).decode(_fs_enc)
192
 
 
193
 
    def realpath(path):
194
 
        return os.path.realpath(path.encode(_fs_enc)).decode(_fs_enc)
 
350
split = os.path.split
 
351
splitext = os.path.splitext
 
352
# These were already imported into local scope
 
353
# mkdtemp = tempfile.mkdtemp
 
354
# rmtree = shutil.rmtree
 
355
 
 
356
MIN_ABS_PATHLENGTH = 1
 
357
 
195
358
 
196
359
if sys.platform == 'win32':
197
 
    # We need to use the Unicode-aware os.path.abspath and
198
 
    # os.path.realpath on Windows systems.
199
 
    def abspath(path):
200
 
        return os.path.abspath(path).replace('\\', '/')
201
 
 
202
 
    def realpath(path):
203
 
        return os.path.realpath(path).replace('\\', '/')
204
 
 
205
 
    def pathjoin(*args):
206
 
        return os.path.join(*args).replace('\\', '/')
207
 
 
208
 
    def normpath(path):
209
 
        return os.path.normpath(path).replace('\\', '/')
210
 
 
211
 
    def getcwd():
212
 
        return os.getcwdu().replace('\\', '/')
213
 
 
214
 
    def mkdtemp(*args, **kwargs):
215
 
        return tempfile.mkdtemp(*args, **kwargs).replace('\\', '/')
216
 
 
217
 
    def rename(old, new):
218
 
        fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
 
360
    abspath = _win32_abspath
 
361
    realpath = _win32_realpath
 
362
    pathjoin = _win32_pathjoin
 
363
    normpath = _win32_normpath
 
364
    getcwd = _win32_getcwd
 
365
    mkdtemp = _win32_mkdtemp
 
366
    rename = _win32_rename
 
367
 
 
368
    MIN_ABS_PATHLENGTH = 3
 
369
 
 
370
    def _win32_delete_readonly(function, path, excinfo):
 
371
        """Error handler for shutil.rmtree function [for win32]
 
372
        Helps to remove files and dirs marked as read-only.
 
373
        """
 
374
        exception = excinfo[1]
 
375
        if function in (os.remove, os.rmdir) \
 
376
            and isinstance(exception, OSError) \
 
377
            and exception.errno == errno.EACCES:
 
378
            make_writable(path)
 
379
            function(path)
 
380
        else:
 
381
            raise
 
382
 
 
383
    def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
 
384
        """Replacer for shutil.rmtree: could remove readonly dirs/files"""
 
385
        return shutil.rmtree(path, ignore_errors, onerror)
 
386
elif sys.platform == 'darwin':
 
387
    getcwd = _mac_getcwd
 
388
 
 
389
 
 
390
def get_terminal_encoding():
 
391
    """Find the best encoding for printing to the screen.
 
392
 
 
393
    This attempts to check both sys.stdout and sys.stdin to see
 
394
    what encoding they are in, and if that fails it falls back to
 
395
    bzrlib.user_encoding.
 
396
    The problem is that on Windows, locale.getpreferredencoding()
 
397
    is not the same encoding as that used by the console:
 
398
    http://mail.python.org/pipermail/python-list/2003-May/162357.html
 
399
 
 
400
    On my standard US Windows XP, the preferred encoding is
 
401
    cp1252, but the console is cp437
 
402
    """
 
403
    output_encoding = getattr(sys.stdout, 'encoding', None)
 
404
    if not output_encoding:
 
405
        input_encoding = getattr(sys.stdin, 'encoding', None)
 
406
        if not input_encoding:
 
407
            output_encoding = bzrlib.user_encoding
 
408
            mutter('encoding stdout as bzrlib.user_encoding %r', output_encoding)
 
409
        else:
 
410
            output_encoding = input_encoding
 
411
            mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
 
412
    else:
 
413
        mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
 
414
    if output_encoding == 'cp0':
 
415
        # invalid encoding (cp0 means 'no codepage' on Windows)
 
416
        output_encoding = bzrlib.user_encoding
 
417
        mutter('cp0 is invalid encoding.'
 
418
               ' encoding stdout as bzrlib.user_encoding %r', output_encoding)
 
419
    # check encoding
 
420
    try:
 
421
        codecs.lookup(output_encoding)
 
422
    except LookupError:
 
423
        sys.stderr.write('bzr: warning:'
 
424
                         ' unknown terminal encoding %s.\n'
 
425
                         '  Using encoding %s instead.\n'
 
426
                         % (output_encoding, bzrlib.user_encoding)
 
427
                        )
 
428
        output_encoding = bzrlib.user_encoding
 
429
 
 
430
    return output_encoding
219
431
 
220
432
 
221
433
def normalizepath(f):
222
 
    if hasattr(os.path, 'realpath'):
 
434
    if getattr(os.path, 'realpath', None) is not None:
223
435
        F = realpath
224
436
    else:
225
437
        F = abspath
289
501
    
290
502
    The empty string as a dir name is taken as top-of-tree and matches 
291
503
    everything.
292
 
    
293
 
    >>> is_inside('src', pathjoin('src', 'foo.c'))
294
 
    True
295
 
    >>> is_inside('src', 'srccontrol')
296
 
    False
297
 
    >>> is_inside('src', pathjoin('src', 'a', 'a', 'a', 'foo.c'))
298
 
    True
299
 
    >>> is_inside('foo.c', 'foo.c')
300
 
    True
301
 
    >>> is_inside('foo.c', '')
302
 
    False
303
 
    >>> is_inside('', 'foo.c')
304
 
    True
305
504
    """
306
505
    # XXX: Most callers of this can actually do something smarter by 
307
506
    # looking at the inventory
322
521
    for dirname in dir_list:
323
522
        if is_inside(dirname, fname):
324
523
            return True
325
 
    else:
326
 
        return False
 
524
    return False
 
525
 
 
526
 
 
527
def is_inside_or_parent_of_any(dir_list, fname):
 
528
    """True if fname is a child or a parent of any of the given files."""
 
529
    for dirname in dir_list:
 
530
        if is_inside(dirname, fname) or is_inside(fname, dirname):
 
531
            return True
 
532
    return False
327
533
 
328
534
 
329
535
def pumpfile(fromfile, tofile):
345
551
 
346
552
 
347
553
def sha_file(f):
348
 
    if hasattr(f, 'tell'):
 
554
    if getattr(f, 'tell', None) is not None:
349
555
        assert f.tell() == 0
350
556
    s = sha.new()
351
557
    BUFSIZE = 128<<10
394
600
 
395
601
def local_time_offset(t=None):
396
602
    """Return offset of local zone from GMT, either at present or at time t."""
397
 
    # python2.3 localtime() can't take None
398
 
    if t == None:
 
603
    if t is None:
399
604
        t = time.time()
400
 
        
401
 
    if time.localtime(t).tm_isdst and time.daylight:
402
 
        return -time.altzone
403
 
    else:
404
 
        return -time.timezone
 
605
    offset = datetime.fromtimestamp(t) - datetime.utcfromtimestamp(t)
 
606
    return offset.days * 86400 + offset.seconds
405
607
 
406
608
    
407
 
def format_date(t, offset=0, timezone='original', date_fmt=None, 
 
609
def format_date(t, offset=0, timezone='original', date_fmt=None,
408
610
                show_offset=True):
409
 
    ## TODO: Perhaps a global option to use either universal or local time?
410
 
    ## Or perhaps just let people set $TZ?
411
 
    assert isinstance(t, float)
412
 
    
 
611
    """Return a formatted date string.
 
612
 
 
613
    :param t: Seconds since the epoch.
 
614
    :param offset: Timezone offset in seconds east of utc.
 
615
    :param timezone: How to display the time: 'utc', 'original' for the
 
616
         timezone specified by offset, or 'local' for the process's current
 
617
         timezone.
 
618
    :param show_offset: Whether to append the timezone.
 
619
    :param date_fmt: strftime format.
 
620
    """
413
621
    if timezone == 'utc':
414
622
        tt = time.gmtime(t)
415
623
        offset = 0
416
624
    elif timezone == 'original':
417
 
        if offset == None:
 
625
        if offset is None:
418
626
            offset = 0
419
627
        tt = time.gmtime(t + offset)
420
628
    elif timezone == 'local':
421
629
        tt = time.localtime(t)
422
630
        offset = local_time_offset(t)
423
631
    else:
424
 
        raise BzrError("unsupported timezone format %r" % timezone,
425
 
                       ['options are "utc", "original", "local"'])
 
632
        raise errors.BzrError("unsupported timezone format %r" % timezone,
 
633
                              ['options are "utc", "original", "local"'])
426
634
    if date_fmt is None:
427
635
        date_fmt = "%a %Y-%m-%d %H:%M:%S"
428
636
    if show_offset:
436
644
    return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
437
645
    
438
646
 
 
647
def format_delta(delta):
 
648
    """Get a nice looking string for a time delta.
 
649
 
 
650
    :param delta: The time difference in seconds, can be positive or negative.
 
651
        positive indicates time in the past, negative indicates time in the
 
652
        future. (usually time.time() - stored_time)
 
653
    :return: String formatted to show approximate resolution
 
654
    """
 
655
    delta = int(delta)
 
656
    if delta >= 0:
 
657
        direction = 'ago'
 
658
    else:
 
659
        direction = 'in the future'
 
660
        delta = -delta
 
661
 
 
662
    seconds = delta
 
663
    if seconds < 90: # print seconds up to 90 seconds
 
664
        if seconds == 1:
 
665
            return '%d second %s' % (seconds, direction,)
 
666
        else:
 
667
            return '%d seconds %s' % (seconds, direction)
 
668
 
 
669
    minutes = int(seconds / 60)
 
670
    seconds -= 60 * minutes
 
671
    if seconds == 1:
 
672
        plural_seconds = ''
 
673
    else:
 
674
        plural_seconds = 's'
 
675
    if minutes < 90: # print minutes, seconds up to 90 minutes
 
676
        if minutes == 1:
 
677
            return '%d minute, %d second%s %s' % (
 
678
                    minutes, seconds, plural_seconds, direction)
 
679
        else:
 
680
            return '%d minutes, %d second%s %s' % (
 
681
                    minutes, seconds, plural_seconds, direction)
 
682
 
 
683
    hours = int(minutes / 60)
 
684
    minutes -= 60 * hours
 
685
    if minutes == 1:
 
686
        plural_minutes = ''
 
687
    else:
 
688
        plural_minutes = 's'
 
689
 
 
690
    if hours == 1:
 
691
        return '%d hour, %d minute%s %s' % (hours, minutes,
 
692
                                            plural_minutes, direction)
 
693
    return '%d hours, %d minute%s %s' % (hours, minutes,
 
694
                                         plural_minutes, direction)
439
695
 
440
696
def filesize(f):
441
697
    """Return size of given open file."""
451
707
except (NotImplementedError, AttributeError):
452
708
    # If python doesn't have os.urandom, or it doesn't work,
453
709
    # then try to first pull random data from /dev/urandom
454
 
    if os.path.exists("/dev/urandom"):
 
710
    try:
455
711
        rand_bytes = file('/dev/urandom', 'rb').read
456
712
    # Otherwise, use this hack as a last resort
457
 
    else:
 
713
    except (IOError, OSError):
458
714
        # not well seeded, but better than nothing
459
715
        def rand_bytes(n):
460
716
            import random
482
738
## decomposition (might be too tricksy though.)
483
739
 
484
740
def splitpath(p):
485
 
    """Turn string into list of parts.
486
 
 
487
 
    >>> splitpath('a')
488
 
    ['a']
489
 
    >>> splitpath('a/b')
490
 
    ['a', 'b']
491
 
    >>> splitpath('a/./b')
492
 
    ['a', 'b']
493
 
    >>> splitpath('a/.b')
494
 
    ['a', '.b']
495
 
    >>> splitpath('a/../b')
496
 
    Traceback (most recent call last):
497
 
    ...
498
 
    BzrError: sorry, '..' not allowed in path
499
 
    """
500
 
    assert isinstance(p, types.StringTypes)
 
741
    """Turn string into list of parts."""
 
742
    assert isinstance(p, basestring)
501
743
 
502
744
    # split on either delimiter because people might use either on
503
745
    # Windows
506
748
    rps = []
507
749
    for f in ps:
508
750
        if f == '..':
509
 
            raise BzrError("sorry, %r not allowed in path" % f)
 
751
            raise errors.BzrError("sorry, %r not allowed in path" % f)
510
752
        elif (f == '.') or (f == ''):
511
753
            pass
512
754
        else:
514
756
    return rps
515
757
 
516
758
def joinpath(p):
517
 
    assert isinstance(p, list)
 
759
    assert isinstance(p, (list, tuple))
518
760
    for f in p:
519
 
        if (f == '..') or (f == None) or (f == ''):
520
 
            raise BzrError("sorry, %r not allowed in path" % f)
 
761
        if (f == '..') or (f is None) or (f == ''):
 
762
            raise errors.BzrError("sorry, %r not allowed in path" % f)
521
763
    return pathjoin(*p)
522
764
 
523
765
 
 
766
@deprecated_function(zero_nine)
524
767
def appendpath(p1, p2):
525
768
    if p1 == '':
526
769
        return p2
530
773
 
531
774
def split_lines(s):
532
775
    """Split s into lines, but without removing the newline characters."""
533
 
    return StringIO(s).readlines()
 
776
    lines = s.split('\n')
 
777
    result = [line + '\n' for line in lines[:-1]]
 
778
    if lines[-1]:
 
779
        result.append(lines[-1])
 
780
    return result
534
781
 
535
782
 
536
783
def hardlinks_good():
540
787
def link_or_copy(src, dest):
541
788
    """Hardlink a file, or copy it if it can't be hardlinked."""
542
789
    if not hardlinks_good():
543
 
        copyfile(src, dest)
 
790
        shutil.copyfile(src, dest)
544
791
        return
545
792
    try:
546
793
        os.link(src, dest)
547
794
    except (OSError, IOError), e:
548
795
        if e.errno != errno.EXDEV:
549
796
            raise
550
 
        copyfile(src, dest)
 
797
        shutil.copyfile(src, dest)
551
798
 
552
799
def delete_any(full_path):
553
800
    """Delete a file or directory."""
561
808
 
562
809
 
563
810
def has_symlinks():
564
 
    if hasattr(os, 'symlink'):
 
811
    if getattr(os, 'symlink', None) is not None:
565
812
        return True
566
813
    else:
567
814
        return False
569
816
 
570
817
def contains_whitespace(s):
571
818
    """True if there are any whitespace characters in s."""
572
 
    for ch in string.whitespace:
 
819
    # string.whitespace can include '\xa0' in certain locales, because it is
 
820
    # considered "non-breaking-space" as part of ISO-8859-1. But it
 
821
    # 1) Isn't a breaking whitespace
 
822
    # 2) Isn't one of ' \t\r\n' which are characters we sometimes use as
 
823
    #    separators
 
824
    # 3) '\xa0' isn't unicode safe since it is >128.
 
825
 
 
826
    # This should *not* be a unicode set of characters in case the source
 
827
    # string is not a Unicode string. We can auto-up-cast the characters since
 
828
    # they are ascii, but we don't want to auto-up-cast the string in case it
 
829
    # is utf-8
 
830
    for ch in ' \t\n\r\v\f':
573
831
        if ch in s:
574
832
            return True
575
833
    else:
595
853
    on string prefixes, assuming that '/u' is a prefix of '/u2'.  This
596
854
    avoids that problem.
597
855
    """
598
 
    if sys.platform != "win32":
599
 
        minlength = 1
600
 
    else:
601
 
        minlength = 3
602
 
    assert len(base) >= minlength, ('Length of base must be equal or exceed the'
603
 
        ' platform minimum length (which is %d)' % minlength)
 
856
 
 
857
    assert len(base) >= MIN_ABS_PATHLENGTH, ('Length of base must be equal or'
 
858
        ' exceed the platform minimum length (which is %d)' % 
 
859
        MIN_ABS_PATHLENGTH)
 
860
 
604
861
    rp = abspath(path)
605
862
 
606
863
    s = []
612
869
        if tail:
613
870
            s.insert(0, tail)
614
871
    else:
615
 
        # XXX This should raise a NotChildPath exception, as its not tied
616
 
        # to branch anymore.
617
 
        raise PathNotChild(rp, base)
 
872
        raise errors.PathNotChild(rp, base)
618
873
 
619
874
    if s:
620
875
        return pathjoin(*s)
635
890
    try:
636
891
        return unicode_or_utf8_string.decode('utf8')
637
892
    except UnicodeDecodeError:
638
 
        raise BzrBadParameterNotUnicode(unicode_or_utf8_string)
 
893
        raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
 
894
 
 
895
 
 
896
def safe_utf8(unicode_or_utf8_string):
 
897
    """Coerce unicode_or_utf8_string to a utf8 string.
 
898
 
 
899
    If it is a str, it is returned.
 
900
    If it is Unicode, it is encoded into a utf-8 string.
 
901
    """
 
902
    if isinstance(unicode_or_utf8_string, str):
 
903
        # TODO: jam 20070209 This is overkill, and probably has an impact on
 
904
        #       performance if we are dealing with lots of apis that want a
 
905
        #       utf-8 revision id
 
906
        try:
 
907
            # Make sure it is a valid utf-8 string
 
908
            unicode_or_utf8_string.decode('utf-8')
 
909
        except UnicodeDecodeError:
 
910
            raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
 
911
        return unicode_or_utf8_string
 
912
    return unicode_or_utf8_string.encode('utf-8')
 
913
 
 
914
 
 
915
_revision_id_warning = ('Unicode revision ids were deprecated in bzr 0.15.'
 
916
                        ' Revision id generators should be creating utf8'
 
917
                        ' revision ids.')
 
918
 
 
919
 
 
920
def safe_revision_id(unicode_or_utf8_string, warn=True):
 
921
    """Revision ids should now be utf8, but at one point they were unicode.
 
922
 
 
923
    :param unicode_or_utf8_string: A possibly Unicode revision_id. (can also be
 
924
        utf8 or None).
 
925
    :param warn: Functions that are sanitizing user data can set warn=False
 
926
    :return: None or a utf8 revision id.
 
927
    """
 
928
    if (unicode_or_utf8_string is None
 
929
        or unicode_or_utf8_string.__class__ == str):
 
930
        return unicode_or_utf8_string
 
931
    if warn:
 
932
        symbol_versioning.warn(_revision_id_warning, DeprecationWarning,
 
933
                               stacklevel=2)
 
934
    return cache_utf8.encode(unicode_or_utf8_string)
 
935
 
 
936
 
 
937
_file_id_warning = ('Unicode file ids were deprecated in bzr 0.15. File id'
 
938
                    ' generators should be creating utf8 file ids.')
 
939
 
 
940
 
 
941
def safe_file_id(unicode_or_utf8_string, warn=True):
 
942
    """File ids should now be utf8, but at one point they were unicode.
 
943
 
 
944
    This is the same as safe_utf8, except it uses the cached encode functions
 
945
    to save a little bit of performance.
 
946
 
 
947
    :param unicode_or_utf8_string: A possibly Unicode file_id. (can also be
 
948
        utf8 or None).
 
949
    :param warn: Functions that are sanitizing user data can set warn=False
 
950
    :return: None or a utf8 file id.
 
951
    """
 
952
    if (unicode_or_utf8_string is None
 
953
        or unicode_or_utf8_string.__class__ == str):
 
954
        return unicode_or_utf8_string
 
955
    if warn:
 
956
        symbol_versioning.warn(_file_id_warning, DeprecationWarning,
 
957
                               stacklevel=2)
 
958
    return cache_utf8.encode(unicode_or_utf8_string)
 
959
 
 
960
 
 
961
_platform_normalizes_filenames = False
 
962
if sys.platform == 'darwin':
 
963
    _platform_normalizes_filenames = True
 
964
 
 
965
 
 
966
def normalizes_filenames():
 
967
    """Return True if this platform normalizes unicode filenames.
 
968
 
 
969
    Mac OSX does, Windows/Linux do not.
 
970
    """
 
971
    return _platform_normalizes_filenames
 
972
 
 
973
 
 
974
def _accessible_normalized_filename(path):
 
975
    """Get the unicode normalized path, and if you can access the file.
 
976
 
 
977
    On platforms where the system normalizes filenames (Mac OSX),
 
978
    you can access a file by any path which will normalize correctly.
 
979
    On platforms where the system does not normalize filenames 
 
980
    (Windows, Linux), you have to access a file by its exact path.
 
981
 
 
982
    Internally, bzr only supports NFC/NFKC normalization, since that is 
 
983
    the standard for XML documents.
 
984
 
 
985
    So return the normalized path, and a flag indicating if the file
 
986
    can be accessed by that path.
 
987
    """
 
988
 
 
989
    return unicodedata.normalize('NFKC', unicode(path)), True
 
990
 
 
991
 
 
992
def _inaccessible_normalized_filename(path):
 
993
    __doc__ = _accessible_normalized_filename.__doc__
 
994
 
 
995
    normalized = unicodedata.normalize('NFKC', unicode(path))
 
996
    return normalized, normalized == path
 
997
 
 
998
 
 
999
if _platform_normalizes_filenames:
 
1000
    normalized_filename = _accessible_normalized_filename
 
1001
else:
 
1002
    normalized_filename = _inaccessible_normalized_filename
639
1003
 
640
1004
 
641
1005
def terminal_width():
642
1006
    """Return estimated terminal width."""
643
 
 
644
 
    # TODO: Do something smart on Windows?
645
 
 
646
 
    # TODO: Is there anything that gets a better update when the window
647
 
    # is resized while the program is running? We could use the Python termcap
648
 
    # library.
 
1007
    if sys.platform == 'win32':
 
1008
        return win32utils.get_console_size()[0]
 
1009
    width = 0
649
1010
    try:
650
 
        return int(os.environ['COLUMNS'])
651
 
    except (IndexError, KeyError, ValueError):
652
 
        return 80
 
1011
        import struct, fcntl, termios
 
1012
        s = struct.pack('HHHH', 0, 0, 0, 0)
 
1013
        x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
 
1014
        width = struct.unpack('HHHH', x)[1]
 
1015
    except IOError:
 
1016
        pass
 
1017
    if width <= 0:
 
1018
        try:
 
1019
            width = int(os.environ['COLUMNS'])
 
1020
        except:
 
1021
            pass
 
1022
    if width <= 0:
 
1023
        width = 80
 
1024
 
 
1025
    return width
 
1026
 
653
1027
 
654
1028
def supports_executable():
655
1029
    return sys.platform != "win32"
 
1030
 
 
1031
 
 
1032
def supports_posix_readonly():
 
1033
    """Return True if 'readonly' has POSIX semantics, False otherwise.
 
1034
 
 
1035
    Notably, a win32 readonly file cannot be deleted, unlike POSIX where the
 
1036
    directory controls creation/deletion, etc.
 
1037
 
 
1038
    And under win32, readonly means that the directory itself cannot be
 
1039
    deleted.  The contents of a readonly directory can be changed, unlike POSIX
 
1040
    where files in readonly directories cannot be added, deleted or renamed.
 
1041
    """
 
1042
    return sys.platform != "win32"
 
1043
 
 
1044
 
 
1045
def set_or_unset_env(env_variable, value):
 
1046
    """Modify the environment, setting or removing the env_variable.
 
1047
 
 
1048
    :param env_variable: The environment variable in question
 
1049
    :param value: The value to set the environment to. If None, then
 
1050
        the variable will be removed.
 
1051
    :return: The original value of the environment variable.
 
1052
    """
 
1053
    orig_val = os.environ.get(env_variable)
 
1054
    if value is None:
 
1055
        if orig_val is not None:
 
1056
            del os.environ[env_variable]
 
1057
    else:
 
1058
        if isinstance(value, unicode):
 
1059
            value = value.encode(bzrlib.user_encoding)
 
1060
        os.environ[env_variable] = value
 
1061
    return orig_val
 
1062
 
 
1063
 
 
1064
_validWin32PathRE = re.compile(r'^([A-Za-z]:[/\\])?[^:<>*"?\|]*$')
 
1065
 
 
1066
 
 
1067
def check_legal_path(path):
 
1068
    """Check whether the supplied path is legal.  
 
1069
    This is only required on Windows, so we don't test on other platforms
 
1070
    right now.
 
1071
    """
 
1072
    if sys.platform != "win32":
 
1073
        return
 
1074
    if _validWin32PathRE.match(path) is None:
 
1075
        raise errors.IllegalPath(path)
 
1076
 
 
1077
 
 
1078
def walkdirs(top, prefix=""):
 
1079
    """Yield data about all the directories in a tree.
 
1080
    
 
1081
    This yields all the data about the contents of a directory at a time.
 
1082
    After each directory has been yielded, if the caller has mutated the list
 
1083
    to exclude some directories, they are then not descended into.
 
1084
    
 
1085
    The data yielded is of the form:
 
1086
    ((directory-relpath, directory-path-from-top),
 
1087
    [(directory-relpath, basename, kind, lstat, path-from-top), ...]),
 
1088
     - directory-relpath is the relative path of the directory being returned
 
1089
       with respect to top. prefix is prepended to this.
 
1090
     - directory-path-from-root is the path including top for this directory. 
 
1091
       It is suitable for use with os functions.
 
1092
     - relpath is the relative path within the subtree being walked.
 
1093
     - basename is the basename of the path
 
1094
     - kind is the kind of the file now. If unknown then the file is not
 
1095
       present within the tree - but it may be recorded as versioned. See
 
1096
       versioned_kind.
 
1097
     - lstat is the stat data *if* the file was statted.
 
1098
     - planned, not implemented: 
 
1099
       path_from_tree_root is the path from the root of the tree.
 
1100
 
 
1101
    :param prefix: Prefix the relpaths that are yielded with 'prefix'. This 
 
1102
        allows one to walk a subtree but get paths that are relative to a tree
 
1103
        rooted higher up.
 
1104
    :return: an iterator over the dirs.
 
1105
    """
 
1106
    #TODO there is a bit of a smell where the results of the directory-
 
1107
    # summary in this, and the path from the root, may not agree 
 
1108
    # depending on top and prefix - i.e. ./foo and foo as a pair leads to
 
1109
    # potentially confusing output. We should make this more robust - but
 
1110
    # not at a speed cost. RBC 20060731
 
1111
    _lstat = os.lstat
 
1112
    _directory = _directory_kind
 
1113
    _listdir = os.listdir
 
1114
    _kind_from_mode = _formats.get
 
1115
    pending = [(safe_unicode(prefix), "", _directory, None, safe_unicode(top))]
 
1116
    while pending:
 
1117
        # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
 
1118
        relroot, _, _, _, top = pending.pop()
 
1119
        if relroot:
 
1120
            relprefix = relroot + u'/'
 
1121
        else:
 
1122
            relprefix = ''
 
1123
        top_slash = top + u'/'
 
1124
 
 
1125
        dirblock = []
 
1126
        append = dirblock.append
 
1127
        for name in sorted(_listdir(top)):
 
1128
            abspath = top_slash + name
 
1129
            statvalue = _lstat(abspath)
 
1130
            kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
 
1131
            append((relprefix + name, name, kind, statvalue, abspath))
 
1132
        yield (relroot, top), dirblock
 
1133
 
 
1134
        # push the user specified dirs from dirblock
 
1135
        pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
 
1136
 
 
1137
 
 
1138
def _walkdirs_utf8(top, prefix=""):
 
1139
    """Yield data about all the directories in a tree.
 
1140
 
 
1141
    This yields the same information as walkdirs() only each entry is yielded
 
1142
    in utf-8. On platforms which have a filesystem encoding of utf8 the paths
 
1143
    are returned as exact byte-strings.
 
1144
 
 
1145
    :return: yields a tuple of (dir_info, [file_info])
 
1146
        dir_info is (utf8_relpath, path-from-top)
 
1147
        file_info is (utf8_relpath, utf8_name, kind, lstat, path-from-top)
 
1148
        if top is an absolute path, path-from-top is also an absolute path.
 
1149
        path-from-top might be unicode or utf8, but it is the correct path to
 
1150
        pass to os functions to affect the file in question. (such as os.lstat)
 
1151
    """
 
1152
    fs_encoding = sys.getfilesystemencoding()
 
1153
    if (sys.platform == 'win32' or
 
1154
        fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968')): # ascii
 
1155
        return _walkdirs_unicode_to_utf8(top, prefix=prefix)
 
1156
    else:
 
1157
        return _walkdirs_fs_utf8(top, prefix=prefix)
 
1158
 
 
1159
 
 
1160
def _walkdirs_fs_utf8(top, prefix=""):
 
1161
    """See _walkdirs_utf8.
 
1162
 
 
1163
    This sub-function is called when we know the filesystem is already in utf8
 
1164
    encoding. So we don't need to transcode filenames.
 
1165
    """
 
1166
    _lstat = os.lstat
 
1167
    _directory = _directory_kind
 
1168
    _listdir = os.listdir
 
1169
    _kind_from_mode = _formats.get
 
1170
 
 
1171
    # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
 
1172
    # But we don't actually uses 1-3 in pending, so set them to None
 
1173
    pending = [(safe_utf8(prefix), None, None, None, safe_utf8(top))]
 
1174
    while pending:
 
1175
        relroot, _, _, _, top = pending.pop()
 
1176
        if relroot:
 
1177
            relprefix = relroot + '/'
 
1178
        else:
 
1179
            relprefix = ''
 
1180
        top_slash = top + '/'
 
1181
 
 
1182
        dirblock = []
 
1183
        append = dirblock.append
 
1184
        for name in sorted(_listdir(top)):
 
1185
            abspath = top_slash + name
 
1186
            statvalue = _lstat(abspath)
 
1187
            kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
 
1188
            append((relprefix + name, name, kind, statvalue, abspath))
 
1189
        yield (relroot, top), dirblock
 
1190
 
 
1191
        # push the user specified dirs from dirblock
 
1192
        pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
 
1193
 
 
1194
 
 
1195
def _walkdirs_unicode_to_utf8(top, prefix=""):
 
1196
    """See _walkdirs_utf8
 
1197
 
 
1198
    Because Win32 has a Unicode api, all of the 'path-from-top' entries will be
 
1199
    Unicode paths.
 
1200
    This is currently the fallback code path when the filesystem encoding is
 
1201
    not UTF-8. It may be better to implement an alternative so that we can
 
1202
    safely handle paths that are not properly decodable in the current
 
1203
    encoding.
 
1204
    """
 
1205
    _utf8_encode = codecs.getencoder('utf8')
 
1206
    _lstat = os.lstat
 
1207
    _directory = _directory_kind
 
1208
    _listdir = os.listdir
 
1209
    _kind_from_mode = _formats.get
 
1210
 
 
1211
    pending = [(safe_utf8(prefix), None, None, None, safe_unicode(top))]
 
1212
    while pending:
 
1213
        relroot, _, _, _, top = pending.pop()
 
1214
        if relroot:
 
1215
            relprefix = relroot + '/'
 
1216
        else:
 
1217
            relprefix = ''
 
1218
        top_slash = top + u'/'
 
1219
 
 
1220
        dirblock = []
 
1221
        append = dirblock.append
 
1222
        for name in sorted(_listdir(top)):
 
1223
            name_utf8 = _utf8_encode(name)[0]
 
1224
            abspath = top_slash + name
 
1225
            statvalue = _lstat(abspath)
 
1226
            kind = _kind_from_mode(statvalue.st_mode & 0170000, 'unknown')
 
1227
            append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
 
1228
        yield (relroot, top), dirblock
 
1229
 
 
1230
        # push the user specified dirs from dirblock
 
1231
        pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
 
1232
 
 
1233
 
 
1234
def copy_tree(from_path, to_path, handlers={}):
 
1235
    """Copy all of the entries in from_path into to_path.
 
1236
 
 
1237
    :param from_path: The base directory to copy. 
 
1238
    :param to_path: The target directory. If it does not exist, it will
 
1239
        be created.
 
1240
    :param handlers: A dictionary of functions, which takes a source and
 
1241
        destinations for files, directories, etc.
 
1242
        It is keyed on the file kind, such as 'directory', 'symlink', or 'file'
 
1243
        'file', 'directory', and 'symlink' should always exist.
 
1244
        If they are missing, they will be replaced with 'os.mkdir()',
 
1245
        'os.readlink() + os.symlink()', and 'shutil.copy2()', respectively.
 
1246
    """
 
1247
    # Now, just copy the existing cached tree to the new location
 
1248
    # We use a cheap trick here.
 
1249
    # Absolute paths are prefixed with the first parameter
 
1250
    # relative paths are prefixed with the second.
 
1251
    # So we can get both the source and target returned
 
1252
    # without any extra work.
 
1253
 
 
1254
    def copy_dir(source, dest):
 
1255
        os.mkdir(dest)
 
1256
 
 
1257
    def copy_link(source, dest):
 
1258
        """Copy the contents of a symlink"""
 
1259
        link_to = os.readlink(source)
 
1260
        os.symlink(link_to, dest)
 
1261
 
 
1262
    real_handlers = {'file':shutil.copy2,
 
1263
                     'symlink':copy_link,
 
1264
                     'directory':copy_dir,
 
1265
                    }
 
1266
    real_handlers.update(handlers)
 
1267
 
 
1268
    if not os.path.exists(to_path):
 
1269
        real_handlers['directory'](from_path, to_path)
 
1270
 
 
1271
    for dir_info, entries in walkdirs(from_path, prefix=to_path):
 
1272
        for relpath, name, kind, st, abspath in entries:
 
1273
            real_handlers[kind](abspath, relpath)
 
1274
 
 
1275
 
 
1276
def path_prefix_key(path):
 
1277
    """Generate a prefix-order path key for path.
 
1278
 
 
1279
    This can be used to sort paths in the same way that walkdirs does.
 
1280
    """
 
1281
    return (dirname(path) , path)
 
1282
 
 
1283
 
 
1284
def compare_paths_prefix_order(path_a, path_b):
 
1285
    """Compare path_a and path_b to generate the same order walkdirs uses."""
 
1286
    key_a = path_prefix_key(path_a)
 
1287
    key_b = path_prefix_key(path_b)
 
1288
    return cmp(key_a, key_b)
 
1289
 
 
1290
 
 
1291
_cached_user_encoding = None
 
1292
 
 
1293
 
 
1294
def get_user_encoding(use_cache=True):
 
1295
    """Find out what the preferred user encoding is.
 
1296
 
 
1297
    This is generally the encoding that is used for command line parameters
 
1298
    and file contents. This may be different from the terminal encoding
 
1299
    or the filesystem encoding.
 
1300
 
 
1301
    :param  use_cache:  Enable cache for detected encoding.
 
1302
                        (This parameter is turned on by default,
 
1303
                        and required only for selftesting)
 
1304
 
 
1305
    :return: A string defining the preferred user encoding
 
1306
    """
 
1307
    global _cached_user_encoding
 
1308
    if _cached_user_encoding is not None and use_cache:
 
1309
        return _cached_user_encoding
 
1310
 
 
1311
    if sys.platform == 'darwin':
 
1312
        # work around egregious python 2.4 bug
 
1313
        sys.platform = 'posix'
 
1314
        try:
 
1315
            import locale
 
1316
        finally:
 
1317
            sys.platform = 'darwin'
 
1318
    else:
 
1319
        import locale
 
1320
 
 
1321
    try:
 
1322
        user_encoding = locale.getpreferredencoding()
 
1323
    except locale.Error, e:
 
1324
        sys.stderr.write('bzr: warning: %s\n'
 
1325
                         '  Could not determine what text encoding to use.\n'
 
1326
                         '  This error usually means your Python interpreter\n'
 
1327
                         '  doesn\'t support the locale set by $LANG (%s)\n'
 
1328
                         "  Continuing with ascii encoding.\n"
 
1329
                         % (e, os.environ.get('LANG')))
 
1330
        user_encoding = 'ascii'
 
1331
 
 
1332
    # Windows returns 'cp0' to indicate there is no code page. So we'll just
 
1333
    # treat that as ASCII, and not support printing unicode characters to the
 
1334
    # console.
 
1335
    if user_encoding in (None, 'cp0'):
 
1336
        user_encoding = 'ascii'
 
1337
    else:
 
1338
        # check encoding
 
1339
        try:
 
1340
            codecs.lookup(user_encoding)
 
1341
        except LookupError:
 
1342
            sys.stderr.write('bzr: warning:'
 
1343
                             ' unknown encoding %s.'
 
1344
                             ' Continuing with ascii encoding.\n'
 
1345
                             % user_encoding
 
1346
                            )
 
1347
            user_encoding = 'ascii'
 
1348
 
 
1349
    if use_cache:
 
1350
        _cached_user_encoding = user_encoding
 
1351
 
 
1352
    return user_encoding
 
1353
 
 
1354
 
 
1355
def recv_all(socket, bytes):
 
1356
    """Receive an exact number of bytes.
 
1357
 
 
1358
    Regular Socket.recv() may return less than the requested number of bytes,
 
1359
    dependning on what's in the OS buffer.  MSG_WAITALL is not available
 
1360
    on all platforms, but this should work everywhere.  This will return
 
1361
    less than the requested amount if the remote end closes.
 
1362
 
 
1363
    This isn't optimized and is intended mostly for use in testing.
 
1364
    """
 
1365
    b = ''
 
1366
    while len(b) < bytes:
 
1367
        new = socket.recv(bytes - len(b))
 
1368
        if new == '':
 
1369
            break # eof
 
1370
        b += new
 
1371
    return b
 
1372
 
 
1373
def dereference_path(path):
 
1374
    """Determine the real path to a file.
 
1375
 
 
1376
    All parent elements are dereferenced.  But the file itself is not
 
1377
    dereferenced.
 
1378
    :param path: The original path.  May be absolute or relative.
 
1379
    :return: the real path *to* the file
 
1380
    """
 
1381
    parent, base = os.path.split(path)
 
1382
    # The pathjoin for '.' is a workaround for Python bug #1213894.
 
1383
    # (initial path components aren't dereferenced)
 
1384
    return pathjoin(realpath(pathjoin('.', parent)), base)