~bzr-pqm/bzr/bzr.dev

4183.6.4 by Martin Pool
Separate out re_compile_checked
1
# Copyright (C) 2005, 2006, 2007, 2009 Canonical Ltd
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
2
#
1 by mbp at sourcefrog
import from baz patch-364
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
7
#
1 by mbp at sourcefrog
import from baz patch-364
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
12
#
1 by mbp at sourcefrog
import from baz patch-364
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1 by mbp at sourcefrog
import from baz patch-364
16
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
17
import os
18
import re
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)
22
import sys
23
import time
4574.3.2 by Martin Pool
Change back to python warnings for failure to load extensions
24
import warnings
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
25
26
from bzrlib.lazy_import import lazy_import
27
lazy_import(globals(), """
2192.1.1 by Alexander Belchenko
Before actually using encoding need to check that Python has corresponding codec
28
import codecs
2215.6.1 by James Henstridge
Don't rely on time.timezone and time.altzone in local_time_offset(),
29
from datetime import datetime
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
30
import errno
1711.4.5 by John Arbash Meinel
the _posix_* routines should use posixpath not os.path, so tests pass on win32
31
from ntpath import (abspath as _nt_abspath,
32
                    join as _nt_join,
33
                    normpath as _nt_normpath,
34
                    realpath as _nt_realpath,
1711.5.2 by John Arbash Meinel
win32 likes to return lowercase drive letters sometimes, and uppercase at other times. normalize this
35
                    splitdrive as _nt_splitdrive,
1711.4.5 by John Arbash Meinel
the _posix_* routines should use posixpath not os.path, so tests pass on win32
36
                    )
37
import posixpath
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
38
import shutil
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
39
from shutil import (
40
    rmtree,
41
    )
4398.4.3 by Vincent Ladeuil
Detect # cores on win32 and Solaris too.
42
import subprocess
1185.31.40 by John Arbash Meinel
Added osutils.mkdtemp()
43
import tempfile
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
44
from tempfile import (
45
    mkdtemp,
46
    )
1185.85.75 by John Arbash Meinel
Adding bzrlib.osutils.unicode_filename to handle unicode normalization for file paths.
47
import unicodedata
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
48
49
from bzrlib import (
2249.5.16 by John Arbash Meinel
[merge] bzr.dev 2283
50
    cache_utf8,
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
51
    errors,
2245.4.6 by Alexander Belchenko
osutils.py: terminal_width() now use win32utils.get_console_size()
52
    win32utils,
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
53
    )
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
54
""")
1 by mbp at sourcefrog
import from baz patch-364
55
3734.2.4 by Vincent Ladeuil
Fix python2.6 deprecation warnings related to hashlib.
56
# sha and md5 modules are deprecated in python2.6 but hashlib is available as
57
# of 2.5
2929.3.1 by Vincent Ladeuil
Fix python2.6 deprecation warnings (still 4 failures 5 errors in test suite).
58
if sys.version_info < (2, 5):
3734.5.2 by Vincent Ladeuil
Martin's review feedback.
59
    import md5 as _mod_md5
60
    md5 = _mod_md5.new
61
    import sha as _mod_sha
62
    sha = _mod_sha.new
2929.3.1 by Vincent Ladeuil
Fix python2.6 deprecation warnings (still 4 failures 5 errors in test suite).
63
else:
64
    from hashlib import (
65
        md5,
66
        sha1 as sha,
67
        )
68
3504.4.1 by John Arbash Meinel
Write an alternative 'walkdirs' implementation that uses win32 apis.
69
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
70
import bzrlib
2309.4.3 by John Arbash Meinel
(broken) change safe_*_id to emit a warning.
71
from bzrlib import symbol_versioning
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
72
1 by mbp at sourcefrog
import from baz patch-364
73
1755.3.7 by John Arbash Meinel
Clean up and write tests for permissions. Now we use fstat which should be cheap, and lets us check the permissions and the file size
74
# On win32, O_BINARY is used to indicate the file should
75
# be opened in binary mode, rather than text mode.
76
# On other platforms, O_BINARY doesn't exist, because
77
# they always open in binary mode, so it is okay to
78
# OR with 0 on those platforms
79
O_BINARY = getattr(os, 'O_BINARY', 0)
80
81
4355.2.2 by Alexander Belchenko
osutils.py: get_unicode_argv function (to obtain unicode command line arguments from sys.argv) moved to the beginning of module based on suggestions from review of John Meinel.
82
def get_unicode_argv():
83
    try:
84
        user_encoding = get_user_encoding()
85
        return [a.decode(user_encoding) for a in sys.argv[1:]]
86
    except UnicodeDecodeError:
87
        raise errors.BzrError(("Parameter '%r' is unsupported by the current "
88
                                                            "encoding." % a))
89
90
1 by mbp at sourcefrog
import from baz patch-364
91
def make_readonly(filename):
92
    """Make a filename read-only."""
2949.6.1 by Alexander Belchenko
windows python has os.lstat
93
    mod = os.lstat(filename).st_mode
2568.1.1 by John Arbash Meinel
(Elliot Murphy) Use os.lstat rather than os.stat for osutils.make_readonly/make_writeable
94
    if not stat.S_ISLNK(mod):
95
        mod = mod & 0777555
96
        os.chmod(filename, mod)
1 by mbp at sourcefrog
import from baz patch-364
97
98
99
def make_writable(filename):
2949.6.1 by Alexander Belchenko
windows python has os.lstat
100
    mod = os.lstat(filename).st_mode
2568.1.1 by John Arbash Meinel
(Elliot Murphy) Use os.lstat rather than os.stat for osutils.make_readonly/make_writeable
101
    if not stat.S_ISLNK(mod):
102
        mod = mod | 0200
103
        os.chmod(filename, mod)
1 by mbp at sourcefrog
import from baz patch-364
104
105
2825.7.1 by Robert Collins
* Partial commits are now approximately 40% faster by walking over the
106
def minimum_path_selection(paths):
107
    """Return the smallset subset of paths which are outside paths.
108
2843.1.1 by Ian Clatworthy
Faster partial commits by walking less data (Robert Collins)
109
    :param paths: A container (and hence not None) of paths.
2825.7.1 by Robert Collins
* Partial commits are now approximately 40% faster by walking over the
110
    :return: A set of paths sufficient to include everything in paths via
4325.3.3 by Johan Walles
Add unit test and fix for minimum_path_selection() vs directory names with
111
        is_inside, drawn from the paths parameter.
2825.7.1 by Robert Collins
* Partial commits are now approximately 40% faster by walking over the
112
    """
4325.3.7 by Johan Walles
Style fixes for minimum_path_selection().
113
    if len(paths) < 2:
114
        return set(paths)
4325.3.3 by Johan Walles
Add unit test and fix for minimum_path_selection() vs directory names with
115
116
    def sort_key(path):
117
        return path.split('/')
118
    sorted_paths = sorted(list(paths), key=sort_key)
119
4325.3.7 by Johan Walles
Style fixes for minimum_path_selection().
120
    search_paths = [sorted_paths[0]]
121
    for path in sorted_paths[1:]:
4325.3.2 by Johan Walles
Use a linear algorithm for osutil.minimum_path_selection().
122
        if not is_inside(search_paths[-1], path):
123
            # This path is unique, add it
124
            search_paths.append(path)
4325.3.7 by Johan Walles
Style fixes for minimum_path_selection().
125
4325.3.2 by Johan Walles
Use a linear algorithm for osutil.minimum_path_selection().
126
    return set(search_paths)
2825.7.1 by Robert Collins
* Partial commits are now approximately 40% faster by walking over the
127
128
1077 by Martin Pool
- avoid compiling REs at module load time
129
_QUOTE_RE = None
969 by Martin Pool
- Add less-sucky is_within_any
130
131
1 by mbp at sourcefrog
import from baz patch-364
132
def quotefn(f):
779 by Martin Pool
- better quotefn for windows: use doublequotes for strings with
133
    """Return a quoted filename filename
134
135
    This previously used backslash quoting, but that works poorly on
136
    Windows."""
137
    # TODO: I'm not really sure this is the best format either.x
1077 by Martin Pool
- avoid compiling REs at module load time
138
    global _QUOTE_RE
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
139
    if _QUOTE_RE is None:
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
140
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
141
779 by Martin Pool
- better quotefn for windows: use doublequotes for strings with
142
    if _QUOTE_RE.search(f):
143
        return '"' + f + '"'
144
    else:
145
        return f
1 by mbp at sourcefrog
import from baz patch-364
146
147
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
148
_directory_kind = 'directory'
149
1755.3.7 by John Arbash Meinel
Clean up and write tests for permissions. Now we use fstat which should be cheap, and lets us check the permissions and the file size
150
def get_umask():
151
    """Return the current umask"""
152
    # Assume that people aren't messing with the umask while running
153
    # XXX: This is not thread safe, but there is no way to get the
154
    #      umask without setting it
155
    umask = os.umask(0)
156
    os.umask(umask)
157
    return umask
158
159
2324.2.1 by Dmitry Vasiliev
kind_marker() optimization
160
_kind_marker_map = {
161
    "file": "",
162
    _directory_kind: "/",
163
    "symlink": "@",
1551.10.30 by Aaron Bentley
Merge from bzr.dev
164
    'tree-reference': '+',
2324.2.1 by Dmitry Vasiliev
kind_marker() optimization
165
}
1551.10.30 by Aaron Bentley
Merge from bzr.dev
166
167
488 by Martin Pool
- new helper function kind_marker()
168
def kind_marker(kind):
2324.2.1 by Dmitry Vasiliev
kind_marker() optimization
169
    try:
170
        return _kind_marker_map[kind]
171
    except KeyError:
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
172
        raise errors.BzrError('invalid file kind %r' % kind)
1 by mbp at sourcefrog
import from baz patch-364
173
2324.2.1 by Dmitry Vasiliev
kind_marker() optimization
174
1732.1.2 by John Arbash Meinel
just use os.path.lexists if it exists
175
lexists = getattr(os.path, 'lexists', None)
176
if lexists is None:
177
    def lexists(f):
178
        try:
2324.2.2 by Dmitry Vasiliev
Fixed lexists() implementation
179
            stat = getattr(os, 'lstat', os.stat)
180
            stat(f)
1732.1.2 by John Arbash Meinel
just use os.path.lexists if it exists
181
            return True
2324.2.2 by Dmitry Vasiliev
Fixed lexists() implementation
182
        except OSError, e:
1732.1.2 by John Arbash Meinel
just use os.path.lexists if it exists
183
            if e.errno == errno.ENOENT:
184
                return False;
185
            else:
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
186
                raise errors.BzrError("lstat/stat of (%r): %r" % (f, e))
1732.1.2 by John Arbash Meinel
just use os.path.lexists if it exists
187
1 by mbp at sourcefrog
import from baz patch-364
188
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
189
def fancy_rename(old, new, rename_func, unlink_func):
190
    """A fancy rename, when you don't have atomic rename.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
191
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
192
    :param old: The old path, to rename from
193
    :param new: The new path, to rename to
194
    :param rename_func: The potentially non-atomic rename function
195
    :param unlink_func: A way to delete the target file if the full rename succeeds
196
    """
197
198
    # sftp rename doesn't allow overwriting, so play tricks:
199
    base = os.path.basename(new)
200
    dirname = os.path.dirname(new)
1553.5.22 by Martin Pool
Change fancy_rename to use rand_chars rather than reinvent it.
201
    tmp_name = u'tmp.%s.%.9f.%d.%s' % (base, time.time(), os.getpid(), rand_chars(10))
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
202
    tmp_name = pathjoin(dirname, tmp_name)
203
204
    # Rename the file out of the way, but keep track if it didn't exist
205
    # We don't want to grab just any exception
206
    # something like EACCES should prevent us from continuing
207
    # The downside is that the rename_func has to throw an exception
208
    # with an errno = ENOENT, or NoSuchFile
209
    file_existed = False
210
    try:
211
        rename_func(new, tmp_name)
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
212
    except (errors.NoSuchFile,), e:
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
213
        pass
1532 by Robert Collins
Merge in John Meinels integration branch.
214
    except IOError, e:
215
        # RBC 20060103 abstraction leakage: the paramiko SFTP clients rename
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
216
        # function raises an IOError with errno is None when a rename fails.
1532 by Robert Collins
Merge in John Meinels integration branch.
217
        # This then gets caught here.
1185.50.37 by John Arbash Meinel
Fixed exception handling for fancy_rename
218
        if e.errno not in (None, errno.ENOENT, errno.ENOTDIR):
1532 by Robert Collins
Merge in John Meinels integration branch.
219
            raise
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
220
    except Exception, e:
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
221
        if (getattr(e, 'errno', None) is None
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
222
            or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
223
            raise
224
    else:
225
        file_existed = True
226
4789.17.1 by John Arbash Meinel
Change fancy_rename slightly.
227
    failure_exc = None
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
228
    success = False
229
    try:
2978.8.2 by Alexander Belchenko
teach fancy_rename to handle change case renames in possible case-insensitive filesystem
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:
2978.8.3 by Alexander Belchenko
Aaron's review
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
4789.17.1 by John Arbash Meinel
Change fancy_rename slightly.
239
            failure_exc = sys.exc_info()
240
            if (file_existed and e.errno in (None, errno.ENOENT)
241
                and old.lower() == new.lower()):
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
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
245
    finally:
246
        if file_existed:
247
            # If the file used to exist, rename it back into place
248
            # otherwise just delete it from the tmp location
249
            if success:
1551.15.4 by Aaron Bentley
Revert now-unnecessary changes
250
                unlink_func(tmp_name)
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
251
            else:
1185.31.49 by John Arbash Meinel
Some corrections using the new osutils.rename. **ALL TESTS PASS**
252
                rename_func(tmp_name, new)
4789.17.2 by John Arbash Meinel
Also handle the case when source *and* target does not exist.
253
    if failure_exc is not None:
254
        raise failure_exc[0], failure_exc[1], failure_exc[2]
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
255
1685.1.9 by John Arbash Meinel
Updated LocalTransport so that it's base is now a URL rather than a local path. This helps consistency with all other functions. To do so, I added local_abspath() which returns the local path, and local_path_to/from_url
256
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
257
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
258
# choke on a Unicode string containing a relative path if
259
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
260
# string.
2093.1.1 by John Arbash Meinel
(Bart Teeuwisse) if sys.getfilesystemencoding() is None, use 'utf-8'
261
_fs_enc = sys.getfilesystemencoding() or 'utf-8'
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
262
def _posix_abspath(path):
1711.4.5 by John Arbash Meinel
the _posix_* routines should use posixpath not os.path, so tests pass on win32
263
    # jam 20060426 rather than encoding to fsencoding
264
    # copy posixpath.abspath, but use os.getcwdu instead
265
    if not posixpath.isabs(path):
266
        path = posixpath.join(getcwd(), path)
267
    return posixpath.normpath(path)
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
268
269
270
def _posix_realpath(path):
1711.4.5 by John Arbash Meinel
the _posix_* routines should use posixpath not os.path, so tests pass on win32
271
    return posixpath.realpath(path.encode(_fs_enc)).decode(_fs_enc)
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
272
273
1711.5.2 by John Arbash Meinel
win32 likes to return lowercase drive letters sometimes, and uppercase at other times. normalize this
274
def _win32_fixdrive(path):
275
    """Force drive letters to be consistent.
276
277
    win32 is inconsistent whether it returns lower or upper case
278
    and even if it was consistent the user might type the other
279
    so we force it to uppercase
280
    running python.exe under cmd.exe return capital C:\\
281
    running win32 python inside a cygwin shell returns lowercase c:\\
282
    """
283
    drive, path = _nt_splitdrive(path)
284
    return drive.upper() + path
285
286
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
287
def _win32_abspath(path):
1711.4.6 by John Arbash Meinel
Removing hacks for _win32_abspath, on real win32 abspath handles unicode just fine, it doesn't handle encoding into 'mbcs'
288
    # Real _nt_abspath doesn't have a problem with a unicode cwd
1711.5.2 by John Arbash Meinel
win32 likes to return lowercase drive letters sometimes, and uppercase at other times. normalize this
289
    return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
290
291
2279.4.1 by Alexander Belchenko
Reimplementation of ntpath.abspath in Python for Windows98: unicode safe, UNC path safe
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]
2279.4.3 by Alexander Belchenko
win98_abspath: support for running in POSIX environment: cwd path has not drive letter
314
            path = path[1:]
2279.4.1 by Alexander Belchenko
Reimplementation of ntpath.abspath in Python for Windows98: unicode safe, UNC path safe
315
        path = cwd + '\\' + path
316
    return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
317
318
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
319
def _win32_realpath(path):
1711.4.6 by John Arbash Meinel
Removing hacks for _win32_abspath, on real win32 abspath handles unicode just fine, it doesn't handle encoding into 'mbcs'
320
    # Real _nt_realpath doesn't have a problem with a unicode cwd
1711.5.2 by John Arbash Meinel
win32 likes to return lowercase drive letters sometimes, and uppercase at other times. normalize this
321
    return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
322
323
324
def _win32_pathjoin(*args):
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
325
    return _nt_join(*args).replace('\\', '/')
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
326
327
328
def _win32_normpath(path):
1711.5.2 by John Arbash Meinel
win32 likes to return lowercase drive letters sometimes, and uppercase at other times. normalize this
329
    return _win32_fixdrive(_nt_normpath(unicode(path)).replace('\\', '/'))
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
330
331
332
def _win32_getcwd():
1711.5.2 by John Arbash Meinel
win32 likes to return lowercase drive letters sometimes, and uppercase at other times. normalize this
333
    return _win32_fixdrive(os.getcwdu().replace('\\', '/'))
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
334
335
336
def _win32_mkdtemp(*args, **kwargs):
1711.5.2 by John Arbash Meinel
win32 likes to return lowercase drive letters sometimes, and uppercase at other times. normalize this
337
    return _win32_fixdrive(tempfile.mkdtemp(*args, **kwargs).replace('\\', '/'))
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
338
339
340
def _win32_rename(old, new):
1711.7.6 by John Arbash Meinel
Change _win32_rename() so that it raises ENOENT *before* it tries any renaming.
341
    """We expect to be able to atomically replace 'new' with old.
342
1711.7.17 by John Arbash Meinel
Delay the extra syscall in _win32_rename until we get a failure.
343
    On win32, if new exists, it must be moved out of the way first,
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
344
    and then deleted.
1711.7.6 by John Arbash Meinel
Change _win32_rename() so that it raises ENOENT *before* it tries any renaming.
345
    """
1711.7.17 by John Arbash Meinel
Delay the extra syscall in _win32_rename until we get a failure.
346
    try:
347
        fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
348
    except OSError, e:
1830.3.15 by John Arbash Meinel
On Mac we get EINVAL when renaming cwd
349
        if e.errno in (errno.EPERM, errno.EACCES, errno.EBUSY, errno.EINVAL):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
350
            # If we try to rename a non-existant file onto cwd, we get
351
            # EPERM or EACCES instead of ENOENT, this will raise ENOENT
1830.3.15 by John Arbash Meinel
On Mac we get EINVAL when renaming cwd
352
            # if the old path doesn't exist, sometimes we get EACCES
353
            # On Linux, we seem to get EBUSY, on Mac we get EINVAL
1711.7.17 by John Arbash Meinel
Delay the extra syscall in _win32_rename until we get a failure.
354
            os.lstat(old)
355
        raise
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
356
357
1830.3.11 by John Arbash Meinel
Create a mac version of 'getcwd()' which normalizes the path.
358
def _mac_getcwd():
3201.1.1 by jameinel
Fix bug #185458, switch from NFKC to NFC and add tests for filenames that would be broken under NFKC
359
    return unicodedata.normalize('NFC', os.getcwdu())
1830.3.11 by John Arbash Meinel
Create a mac version of 'getcwd()' which normalizes the path.
360
361
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
362
# Default is to just use the python builtins, but these can be rebound on
363
# particular platforms.
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
364
abspath = _posix_abspath
365
realpath = _posix_realpath
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
366
pathjoin = os.path.join
367
normpath = os.path.normpath
368
getcwd = os.getcwdu
369
rename = os.rename
370
dirname = os.path.dirname
371
basename = os.path.basename
2215.4.2 by Alexander Belchenko
split and splitext now the part of osutils
372
split = os.path.split
373
splitext = os.path.splitext
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
374
# These were already imported into local scope
375
# mkdtemp = tempfile.mkdtemp
376
# rmtree = shutil.rmtree
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
377
1551.2.53 by abentley
Strip trailing slashes in a platform-sensible way
378
MIN_ABS_PATHLENGTH = 1
379
1685.1.9 by John Arbash Meinel
Updated LocalTransport so that it's base is now a URL rather than a local path. This helps consistency with all other functions. To do so, I added local_abspath() which returns the local path, and local_path_to/from_url
380
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
381
if sys.platform == 'win32':
3224.5.35 by Andrew Bennetts
More improvements suggested by John's review.
382
    if win32utils.winver == 'Windows 98':
383
        abspath = _win98_abspath
384
    else:
385
        abspath = _win32_abspath
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
386
    realpath = _win32_realpath
387
    pathjoin = _win32_pathjoin
388
    normpath = _win32_normpath
389
    getcwd = _win32_getcwd
390
    mkdtemp = _win32_mkdtemp
391
    rename = _win32_rename
392
1551.2.53 by abentley
Strip trailing slashes in a platform-sensible way
393
    MIN_ABS_PATHLENGTH = 3
1532 by Robert Collins
Merge in John Meinels integration branch.
394
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
395
    def _win32_delete_readonly(function, path, excinfo):
396
        """Error handler for shutil.rmtree function [for win32]
397
        Helps to remove files and dirs marked as read-only.
398
        """
2116.5.1 by Henri Wiechers
Fixes osutils.rmtree on Windows with Python 2.5
399
        exception = excinfo[1]
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
400
        if function in (os.remove, os.rmdir) \
2116.5.1 by Henri Wiechers
Fixes osutils.rmtree on Windows with Python 2.5
401
            and isinstance(exception, OSError) \
402
            and exception.errno == errno.EACCES:
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
403
            make_writable(path)
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
404
            function(path)
405
        else:
406
            raise
407
408
    def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
409
        """Replacer for shutil.rmtree: could remove readonly dirs/files"""
410
        return shutil.rmtree(path, ignore_errors, onerror)
4355.2.2 by Alexander Belchenko
osutils.py: get_unicode_argv function (to obtain unicode command line arguments from sys.argv) moved to the beginning of module based on suggestions from review of John Meinel.
411
412
    f = win32utils.get_unicode_argv     # special function or None
413
    if f is not None:
414
        get_unicode_argv = f
415
1830.3.11 by John Arbash Meinel
Create a mac version of 'getcwd()' which normalizes the path.
416
elif sys.platform == 'darwin':
417
    getcwd = _mac_getcwd
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
418
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
419
1711.4.10 by John Arbash Meinel
Pull out sys.stdout.encoding handling into a separate function so it can be tested, and used elsewhere.
420
def get_terminal_encoding():
421
    """Find the best encoding for printing to the screen.
422
423
    This attempts to check both sys.stdout and sys.stdin to see
424
    what encoding they are in, and if that fails it falls back to
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
425
    osutils.get_user_encoding().
1711.4.10 by John Arbash Meinel
Pull out sys.stdout.encoding handling into a separate function so it can be tested, and used elsewhere.
426
    The problem is that on Windows, locale.getpreferredencoding()
427
    is not the same encoding as that used by the console:
428
    http://mail.python.org/pipermail/python-list/2003-May/162357.html
429
430
    On my standard US Windows XP, the preferred encoding is
431
    cp1252, but the console is cp437
432
    """
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
433
    from bzrlib.trace import mutter
1711.4.10 by John Arbash Meinel
Pull out sys.stdout.encoding handling into a separate function so it can be tested, and used elsewhere.
434
    output_encoding = getattr(sys.stdout, 'encoding', None)
435
    if not output_encoding:
436
        input_encoding = getattr(sys.stdin, 'encoding', None)
437
        if not input_encoding:
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
438
            output_encoding = get_user_encoding()
439
            mutter('encoding stdout as osutils.get_user_encoding() %r',
440
                   output_encoding)
1711.4.10 by John Arbash Meinel
Pull out sys.stdout.encoding handling into a separate function so it can be tested, and used elsewhere.
441
        else:
442
            output_encoding = input_encoding
443
            mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
444
    else:
445
        mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
2127.4.1 by Alexander Belchenko
(jam, bialix) Workaround for cp0 console encoding on Windows
446
    if output_encoding == 'cp0':
447
        # invalid encoding (cp0 means 'no codepage' on Windows)
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
448
        output_encoding = get_user_encoding()
2127.4.1 by Alexander Belchenko
(jam, bialix) Workaround for cp0 console encoding on Windows
449
        mutter('cp0 is invalid encoding.'
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
450
               ' encoding stdout as osutils.get_user_encoding() %r',
451
               output_encoding)
2192.1.1 by Alexander Belchenko
Before actually using encoding need to check that Python has corresponding codec
452
    # check encoding
453
    try:
454
        codecs.lookup(output_encoding)
455
    except LookupError:
456
        sys.stderr.write('bzr: warning:'
2192.1.9 by Alexander Belchenko
final fix suggested by John Meinel
457
                         ' unknown terminal encoding %s.\n'
2192.1.1 by Alexander Belchenko
Before actually using encoding need to check that Python has corresponding codec
458
                         '  Using encoding %s instead.\n'
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
459
                         % (output_encoding, get_user_encoding())
2192.1.1 by Alexander Belchenko
Before actually using encoding need to check that Python has corresponding codec
460
                        )
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
461
        output_encoding = get_user_encoding()
2192.1.1 by Alexander Belchenko
Before actually using encoding need to check that Python has corresponding codec
462
1711.4.10 by John Arbash Meinel
Pull out sys.stdout.encoding handling into a separate function so it can be tested, and used elsewhere.
463
    return output_encoding
464
465
1185.31.32 by John Arbash Meinel
Updated the bzr sourcecode to use bzrlib.osutils.pathjoin rather than os.path.join to enforce internal use of / instead of \
466
def normalizepath(f):
3287.18.2 by Matt McClure
Reverts to 3290.
467
    if getattr(os.path, 'realpath', None) is not None:
1185.31.32 by John Arbash Meinel
Updated the bzr sourcecode to use bzrlib.osutils.pathjoin rather than os.path.join to enforce internal use of / instead of \
468
        F = realpath
469
    else:
470
        F = abspath
471
    [p,e] = os.path.split(f)
472
    if e == "" or e == "." or e == "..":
473
        return F(f)
474
    else:
475
        return pathjoin(F(p), e)
476
1 by mbp at sourcefrog
import from baz patch-364
477
478
def isdir(f):
479
    """True if f is an accessible directory."""
480
    try:
481
        return S_ISDIR(os.lstat(f)[ST_MODE])
482
    except OSError:
483
        return False
484
485
486
def isfile(f):
487
    """True if f is a regular file."""
488
    try:
489
        return S_ISREG(os.lstat(f)[ST_MODE])
490
    except OSError:
491
        return False
492
1092.2.6 by Robert Collins
symlink support updated to work
493
def islink(f):
494
    """True if f is a symlink."""
495
    try:
496
        return S_ISLNK(os.lstat(f)[ST_MODE])
497
    except OSError:
498
        return False
1 by mbp at sourcefrog
import from baz patch-364
499
485 by Martin Pool
- move commit code into its own module
500
def is_inside(dir, fname):
501
    """True if fname is inside dir.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
502
1185.31.38 by John Arbash Meinel
Changing os.path.normpath to osutils.normpath
503
    The parameters should typically be passed to osutils.normpath first, so
969 by Martin Pool
- Add less-sucky is_within_any
504
    that . and .. and repeated slashes are eliminated, and the separators
505
    are canonical for the platform.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
506
507
    The empty string as a dir name is taken as top-of-tree and matches
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
508
    everything.
485 by Martin Pool
- move commit code into its own module
509
    """
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
510
    # XXX: Most callers of this can actually do something smarter by
969 by Martin Pool
- Add less-sucky is_within_any
511
    # looking at the inventory
972 by Martin Pool
- less dodgy is_inside function
512
    if dir == fname:
513
        return True
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
514
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
515
    if dir == '':
516
        return True
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
517
1185.31.34 by John Arbash Meinel
Removing instances of os.sep
518
    if dir[-1] != '/':
519
        dir += '/'
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
520
972 by Martin Pool
- less dodgy is_inside function
521
    return fname.startswith(dir)
522
485 by Martin Pool
- move commit code into its own module
523
524
def is_inside_any(dir_list, fname):
525
    """True if fname is inside any of given dirs."""
526
    for dirname in dir_list:
527
        if is_inside(dirname, fname):
528
            return True
2324.2.3 by Dmitry Vasiliev
Fixed is_inside_* methods implementation
529
    return False
485 by Martin Pool
- move commit code into its own module
530
531
1740.3.4 by Jelmer Vernooij
Move inventory to commit builder.
532
def is_inside_or_parent_of_any(dir_list, fname):
533
    """True if fname is a child or a parent of any of the given files."""
534
    for dirname in dir_list:
535
        if is_inside(dirname, fname) or is_inside(fname, dirname):
536
            return True
2324.2.3 by Dmitry Vasiliev
Fixed is_inside_* methods implementation
537
    return False
1740.3.4 by Jelmer Vernooij
Move inventory to commit builder.
538
539
3956.2.1 by John Arbash Meinel
Add report_activity to osutils.pumpfile
540
def pumpfile(from_file, to_file, read_length=-1, buff_size=32768,
541
             report_activity=None, direction='read'):
2745.5.2 by Robert Collins
* ``bzrlib.transport.Transport.put_file`` now returns the number of bytes
542
    """Copy contents of one file to another.
3408.6.1 by Eric Holmberg
Fix for Bug #215426 in which bzr can cause a MemoryError in socket.recv while
543
544
    The read_length can either be -1 to read to end-of-file (EOF) or
545
    it can specify the maximum number of bytes to read.
546
547
    The buff_size represents the maximum size for each read operation
548
    performed on from_file.
549
3956.2.1 by John Arbash Meinel
Add report_activity to osutils.pumpfile
550
    :param report_activity: Call this as bytes are read, see
551
        Transport._report_activity
552
    :param direction: Will be passed to report_activity
553
2745.5.2 by Robert Collins
* ``bzrlib.transport.Transport.put_file`` now returns the number of bytes
554
    :return: The number of bytes copied.
555
    """
556
    length = 0
3408.6.1 by Eric Holmberg
Fix for Bug #215426 in which bzr can cause a MemoryError in socket.recv while
557
    if read_length >= 0:
558
        # read specified number of bytes
559
560
        while read_length > 0:
561
            num_bytes_to_read = min(read_length, buff_size)
562
563
            block = from_file.read(num_bytes_to_read)
564
            if not block:
565
                # EOF reached
566
                break
3956.2.1 by John Arbash Meinel
Add report_activity to osutils.pumpfile
567
            if report_activity is not None:
568
                report_activity(len(block), direction)
3408.6.1 by Eric Holmberg
Fix for Bug #215426 in which bzr can cause a MemoryError in socket.recv while
569
            to_file.write(block)
570
571
            actual_bytes_read = len(block)
572
            read_length -= actual_bytes_read
573
            length += actual_bytes_read
574
    else:
575
        # read to EOF
576
        while True:
577
            block = from_file.read(buff_size)
578
            if not block:
579
                # EOF reached
580
                break
3956.2.1 by John Arbash Meinel
Add report_activity to osutils.pumpfile
581
            if report_activity is not None:
582
                report_activity(len(block), direction)
3408.6.1 by Eric Holmberg
Fix for Bug #215426 in which bzr can cause a MemoryError in socket.recv while
583
            to_file.write(block)
584
            length += len(block)
2745.5.2 by Robert Collins
* ``bzrlib.transport.Transport.put_file`` now returns the number of bytes
585
    return length
1 by mbp at sourcefrog
import from baz patch-364
586
587
3635.1.2 by Robert Collins
Add osutils.pump_string_file helper function.
588
def pump_string_file(bytes, file_handle, segment_size=None):
589
    """Write bytes to file_handle in many smaller writes.
590
591
    :param bytes: The string to write.
592
    :param file_handle: The file to write to.
593
    """
594
    # Write data in chunks rather than all at once, because very large
595
    # writes fail on some platforms (e.g. Windows with SMB  mounted
596
    # drives).
597
    if not segment_size:
598
        segment_size = 5242880 # 5MB
599
    segments = range(len(bytes) / segment_size + 1)
600
    write = file_handle.write
601
    for segment_index in segments:
602
        segment = buffer(bytes, segment_index * segment_size, segment_size)
603
        write(segment)
604
605
1185.67.7 by Aaron Bentley
Refactored a bit
606
def file_iterator(input_file, readsize=32768):
607
    while True:
608
        b = input_file.read(readsize)
609
        if len(b) == 0:
610
            break
611
        yield b
612
613
1 by mbp at sourcefrog
import from baz patch-364
614
def sha_file(f):
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
615
    """Calculate the hexdigest of an open file.
616
617
    The file cursor should be already at the start.
618
    """
2929.3.1 by Vincent Ladeuil
Fix python2.6 deprecation warnings (still 4 failures 5 errors in test suite).
619
    s = sha()
320 by Martin Pool
- Compute SHA-1 of files in chunks
620
    BUFSIZE = 128<<10
621
    while True:
622
        b = f.read(BUFSIZE)
623
        if not b:
624
            break
625
        s.update(b)
1 by mbp at sourcefrog
import from baz patch-364
626
    return s.hexdigest()
627
628
3368.2.49 by Ian Clatworthy
added osutils.size_sha_file() with tests
629
def size_sha_file(f):
630
    """Calculate the size and hexdigest of an open file.
631
632
    The file cursor should be already at the start and
633
    the caller is responsible for closing the file afterwards.
634
    """
635
    size = 0
636
    s = sha()
637
    BUFSIZE = 128<<10
638
    while True:
639
        b = f.read(BUFSIZE)
640
        if not b:
641
            break
642
        size += len(b)
643
        s.update(b)
644
    return size, s.hexdigest()
645
646
2872.3.1 by Martin Pool
Add -Dhashcache option; clean up dirstate sha1 code
647
def sha_file_by_name(fname):
648
    """Calculate the SHA1 of a file by reading the full text"""
2929.3.1 by Vincent Ladeuil
Fix python2.6 deprecation warnings (still 4 failures 5 errors in test suite).
649
    s = sha()
2922.1.1 by John Arbash Meinel
Fix bug #153493, use O_BINARY when reading files.
650
    f = os.open(fname, os.O_RDONLY | O_BINARY)
2872.3.1 by Martin Pool
Add -Dhashcache option; clean up dirstate sha1 code
651
    try:
2872.3.2 by Martin Pool
Do sha_file_by_name using raw os files rather than file objects; makes this routine about 12osutils.py faster
652
        while True:
653
            b = os.read(f, 1<<16)
654
            if not b:
655
                return s.hexdigest()
656
            s.update(b)
2872.3.1 by Martin Pool
Add -Dhashcache option; clean up dirstate sha1 code
657
    finally:
2872.3.2 by Martin Pool
Do sha_file_by_name using raw os files rather than file objects; makes this routine about 12osutils.py faster
658
        os.close(f)
2872.3.1 by Martin Pool
Add -Dhashcache option; clean up dirstate sha1 code
659
660
2929.3.1 by Vincent Ladeuil
Fix python2.6 deprecation warnings (still 4 failures 5 errors in test suite).
661
def sha_strings(strings, _factory=sha):
1235 by Martin Pool
- split sha_strings into osutils
662
    """Return the sha-1 of concatenation of strings"""
2825.2.1 by Robert Collins
Micro-tweaks to sha routines.
663
    s = _factory()
1235 by Martin Pool
- split sha_strings into osutils
664
    map(s.update, strings)
665
    return s.hexdigest()
666
667
2929.3.1 by Vincent Ladeuil
Fix python2.6 deprecation warnings (still 4 failures 5 errors in test suite).
668
def sha_string(f, _factory=sha):
2825.2.1 by Robert Collins
Micro-tweaks to sha routines.
669
    return _factory(f).hexdigest()
1 by mbp at sourcefrog
import from baz patch-364
670
671
124 by mbp at sourcefrog
- check file text for past revisions is correct
672
def fingerprint_file(f):
126 by mbp at sourcefrog
Use just one big read to fingerprint files
673
    b = f.read()
2825.2.1 by Robert Collins
Micro-tweaks to sha routines.
674
    return {'size': len(b),
2929.3.1 by Vincent Ladeuil
Fix python2.6 deprecation warnings (still 4 failures 5 errors in test suite).
675
            'sha1': sha(b).hexdigest()}
124 by mbp at sourcefrog
- check file text for past revisions is correct
676
677
1 by mbp at sourcefrog
import from baz patch-364
678
def compare_files(a, b):
679
    """Returns true if equal in contents"""
74 by mbp at sourcefrog
compare_files: read in one page at a time rather than
680
    BUFSIZE = 4096
681
    while True:
682
        ai = a.read(BUFSIZE)
683
        bi = b.read(BUFSIZE)
684
        if ai != bi:
685
            return False
686
        if ai == '':
687
            return True
1 by mbp at sourcefrog
import from baz patch-364
688
689
49 by mbp at sourcefrog
fix local-time-offset calculation
690
def local_time_offset(t=None):
691
    """Return offset of local zone from GMT, either at present or at time t."""
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
692
    if t is None:
73 by mbp at sourcefrog
fix time.localtime call for python 2.3
693
        t = time.time()
2215.6.1 by James Henstridge
Don't rely on time.timezone and time.altzone in local_time_offset(),
694
    offset = datetime.fromtimestamp(t) - datetime.utcfromtimestamp(t)
695
    return offset.days * 86400 + offset.seconds
8 by mbp at sourcefrog
store committer's timezone in revision and show
696
3512.3.1 by Martin von Gagern
Hand-selected minimalistic set of changes from my setlocale branch.
697
weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
698
2425.6.2 by Martin Pool
Make timestamps use existing format_date; document that function more
699
def format_date(t, offset=0, timezone='original', date_fmt=None,
3526.5.4 by Martin von Gagern
Use separate function format_local_date for local weekday formats in unicode.
700
                show_offset=True):
2425.6.2 by Martin Pool
Make timestamps use existing format_date; document that function more
701
    """Return a formatted date string.
702
703
    :param t: Seconds since the epoch.
704
    :param offset: Timezone offset in seconds east of utc.
705
    :param timezone: How to display the time: 'utc', 'original' for the
706
         timezone specified by offset, or 'local' for the process's current
707
         timezone.
3526.5.4 by Martin von Gagern
Use separate function format_local_date for local weekday formats in unicode.
708
    :param date_fmt: strftime format.
709
    :param show_offset: Whether to append the timezone.
710
    """
711
    (date_fmt, tt, offset_str) = \
712
               _format_date(t, offset, timezone, date_fmt, show_offset)
713
    date_fmt = date_fmt.replace('%a', weekdays[tt[6]])
714
    date_str = time.strftime(date_fmt, tt)
715
    return date_str + offset_str
716
717
def format_local_date(t, offset=0, timezone='original', date_fmt=None,
718
                      show_offset=True):
719
    """Return an unicode date string formatted according to the current locale.
720
721
    :param t: Seconds since the epoch.
722
    :param offset: Timezone offset in seconds east of utc.
723
    :param timezone: How to display the time: 'utc', 'original' for the
724
         timezone specified by offset, or 'local' for the process's current
725
         timezone.
726
    :param date_fmt: strftime format.
727
    :param show_offset: Whether to append the timezone.
728
    """
729
    (date_fmt, tt, offset_str) = \
730
               _format_date(t, offset, timezone, date_fmt, show_offset)
731
    date_str = time.strftime(date_fmt, tt)
732
    if not isinstance(date_str, unicode):
4385.4.1 by Alexander Belchenko
removed all references to bzrlib.user_encoding
733
        date_str = date_str.decode(get_user_encoding(), 'replace')
3526.5.4 by Martin von Gagern
Use separate function format_local_date for local weekday formats in unicode.
734
    return date_str + offset_str
735
736
def _format_date(t, offset, timezone, date_fmt, show_offset):
8 by mbp at sourcefrog
store committer's timezone in revision and show
737
    if timezone == 'utc':
1 by mbp at sourcefrog
import from baz patch-364
738
        tt = time.gmtime(t)
739
        offset = 0
8 by mbp at sourcefrog
store committer's timezone in revision and show
740
    elif timezone == 'original':
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
741
        if offset is None:
23 by mbp at sourcefrog
format_date: handle revisions with no timezone offset
742
            offset = 0
16 by mbp at sourcefrog
fix inverted calculation for original timezone -> utc
743
        tt = time.gmtime(t + offset)
12 by mbp at sourcefrog
new --timezone option for bzr log
744
    elif timezone == 'local':
1 by mbp at sourcefrog
import from baz patch-364
745
        tt = time.localtime(t)
49 by mbp at sourcefrog
fix local-time-offset calculation
746
        offset = local_time_offset(t)
12 by mbp at sourcefrog
new --timezone option for bzr log
747
    else:
3144.1.1 by Lukáš Lalinský
Fixed error reporting of unsupported timezone format.
748
        raise errors.UnsupportedTimezoneFormat(timezone)
1185.12.24 by Aaron Bentley
Made format_date more flexible
749
    if date_fmt is None:
750
        date_fmt = "%a %Y-%m-%d %H:%M:%S"
751
    if show_offset:
752
        offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
753
    else:
754
        offset_str = ''
3526.5.4 by Martin von Gagern
Use separate function format_local_date for local weekday formats in unicode.
755
    return (date_fmt, tt, offset_str)
1 by mbp at sourcefrog
import from baz patch-364
756
757
758
def compact_date(when):
759
    return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
760
1 by mbp at sourcefrog
import from baz patch-364
761
1957.1.4 by John Arbash Meinel
create a helper for formatting a time delta
762
def format_delta(delta):
763
    """Get a nice looking string for a time delta.
764
765
    :param delta: The time difference in seconds, can be positive or negative.
766
        positive indicates time in the past, negative indicates time in the
767
        future. (usually time.time() - stored_time)
768
    :return: String formatted to show approximate resolution
769
    """
770
    delta = int(delta)
771
    if delta >= 0:
772
        direction = 'ago'
773
    else:
774
        direction = 'in the future'
775
        delta = -delta
776
777
    seconds = delta
778
    if seconds < 90: # print seconds up to 90 seconds
779
        if seconds == 1:
780
            return '%d second %s' % (seconds, direction,)
781
        else:
782
            return '%d seconds %s' % (seconds, direction)
783
784
    minutes = int(seconds / 60)
785
    seconds -= 60 * minutes
786
    if seconds == 1:
787
        plural_seconds = ''
788
    else:
789
        plural_seconds = 's'
790
    if minutes < 90: # print minutes, seconds up to 90 minutes
791
        if minutes == 1:
792
            return '%d minute, %d second%s %s' % (
793
                    minutes, seconds, plural_seconds, direction)
794
        else:
795
            return '%d minutes, %d second%s %s' % (
796
                    minutes, seconds, plural_seconds, direction)
797
798
    hours = int(minutes / 60)
799
    minutes -= 60 * hours
800
    if minutes == 1:
801
        plural_minutes = ''
802
    else:
803
        plural_minutes = 's'
804
805
    if hours == 1:
806
        return '%d hour, %d minute%s %s' % (hours, minutes,
807
                                            plural_minutes, direction)
808
    return '%d hours, %d minute%s %s' % (hours, minutes,
809
                                         plural_minutes, direction)
1 by mbp at sourcefrog
import from baz patch-364
810
811
def filesize(f):
812
    """Return size of given open file."""
813
    return os.fstat(f.fileno())[ST_SIZE]
814
1553.5.5 by Martin Pool
New utility routine rand_chars
815
1185.1.7 by Robert Collins
Nathaniel McCallums patch for urandom friendliness on aix.
816
# Define rand_bytes based on platform.
817
try:
818
    # Python 2.4 and later have os.urandom,
819
    # but it doesn't work on some arches
820
    os.urandom(1)
1 by mbp at sourcefrog
import from baz patch-364
821
    rand_bytes = os.urandom
1185.1.7 by Robert Collins
Nathaniel McCallums patch for urandom friendliness on aix.
822
except (NotImplementedError, AttributeError):
823
    # If python doesn't have os.urandom, or it doesn't work,
824
    # then try to first pull random data from /dev/urandom
2067.1.1 by John Arbash Meinel
Catch an exception while opening /dev/urandom rather than using os.path.exists()
825
    try:
1185.1.7 by Robert Collins
Nathaniel McCallums patch for urandom friendliness on aix.
826
        rand_bytes = file('/dev/urandom', 'rb').read
827
    # Otherwise, use this hack as a last resort
2067.1.1 by John Arbash Meinel
Catch an exception while opening /dev/urandom rather than using os.path.exists()
828
    except (IOError, OSError):
1185.1.7 by Robert Collins
Nathaniel McCallums patch for urandom friendliness on aix.
829
        # not well seeded, but better than nothing
830
        def rand_bytes(n):
831
            import random
832
            s = ''
833
            while n:
834
                s += chr(random.randint(0, 255))
835
                n -= 1
836
            return s
1 by mbp at sourcefrog
import from baz patch-364
837
1553.5.5 by Martin Pool
New utility routine rand_chars
838
839
ALNUM = '0123456789abcdefghijklmnopqrstuvwxyz'
840
def rand_chars(num):
841
    """Return a random string of num alphanumeric characters
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
842
843
    The result only contains lowercase chars because it may be used on
1553.5.5 by Martin Pool
New utility routine rand_chars
844
    case-insensitive filesystems.
845
    """
846
    s = ''
847
    for raw_byte in rand_bytes(num):
848
        s += ALNUM[ord(raw_byte) % 36]
849
    return s
850
851
1 by mbp at sourcefrog
import from baz patch-364
852
## TODO: We could later have path objects that remember their list
1759.2.2 by Jelmer Vernooij
Revert some of my spelling fixes and fix some typos after review by Aaron.
853
## decomposition (might be too tricksy though.)
1 by mbp at sourcefrog
import from baz patch-364
854
855
def splitpath(p):
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
856
    """Turn string into list of parts."""
271 by Martin Pool
- Windows path fixes
857
    # split on either delimiter because people might use either on
858
    # Windows
859
    ps = re.split(r'[\\/]', p)
860
861
    rps = []
1 by mbp at sourcefrog
import from baz patch-364
862
    for f in ps:
863
        if f == '..':
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
864
            raise errors.BzrError("sorry, %r not allowed in path" % f)
271 by Martin Pool
- Windows path fixes
865
        elif (f == '.') or (f == ''):
866
            pass
867
        else:
868
            rps.append(f)
869
    return rps
1 by mbp at sourcefrog
import from baz patch-364
870
3890.2.4 by John Arbash Meinel
Add a new function that can convert 'chunks' format to a 'lines' format.
871
1 by mbp at sourcefrog
import from baz patch-364
872
def joinpath(p):
873
    for f in p:
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
874
        if (f == '..') or (f is None) or (f == ''):
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
875
            raise errors.BzrError("sorry, %r not allowed in path" % f)
1185.31.32 by John Arbash Meinel
Updated the bzr sourcecode to use bzrlib.osutils.pathjoin rather than os.path.join to enforce internal use of / instead of \
876
    return pathjoin(*p)
1 by mbp at sourcefrog
import from baz patch-364
877
878
4370.1.1 by Ian Clatworthy
add osutils.parent_directories() API
879
def parent_directories(filename):
4371.1.1 by Ian Clatworthy
(igc) added osutils.parent_directories() (Ian Clatworthy)
880
    """Return the list of parent directories, deepest first.
881
    
882
    For example, parent_directories("a/b/c") -> ["a/b", "a"].
883
    """
4370.1.1 by Ian Clatworthy
add osutils.parent_directories() API
884
    parents = []
885
    parts = splitpath(dirname(filename))
886
    while parts:
887
        parents.append(joinpath(parts))
888
        parts.pop()
889
    return parents
890
891
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
892
_extension_load_failures = []
893
894
895
def failed_to_load_extension(exception):
4574.3.1 by Martin Pool
Give a warning when failing to load _chunks_to_lines_pyx
896
    """Handle failing to load a binary extension.
897
898
    This should be called from the ImportError block guarding the attempt to
899
    import the native extension.  If this function returns, the pure-Python
900
    implementation should be loaded instead::
901
902
    >>> try:
903
    >>>     import bzrlib._fictional_extension_pyx
904
    >>> except ImportError, e:
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
905
    >>>     bzrlib.osutils.failed_to_load_extension(e)
4574.3.1 by Martin Pool
Give a warning when failing to load _chunks_to_lines_pyx
906
    >>>     import bzrlib._fictional_extension_py
907
    """
908
    # NB: This docstring is just an example, not a doctest, because doctest
909
    # currently can't cope with the use of lazy imports in this namespace --
910
    # mbp 20090729
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
911
    
912
    # This currently doesn't report the failure at the time it occurs, because
913
    # they tend to happen very early in startup when we can't check config
914
    # files etc, and also we want to report all failures but not spam the user
915
    # with 10 warnings.
916
    from bzrlib import trace
917
    exception_str = str(exception)
918
    if exception_str not in _extension_load_failures:
919
        trace.mutter("failed to load compiled extension: %s" % exception_str)
920
        _extension_load_failures.append(exception_str)
921
922
923
def report_extension_load_failures():
924
    if not _extension_load_failures:
925
        return
926
    from bzrlib.config import GlobalConfig
927
    if GlobalConfig().get_user_option_as_bool('ignore_missing_extensions'):
928
        return
929
    # the warnings framework should by default show this only once
4695.4.1 by Martin Pool
Give a shorter/cleaner message for missing extensions
930
    from bzrlib.trace import warning
931
    warning(
932
        "bzr: warning: some compiled extensions could not be loaded; "
933
        "see <https://answers.launchpad.net/bzr/+faq/703>")
934
    # we no longer show the specific missing extensions here, because it makes
935
    # the message too long and scary - see
936
    # https://bugs.launchpad.net/bzr/+bug/430529
4574.3.1 by Martin Pool
Give a warning when failing to load _chunks_to_lines_pyx
937
938
3890.2.7 by John Arbash Meinel
A Pyrex extension is about 5x faster than the fastest python code I could write.
939
try:
940
    from bzrlib._chunks_to_lines_pyx import chunks_to_lines
4574.3.1 by Martin Pool
Give a warning when failing to load _chunks_to_lines_pyx
941
except ImportError, e:
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
942
    failed_to_load_extension(e)
3890.2.8 by John Arbash Meinel
Move everything into properly parameterized tests.
943
    from bzrlib._chunks_to_lines_py import chunks_to_lines
3890.2.7 by John Arbash Meinel
A Pyrex extension is about 5x faster than the fastest python code I could write.
944
945
1231 by Martin Pool
- more progress on fetch on top of weaves
946
def split_lines(s):
947
    """Split s into lines, but without removing the newline characters."""
3890.2.18 by John Arbash Meinel
Implement osutils.split_lines() in terms of chunks_to_lines if possible.
948
    # Trivially convert a fulltext into a 'chunked' representation, and let
949
    # chunks_to_lines do the heavy lifting.
950
    if isinstance(s, str):
951
        # chunks_to_lines only supports 8-bit strings
952
        return chunks_to_lines([s])
953
    else:
954
        return _split_lines(s)
955
956
957
def _split_lines(s):
958
    """Split s into lines, but without removing the newline characters.
959
960
    This supports Unicode or plain string objects.
961
    """
1666.1.6 by Robert Collins
Make knit the default format.
962
    lines = s.split('\n')
963
    result = [line + '\n' for line in lines[:-1]]
964
    if lines[-1]:
965
        result.append(lines[-1])
966
    return result
1391 by Robert Collins
merge from integration
967
968
1185.10.4 by Aaron Bentley
Disabled hardlinks on cygwin, mac OS
969
def hardlinks_good():
1185.10.5 by Aaron Bentley
Fixed hardlinks_good test
970
    return sys.platform not in ('win32', 'cygwin', 'darwin')
1185.10.4 by Aaron Bentley
Disabled hardlinks on cygwin, mac OS
971
1185.1.46 by Robert Collins
Aarons branch --basis patch
972
1185.10.3 by Aaron Bentley
Made copy_multi_immutable create hardlinks opportunistically
973
def link_or_copy(src, dest):
974
    """Hardlink a file, or copy it if it can't be hardlinked."""
1185.10.4 by Aaron Bentley
Disabled hardlinks on cygwin, mac OS
975
    if not hardlinks_good():
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
976
        shutil.copyfile(src, dest)
1185.10.3 by Aaron Bentley
Made copy_multi_immutable create hardlinks opportunistically
977
        return
978
    try:
979
        os.link(src, dest)
980
    except (OSError, IOError), e:
981
        if e.errno != errno.EXDEV:
982
            raise
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
983
        shutil.copyfile(src, dest)
1399.1.4 by Robert Collins
move diff and symlink conditionals into inventory.py from diff.py
984
2831.5.2 by Vincent Ladeuil
Review feedback.
985
986
def delete_any(path):
4490.1.1 by Martin Pool
merge fix for forcing readonly deletion, and tweak
987
    """Delete a file, symlink or directory.  
988
    
989
    Will delete even if readonly.
990
    """
4440.1.2 by Craig Hewetson
Fixes made after first code review.
991
    try:
4490.1.1 by Martin Pool
merge fix for forcing readonly deletion, and tweak
992
       _delete_file_or_dir(path)
4440.1.2 by Craig Hewetson
Fixes made after first code review.
993
    except (OSError, IOError), e:
994
        if e.errno in (errno.EPERM, errno.EACCES):
4490.1.1 by Martin Pool
merge fix for forcing readonly deletion, and tweak
995
            # make writable and try again
996
            try:
4440.1.2 by Craig Hewetson
Fixes made after first code review.
997
                make_writable(path)
4490.1.1 by Martin Pool
merge fix for forcing readonly deletion, and tweak
998
            except (OSError, IOError):
4440.1.2 by Craig Hewetson
Fixes made after first code review.
999
                pass
4490.1.1 by Martin Pool
merge fix for forcing readonly deletion, and tweak
1000
            _delete_file_or_dir(path)
1001
        else:
1002
            raise
1003
1004
1005
def _delete_file_or_dir(path):
1006
    # Look Before You Leap (LBYL) is appropriate here instead of Easier to Ask for
1007
    # Forgiveness than Permission (EAFP) because:
1008
    # - root can damage a solaris file system by using unlink,
1009
    # - unlink raises different exceptions on different OSes (linux: EISDIR, win32:
1010
    #   EACCES, OSX: EPERM) when invoked on a directory.
2831.5.2 by Vincent Ladeuil
Review feedback.
1011
    if isdir(path): # Takes care of symlinks
1012
        os.rmdir(path)
1013
    else:
1014
        os.unlink(path)
1558.12.9 by Aaron Bentley
Handle resolving conflicts with directories properly
1015
1399.1.4 by Robert Collins
move diff and symlink conditionals into inventory.py from diff.py
1016
1017
def has_symlinks():
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
1018
    if getattr(os, 'symlink', None) is not None:
1399.1.4 by Robert Collins
move diff and symlink conditionals into inventory.py from diff.py
1019
        return True
1020
    else:
1021
        return False
2831.5.2 by Vincent Ladeuil
Review feedback.
1022
1185.16.38 by Martin Pool
- move contains_whitespace and contains_linebreaks to osutils
1023
3136.1.1 by Aaron Bentley
Add support for hardlinks to TreeTransform
1024
def has_hardlinks():
1025
    if getattr(os, 'link', None) is not None:
1026
        return True
1027
    else:
1028
        return False
1029
1030
3287.18.14 by Matt McClure
Extracted a host_os_dereferences_symlinks method.
1031
def host_os_dereferences_symlinks():
1032
    return (has_symlinks()
3287.18.19 by Matt McClure
Changed tested sys.platform value from 'windows' (mistaken) to 'win32'
1033
            and sys.platform not in ('cygwin', 'win32'))
3287.18.14 by Matt McClure
Extracted a host_os_dereferences_symlinks method.
1034
1035
4241.14.14 by Vincent Ladeuil
Test and implements osutils.readlink().
1036
def readlink(abspath):
1037
    """Return a string representing the path to which the symbolic link points.
1038
1039
    :param abspath: The link absolute unicode path.
1040
1041
    This his guaranteed to return the symbolic link in unicode in all python
1042
    versions.
1043
    """
1044
    link = abspath.encode(_fs_enc)
1045
    target = os.readlink(link)
1046
    target = target.decode(_fs_enc)
1047
    return target
1048
1049
1185.16.38 by Martin Pool
- move contains_whitespace and contains_linebreaks to osutils
1050
def contains_whitespace(s):
1051
    """True if there are any whitespace characters in s."""
2249.2.1 by John Arbash Meinel
(John Arbash Meinel) hard-code the whitespace chars to avoid problems in some locales.
1052
    # string.whitespace can include '\xa0' in certain locales, because it is
1053
    # considered "non-breaking-space" as part of ISO-8859-1. But it
1054
    # 1) Isn't a breaking whitespace
1055
    # 2) Isn't one of ' \t\r\n' which are characters we sometimes use as
1056
    #    separators
1057
    # 3) '\xa0' isn't unicode safe since it is >128.
2249.5.16 by John Arbash Meinel
[merge] bzr.dev 2283
1058
1059
    # This should *not* be a unicode set of characters in case the source
1060
    # string is not a Unicode string. We can auto-up-cast the characters since
1061
    # they are ascii, but we don't want to auto-up-cast the string in case it
1062
    # is utf-8
1063
    for ch in ' \t\n\r\v\f':
1185.16.38 by Martin Pool
- move contains_whitespace and contains_linebreaks to osutils
1064
        if ch in s:
1065
            return True
1066
    else:
1067
        return False
1068
1069
1070
def contains_linebreaks(s):
1071
    """True if there is any vertical whitespace in s."""
1072
    for ch in '\f\n\r':
1073
        if ch in s:
1074
            return True
1075
    else:
1076
        return False
1457.1.2 by Robert Collins
move branch._relpath into osutils as relpath
1077
1078
1079
def relpath(base, path):
1080
    """Return path relative to base, or raise exception.
1081
1082
    The path may be either an absolute path or a path relative to the
1083
    current working directory.
1084
1085
    os.path.commonprefix (python2.4) has a bad bug that it works just
1086
    on string prefixes, assuming that '/u' is a prefix of '/u2'.  This
1636.1.1 by Robert Collins
Fix calling relpath() and abspath() on transports at their root.
1087
    avoids that problem.
1088
    """
1685.1.12 by John Arbash Meinel
Some more work to get LocalTransport to only support URLs
1089
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1090
    if len(base) < MIN_ABS_PATHLENGTH:
1091
        # must have space for e.g. a drive letter
1092
        raise ValueError('%r is too short to calculate a relative path'
1093
            % (base,))
1685.1.9 by John Arbash Meinel
Updated LocalTransport so that it's base is now a URL rather than a local path. This helps consistency with all other functions. To do so, I added local_abspath() which returns the local path, and local_path_to/from_url
1094
1685.1.12 by John Arbash Meinel
Some more work to get LocalTransport to only support URLs
1095
    rp = abspath(path)
1457.1.2 by Robert Collins
move branch._relpath into osutils as relpath
1096
1097
    s = []
1685.1.12 by John Arbash Meinel
Some more work to get LocalTransport to only support URLs
1098
    head = rp
4555.2.1 by John Arbash Meinel
Fix bug #394227, osutils.relpath() could get into an infinite loop.
1099
    while True:
1100
        if len(head) <= len(base) and head != base:
1101
            raise errors.PathNotChild(rp, base)
1457.1.2 by Robert Collins
move branch._relpath into osutils as relpath
1102
        if head == base:
1103
            break
4555.2.1 by John Arbash Meinel
Fix bug #394227, osutils.relpath() could get into an infinite loop.
1104
        head, tail = split(head)
1457.1.2 by Robert Collins
move branch._relpath into osutils as relpath
1105
        if tail:
4555.2.1 by John Arbash Meinel
Fix bug #394227, osutils.relpath() could get into an infinite loop.
1106
            s.append(tail)
1457.1.2 by Robert Collins
move branch._relpath into osutils as relpath
1107
1185.31.35 by John Arbash Meinel
Couple small fixes, all tests pass on cygwin.
1108
    if s:
4555.2.3 by John Arbash Meinel
Fix a trivial bug that should have been caught earlier. :)
1109
        return pathjoin(*reversed(s))
1185.31.35 by John Arbash Meinel
Couple small fixes, all tests pass on cygwin.
1110
    else:
1111
        return ''
1185.33.60 by Martin Pool
Use full terminal width for verbose test output.
1112
1113
3794.5.29 by Mark Hammond
cicp_canonical_relpath -> _cicp_canonical_relpath
1114
def _cicp_canonical_relpath(base, path):
3794.5.1 by Mark Hammond
Add canonical_relpath api function
1115
    """Return the canonical path relative to base.
1116
1117
    Like relpath, but on case-insensitive-case-preserving file-systems, this
3794.5.13 by Mark Hammond
Tweaks suggested by Martin
1118
    will return the relpath as stored on the file-system rather than in the
1119
    case specified in the input string, for all existing portions of the path.
1120
3794.5.28 by Mark Hammond
Update comments.
1121
    This will cause O(N) behaviour if called for every path in a tree; if you
1122
    have a number of paths to convert, you should use canonical_relpaths().
3794.5.31 by Mark Hammond
bulk of the simple review comments from igc.
1123
    """
1124
    # TODO: it should be possible to optimize this for Windows by using the
1125
    # win32 API FindFiles function to look for the specified name - but using
1126
    # os.listdir() still gives us the correct, platform agnostic semantics in
1127
    # the short term.
3794.5.13 by Mark Hammond
Tweaks suggested by Martin
1128
3794.5.1 by Mark Hammond
Add canonical_relpath api function
1129
    rel = relpath(base, path)
1130
    # '.' will have been turned into ''
1131
    if not rel:
1132
        return rel
1133
1134
    abs_base = abspath(base)
1135
    current = abs_base
1136
    _listdir = os.listdir
1137
1138
    # use an explicit iterator so we can easily consume the rest on early exit.
3794.5.36 by Mark Hammond
test for, and fix problem with canonical_relpath when the tail does not exist.
1139
    bit_iter = iter(rel.split('/'))
3794.5.1 by Mark Hammond
Add canonical_relpath api function
1140
    for bit in bit_iter:
1141
        lbit = bit.lower()
4634.70.2 by John Arbash Meinel
Fix bug #322807, teach cicp_canonical_relpath how to handle
1142
        try:
1143
            next_entries = _listdir(current)
4634.70.3 by John Arbash Meinel
Clean up some terminology, catch a double _listdir request, thanks spiv.
1144
        except OSError: # enoent, eperm, etc
1145
            # We can't find this in the filesystem, so just append the
1146
            # remaining bits.
4634.70.2 by John Arbash Meinel
Fix bug #322807, teach cicp_canonical_relpath how to handle
1147
            current = pathjoin(current, bit, *list(bit_iter))
1148
            break
4634.70.3 by John Arbash Meinel
Clean up some terminology, catch a double _listdir request, thanks spiv.
1149
        for look in next_entries:
3794.5.1 by Mark Hammond
Add canonical_relpath api function
1150
            if lbit == look.lower():
1151
                current = pathjoin(current, look)
1152
                break
1153
        else:
1154
            # got to the end, nothing matched, so we just return the
1155
            # non-existing bits as they were specified (the filename may be
1156
            # the target of a move, for example).
1157
            current = pathjoin(current, bit, *list(bit_iter))
1158
            break
4634.70.2 by John Arbash Meinel
Fix bug #322807, teach cicp_canonical_relpath how to handle
1159
    return current[len(abs_base):].lstrip('/')
3794.5.1 by Mark Hammond
Add canonical_relpath api function
1160
3794.5.13 by Mark Hammond
Tweaks suggested by Martin
1161
# XXX - TODO - we need better detection/integration of case-insensitive
4241.9.5 by Vincent Ladeuil
Fix unicode related OSX failures.
1162
# file-systems; Linux often sees FAT32 devices (or NFS-mounted OSX
1163
# filesystems), for example, so could probably benefit from the same basic
1164
# support there.  For now though, only Windows and OSX get that support, and
1165
# they get it for *all* file-systems!
4241.9.2 by Vincent Ladeuil
Fix most of cicp related failures on OSX.
1166
if sys.platform in ('win32', 'darwin'):
3794.5.29 by Mark Hammond
cicp_canonical_relpath -> _cicp_canonical_relpath
1167
    canonical_relpath = _cicp_canonical_relpath
3794.5.1 by Mark Hammond
Add canonical_relpath api function
1168
else:
1169
    canonical_relpath = relpath
1170
3794.5.15 by Mark Hammond
Add canonical_relpaths() as a placeholder for a future caching implementation.
1171
def canonical_relpaths(base, paths):
1172
    """Create an iterable to canonicalize a sequence of relative paths.
1173
1174
    The intent is for this implementation to use a cache, vastly speeding
1175
    up multiple transformations in the same directory.
1176
    """
1177
    # but for now, we haven't optimized...
1178
    return [canonical_relpath(base, p) for p in paths]
3794.5.1 by Mark Hammond
Add canonical_relpath api function
1179
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
1180
def safe_unicode(unicode_or_utf8_string):
1181
    """Coerce unicode_or_utf8_string into unicode.
1182
1183
    If it is unicode, it is returned.
4204.2.1 by Matt Nordhoff
Fix a broken sentence in osutils.safe_unicode's docstring
1184
    Otherwise it is decoded from utf-8. If decoding fails, the exception is
1185
    wrapped in a BzrBadParameterNotUnicode exception.
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
1186
    """
1187
    if isinstance(unicode_or_utf8_string, unicode):
1188
        return unicode_or_utf8_string
1189
    try:
1190
        return unicode_or_utf8_string.decode('utf8')
1191
    except UnicodeDecodeError:
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
1192
        raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
1193
1194
2249.5.8 by John Arbash Meinel
Add osutils.safe_utf8 and safe_revision_id for the new revision_id work.
1195
def safe_utf8(unicode_or_utf8_string):
1196
    """Coerce unicode_or_utf8_string to a utf8 string.
1197
1198
    If it is a str, it is returned.
1199
    If it is Unicode, it is encoded into a utf-8 string.
1200
    """
1201
    if isinstance(unicode_or_utf8_string, str):
1202
        # TODO: jam 20070209 This is overkill, and probably has an impact on
1203
        #       performance if we are dealing with lots of apis that want a
1204
        #       utf-8 revision id
1205
        try:
1206
            # Make sure it is a valid utf-8 string
1207
            unicode_or_utf8_string.decode('utf-8')
1208
        except UnicodeDecodeError:
1209
            raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
1210
        return unicode_or_utf8_string
1211
    return unicode_or_utf8_string.encode('utf-8')
1212
1213
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
1214
_revision_id_warning = ('Unicode revision ids were deprecated in bzr 0.15.'
1215
                        ' Revision id generators should be creating utf8'
1216
                        ' revision ids.')
1217
1218
1219
def safe_revision_id(unicode_or_utf8_string, warn=True):
2249.5.8 by John Arbash Meinel
Add osutils.safe_utf8 and safe_revision_id for the new revision_id work.
1220
    """Revision ids should now be utf8, but at one point they were unicode.
1221
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
1222
    :param unicode_or_utf8_string: A possibly Unicode revision_id. (can also be
1223
        utf8 or None).
1224
    :param warn: Functions that are sanitizing user data can set warn=False
1225
    :return: None or a utf8 revision id.
2249.5.8 by John Arbash Meinel
Add osutils.safe_utf8 and safe_revision_id for the new revision_id work.
1226
    """
2309.4.3 by John Arbash Meinel
(broken) change safe_*_id to emit a warning.
1227
    if (unicode_or_utf8_string is None
1228
        or unicode_or_utf8_string.__class__ == str):
1229
        return unicode_or_utf8_string
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
1230
    if warn:
1231
        symbol_versioning.warn(_revision_id_warning, DeprecationWarning,
1232
                               stacklevel=2)
2309.4.3 by John Arbash Meinel
(broken) change safe_*_id to emit a warning.
1233
    return cache_utf8.encode(unicode_or_utf8_string)
1234
1235
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
1236
_file_id_warning = ('Unicode file ids were deprecated in bzr 0.15. File id'
1237
                    ' generators should be creating utf8 file ids.')
1238
1239
1240
def safe_file_id(unicode_or_utf8_string, warn=True):
2309.4.3 by John Arbash Meinel
(broken) change safe_*_id to emit a warning.
1241
    """File ids should now be utf8, but at one point they were unicode.
1242
1243
    This is the same as safe_utf8, except it uses the cached encode functions
1244
    to save a little bit of performance.
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
1245
1246
    :param unicode_or_utf8_string: A possibly Unicode file_id. (can also be
1247
        utf8 or None).
1248
    :param warn: Functions that are sanitizing user data can set warn=False
1249
    :return: None or a utf8 file id.
2309.4.3 by John Arbash Meinel
(broken) change safe_*_id to emit a warning.
1250
    """
1251
    if (unicode_or_utf8_string is None
1252
        or unicode_or_utf8_string.__class__ == str):
1253
        return unicode_or_utf8_string
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
1254
    if warn:
1255
        symbol_versioning.warn(_file_id_warning, DeprecationWarning,
1256
                               stacklevel=2)
2309.4.3 by John Arbash Meinel
(broken) change safe_*_id to emit a warning.
1257
    return cache_utf8.encode(unicode_or_utf8_string)
2294.1.4 by John Arbash Meinel
Add safe_file_id as a helper in osutils.
1258
1259
1185.85.75 by John Arbash Meinel
Adding bzrlib.osutils.unicode_filename to handle unicode normalization for file paths.
1260
_platform_normalizes_filenames = False
1261
if sys.platform == 'darwin':
1262
    _platform_normalizes_filenames = True
1263
1264
1265
def normalizes_filenames():
1266
    """Return True if this platform normalizes unicode filenames.
1267
1268
    Mac OSX does, Windows/Linux do not.
1269
    """
1270
    return _platform_normalizes_filenames
1271
1272
1830.3.2 by John Arbash Meinel
normalized_filename is a much better name
1273
def _accessible_normalized_filename(path):
1830.3.1 by John Arbash Meinel
Change the return value of unicode_filename, and make it testable on all platforms
1274
    """Get the unicode normalized path, and if you can access the file.
1275
1276
    On platforms where the system normalizes filenames (Mac OSX),
1277
    you can access a file by any path which will normalize correctly.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1278
    On platforms where the system does not normalize filenames
1830.3.1 by John Arbash Meinel
Change the return value of unicode_filename, and make it testable on all platforms
1279
    (Windows, Linux), you have to access a file by its exact path.
1280
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1281
    Internally, bzr only supports NFC normalization, since that is
1830.3.1 by John Arbash Meinel
Change the return value of unicode_filename, and make it testable on all platforms
1282
    the standard for XML documents.
1283
1284
    So return the normalized path, and a flag indicating if the file
1285
    can be accessed by that path.
1286
    """
1287
3201.1.1 by jameinel
Fix bug #185458, switch from NFKC to NFC and add tests for filenames that would be broken under NFKC
1288
    return unicodedata.normalize('NFC', unicode(path)), True
1830.3.1 by John Arbash Meinel
Change the return value of unicode_filename, and make it testable on all platforms
1289
1290
1830.3.2 by John Arbash Meinel
normalized_filename is a much better name
1291
def _inaccessible_normalized_filename(path):
1292
    __doc__ = _accessible_normalized_filename.__doc__
1830.3.1 by John Arbash Meinel
Change the return value of unicode_filename, and make it testable on all platforms
1293
3201.1.1 by jameinel
Fix bug #185458, switch from NFKC to NFC and add tests for filenames that would be broken under NFKC
1294
    normalized = unicodedata.normalize('NFC', unicode(path))
1830.3.1 by John Arbash Meinel
Change the return value of unicode_filename, and make it testable on all platforms
1295
    return normalized, normalized == path
1296
1297
1185.85.75 by John Arbash Meinel
Adding bzrlib.osutils.unicode_filename to handle unicode normalization for file paths.
1298
if _platform_normalizes_filenames:
1830.3.2 by John Arbash Meinel
normalized_filename is a much better name
1299
    normalized_filename = _accessible_normalized_filename
1185.85.75 by John Arbash Meinel
Adding bzrlib.osutils.unicode_filename to handle unicode normalization for file paths.
1300
else:
1830.3.2 by John Arbash Meinel
normalized_filename is a much better name
1301
    normalized_filename = _inaccessible_normalized_filename
1185.85.75 by John Arbash Meinel
Adding bzrlib.osutils.unicode_filename to handle unicode normalization for file paths.
1302
1303
1185.33.60 by Martin Pool
Use full terminal width for verbose test output.
1304
def terminal_width():
1305
    """Return estimated terminal width."""
1704.2.3 by Martin Pool
(win32) Detect terminal width using GetConsoleScreenBufferInfo (Alexander)
1306
    if sys.platform == 'win32':
2245.4.6 by Alexander Belchenko
osutils.py: terminal_width() now use win32utils.get_console_size()
1307
        return win32utils.get_console_size()[0]
1704.2.2 by Martin Pool
Detect terminal width using ioctl
1308
    width = 0
1185.33.60 by Martin Pool
Use full terminal width for verbose test output.
1309
    try:
1704.2.2 by Martin Pool
Detect terminal width using ioctl
1310
        import struct, fcntl, termios
1311
        s = struct.pack('HHHH', 0, 0, 0, 0)
1312
        x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
1313
        width = struct.unpack('HHHH', x)[1]
1314
    except IOError:
1315
        pass
1316
    if width <= 0:
1317
        try:
1318
            width = int(os.environ['COLUMNS'])
1319
        except:
1320
            pass
1321
    if width <= 0:
1322
        width = 80
1323
1324
    return width
1534.7.25 by Aaron Bentley
Added set_executability
1325
1963.1.5 by John Arbash Meinel
Create an osutils helper function for modifying the environment
1326
1534.7.25 by Aaron Bentley
Added set_executability
1327
def supports_executable():
1534.7.160 by Aaron Bentley
Changed implementation of supports_executable
1328
    return sys.platform != "win32"
1551.2.53 by abentley
Strip trailing slashes in a platform-sensible way
1329
1330
1551.10.4 by Aaron Bentley
Update to skip on win32
1331
def supports_posix_readonly():
1332
    """Return True if 'readonly' has POSIX semantics, False otherwise.
1333
1334
    Notably, a win32 readonly file cannot be deleted, unlike POSIX where the
1335
    directory controls creation/deletion, etc.
1336
1337
    And under win32, readonly means that the directory itself cannot be
1338
    deleted.  The contents of a readonly directory can be changed, unlike POSIX
1339
    where files in readonly directories cannot be added, deleted or renamed.
1340
    """
1341
    return sys.platform != "win32"
1342
1343
1963.1.5 by John Arbash Meinel
Create an osutils helper function for modifying the environment
1344
def set_or_unset_env(env_variable, value):
1345
    """Modify the environment, setting or removing the env_variable.
1346
1347
    :param env_variable: The environment variable in question
1348
    :param value: The value to set the environment to. If None, then
1349
        the variable will be removed.
1350
    :return: The original value of the environment variable.
1351
    """
1352
    orig_val = os.environ.get(env_variable)
1353
    if value is None:
1354
        if orig_val is not None:
1355
            del os.environ[env_variable]
1356
    else:
1357
        if isinstance(value, unicode):
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
1358
            value = value.encode(get_user_encoding())
1963.1.5 by John Arbash Meinel
Create an osutils helper function for modifying the environment
1359
        os.environ[env_variable] = value
1360
    return orig_val
1361
1362
1551.2.56 by Aaron Bentley
Better illegal pathname check for Windows
1363
_validWin32PathRE = re.compile(r'^([A-Za-z]:[/\\])?[^:<>*"?\|]*$')
1364
1365
1366
def check_legal_path(path):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1367
    """Check whether the supplied path is legal.
1551.2.56 by Aaron Bentley
Better illegal pathname check for Windows
1368
    This is only required on Windows, so we don't test on other platforms
1369
    right now.
1370
    """
1371
    if sys.platform != "win32":
1372
        return
1373
    if _validWin32PathRE.match(path) is None:
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
1374
        raise errors.IllegalPath(path)
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1375
1376
3596.2.2 by John Arbash Meinel
Factor out the common exception handling looking for ENOTDIR and use it
1377
_WIN32_ERROR_DIRECTORY = 267 # Similar to errno.ENOTDIR
1378
1379
def _is_error_enotdir(e):
1380
    """Check if this exception represents ENOTDIR.
1381
1382
    Unfortunately, python is very inconsistent about the exception
1383
    here. The cases are:
1384
      1) Linux, Mac OSX all versions seem to set errno == ENOTDIR
1385
      2) Windows, Python2.4, uses errno == ERROR_DIRECTORY (267)
1386
         which is the windows error code.
1387
      3) Windows, Python2.5 uses errno == EINVAL and
1388
         winerror == ERROR_DIRECTORY
1389
1390
    :param e: An Exception object (expected to be OSError with an errno
1391
        attribute, but we should be able to cope with anything)
1392
    :return: True if this represents an ENOTDIR error. False otherwise.
1393
    """
1394
    en = getattr(e, 'errno', None)
1395
    if (en == errno.ENOTDIR
1396
        or (sys.platform == 'win32'
1397
            and (en == _WIN32_ERROR_DIRECTORY
1398
                 or (en == errno.EINVAL
1399
                     and getattr(e, 'winerror', None) == _WIN32_ERROR_DIRECTORY)
1400
        ))):
1401
        return True
1402
    return False
1403
1404
1757.2.8 by Robert Collins
Teach walkdirs to walk a subdir of a tree.
1405
def walkdirs(top, prefix=""):
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1406
    """Yield data about all the directories in a tree.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1407
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1408
    This yields all the data about the contents of a directory at a time.
1409
    After each directory has been yielded, if the caller has mutated the list
1410
    to exclude some directories, they are then not descended into.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1411
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1412
    The data yielded is of the form:
1897.1.2 by Robert Collins
cleanup osutils.walkdirs changes after review.
1413
    ((directory-relpath, directory-path-from-top),
2694.4.1 by Alexander Belchenko
trivial fix for docstring of osutils.walkdirs()
1414
    [(relpath, basename, kind, lstat, path-from-top), ...]),
1897.1.2 by Robert Collins
cleanup osutils.walkdirs changes after review.
1415
     - directory-relpath is the relative path of the directory being returned
1416
       with respect to top. prefix is prepended to this.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1417
     - directory-path-from-root is the path including top for this directory.
1897.1.2 by Robert Collins
cleanup osutils.walkdirs changes after review.
1418
       It is suitable for use with os functions.
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
1419
     - relpath is the relative path within the subtree being walked.
1420
     - basename is the basename of the path
1897.1.2 by Robert Collins
cleanup osutils.walkdirs changes after review.
1421
     - kind is the kind of the file now. If unknown then the file is not
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
1422
       present within the tree - but it may be recorded as versioned. See
1423
       versioned_kind.
1424
     - lstat is the stat data *if* the file was statted.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1425
     - planned, not implemented:
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
1426
       path_from_tree_root is the path from the root of the tree.
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1427
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1428
    :param prefix: Prefix the relpaths that are yielded with 'prefix'. This
1757.2.16 by Robert Collins
Review comments.
1429
        allows one to walk a subtree but get paths that are relative to a tree
1430
        rooted higher up.
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1431
    :return: an iterator over the dirs.
1432
    """
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
1433
    #TODO there is a bit of a smell where the results of the directory-
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1434
    # summary in this, and the path from the root, may not agree
1897.1.1 by Robert Collins
Add some useful summary data to osutils.walkdirs output.
1435
    # depending on top and prefix - i.e. ./foo and foo as a pair leads to
1436
    # potentially confusing output. We should make this more robust - but
1897.1.2 by Robert Collins
cleanup osutils.walkdirs changes after review.
1437
    # not at a speed cost. RBC 20060731
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1438
    _lstat = os.lstat
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1439
    _directory = _directory_kind
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
1440
    _listdir = os.listdir
3696.3.5 by Robert Collins
Streamline _walkdirs_utf8 for utf8 file systems, reducing time to traverse a mozilla tree from 1s to .6 seconds. (Robert Collins)
1441
    _kind_from_mode = file_kind_from_stat_mode
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1442
    pending = [(safe_unicode(prefix), "", _directory, None, safe_unicode(top))]
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1443
    while pending:
1444
        # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1445
        relroot, _, _, _, top = pending.pop()
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1446
        if relroot:
1447
            relprefix = relroot + u'/'
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1448
        else:
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1449
            relprefix = ''
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1450
        top_slash = top + u'/'
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1451
1452
        dirblock = []
1453
        append = dirblock.append
3585.2.4 by Robert Collins
* Deleting directories by hand before running ``bzr rm`` will not
1454
        try:
1455
            names = sorted(_listdir(top))
3596.2.2 by John Arbash Meinel
Factor out the common exception handling looking for ENOTDIR and use it
1456
        except OSError, e:
1457
            if not _is_error_enotdir(e):
3585.2.4 by Robert Collins
* Deleting directories by hand before running ``bzr rm`` will not
1458
                raise
1459
        else:
1460
            for name in names:
1461
                abspath = top_slash + name
1462
                statvalue = _lstat(abspath)
3696.3.5 by Robert Collins
Streamline _walkdirs_utf8 for utf8 file systems, reducing time to traverse a mozilla tree from 1s to .6 seconds. (Robert Collins)
1463
                kind = _kind_from_mode(statvalue.st_mode)
3585.2.4 by Robert Collins
* Deleting directories by hand before running ``bzr rm`` will not
1464
                append((relprefix + name, name, kind, statvalue, abspath))
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1465
        yield (relroot, top), dirblock
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1466
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
1467
        # push the user specified dirs from dirblock
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1468
        pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1773.3.1 by Robert Collins
Add path_prefix_key and compare_paths_prefix_order utility functions.
1469
1470
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1471
class DirReader(object):
1472
    """An interface for reading directories."""
1473
1474
    def top_prefix_to_starting_dir(self, top, prefix=""):
1475
        """Converts top and prefix to a starting dir entry
1476
1477
        :param top: A utf8 path
1478
        :param prefix: An optional utf8 path to prefix output relative paths
1479
            with.
1480
        :return: A tuple starting with prefix, and ending with the native
1481
            encoding of top.
1482
        """
1483
        raise NotImplementedError(self.top_prefix_to_starting_dir)
1484
1485
    def read_dir(self, prefix, top):
1486
        """Read a specific dir.
1487
1488
        :param prefix: A utf8 prefix to be preprended to the path basenames.
1489
        :param top: A natively encoded path to read.
3696.3.10 by Robert Collins
Review feedback.
1490
        :return: A list of the directories contents. Each item contains:
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1491
            (utf8_relpath, utf8_name, kind, lstatvalue, native_abspath)
1492
        """
1493
        raise NotImplementedError(self.read_dir)
1494
1495
1496
_selected_dir_reader = None
1497
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1498
2255.7.27 by John Arbash Meinel
Add a _walkdirs_utf8 which returns utf8 paths instead of Unicode. Approx 20% faster in walking utf8 filesystems
1499
def _walkdirs_utf8(top, prefix=""):
1500
    """Yield data about all the directories in a tree.
1501
1502
    This yields the same information as walkdirs() only each entry is yielded
1503
    in utf-8. On platforms which have a filesystem encoding of utf8 the paths
1504
    are returned as exact byte-strings.
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1505
1506
    :return: yields a tuple of (dir_info, [file_info])
1507
        dir_info is (utf8_relpath, path-from-top)
1508
        file_info is (utf8_relpath, utf8_name, kind, lstat, path-from-top)
1509
        if top is an absolute path, path-from-top is also an absolute path.
1510
        path-from-top might be unicode or utf8, but it is the correct path to
1511
        pass to os functions to affect the file in question. (such as os.lstat)
1512
    """
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1513
    global _selected_dir_reader
1514
    if _selected_dir_reader is None:
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1515
        fs_encoding = _fs_enc.upper()
3224.5.17 by Andrew Bennetts
Avoid importing win32utils when sys.platform != win32
1516
        if sys.platform == "win32" and win32utils.winver == 'Windows NT':
3557.2.4 by John Arbash Meinel
Cleanup the tests a bit, and add a test that we downgrade if os.name isn't 'nt'
1517
            # Win98 doesn't have unicode apis like FindFirstFileW
1518
            # TODO: We possibly could support Win98 by falling back to the
1519
            #       original FindFirstFile, and using TCHAR instead of WCHAR,
1520
            #       but that gets a bit tricky, and requires custom compiling
1521
            #       for win98 anyway.
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1522
            try:
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1523
                from bzrlib._walkdirs_win32 import Win32ReadDir
1524
                _selected_dir_reader = Win32ReadDir()
4241.14.6 by Vincent Ladeuil
Start DirReader parametrized tests.
1525
            except ImportError:
1526
                pass
1527
        elif fs_encoding in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
3557.2.3 by John Arbash Meinel
Change the logic for selecting a real _walkdirs_utf8 implementation,
1528
            # ANSI_X3.4-1968 is a form of ASCII
3696.3.5 by Robert Collins
Streamline _walkdirs_utf8 for utf8 file systems, reducing time to traverse a mozilla tree from 1s to .6 seconds. (Robert Collins)
1529
            try:
1530
                from bzrlib._readdir_pyx import UTF8DirReader
1531
                _selected_dir_reader = UTF8DirReader()
4574.3.6 by Martin Pool
More warnings when failing to load extensions
1532
            except ImportError, e:
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
1533
                failed_to_load_extension(e)
4241.14.6 by Vincent Ladeuil
Start DirReader parametrized tests.
1534
                pass
1535
1536
    if _selected_dir_reader is None:
1537
        # Fallback to the python version
1538
        _selected_dir_reader = UnicodeDirReader()
1539
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1540
    # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1541
    # But we don't actually uses 1-3 in pending, so set them to None
3696.3.5 by Robert Collins
Streamline _walkdirs_utf8 for utf8 file systems, reducing time to traverse a mozilla tree from 1s to .6 seconds. (Robert Collins)
1542
    pending = [[_selected_dir_reader.top_prefix_to_starting_dir(top, prefix)]]
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1543
    read_dir = _selected_dir_reader.read_dir
1544
    _directory = _directory_kind
2255.7.27 by John Arbash Meinel
Add a _walkdirs_utf8 which returns utf8 paths instead of Unicode. Approx 20% faster in walking utf8 filesystems
1545
    while pending:
3696.3.5 by Robert Collins
Streamline _walkdirs_utf8 for utf8 file systems, reducing time to traverse a mozilla tree from 1s to .6 seconds. (Robert Collins)
1546
        relroot, _, _, _, top = pending[-1].pop()
1547
        if not pending[-1]:
1548
            pending.pop()
1549
        dirblock = sorted(read_dir(relroot, top))
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1550
        yield (relroot, top), dirblock
1551
        # push the user specified dirs from dirblock
3696.3.5 by Robert Collins
Streamline _walkdirs_utf8 for utf8 file systems, reducing time to traverse a mozilla tree from 1s to .6 seconds. (Robert Collins)
1552
        next = [d for d in reversed(dirblock) if d[2] == _directory]
1553
        if next:
1554
            pending.append(next)
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1555
1556
1557
class UnicodeDirReader(DirReader):
1558
    """A dir reader for non-utf8 file systems, which transcodes."""
1559
1560
    __slots__ = ['_utf8_encode']
1561
1562
    def __init__(self):
1563
        self._utf8_encode = codecs.getencoder('utf8')
1564
1565
    def top_prefix_to_starting_dir(self, top, prefix=""):
1566
        """See DirReader.top_prefix_to_starting_dir."""
1567
        return (safe_utf8(prefix), None, None, None, safe_unicode(top))
1568
1569
    def read_dir(self, prefix, top):
1570
        """Read a single directory from a non-utf8 file system.
1571
1572
        top, and the abspath element in the output are unicode, all other paths
1573
        are utf8. Local disk IO is done via unicode calls to listdir etc.
1574
1575
        This is currently the fallback code path when the filesystem encoding is
1576
        not UTF-8. It may be better to implement an alternative so that we can
1577
        safely handle paths that are not properly decodable in the current
1578
        encoding.
1579
1580
        See DirReader.read_dir for details.
1581
        """
1582
        _utf8_encode = self._utf8_encode
1583
        _lstat = os.lstat
1584
        _listdir = os.listdir
3696.3.5 by Robert Collins
Streamline _walkdirs_utf8 for utf8 file systems, reducing time to traverse a mozilla tree from 1s to .6 seconds. (Robert Collins)
1585
        _kind_from_mode = file_kind_from_stat_mode
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1586
1587
        if prefix:
1588
            relprefix = prefix + '/'
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1589
        else:
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1590
            relprefix = ''
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1591
        top_slash = top + u'/'
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1592
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1593
        dirblock = []
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1594
        append = dirblock.append
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1595
        for name in sorted(_listdir(top)):
3696.3.12 by Robert Collins
Fix PQM test failure.
1596
            try:
1597
                name_utf8 = _utf8_encode(name)[0]
1598
            except UnicodeDecodeError:
1599
                raise errors.BadFilenameEncoding(
1600
                    _utf8_encode(relprefix)[0] + name, _fs_enc)
2255.7.32 by John Arbash Meinel
Add tests that the walkdirs variants work on unicode paths.
1601
            abspath = top_slash + name
1602
            statvalue = _lstat(abspath)
3696.3.5 by Robert Collins
Streamline _walkdirs_utf8 for utf8 file systems, reducing time to traverse a mozilla tree from 1s to .6 seconds. (Robert Collins)
1603
            kind = _kind_from_mode(statvalue.st_mode)
2255.7.33 by John Arbash Meinel
More inner loop tuning of walkdirs, can save as much as 5%
1604
            append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
3696.3.1 by Robert Collins
Refactor bzrlib.osutils._walkdirs_utf8 to aid API migration in future.
1605
        return dirblock
2255.7.27 by John Arbash Meinel
Add a _walkdirs_utf8 which returns utf8 paths instead of Unicode. Approx 20% faster in walking utf8 filesystems
1606
1607
1907.3.2 by John Arbash Meinel
Updated the copy_tree function to allow overriding functionality.
1608
def copy_tree(from_path, to_path, handlers={}):
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1609
    """Copy all of the entries in from_path into to_path.
1610
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1611
    :param from_path: The base directory to copy.
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1612
    :param to_path: The target directory. If it does not exist, it will
1613
        be created.
1907.3.2 by John Arbash Meinel
Updated the copy_tree function to allow overriding functionality.
1614
    :param handlers: A dictionary of functions, which takes a source and
1615
        destinations for files, directories, etc.
1616
        It is keyed on the file kind, such as 'directory', 'symlink', or 'file'
1617
        'file', 'directory', and 'symlink' should always exist.
1618
        If they are missing, they will be replaced with 'os.mkdir()',
1619
        'os.readlink() + os.symlink()', and 'shutil.copy2()', respectively.
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1620
    """
1621
    # Now, just copy the existing cached tree to the new location
1622
    # We use a cheap trick here.
1623
    # Absolute paths are prefixed with the first parameter
1624
    # relative paths are prefixed with the second.
1625
    # So we can get both the source and target returned
1626
    # without any extra work.
1627
1907.3.2 by John Arbash Meinel
Updated the copy_tree function to allow overriding functionality.
1628
    def copy_dir(source, dest):
1629
        os.mkdir(dest)
1630
1631
    def copy_link(source, dest):
1632
        """Copy the contents of a symlink"""
1633
        link_to = os.readlink(source)
1634
        os.symlink(link_to, dest)
1635
1636
    real_handlers = {'file':shutil.copy2,
1637
                     'symlink':copy_link,
1638
                     'directory':copy_dir,
1639
                    }
1640
    real_handlers.update(handlers)
1641
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1642
    if not os.path.exists(to_path):
1907.3.2 by John Arbash Meinel
Updated the copy_tree function to allow overriding functionality.
1643
        real_handlers['directory'](from_path, to_path)
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1644
1645
    for dir_info, entries in walkdirs(from_path, prefix=to_path):
1646
        for relpath, name, kind, st, abspath in entries:
1907.3.2 by John Arbash Meinel
Updated the copy_tree function to allow overriding functionality.
1647
            real_handlers[kind](abspath, relpath)
1907.3.1 by John Arbash Meinel
create a copy_tree wrapper around walkdirs()
1648
1649
1773.3.1 by Robert Collins
Add path_prefix_key and compare_paths_prefix_order utility functions.
1650
def path_prefix_key(path):
1651
    """Generate a prefix-order path key for path.
1652
1653
    This can be used to sort paths in the same way that walkdirs does.
1654
    """
1773.3.2 by Robert Collins
New corner case from John Meinel, showing up the need to check the directory lexographically outside of a single tree's root. Fixed.
1655
    return (dirname(path) , path)
1773.3.1 by Robert Collins
Add path_prefix_key and compare_paths_prefix_order utility functions.
1656
1657
1658
def compare_paths_prefix_order(path_a, path_b):
1659
    """Compare path_a and path_b to generate the same order walkdirs uses."""
1660
    key_a = path_prefix_key(path_a)
1661
    key_b = path_prefix_key(path_b)
1662
    return cmp(key_a, key_b)
1955.2.2 by John Arbash Meinel
Change the name of the test classes (test_lang => test_locale), move the function into osutils.py
1663
1664
1665
_cached_user_encoding = None
1666
1667
2192.1.3 by Alexander Belchenko
Tests for osutils.get_user_encoding
1668
def get_user_encoding(use_cache=True):
1955.2.2 by John Arbash Meinel
Change the name of the test classes (test_lang => test_locale), move the function into osutils.py
1669
    """Find out what the preferred user encoding is.
1670
1671
    This is generally the encoding that is used for command line parameters
1672
    and file contents. This may be different from the terminal encoding
1673
    or the filesystem encoding.
1674
2192.1.3 by Alexander Belchenko
Tests for osutils.get_user_encoding
1675
    :param  use_cache:  Enable cache for detected encoding.
1676
                        (This parameter is turned on by default,
1677
                        and required only for selftesting)
1678
1955.2.2 by John Arbash Meinel
Change the name of the test classes (test_lang => test_locale), move the function into osutils.py
1679
    :return: A string defining the preferred user encoding
1680
    """
1681
    global _cached_user_encoding
2192.1.3 by Alexander Belchenko
Tests for osutils.get_user_encoding
1682
    if _cached_user_encoding is not None and use_cache:
1955.2.2 by John Arbash Meinel
Change the name of the test classes (test_lang => test_locale), move the function into osutils.py
1683
        return _cached_user_encoding
1684
1685
    if sys.platform == 'darwin':
3638.3.10 by Vincent Ladeuil
Provides a better default encoding on OSX.
1686
        # python locale.getpreferredencoding() always return
1687
        # 'mac-roman' on darwin. That's a lie.
1955.2.2 by John Arbash Meinel
Change the name of the test classes (test_lang => test_locale), move the function into osutils.py
1688
        sys.platform = 'posix'
1689
        try:
3638.3.10 by Vincent Ladeuil
Provides a better default encoding on OSX.
1690
            if os.environ.get('LANG', None) is None:
1691
                # If LANG is not set, we end up with 'ascii', which is bad
1692
                # ('mac-roman' is more than ascii), so we set a default which
1693
                # will give us UTF-8 (which appears to work in all cases on
1694
                # OSX). Users are still free to override LANG of course, as
1695
                # long as it give us something meaningful. This work-around
1696
                # *may* not be needed with python 3k and/or OSX 10.5, but will
1697
                # work with them too -- vila 20080908
1698
                os.environ['LANG'] = 'en_US.UTF-8'
1955.2.2 by John Arbash Meinel
Change the name of the test classes (test_lang => test_locale), move the function into osutils.py
1699
            import locale
1700
        finally:
1701
            sys.platform = 'darwin'
1702
    else:
1703
        import locale
1704
1705
    try:
2192.1.3 by Alexander Belchenko
Tests for osutils.get_user_encoding
1706
        user_encoding = locale.getpreferredencoding()
1955.2.2 by John Arbash Meinel
Change the name of the test classes (test_lang => test_locale), move the function into osutils.py
1707
    except locale.Error, e:
1955.2.3 by John Arbash Meinel
Change error message text
1708
        sys.stderr.write('bzr: warning: %s\n'
2001.2.1 by Jelmer Vernooij
Fix typo in encoding warning.
1709
                         '  Could not determine what text encoding to use.\n'
1955.2.3 by John Arbash Meinel
Change error message text
1710
                         '  This error usually means your Python interpreter\n'
1711
                         '  doesn\'t support the locale set by $LANG (%s)\n'
1712
                         "  Continuing with ascii encoding.\n"
1955.2.2 by John Arbash Meinel
Change the name of the test classes (test_lang => test_locale), move the function into osutils.py
1713
                         % (e, os.environ.get('LANG')))
2192.1.7 by Alexander Belchenko
get_user_encoding: if locale.Error raised we need to set user_encoding to 'ascii' as warning says
1714
        user_encoding = 'ascii'
1955.2.2 by John Arbash Meinel
Change the name of the test classes (test_lang => test_locale), move the function into osutils.py
1715
2127.4.1 by Alexander Belchenko
(jam, bialix) Workaround for cp0 console encoding on Windows
1716
    # Windows returns 'cp0' to indicate there is no code page. So we'll just
1717
    # treat that as ASCII, and not support printing unicode characters to the
1718
    # console.
3405.3.1 by Neil Martinsen-Burrell
accept for an encoding to mean ascii
1719
    #
1720
    # For python scripts run under vim, we get '', so also treat that as ASCII
1721
    if user_encoding in (None, 'cp0', ''):
2192.1.3 by Alexander Belchenko
Tests for osutils.get_user_encoding
1722
        user_encoding = 'ascii'
2192.1.1 by Alexander Belchenko
Before actually using encoding need to check that Python has corresponding codec
1723
    else:
1724
        # check encoding
1725
        try:
2192.1.3 by Alexander Belchenko
Tests for osutils.get_user_encoding
1726
            codecs.lookup(user_encoding)
2192.1.1 by Alexander Belchenko
Before actually using encoding need to check that Python has corresponding codec
1727
        except LookupError:
1728
            sys.stderr.write('bzr: warning:'
1729
                             ' unknown encoding %s.'
1730
                             ' Continuing with ascii encoding.\n'
2192.1.3 by Alexander Belchenko
Tests for osutils.get_user_encoding
1731
                             % user_encoding
2192.1.1 by Alexander Belchenko
Before actually using encoding need to check that Python has corresponding codec
1732
                            )
2192.1.3 by Alexander Belchenko
Tests for osutils.get_user_encoding
1733
            user_encoding = 'ascii'
1734
1735
    if use_cache:
1736
        _cached_user_encoding = user_encoding
1737
1738
    return user_encoding
2091.1.1 by Martin Pool
Avoid MSG_WAITALL as it doesn't work on Windows
1739
1740
3626.1.1 by Mark Hammond
Add osutils.get_host_name() to return a unicode hostname to prevent
1741
def get_host_name():
3626.1.4 by John Arbash Meinel
Document the difference in get_host_name, per Robert's request.
1742
    """Return the current unicode host name.
1743
1744
    This is meant to be used in place of socket.gethostname() because that
1745
    behaves inconsistently on different platforms.
1746
    """
3626.1.1 by Mark Hammond
Add osutils.get_host_name() to return a unicode hostname to prevent
1747
    if sys.platform == "win32":
1748
        import win32utils
1749
        return win32utils.get_host_name()
1750
    else:
1751
        import socket
1752
        return socket.gethostname().decode(get_user_encoding())
1753
1754
2091.1.1 by Martin Pool
Avoid MSG_WAITALL as it doesn't work on Windows
1755
def recv_all(socket, bytes):
1756
    """Receive an exact number of bytes.
1757
1758
    Regular Socket.recv() may return less than the requested number of bytes,
1759
    dependning on what's in the OS buffer.  MSG_WAITALL is not available
1760
    on all platforms, but this should work everywhere.  This will return
1761
    less than the requested amount if the remote end closes.
1762
1763
    This isn't optimized and is intended mostly for use in testing.
1764
    """
1765
    b = ''
1766
    while len(b) < bytes:
3923.3.1 by Andrew Bennetts
Quick attempt at adding some EINTR-proofing to smart protocol code.
1767
        new = until_no_eintr(socket.recv, bytes - len(b))
2091.1.1 by Martin Pool
Avoid MSG_WAITALL as it doesn't work on Windows
1768
        if new == '':
1769
            break # eof
1770
        b += new
1771
    return b
1772
3118.2.1 by Andrew Bennetts
(andrew) Fix #115781 by passing no more than 64k at a time to socket.sendall.
1773
3958.1.5 by Andrew Bennetts
Remove unnecessary 'direction' argument to osutils.send_all.
1774
def send_all(socket, bytes, report_activity=None):
3118.2.1 by Andrew Bennetts
(andrew) Fix #115781 by passing no more than 64k at a time to socket.sendall.
1775
    """Send all bytes on a socket.
1776
1777
    Regular socket.sendall() can give socket error 10053 on Windows.  This
1778
    implementation sends no more than 64k at a time, which avoids this problem.
3958.1.1 by Andrew Bennetts
Report traffic on smart media as transport activity.
1779
1780
    :param report_activity: Call this as bytes are read, see
1781
        Transport._report_activity
3118.2.1 by Andrew Bennetts
(andrew) Fix #115781 by passing no more than 64k at a time to socket.sendall.
1782
    """
1783
    chunk_size = 2**16
1784
    for pos in xrange(0, len(bytes), chunk_size):
3958.1.1 by Andrew Bennetts
Report traffic on smart media as transport activity.
1785
        block = bytes[pos:pos+chunk_size]
1786
        if report_activity is not None:
3958.1.5 by Andrew Bennetts
Remove unnecessary 'direction' argument to osutils.send_all.
1787
            report_activity(len(block), 'write')
3958.1.1 by Andrew Bennetts
Report traffic on smart media as transport activity.
1788
        until_no_eintr(socket.sendall, block)
3118.2.1 by Andrew Bennetts
(andrew) Fix #115781 by passing no more than 64k at a time to socket.sendall.
1789
1790
2091.3.7 by Aaron Bentley
Rename real_parent to dereferenced_path
1791
def dereference_path(path):
1792
    """Determine the real path to a file.
1793
1794
    All parent elements are dereferenced.  But the file itself is not
1795
    dereferenced.
1796
    :param path: The original path.  May be absolute or relative.
1797
    :return: the real path *to* the file
1798
    """
2091.3.5 by Aaron Bentley
Move realpath functionality into osutils
1799
    parent, base = os.path.split(path)
1800
    # The pathjoin for '.' is a workaround for Python bug #1213894.
1801
    # (initial path components aren't dereferenced)
1802
    return pathjoin(realpath(pathjoin('.', parent)), base)
2681.3.4 by Lukáš Lalinsky
- Rename 'windows' to 'mapi'
1803
1804
1805
def supports_mapi():
1806
    """Return True if we can use MAPI to launch a mail client."""
1807
    return sys.platform == "win32"
3089.3.8 by Ian Clatworthy
move resource loading into a reusable function
1808
1809
1810
def resource_string(package, resource_name):
1811
    """Load a resource from a package and return it as a string.
1812
1813
    Note: Only packages that start with bzrlib are currently supported.
1814
1815
    This is designed to be a lightweight implementation of resource
1816
    loading in a way which is API compatible with the same API from
1817
    pkg_resources. See
1818
    http://peak.telecommunity.com/DevCenter/PkgResources#basic-resource-access.
1819
    If and when pkg_resources becomes a standard library, this routine
1820
    can delegate to it.
1821
    """
1822
    # Check package name is within bzrlib
1823
    if package == "bzrlib":
1824
        resource_relpath = resource_name
1825
    elif package.startswith("bzrlib."):
1826
        package = package[len("bzrlib."):].replace('.', os.sep)
1827
        resource_relpath = pathjoin(package, resource_name)
1828
    else:
1829
        raise errors.BzrError('resource package %s not in bzrlib' % package)
1830
1831
    # Map the resource to a file and read its contents
1832
    base = dirname(bzrlib.__file__)
1833
    if getattr(sys, 'frozen', None):    # bzr.exe
1834
        base = abspath(pathjoin(base, '..', '..'))
1835
    filename = pathjoin(base, resource_relpath)
1836
    return open(filename, 'rU').read()
1739.2.7 by Robert Collins
Update readdir pyrex source files and usage in line with current practice.
1837
1838
3696.3.5 by Robert Collins
Streamline _walkdirs_utf8 for utf8 file systems, reducing time to traverse a mozilla tree from 1s to .6 seconds. (Robert Collins)
1839
def file_kind_from_stat_mode_thunk(mode):
1840
    global file_kind_from_stat_mode
1841
    if file_kind_from_stat_mode is file_kind_from_stat_mode_thunk:
1842
        try:
1843
            from bzrlib._readdir_pyx import UTF8DirReader
1844
            file_kind_from_stat_mode = UTF8DirReader().kind_from_mode
4574.3.6 by Martin Pool
More warnings when failing to load extensions
1845
        except ImportError, e:
4694.2.1 by John Arbash Meinel
Fix bug #430645, don't issue a warning when failing to import _readdir_pyx the second time.
1846
            # This is one time where we won't warn that an extension failed to
1847
            # load. The extension is never available on Windows anyway.
3696.3.5 by Robert Collins
Streamline _walkdirs_utf8 for utf8 file systems, reducing time to traverse a mozilla tree from 1s to .6 seconds. (Robert Collins)
1848
            from bzrlib._readdir_py import (
3696.4.8 by Robert Collins
Fix up inter_changes with dirstate both C and python.
1849
                _kind_from_mode as file_kind_from_stat_mode
3696.3.5 by Robert Collins
Streamline _walkdirs_utf8 for utf8 file systems, reducing time to traverse a mozilla tree from 1s to .6 seconds. (Robert Collins)
1850
                )
1851
    return file_kind_from_stat_mode(mode)
1852
file_kind_from_stat_mode = file_kind_from_stat_mode_thunk
1853
1854
1855
def file_kind(f, _lstat=os.lstat):
1856
    try:
1857
        return file_kind_from_stat_mode(_lstat(f).st_mode)
1858
    except OSError, e:
1859
        if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
1860
            raise errors.NoSuchFile(f)
1861
        raise
1862
3923.3.1 by Andrew Bennetts
Quick attempt at adding some EINTR-proofing to smart protocol code.
1863
1864
def until_no_eintr(f, *a, **kw):
3923.3.2 by Andrew Bennetts
Use e.errno rather than e.args[0].
1865
    """Run f(*a, **kw), retrying if an EINTR error occurs."""
3923.3.1 by Andrew Bennetts
Quick attempt at adding some EINTR-proofing to smart protocol code.
1866
    # Borrowed from Twisted's twisted.python.util.untilConcludes function.
1867
    while True:
1868
        try:
1869
            return f(*a, **kw)
1870
        except (IOError, OSError), e:
3923.3.2 by Andrew Bennetts
Use e.errno rather than e.args[0].
1871
            if e.errno == errno.EINTR:
3923.3.1 by Andrew Bennetts
Quick attempt at adding some EINTR-proofing to smart protocol code.
1872
                continue
1873
            raise
1874
4183.6.4 by Martin Pool
Separate out re_compile_checked
1875
def re_compile_checked(re_string, flags=0, where=""):
1876
    """Return a compiled re, or raise a sensible error.
4325.3.2 by Johan Walles
Use a linear algorithm for osutil.minimum_path_selection().
1877
4183.6.4 by Martin Pool
Separate out re_compile_checked
1878
    This should only be used when compiling user-supplied REs.
1879
1880
    :param re_string: Text form of regular expression.
1881
    :param flags: eg re.IGNORECASE
4325.3.2 by Johan Walles
Use a linear algorithm for osutil.minimum_path_selection().
1882
    :param where: Message explaining to the user the context where
4183.6.4 by Martin Pool
Separate out re_compile_checked
1883
        it occurred, eg 'log search filter'.
1884
    """
1885
    # from https://bugs.launchpad.net/bzr/+bug/251352
1886
    try:
1887
        re_obj = re.compile(re_string, flags)
1888
        re_obj.search("")
1889
        return re_obj
1890
    except re.error, e:
1891
        if where:
1892
            where = ' in ' + where
1893
        # despite the name 'error' is a type
1894
        raise errors.BzrCommandError('Invalid regular expression%s: %r: %s'
1895
            % (where, re_string, e))
1896
3923.3.1 by Andrew Bennetts
Quick attempt at adding some EINTR-proofing to smart protocol code.
1897
0.16.79 by Aaron Bentley
Remove dependencies on bzrtools
1898
if sys.platform == "win32":
1899
    import msvcrt
1900
    def getchar():
1901
        return msvcrt.getch()
1902
else:
1903
    import tty
1904
    import termios
1905
    def getchar():
1906
        fd = sys.stdin.fileno()
1907
        settings = termios.tcgetattr(fd)
1908
        try:
1909
            tty.setraw(fd)
1910
            ch = sys.stdin.read(1)
1911
        finally:
1912
            termios.tcsetattr(fd, termios.TCSADRAIN, settings)
1913
        return ch
4398.4.3 by Vincent Ladeuil
Detect # cores on win32 and Solaris too.
1914
1915
1916
if sys.platform == 'linux2':
1917
    def _local_concurrency():
1918
        concurrency = None
1919
        prefix = 'processor'
1920
        for line in file('/proc/cpuinfo', 'rb'):
1921
            if line.startswith(prefix):
1922
                concurrency = int(line[line.find(':')+1:]) + 1
1923
        return concurrency
1924
elif sys.platform == 'darwin':
1925
    def _local_concurrency():
1926
        return subprocess.Popen(['sysctl', '-n', 'hw.availcpu'],
1927
                                stdout=subprocess.PIPE).communicate()[0]
4413.1.1 by Matthew Fuller
Catch the number of cores on FreeBSD too.
1928
elif sys.platform[0:7] == 'freebsd':
1929
    def _local_concurrency():
1930
        return subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
1931
                                stdout=subprocess.PIPE).communicate()[0]
4398.4.3 by Vincent Ladeuil
Detect # cores on win32 and Solaris too.
1932
elif sys.platform == 'sunos5':
1933
    def _local_concurrency():
1934
        return subprocess.Popen(['psrinfo', '-p',],
1935
                                stdout=subprocess.PIPE).communicate()[0]
1936
elif sys.platform == "win32":
1937
    def _local_concurrency():
4398.4.4 by Vincent Ladeuil
Fixed as per John's review.
1938
        # This appears to return the number of cores.
4398.4.3 by Vincent Ladeuil
Detect # cores on win32 and Solaris too.
1939
        return os.environ.get('NUMBER_OF_PROCESSORS')
1940
else:
1941
    def _local_concurrency():
1942
        # Who knows ?
1943
        return None
1944
1945
4398.4.4 by Vincent Ladeuil
Fixed as per John's review.
1946
_cached_local_concurrency = None
1947
1948
def local_concurrency(use_cache=True):
4398.4.3 by Vincent Ladeuil
Detect # cores on win32 and Solaris too.
1949
    """Return how many processes can be run concurrently.
1950
1951
    Rely on platform specific implementations and default to 1 (one) if
1952
    anything goes wrong.
1953
    """
4398.4.4 by Vincent Ladeuil
Fixed as per John's review.
1954
    global _cached_local_concurrency
1955
    if _cached_local_concurrency is not None and use_cache:
1956
        return _cached_local_concurrency
1957
4398.4.3 by Vincent Ladeuil
Detect # cores on win32 and Solaris too.
1958
    try:
1959
        concurrency = _local_concurrency()
1960
    except (OSError, IOError):
1961
        concurrency = None
1962
    try:
1963
        concurrency = int(concurrency)
1964
    except (TypeError, ValueError):
1965
        concurrency = 1
4398.4.4 by Vincent Ladeuil
Fixed as per John's review.
1966
    if use_cache:
1967
        _cached_concurrency = concurrency
4398.4.3 by Vincent Ladeuil
Detect # cores on win32 and Solaris too.
1968
    return concurrency