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