~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

Late bind to PatienceSequenceMatcher in merge3.py

Show diffs side-by-side

added added

removed removed

Lines of Context:
24
24
import os
25
25
import re
26
26
import sha
 
27
import shutil
27
28
import string
28
29
import sys
29
30
import time
30
31
import types
 
32
import tempfile
31
33
 
32
34
import bzrlib
33
 
from bzrlib.errors import BzrError, NotBranchError
 
35
from bzrlib.errors import (BzrError,
 
36
                           BzrBadParameterNotUnicode,
 
37
                           NoSuchFile,
 
38
                           PathNotChild,
 
39
                           IllegalPath,
 
40
                           )
34
41
from bzrlib.trace import mutter
 
42
import bzrlib.win32console
35
43
 
36
44
 
37
45
def make_readonly(filename):
97
105
        raise BzrError('invalid file kind %r' % kind)
98
106
 
99
107
def lexists(f):
 
108
    if hasattr(os.path, 'lexists'):
 
109
        return os.path.lexists(f)
100
110
    try:
101
111
        if hasattr(os, 'lstat'):
102
112
            os.lstat(f)
109
119
        else:
110
120
            raise BzrError("lstat/stat of (%r): %r" % (f, e))
111
121
 
112
 
def normalizepath(f):
113
 
    if hasattr(os.path, 'realpath'):
114
 
        F = os.path.realpath
115
 
    else:
116
 
        F = os.path.abspath
117
 
    [p,e] = os.path.split(f)
118
 
    if e == "" or e == "." or e == "..":
119
 
        return F(f)
120
 
    else:
121
 
        return os.path.join(F(p), e)
 
122
def fancy_rename(old, new, rename_func, unlink_func):
 
123
    """A fancy rename, when you don't have atomic rename.
 
124
    
 
125
    :param old: The old path, to rename from
 
126
    :param new: The new path, to rename to
 
127
    :param rename_func: The potentially non-atomic rename function
 
128
    :param unlink_func: A way to delete the target file if the full rename succeeds
 
129
    """
 
130
 
 
131
    # sftp rename doesn't allow overwriting, so play tricks:
 
132
    import random
 
133
    base = os.path.basename(new)
 
134
    dirname = os.path.dirname(new)
 
135
    tmp_name = u'tmp.%s.%.9f.%d.%s' % (base, time.time(), os.getpid(), rand_chars(10))
 
136
    tmp_name = pathjoin(dirname, tmp_name)
 
137
 
 
138
    # Rename the file out of the way, but keep track if it didn't exist
 
139
    # We don't want to grab just any exception
 
140
    # something like EACCES should prevent us from continuing
 
141
    # The downside is that the rename_func has to throw an exception
 
142
    # with an errno = ENOENT, or NoSuchFile
 
143
    file_existed = False
 
144
    try:
 
145
        rename_func(new, tmp_name)
 
146
    except (NoSuchFile,), e:
 
147
        pass
 
148
    except IOError, e:
 
149
        # RBC 20060103 abstraction leakage: the paramiko SFTP clients rename
 
150
        # function raises an IOError with errno == None when a rename fails.
 
151
        # This then gets caught here.
 
152
        if e.errno not in (None, errno.ENOENT, errno.ENOTDIR):
 
153
            raise
 
154
    except Exception, e:
 
155
        if (not hasattr(e, 'errno') 
 
156
            or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
 
157
            raise
 
158
    else:
 
159
        file_existed = True
 
160
 
 
161
    success = False
 
162
    try:
 
163
        # This may throw an exception, in which case success will
 
164
        # not be set.
 
165
        rename_func(old, new)
 
166
        success = True
 
167
    finally:
 
168
        if file_existed:
 
169
            # If the file used to exist, rename it back into place
 
170
            # otherwise just delete it from the tmp location
 
171
            if success:
 
172
                unlink_func(tmp_name)
 
173
            else:
 
174
                rename_func(tmp_name, new)
 
175
 
 
176
# Default is to just use the python builtins, but these can be rebound on
 
177
# particular platforms.
 
178
abspath = os.path.abspath
 
179
realpath = os.path.realpath
 
180
pathjoin = os.path.join
 
181
normpath = os.path.normpath
 
182
getcwd = os.getcwdu
 
183
mkdtemp = tempfile.mkdtemp
 
184
rename = os.rename
 
185
dirname = os.path.dirname
 
186
basename = os.path.basename
 
187
rmtree = shutil.rmtree
 
188
 
 
189
MIN_ABS_PATHLENGTH = 1
122
190
 
123
191
if os.name == "posix":
124
192
    # In Python 2.4.2 and older, os.path.abspath and os.path.realpath
128
196
    _fs_enc = sys.getfilesystemencoding()
129
197
    def abspath(path):
130
198
        return os.path.abspath(path.encode(_fs_enc)).decode(_fs_enc)
 
199
 
131
200
    def realpath(path):
132
201
        return os.path.realpath(path.encode(_fs_enc)).decode(_fs_enc)
133
 
else:
 
202
 
 
203
if sys.platform == 'win32':
134
204
    # We need to use the Unicode-aware os.path.abspath and
135
205
    # os.path.realpath on Windows systems.
136
 
    abspath = os.path.abspath
137
 
    realpath = os.path.realpath
 
206
    def abspath(path):
 
207
        return os.path.abspath(path).replace('\\', '/')
 
208
 
 
209
    def realpath(path):
 
210
        return os.path.realpath(path).replace('\\', '/')
 
211
 
 
212
    def pathjoin(*args):
 
213
        return os.path.join(*args).replace('\\', '/')
 
214
 
 
215
    def normpath(path):
 
216
        return os.path.normpath(path).replace('\\', '/')
 
217
 
 
218
    def getcwd():
 
219
        return os.getcwdu().replace('\\', '/')
 
220
 
 
221
    def mkdtemp(*args, **kwargs):
 
222
        return tempfile.mkdtemp(*args, **kwargs).replace('\\', '/')
 
223
 
 
224
    def rename(old, new):
 
225
        fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
 
226
 
 
227
    MIN_ABS_PATHLENGTH = 3
 
228
 
 
229
    def _win32_delete_readonly(function, path, excinfo):
 
230
        """Error handler for shutil.rmtree function [for win32]
 
231
        Helps to remove files and dirs marked as read-only.
 
232
        """
 
233
        type_, value = excinfo[:2]
 
234
        if function in (os.remove, os.rmdir) \
 
235
            and type_ == OSError \
 
236
            and value.errno == errno.EACCES:
 
237
            bzrlib.osutils.make_writable(path)
 
238
            function(path)
 
239
        else:
 
240
            raise
 
241
 
 
242
    def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
 
243
        """Replacer for shutil.rmtree: could remove readonly dirs/files"""
 
244
        return shutil.rmtree(path, ignore_errors, onerror)
 
245
 
 
246
 
 
247
def normalizepath(f):
 
248
    if hasattr(os.path, 'realpath'):
 
249
        F = realpath
 
250
    else:
 
251
        F = abspath
 
252
    [p,e] = os.path.split(f)
 
253
    if e == "" or e == "." or e == "..":
 
254
        return F(f)
 
255
    else:
 
256
        return pathjoin(F(p), e)
 
257
 
138
258
 
139
259
def backup_file(fn):
140
260
    """Copy a file to a backup.
163
283
    finally:
164
284
        outf.close()
165
285
 
166
 
if os.name == 'nt':
167
 
    import shutil
168
 
    rename = shutil.move
169
 
else:
170
 
    rename = os.rename
171
 
 
172
286
 
173
287
def isdir(f):
174
288
    """True if f is an accessible directory."""
195
309
def is_inside(dir, fname):
196
310
    """True if fname is inside dir.
197
311
    
198
 
    The parameters should typically be passed to os.path.normpath first, so
 
312
    The parameters should typically be passed to osutils.normpath first, so
199
313
    that . and .. and repeated slashes are eliminated, and the separators
200
314
    are canonical for the platform.
201
315
    
202
316
    The empty string as a dir name is taken as top-of-tree and matches 
203
317
    everything.
204
318
    
205
 
    >>> is_inside('src', os.path.join('src', 'foo.c'))
 
319
    >>> is_inside('src', pathjoin('src', 'foo.c'))
206
320
    True
207
321
    >>> is_inside('src', 'srccontrol')
208
322
    False
209
 
    >>> is_inside('src', os.path.join('src', 'a', 'a', 'a', 'foo.c'))
 
323
    >>> is_inside('src', pathjoin('src', 'a', 'a', 'a', 'foo.c'))
210
324
    True
211
325
    >>> is_inside('foo.c', 'foo.c')
212
326
    True
223
337
    if dir == '':
224
338
        return True
225
339
 
226
 
    if dir[-1] != os.sep:
227
 
        dir += os.sep
 
340
    if dir[-1] != '/':
 
341
        dir += '/'
228
342
 
229
343
    return fname.startswith(dir)
230
344
 
240
354
 
241
355
def pumpfile(fromfile, tofile):
242
356
    """Copy contents of one file to another."""
243
 
    tofile.write(fromfile.read())
 
357
    BUFSIZE = 32768
 
358
    while True:
 
359
        b = fromfile.read(BUFSIZE)
 
360
        if not b:
 
361
            break
 
362
        tofile.write(b)
 
363
 
 
364
 
 
365
def file_iterator(input_file, readsize=32768):
 
366
    while True:
 
367
        b = input_file.read(readsize)
 
368
        if len(b) == 0:
 
369
            break
 
370
        yield b
244
371
 
245
372
 
246
373
def sha_file(f):
340
467
    """Return size of given open file."""
341
468
    return os.fstat(f.fileno())[ST_SIZE]
342
469
 
 
470
 
343
471
# Define rand_bytes based on platform.
344
472
try:
345
473
    # Python 2.4 and later have os.urandom,
362
490
                n -= 1
363
491
            return s
364
492
 
 
493
 
 
494
ALNUM = '0123456789abcdefghijklmnopqrstuvwxyz'
 
495
def rand_chars(num):
 
496
    """Return a random string of num alphanumeric characters
 
497
    
 
498
    The result only contains lowercase chars because it may be used on 
 
499
    case-insensitive filesystems.
 
500
    """
 
501
    s = ''
 
502
    for raw_byte in rand_bytes(num):
 
503
        s += ALNUM[ord(raw_byte) % 36]
 
504
    return s
 
505
 
 
506
 
365
507
## TODO: We could later have path objects that remember their list
366
508
## decomposition (might be too tricksy though.)
367
509
 
402
544
    for f in p:
403
545
        if (f == '..') or (f == None) or (f == ''):
404
546
            raise BzrError("sorry, %r not allowed in path" % f)
405
 
    return os.path.join(*p)
 
547
    return pathjoin(*p)
406
548
 
407
549
 
408
550
def appendpath(p1, p2):
409
551
    if p1 == '':
410
552
        return p2
411
553
    else:
412
 
        return os.path.join(p1, p2)
 
554
        return pathjoin(p1, p2)
413
555
    
414
556
 
415
557
def split_lines(s):
416
558
    """Split s into lines, but without removing the newline characters."""
417
 
    return StringIO(s).readlines()
 
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
418
564
 
419
565
 
420
566
def hardlinks_good():
433
579
            raise
434
580
        copyfile(src, dest)
435
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
 
436
592
 
437
593
def has_symlinks():
438
594
    if hasattr(os, 'symlink'):
467
623
 
468
624
    os.path.commonprefix (python2.4) has a bad bug that it works just
469
625
    on string prefixes, assuming that '/u' is a prefix of '/u2'.  This
470
 
    avoids that problem."""
 
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)
471
632
    rp = abspath(path)
472
633
 
473
634
    s = []
481
642
    else:
482
643
        # XXX This should raise a NotChildPath exception, as its not tied
483
644
        # to branch anymore.
484
 
        raise NotBranchError("path %r is not within branch %r" % (rp, base))
485
 
 
486
 
    return os.sep.join(s)
 
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)