~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: Martin Pool
  • Date: 2006-06-04 21:22:51 UTC
  • mto: This revision was merged to the branch mainline in revision 1797.
  • Revision ID: mbp@sourcefrog.net-20060604212251-8f5dc15da9189eac
When an unhandled exception occurs, write the traceback to stderr.

Also encourage the user to send this to the list.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
# Bazaar-NG -- distributed version control
2
 
 
 
2
#
3
3
# Copyright (C) 2005 by Canonical Ltd
4
 
 
 
4
#
5
5
# This program is free software; you can redistribute it and/or modify
6
6
# it under the terms of the GNU General Public License as published by
7
7
# the Free Software Foundation; either version 2 of the License, or
8
8
# (at your option) any later version.
9
 
 
 
9
#
10
10
# This program is distributed in the hope that it will be useful,
11
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
12
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
13
# GNU General Public License for more details.
14
 
 
 
14
#
15
15
# You should have received a copy of the GNU General Public License
16
16
# along with this program; if not, write to the Free Software
17
17
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
18
 
19
 
import os, types, re, time, errno
20
 
from stat import S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE
 
19
from shutil import copyfile
 
20
from stat import (S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE,
 
21
                  S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
 
22
from cStringIO import StringIO
 
23
import errno
 
24
import os
 
25
import re
 
26
import sha
 
27
import shutil
 
28
import stat
 
29
import string
 
30
import sys
 
31
import time
 
32
import types
 
33
import tempfile
21
34
 
22
 
from errors import bailout, BzrError
23
 
from trace import mutter
24
35
import bzrlib
 
36
from bzrlib.errors import (BzrError,
 
37
                           BzrBadParameterNotUnicode,
 
38
                           NoSuchFile,
 
39
                           PathNotChild,
 
40
                           IllegalPath,
 
41
                           )
 
42
from bzrlib.symbol_versioning import *
 
43
from bzrlib.trace import mutter
 
44
import bzrlib.win32console
 
45
 
25
46
 
26
47
def make_readonly(filename):
27
48
    """Make a filename read-only."""
28
 
    # TODO: probably needs to be fixed for windows
29
49
    mod = os.stat(filename).st_mode
30
50
    mod = mod & 0777555
31
51
    os.chmod(filename, mod)
37
57
    os.chmod(filename, mod)
38
58
 
39
59
 
40
 
_QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/_~-])')
 
60
_QUOTE_RE = None
 
61
 
 
62
 
41
63
def quotefn(f):
42
 
    """Return shell-quoted filename"""
43
 
    ## We could be a bit more terse by using double-quotes etc
44
 
    f = _QUOTE_RE.sub(r'\\\1', f)
45
 
    if f[0] == '~':
46
 
        f[0:1] = r'\~' 
47
 
    return f
48
 
 
49
 
 
50
 
def file_kind(f):
51
 
    mode = os.lstat(f)[ST_MODE]
52
 
    if S_ISREG(mode):
53
 
        return 'file'
54
 
    elif S_ISDIR(mode):
55
 
        return 'directory'
56
 
    elif S_ISLNK(mode):
57
 
        return 'symlink'
58
 
    else:
59
 
        raise BzrError("can't handle file kind with mode %o of %r" % (mode, f)) 
60
 
 
 
64
    """Return a quoted filename filename
 
65
 
 
66
    This previously used backslash quoting, but that works poorly on
 
67
    Windows."""
 
68
    # TODO: I'm not really sure this is the best format either.x
 
69
    global _QUOTE_RE
 
70
    if _QUOTE_RE == None:
 
71
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
 
72
        
 
73
    if _QUOTE_RE.search(f):
 
74
        return '"' + f + '"'
 
75
    else:
 
76
        return f
 
77
 
 
78
 
 
79
_formats = {
 
80
    stat.S_IFDIR:'directory',
 
81
    stat.S_IFCHR:'chardev',
 
82
    stat.S_IFBLK:'block',
 
83
    stat.S_IFREG:'file',
 
84
    stat.S_IFIFO:'fifo',
 
85
    stat.S_IFLNK:'symlink',
 
86
    stat.S_IFSOCK:'socket',
 
87
}
 
88
def file_kind(f, _formats=_formats, _unknown='unknown', _lstat=os.lstat):
 
89
    try:
 
90
        return _formats[_lstat(f).st_mode & 0170000]
 
91
    except KeyError:
 
92
        return _unknown
 
93
 
 
94
 
 
95
def kind_marker(kind):
 
96
    if kind == 'file':
 
97
        return ''
 
98
    elif kind == 'directory':
 
99
        return '/'
 
100
    elif kind == 'symlink':
 
101
        return '@'
 
102
    else:
 
103
        raise BzrError('invalid file kind %r' % kind)
 
104
 
 
105
lexists = getattr(os.path, 'lexists', None)
 
106
if lexists is None:
 
107
    def lexists(f):
 
108
        try:
 
109
            if hasattr(os, 'lstat'):
 
110
                os.lstat(f)
 
111
            else:
 
112
                os.stat(f)
 
113
            return True
 
114
        except OSError,e:
 
115
            if e.errno == errno.ENOENT:
 
116
                return False;
 
117
            else:
 
118
                raise BzrError("lstat/stat of (%r): %r" % (f, e))
 
119
 
 
120
 
 
121
def fancy_rename(old, new, rename_func, unlink_func):
 
122
    """A fancy rename, when you don't have atomic rename.
 
123
    
 
124
    :param old: The old path, to rename from
 
125
    :param new: The new path, to rename to
 
126
    :param rename_func: The potentially non-atomic rename function
 
127
    :param unlink_func: A way to delete the target file if the full rename succeeds
 
128
    """
 
129
 
 
130
    # sftp rename doesn't allow overwriting, so play tricks:
 
131
    import random
 
132
    base = os.path.basename(new)
 
133
    dirname = os.path.dirname(new)
 
134
    tmp_name = u'tmp.%s.%.9f.%d.%s' % (base, time.time(), os.getpid(), rand_chars(10))
 
135
    tmp_name = pathjoin(dirname, tmp_name)
 
136
 
 
137
    # Rename the file out of the way, but keep track if it didn't exist
 
138
    # We don't want to grab just any exception
 
139
    # something like EACCES should prevent us from continuing
 
140
    # The downside is that the rename_func has to throw an exception
 
141
    # with an errno = ENOENT, or NoSuchFile
 
142
    file_existed = False
 
143
    try:
 
144
        rename_func(new, tmp_name)
 
145
    except (NoSuchFile,), e:
 
146
        pass
 
147
    except IOError, e:
 
148
        # RBC 20060103 abstraction leakage: the paramiko SFTP clients rename
 
149
        # function raises an IOError with errno == None when a rename fails.
 
150
        # This then gets caught here.
 
151
        if e.errno not in (None, errno.ENOENT, errno.ENOTDIR):
 
152
            raise
 
153
    except Exception, e:
 
154
        if (not hasattr(e, 'errno') 
 
155
            or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
 
156
            raise
 
157
    else:
 
158
        file_existed = True
 
159
 
 
160
    success = False
 
161
    try:
 
162
        # This may throw an exception, in which case success will
 
163
        # not be set.
 
164
        rename_func(old, new)
 
165
        success = True
 
166
    finally:
 
167
        if file_existed:
 
168
            # If the file used to exist, rename it back into place
 
169
            # otherwise just delete it from the tmp location
 
170
            if success:
 
171
                unlink_func(tmp_name)
 
172
            else:
 
173
                rename_func(tmp_name, new)
 
174
 
 
175
# Default is to just use the python builtins, but these can be rebound on
 
176
# particular platforms.
 
177
abspath = os.path.abspath
 
178
realpath = os.path.realpath
 
179
pathjoin = os.path.join
 
180
normpath = os.path.normpath
 
181
getcwd = os.getcwdu
 
182
mkdtemp = tempfile.mkdtemp
 
183
rename = os.rename
 
184
dirname = os.path.dirname
 
185
basename = os.path.basename
 
186
rmtree = shutil.rmtree
 
187
 
 
188
MIN_ABS_PATHLENGTH = 1
 
189
 
 
190
if os.name == "posix":
 
191
    # In Python 2.4.2 and older, os.path.abspath and os.path.realpath
 
192
    # choke on a Unicode string containing a relative path if
 
193
    # os.getcwd() returns a non-sys.getdefaultencoding()-encoded
 
194
    # string.
 
195
    _fs_enc = sys.getfilesystemencoding()
 
196
    def abspath(path):
 
197
        return os.path.abspath(path.encode(_fs_enc)).decode(_fs_enc)
 
198
 
 
199
    def realpath(path):
 
200
        return os.path.realpath(path.encode(_fs_enc)).decode(_fs_enc)
 
201
 
 
202
if sys.platform == 'win32':
 
203
    # We need to use the Unicode-aware os.path.abspath and
 
204
    # os.path.realpath on Windows systems.
 
205
    def abspath(path):
 
206
        return os.path.abspath(path).replace('\\', '/')
 
207
 
 
208
    def realpath(path):
 
209
        return os.path.realpath(path).replace('\\', '/')
 
210
 
 
211
    def pathjoin(*args):
 
212
        return os.path.join(*args).replace('\\', '/')
 
213
 
 
214
    def normpath(path):
 
215
        return os.path.normpath(path).replace('\\', '/')
 
216
 
 
217
    def getcwd():
 
218
        return os.getcwdu().replace('\\', '/')
 
219
 
 
220
    def mkdtemp(*args, **kwargs):
 
221
        return tempfile.mkdtemp(*args, **kwargs).replace('\\', '/')
 
222
 
 
223
    def rename(old, new):
 
224
        fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
 
225
 
 
226
    MIN_ABS_PATHLENGTH = 3
 
227
 
 
228
    def _win32_delete_readonly(function, path, excinfo):
 
229
        """Error handler for shutil.rmtree function [for win32]
 
230
        Helps to remove files and dirs marked as read-only.
 
231
        """
 
232
        type_, value = excinfo[:2]
 
233
        if function in (os.remove, os.rmdir) \
 
234
            and type_ == OSError \
 
235
            and value.errno == errno.EACCES:
 
236
            bzrlib.osutils.make_writable(path)
 
237
            function(path)
 
238
        else:
 
239
            raise
 
240
 
 
241
    def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
 
242
        """Replacer for shutil.rmtree: could remove readonly dirs/files"""
 
243
        return shutil.rmtree(path, ignore_errors, onerror)
 
244
 
 
245
 
 
246
def normalizepath(f):
 
247
    if hasattr(os.path, 'realpath'):
 
248
        F = realpath
 
249
    else:
 
250
        F = abspath
 
251
    [p,e] = os.path.split(f)
 
252
    if e == "" or e == "." or e == "..":
 
253
        return F(f)
 
254
    else:
 
255
        return pathjoin(F(p), e)
 
256
 
 
257
 
 
258
def backup_file(fn):
 
259
    """Copy a file to a backup.
 
260
 
 
261
    Backups are named in GNU-style, with a ~ suffix.
 
262
 
 
263
    If the file is already a backup, it's not copied.
 
264
    """
 
265
    if fn[-1] == '~':
 
266
        return
 
267
    bfn = fn + '~'
 
268
 
 
269
    if has_symlinks() and os.path.islink(fn):
 
270
        target = os.readlink(fn)
 
271
        os.symlink(target, bfn)
 
272
        return
 
273
    inf = file(fn, 'rb')
 
274
    try:
 
275
        content = inf.read()
 
276
    finally:
 
277
        inf.close()
 
278
    
 
279
    outf = file(bfn, 'wb')
 
280
    try:
 
281
        outf.write(content)
 
282
    finally:
 
283
        outf.close()
61
284
 
62
285
 
63
286
def isdir(f):
68
291
        return False
69
292
 
70
293
 
71
 
 
72
294
def isfile(f):
73
295
    """True if f is a regular file."""
74
296
    try:
76
298
    except OSError:
77
299
        return False
78
300
 
 
301
def islink(f):
 
302
    """True if f is a symlink."""
 
303
    try:
 
304
        return S_ISLNK(os.lstat(f)[ST_MODE])
 
305
    except OSError:
 
306
        return False
 
307
 
 
308
def is_inside(dir, fname):
 
309
    """True if fname is inside dir.
 
310
    
 
311
    The parameters should typically be passed to osutils.normpath first, so
 
312
    that . and .. and repeated slashes are eliminated, and the separators
 
313
    are canonical for the platform.
 
314
    
 
315
    The empty string as a dir name is taken as top-of-tree and matches 
 
316
    everything.
 
317
    
 
318
    >>> is_inside('src', pathjoin('src', 'foo.c'))
 
319
    True
 
320
    >>> is_inside('src', 'srccontrol')
 
321
    False
 
322
    >>> is_inside('src', pathjoin('src', 'a', 'a', 'a', 'foo.c'))
 
323
    True
 
324
    >>> is_inside('foo.c', 'foo.c')
 
325
    True
 
326
    >>> is_inside('foo.c', '')
 
327
    False
 
328
    >>> is_inside('', 'foo.c')
 
329
    True
 
330
    """
 
331
    # XXX: Most callers of this can actually do something smarter by 
 
332
    # looking at the inventory
 
333
    if dir == fname:
 
334
        return True
 
335
    
 
336
    if dir == '':
 
337
        return True
 
338
 
 
339
    if dir[-1] != '/':
 
340
        dir += '/'
 
341
 
 
342
    return fname.startswith(dir)
 
343
 
 
344
 
 
345
def is_inside_any(dir_list, fname):
 
346
    """True if fname is inside any of given dirs."""
 
347
    for dirname in dir_list:
 
348
        if is_inside(dirname, fname):
 
349
            return True
 
350
    else:
 
351
        return False
 
352
 
79
353
 
80
354
def pumpfile(fromfile, tofile):
81
355
    """Copy contents of one file to another."""
82
 
    tofile.write(fromfile.read())
83
 
 
84
 
 
85
 
def uuid():
86
 
    """Return a new UUID"""
87
 
    try:
88
 
        return file('/proc/sys/kernel/random/uuid').readline().rstrip('\n')
89
 
    except IOError:
90
 
        return chomp(os.popen('uuidgen').readline())
 
356
    BUFSIZE = 32768
 
357
    while True:
 
358
        b = fromfile.read(BUFSIZE)
 
359
        if not b:
 
360
            break
 
361
        tofile.write(b)
 
362
 
 
363
 
 
364
def file_iterator(input_file, readsize=32768):
 
365
    while True:
 
366
        b = input_file.read(readsize)
 
367
        if len(b) == 0:
 
368
            break
 
369
        yield b
91
370
 
92
371
 
93
372
def sha_file(f):
94
 
    import sha
95
373
    if hasattr(f, 'tell'):
96
374
        assert f.tell() == 0
97
375
    s = sha.new()
104
382
    return s.hexdigest()
105
383
 
106
384
 
 
385
 
 
386
def sha_strings(strings):
 
387
    """Return the sha-1 of concatenation of strings"""
 
388
    s = sha.new()
 
389
    map(s.update, strings)
 
390
    return s.hexdigest()
 
391
 
 
392
 
107
393
def sha_string(f):
108
 
    import sha
109
394
    s = sha.new()
110
395
    s.update(f)
111
396
    return s.hexdigest()
112
397
 
113
398
 
114
 
 
115
399
def fingerprint_file(f):
116
 
    import sha
117
400
    s = sha.new()
118
401
    b = f.read()
119
402
    s.update(b)
122
405
            'sha1': s.hexdigest()}
123
406
 
124
407
 
125
 
def config_dir():
126
 
    """Return per-user configuration directory.
127
 
 
128
 
    By default this is ~/.bzr.conf/
129
 
    
130
 
    TODO: Global option --config-dir to override this.
131
 
    """
132
 
    return os.path.expanduser("~/.bzr.conf")
133
 
 
134
 
 
135
 
def _auto_user_id():
136
 
    """Calculate automatic user identification.
137
 
 
138
 
    Returns (realname, email).
139
 
 
140
 
    Only used when none is set in the environment or the id file.
141
 
 
142
 
    This previously used the FQDN as the default domain, but that can
143
 
    be very slow on machines where DNS is broken.  So now we simply
144
 
    use the hostname.
145
 
    """
146
 
    import socket
147
 
 
148
 
    # XXX: Any good way to get real user name on win32?
149
 
 
150
 
    try:
151
 
        import pwd
152
 
        uid = os.getuid()
153
 
        w = pwd.getpwuid(uid)
154
 
        gecos = w.pw_gecos.decode(bzrlib.user_encoding)
155
 
        username = w.pw_name.decode(bzrlib.user_encoding)
156
 
        comma = gecos.find(',')
157
 
        if comma == -1:
158
 
            realname = gecos
159
 
        else:
160
 
            realname = gecos[:comma]
161
 
        if not realname:
162
 
            realname = username
163
 
 
164
 
    except ImportError:
165
 
        import getpass
166
 
        realname = username = getpass.getuser().decode(bzrlib.user_encoding)
167
 
 
168
 
    return realname, (username + '@' + socket.gethostname())
169
 
 
170
 
 
171
 
def _get_user_id():
172
 
    """Return the full user id from a file or environment variable.
173
 
 
174
 
    TODO: Allow taking this from a file in the branch directory too
175
 
    for per-branch ids."""
176
 
    v = os.environ.get('BZREMAIL')
177
 
    if v:
178
 
        return v.decode(bzrlib.user_encoding)
179
 
    
180
 
    try:
181
 
        return (open(os.path.join(config_dir(), "email"))
182
 
                .read()
183
 
                .decode(bzrlib.user_encoding)
184
 
                .rstrip("\r\n"))
185
 
    except IOError, e:
186
 
        if e.errno != errno.ENOENT:
187
 
            raise e
188
 
 
189
 
    v = os.environ.get('EMAIL')
190
 
    if v:
191
 
        return v.decode(bzrlib.user_encoding)
192
 
    else:    
193
 
        return None
194
 
 
195
 
 
196
 
def username():
197
 
    """Return email-style username.
198
 
 
199
 
    Something similar to 'Martin Pool <mbp@sourcefrog.net>'
200
 
 
201
 
    TODO: Check it's reasonably well-formed.
202
 
    """
203
 
    v = _get_user_id()
204
 
    if v:
205
 
        return v
206
 
    
207
 
    name, email = _auto_user_id()
208
 
    if name:
209
 
        return '%s <%s>' % (name, email)
210
 
    else:
211
 
        return email
212
 
 
213
 
 
214
 
_EMAIL_RE = re.compile(r'[\w+.-]+@[\w+.-]+')
215
 
def user_email():
216
 
    """Return just the email component of a username."""
217
 
    e = _get_user_id()
218
 
    if e:
219
 
        m = _EMAIL_RE.search(e)
220
 
        if not m:
221
 
            bailout("%r doesn't seem to contain a reasonable email address" % e)
222
 
        return m.group(0)
223
 
 
224
 
    return _auto_user_id()[1]
225
 
    
226
 
 
227
 
 
228
408
def compare_files(a, b):
229
409
    """Returns true if equal in contents"""
230
410
    BUFSIZE = 4096
237
417
            return True
238
418
 
239
419
 
240
 
 
241
420
def local_time_offset(t=None):
242
421
    """Return offset of local zone from GMT, either at present or at time t."""
243
422
    # python2.3 localtime() can't take None
250
429
        return -time.timezone
251
430
 
252
431
    
253
 
def format_date(t, offset=0, timezone='original'):
 
432
def format_date(t, offset=0, timezone='original', date_fmt=None, 
 
433
                show_offset=True):
254
434
    ## TODO: Perhaps a global option to use either universal or local time?
255
435
    ## Or perhaps just let people set $TZ?
256
436
    assert isinstance(t, float)
266
446
        tt = time.localtime(t)
267
447
        offset = local_time_offset(t)
268
448
    else:
269
 
        bailout("unsupported timezone format %r",
270
 
                ['options are "utc", "original", "local"'])
271
 
 
272
 
    return (time.strftime("%a %Y-%m-%d %H:%M:%S", tt)
273
 
            + ' %+03d%02d' % (offset / 3600, (offset / 60) % 60))
 
449
        raise BzrError("unsupported timezone format %r" % timezone,
 
450
                       ['options are "utc", "original", "local"'])
 
451
    if date_fmt is None:
 
452
        date_fmt = "%a %Y-%m-%d %H:%M:%S"
 
453
    if show_offset:
 
454
        offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
 
455
    else:
 
456
        offset_str = ''
 
457
    return (time.strftime(date_fmt, tt) +  offset_str)
274
458
 
275
459
 
276
460
def compact_date(when):
283
467
    return os.fstat(f.fileno())[ST_SIZE]
284
468
 
285
469
 
286
 
if hasattr(os, 'urandom'): # python 2.4 and later
 
470
# Define rand_bytes based on platform.
 
471
try:
 
472
    # Python 2.4 and later have os.urandom,
 
473
    # but it doesn't work on some arches
 
474
    os.urandom(1)
287
475
    rand_bytes = os.urandom
288
 
else:
289
 
    # FIXME: No good on non-Linux
290
 
    _rand_file = file('/dev/urandom', 'rb')
291
 
    rand_bytes = _rand_file.read
 
476
except (NotImplementedError, AttributeError):
 
477
    # If python doesn't have os.urandom, or it doesn't work,
 
478
    # then try to first pull random data from /dev/urandom
 
479
    if os.path.exists("/dev/urandom"):
 
480
        rand_bytes = file('/dev/urandom', 'rb').read
 
481
    # Otherwise, use this hack as a last resort
 
482
    else:
 
483
        # not well seeded, but better than nothing
 
484
        def rand_bytes(n):
 
485
            import random
 
486
            s = ''
 
487
            while n:
 
488
                s += chr(random.randint(0, 255))
 
489
                n -= 1
 
490
            return s
 
491
 
 
492
 
 
493
ALNUM = '0123456789abcdefghijklmnopqrstuvwxyz'
 
494
def rand_chars(num):
 
495
    """Return a random string of num alphanumeric characters
 
496
    
 
497
    The result only contains lowercase chars because it may be used on 
 
498
    case-insensitive filesystems.
 
499
    """
 
500
    s = ''
 
501
    for raw_byte in rand_bytes(num):
 
502
        s += ALNUM[ord(raw_byte) % 36]
 
503
    return s
292
504
 
293
505
 
294
506
## TODO: We could later have path objects that remember their list
308
520
    >>> splitpath('a/../b')
309
521
    Traceback (most recent call last):
310
522
    ...
311
 
    BzrError: ("sorry, '..' not allowed in path", [])
 
523
    BzrError: sorry, '..' not allowed in path
312
524
    """
313
525
    assert isinstance(p, types.StringTypes)
314
526
 
319
531
    rps = []
320
532
    for f in ps:
321
533
        if f == '..':
322
 
            bailout("sorry, %r not allowed in path" % f)
 
534
            raise BzrError("sorry, %r not allowed in path" % f)
323
535
        elif (f == '.') or (f == ''):
324
536
            pass
325
537
        else:
330
542
    assert isinstance(p, list)
331
543
    for f in p:
332
544
        if (f == '..') or (f == None) or (f == ''):
333
 
            bailout("sorry, %r not allowed in path" % f)
334
 
    return os.path.join(*p)
335
 
 
336
 
 
 
545
            raise BzrError("sorry, %r not allowed in path" % f)
 
546
    return pathjoin(*p)
 
547
 
 
548
 
 
549
@deprecated_function(zero_nine)
337
550
def appendpath(p1, p2):
338
551
    if p1 == '':
339
552
        return p2
340
553
    else:
341
 
        return os.path.join(p1, p2)
 
554
        return pathjoin(p1, p2)
342
555
    
343
556
 
344
 
def extern_command(cmd, ignore_errors = False):
345
 
    mutter('external command: %s' % `cmd`)
346
 
    if os.system(cmd):
347
 
        if not ignore_errors:
348
 
            bailout('command failed')
349
 
 
 
557
def split_lines(s):
 
558
    """Split s into lines, but without removing the newline characters."""
 
559
    lines = s.split('\n')
 
560
    result = [line + '\n' for line in lines[:-1]]
 
561
    if lines[-1]:
 
562
        result.append(lines[-1])
 
563
    return result
 
564
 
 
565
 
 
566
def hardlinks_good():
 
567
    return sys.platform not in ('win32', 'cygwin', 'darwin')
 
568
 
 
569
 
 
570
def link_or_copy(src, dest):
 
571
    """Hardlink a file, or copy it if it can't be hardlinked."""
 
572
    if not hardlinks_good():
 
573
        copyfile(src, dest)
 
574
        return
 
575
    try:
 
576
        os.link(src, dest)
 
577
    except (OSError, IOError), e:
 
578
        if e.errno != errno.EXDEV:
 
579
            raise
 
580
        copyfile(src, dest)
 
581
 
 
582
def delete_any(full_path):
 
583
    """Delete a file or directory."""
 
584
    try:
 
585
        os.unlink(full_path)
 
586
    except OSError, e:
 
587
    # We may be renaming a dangling inventory id
 
588
        if e.errno not in (errno.EISDIR, errno.EACCES, errno.EPERM):
 
589
            raise
 
590
        os.rmdir(full_path)
 
591
 
 
592
 
 
593
def has_symlinks():
 
594
    if hasattr(os, 'symlink'):
 
595
        return True
 
596
    else:
 
597
        return False
 
598
        
 
599
 
 
600
def contains_whitespace(s):
 
601
    """True if there are any whitespace characters in s."""
 
602
    for ch in string.whitespace:
 
603
        if ch in s:
 
604
            return True
 
605
    else:
 
606
        return False
 
607
 
 
608
 
 
609
def contains_linebreaks(s):
 
610
    """True if there is any vertical whitespace in s."""
 
611
    for ch in '\f\n\r':
 
612
        if ch in s:
 
613
            return True
 
614
    else:
 
615
        return False
 
616
 
 
617
 
 
618
def relpath(base, path):
 
619
    """Return path relative to base, or raise exception.
 
620
 
 
621
    The path may be either an absolute path or a path relative to the
 
622
    current working directory.
 
623
 
 
624
    os.path.commonprefix (python2.4) has a bad bug that it works just
 
625
    on string prefixes, assuming that '/u' is a prefix of '/u2'.  This
 
626
    avoids that problem.
 
627
    """
 
628
 
 
629
    assert len(base) >= MIN_ABS_PATHLENGTH, ('Length of base must be equal or'
 
630
        ' exceed the platform minimum length (which is %d)' % 
 
631
        MIN_ABS_PATHLENGTH)
 
632
    rp = abspath(path)
 
633
 
 
634
    s = []
 
635
    head = rp
 
636
    while len(head) >= len(base):
 
637
        if head == base:
 
638
            break
 
639
        head, tail = os.path.split(head)
 
640
        if tail:
 
641
            s.insert(0, tail)
 
642
    else:
 
643
        # XXX This should raise a NotChildPath exception, as its not tied
 
644
        # to branch anymore.
 
645
        raise PathNotChild(rp, base)
 
646
 
 
647
    if s:
 
648
        return pathjoin(*s)
 
649
    else:
 
650
        return ''
 
651
 
 
652
 
 
653
def safe_unicode(unicode_or_utf8_string):
 
654
    """Coerce unicode_or_utf8_string into unicode.
 
655
 
 
656
    If it is unicode, it is returned.
 
657
    Otherwise it is decoded from utf-8. If a decoding error
 
658
    occurs, it is wrapped as a If the decoding fails, the exception is wrapped 
 
659
    as a BzrBadParameter exception.
 
660
    """
 
661
    if isinstance(unicode_or_utf8_string, unicode):
 
662
        return unicode_or_utf8_string
 
663
    try:
 
664
        return unicode_or_utf8_string.decode('utf8')
 
665
    except UnicodeDecodeError:
 
666
        raise BzrBadParameterNotUnicode(unicode_or_utf8_string)
 
667
 
 
668
 
 
669
def terminal_width():
 
670
    """Return estimated terminal width."""
 
671
    if sys.platform == 'win32':
 
672
        import bzrlib.win32console
 
673
        return bzrlib.win32console.get_console_size()[0]
 
674
    width = 0
 
675
    try:
 
676
        import struct, fcntl, termios
 
677
        s = struct.pack('HHHH', 0, 0, 0, 0)
 
678
        x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
 
679
        width = struct.unpack('HHHH', x)[1]
 
680
    except IOError:
 
681
        pass
 
682
    if width <= 0:
 
683
        try:
 
684
            width = int(os.environ['COLUMNS'])
 
685
        except:
 
686
            pass
 
687
    if width <= 0:
 
688
        width = 80
 
689
 
 
690
    return width
 
691
 
 
692
def supports_executable():
 
693
    return sys.platform != "win32"
 
694
 
 
695
 
 
696
def strip_trailing_slash(path):
 
697
    """Strip trailing slash, except for root paths.
 
698
    The definition of 'root path' is platform-dependent.
 
699
    """
 
700
    if len(path) != MIN_ABS_PATHLENGTH and path[-1] == '/':
 
701
        return path[:-1]
 
702
    else:
 
703
        return path
 
704
 
 
705
 
 
706
_validWin32PathRE = re.compile(r'^([A-Za-z]:[/\\])?[^:<>*"?\|]*$')
 
707
 
 
708
 
 
709
def check_legal_path(path):
 
710
    """Check whether the supplied path is legal.  
 
711
    This is only required on Windows, so we don't test on other platforms
 
712
    right now.
 
713
    """
 
714
    if sys.platform != "win32":
 
715
        return
 
716
    if _validWin32PathRE.match(path) is None:
 
717
        raise IllegalPath(path)