/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: Ian Clatworthy
  • Date: 2009-12-03 23:21:16 UTC
  • mfrom: (4852.4.1 RCStoVCS)
  • mto: This revision was merged to the branch mainline in revision 4860.
  • Revision ID: ian.clatworthy@canonical.com-20091203232116-f8igfvc6muqrn4yx
Revision Control -> Version Control in docs

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2009 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
 
from __future__ import absolute_import
18
 
 
19
 
import errno
20
17
import os
21
18
import re
22
19
import stat
 
20
from stat import (S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE,
 
21
                  S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
23
22
import sys
24
23
import time
 
24
import warnings
 
25
 
 
26
from bzrlib.lazy_import import lazy_import
 
27
lazy_import(globals(), """
25
28
import codecs
26
 
 
27
 
from .lazy_import import lazy_import
28
 
lazy_import(globals(), """
29
29
from datetime import datetime
30
 
import getpass
31
 
import locale
32
 
import ntpath
 
30
import errno
 
31
from ntpath import (abspath as _nt_abspath,
 
32
                    join as _nt_join,
 
33
                    normpath as _nt_normpath,
 
34
                    realpath as _nt_realpath,
 
35
                    splitdrive as _nt_splitdrive,
 
36
                    )
33
37
import posixpath
34
 
import select
35
 
# We need to import both shutil and rmtree as we export the later on posix
36
 
# and need the former on windows
37
38
import shutil
38
 
from shutil import rmtree
39
 
import socket
 
39
from shutil import (
 
40
    rmtree,
 
41
    )
40
42
import subprocess
41
 
# We need to import both tempfile and mkdtemp as we export the later on posix
42
 
# and need the former on windows
43
43
import tempfile
44
 
from tempfile import mkdtemp
 
44
from tempfile import (
 
45
    mkdtemp,
 
46
    )
45
47
import unicodedata
46
48
 
47
 
from breezy import (
48
 
    config,
49
 
    trace,
 
49
from bzrlib import (
 
50
    cache_utf8,
 
51
    errors,
50
52
    win32utils,
51
53
    )
52
 
from breezy.i18n import gettext
53
54
""")
54
55
 
55
 
from .sixish import (
56
 
    PY3,
57
 
    text_type,
58
 
    )
59
 
 
60
 
from hashlib import (
61
 
    md5,
62
 
    sha1 as sha,
63
 
    )
64
 
 
65
 
 
66
 
import breezy
67
 
from . import (
68
 
    _fs_enc,
69
 
    errors,
70
 
    )
 
56
# sha and md5 modules are deprecated in python2.6 but hashlib is available as
 
57
# of 2.5
 
58
if sys.version_info < (2, 5):
 
59
    import md5 as _mod_md5
 
60
    md5 = _mod_md5.new
 
61
    import sha as _mod_sha
 
62
    sha = _mod_sha.new
 
63
else:
 
64
    from hashlib import (
 
65
        md5,
 
66
        sha1 as sha,
 
67
        )
 
68
 
 
69
 
 
70
import bzrlib
 
71
from bzrlib import symbol_versioning
71
72
 
72
73
 
73
74
# On win32, O_BINARY is used to indicate the file should
74
75
# be opened in binary mode, rather than text mode.
75
76
# On other platforms, O_BINARY doesn't exist, because
76
77
# they always open in binary mode, so it is okay to
77
 
# OR with 0 on those platforms.
78
 
# O_NOINHERIT and O_TEXT exists only on win32 too.
 
78
# OR with 0 on those platforms
79
79
O_BINARY = getattr(os, 'O_BINARY', 0)
80
 
O_TEXT = getattr(os, 'O_TEXT', 0)
81
 
O_NOINHERIT = getattr(os, 'O_NOINHERIT', 0)
82
 
 
83
 
 
84
 
class UnsupportedTimezoneFormat(errors.BzrError):
85
 
 
86
 
    _fmt = ('Unsupported timezone format "%(timezone)s", '
87
 
            'options are "utc", "original", "local".')
88
 
 
89
 
    def __init__(self, timezone):
90
 
        self.timezone = timezone
91
80
 
92
81
 
93
82
def get_unicode_argv():
94
 
    if PY3:
95
 
        return sys.argv[1:]
96
83
    try:
97
84
        user_encoding = get_user_encoding()
98
85
        return [a.decode(user_encoding) for a in sys.argv[1:]]
99
86
    except UnicodeDecodeError:
100
 
        raise errors.BzrError(gettext("Parameter {0!r} encoding is unsupported by {1} "
101
 
                                      "application locale.").format(a, user_encoding))
 
87
        raise errors.BzrError(("Parameter '%r' is unsupported by the current "
 
88
                                                            "encoding." % a))
102
89
 
103
90
 
104
91
def make_readonly(filename):
105
92
    """Make a filename read-only."""
106
93
    mod = os.lstat(filename).st_mode
107
94
    if not stat.S_ISLNK(mod):
108
 
        mod = mod & 0o777555
109
 
        chmod_if_possible(filename, mod)
 
95
        mod = mod & 0777555
 
96
        os.chmod(filename, mod)
110
97
 
111
98
 
112
99
def make_writable(filename):
113
100
    mod = os.lstat(filename).st_mode
114
101
    if not stat.S_ISLNK(mod):
115
 
        mod = mod | 0o200
116
 
        chmod_if_possible(filename, mod)
117
 
 
118
 
 
119
 
def chmod_if_possible(filename, mode):
120
 
    # Set file mode if that can be safely done.
121
 
    # Sometimes even on unix the filesystem won't allow it - see
122
 
    # https://bugs.launchpad.net/bzr/+bug/606537
123
 
    try:
124
 
        # It is probably faster to just do the chmod, rather than
125
 
        # doing a stat, and then trying to compare
126
 
        os.chmod(filename, mode)
127
 
    except (IOError, OSError) as e:
128
 
        # Permission/access denied seems to commonly happen on smbfs; there's
129
 
        # probably no point warning about it.
130
 
        # <https://bugs.launchpad.net/bzr/+bug/606537>
131
 
        if getattr(e, 'errno') in (errno.EPERM, errno.EACCES):
132
 
            trace.mutter("ignore error on chmod of %r: %r" % (
133
 
                filename, e))
134
 
            return
135
 
        raise
 
102
        mod = mod | 0200
 
103
        os.chmod(filename, mod)
136
104
 
137
105
 
138
106
def minimum_path_selection(paths):
146
114
        return set(paths)
147
115
 
148
116
    def sort_key(path):
149
 
        if isinstance(path, bytes):
150
 
            return path.split(b'/')
151
 
        else:
152
 
            return path.split('/')
 
117
        return path.split('/')
153
118
    sorted_paths = sorted(list(paths), key=sort_key)
154
119
 
155
120
    search_paths = [sorted_paths[0]]
182
147
 
183
148
_directory_kind = 'directory'
184
149
 
185
 
 
186
150
def get_umask():
187
151
    """Return the current umask"""
188
152
    # Assume that people aren't messing with the umask while running
205
169
    try:
206
170
        return _kind_marker_map[kind]
207
171
    except KeyError:
208
 
        # Slightly faster than using .get(, '') when the common case is that
209
 
        # kind will be found
210
 
        return ''
 
172
        raise errors.BzrError('invalid file kind %r' % kind)
211
173
 
212
174
 
213
175
lexists = getattr(os.path, 'lexists', None)
217
179
            stat = getattr(os, 'lstat', os.stat)
218
180
            stat(f)
219
181
            return True
220
 
        except OSError as e:
 
182
        except OSError, e:
221
183
            if e.errno == errno.ENOENT:
222
 
                return False
 
184
                return False;
223
185
            else:
224
 
                raise errors.BzrError(
225
 
                    gettext("lstat/stat of ({0!r}): {1!r}").format(f, e))
 
186
                raise errors.BzrError("lstat/stat of (%r): %r" % (f, e))
226
187
 
227
188
 
228
189
def fancy_rename(old, new, rename_func, unlink_func):
231
192
    :param old: The old path, to rename from
232
193
    :param new: The new path, to rename to
233
194
    :param rename_func: The potentially non-atomic rename function
234
 
    :param unlink_func: A way to delete the target file if the full rename
235
 
        succeeds
 
195
    :param unlink_func: A way to delete the target file if the full rename succeeds
236
196
    """
 
197
 
237
198
    # sftp rename doesn't allow overwriting, so play tricks:
238
199
    base = os.path.basename(new)
239
200
    dirname = os.path.dirname(new)
240
 
    # callers use different encodings for the paths so the following MUST
241
 
    # respect that. We rely on python upcasting to unicode if new is unicode
242
 
    # and keeping a str if not.
243
 
    tmp_name = 'tmp.%s.%.9f.%d.%s' % (base, time.time(),
244
 
                                      os.getpid(), rand_chars(10))
 
201
    tmp_name = u'tmp.%s.%.9f.%d.%s' % (base, time.time(), os.getpid(), rand_chars(10))
245
202
    tmp_name = pathjoin(dirname, tmp_name)
246
203
 
247
204
    # Rename the file out of the way, but keep track if it didn't exist
252
209
    file_existed = False
253
210
    try:
254
211
        rename_func(new, tmp_name)
255
 
    except (errors.NoSuchFile,):
 
212
    except (errors.NoSuchFile,), e:
256
213
        pass
257
 
    except IOError as e:
 
214
    except IOError, e:
258
215
        # RBC 20060103 abstraction leakage: the paramiko SFTP clients rename
259
216
        # function raises an IOError with errno is None when a rename fails.
260
217
        # This then gets caught here.
261
218
        if e.errno not in (None, errno.ENOENT, errno.ENOTDIR):
262
219
            raise
263
 
    except Exception as e:
 
220
    except Exception, e:
264
221
        if (getattr(e, 'errno', None) is None
265
 
                or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
 
222
            or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
266
223
            raise
267
224
    else:
268
225
        file_existed = True
269
226
 
 
227
    failure_exc = None
270
228
    success = False
271
229
    try:
272
 
        # This may throw an exception, in which case success will
273
 
        # not be set.
274
 
        rename_func(old, new)
275
 
        success = True
276
 
    except (IOError, OSError) as e:
277
 
        # source and target may be aliases of each other (e.g. on a
278
 
        # case-insensitive filesystem), so we may have accidentally renamed
279
 
        # source by when we tried to rename target
280
 
        if (file_existed and e.errno in (None, errno.ENOENT)
 
230
        try:
 
231
            # This may throw an exception, in which case success will
 
232
            # not be set.
 
233
            rename_func(old, new)
 
234
            success = True
 
235
        except (IOError, OSError), e:
 
236
            # source and target may be aliases of each other (e.g. on a
 
237
            # case-insensitive filesystem), so we may have accidentally renamed
 
238
            # source by when we tried to rename target
 
239
            failure_exc = sys.exc_info()
 
240
            if (file_existed and e.errno in (None, errno.ENOENT)
281
241
                and old.lower() == new.lower()):
282
 
            # source and target are the same file on a case-insensitive
283
 
            # filesystem, so we don't generate an exception
284
 
            pass
285
 
        else:
286
 
            raise
 
242
                # source and target are the same file on a case-insensitive
 
243
                # filesystem, so we don't generate an exception
 
244
                failure_exc = None
287
245
    finally:
288
246
        if file_existed:
289
247
            # If the file used to exist, rename it back into place
292
250
                unlink_func(tmp_name)
293
251
            else:
294
252
                rename_func(tmp_name, new)
 
253
    if failure_exc is not None:
 
254
        raise failure_exc[0], failure_exc[1], failure_exc[2]
295
255
 
296
256
 
297
257
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
298
258
# choke on a Unicode string containing a relative path if
299
259
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
300
260
# string.
 
261
_fs_enc = sys.getfilesystemencoding() or 'utf-8'
301
262
def _posix_abspath(path):
302
263
    # jam 20060426 rather than encoding to fsencoding
303
264
    # copy posixpath.abspath, but use os.getcwdu instead
304
265
    if not posixpath.isabs(path):
305
266
        path = posixpath.join(getcwd(), path)
306
 
    return _posix_normpath(path)
 
267
    return posixpath.normpath(path)
307
268
 
308
269
 
309
270
def _posix_realpath(path):
310
271
    return posixpath.realpath(path.encode(_fs_enc)).decode(_fs_enc)
311
272
 
312
273
 
313
 
def _posix_normpath(path):
314
 
    path = posixpath.normpath(path)
315
 
    # Bug 861008: posixpath.normpath() returns a path normalized according to
316
 
    # the POSIX standard, which stipulates (for compatibility reasons) that two
317
 
    # leading slashes must not be simplified to one, and only if there are 3 or
318
 
    # more should they be simplified as one. So we treat the leading 2 slashes
319
 
    # as a special case here by simply removing the first slash, as we consider
320
 
    # that breaking POSIX compatibility for this obscure feature is acceptable.
321
 
    # This is not a paranoid precaution, as we notably get paths like this when
322
 
    # the repo is hosted at the root of the filesystem, i.e. in "/".
323
 
    if path.startswith('//'):
324
 
        path = path[1:]
325
 
    return path
326
 
 
327
 
 
328
 
def _posix_path_from_environ(key):
329
 
    """Get unicode path from `key` in environment or None if not present
330
 
 
331
 
    Note that posix systems use arbitrary byte strings for filesystem objects,
332
 
    so a path that raises BadFilenameEncoding here may still be accessible.
333
 
    """
334
 
    val = os.environ.get(key, None)
335
 
    if PY3 or val is None:
336
 
        return val
337
 
    try:
338
 
        return val.decode(_fs_enc)
339
 
    except UnicodeDecodeError:
340
 
        # GZ 2011-12-12:Ideally want to include `key` in the exception message
341
 
        raise errors.BadFilenameEncoding(val, _fs_enc)
342
 
 
343
 
 
344
 
def _posix_get_home_dir():
345
 
    """Get the home directory of the current user as a unicode path"""
346
 
    path = posixpath.expanduser("~")
347
 
    try:
348
 
        return path.decode(_fs_enc)
349
 
    except AttributeError:
350
 
        return path
351
 
    except UnicodeDecodeError:
352
 
        raise errors.BadFilenameEncoding(path, _fs_enc)
353
 
 
354
 
 
355
 
def _posix_getuser_unicode():
356
 
    """Get username from environment or password database as unicode"""
357
 
    name = getpass.getuser()
358
 
    if PY3:
359
 
        return name
360
 
    user_encoding = get_user_encoding()
361
 
    try:
362
 
        return name.decode(user_encoding)
363
 
    except UnicodeDecodeError:
364
 
        raise errors.BzrError("Encoding of username %r is unsupported by %s "
365
 
                              "application locale." % (name, user_encoding))
366
 
 
367
 
 
368
274
def _win32_fixdrive(path):
369
275
    """Force drive letters to be consistent.
370
276
 
374
280
    running python.exe under cmd.exe return capital C:\\
375
281
    running win32 python inside a cygwin shell returns lowercase c:\\
376
282
    """
377
 
    drive, path = ntpath.splitdrive(path)
 
283
    drive, path = _nt_splitdrive(path)
378
284
    return drive.upper() + path
379
285
 
380
286
 
381
287
def _win32_abspath(path):
382
 
    # Real ntpath.abspath doesn't have a problem with a unicode cwd
383
 
    return _win32_fixdrive(ntpath.abspath(path).replace('\\', '/'))
 
288
    # Real _nt_abspath doesn't have a problem with a unicode cwd
 
289
    return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
 
290
 
 
291
 
 
292
def _win98_abspath(path):
 
293
    """Return the absolute version of a path.
 
294
    Windows 98 safe implementation (python reimplementation
 
295
    of Win32 API function GetFullPathNameW)
 
296
    """
 
297
    # Corner cases:
 
298
    #   C:\path     => C:/path
 
299
    #   C:/path     => C:/path
 
300
    #   \\HOST\path => //HOST/path
 
301
    #   //HOST/path => //HOST/path
 
302
    #   path        => C:/cwd/path
 
303
    #   /path       => C:/path
 
304
    path = unicode(path)
 
305
    # check for absolute path
 
306
    drive = _nt_splitdrive(path)[0]
 
307
    if drive == '' and path[:2] not in('//','\\\\'):
 
308
        cwd = os.getcwdu()
 
309
        # we cannot simply os.path.join cwd and path
 
310
        # because os.path.join('C:','/path') produce '/path'
 
311
        # and this is incorrect
 
312
        if path[:1] in ('/','\\'):
 
313
            cwd = _nt_splitdrive(cwd)[0]
 
314
            path = path[1:]
 
315
        path = cwd + '\\' + path
 
316
    return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
384
317
 
385
318
 
386
319
def _win32_realpath(path):
387
 
    # Real ntpath.realpath doesn't have a problem with a unicode cwd
388
 
    return _win32_fixdrive(ntpath.realpath(path).replace('\\', '/'))
 
320
    # Real _nt_realpath doesn't have a problem with a unicode cwd
 
321
    return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
389
322
 
390
323
 
391
324
def _win32_pathjoin(*args):
392
 
    return ntpath.join(*args).replace('\\', '/')
 
325
    return _nt_join(*args).replace('\\', '/')
393
326
 
394
327
 
395
328
def _win32_normpath(path):
396
 
    return _win32_fixdrive(ntpath.normpath(path).replace('\\', '/'))
 
329
    return _win32_fixdrive(_nt_normpath(unicode(path)).replace('\\', '/'))
397
330
 
398
331
 
399
332
def _win32_getcwd():
400
 
    return _win32_fixdrive(_getcwd().replace('\\', '/'))
 
333
    return _win32_fixdrive(os.getcwdu().replace('\\', '/'))
401
334
 
402
335
 
403
336
def _win32_mkdtemp(*args, **kwargs):
412
345
    """
413
346
    try:
414
347
        fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
415
 
    except OSError as e:
 
348
    except OSError, e:
416
349
        if e.errno in (errno.EPERM, errno.EACCES, errno.EBUSY, errno.EINVAL):
417
350
            # If we try to rename a non-existant file onto cwd, we get
418
351
            # EPERM or EACCES instead of ENOENT, this will raise ENOENT
423
356
 
424
357
 
425
358
def _mac_getcwd():
426
 
    return unicodedata.normalize('NFC', _getcwd())
427
 
 
428
 
 
429
 
def _rename_wrap_exception(rename_func):
430
 
    """Adds extra information to any exceptions that come from rename().
431
 
 
432
 
    The exception has an updated message and 'old_filename' and 'new_filename'
433
 
    attributes.
434
 
    """
435
 
 
436
 
    def _rename_wrapper(old, new):
437
 
        try:
438
 
            rename_func(old, new)
439
 
        except OSError as e:
440
 
            detailed_error = OSError(e.errno, e.strerror +
441
 
                                     " [occurred when renaming '%s' to '%s']" %
442
 
                                     (old, new))
443
 
            detailed_error.old_filename = old
444
 
            detailed_error.new_filename = new
445
 
            raise detailed_error
446
 
 
447
 
    return _rename_wrapper
448
 
 
449
 
 
450
 
if sys.version_info > (3,):
451
 
    _getcwd = os.getcwd
452
 
else:
453
 
    _getcwd = os.getcwdu
454
 
 
455
 
 
456
 
# Default rename wraps os.rename()
457
 
rename = _rename_wrap_exception(os.rename)
 
359
    return unicodedata.normalize('NFC', os.getcwdu())
 
360
 
458
361
 
459
362
# Default is to just use the python builtins, but these can be rebound on
460
363
# particular platforms.
461
364
abspath = _posix_abspath
462
365
realpath = _posix_realpath
463
366
pathjoin = os.path.join
464
 
normpath = _posix_normpath
465
 
path_from_environ = _posix_path_from_environ
466
 
_get_home_dir = _posix_get_home_dir
467
 
getuser_unicode = _posix_getuser_unicode
468
 
getcwd = _getcwd
 
367
normpath = os.path.normpath
 
368
getcwd = os.getcwdu
 
369
rename = os.rename
469
370
dirname = os.path.dirname
470
371
basename = os.path.basename
471
372
split = os.path.split
472
373
splitext = os.path.splitext
473
 
# These were already lazily imported into local scope
 
374
# These were already imported into local scope
474
375
# mkdtemp = tempfile.mkdtemp
475
376
# rmtree = shutil.rmtree
476
 
lstat = os.lstat
477
 
fstat = os.fstat
478
 
 
479
 
 
480
 
def wrap_stat(st):
481
 
    return st
482
 
 
483
377
 
484
378
MIN_ABS_PATHLENGTH = 1
485
379
 
486
380
 
487
381
if sys.platform == 'win32':
488
 
    abspath = _win32_abspath
 
382
    if win32utils.winver == 'Windows 98':
 
383
        abspath = _win98_abspath
 
384
    else:
 
385
        abspath = _win32_abspath
489
386
    realpath = _win32_realpath
490
387
    pathjoin = _win32_pathjoin
491
388
    normpath = _win32_normpath
492
389
    getcwd = _win32_getcwd
493
390
    mkdtemp = _win32_mkdtemp
494
 
    rename = _rename_wrap_exception(_win32_rename)
495
 
    try:
496
 
        from . import _walkdirs_win32
497
 
    except ImportError:
498
 
        pass
499
 
    else:
500
 
        lstat = _walkdirs_win32.lstat
501
 
        fstat = _walkdirs_win32.fstat
502
 
        wrap_stat = _walkdirs_win32.wrap_stat
 
391
    rename = _win32_rename
503
392
 
504
393
    MIN_ABS_PATHLENGTH = 3
505
394
 
509
398
        """
510
399
        exception = excinfo[1]
511
400
        if function in (os.remove, os.rmdir) \
512
 
                and isinstance(exception, OSError) \
513
 
                and exception.errno == errno.EACCES:
 
401
            and isinstance(exception, OSError) \
 
402
            and exception.errno == errno.EACCES:
514
403
            make_writable(path)
515
404
            function(path)
516
405
        else:
520
409
        """Replacer for shutil.rmtree: could remove readonly dirs/files"""
521
410
        return shutil.rmtree(path, ignore_errors, onerror)
522
411
 
523
 
    get_unicode_argv = getattr(win32utils, 'get_unicode_argv', get_unicode_argv)
524
 
    path_from_environ = win32utils.get_environ_unicode
525
 
    _get_home_dir = win32utils.get_home_location
526
 
    getuser_unicode = win32utils.get_user_name
 
412
    f = win32utils.get_unicode_argv     # special function or None
 
413
    if f is not None:
 
414
        get_unicode_argv = f
527
415
 
528
416
elif sys.platform == 'darwin':
529
417
    getcwd = _mac_getcwd
530
418
 
531
419
 
532
 
def get_terminal_encoding(trace=False):
 
420
def get_terminal_encoding():
533
421
    """Find the best encoding for printing to the screen.
534
422
 
535
423
    This attempts to check both sys.stdout and sys.stdin to see
541
429
 
542
430
    On my standard US Windows XP, the preferred encoding is
543
431
    cp1252, but the console is cp437
544
 
 
545
 
    :param trace: If True trace the selected encoding via mutter().
546
432
    """
547
 
    from .trace import mutter
 
433
    from bzrlib.trace import mutter
548
434
    output_encoding = getattr(sys.stdout, 'encoding', None)
549
435
    if not output_encoding:
550
436
        input_encoding = getattr(sys.stdin, 'encoding', None)
551
437
        if not input_encoding:
552
438
            output_encoding = get_user_encoding()
553
 
            if trace:
554
 
                mutter('encoding stdout as osutils.get_user_encoding() %r',
555
 
                       output_encoding)
 
439
            mutter('encoding stdout as osutils.get_user_encoding() %r',
 
440
                   output_encoding)
556
441
        else:
557
442
            output_encoding = input_encoding
558
 
            if trace:
559
 
                mutter('encoding stdout as sys.stdin encoding %r',
560
 
                       output_encoding)
 
443
            mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
561
444
    else:
562
 
        if trace:
563
 
            mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
 
445
        mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
564
446
    if output_encoding == 'cp0':
565
447
        # invalid encoding (cp0 means 'no codepage' on Windows)
566
448
        output_encoding = get_user_encoding()
567
 
        if trace:
568
 
            mutter('cp0 is invalid encoding.'
569
 
                   ' encoding stdout as osutils.get_user_encoding() %r',
570
 
                   output_encoding)
 
449
        mutter('cp0 is invalid encoding.'
 
450
               ' encoding stdout as osutils.get_user_encoding() %r',
 
451
               output_encoding)
571
452
    # check encoding
572
453
    try:
573
454
        codecs.lookup(output_encoding)
574
455
    except LookupError:
575
 
        sys.stderr.write('brz: warning:'
 
456
        sys.stderr.write('bzr: warning:'
576
457
                         ' unknown terminal encoding %s.\n'
577
458
                         '  Using encoding %s instead.\n'
578
459
                         % (output_encoding, get_user_encoding())
579
 
                         )
 
460
                        )
580
461
        output_encoding = get_user_encoding()
581
462
 
582
463
    return output_encoding
587
468
        F = realpath
588
469
    else:
589
470
        F = abspath
590
 
    [p, e] = os.path.split(f)
 
471
    [p,e] = os.path.split(f)
591
472
    if e == "" or e == "." or e == "..":
592
473
        return F(f)
593
474
    else:
597
478
def isdir(f):
598
479
    """True if f is an accessible directory."""
599
480
    try:
600
 
        return stat.S_ISDIR(os.lstat(f)[stat.ST_MODE])
 
481
        return S_ISDIR(os.lstat(f)[ST_MODE])
601
482
    except OSError:
602
483
        return False
603
484
 
605
486
def isfile(f):
606
487
    """True if f is a regular file."""
607
488
    try:
608
 
        return stat.S_ISREG(os.lstat(f)[stat.ST_MODE])
 
489
        return S_ISREG(os.lstat(f)[ST_MODE])
609
490
    except OSError:
610
491
        return False
611
492
 
612
 
 
613
493
def islink(f):
614
494
    """True if f is a symlink."""
615
495
    try:
616
 
        return stat.S_ISLNK(os.lstat(f)[stat.ST_MODE])
 
496
        return S_ISLNK(os.lstat(f)[ST_MODE])
617
497
    except OSError:
618
498
        return False
619
499
 
620
 
 
621
500
def is_inside(dir, fname):
622
501
    """True if fname is inside dir.
623
502
 
633
512
    if dir == fname:
634
513
        return True
635
514
 
636
 
    if dir in ('', b''):
 
515
    if dir == '':
637
516
        return True
638
517
 
639
 
    if isinstance(dir, bytes):
640
 
        if not dir.endswith(b'/'):
641
 
            dir += b'/'
642
 
    else:
643
 
        if not dir.endswith('/'):
644
 
            dir += '/'
 
518
    if dir[-1] != '/':
 
519
        dir += '/'
645
520
 
646
521
    return fname.startswith(dir)
647
522
 
720
595
    # writes fail on some platforms (e.g. Windows with SMB  mounted
721
596
    # drives).
722
597
    if not segment_size:
723
 
        segment_size = 5242880  # 5MB
724
 
    offsets = range(0, len(bytes), segment_size)
725
 
    view = memoryview(bytes)
 
598
        segment_size = 5242880 # 5MB
 
599
    segments = range(len(bytes) / segment_size + 1)
726
600
    write = file_handle.write
727
 
    for offset in offsets:
728
 
        write(view[offset:offset + segment_size])
 
601
    for segment_index in segments:
 
602
        segment = buffer(bytes, segment_index * segment_size, segment_size)
 
603
        write(segment)
729
604
 
730
605
 
731
606
def file_iterator(input_file, readsize=32768):
736
611
        yield b
737
612
 
738
613
 
739
 
# GZ 2017-09-16: Makes sense in general for hexdigest() result to be text, but
740
 
# used as bytes through most interfaces so encode with this wrapper.
741
 
if PY3:
742
 
    def _hexdigest(hashobj):
743
 
        return hashobj.hexdigest().encode()
744
 
else:
745
 
    def _hexdigest(hashobj):
746
 
        return hashobj.hexdigest()
747
 
 
748
 
 
749
614
def sha_file(f):
750
615
    """Calculate the hexdigest of an open file.
751
616
 
752
617
    The file cursor should be already at the start.
753
618
    """
754
619
    s = sha()
755
 
    BUFSIZE = 128 << 10
 
620
    BUFSIZE = 128<<10
756
621
    while True:
757
622
        b = f.read(BUFSIZE)
758
623
        if not b:
759
624
            break
760
625
        s.update(b)
761
 
    return _hexdigest(s)
 
626
    return s.hexdigest()
762
627
 
763
628
 
764
629
def size_sha_file(f):
769
634
    """
770
635
    size = 0
771
636
    s = sha()
772
 
    BUFSIZE = 128 << 10
 
637
    BUFSIZE = 128<<10
773
638
    while True:
774
639
        b = f.read(BUFSIZE)
775
640
        if not b:
776
641
            break
777
642
        size += len(b)
778
643
        s.update(b)
779
 
    return size, _hexdigest(s)
 
644
    return size, s.hexdigest()
780
645
 
781
646
 
782
647
def sha_file_by_name(fname):
783
648
    """Calculate the SHA1 of a file by reading the full text"""
784
649
    s = sha()
785
 
    f = os.open(fname, os.O_RDONLY | O_BINARY | O_NOINHERIT)
 
650
    f = os.open(fname, os.O_RDONLY | O_BINARY)
786
651
    try:
787
652
        while True:
788
 
            b = os.read(f, 1 << 16)
 
653
            b = os.read(f, 1<<16)
789
654
            if not b:
790
 
                return _hexdigest(s)
 
655
                return s.hexdigest()
791
656
            s.update(b)
792
657
    finally:
793
658
        os.close(f)
796
661
def sha_strings(strings, _factory=sha):
797
662
    """Return the sha-1 of concatenation of strings"""
798
663
    s = _factory()
799
 
    for string in strings:
800
 
        s.update(string)
801
 
    return _hexdigest(s)
 
664
    map(s.update, strings)
 
665
    return s.hexdigest()
802
666
 
803
667
 
804
668
def sha_string(f, _factory=sha):
805
 
    # GZ 2017-09-16: Dodgy if factory is ever not sha, probably shouldn't be.
806
 
    return _hexdigest(_factory(f))
 
669
    return _factory(f).hexdigest()
807
670
 
808
671
 
809
672
def fingerprint_file(f):
810
673
    b = f.read()
811
674
    return {'size': len(b),
812
 
            'sha1': _hexdigest(sha(b))}
 
675
            'sha1': sha(b).hexdigest()}
813
676
 
814
677
 
815
678
def compare_files(a, b):
820
683
        bi = b.read(BUFSIZE)
821
684
        if ai != bi:
822
685
            return False
823
 
        if not ai:
 
686
        if ai == '':
824
687
            return True
825
688
 
826
689
 
831
694
    offset = datetime.fromtimestamp(t) - datetime.utcfromtimestamp(t)
832
695
    return offset.days * 86400 + offset.seconds
833
696
 
834
 
 
835
697
weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
836
698
_default_format_by_weekday_num = [wd + " %Y-%m-%d %H:%M:%S" for wd in weekdays]
837
699
 
849
711
    :param show_offset: Whether to append the timezone.
850
712
    """
851
713
    (date_fmt, tt, offset_str) = \
852
 
        _format_date(t, offset, timezone, date_fmt, show_offset)
 
714
               _format_date(t, offset, timezone, date_fmt, show_offset)
853
715
    date_fmt = date_fmt.replace('%a', weekdays[tt[6]])
854
716
    date_str = time.strftime(date_fmt, tt)
855
717
    return date_str + offset_str
860
722
 
861
723
 
862
724
def format_date_with_offset_in_original_timezone(t, offset=0,
863
 
                                                 _cache=_offset_cache):
 
725
    _cache=_offset_cache):
864
726
    """Return a formatted date string in the original timezone.
865
727
 
866
728
    This routine may be faster then format_date.
893
755
    :param show_offset: Whether to append the timezone.
894
756
    """
895
757
    (date_fmt, tt, offset_str) = \
896
 
        _format_date(t, offset, timezone, date_fmt, show_offset)
 
758
               _format_date(t, offset, timezone, date_fmt, show_offset)
897
759
    date_str = time.strftime(date_fmt, tt)
898
 
    if not isinstance(date_str, text_type):
 
760
    if not isinstance(date_str, unicode):
899
761
        date_str = date_str.decode(get_user_encoding(), 'replace')
900
762
    return date_str + offset_str
901
763
 
912
774
        tt = time.localtime(t)
913
775
        offset = local_time_offset(t)
914
776
    else:
915
 
        raise UnsupportedTimezoneFormat(timezone)
 
777
        raise errors.UnsupportedTimezoneFormat(timezone)
916
778
    if date_fmt is None:
917
779
        date_fmt = "%a %Y-%m-%d %H:%M:%S"
918
780
    if show_offset:
942
804
        delta = -delta
943
805
 
944
806
    seconds = delta
945
 
    if seconds < 90:  # print seconds up to 90 seconds
 
807
    if seconds < 90: # print seconds up to 90 seconds
946
808
        if seconds == 1:
947
809
            return '%d second %s' % (seconds, direction,)
948
810
        else:
954
816
        plural_seconds = ''
955
817
    else:
956
818
        plural_seconds = 's'
957
 
    if minutes < 90:  # print minutes, seconds up to 90 minutes
 
819
    if minutes < 90: # print minutes, seconds up to 90 minutes
958
820
        if minutes == 1:
959
821
            return '%d minute, %d second%s %s' % (
960
 
                minutes, seconds, plural_seconds, direction)
 
822
                    minutes, seconds, plural_seconds, direction)
961
823
        else:
962
824
            return '%d minutes, %d second%s %s' % (
963
 
                minutes, seconds, plural_seconds, direction)
 
825
                    minutes, seconds, plural_seconds, direction)
964
826
 
965
827
    hours = int(minutes / 60)
966
828
    minutes -= 60 * hours
975
837
    return '%d hours, %d minute%s %s' % (hours, minutes,
976
838
                                         plural_minutes, direction)
977
839
 
978
 
 
979
840
def filesize(f):
980
841
    """Return size of given open file."""
981
 
    return os.fstat(f.fileno())[stat.ST_SIZE]
982
 
 
983
 
 
984
 
# Alias os.urandom to support platforms (which?) without /dev/urandom and
985
 
# override if it doesn't work. Avoid checking on windows where there is
986
 
# significant initialisation cost that can be avoided for some bzr calls.
987
 
 
988
 
rand_bytes = os.urandom
989
 
 
990
 
if rand_bytes.__module__ != "nt":
 
842
    return os.fstat(f.fileno())[ST_SIZE]
 
843
 
 
844
 
 
845
# Define rand_bytes based on platform.
 
846
try:
 
847
    # Python 2.4 and later have os.urandom,
 
848
    # but it doesn't work on some arches
 
849
    os.urandom(1)
 
850
    rand_bytes = os.urandom
 
851
except (NotImplementedError, AttributeError):
 
852
    # If python doesn't have os.urandom, or it doesn't work,
 
853
    # then try to first pull random data from /dev/urandom
991
854
    try:
992
 
        rand_bytes(1)
993
 
    except NotImplementedError:
 
855
        rand_bytes = file('/dev/urandom', 'rb').read
 
856
    # Otherwise, use this hack as a last resort
 
857
    except (IOError, OSError):
994
858
        # not well seeded, but better than nothing
995
859
        def rand_bytes(n):
996
860
            import random
1002
866
 
1003
867
 
1004
868
ALNUM = '0123456789abcdefghijklmnopqrstuvwxyz'
1005
 
 
1006
 
 
1007
869
def rand_chars(num):
1008
870
    """Return a random string of num alphanumeric characters
1009
871
 
1012
874
    """
1013
875
    s = ''
1014
876
    for raw_byte in rand_bytes(num):
1015
 
        if not PY3:
1016
 
            s += ALNUM[ord(raw_byte) % 36]
1017
 
        else:
1018
 
            s += ALNUM[raw_byte % 36]
 
877
        s += ALNUM[ord(raw_byte) % 36]
1019
878
    return s
1020
879
 
1021
880
 
1022
 
# TODO: We could later have path objects that remember their list
1023
 
# decomposition (might be too tricksy though.)
 
881
## TODO: We could later have path objects that remember their list
 
882
## decomposition (might be too tricksy though.)
1024
883
 
1025
884
def splitpath(p):
1026
885
    """Turn string into list of parts."""
1027
 
    use_bytes = isinstance(p, bytes)
1028
 
    if os.path.sep == '\\':
1029
 
        # split on either delimiter because people might use either on
1030
 
        # Windows
1031
 
        if use_bytes:
1032
 
            ps = re.split(b'[\\\\/]', p)
1033
 
        else:
1034
 
            ps = re.split(r'[\\/]', p)
1035
 
    else:
1036
 
        if use_bytes:
1037
 
            ps = p.split(b'/')
1038
 
        else:
1039
 
            ps = p.split('/')
1040
 
 
1041
 
    if use_bytes:
1042
 
        parent_dir = b'..'
1043
 
        current_empty_dir = (b'.', b'')
1044
 
    else:
1045
 
        parent_dir = '..'
1046
 
        current_empty_dir = ('.', '')
 
886
    # split on either delimiter because people might use either on
 
887
    # Windows
 
888
    ps = re.split(r'[\\/]', p)
1047
889
 
1048
890
    rps = []
1049
891
    for f in ps:
1050
 
        if f == parent_dir:
1051
 
            raise errors.BzrError(gettext("sorry, %r not allowed in path") % f)
1052
 
        elif f in current_empty_dir:
 
892
        if f == '..':
 
893
            raise errors.BzrError("sorry, %r not allowed in path" % f)
 
894
        elif (f == '.') or (f == ''):
1053
895
            pass
1054
896
        else:
1055
897
            rps.append(f)
1059
901
def joinpath(p):
1060
902
    for f in p:
1061
903
        if (f == '..') or (f is None) or (f == ''):
1062
 
            raise errors.BzrError(gettext("sorry, %r not allowed in path") % f)
 
904
            raise errors.BzrError("sorry, %r not allowed in path" % f)
1063
905
    return pathjoin(*p)
1064
906
 
1065
907
 
1066
908
def parent_directories(filename):
1067
909
    """Return the list of parent directories, deepest first.
1068
 
 
 
910
    
1069
911
    For example, parent_directories("a/b/c") -> ["a/b", "a"].
1070
912
    """
1071
913
    parents = []
1087
929
    implementation should be loaded instead::
1088
930
 
1089
931
    >>> try:
1090
 
    >>>     import breezy._fictional_extension_pyx
 
932
    >>>     import bzrlib._fictional_extension_pyx
1091
933
    >>> except ImportError, e:
1092
 
    >>>     breezy.osutils.failed_to_load_extension(e)
1093
 
    >>>     import breezy._fictional_extension_py
 
934
    >>>     bzrlib.osutils.failed_to_load_extension(e)
 
935
    >>>     import bzrlib._fictional_extension_py
1094
936
    """
1095
937
    # NB: This docstring is just an example, not a doctest, because doctest
1096
938
    # currently can't cope with the use of lazy imports in this namespace --
1097
939
    # mbp 20090729
1098
 
 
 
940
    
1099
941
    # This currently doesn't report the failure at the time it occurs, because
1100
942
    # they tend to happen very early in startup when we can't check config
1101
943
    # files etc, and also we want to report all failures but not spam the user
1102
944
    # with 10 warnings.
 
945
    from bzrlib import trace
1103
946
    exception_str = str(exception)
1104
947
    if exception_str not in _extension_load_failures:
1105
948
        trace.mutter("failed to load compiled extension: %s" % exception_str)
1109
952
def report_extension_load_failures():
1110
953
    if not _extension_load_failures:
1111
954
        return
1112
 
    if config.GlobalConfig().suppress_warning('missing_extensions'):
 
955
    from bzrlib.config import GlobalConfig
 
956
    if GlobalConfig().get_user_option_as_bool('ignore_missing_extensions'):
1113
957
        return
1114
958
    # the warnings framework should by default show this only once
1115
 
    from .trace import warning
 
959
    from bzrlib.trace import warning
1116
960
    warning(
1117
 
        "brz: warning: some compiled extensions could not be loaded; "
1118
 
        "see ``brz help missing-extensions``")
 
961
        "bzr: warning: some compiled extensions could not be loaded; "
 
962
        "see <https://answers.launchpad.net/bzr/+faq/703>")
1119
963
    # we no longer show the specific missing extensions here, because it makes
1120
964
    # the message too long and scary - see
1121
965
    # https://bugs.launchpad.net/bzr/+bug/430529
1122
966
 
1123
967
 
1124
968
try:
1125
 
    from ._chunks_to_lines_pyx import chunks_to_lines
1126
 
except ImportError as e:
 
969
    from bzrlib._chunks_to_lines_pyx import chunks_to_lines
 
970
except ImportError, e:
1127
971
    failed_to_load_extension(e)
1128
 
    from ._chunks_to_lines_py import chunks_to_lines
 
972
    from bzrlib._chunks_to_lines_py import chunks_to_lines
1129
973
 
1130
974
 
1131
975
def split_lines(s):
1132
976
    """Split s into lines, but without removing the newline characters."""
1133
977
    # Trivially convert a fulltext into a 'chunked' representation, and let
1134
978
    # chunks_to_lines do the heavy lifting.
1135
 
    if isinstance(s, bytes):
 
979
    if isinstance(s, str):
1136
980
        # chunks_to_lines only supports 8-bit strings
1137
981
        return chunks_to_lines([s])
1138
982
    else:
1144
988
 
1145
989
    This supports Unicode or plain string objects.
1146
990
    """
1147
 
    nl = b'\n' if isinstance(s, bytes) else u'\n'
1148
 
    lines = s.split(nl)
1149
 
    result = [line + nl for line in lines[:-1]]
 
991
    lines = s.split('\n')
 
992
    result = [line + '\n' for line in lines[:-1]]
1150
993
    if lines[-1]:
1151
994
        result.append(lines[-1])
1152
995
    return result
1163
1006
        return
1164
1007
    try:
1165
1008
        os.link(src, dest)
1166
 
    except (OSError, IOError) as e:
 
1009
    except (OSError, IOError), e:
1167
1010
        if e.errno != errno.EXDEV:
1168
1011
            raise
1169
1012
        shutil.copyfile(src, dest)
1170
1013
 
1171
1014
 
1172
1015
def delete_any(path):
1173
 
    """Delete a file, symlink or directory.
1174
 
 
 
1016
    """Delete a file, symlink or directory.  
 
1017
    
1175
1018
    Will delete even if readonly.
1176
1019
    """
1177
1020
    try:
1178
 
        _delete_file_or_dir(path)
1179
 
    except (OSError, IOError) as e:
 
1021
       _delete_file_or_dir(path)
 
1022
    except (OSError, IOError), e:
1180
1023
        if e.errno in (errno.EPERM, errno.EACCES):
1181
1024
            # make writable and try again
1182
1025
            try:
1194
1037
    # - root can damage a solaris file system by using unlink,
1195
1038
    # - unlink raises different exceptions on different OSes (linux: EISDIR, win32:
1196
1039
    #   EACCES, OSX: EPERM) when invoked on a directory.
1197
 
    if isdir(path):  # Takes care of symlinks
 
1040
    if isdir(path): # Takes care of symlinks
1198
1041
        os.rmdir(path)
1199
1042
    else:
1200
1043
        os.unlink(path)
1242
1085
    #    separators
1243
1086
    # 3) '\xa0' isn't unicode safe since it is >128.
1244
1087
 
1245
 
    if isinstance(s, str):
1246
 
        ws = ' \t\n\r\v\f'
1247
 
    else:
1248
 
        ws = (b' ', b'\t', b'\n', b'\r', b'\v', b'\f')
1249
 
    for ch in ws:
 
1088
    # This should *not* be a unicode set of characters in case the source
 
1089
    # string is not a Unicode string. We can auto-up-cast the characters since
 
1090
    # they are ascii, but we don't want to auto-up-cast the string in case it
 
1091
    # is utf-8
 
1092
    for ch in ' \t\n\r\v\f':
1250
1093
        if ch in s:
1251
1094
            return True
1252
1095
    else:
1263
1106
 
1264
1107
 
1265
1108
def relpath(base, path):
1266
 
    """Return path relative to base, or raise PathNotChild exception.
 
1109
    """Return path relative to base, or raise exception.
1267
1110
 
1268
1111
    The path may be either an absolute path or a path relative to the
1269
1112
    current working directory.
1271
1114
    os.path.commonprefix (python2.4) has a bad bug that it works just
1272
1115
    on string prefixes, assuming that '/u' is a prefix of '/u2'.  This
1273
1116
    avoids that problem.
1274
 
 
1275
 
    NOTE: `base` should not have a trailing slash otherwise you'll get
1276
 
    PathNotChild exceptions regardless of `path`.
1277
1117
    """
1278
1118
 
1279
1119
    if len(base) < MIN_ABS_PATHLENGTH:
1280
1120
        # must have space for e.g. a drive letter
1281
 
        raise ValueError(gettext('%r is too short to calculate a relative path')
1282
 
                         % (base,))
 
1121
        raise ValueError('%r is too short to calculate a relative path'
 
1122
            % (base,))
1283
1123
 
1284
1124
    rp = abspath(path)
1285
1125
 
1330
1170
        lbit = bit.lower()
1331
1171
        try:
1332
1172
            next_entries = _listdir(current)
1333
 
        except OSError:  # enoent, eperm, etc
 
1173
        except OSError: # enoent, eperm, etc
1334
1174
            # We can't find this in the filesystem, so just append the
1335
1175
            # remaining bits.
1336
1176
            current = pathjoin(current, bit, *list(bit_iter))
1347
1187
            break
1348
1188
    return current[len(abs_base):].lstrip('/')
1349
1189
 
1350
 
 
1351
1190
# XXX - TODO - we need better detection/integration of case-insensitive
1352
1191
# file-systems; Linux often sees FAT32 devices (or NFS-mounted OSX
1353
1192
# filesystems), for example, so could probably benefit from the same basic
1358
1197
else:
1359
1198
    canonical_relpath = relpath
1360
1199
 
1361
 
 
1362
1200
def canonical_relpaths(base, paths):
1363
1201
    """Create an iterable to canonicalize a sequence of relative paths.
1364
1202
 
1368
1206
    # but for now, we haven't optimized...
1369
1207
    return [canonical_relpath(base, p) for p in paths]
1370
1208
 
1371
 
 
1372
 
def decode_filename(filename):
1373
 
    """Decode the filename using the filesystem encoding
1374
 
 
1375
 
    If it is unicode, it is returned.
1376
 
    Otherwise it is decoded from the the filesystem's encoding. If decoding
1377
 
    fails, a errors.BadFilenameEncoding exception is raised.
1378
 
    """
1379
 
    if isinstance(filename, text_type):
1380
 
        return filename
1381
 
    try:
1382
 
        return filename.decode(_fs_enc)
1383
 
    except UnicodeDecodeError:
1384
 
        raise errors.BadFilenameEncoding(filename, _fs_enc)
1385
 
 
1386
 
 
1387
1209
def safe_unicode(unicode_or_utf8_string):
1388
1210
    """Coerce unicode_or_utf8_string into unicode.
1389
1211
 
1391
1213
    Otherwise it is decoded from utf-8. If decoding fails, the exception is
1392
1214
    wrapped in a BzrBadParameterNotUnicode exception.
1393
1215
    """
1394
 
    if isinstance(unicode_or_utf8_string, text_type):
 
1216
    if isinstance(unicode_or_utf8_string, unicode):
1395
1217
        return unicode_or_utf8_string
1396
1218
    try:
1397
1219
        return unicode_or_utf8_string.decode('utf8')
1405
1227
    If it is a str, it is returned.
1406
1228
    If it is Unicode, it is encoded into a utf-8 string.
1407
1229
    """
1408
 
    if isinstance(unicode_or_utf8_string, bytes):
 
1230
    if isinstance(unicode_or_utf8_string, str):
1409
1231
        # TODO: jam 20070209 This is overkill, and probably has an impact on
1410
1232
        #       performance if we are dealing with lots of apis that want a
1411
1233
        #       utf-8 revision id
1418
1240
    return unicode_or_utf8_string.encode('utf-8')
1419
1241
 
1420
1242
 
1421
 
def safe_revision_id(unicode_or_utf8_string):
 
1243
_revision_id_warning = ('Unicode revision ids were deprecated in bzr 0.15.'
 
1244
                        ' Revision id generators should be creating utf8'
 
1245
                        ' revision ids.')
 
1246
 
 
1247
 
 
1248
def safe_revision_id(unicode_or_utf8_string, warn=True):
1422
1249
    """Revision ids should now be utf8, but at one point they were unicode.
1423
1250
 
1424
1251
    :param unicode_or_utf8_string: A possibly Unicode revision_id. (can also be
1425
1252
        utf8 or None).
 
1253
    :param warn: Functions that are sanitizing user data can set warn=False
1426
1254
    :return: None or a utf8 revision id.
1427
1255
    """
1428
1256
    if (unicode_or_utf8_string is None
1429
 
            or unicode_or_utf8_string.__class__ == bytes):
 
1257
        or unicode_or_utf8_string.__class__ == str):
1430
1258
        return unicode_or_utf8_string
1431
 
    raise TypeError('Unicode revision ids are no longer supported. '
1432
 
                    'Revision id generators should be creating utf8 revision '
1433
 
                    'ids.')
1434
 
 
1435
 
 
1436
 
def safe_file_id(unicode_or_utf8_string):
 
1259
    if warn:
 
1260
        symbol_versioning.warn(_revision_id_warning, DeprecationWarning,
 
1261
                               stacklevel=2)
 
1262
    return cache_utf8.encode(unicode_or_utf8_string)
 
1263
 
 
1264
 
 
1265
_file_id_warning = ('Unicode file ids were deprecated in bzr 0.15. File id'
 
1266
                    ' generators should be creating utf8 file ids.')
 
1267
 
 
1268
 
 
1269
def safe_file_id(unicode_or_utf8_string, warn=True):
1437
1270
    """File ids should now be utf8, but at one point they were unicode.
1438
1271
 
1439
1272
    This is the same as safe_utf8, except it uses the cached encode functions
1441
1274
 
1442
1275
    :param unicode_or_utf8_string: A possibly Unicode file_id. (can also be
1443
1276
        utf8 or None).
 
1277
    :param warn: Functions that are sanitizing user data can set warn=False
1444
1278
    :return: None or a utf8 file id.
1445
1279
    """
1446
1280
    if (unicode_or_utf8_string is None
1447
 
            or unicode_or_utf8_string.__class__ == bytes):
 
1281
        or unicode_or_utf8_string.__class__ == str):
1448
1282
        return unicode_or_utf8_string
1449
 
    raise TypeError('Unicode file ids are no longer supported. '
1450
 
                    'File id generators should be creating utf8 file ids.')
 
1283
    if warn:
 
1284
        symbol_versioning.warn(_file_id_warning, DeprecationWarning,
 
1285
                               stacklevel=2)
 
1286
    return cache_utf8.encode(unicode_or_utf8_string)
1451
1287
 
1452
1288
 
1453
1289
_platform_normalizes_filenames = False
1458
1294
def normalizes_filenames():
1459
1295
    """Return True if this platform normalizes unicode filenames.
1460
1296
 
1461
 
    Only Mac OSX.
 
1297
    Mac OSX does, Windows/Linux do not.
1462
1298
    """
1463
1299
    return _platform_normalizes_filenames
1464
1300
 
1469
1305
    On platforms where the system normalizes filenames (Mac OSX),
1470
1306
    you can access a file by any path which will normalize correctly.
1471
1307
    On platforms where the system does not normalize filenames
1472
 
    (everything else), you have to access a file by its exact path.
 
1308
    (Windows, Linux), you have to access a file by its exact path.
1473
1309
 
1474
1310
    Internally, bzr only supports NFC normalization, since that is
1475
1311
    the standard for XML documents.
1478
1314
    can be accessed by that path.
1479
1315
    """
1480
1316
 
1481
 
    if isinstance(path, bytes):
1482
 
        path = path.decode(sys.getfilesystemencoding())
1483
 
    return unicodedata.normalize('NFC', path), True
 
1317
    return unicodedata.normalize('NFC', unicode(path)), True
1484
1318
 
1485
1319
 
1486
1320
def _inaccessible_normalized_filename(path):
1487
1321
    __doc__ = _accessible_normalized_filename.__doc__
1488
1322
 
1489
 
    if isinstance(path, bytes):
1490
 
        path = path.decode(sys.getfilesystemencoding())
1491
 
    normalized = unicodedata.normalize('NFC', path)
 
1323
    normalized = unicodedata.normalize('NFC', unicode(path))
1492
1324
    return normalized, normalized == path
1493
1325
 
1494
1326
 
1498
1330
    normalized_filename = _inaccessible_normalized_filename
1499
1331
 
1500
1332
 
1501
 
def set_signal_handler(signum, handler, restart_syscall=True):
1502
 
    """A wrapper for signal.signal that also calls siginterrupt(signum, False)
1503
 
    on platforms that support that.
1504
 
 
1505
 
    :param restart_syscall: if set, allow syscalls interrupted by a signal to
1506
 
        automatically restart (by calling `signal.siginterrupt(signum,
1507
 
        False)`).  May be ignored if the feature is not available on this
1508
 
        platform or Python version.
1509
 
    """
1510
 
    try:
1511
 
        import signal
1512
 
        siginterrupt = signal.siginterrupt
1513
 
    except ImportError:
1514
 
        # This python implementation doesn't provide signal support, hence no
1515
 
        # handler exists
1516
 
        return None
1517
 
    except AttributeError:
1518
 
        # siginterrupt doesn't exist on this platform, or for this version
1519
 
        # of Python.
1520
 
        def siginterrupt(signum, flag): return None
1521
 
    if restart_syscall:
1522
 
        def sig_handler(*args):
1523
 
            # Python resets the siginterrupt flag when a signal is
1524
 
            # received.  <http://bugs.python.org/issue8354>
1525
 
            # As a workaround for some cases, set it back the way we want it.
1526
 
            siginterrupt(signum, False)
1527
 
            # Now run the handler function passed to set_signal_handler.
1528
 
            handler(*args)
1529
 
    else:
1530
 
        sig_handler = handler
1531
 
    old_handler = signal.signal(signum, sig_handler)
1532
 
    if restart_syscall:
1533
 
        siginterrupt(signum, False)
1534
 
    return old_handler
1535
 
 
1536
 
 
1537
 
default_terminal_width = 80
1538
 
"""The default terminal width for ttys.
1539
 
 
1540
 
This is defined so that higher levels can share a common fallback value when
1541
 
terminal_width() returns None.
1542
 
"""
1543
 
 
1544
 
# Keep some state so that terminal_width can detect if _terminal_size has
1545
 
# returned a different size since the process started.  See docstring and
1546
 
# comments of terminal_width for details.
1547
 
# _terminal_size_state has 3 possible values: no_data, unchanged, and changed.
1548
 
_terminal_size_state = 'no_data'
1549
 
_first_terminal_size = None
1550
 
 
1551
 
 
1552
1333
def terminal_width():
1553
 
    """Return terminal width.
1554
 
 
1555
 
    None is returned if the width can't established precisely.
1556
 
 
1557
 
    The rules are:
1558
 
    - if BRZ_COLUMNS is set, returns its value
1559
 
    - if there is no controlling terminal, returns None
1560
 
    - query the OS, if the queried size has changed since the last query,
1561
 
      return its value,
1562
 
    - if COLUMNS is set, returns its value,
1563
 
    - if the OS has a value (even though it's never changed), return its value.
1564
 
 
1565
 
    From there, we need to query the OS to get the size of the controlling
1566
 
    terminal.
1567
 
 
1568
 
    On Unices we query the OS by:
1569
 
    - get termios.TIOCGWINSZ
1570
 
    - if an error occurs or a negative value is obtained, returns None
1571
 
 
1572
 
    On Windows we query the OS by:
1573
 
    - win32utils.get_console_size() decides,
1574
 
    - returns None on error (provided default value)
1575
 
    """
1576
 
    # Note to implementors: if changing the rules for determining the width,
1577
 
    # make sure you've considered the behaviour in these cases:
1578
 
    #  - M-x shell in emacs, where $COLUMNS is set and TIOCGWINSZ returns 0,0.
1579
 
    #  - brz log | less, in bash, where $COLUMNS not set and TIOCGWINSZ returns
1580
 
    #    0,0.
1581
 
    #  - (add more interesting cases here, if you find any)
1582
 
    # Some programs implement "Use $COLUMNS (if set) until SIGWINCH occurs",
1583
 
    # but we don't want to register a signal handler because it is impossible
1584
 
    # to do so without risking EINTR errors in Python <= 2.6.5 (see
1585
 
    # <http://bugs.python.org/issue8354>).  Instead we check TIOCGWINSZ every
1586
 
    # time so we can notice if the reported size has changed, which should have
1587
 
    # a similar effect.
1588
 
 
1589
 
    # If BRZ_COLUMNS is set, take it, user is always right
1590
 
    # Except if they specified 0 in which case, impose no limit here
1591
 
    try:
1592
 
        width = int(os.environ['BRZ_COLUMNS'])
1593
 
    except (KeyError, ValueError):
1594
 
        width = None
1595
 
    if width is not None:
1596
 
        if width > 0:
1597
 
            return width
1598
 
        else:
1599
 
            return None
1600
 
 
1601
 
    isatty = getattr(sys.stdout, 'isatty', None)
1602
 
    if isatty is None or not isatty():
1603
 
        # Don't guess, setting BRZ_COLUMNS is the recommended way to override.
1604
 
        return None
1605
 
 
1606
 
    # Query the OS
1607
 
    width, height = os_size = _terminal_size(None, None)
1608
 
    global _first_terminal_size, _terminal_size_state
1609
 
    if _terminal_size_state == 'no_data':
1610
 
        _first_terminal_size = os_size
1611
 
        _terminal_size_state = 'unchanged'
1612
 
    elif (_terminal_size_state == 'unchanged' and
1613
 
          _first_terminal_size != os_size):
1614
 
        _terminal_size_state = 'changed'
1615
 
 
1616
 
    # If the OS claims to know how wide the terminal is, and this value has
1617
 
    # ever changed, use that.
1618
 
    if _terminal_size_state == 'changed':
1619
 
        if width is not None and width > 0:
1620
 
            return width
1621
 
 
1622
 
    # If COLUMNS is set, use it.
1623
 
    try:
1624
 
        return int(os.environ['COLUMNS'])
1625
 
    except (KeyError, ValueError):
1626
 
        pass
1627
 
 
1628
 
    # Finally, use an unchanged size from the OS, if we have one.
1629
 
    if _terminal_size_state == 'unchanged':
1630
 
        if width is not None and width > 0:
1631
 
            return width
1632
 
 
1633
 
    # The width could not be determined.
1634
 
    return None
1635
 
 
1636
 
 
1637
 
def _win32_terminal_size(width, height):
1638
 
    width, height = win32utils.get_console_size(
1639
 
        defaultx=width, defaulty=height)
1640
 
    return width, height
1641
 
 
1642
 
 
1643
 
def _ioctl_terminal_size(width, height):
1644
 
    try:
1645
 
        import struct
1646
 
        import fcntl
1647
 
        import termios
 
1334
    """Return estimated terminal width."""
 
1335
    if sys.platform == 'win32':
 
1336
        return win32utils.get_console_size()[0]
 
1337
    width = 0
 
1338
    try:
 
1339
        import struct, fcntl, termios
1648
1340
        s = struct.pack('HHHH', 0, 0, 0, 0)
1649
1341
        x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
1650
 
        height, width = struct.unpack('HHHH', x)[0:2]
1651
 
    except (IOError, AttributeError):
 
1342
        width = struct.unpack('HHHH', x)[1]
 
1343
    except IOError:
1652
1344
        pass
1653
 
    return width, height
1654
 
 
1655
 
 
1656
 
_terminal_size = None
1657
 
"""Returns the terminal size as (width, height).
1658
 
 
1659
 
:param width: Default value for width.
1660
 
:param height: Default value for height.
1661
 
 
1662
 
This is defined specifically for each OS and query the size of the controlling
1663
 
terminal. If any error occurs, the provided default values should be returned.
1664
 
"""
1665
 
if sys.platform == 'win32':
1666
 
    _terminal_size = _win32_terminal_size
1667
 
else:
1668
 
    _terminal_size = _ioctl_terminal_size
1669
 
 
1670
 
 
1671
 
def supports_executable(path):
1672
 
    """Return if filesystem at path supports executable bit.
1673
 
 
1674
 
    :param path: Path for which to check the file system
1675
 
    :return: boolean indicating whether executable bit can be stored/relied upon
1676
 
    """
1677
 
    if sys.platform == 'win32':
1678
 
        return False
1679
 
    try:
1680
 
        fs_type = get_fs_type(path)
1681
 
    except errors.DependencyNotPresent as e:
1682
 
        trace.mutter('Unable to get fs type for %r: %s', path, e)
1683
 
    else:
1684
 
        if fs_type in ('vfat', 'ntfs'):
1685
 
            # filesystems known to not support executable bit
1686
 
            return False
1687
 
    return True
1688
 
 
1689
 
 
1690
 
def supports_symlinks(path):
1691
 
    """Return if the filesystem at path supports the creation of symbolic links.
1692
 
 
1693
 
    """
1694
 
    if not has_symlinks():
1695
 
        return False
1696
 
    try:
1697
 
        fs_type = get_fs_type(path)
1698
 
    except errors.DependencyNotPresent as e:
1699
 
        trace.mutter('Unable to get fs type for %r: %s', path, e)
1700
 
    else:
1701
 
        if fs_type in ('vfat', 'ntfs'):
1702
 
            # filesystems known to not support symlinks
1703
 
            return False
1704
 
    return True
 
1345
    if width <= 0:
 
1346
        try:
 
1347
            width = int(os.environ['COLUMNS'])
 
1348
        except:
 
1349
            pass
 
1350
    if width <= 0:
 
1351
        width = 80
 
1352
 
 
1353
    return width
 
1354
 
 
1355
 
 
1356
def supports_executable():
 
1357
    return sys.platform != "win32"
1705
1358
 
1706
1359
 
1707
1360
def supports_posix_readonly():
1730
1383
        if orig_val is not None:
1731
1384
            del os.environ[env_variable]
1732
1385
    else:
1733
 
        if not PY3 and isinstance(value, text_type):
 
1386
        if isinstance(value, unicode):
1734
1387
            value = value.encode(get_user_encoding())
1735
1388
        os.environ[env_variable] = value
1736
1389
    return orig_val
1750
1403
        raise errors.IllegalPath(path)
1751
1404
 
1752
1405
 
1753
 
_WIN32_ERROR_DIRECTORY = 267  # Similar to errno.ENOTDIR
1754
 
 
 
1406
_WIN32_ERROR_DIRECTORY = 267 # Similar to errno.ENOTDIR
1755
1407
 
1756
1408
def _is_error_enotdir(e):
1757
1409
    """Check if this exception represents ENOTDIR.
1769
1421
    :return: True if this represents an ENOTDIR error. False otherwise.
1770
1422
    """
1771
1423
    en = getattr(e, 'errno', None)
1772
 
    if (en == errno.ENOTDIR or
1773
 
        (sys.platform == 'win32' and
1774
 
            (en == _WIN32_ERROR_DIRECTORY or
1775
 
             (en == errno.EINVAL
1776
 
              and getattr(e, 'winerror', None) == _WIN32_ERROR_DIRECTORY)
1777
 
             ))):
 
1424
    if (en == errno.ENOTDIR
 
1425
        or (sys.platform == 'win32'
 
1426
            and (en == _WIN32_ERROR_DIRECTORY
 
1427
                 or (en == errno.EINVAL
 
1428
                     and getattr(e, 'winerror', None) == _WIN32_ERROR_DIRECTORY)
 
1429
        ))):
1778
1430
        return True
1779
1431
    return False
1780
1432
 
1807
1459
        rooted higher up.
1808
1460
    :return: an iterator over the dirs.
1809
1461
    """
1810
 
    # TODO there is a bit of a smell where the results of the directory-
 
1462
    #TODO there is a bit of a smell where the results of the directory-
1811
1463
    # summary in this, and the path from the root, may not agree
1812
1464
    # depending on top and prefix - i.e. ./foo and foo as a pair leads to
1813
1465
    # potentially confusing output. We should make this more robust - but
1829
1481
        dirblock = []
1830
1482
        append = dirblock.append
1831
1483
        try:
1832
 
            names = sorted(map(decode_filename, _listdir(top)))
1833
 
        except OSError as e:
 
1484
            names = sorted(_listdir(top))
 
1485
        except OSError, e:
1834
1486
            if not _is_error_enotdir(e):
1835
1487
                raise
1836
1488
        else:
1889
1541
    """
1890
1542
    global _selected_dir_reader
1891
1543
    if _selected_dir_reader is None:
1892
 
        if sys.platform == "win32":
 
1544
        fs_encoding = _fs_enc.upper()
 
1545
        if sys.platform == "win32" and win32utils.winver == 'Windows NT':
 
1546
            # Win98 doesn't have unicode apis like FindFirstFileW
 
1547
            # TODO: We possibly could support Win98 by falling back to the
 
1548
            #       original FindFirstFile, and using TCHAR instead of WCHAR,
 
1549
            #       but that gets a bit tricky, and requires custom compiling
 
1550
            #       for win98 anyway.
1893
1551
            try:
1894
 
                from ._walkdirs_win32 import Win32ReadDir
 
1552
                from bzrlib._walkdirs_win32 import Win32ReadDir
1895
1553
                _selected_dir_reader = Win32ReadDir()
1896
1554
            except ImportError:
1897
1555
                pass
1898
 
        elif _fs_enc in ('utf-8', 'ascii'):
 
1556
        elif fs_encoding in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
 
1557
            # ANSI_X3.4-1968 is a form of ASCII
1899
1558
            try:
1900
 
                from ._readdir_pyx import UTF8DirReader
 
1559
                from bzrlib._readdir_pyx import UTF8DirReader
1901
1560
                _selected_dir_reader = UTF8DirReader()
1902
 
            except ImportError as e:
 
1561
            except ImportError, e:
1903
1562
                failed_to_load_extension(e)
1904
1563
                pass
1905
1564
 
1950
1609
        See DirReader.read_dir for details.
1951
1610
        """
1952
1611
        _utf8_encode = self._utf8_encode
1953
 
 
1954
 
        def _fs_decode(s): return s.decode(_fs_enc)
1955
 
 
1956
 
        def _fs_encode(s): return s.encode(_fs_enc)
1957
1612
        _lstat = os.lstat
1958
1613
        _listdir = os.listdir
1959
1614
        _kind_from_mode = file_kind_from_stat_mode
1960
1615
 
1961
1616
        if prefix:
1962
 
            relprefix = prefix + b'/'
 
1617
            relprefix = prefix + '/'
1963
1618
        else:
1964
 
            relprefix = b''
1965
 
        top_slash = top + '/'
 
1619
            relprefix = ''
 
1620
        top_slash = top + u'/'
1966
1621
 
1967
1622
        dirblock = []
1968
1623
        append = dirblock.append
1969
 
        for name_native in _listdir(top.encode('utf-8')):
 
1624
        for name in sorted(_listdir(top)):
1970
1625
            try:
1971
 
                name = _fs_decode(name_native)
 
1626
                name_utf8 = _utf8_encode(name)[0]
1972
1627
            except UnicodeDecodeError:
1973
1628
                raise errors.BadFilenameEncoding(
1974
 
                    relprefix + name_native, _fs_enc)
1975
 
            name_utf8 = _utf8_encode(name)[0]
 
1629
                    _utf8_encode(relprefix)[0] + name, _fs_enc)
1976
1630
            abspath = top_slash + name
1977
1631
            statvalue = _lstat(abspath)
1978
1632
            kind = _kind_from_mode(statvalue.st_mode)
1979
1633
            append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
1980
 
        return sorted(dirblock)
 
1634
        return dirblock
1981
1635
 
1982
1636
 
1983
1637
def copy_tree(from_path, to_path, handlers={}):
2008
1662
        link_to = os.readlink(source)
2009
1663
        os.symlink(link_to, dest)
2010
1664
 
2011
 
    real_handlers = {'file': shutil.copy2,
2012
 
                     'symlink': copy_link,
2013
 
                     'directory': copy_dir,
2014
 
                     }
 
1665
    real_handlers = {'file':shutil.copy2,
 
1666
                     'symlink':copy_link,
 
1667
                     'directory':copy_dir,
 
1668
                    }
2015
1669
    real_handlers.update(handlers)
2016
1670
 
2017
1671
    if not os.path.exists(to_path):
2022
1676
            real_handlers[kind](abspath, relpath)
2023
1677
 
2024
1678
 
2025
 
def copy_ownership_from_path(dst, src=None):
2026
 
    """Copy usr/grp ownership from src file/dir to dst file/dir.
2027
 
 
2028
 
    If src is None, the containing directory is used as source. If chown
2029
 
    fails, the error is ignored and a warning is printed.
2030
 
    """
2031
 
    chown = getattr(os, 'chown', None)
2032
 
    if chown is None:
2033
 
        return
2034
 
 
2035
 
    if src is None:
2036
 
        src = os.path.dirname(dst)
2037
 
        if src == '':
2038
 
            src = '.'
2039
 
 
2040
 
    try:
2041
 
        s = os.stat(src)
2042
 
        chown(dst, s.st_uid, s.st_gid)
2043
 
    except OSError:
2044
 
        trace.warning(
2045
 
            'Unable to copy ownership from "%s" to "%s". '
2046
 
            'You may want to set it manually.', src, dst)
2047
 
        trace.log_exception_quietly()
2048
 
 
2049
 
 
2050
1679
def path_prefix_key(path):
2051
1680
    """Generate a prefix-order path key for path.
2052
1681
 
2053
1682
    This can be used to sort paths in the same way that walkdirs does.
2054
1683
    """
2055
 
    return (dirname(path), path)
 
1684
    return (dirname(path) , path)
2056
1685
 
2057
1686
 
2058
1687
def compare_paths_prefix_order(path_a, path_b):
2059
1688
    """Compare path_a and path_b to generate the same order walkdirs uses."""
2060
1689
    key_a = path_prefix_key(path_a)
2061
1690
    key_b = path_prefix_key(path_b)
2062
 
    return (key_a > key_b) - (key_a < key_b)
 
1691
    return cmp(key_a, key_b)
2063
1692
 
2064
1693
 
2065
1694
_cached_user_encoding = None
2066
1695
 
2067
1696
 
2068
 
def get_user_encoding():
 
1697
def get_user_encoding(use_cache=True):
2069
1698
    """Find out what the preferred user encoding is.
2070
1699
 
2071
1700
    This is generally the encoding that is used for command line parameters
2072
1701
    and file contents. This may be different from the terminal encoding
2073
1702
    or the filesystem encoding.
2074
1703
 
 
1704
    :param  use_cache:  Enable cache for detected encoding.
 
1705
                        (This parameter is turned on by default,
 
1706
                        and required only for selftesting)
 
1707
 
2075
1708
    :return: A string defining the preferred user encoding
2076
1709
    """
2077
1710
    global _cached_user_encoding
2078
 
    if _cached_user_encoding is not None:
 
1711
    if _cached_user_encoding is not None and use_cache:
2079
1712
        return _cached_user_encoding
2080
1713
 
2081
 
    if os.name == 'posix' and getattr(locale, 'CODESET', None) is not None:
2082
 
        # Use the existing locale settings and call nl_langinfo directly
2083
 
        # rather than going through getpreferredencoding. This avoids
2084
 
        # <http://bugs.python.org/issue6202> on OSX Python 2.6 and the
2085
 
        # possibility of the setlocale call throwing an error.
2086
 
        user_encoding = locale.nl_langinfo(locale.CODESET)
 
1714
    if sys.platform == 'darwin':
 
1715
        # python locale.getpreferredencoding() always return
 
1716
        # 'mac-roman' on darwin. That's a lie.
 
1717
        sys.platform = 'posix'
 
1718
        try:
 
1719
            if os.environ.get('LANG', None) is None:
 
1720
                # If LANG is not set, we end up with 'ascii', which is bad
 
1721
                # ('mac-roman' is more than ascii), so we set a default which
 
1722
                # will give us UTF-8 (which appears to work in all cases on
 
1723
                # OSX). Users are still free to override LANG of course, as
 
1724
                # long as it give us something meaningful. This work-around
 
1725
                # *may* not be needed with python 3k and/or OSX 10.5, but will
 
1726
                # work with them too -- vila 20080908
 
1727
                os.environ['LANG'] = 'en_US.UTF-8'
 
1728
            import locale
 
1729
        finally:
 
1730
            sys.platform = 'darwin'
2087
1731
    else:
2088
 
        # GZ 2011-12-19: On windows could call GetACP directly instead.
2089
 
        user_encoding = locale.getpreferredencoding(False)
 
1732
        import locale
2090
1733
 
2091
1734
    try:
2092
 
        user_encoding = codecs.lookup(user_encoding).name
2093
 
    except LookupError:
2094
 
        if user_encoding not in ("", "cp0"):
2095
 
            sys.stderr.write('brz: warning:'
 
1735
        user_encoding = locale.getpreferredencoding()
 
1736
    except locale.Error, e:
 
1737
        sys.stderr.write('bzr: warning: %s\n'
 
1738
                         '  Could not determine what text encoding to use.\n'
 
1739
                         '  This error usually means your Python interpreter\n'
 
1740
                         '  doesn\'t support the locale set by $LANG (%s)\n'
 
1741
                         "  Continuing with ascii encoding.\n"
 
1742
                         % (e, os.environ.get('LANG')))
 
1743
        user_encoding = 'ascii'
 
1744
 
 
1745
    # Windows returns 'cp0' to indicate there is no code page. So we'll just
 
1746
    # treat that as ASCII, and not support printing unicode characters to the
 
1747
    # console.
 
1748
    #
 
1749
    # For python scripts run under vim, we get '', so also treat that as ASCII
 
1750
    if user_encoding in (None, 'cp0', ''):
 
1751
        user_encoding = 'ascii'
 
1752
    else:
 
1753
        # check encoding
 
1754
        try:
 
1755
            codecs.lookup(user_encoding)
 
1756
        except LookupError:
 
1757
            sys.stderr.write('bzr: warning:'
2096
1758
                             ' unknown encoding %s.'
2097
1759
                             ' Continuing with ascii encoding.\n'
2098
1760
                             % user_encoding
2099
 
                             )
2100
 
        user_encoding = 'ascii'
2101
 
    else:
2102
 
        # Get 'ascii' when setlocale has not been called or LANG=C or unset.
2103
 
        if user_encoding == 'ascii':
2104
 
            if sys.platform == 'darwin':
2105
 
                # OSX is special-cased in Python to have a UTF-8 filesystem
2106
 
                # encoding and previously had LANG set here if not present.
2107
 
                user_encoding = 'utf-8'
2108
 
            # GZ 2011-12-19: Maybe UTF-8 should be the default in this case
2109
 
            #                for some other posix platforms as well.
2110
 
 
2111
 
    _cached_user_encoding = user_encoding
 
1761
                            )
 
1762
            user_encoding = 'ascii'
 
1763
 
 
1764
    if use_cache:
 
1765
        _cached_user_encoding = user_encoding
 
1766
 
2112
1767
    return user_encoding
2113
1768
 
2114
1769
 
2115
 
def get_diff_header_encoding():
2116
 
    return get_terminal_encoding()
2117
 
 
2118
 
 
2119
1770
def get_host_name():
2120
1771
    """Return the current unicode host name.
2121
1772
 
2123
1774
    behaves inconsistently on different platforms.
2124
1775
    """
2125
1776
    if sys.platform == "win32":
 
1777
        import win32utils
2126
1778
        return win32utils.get_host_name()
2127
1779
    else:
2128
1780
        import socket
2129
 
        if PY3:
2130
 
            return socket.gethostname()
2131
1781
        return socket.gethostname().decode(get_user_encoding())
2132
1782
 
2133
1783
 
2134
 
# We must not read/write any more than 64k at a time from/to a socket so we
2135
 
# don't risk "no buffer space available" errors on some platforms.  Windows in
2136
 
# particular is likely to throw WSAECONNABORTED or WSAENOBUFS if given too much
2137
 
# data at once.
2138
 
MAX_SOCKET_CHUNK = 64 * 1024
2139
 
 
2140
 
_end_of_stream_errors = [errno.ECONNRESET, errno.EPIPE, errno.EINVAL]
2141
 
for _eno in ['WSAECONNRESET', 'WSAECONNABORTED']:
2142
 
    _eno = getattr(errno, _eno, None)
2143
 
    if _eno is not None:
2144
 
        _end_of_stream_errors.append(_eno)
2145
 
del _eno
2146
 
 
2147
 
 
2148
 
def read_bytes_from_socket(sock, report_activity=None,
2149
 
                           max_read_size=MAX_SOCKET_CHUNK):
2150
 
    """Read up to max_read_size of bytes from sock and notify of progress.
2151
 
 
2152
 
    Translates "Connection reset by peer" into file-like EOF (return an
2153
 
    empty string rather than raise an error), and repeats the recv if
2154
 
    interrupted by a signal.
2155
 
    """
2156
 
    while True:
2157
 
        try:
2158
 
            data = sock.recv(max_read_size)
2159
 
        except socket.error as e:
2160
 
            eno = e.args[0]
2161
 
            if eno in _end_of_stream_errors:
2162
 
                # The connection was closed by the other side.  Callers expect
2163
 
                # an empty string to signal end-of-stream.
2164
 
                return b""
2165
 
            elif eno == errno.EINTR:
2166
 
                # Retry the interrupted recv.
2167
 
                continue
2168
 
            raise
2169
 
        else:
2170
 
            if report_activity is not None:
2171
 
                report_activity(len(data), 'read')
2172
 
            return data
2173
 
 
2174
 
 
2175
 
def recv_all(socket, count):
 
1784
def recv_all(socket, bytes):
2176
1785
    """Receive an exact number of bytes.
2177
1786
 
2178
1787
    Regular Socket.recv() may return less than the requested number of bytes,
2179
 
    depending on what's in the OS buffer.  MSG_WAITALL is not available
 
1788
    dependning on what's in the OS buffer.  MSG_WAITALL is not available
2180
1789
    on all platforms, but this should work everywhere.  This will return
2181
1790
    less than the requested amount if the remote end closes.
2182
1791
 
2183
1792
    This isn't optimized and is intended mostly for use in testing.
2184
1793
    """
2185
 
    b = b''
2186
 
    while len(b) < count:
2187
 
        new = read_bytes_from_socket(socket, None, count - len(b))
2188
 
        if new == b'':
2189
 
            break  # eof
 
1794
    b = ''
 
1795
    while len(b) < bytes:
 
1796
        new = until_no_eintr(socket.recv, bytes - len(b))
 
1797
        if new == '':
 
1798
            break # eof
2190
1799
        b += new
2191
1800
    return b
2192
1801
 
2193
1802
 
2194
 
def send_all(sock, bytes, report_activity=None):
 
1803
def send_all(socket, bytes, report_activity=None):
2195
1804
    """Send all bytes on a socket.
2196
1805
 
2197
 
    Breaks large blocks in smaller chunks to avoid buffering limitations on
2198
 
    some platforms, and catches EINTR which may be thrown if the send is
2199
 
    interrupted by a signal.
2200
 
 
2201
 
    This is preferred to socket.sendall(), because it avoids portability bugs
2202
 
    and provides activity reporting.
 
1806
    Regular socket.sendall() can give socket error 10053 on Windows.  This
 
1807
    implementation sends no more than 64k at a time, which avoids this problem.
2203
1808
 
2204
1809
    :param report_activity: Call this as bytes are read, see
2205
1810
        Transport._report_activity
2206
1811
    """
2207
 
    sent_total = 0
2208
 
    byte_count = len(bytes)
2209
 
    view = memoryview(bytes)
2210
 
    while sent_total < byte_count:
2211
 
        try:
2212
 
            sent = sock.send(view[sent_total:sent_total + MAX_SOCKET_CHUNK])
2213
 
        except (socket.error, IOError) as e:
2214
 
            if e.args[0] in _end_of_stream_errors:
2215
 
                raise errors.ConnectionReset(
2216
 
                    "Error trying to write to socket", e)
2217
 
            if e.args[0] != errno.EINTR:
2218
 
                raise
2219
 
        else:
2220
 
            if sent == 0:
2221
 
                raise errors.ConnectionReset('Sending to %s returned 0 bytes'
2222
 
                                             % (sock,))
2223
 
            sent_total += sent
2224
 
            if report_activity is not None:
2225
 
                report_activity(sent, 'write')
2226
 
 
2227
 
 
2228
 
def connect_socket(address):
2229
 
    # Slight variation of the socket.create_connection() function (provided by
2230
 
    # python-2.6) that can fail if getaddrinfo returns an empty list. We also
2231
 
    # provide it for previous python versions. Also, we don't use the timeout
2232
 
    # parameter (provided by the python implementation) so we don't implement
2233
 
    # it either).
2234
 
    err = socket.error('getaddrinfo returns an empty list')
2235
 
    host, port = address
2236
 
    for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
2237
 
        af, socktype, proto, canonname, sa = res
2238
 
        sock = None
2239
 
        try:
2240
 
            sock = socket.socket(af, socktype, proto)
2241
 
            sock.connect(sa)
2242
 
            return sock
2243
 
 
2244
 
        except socket.error as e:
2245
 
            err = e
2246
 
            # 'err' is now the most recent error
2247
 
            if sock is not None:
2248
 
                sock.close()
2249
 
    raise err
 
1812
    chunk_size = 2**16
 
1813
    for pos in xrange(0, len(bytes), chunk_size):
 
1814
        block = bytes[pos:pos+chunk_size]
 
1815
        if report_activity is not None:
 
1816
            report_activity(len(block), 'write')
 
1817
        until_no_eintr(socket.sendall, block)
2250
1818
 
2251
1819
 
2252
1820
def dereference_path(path):
2271
1839
def resource_string(package, resource_name):
2272
1840
    """Load a resource from a package and return it as a string.
2273
1841
 
2274
 
    Note: Only packages that start with breezy are currently supported.
 
1842
    Note: Only packages that start with bzrlib are currently supported.
2275
1843
 
2276
1844
    This is designed to be a lightweight implementation of resource
2277
1845
    loading in a way which is API compatible with the same API from
2280
1848
    If and when pkg_resources becomes a standard library, this routine
2281
1849
    can delegate to it.
2282
1850
    """
2283
 
    # Check package name is within breezy
2284
 
    if package == "breezy":
 
1851
    # Check package name is within bzrlib
 
1852
    if package == "bzrlib":
2285
1853
        resource_relpath = resource_name
2286
 
    elif package.startswith("breezy."):
2287
 
        package = package[len("breezy."):].replace('.', os.sep)
 
1854
    elif package.startswith("bzrlib."):
 
1855
        package = package[len("bzrlib."):].replace('.', os.sep)
2288
1856
        resource_relpath = pathjoin(package, resource_name)
2289
1857
    else:
2290
 
        raise errors.BzrError('resource package %s not in breezy' % package)
 
1858
        raise errors.BzrError('resource package %s not in bzrlib' % package)
2291
1859
 
2292
1860
    # Map the resource to a file and read its contents
2293
 
    base = dirname(breezy.__file__)
 
1861
    base = dirname(bzrlib.__file__)
2294
1862
    if getattr(sys, 'frozen', None):    # bzr.exe
2295
1863
        base = abspath(pathjoin(base, '..', '..'))
2296
 
    with open(pathjoin(base, resource_relpath), "rt") as f:
2297
 
        return f.read()
 
1864
    filename = pathjoin(base, resource_relpath)
 
1865
    return open(filename, 'rU').read()
2298
1866
 
2299
1867
 
2300
1868
def file_kind_from_stat_mode_thunk(mode):
2301
1869
    global file_kind_from_stat_mode
2302
1870
    if file_kind_from_stat_mode is file_kind_from_stat_mode_thunk:
2303
1871
        try:
2304
 
            from ._readdir_pyx import UTF8DirReader
 
1872
            from bzrlib._readdir_pyx import UTF8DirReader
2305
1873
            file_kind_from_stat_mode = UTF8DirReader().kind_from_mode
2306
 
        except ImportError:
 
1874
        except ImportError, e:
2307
1875
            # This is one time where we won't warn that an extension failed to
2308
1876
            # load. The extension is never available on Windows anyway.
2309
 
            from ._readdir_py import (
 
1877
            from bzrlib._readdir_py import (
2310
1878
                _kind_from_mode as file_kind_from_stat_mode
2311
1879
                )
2312
1880
    return file_kind_from_stat_mode(mode)
2313
 
 
2314
 
 
2315
1881
file_kind_from_stat_mode = file_kind_from_stat_mode_thunk
2316
1882
 
2317
1883
 
2318
 
def file_stat(f, _lstat=os.lstat):
 
1884
def file_kind(f, _lstat=os.lstat):
2319
1885
    try:
2320
 
        # XXX cache?
2321
 
        return _lstat(f)
2322
 
    except OSError as e:
 
1886
        return file_kind_from_stat_mode(_lstat(f).st_mode)
 
1887
    except OSError, e:
2323
1888
        if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
2324
1889
            raise errors.NoSuchFile(f)
2325
1890
        raise
2326
1891
 
2327
1892
 
2328
 
def file_kind(f, _lstat=os.lstat):
2329
 
    stat_value = file_stat(f, _lstat)
2330
 
    return file_kind_from_stat_mode(stat_value.st_mode)
2331
 
 
2332
 
 
2333
1893
def until_no_eintr(f, *a, **kw):
2334
 
    """Run f(*a, **kw), retrying if an EINTR error occurs.
2335
 
 
2336
 
    WARNING: you must be certain that it is safe to retry the call repeatedly
2337
 
    if EINTR does occur.  This is typically only true for low-level operations
2338
 
    like os.read.  If in any doubt, don't use this.
2339
 
 
2340
 
    Keep in mind that this is not a complete solution to EINTR.  There is
2341
 
    probably code in the Python standard library and other dependencies that
2342
 
    may encounter EINTR if a signal arrives (and there is signal handler for
2343
 
    that signal).  So this function can reduce the impact for IO that breezy
2344
 
    directly controls, but it is not a complete solution.
2345
 
    """
 
1894
    """Run f(*a, **kw), retrying if an EINTR error occurs."""
2346
1895
    # Borrowed from Twisted's twisted.python.util.untilConcludes function.
2347
1896
    while True:
2348
1897
        try:
2349
1898
            return f(*a, **kw)
2350
 
        except (IOError, OSError) as e:
 
1899
        except (IOError, OSError), e:
2351
1900
            if e.errno == errno.EINTR:
2352
1901
                continue
2353
1902
            raise
2354
1903
 
 
1904
def re_compile_checked(re_string, flags=0, where=""):
 
1905
    """Return a compiled re, or raise a sensible error.
 
1906
 
 
1907
    This should only be used when compiling user-supplied REs.
 
1908
 
 
1909
    :param re_string: Text form of regular expression.
 
1910
    :param flags: eg re.IGNORECASE
 
1911
    :param where: Message explaining to the user the context where
 
1912
        it occurred, eg 'log search filter'.
 
1913
    """
 
1914
    # from https://bugs.launchpad.net/bzr/+bug/251352
 
1915
    try:
 
1916
        re_obj = re.compile(re_string, flags)
 
1917
        re_obj.search("")
 
1918
        return re_obj
 
1919
    except re.error, e:
 
1920
        if where:
 
1921
            where = ' in ' + where
 
1922
        # despite the name 'error' is a type
 
1923
        raise errors.BzrCommandError('Invalid regular expression%s: %r: %s'
 
1924
            % (where, re_string, e))
 
1925
 
2355
1926
 
2356
1927
if sys.platform == "win32":
 
1928
    import msvcrt
2357
1929
    def getchar():
2358
 
        import msvcrt
2359
1930
        return msvcrt.getch()
2360
1931
else:
 
1932
    import tty
 
1933
    import termios
2361
1934
    def getchar():
2362
 
        import tty
2363
 
        import termios
2364
1935
        fd = sys.stdin.fileno()
2365
1936
        settings = termios.tcgetattr(fd)
2366
1937
        try:
2370
1941
            termios.tcsetattr(fd, termios.TCSADRAIN, settings)
2371
1942
        return ch
2372
1943
 
2373
 
if sys.platform.startswith('linux'):
 
1944
 
 
1945
if sys.platform == 'linux2':
2374
1946
    def _local_concurrency():
2375
 
        try:
2376
 
            return os.sysconf('SC_NPROCESSORS_ONLN')
2377
 
        except (ValueError, OSError, AttributeError):
2378
 
            return None
 
1947
        concurrency = None
 
1948
        prefix = 'processor'
 
1949
        for line in file('/proc/cpuinfo', 'rb'):
 
1950
            if line.startswith(prefix):
 
1951
                concurrency = int(line[line.find(':')+1:]) + 1
 
1952
        return concurrency
2379
1953
elif sys.platform == 'darwin':
2380
1954
    def _local_concurrency():
2381
1955
        return subprocess.Popen(['sysctl', '-n', 'hw.availcpu'],
2382
1956
                                stdout=subprocess.PIPE).communicate()[0]
2383
 
elif "bsd" in sys.platform:
 
1957
elif sys.platform[0:7] == 'freebsd':
2384
1958
    def _local_concurrency():
2385
1959
        return subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
2386
1960
                                stdout=subprocess.PIPE).communicate()[0]
2387
1961
elif sys.platform == 'sunos5':
2388
1962
    def _local_concurrency():
2389
 
        return subprocess.Popen(['psrinfo', '-p', ],
 
1963
        return subprocess.Popen(['psrinfo', '-p',],
2390
1964
                                stdout=subprocess.PIPE).communicate()[0]
2391
1965
elif sys.platform == "win32":
2392
1966
    def _local_concurrency():
2400
1974
 
2401
1975
_cached_local_concurrency = None
2402
1976
 
2403
 
 
2404
1977
def local_concurrency(use_cache=True):
2405
1978
    """Return how many processes can be run concurrently.
2406
1979
 
2412
1985
    if _cached_local_concurrency is not None and use_cache:
2413
1986
        return _cached_local_concurrency
2414
1987
 
2415
 
    concurrency = os.environ.get('BRZ_CONCURRENCY', None)
 
1988
    concurrency = os.environ.get('BZR_CONCURRENCY', None)
2416
1989
    if concurrency is None:
2417
 
        import multiprocessing
2418
1990
        try:
2419
 
            concurrency = multiprocessing.cpu_count()
2420
 
        except NotImplementedError:
2421
 
            # multiprocessing.cpu_count() isn't implemented on all platforms
2422
 
            try:
2423
 
                concurrency = _local_concurrency()
2424
 
            except (OSError, IOError):
2425
 
                pass
 
1991
            concurrency = _local_concurrency()
 
1992
        except (OSError, IOError):
 
1993
            pass
2426
1994
    try:
2427
1995
        concurrency = int(concurrency)
2428
1996
    except (TypeError, ValueError):
2429
1997
        concurrency = 1
2430
1998
    if use_cache:
2431
 
        _cached_local_concurrency = concurrency
 
1999
        _cached_concurrency = concurrency
2432
2000
    return concurrency
2433
 
 
2434
 
 
2435
 
class UnicodeOrBytesToBytesWriter(codecs.StreamWriter):
2436
 
    """A stream writer that doesn't decode str arguments."""
2437
 
 
2438
 
    def __init__(self, encode, stream, errors='strict'):
2439
 
        codecs.StreamWriter.__init__(self, stream, errors)
2440
 
        self.encode = encode
2441
 
 
2442
 
    def write(self, object):
2443
 
        if isinstance(object, str):
2444
 
            self.stream.write(object)
2445
 
        else:
2446
 
            data, _ = self.encode(object, self.errors)
2447
 
            self.stream.write(data)
2448
 
 
2449
 
 
2450
 
if sys.platform == 'win32':
2451
 
    def open_file(filename, mode='r', bufsize=-1):
2452
 
        """This function is used to override the ``open`` builtin.
2453
 
 
2454
 
        But it uses O_NOINHERIT flag so the file handle is not inherited by
2455
 
        child processes.  Deleting or renaming a closed file opened with this
2456
 
        function is not blocking child processes.
2457
 
        """
2458
 
        writing = 'w' in mode
2459
 
        appending = 'a' in mode
2460
 
        updating = '+' in mode
2461
 
        binary = 'b' in mode
2462
 
 
2463
 
        flags = O_NOINHERIT
2464
 
        # see http://msdn.microsoft.com/en-us/library/yeby3zcb%28VS.71%29.aspx
2465
 
        # for flags for each modes.
2466
 
        if binary:
2467
 
            flags |= O_BINARY
2468
 
        else:
2469
 
            flags |= O_TEXT
2470
 
 
2471
 
        if writing:
2472
 
            if updating:
2473
 
                flags |= os.O_RDWR
2474
 
            else:
2475
 
                flags |= os.O_WRONLY
2476
 
            flags |= os.O_CREAT | os.O_TRUNC
2477
 
        elif appending:
2478
 
            if updating:
2479
 
                flags |= os.O_RDWR
2480
 
            else:
2481
 
                flags |= os.O_WRONLY
2482
 
            flags |= os.O_CREAT | os.O_APPEND
2483
 
        else:  # reading
2484
 
            if updating:
2485
 
                flags |= os.O_RDWR
2486
 
            else:
2487
 
                flags |= os.O_RDONLY
2488
 
 
2489
 
        return os.fdopen(os.open(filename, flags), mode, bufsize)
2490
 
else:
2491
 
    open_file = open
2492
 
 
2493
 
 
2494
 
def available_backup_name(base, exists):
2495
 
    """Find a non-existing backup file name.
2496
 
 
2497
 
    This will *not* create anything, this only return a 'free' entry.  This
2498
 
    should be used for checking names in a directory below a locked
2499
 
    tree/branch/repo to avoid race conditions. This is LBYL (Look Before You
2500
 
    Leap) and generally discouraged.
2501
 
 
2502
 
    :param base: The base name.
2503
 
 
2504
 
    :param exists: A callable returning True if the path parameter exists.
2505
 
    """
2506
 
    counter = 1
2507
 
    name = "%s.~%d~" % (base, counter)
2508
 
    while exists(name):
2509
 
        counter += 1
2510
 
        name = "%s.~%d~" % (base, counter)
2511
 
    return name
2512
 
 
2513
 
 
2514
 
def set_fd_cloexec(fd):
2515
 
    """Set a Unix file descriptor's FD_CLOEXEC flag.  Do nothing if platform
2516
 
    support for this is not available.
2517
 
    """
2518
 
    try:
2519
 
        import fcntl
2520
 
        old = fcntl.fcntl(fd, fcntl.F_GETFD)
2521
 
        fcntl.fcntl(fd, fcntl.F_SETFD, old | fcntl.FD_CLOEXEC)
2522
 
    except (ImportError, AttributeError):
2523
 
        # Either the fcntl module or specific constants are not present
2524
 
        pass
2525
 
 
2526
 
 
2527
 
def find_executable_on_path(name):
2528
 
    """Finds an executable on the PATH.
2529
 
 
2530
 
    On Windows, this will try to append each extension in the PATHEXT
2531
 
    environment variable to the name, if it cannot be found with the name
2532
 
    as given.
2533
 
 
2534
 
    :param name: The base name of the executable.
2535
 
    :return: The path to the executable found or None.
2536
 
    """
2537
 
    if sys.platform == 'win32':
2538
 
        exts = os.environ.get('PATHEXT', '').split(os.pathsep)
2539
 
        exts = [ext.lower() for ext in exts]
2540
 
        base, ext = os.path.splitext(name)
2541
 
        if ext != '':
2542
 
            if ext.lower() not in exts:
2543
 
                return None
2544
 
            name = base
2545
 
            exts = [ext]
2546
 
    else:
2547
 
        exts = ['']
2548
 
    path = os.environ.get('PATH')
2549
 
    if path is not None:
2550
 
        path = path.split(os.pathsep)
2551
 
        for ext in exts:
2552
 
            for d in path:
2553
 
                f = os.path.join(d, name) + ext
2554
 
                if os.access(f, os.X_OK):
2555
 
                    return f
2556
 
    if sys.platform == 'win32':
2557
 
        app_path = win32utils.get_app_path(name)
2558
 
        if app_path != name:
2559
 
            return app_path
2560
 
    return None
2561
 
 
2562
 
 
2563
 
def _posix_is_local_pid_dead(pid):
2564
 
    """True if pid doesn't correspond to live process on this machine"""
2565
 
    try:
2566
 
        # Special meaning of unix kill: just check if it's there.
2567
 
        os.kill(pid, 0)
2568
 
    except OSError as e:
2569
 
        if e.errno == errno.ESRCH:
2570
 
            # On this machine, and really not found: as sure as we can be
2571
 
            # that it's dead.
2572
 
            return True
2573
 
        elif e.errno == errno.EPERM:
2574
 
            # exists, though not ours
2575
 
            return False
2576
 
        else:
2577
 
            trace.mutter("os.kill(%d, 0) failed: %s" % (pid, e))
2578
 
            # Don't really know.
2579
 
            return False
2580
 
    else:
2581
 
        # Exists and our process: not dead.
2582
 
        return False
2583
 
 
2584
 
 
2585
 
if sys.platform == "win32":
2586
 
    is_local_pid_dead = win32utils.is_local_pid_dead
2587
 
else:
2588
 
    is_local_pid_dead = _posix_is_local_pid_dead
2589
 
 
2590
 
_maybe_ignored = ['EAGAIN', 'EINTR', 'ENOTSUP', 'EOPNOTSUPP', 'EACCES']
2591
 
_fdatasync_ignored = [getattr(errno, name) for name in _maybe_ignored
2592
 
                      if getattr(errno, name, None) is not None]
2593
 
 
2594
 
 
2595
 
def fdatasync(fileno):
2596
 
    """Flush file contents to disk if possible.
2597
 
 
2598
 
    :param fileno: Integer OS file handle.
2599
 
    :raises TransportNotPossible: If flushing to disk is not possible.
2600
 
    """
2601
 
    fn = getattr(os, 'fdatasync', getattr(os, 'fsync', None))
2602
 
    if fn is not None:
2603
 
        try:
2604
 
            fn(fileno)
2605
 
        except IOError as e:
2606
 
            # See bug #1075108, on some platforms fdatasync exists, but can
2607
 
            # raise ENOTSUP. However, we are calling fdatasync to be helpful
2608
 
            # and reduce the chance of corruption-on-powerloss situations. It
2609
 
            # is not a mandatory call, so it is ok to suppress failures.
2610
 
            trace.mutter("ignoring error calling fdatasync: %s" % (e,))
2611
 
            if getattr(e, 'errno', None) not in _fdatasync_ignored:
2612
 
                raise
2613
 
 
2614
 
 
2615
 
def ensure_empty_directory_exists(path, exception_class):
2616
 
    """Make sure a local directory exists and is empty.
2617
 
 
2618
 
    If it does not exist, it is created.  If it exists and is not empty, an
2619
 
    instance of exception_class is raised.
2620
 
    """
2621
 
    try:
2622
 
        os.mkdir(path)
2623
 
    except OSError as e:
2624
 
        if e.errno != errno.EEXIST:
2625
 
            raise
2626
 
        if os.listdir(path) != []:
2627
 
            raise exception_class(path)
2628
 
 
2629
 
 
2630
 
def is_environment_error(evalue):
2631
 
    """True if exception instance is due to a process environment issue
2632
 
 
2633
 
    This includes OSError and IOError, but also other errors that come from
2634
 
    the operating system or core libraries but are not subclasses of those.
2635
 
    """
2636
 
    if isinstance(evalue, (EnvironmentError, select.error)):
2637
 
        return True
2638
 
    if sys.platform == "win32" and win32utils._is_pywintypes_error(evalue):
2639
 
        return True
2640
 
    return False
2641
 
 
2642
 
 
2643
 
def read_mtab(path):
2644
 
    """Read an fstab-style file and extract mountpoint+filesystem information.
2645
 
 
2646
 
    :param path: Path to read from
2647
 
    :yield: Tuples with mountpoints (as bytestrings) and filesystem names
2648
 
    """
2649
 
    with open(path, 'rb') as f:
2650
 
        for line in f:
2651
 
            if line.startswith(b'#'):
2652
 
                continue
2653
 
            cols = line.split()
2654
 
            if len(cols) < 3:
2655
 
                continue
2656
 
            yield cols[1], cols[2].decode('ascii', 'replace')
2657
 
 
2658
 
 
2659
 
MTAB_PATH = '/etc/mtab'
2660
 
 
2661
 
class FilesystemFinder(object):
2662
 
    """Find the filesystem for a particular path."""
2663
 
 
2664
 
    def __init__(self, mountpoints):
2665
 
        def key(x):
2666
 
            return len(x[0])
2667
 
        self._mountpoints = sorted(mountpoints, key=key, reverse=True)
2668
 
 
2669
 
    @classmethod
2670
 
    def from_mtab(cls):
2671
 
        """Create a FilesystemFinder from an mtab-style file.
2672
 
 
2673
 
        Note that this will silenty ignore mtab if it doesn't exist or can not
2674
 
        be opened.
2675
 
        """
2676
 
        # TODO(jelmer): Use inotify to be notified when /etc/mtab changes and
2677
 
        # we need to re-read it.
2678
 
        try:
2679
 
            return cls(read_mtab(MTAB_PATH))
2680
 
        except EnvironmentError as e:
2681
 
            trace.mutter('Unable to read mtab: %s', e)
2682
 
            return cls([])
2683
 
 
2684
 
    def find(self, path):
2685
 
        """Find the filesystem used by a particular path.
2686
 
 
2687
 
        :param path: Path to find (bytestring or text type)
2688
 
        :return: Filesystem name (as text type) or None, if the filesystem is
2689
 
            unknown.
2690
 
        """
2691
 
        for mountpoint, filesystem in self._mountpoints:
2692
 
            if is_inside(mountpoint, path):
2693
 
                return filesystem
2694
 
        return None
2695
 
 
2696
 
 
2697
 
_FILESYSTEM_FINDER = None
2698
 
 
2699
 
 
2700
 
def get_fs_type(path):
2701
 
    """Return the filesystem type for the partition a path is in.
2702
 
 
2703
 
    :param path: Path to search filesystem type for
2704
 
    :return: A FS type, as string. E.g. "ext2"
2705
 
    """
2706
 
    global _FILESYSTEM_FINDER
2707
 
    if _FILESYSTEM_FINDER is None:
2708
 
        _FILESYSTEM_FINDER = FilesystemFinder.from_mtab()
2709
 
 
2710
 
    if not isinstance(path, bytes):
2711
 
        path = path.encode(_fs_enc)
2712
 
 
2713
 
    return _FILESYSTEM_FINDER.find(path)
2714
 
 
2715
 
 
2716
 
if PY3:
2717
 
    perf_counter = time.perf_counter
2718
 
else:
2719
 
    perf_counter = time.clock