/brz/remove-bazaar

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