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