/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: Canonical.com Patch Queue Manager
  • Date: 2009-05-14 18:29:44 UTC
  • mfrom: (4361.1.1 rio-optimized)
  • Revision ID: pqm@pqm.ubuntu.com-20090514182944-yz4v4ggktei02wo0
(jam) Some optimizations for RIO.

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