~bzr-pqm/bzr/bzr.dev

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