/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
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)
4747.5.1 by Vincent Ladeuil
catch SIGWINCH, but that means soem IO can be interrupted and the code
22
import signal
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
23
import sys
24
import time
4574.3.2 by Martin Pool
Change back to python warnings for failure to load extensions
25
import warnings
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
26
27
from bzrlib.lazy_import import lazy_import
28
lazy_import(globals(), """
2192.1.1 by Alexander Belchenko
Before actually using encoding need to check that Python has corresponding codec
29
import codecs
2215.6.1 by James Henstridge
Don't rely on time.timezone and time.altzone in local_time_offset(),
30
from datetime import datetime
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
31
import errno
1711.4.5 by John Arbash Meinel
the _posix_* routines should use posixpath not os.path, so tests pass on win32
32
from ntpath import (abspath as _nt_abspath,
33
                    join as _nt_join,
34
                    normpath as _nt_normpath,
35
                    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
36
                    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
37
                    )
38
import posixpath
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
39
import shutil
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
40
from shutil import (
41
    rmtree,
42
    )
4398.4.3 by Vincent Ladeuil
Detect # cores on win32 and Solaris too.
43
import subprocess
1185.31.40 by John Arbash Meinel
Added osutils.mkdtemp()
44
import tempfile
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
45
from tempfile import (
46
    mkdtemp,
47
    )
1185.85.75 by John Arbash Meinel
Adding bzrlib.osutils.unicode_filename to handle unicode normalization for file paths.
48
import unicodedata
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
49
50
from bzrlib import (
2249.5.16 by John Arbash Meinel
[merge] bzr.dev 2283
51
    cache_utf8,
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
52
    errors,
2245.4.6 by Alexander Belchenko
osutils.py: terminal_width() now use win32utils.get_console_size()
53
    win32utils,
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
54
    )
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
55
""")
1 by mbp at sourcefrog
import from baz patch-364
56
3734.2.4 by Vincent Ladeuil
Fix python2.6 deprecation warnings related to hashlib.
57
# sha and md5 modules are deprecated in python2.6 but hashlib is available as
58
# of 2.5
2929.3.1 by Vincent Ladeuil
Fix python2.6 deprecation warnings (still 4 failures 5 errors in test suite).
59
if sys.version_info < (2, 5):
3734.5.2 by Vincent Ladeuil
Martin's review feedback.
60
    import md5 as _mod_md5
61
    md5 = _mod_md5.new
62
    import sha as _mod_sha
63
    sha = _mod_sha.new
2929.3.1 by Vincent Ladeuil
Fix python2.6 deprecation warnings (still 4 failures 5 errors in test suite).
64
else:
65
    from hashlib import (
66
        md5,
67
        sha1 as sha,
68
        )
69
3504.4.1 by John Arbash Meinel
Write an alternative 'walkdirs' implementation that uses win32 apis.
70
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
71
import bzrlib
2309.4.3 by John Arbash Meinel
(broken) change safe_*_id to emit a warning.
72
from bzrlib import symbol_versioning
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
73
1 by mbp at sourcefrog
import from baz patch-364
74
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
75
# On win32, O_BINARY is used to indicate the file should
76
# be opened in binary mode, rather than text mode.
77
# On other platforms, O_BINARY doesn't exist, because
78
# they always open in binary mode, so it is okay to
79
# OR with 0 on those platforms
80
O_BINARY = getattr(os, 'O_BINARY', 0)
81
82
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.
83
def get_unicode_argv():
84
    try:
85
        user_encoding = get_user_encoding()
86
        return [a.decode(user_encoding) for a in sys.argv[1:]]
87
    except UnicodeDecodeError:
88
        raise errors.BzrError(("Parameter '%r' is unsupported by the current "
89
                                                            "encoding." % a))
90
91
1 by mbp at sourcefrog
import from baz patch-364
92
def make_readonly(filename):
93
    """Make a filename read-only."""
2949.6.1 by Alexander Belchenko
windows python has os.lstat
94
    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
95
    if not stat.S_ISLNK(mod):
96
        mod = mod & 0777555
97
        os.chmod(filename, mod)
1 by mbp at sourcefrog
import from baz patch-364
98
99
100
def make_writable(filename):
2949.6.1 by Alexander Belchenko
windows python has os.lstat
101
    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
102
    if not stat.S_ISLNK(mod):
103
        mod = mod | 0200
104
        os.chmod(filename, mod)
1 by mbp at sourcefrog
import from baz patch-364
105
106
2825.7.1 by Robert Collins
* Partial commits are now approximately 40% faster by walking over the
107
def minimum_path_selection(paths):
108
    """Return the smallset subset of paths which are outside paths.
109
2843.1.1 by Ian Clatworthy
Faster partial commits by walking less data (Robert Collins)
110
    :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
111
    :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
112
        is_inside, drawn from the paths parameter.
2825.7.1 by Robert Collins
* Partial commits are now approximately 40% faster by walking over the
113
    """
4325.3.7 by Johan Walles
Style fixes for minimum_path_selection().
114
    if len(paths) < 2:
115
        return set(paths)
4325.3.3 by Johan Walles
Add unit test and fix for minimum_path_selection() vs directory names with
116
117
    def sort_key(path):
118
        return path.split('/')
119
    sorted_paths = sorted(list(paths), key=sort_key)
120
4325.3.7 by Johan Walles
Style fixes for minimum_path_selection().
121
    search_paths = [sorted_paths[0]]
122
    for path in sorted_paths[1:]:
4325.3.2 by Johan Walles
Use a linear algorithm for osutil.minimum_path_selection().
123
        if not is_inside(search_paths[-1], path):
124
            # This path is unique, add it
125
            search_paths.append(path)
4325.3.7 by Johan Walles
Style fixes for minimum_path_selection().
126
4325.3.2 by Johan Walles
Use a linear algorithm for osutil.minimum_path_selection().
127
    return set(search_paths)
2825.7.1 by Robert Collins
* Partial commits are now approximately 40% faster by walking over the
128
129
1077 by Martin Pool
- avoid compiling REs at module load time
130
_QUOTE_RE = None
969 by Martin Pool
- Add less-sucky is_within_any
131
132
1 by mbp at sourcefrog
import from baz patch-364
133
def quotefn(f):
779 by Martin Pool
- better quotefn for windows: use doublequotes for strings with
134
    """Return a quoted filename filename
135
136
    This previously used backslash quoting, but that works poorly on
137
    Windows."""
138
    # TODO: I'm not really sure this is the best format either.x
1077 by Martin Pool
- avoid compiling REs at module load time
139
    global _QUOTE_RE
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
140
    if _QUOTE_RE is None:
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
141
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
142
779 by Martin Pool
- better quotefn for windows: use doublequotes for strings with
143
    if _QUOTE_RE.search(f):
144
        return '"' + f + '"'
145
    else:
146
        return f
1 by mbp at sourcefrog
import from baz patch-364
147
148
1753.1.1 by Robert Collins
(rbc, jam, mbp)Add bzrlib.osutils.walkdirs, an optimised walk-and-stat routine.
149
_directory_kind = 'directory'
150
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
151
def get_umask():
152
    """Return the current umask"""
153
    # Assume that people aren't messing with the umask while running
154
    # XXX: This is not thread safe, but there is no way to get the
155
    #      umask without setting it
156
    umask = os.umask(0)
157
    os.umask(umask)
158
    return umask
159
160
2324.2.1 by Dmitry Vasiliev
kind_marker() optimization
161
_kind_marker_map = {
162
    "file": "",
163
    _directory_kind: "/",
164
    "symlink": "@",
1551.10.30 by Aaron Bentley
Merge from bzr.dev
165
    'tree-reference': '+',
2324.2.1 by Dmitry Vasiliev
kind_marker() optimization
166
}
1551.10.30 by Aaron Bentley
Merge from bzr.dev
167
168
488 by Martin Pool
- new helper function kind_marker()
169
def kind_marker(kind):
2324.2.1 by Dmitry Vasiliev
kind_marker() optimization
170
    try:
171
        return _kind_marker_map[kind]
172
    except KeyError:
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
173
        raise errors.BzrError('invalid file kind %r' % kind)
1 by mbp at sourcefrog
import from baz patch-364
174
2324.2.1 by Dmitry Vasiliev
kind_marker() optimization
175
1732.1.2 by John Arbash Meinel
just use os.path.lexists if it exists
176
lexists = getattr(os.path, 'lexists', None)
177
if lexists is None:
178
    def lexists(f):
179
        try:
2324.2.2 by Dmitry Vasiliev
Fixed lexists() implementation
180
            stat = getattr(os, 'lstat', os.stat)
181
            stat(f)
1732.1.2 by John Arbash Meinel
just use os.path.lexists if it exists
182
            return True
2324.2.2 by Dmitry Vasiliev
Fixed lexists() implementation
183
        except OSError, e:
1732.1.2 by John Arbash Meinel
just use os.path.lexists if it exists
184
            if e.errno == errno.ENOENT:
185
                return False;
186
            else:
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
187
                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
188
1 by mbp at sourcefrog
import from baz patch-364
189
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
190
def fancy_rename(old, new, rename_func, unlink_func):
191
    """A fancy rename, when you don't have atomic rename.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
192
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
193
    :param old: The old path, to rename from
194
    :param new: The new path, to rename to
195
    :param rename_func: The potentially non-atomic rename function
196
    :param unlink_func: A way to delete the target file if the full rename succeeds
197
    """
198
199
    # sftp rename doesn't allow overwriting, so play tricks:
200
    base = os.path.basename(new)
201
    dirname = os.path.dirname(new)
1553.5.22 by Martin Pool
Change fancy_rename to use rand_chars rather than reinvent it.
202
    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.
203
    tmp_name = pathjoin(dirname, tmp_name)
204
205
    # Rename the file out of the way, but keep track if it didn't exist
206
    # We don't want to grab just any exception
207
    # something like EACCES should prevent us from continuing
208
    # The downside is that the rename_func has to throw an exception
209
    # with an errno = ENOENT, or NoSuchFile
210
    file_existed = False
211
    try:
212
        rename_func(new, tmp_name)
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
213
    except (errors.NoSuchFile,), e:
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
214
        pass
1532 by Robert Collins
Merge in John Meinels integration branch.
215
    except IOError, e:
216
        # 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'.
217
        # function raises an IOError with errno is None when a rename fails.
1532 by Robert Collins
Merge in John Meinels integration branch.
218
        # This then gets caught here.
1185.50.37 by John Arbash Meinel
Fixed exception handling for fancy_rename
219
        if e.errno not in (None, errno.ENOENT, errno.ENOTDIR):
1532 by Robert Collins
Merge in John Meinels integration branch.
220
            raise
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
221
    except Exception, e:
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
222
        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.
223
            or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
224
            raise
225
    else:
226
        file_existed = True
227
4789.17.1 by John Arbash Meinel
Change fancy_rename slightly.
228
    failure_exc = None
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
229
    success = False
230
    try:
2978.8.2 by Alexander Belchenko
teach fancy_rename to handle change case renames in possible case-insensitive filesystem
231
        try:
232
            # This may throw an exception, in which case success will
233
            # not be set.
234
            rename_func(old, new)
235
            success = True
236
        except (IOError, OSError), e:
2978.8.3 by Alexander Belchenko
Aaron's review
237
            # source and target may be aliases of each other (e.g. on a
238
            # case-insensitive filesystem), so we may have accidentally renamed
239
            # source by when we tried to rename target
4789.17.1 by John Arbash Meinel
Change fancy_rename slightly.
240
            failure_exc = sys.exc_info()
241
            if (file_existed and e.errno in (None, errno.ENOENT)
242
                and old.lower() == new.lower()):
243
                # source and target are the same file on a case-insensitive
244
                # filesystem, so we don't generate an exception
245
                failure_exc = None
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
246
    finally:
247
        if file_existed:
248
            # If the file used to exist, rename it back into place
249
            # otherwise just delete it from the tmp location
250
            if success:
1551.15.4 by Aaron Bentley
Revert now-unnecessary changes
251
                unlink_func(tmp_name)
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
252
            else:
1185.31.49 by John Arbash Meinel
Some corrections using the new osutils.rename. **ALL TESTS PASS**
253
                rename_func(tmp_name, new)
4789.17.2 by John Arbash Meinel
Also handle the case when source *and* target does not exist.
254
    if failure_exc is not None:
255
        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.
256
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
257
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
258
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
259
# choke on a Unicode string containing a relative path if
260
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
261
# string.
2093.1.1 by John Arbash Meinel
(Bart Teeuwisse) if sys.getfilesystemencoding() is None, use 'utf-8'
262
_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
263
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
264
    # jam 20060426 rather than encoding to fsencoding
265
    # copy posixpath.abspath, but use os.getcwdu instead
266
    if not posixpath.isabs(path):
267
        path = posixpath.join(getcwd(), path)
268
    return posixpath.normpath(path)
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
269
270
271
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
272
    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
273
274
1711.5.2 by John Arbash Meinel
win32 likes to return lowercase drive letters sometimes, and uppercase at other times. normalize this
275
def _win32_fixdrive(path):
276
    """Force drive letters to be consistent.
277
278
    win32 is inconsistent whether it returns lower or upper case
279
    and even if it was consistent the user might type the other
280
    so we force it to uppercase
281
    running python.exe under cmd.exe return capital C:\\
282
    running win32 python inside a cygwin shell returns lowercase c:\\
283
    """
284
    drive, path = _nt_splitdrive(path)
285
    return drive.upper() + path
286
287
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
288
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'
289
    # 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
290
    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
291
292
2279.4.1 by Alexander Belchenko
Reimplementation of ntpath.abspath in Python for Windows98: unicode safe, UNC path safe
293
def _win98_abspath(path):
294
    """Return the absolute version of a path.
295
    Windows 98 safe implementation (python reimplementation
296
    of Win32 API function GetFullPathNameW)
297
    """
298
    # Corner cases:
299
    #   C:\path     => C:/path
300
    #   C:/path     => C:/path
301
    #   \\HOST\path => //HOST/path
302
    #   //HOST/path => //HOST/path
303
    #   path        => C:/cwd/path
304
    #   /path       => C:/path
305
    path = unicode(path)
306
    # check for absolute path
307
    drive = _nt_splitdrive(path)[0]
308
    if drive == '' and path[:2] not in('//','\\\\'):
309
        cwd = os.getcwdu()
310
        # we cannot simply os.path.join cwd and path
311
        # because os.path.join('C:','/path') produce '/path'
312
        # and this is incorrect
313
        if path[:1] in ('/','\\'):
314
            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
315
            path = path[1:]
2279.4.1 by Alexander Belchenko
Reimplementation of ntpath.abspath in Python for Windows98: unicode safe, UNC path safe
316
        path = cwd + '\\' + path
317
    return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
318
319
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
320
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'
321
    # 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
322
    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
323
324
325
def _win32_pathjoin(*args):
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
326
    return _nt_join(*args).replace('\\', '/')
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
327
328
329
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
330
    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
331
332
333
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
334
    return _win32_fixdrive(os.getcwdu().replace('\\', '/'))
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
335
336
337
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
338
    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
339
340
341
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.
342
    """We expect to be able to atomically replace 'new' with old.
343
1711.7.17 by John Arbash Meinel
Delay the extra syscall in _win32_rename until we get a failure.
344
    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
345
    and then deleted.
1711.7.6 by John Arbash Meinel
Change _win32_rename() so that it raises ENOENT *before* it tries any renaming.
346
    """
1711.7.17 by John Arbash Meinel
Delay the extra syscall in _win32_rename until we get a failure.
347
    try:
348
        fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
349
    except OSError, e:
1830.3.15 by John Arbash Meinel
On Mac we get EINVAL when renaming cwd
350
        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
351
            # If we try to rename a non-existant file onto cwd, we get
352
            # 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
353
            # if the old path doesn't exist, sometimes we get EACCES
354
            # 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.
355
            os.lstat(old)
356
        raise
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
357
358
1830.3.11 by John Arbash Meinel
Create a mac version of 'getcwd()' which normalizes the path.
359
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
360
    return unicodedata.normalize('NFC', os.getcwdu())
1830.3.11 by John Arbash Meinel
Create a mac version of 'getcwd()' which normalizes the path.
361
362
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
363
# Default is to just use the python builtins, but these can be rebound on
364
# particular platforms.
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
365
abspath = _posix_abspath
366
realpath = _posix_realpath
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
367
pathjoin = os.path.join
368
normpath = os.path.normpath
369
getcwd = os.getcwdu
370
rename = os.rename
371
dirname = os.path.dirname
372
basename = os.path.basename
2215.4.2 by Alexander Belchenko
split and splitext now the part of osutils
373
split = os.path.split
374
splitext = os.path.splitext
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
375
# These were already imported into local scope
376
# mkdtemp = tempfile.mkdtemp
377
# rmtree = shutil.rmtree
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
378
1551.2.53 by abentley
Strip trailing slashes in a platform-sensible way
379
MIN_ABS_PATHLENGTH = 1
380
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
381
1185.31.47 by John Arbash Meinel
Added a fancy footwork rename to osutils, made SftpTransport use it.
382
if sys.platform == 'win32':
3224.5.35 by Andrew Bennetts
More improvements suggested by John's review.
383
    if win32utils.winver == 'Windows 98':
384
        abspath = _win98_abspath
385
    else:
386
        abspath = _win32_abspath
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
387
    realpath = _win32_realpath
388
    pathjoin = _win32_pathjoin
389
    normpath = _win32_normpath
390
    getcwd = _win32_getcwd
391
    mkdtemp = _win32_mkdtemp
392
    rename = _win32_rename
393
1551.2.53 by abentley
Strip trailing slashes in a platform-sensible way
394
    MIN_ABS_PATHLENGTH = 3
1532 by Robert Collins
Merge in John Meinels integration branch.
395
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
396
    def _win32_delete_readonly(function, path, excinfo):
397
        """Error handler for shutil.rmtree function [for win32]
398
        Helps to remove files and dirs marked as read-only.
399
        """
2116.5.1 by Henri Wiechers
Fixes osutils.rmtree on Windows with Python 2.5
400
        exception = excinfo[1]
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
401
        if function in (os.remove, os.rmdir) \
2116.5.1 by Henri Wiechers
Fixes osutils.rmtree on Windows with Python 2.5
402
            and isinstance(exception, OSError) \
403
            and exception.errno == errno.EACCES:
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
404
            make_writable(path)
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
405
            function(path)
406
        else:
407
            raise
408
409
    def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
410
        """Replacer for shutil.rmtree: could remove readonly dirs/files"""
411
        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.
412
413
    f = win32utils.get_unicode_argv     # special function or None
414
    if f is not None:
415
        get_unicode_argv = f
416
1830.3.11 by John Arbash Meinel
Create a mac version of 'getcwd()' which normalizes the path.
417
elif sys.platform == 'darwin':
418
    getcwd = _mac_getcwd
1692.7.6 by Martin Pool
[patch] force deletion of trees containing readonly files (alexander)
419
1685.1.31 by John Arbash Meinel
Adding tests for the rest of the _win32 functions.
420
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.
421
def get_terminal_encoding():
422
    """Find the best encoding for printing to the screen.
423
424
    This attempts to check both sys.stdout and sys.stdin to see
425
    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.
426
    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.
427
    The problem is that on Windows, locale.getpreferredencoding()
428
    is not the same encoding as that used by the console:
429
    http://mail.python.org/pipermail/python-list/2003-May/162357.html
430
431
    On my standard US Windows XP, the preferred encoding is
432
    cp1252, but the console is cp437
433
    """
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.
434
    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.
435
    output_encoding = getattr(sys.stdout, 'encoding', None)
436
    if not output_encoding:
437
        input_encoding = getattr(sys.stdin, 'encoding', None)
438
        if not input_encoding:
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
439
            output_encoding = get_user_encoding()
440
            mutter('encoding stdout as osutils.get_user_encoding() %r',
441
                   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.
442
        else:
443
            output_encoding = input_encoding
444
            mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
445
    else:
446
        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
447
    if output_encoding == 'cp0':
448
        # 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.
449
        output_encoding = get_user_encoding()
2127.4.1 by Alexander Belchenko
(jam, bialix) Workaround for cp0 console encoding on Windows
450
        mutter('cp0 is invalid encoding.'
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
451
               ' encoding stdout as osutils.get_user_encoding() %r',
452
               output_encoding)
2192.1.1 by Alexander Belchenko
Before actually using encoding need to check that Python has corresponding codec
453
    # check encoding
454
    try:
455
        codecs.lookup(output_encoding)
456
    except LookupError:
457
        sys.stderr.write('bzr: warning:'
2192.1.9 by Alexander Belchenko
final fix suggested by John Meinel
458
                         ' unknown terminal encoding %s.\n'
2192.1.1 by Alexander Belchenko
Before actually using encoding need to check that Python has corresponding codec
459
                         '  Using encoding %s instead.\n'
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
460
                         % (output_encoding, get_user_encoding())
2192.1.1 by Alexander Belchenko
Before actually using encoding need to check that Python has corresponding codec
461
                        )
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
462
        output_encoding = get_user_encoding()
2192.1.1 by Alexander Belchenko
Before actually using encoding need to check that Python has corresponding codec
463
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.
464
    return output_encoding
465
466
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 \
467
def normalizepath(f):
3287.18.2 by Matt McClure
Reverts to 3290.
468
    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 \
469
        F = realpath
470
    else:
471
        F = abspath
472
    [p,e] = os.path.split(f)
473
    if e == "" or e == "." or e == "..":
474
        return F(f)
475
    else:
476
        return pathjoin(F(p), e)
477
1 by mbp at sourcefrog
import from baz patch-364
478
479
def isdir(f):
480
    """True if f is an accessible directory."""
481
    try:
482
        return S_ISDIR(os.lstat(f)[ST_MODE])
483
    except OSError:
484
        return False
485
486
487
def isfile(f):
488
    """True if f is a regular file."""
489
    try:
490
        return S_ISREG(os.lstat(f)[ST_MODE])
491
    except OSError:
492
        return False
493
1092.2.6 by Robert Collins
symlink support updated to work
494
def islink(f):
495
    """True if f is a symlink."""
496
    try:
497
        return S_ISLNK(os.lstat(f)[ST_MODE])
498
    except OSError:
499
        return False
1 by mbp at sourcefrog
import from baz patch-364
500
485 by Martin Pool
- move commit code into its own module
501
def is_inside(dir, fname):
502
    """True if fname is inside dir.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
503
1185.31.38 by John Arbash Meinel
Changing os.path.normpath to osutils.normpath
504
    The parameters should typically be passed to osutils.normpath first, so
969 by Martin Pool
- Add less-sucky is_within_any
505
    that . and .. and repeated slashes are eliminated, and the separators
506
    are canonical for the platform.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
507
508
    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
509
    everything.
485 by Martin Pool
- move commit code into its own module
510
    """
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
511
    # XXX: Most callers of this can actually do something smarter by
969 by Martin Pool
- Add less-sucky is_within_any
512
    # looking at the inventory
972 by Martin Pool
- less dodgy is_inside function
513
    if dir == fname:
514
        return True
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
515
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
516
    if dir == '':
517
        return True
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
518
1185.31.34 by John Arbash Meinel
Removing instances of os.sep
519
    if dir[-1] != '/':
520
        dir += '/'
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
521
972 by Martin Pool
- less dodgy is_inside function
522
    return fname.startswith(dir)
523
485 by Martin Pool
- move commit code into its own module
524
525
def is_inside_any(dir_list, fname):
526
    """True if fname is inside any of given dirs."""
527
    for dirname in dir_list:
528
        if is_inside(dirname, fname):
529
            return True
2324.2.3 by Dmitry Vasiliev
Fixed is_inside_* methods implementation
530
    return False
485 by Martin Pool
- move commit code into its own module
531
532
1740.3.4 by Jelmer Vernooij
Move inventory to commit builder.
533
def is_inside_or_parent_of_any(dir_list, fname):
534
    """True if fname is a child or a parent of any of the given files."""
535
    for dirname in dir_list:
536
        if is_inside(dirname, fname) or is_inside(fname, dirname):
537
            return True
2324.2.3 by Dmitry Vasiliev
Fixed is_inside_* methods implementation
538
    return False
1740.3.4 by Jelmer Vernooij
Move inventory to commit builder.
539
540
3956.2.1 by John Arbash Meinel
Add report_activity to osutils.pumpfile
541
def pumpfile(from_file, to_file, read_length=-1, buff_size=32768,
542
             report_activity=None, direction='read'):
2745.5.2 by Robert Collins
* ``bzrlib.transport.Transport.put_file`` now returns the number of bytes
543
    """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
544
545
    The read_length can either be -1 to read to end-of-file (EOF) or
546
    it can specify the maximum number of bytes to read.
547
548
    The buff_size represents the maximum size for each read operation
549
    performed on from_file.
550
3956.2.1 by John Arbash Meinel
Add report_activity to osutils.pumpfile
551
    :param report_activity: Call this as bytes are read, see
552
        Transport._report_activity
553
    :param direction: Will be passed to report_activity
554
2745.5.2 by Robert Collins
* ``bzrlib.transport.Transport.put_file`` now returns the number of bytes
555
    :return: The number of bytes copied.
556
    """
557
    length = 0
3408.6.1 by Eric Holmberg
Fix for Bug #215426 in which bzr can cause a MemoryError in socket.recv while
558
    if read_length >= 0:
559
        # read specified number of bytes
560
561
        while read_length > 0:
562
            num_bytes_to_read = min(read_length, buff_size)
563
564
            block = from_file.read(num_bytes_to_read)
565
            if not block:
566
                # EOF reached
567
                break
3956.2.1 by John Arbash Meinel
Add report_activity to osutils.pumpfile
568
            if report_activity is not None:
569
                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
570
            to_file.write(block)
571
572
            actual_bytes_read = len(block)
573
            read_length -= actual_bytes_read
574
            length += actual_bytes_read
575
    else:
576
        # read to EOF
577
        while True:
578
            block = from_file.read(buff_size)
579
            if not block:
580
                # EOF reached
581
                break
3956.2.1 by John Arbash Meinel
Add report_activity to osutils.pumpfile
582
            if report_activity is not None:
583
                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
584
            to_file.write(block)
585
            length += len(block)
2745.5.2 by Robert Collins
* ``bzrlib.transport.Transport.put_file`` now returns the number of bytes
586
    return length
1 by mbp at sourcefrog
import from baz patch-364
587
588
3635.1.2 by Robert Collins
Add osutils.pump_string_file helper function.
589
def pump_string_file(bytes, file_handle, segment_size=None):
590
    """Write bytes to file_handle in many smaller writes.
591
592
    :param bytes: The string to write.
593
    :param file_handle: The file to write to.
594
    """
595
    # Write data in chunks rather than all at once, because very large
596
    # writes fail on some platforms (e.g. Windows with SMB  mounted
597
    # drives).
598
    if not segment_size:
599
        segment_size = 5242880 # 5MB
600
    segments = range(len(bytes) / segment_size + 1)
601
    write = file_handle.write
602
    for segment_index in segments:
603
        segment = buffer(bytes, segment_index * segment_size, segment_size)
604
        write(segment)
605
606
1185.67.7 by Aaron Bentley
Refactored a bit
607
def file_iterator(input_file, readsize=32768):
608
    while True:
609
        b = input_file.read(readsize)
610
        if len(b) == 0:
611
            break
612
        yield b
613
614
1 by mbp at sourcefrog
import from baz patch-364
615
def sha_file(f):
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
616
    """Calculate the hexdigest of an open file.
617
618
    The file cursor should be already at the start.
619
    """
2929.3.1 by Vincent Ladeuil
Fix python2.6 deprecation warnings (still 4 failures 5 errors in test suite).
620
    s = sha()
320 by Martin Pool
- Compute SHA-1 of files in chunks
621
    BUFSIZE = 128<<10
622
    while True:
623
        b = f.read(BUFSIZE)
624
        if not b:
625
            break
626
        s.update(b)
1 by mbp at sourcefrog
import from baz patch-364
627
    return s.hexdigest()
628
629
3368.2.49 by Ian Clatworthy
added osutils.size_sha_file() with tests
630
def size_sha_file(f):
631
    """Calculate the size and hexdigest of an open file.
632
633
    The file cursor should be already at the start and
634
    the caller is responsible for closing the file afterwards.
635
    """
636
    size = 0
637
    s = sha()
638
    BUFSIZE = 128<<10
639
    while True:
640
        b = f.read(BUFSIZE)
641
        if not b:
642
            break
643
        size += len(b)
644
        s.update(b)
645
    return size, s.hexdigest()
646
647
2872.3.1 by Martin Pool
Add -Dhashcache option; clean up dirstate sha1 code
648
def sha_file_by_name(fname):
649
    """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).
650
    s = sha()
2922.1.1 by John Arbash Meinel
Fix bug #153493, use O_BINARY when reading files.
651
    f = os.open(fname, os.O_RDONLY | O_BINARY)
2872.3.1 by Martin Pool
Add -Dhashcache option; clean up dirstate sha1 code
652
    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
653
        while True:
654
            b = os.read(f, 1<<16)
655
            if not b:
656
                return s.hexdigest()
657
            s.update(b)
2872.3.1 by Martin Pool
Add -Dhashcache option; clean up dirstate sha1 code
658
    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
659
        os.close(f)
2872.3.1 by Martin Pool
Add -Dhashcache option; clean up dirstate sha1 code
660
661
2929.3.1 by Vincent Ladeuil
Fix python2.6 deprecation warnings (still 4 failures 5 errors in test suite).
662
def sha_strings(strings, _factory=sha):
1235 by Martin Pool
- split sha_strings into osutils
663
    """Return the sha-1 of concatenation of strings"""
2825.2.1 by Robert Collins
Micro-tweaks to sha routines.
664
    s = _factory()
1235 by Martin Pool
- split sha_strings into osutils
665
    map(s.update, strings)
666
    return s.hexdigest()
667
668
2929.3.1 by Vincent Ladeuil
Fix python2.6 deprecation warnings (still 4 failures 5 errors in test suite).
669
def sha_string(f, _factory=sha):
2825.2.1 by Robert Collins
Micro-tweaks to sha routines.
670
    return _factory(f).hexdigest()
1 by mbp at sourcefrog
import from baz patch-364
671
672
124 by mbp at sourcefrog
- check file text for past revisions is correct
673
def fingerprint_file(f):
126 by mbp at sourcefrog
Use just one big read to fingerprint files
674
    b = f.read()
2825.2.1 by Robert Collins
Micro-tweaks to sha routines.
675
    return {'size': len(b),
2929.3.1 by Vincent Ladeuil
Fix python2.6 deprecation warnings (still 4 failures 5 errors in test suite).
676
            'sha1': sha(b).hexdigest()}
124 by mbp at sourcefrog
- check file text for past revisions is correct
677
678
1 by mbp at sourcefrog
import from baz patch-364
679
def compare_files(a, b):
680
    """Returns true if equal in contents"""
74 by mbp at sourcefrog
compare_files: read in one page at a time rather than
681
    BUFSIZE = 4096
682
    while True:
683
        ai = a.read(BUFSIZE)
684
        bi = b.read(BUFSIZE)
685
        if ai != bi:
686
            return False
687
        if ai == '':
688
            return True
1 by mbp at sourcefrog
import from baz patch-364
689
690
49 by mbp at sourcefrog
fix local-time-offset calculation
691
def local_time_offset(t=None):
692
    """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'.
693
    if t is None:
73 by mbp at sourcefrog
fix time.localtime call for python 2.3
694
        t = time.time()
2215.6.1 by James Henstridge
Don't rely on time.timezone and time.altzone in local_time_offset(),
695
    offset = datetime.fromtimestamp(t) - datetime.utcfromtimestamp(t)
696
    return offset.days * 86400 + offset.seconds
8 by mbp at sourcefrog
store committer's timezone in revision and show
697
3512.3.1 by Martin von Gagern
Hand-selected minimalistic set of changes from my setlocale branch.
698
weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
4379.4.1 by Ian Clatworthy
make log --long faster
699
_default_format_by_weekday_num = [wd + " %Y-%m-%d %H:%M:%S" for wd in weekdays]
700
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
701
2425.6.2 by Martin Pool
Make timestamps use existing format_date; document that function more
702
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.
703
                show_offset=True):
2425.6.2 by Martin Pool
Make timestamps use existing format_date; document that function more
704
    """Return a formatted date string.
705
706
    :param t: Seconds since the epoch.
707
    :param offset: Timezone offset in seconds east of utc.
708
    :param timezone: How to display the time: 'utc', 'original' for the
709
         timezone specified by offset, or 'local' for the process's current
710
         timezone.
3526.5.4 by Martin von Gagern
Use separate function format_local_date for local weekday formats in unicode.
711
    :param date_fmt: strftime format.
712
    :param show_offset: Whether to append the timezone.
713
    """
714
    (date_fmt, tt, offset_str) = \
715
               _format_date(t, offset, timezone, date_fmt, show_offset)
716
    date_fmt = date_fmt.replace('%a', weekdays[tt[6]])
717
    date_str = time.strftime(date_fmt, tt)
718
    return date_str + offset_str
719
4379.4.1 by Ian Clatworthy
make log --long faster
720
721
# Cache of formatted offset strings
722
_offset_cache = {}
723
724
4379.4.2 by Ian Clatworthy
add NEWS item and tests for new date formatting API
725
def format_date_with_offset_in_original_timezone(t, offset=0,
4379.4.1 by Ian Clatworthy
make log --long faster
726
    _cache=_offset_cache):
727
    """Return a formatted date string in the original timezone.
728
729
    This routine may be faster then format_date.
730
731
    :param t: Seconds since the epoch.
732
    :param offset: Timezone offset in seconds east of utc.
733
    """
734
    if offset is None:
735
        offset = 0
736
    tt = time.gmtime(t + offset)
737
    date_fmt = _default_format_by_weekday_num[tt[6]]
738
    date_str = time.strftime(date_fmt, tt)
739
    offset_str = _cache.get(offset, None)
740
    if offset_str is None:
741
        offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
742
        _cache[offset] = offset_str
743
    return date_str + offset_str
744
745
3526.5.4 by Martin von Gagern
Use separate function format_local_date for local weekday formats in unicode.
746
def format_local_date(t, offset=0, timezone='original', date_fmt=None,
747
                      show_offset=True):
748
    """Return an unicode date string formatted according to the current locale.
749
750
    :param t: Seconds since the epoch.
751
    :param offset: Timezone offset in seconds east of utc.
752
    :param timezone: How to display the time: 'utc', 'original' for the
753
         timezone specified by offset, or 'local' for the process's current
754
         timezone.
755
    :param date_fmt: strftime format.
756
    :param show_offset: Whether to append the timezone.
757
    """
758
    (date_fmt, tt, offset_str) = \
759
               _format_date(t, offset, timezone, date_fmt, show_offset)
760
    date_str = time.strftime(date_fmt, tt)
761
    if not isinstance(date_str, unicode):
4385.4.1 by Alexander Belchenko
removed all references to bzrlib.user_encoding
762
        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.
763
    return date_str + offset_str
764
4379.4.1 by Ian Clatworthy
make log --long faster
765
3526.5.4 by Martin von Gagern
Use separate function format_local_date for local weekday formats in unicode.
766
def _format_date(t, offset, timezone, date_fmt, show_offset):
8 by mbp at sourcefrog
store committer's timezone in revision and show
767
    if timezone == 'utc':
1 by mbp at sourcefrog
import from baz patch-364
768
        tt = time.gmtime(t)
769
        offset = 0
8 by mbp at sourcefrog
store committer's timezone in revision and show
770
    elif timezone == 'original':
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
771
        if offset is None:
23 by mbp at sourcefrog
format_date: handle revisions with no timezone offset
772
            offset = 0
16 by mbp at sourcefrog
fix inverted calculation for original timezone -> utc
773
        tt = time.gmtime(t + offset)
12 by mbp at sourcefrog
new --timezone option for bzr log
774
    elif timezone == 'local':
1 by mbp at sourcefrog
import from baz patch-364
775
        tt = time.localtime(t)
49 by mbp at sourcefrog
fix local-time-offset calculation
776
        offset = local_time_offset(t)
12 by mbp at sourcefrog
new --timezone option for bzr log
777
    else:
3144.1.1 by Lukáš Lalinský
Fixed error reporting of unsupported timezone format.
778
        raise errors.UnsupportedTimezoneFormat(timezone)
1185.12.24 by Aaron Bentley
Made format_date more flexible
779
    if date_fmt is None:
780
        date_fmt = "%a %Y-%m-%d %H:%M:%S"
781
    if show_offset:
782
        offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
783
    else:
784
        offset_str = ''
3526.5.4 by Martin von Gagern
Use separate function format_local_date for local weekday formats in unicode.
785
    return (date_fmt, tt, offset_str)
1 by mbp at sourcefrog
import from baz patch-364
786
787
788
def compact_date(when):
789
    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
790
1 by mbp at sourcefrog
import from baz patch-364
791
1957.1.4 by John Arbash Meinel
create a helper for formatting a time delta
792
def format_delta(delta):
793
    """Get a nice looking string for a time delta.
794
795
    :param delta: The time difference in seconds, can be positive or negative.
796
        positive indicates time in the past, negative indicates time in the
797
        future. (usually time.time() - stored_time)
798
    :return: String formatted to show approximate resolution
799
    """
800
    delta = int(delta)
801
    if delta >= 0:
802
        direction = 'ago'
803
    else:
804
        direction = 'in the future'
805
        delta = -delta
806
807
    seconds = delta
808
    if seconds < 90: # print seconds up to 90 seconds
809
        if seconds == 1:
810
            return '%d second %s' % (seconds, direction,)
811
        else:
812
            return '%d seconds %s' % (seconds, direction)
813
814
    minutes = int(seconds / 60)
815
    seconds -= 60 * minutes
816
    if seconds == 1:
817
        plural_seconds = ''
818
    else:
819
        plural_seconds = 's'
820
    if minutes < 90: # print minutes, seconds up to 90 minutes
821
        if minutes == 1:
822
            return '%d minute, %d second%s %s' % (
823
                    minutes, seconds, plural_seconds, direction)
824
        else:
825
            return '%d minutes, %d second%s %s' % (
826
                    minutes, seconds, plural_seconds, direction)
827
828
    hours = int(minutes / 60)
829
    minutes -= 60 * hours
830
    if minutes == 1:
831
        plural_minutes = ''
832
    else:
833
        plural_minutes = 's'
834
835
    if hours == 1:
836
        return '%d hour, %d minute%s %s' % (hours, minutes,
837
                                            plural_minutes, direction)
838
    return '%d hours, %d minute%s %s' % (hours, minutes,
839
                                         plural_minutes, direction)
1 by mbp at sourcefrog
import from baz patch-364
840
841
def filesize(f):
842
    """Return size of given open file."""
843
    return os.fstat(f.fileno())[ST_SIZE]
844
1553.5.5 by Martin Pool
New utility routine rand_chars
845
1185.1.7 by Robert Collins
Nathaniel McCallums patch for urandom friendliness on aix.
846
# Define rand_bytes based on platform.
847
try:
848
    # Python 2.4 and later have os.urandom,
849
    # but it doesn't work on some arches
850
    os.urandom(1)
1 by mbp at sourcefrog
import from baz patch-364
851
    rand_bytes = os.urandom
1185.1.7 by Robert Collins
Nathaniel McCallums patch for urandom friendliness on aix.
852
except (NotImplementedError, AttributeError):
853
    # If python doesn't have os.urandom, or it doesn't work,
854
    # 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()
855
    try:
1185.1.7 by Robert Collins
Nathaniel McCallums patch for urandom friendliness on aix.
856
        rand_bytes = file('/dev/urandom', 'rb').read
857
    # 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()
858
    except (IOError, OSError):
1185.1.7 by Robert Collins
Nathaniel McCallums patch for urandom friendliness on aix.
859
        # not well seeded, but better than nothing
860
        def rand_bytes(n):
861
            import random
862
            s = ''
863
            while n:
864
                s += chr(random.randint(0, 255))
865
                n -= 1
866
            return s
1 by mbp at sourcefrog
import from baz patch-364
867
1553.5.5 by Martin Pool
New utility routine rand_chars
868
869
ALNUM = '0123456789abcdefghijklmnopqrstuvwxyz'
870
def rand_chars(num):
871
    """Return a random string of num alphanumeric characters
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
872
873
    The result only contains lowercase chars because it may be used on
1553.5.5 by Martin Pool
New utility routine rand_chars
874
    case-insensitive filesystems.
875
    """
876
    s = ''
877
    for raw_byte in rand_bytes(num):
878
        s += ALNUM[ord(raw_byte) % 36]
879
    return s
880
881
1 by mbp at sourcefrog
import from baz patch-364
882
## 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.
883
## decomposition (might be too tricksy though.)
1 by mbp at sourcefrog
import from baz patch-364
884
885
def splitpath(p):
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
886
    """Turn string into list of parts."""
271 by Martin Pool
- Windows path fixes
887
    # split on either delimiter because people might use either on
888
    # Windows
889
    ps = re.split(r'[\\/]', p)
890
891
    rps = []
1 by mbp at sourcefrog
import from baz patch-364
892
    for f in ps:
893
        if f == '..':
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
894
            raise errors.BzrError("sorry, %r not allowed in path" % f)
271 by Martin Pool
- Windows path fixes
895
        elif (f == '.') or (f == ''):
896
            pass
897
        else:
898
            rps.append(f)
899
    return rps
1 by mbp at sourcefrog
import from baz patch-364
900
3890.2.4 by John Arbash Meinel
Add a new function that can convert 'chunks' format to a 'lines' format.
901
1 by mbp at sourcefrog
import from baz patch-364
902
def joinpath(p):
903
    for f in p:
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
904
        if (f == '..') or (f is None) or (f == ''):
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
905
            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 \
906
    return pathjoin(*p)
1 by mbp at sourcefrog
import from baz patch-364
907
908
4370.1.1 by Ian Clatworthy
add osutils.parent_directories() API
909
def parent_directories(filename):
4371.1.1 by Ian Clatworthy
(igc) added osutils.parent_directories() (Ian Clatworthy)
910
    """Return the list of parent directories, deepest first.
911
    
912
    For example, parent_directories("a/b/c") -> ["a/b", "a"].
913
    """
4370.1.1 by Ian Clatworthy
add osutils.parent_directories() API
914
    parents = []
915
    parts = splitpath(dirname(filename))
916
    while parts:
917
        parents.append(joinpath(parts))
918
        parts.pop()
919
    return parents
920
921
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
922
_extension_load_failures = []
923
924
925
def failed_to_load_extension(exception):
4574.3.1 by Martin Pool
Give a warning when failing to load _chunks_to_lines_pyx
926
    """Handle failing to load a binary extension.
927
928
    This should be called from the ImportError block guarding the attempt to
929
    import the native extension.  If this function returns, the pure-Python
930
    implementation should be loaded instead::
931
932
    >>> try:
933
    >>>     import bzrlib._fictional_extension_pyx
934
    >>> except ImportError, e:
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
935
    >>>     bzrlib.osutils.failed_to_load_extension(e)
4574.3.1 by Martin Pool
Give a warning when failing to load _chunks_to_lines_pyx
936
    >>>     import bzrlib._fictional_extension_py
937
    """
938
    # NB: This docstring is just an example, not a doctest, because doctest
939
    # currently can't cope with the use of lazy imports in this namespace --
940
    # mbp 20090729
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
941
    
942
    # This currently doesn't report the failure at the time it occurs, because
943
    # they tend to happen very early in startup when we can't check config
944
    # files etc, and also we want to report all failures but not spam the user
945
    # with 10 warnings.
946
    from bzrlib import trace
947
    exception_str = str(exception)
948
    if exception_str not in _extension_load_failures:
949
        trace.mutter("failed to load compiled extension: %s" % exception_str)
950
        _extension_load_failures.append(exception_str)
951
952
953
def report_extension_load_failures():
954
    if not _extension_load_failures:
955
        return
956
    from bzrlib.config import GlobalConfig
957
    if GlobalConfig().get_user_option_as_bool('ignore_missing_extensions'):
958
        return
959
    # the warnings framework should by default show this only once
4695.4.1 by Martin Pool
Give a shorter/cleaner message for missing extensions
960
    from bzrlib.trace import warning
961
    warning(
962
        "bzr: warning: some compiled extensions could not be loaded; "
963
        "see <https://answers.launchpad.net/bzr/+faq/703>")
964
    # we no longer show the specific missing extensions here, because it makes
965
    # the message too long and scary - see
966
    # https://bugs.launchpad.net/bzr/+bug/430529
4574.3.1 by Martin Pool
Give a warning when failing to load _chunks_to_lines_pyx
967
968
3890.2.7 by John Arbash Meinel
A Pyrex extension is about 5x faster than the fastest python code I could write.
969
try:
970
    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
971
except ImportError, e:
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
972
    failed_to_load_extension(e)
3890.2.8 by John Arbash Meinel
Move everything into properly parameterized tests.
973
    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.
974
975
1231 by Martin Pool
- more progress on fetch on top of weaves
976
def split_lines(s):
977
    """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.
978
    # Trivially convert a fulltext into a 'chunked' representation, and let
979
    # chunks_to_lines do the heavy lifting.
980
    if isinstance(s, str):
981
        # chunks_to_lines only supports 8-bit strings
982
        return chunks_to_lines([s])
983
    else:
984
        return _split_lines(s)
985
986
987
def _split_lines(s):
988
    """Split s into lines, but without removing the newline characters.
989
990
    This supports Unicode or plain string objects.
991
    """
1666.1.6 by Robert Collins
Make knit the default format.
992
    lines = s.split('\n')
993
    result = [line + '\n' for line in lines[:-1]]
994
    if lines[-1]:
995
        result.append(lines[-1])
996
    return result
1391 by Robert Collins
merge from integration
997
998
1185.10.4 by Aaron Bentley
Disabled hardlinks on cygwin, mac OS
999
def hardlinks_good():
1185.10.5 by Aaron Bentley
Fixed hardlinks_good test
1000
    return sys.platform not in ('win32', 'cygwin', 'darwin')
1185.10.4 by Aaron Bentley
Disabled hardlinks on cygwin, mac OS
1001
1185.1.46 by Robert Collins
Aarons branch --basis patch
1002
1185.10.3 by Aaron Bentley
Made copy_multi_immutable create hardlinks opportunistically
1003
def link_or_copy(src, dest):
1004
    """Hardlink a file, or copy it if it can't be hardlinked."""
1185.10.4 by Aaron Bentley
Disabled hardlinks on cygwin, mac OS
1005
    if not hardlinks_good():
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
1006
        shutil.copyfile(src, dest)
1185.10.3 by Aaron Bentley
Made copy_multi_immutable create hardlinks opportunistically
1007
        return
1008
    try:
1009
        os.link(src, dest)
1010
    except (OSError, IOError), e:
1011
        if e.errno != errno.EXDEV:
1012
            raise
1996.3.14 by John Arbash Meinel
lazy_import osutils and sign_my_commits
1013
        shutil.copyfile(src, dest)
1399.1.4 by Robert Collins
move diff and symlink conditionals into inventory.py from diff.py
1014
2831.5.2 by Vincent Ladeuil
Review feedback.
1015
1016
def delete_any(path):
4490.1.1 by Martin Pool
merge fix for forcing readonly deletion, and tweak
1017
    """Delete a file, symlink or directory.  
1018
    
1019
    Will delete even if readonly.
1020
    """
4440.1.2 by Craig Hewetson
Fixes made after first code review.
1021
    try:
4490.1.1 by Martin Pool
merge fix for forcing readonly deletion, and tweak
1022
       _delete_file_or_dir(path)
4440.1.2 by Craig Hewetson
Fixes made after first code review.
1023
    except (OSError, IOError), e:
1024
        if e.errno in (errno.EPERM, errno.EACCES):
4490.1.1 by Martin Pool
merge fix for forcing readonly deletion, and tweak
1025
            # make writable and try again
1026
            try:
4440.1.2 by Craig Hewetson
Fixes made after first code review.
1027
                make_writable(path)
4490.1.1 by Martin Pool
merge fix for forcing readonly deletion, and tweak
1028
            except (OSError, IOError):
4440.1.2 by Craig Hewetson
Fixes made after first code review.
1029
                pass
4490.1.1 by Martin Pool
merge fix for forcing readonly deletion, and tweak
1030
            _delete_file_or_dir(path)
1031
        else:
1032
            raise
1033
1034
1035
def _delete_file_or_dir(path):
1036
    # Look Before You Leap (LBYL) is appropriate here instead of Easier to Ask for
1037
    # Forgiveness than Permission (EAFP) because:
1038
    # - root can damage a solaris file system by using unlink,
1039
    # - unlink raises different exceptions on different OSes (linux: EISDIR, win32:
1040
    #   EACCES, OSX: EPERM) when invoked on a directory.
2831.5.2 by Vincent Ladeuil
Review feedback.
1041
    if isdir(path): # Takes care of symlinks
1042
        os.rmdir(path)
1043
    else:
1044
        os.unlink(path)
1558.12.9 by Aaron Bentley
Handle resolving conflicts with directories properly
1045
1399.1.4 by Robert Collins
move diff and symlink conditionals into inventory.py from diff.py
1046
1047
def has_symlinks():
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
1048
    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
1049
        return True
1050
    else:
1051
        return False
2831.5.2 by Vincent Ladeuil
Review feedback.
1052
1185.16.38 by Martin Pool
- move contains_whitespace and contains_linebreaks to osutils
1053
3136.1.1 by Aaron Bentley
Add support for hardlinks to TreeTransform
1054
def has_hardlinks():
1055
    if getattr(os, 'link', None) is not None:
1056
        return True
1057
    else:
1058
        return False
1059
1060
3287.18.14 by Matt McClure
Extracted a host_os_dereferences_symlinks method.
1061
def host_os_dereferences_symlinks():
1062
    return (has_symlinks()
3287.18.19 by Matt McClure
Changed tested sys.platform value from 'windows' (mistaken) to 'win32'
1063
            and sys.platform not in ('cygwin', 'win32'))
3287.18.14 by Matt McClure
Extracted a host_os_dereferences_symlinks method.
1064
1065
4241.14.14 by Vincent Ladeuil
Test and implements osutils.readlink().
1066
def readlink(abspath):
1067
    """Return a string representing the path to which the symbolic link points.
1068
1069
    :param abspath: The link absolute unicode path.
1070
1071
    This his guaranteed to return the symbolic link in unicode in all python
1072
    versions.
1073
    """
1074
    link = abspath.encode(_fs_enc)
1075
    target = os.readlink(link)
1076
    target = target.decode(_fs_enc)
1077
    return target
1078
1079
1185.16.38 by Martin Pool
- move contains_whitespace and contains_linebreaks to osutils
1080
def contains_whitespace(s):
1081
    """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.
1082
    # string.whitespace can include '\xa0' in certain locales, because it is
1083
    # considered "non-breaking-space" as part of ISO-8859-1. But it
1084
    # 1) Isn't a breaking whitespace
1085
    # 2) Isn't one of ' \t\r\n' which are characters we sometimes use as
1086
    #    separators
1087
    # 3) '\xa0' isn't unicode safe since it is >128.
2249.5.16 by John Arbash Meinel
[merge] bzr.dev 2283
1088
1089
    # This should *not* be a unicode set of characters in case the source
1090
    # string is not a Unicode string. We can auto-up-cast the characters since
1091
    # they are ascii, but we don't want to auto-up-cast the string in case it
1092
    # is utf-8
1093
    for ch in ' \t\n\r\v\f':
1185.16.38 by Martin Pool
- move contains_whitespace and contains_linebreaks to osutils
1094
        if ch in s:
1095
            return True
1096
    else:
1097
        return False
1098
1099
1100
def contains_linebreaks(s):
1101
    """True if there is any vertical whitespace in s."""
1102
    for ch in '\f\n\r':
1103
        if ch in s:
1104
            return True
1105
    else:
1106
        return False
1457.1.2 by Robert Collins
move branch._relpath into osutils as relpath
1107
1108
1109
def relpath(base, path):
1110
    """Return path relative to base, or raise exception.
1111
1112
    The path may be either an absolute path or a path relative to the
1113
    current working directory.
1114
1115
    os.path.commonprefix (python2.4) has a bad bug that it works just
1116
    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.
1117
    avoids that problem.
1118
    """
1685.1.12 by John Arbash Meinel
Some more work to get LocalTransport to only support URLs
1119
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1120
    if len(base) < MIN_ABS_PATHLENGTH:
1121
        # must have space for e.g. a drive letter
1122
        raise ValueError('%r is too short to calculate a relative path'
1123
            % (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
1124
1685.1.12 by John Arbash Meinel
Some more work to get LocalTransport to only support URLs
1125
    rp = abspath(path)
1457.1.2 by Robert Collins
move branch._relpath into osutils as relpath
1126
1127
    s = []
1685.1.12 by John Arbash Meinel
Some more work to get LocalTransport to only support URLs
1128
    head = rp
4555.2.1 by John Arbash Meinel
Fix bug #394227, osutils.relpath() could get into an infinite loop.
1129
    while True:
1130
        if len(head) <= len(base) and head != base:
1131
            raise errors.PathNotChild(rp, base)
1457.1.2 by Robert Collins
move branch._relpath into osutils as relpath
1132
        if head == base:
1133
            break
4555.2.1 by John Arbash Meinel
Fix bug #394227, osutils.relpath() could get into an infinite loop.
1134
        head, tail = split(head)
1457.1.2 by Robert Collins
move branch._relpath into osutils as relpath
1135
        if tail:
4555.2.1 by John Arbash Meinel
Fix bug #394227, osutils.relpath() could get into an infinite loop.
1136
            s.append(tail)
1457.1.2 by Robert Collins
move branch._relpath into osutils as relpath
1137
1185.31.35 by John Arbash Meinel
Couple small fixes, all tests pass on cygwin.
1138
    if s:
4555.2.3 by John Arbash Meinel
Fix a trivial bug that should have been caught earlier. :)
1139
        return pathjoin(*reversed(s))
1185.31.35 by John Arbash Meinel
Couple small fixes, all tests pass on cygwin.
1140
    else:
1141
        return ''
1185.33.60 by Martin Pool
Use full terminal width for verbose test output.
1142
1143
3794.5.29 by Mark Hammond
cicp_canonical_relpath -> _cicp_canonical_relpath
1144
def _cicp_canonical_relpath(base, path):
3794.5.1 by Mark Hammond
Add canonical_relpath api function
1145
    """Return the canonical path relative to base.
1146
1147
    Like relpath, but on case-insensitive-case-preserving file-systems, this
3794.5.13 by Mark Hammond
Tweaks suggested by Martin
1148
    will return the relpath as stored on the file-system rather than in the
1149
    case specified in the input string, for all existing portions of the path.
1150
3794.5.28 by Mark Hammond
Update comments.
1151
    This will cause O(N) behaviour if called for every path in a tree; if you
1152
    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.
1153
    """
1154
    # TODO: it should be possible to optimize this for Windows by using the
1155
    # win32 API FindFiles function to look for the specified name - but using
1156
    # os.listdir() still gives us the correct, platform agnostic semantics in
1157
    # the short term.
3794.5.13 by Mark Hammond
Tweaks suggested by Martin
1158
3794.5.1 by Mark Hammond
Add canonical_relpath api function
1159
    rel = relpath(base, path)
1160
    # '.' will have been turned into ''
1161
    if not rel:
1162
        return rel
1163
1164
    abs_base = abspath(base)
1165
    current = abs_base
1166
    _listdir = os.listdir
1167
1168
    # 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.
1169
    bit_iter = iter(rel.split('/'))
3794.5.1 by Mark Hammond
Add canonical_relpath api function
1170
    for bit in bit_iter:
1171
        lbit = bit.lower()
4634.70.2 by John Arbash Meinel
Fix bug #322807, teach cicp_canonical_relpath how to handle
1172
        try:
1173
            next_entries = _listdir(current)
4634.70.3 by John Arbash Meinel
Clean up some terminology, catch a double _listdir request, thanks spiv.
1174
        except OSError: # enoent, eperm, etc
1175
            # We can't find this in the filesystem, so just append the
1176
            # remaining bits.
4634.70.2 by John Arbash Meinel
Fix bug #322807, teach cicp_canonical_relpath how to handle
1177
            current = pathjoin(current, bit, *list(bit_iter))
1178
            break
4634.70.3 by John Arbash Meinel
Clean up some terminology, catch a double _listdir request, thanks spiv.
1179
        for look in next_entries:
3794.5.1 by Mark Hammond
Add canonical_relpath api function
1180
            if lbit == look.lower():
1181
                current = pathjoin(current, look)
1182
                break
1183
        else:
1184
            # got to the end, nothing matched, so we just return the
1185
            # non-existing bits as they were specified (the filename may be
1186
            # the target of a move, for example).
1187
            current = pathjoin(current, bit, *list(bit_iter))
1188
            break
4634.70.2 by John Arbash Meinel
Fix bug #322807, teach cicp_canonical_relpath how to handle
1189
    return current[len(abs_base):].lstrip('/')
3794.5.1 by Mark Hammond
Add canonical_relpath api function
1190
3794.5.13 by Mark Hammond
Tweaks suggested by Martin
1191
# XXX - TODO - we need better detection/integration of case-insensitive
4241.9.5 by Vincent Ladeuil
Fix unicode related OSX failures.
1192
# file-systems; Linux often sees FAT32 devices (or NFS-mounted OSX
1193
# filesystems), for example, so could probably benefit from the same basic
1194
# support there.  For now though, only Windows and OSX get that support, and
1195
# they get it for *all* file-systems!
4241.9.2 by Vincent Ladeuil
Fix most of cicp related failures on OSX.
1196
if sys.platform in ('win32', 'darwin'):
3794.5.29 by Mark Hammond
cicp_canonical_relpath -> _cicp_canonical_relpath
1197
    canonical_relpath = _cicp_canonical_relpath
3794.5.1 by Mark Hammond
Add canonical_relpath api function
1198
else:
1199
    canonical_relpath = relpath
1200
3794.5.15 by Mark Hammond
Add canonical_relpaths() as a placeholder for a future caching implementation.
1201
def canonical_relpaths(base, paths):
1202
    """Create an iterable to canonicalize a sequence of relative paths.
1203
1204
    The intent is for this implementation to use a cache, vastly speeding
1205
    up multiple transformations in the same directory.
1206
    """
1207
    # but for now, we haven't optimized...
1208
    return [canonical_relpath(base, p) for p in paths]
3794.5.1 by Mark Hammond
Add canonical_relpath api function
1209
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
1210
def safe_unicode(unicode_or_utf8_string):
1211
    """Coerce unicode_or_utf8_string into unicode.
1212
1213
    If it is unicode, it is returned.
4204.2.1 by Matt Nordhoff
Fix a broken sentence in osutils.safe_unicode's docstring
1214
    Otherwise it is decoded from utf-8. If decoding fails, the exception is
1215
    wrapped in a BzrBadParameterNotUnicode exception.
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
1216
    """
1217
    if isinstance(unicode_or_utf8_string, unicode):
1218
        return unicode_or_utf8_string
1219
    try:
1220
        return unicode_or_utf8_string.decode('utf8')
1221
    except UnicodeDecodeError:
1996.3.25 by John Arbash Meinel
Make importing errors lazy for osutils
1222
        raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
1534.3.1 by Robert Collins
* bzrlib.osutils.safe_unicode now exists to provide parameter coercion
1223
1224
2249.5.8 by John Arbash Meinel
Add osutils.safe_utf8 and safe_revision_id for the new revision_id work.
1225
def safe_utf8(unicode_or_utf8_string):
1226
    """Coerce unicode_or_utf8_string to a utf8 string.
1227
1228
    If it is a str, it is returned.
1229
    If it is Unicode, it is encoded into a utf-8 string.
1230
    """
1231
    if isinstance(unicode_or_utf8_string, str):
1232
        # TODO: jam 20070209 This is overkill, and probably has an impact on
1233
        #       performance if we are dealing with lots of apis that want a
1234
        #       utf-8 revision id
1235
        try:
1236
            # Make sure it is a valid utf-8 string
1237
            unicode_or_utf8_string.decode('utf-8')
1238
        except UnicodeDecodeError:
1239
            raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
1240
        return unicode_or_utf8_string
1241
    return unicode_or_utf8_string.encode('utf-8')
1242
1243
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
1244
_revision_id_warning = ('Unicode revision ids were deprecated in bzr 0.15.'
1245
                        ' Revision id generators should be creating utf8'
1246
                        ' revision ids.')
1247
1248
1249
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.
1250
    """Revision ids should now be utf8, but at one point they were unicode.
1251
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
1252
    :param unicode_or_utf8_string: A possibly Unicode revision_id. (can also be
1253
        utf8 or None).
1254
    :param warn: Functions that are sanitizing user data can set warn=False
1255
    :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.
1256
    """
2309.4.3 by John Arbash Meinel
(broken) change safe_*_id to emit a warning.
1257
    if (unicode_or_utf8_string is None
1258
        or unicode_or_utf8_string.__class__ == str):
1259
        return unicode_or_utf8_string
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
1260
    if warn:
1261
        symbol_versioning.warn(_revision_id_warning, DeprecationWarning,
1262
                               stacklevel=2)
2309.4.3 by John Arbash Meinel
(broken) change safe_*_id to emit a warning.
1263
    return cache_utf8.encode(unicode_or_utf8_string)
1264
1265
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
1266
_file_id_warning = ('Unicode file ids were deprecated in bzr 0.15. File id'
1267
                    ' generators should be creating utf8 file ids.')
1268
1269
1270
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.
1271
    """File ids should now be utf8, but at one point they were unicode.
1272
1273
    This is the same as safe_utf8, except it uses the cached encode functions
1274
    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.
1275
1276
    :param unicode_or_utf8_string: A possibly Unicode file_id. (can also be
1277
        utf8 or None).
1278
    :param warn: Functions that are sanitizing user data can set warn=False
1279
    :return: None or a utf8 file id.
2309.4.3 by John Arbash Meinel
(broken) change safe_*_id to emit a warning.
1280
    """
1281
    if (unicode_or_utf8_string is None
1282
        or unicode_or_utf8_string.__class__ == str):
1283
        return unicode_or_utf8_string
2309.4.4 by John Arbash Meinel
Change what warnings are raised, and add tests that they are used.
1284
    if warn:
1285
        symbol_versioning.warn(_file_id_warning, DeprecationWarning,
1286
                               stacklevel=2)
2309.4.3 by John Arbash Meinel
(broken) change safe_*_id to emit a warning.
1287
    return cache_utf8.encode(unicode_or_utf8_string)
2294.1.4 by John Arbash Meinel
Add safe_file_id as a helper in osutils.
1288
1289
1185.85.75 by John Arbash Meinel
Adding bzrlib.osutils.unicode_filename to handle unicode normalization for file paths.
1290
_platform_normalizes_filenames = False
1291
if sys.platform == 'darwin':
1292
    _platform_normalizes_filenames = True
1293
1294
1295
def normalizes_filenames():
1296
    """Return True if this platform normalizes unicode filenames.
1297
1298
    Mac OSX does, Windows/Linux do not.
1299
    """
1300
    return _platform_normalizes_filenames
1301
1302
1830.3.2 by John Arbash Meinel
normalized_filename is a much better name
1303
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
1304
    """Get the unicode normalized path, and if you can access the file.
1305
1306
    On platforms where the system normalizes filenames (Mac OSX),
1307
    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
1308
    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
1309
    (Windows, Linux), you have to access a file by its exact path.
1310
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1311
    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
1312
    the standard for XML documents.
1313
1314
    So return the normalized path, and a flag indicating if the file
1315
    can be accessed by that path.
1316
    """
1317
3201.1.1 by jameinel
Fix bug #185458, switch from NFKC to NFC and add tests for filenames that would be broken under NFKC
1318
    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
1319
1320
1830.3.2 by John Arbash Meinel
normalized_filename is a much better name
1321
def _inaccessible_normalized_filename(path):
1322
    __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
1323
3201.1.1 by jameinel
Fix bug #185458, switch from NFKC to NFC and add tests for filenames that would be broken under NFKC
1324
    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
1325
    return normalized, normalized == path
1326
1327
1185.85.75 by John Arbash Meinel
Adding bzrlib.osutils.unicode_filename to handle unicode normalization for file paths.
1328
if _platform_normalizes_filenames:
1830.3.2 by John Arbash Meinel
normalized_filename is a much better name
1329
    normalized_filename = _accessible_normalized_filename
1185.85.75 by John Arbash Meinel
Adding bzrlib.osutils.unicode_filename to handle unicode normalization for file paths.
1330
else:
1830.3.2 by John Arbash Meinel
normalized_filename is a much better name
1331
    normalized_filename = _inaccessible_normalized_filename
1185.85.75 by John Arbash Meinel
Adding bzrlib.osutils.unicode_filename to handle unicode normalization for file paths.
1332
1333
4747.3.6 by Vincent Ladeuil
terminal_width can now returns None.
1334
default_terminal_width = 80
1335
"""The default terminal width for ttys.
1336
1337
This is defined so that higher levels can share a common fallback value when
1338
terminal_width() returns None.
1339
"""
1340
1341
1185.33.60 by Martin Pool
Use full terminal width for verbose test output.
1342
def terminal_width():
4747.3.6 by Vincent Ladeuil
terminal_width can now returns None.
1343
    """Return terminal width.
1344
1345
    None is returned if the width can't established precisely.
4747.4.5 by Vincent Ladeuil
More robusts tests for osutils.terminal_width().
1346
1347
    The rules are:
1348
    - if BZR_COLUMNS is set, returns its value
1349
    - if there is no controlling terminal, returns None
1350
    - if COLUMNS is set, returns its value,
1351
1352
    From there, we need to query the OS to get the size of the controlling
1353
    terminal.
1354
1355
    Unices:
1356
    - get termios.TIOCGWINSZ
1357
    - if an error occurs or a negative value is obtained, returns None
1358
1359
    Windows:
1360
    
1361
    - win32utils.get_console_size() decides,
1362
    - returns None on error (provided default value)
4747.3.6 by Vincent Ladeuil
terminal_width can now returns None.
1363
    """
4747.3.4 by Vincent Ladeuil
Add tests, introduce explicit default values, always respect COLUMNS.
1364
4747.3.7 by Vincent Ladeuil
Introduce BZR_COLUMNS since COLUMNS behaviour is too obscure.
1365
    # If BZR_COLUMNS is set, take it, user is always right
1366
    try:
1367
        return int(os.environ['BZR_COLUMNS'])
1368
    except (KeyError, ValueError):
1369
        pass
1370
4747.3.3 by Vincent Ladeuil
More complete fix (previous one changed the focus).
1371
    isatty = getattr(sys.stdout, 'isatty', None)
1372
    if  isatty is None or not isatty():
4747.3.7 by Vincent Ladeuil
Introduce BZR_COLUMNS since COLUMNS behaviour is too obscure.
1373
        # Don't guess, setting BZR_COLUMNS is the recommended way to override.
4747.3.6 by Vincent Ladeuil
terminal_width can now returns None.
1374
        return None
4747.3.1 by Joke de Buhr
Prevent linebreaks in output if it's not connected to a tty.
1375
4747.4.5 by Vincent Ladeuil
More robusts tests for osutils.terminal_width().
1376
    # If COLUMNS is set, take it, the terminal knows better (even inside a
1377
    # given terminal, the application can decide to set COLUMNS to a lower
1378
    # 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.
1379
    try:
1380
        return int(os.environ['COLUMNS'])
1381
    except (KeyError, ValueError):
1382
        pass
1383
4747.4.5 by Vincent Ladeuil
More robusts tests for osutils.terminal_width().
1384
    width, height = _terminal_size(None, None)
1385
    if width <= 0:
1386
        # Consider invalid values as meaning no width
1387
        return None
1388
1389
    return width
1390
1391
1392
def _win32_terminal_size(width, height):
1393
    width, height = win32utils.get_console_size(defaultx=width, defaulty=height)
1394
    return width, height
1395
1396
1397
def _ioctl_terminal_size(width, height):
1185.33.60 by Martin Pool
Use full terminal width for verbose test output.
1398
    try:
1704.2.2 by Martin Pool
Detect terminal width using ioctl
1399
        import struct, fcntl, termios
1400
        s = struct.pack('HHHH', 0, 0, 0, 0)
1401
        x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
4747.5.1 by Vincent Ladeuil
catch SIGWINCH, but that means soem IO can be interrupted and the code
1402
        height, width = struct.unpack('HHHH', x)[0:2]
4747.3.4 by Vincent Ladeuil
Add tests, introduce explicit default values, always respect COLUMNS.
1403
    except (IOError, AttributeError):
4747.4.5 by Vincent Ladeuil
More robusts tests for osutils.terminal_width().
1404
        pass
1405
    return width, height
1406
1407
_terminal_size = None
1408
"""Returns the terminal size as (width, height).
1409
1410
:param width: Default value for width.
1411
:param height: Default value for height.
1412
1413
This is defined specifically for each OS and query the size of the controlling
1414
terminal. If any error occurs, the provided default values should be returned.
1415
"""
1416
if sys.platform == 'win32':
1417
    _terminal_size = _win32_terminal_size
1418
else:
1419
    _terminal_size = _ioctl_terminal_size
1534.7.25 by Aaron Bentley
Added set_executability
1420
1963.1.5 by John Arbash Meinel
Create an osutils helper function for modifying the environment
1421
4747.5.1 by Vincent Ladeuil
catch SIGWINCH, but that means soem IO can be interrupted and the code
1422
def _terminal_size_changed(signum, frame):
1423
    """Set COLUMNS upon receiving a SIGnal for WINdow size CHange."""
1424
    width, height = _terminal_size(None, None)
1425
    if width is not None:
1426
        os.environ['COLUMNS'] = str(width)
1427
signal.signal(signal.SIGWINCH, _terminal_size_changed)
1428
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