/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: Aaron Bentley
  • Date: 2009-03-10 07:41:16 UTC
  • mto: This revision was merged to the branch mainline in revision 4112.
  • Revision ID: aaron@aaronbentley.com-20090310074116-ky77036dajc58bsi
More support for not autodetecting tree refs

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