/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: abentley
  • Date: 2006-04-21 05:52:44 UTC
  • mto: This revision was merged to the branch mainline in revision 1683.
  • Revision ID: abentley@lappy-20060421055244-2ba416dcc7539d96
Fix fileid involed tests on win32 (by skipping them for unescaped weave formats)

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Bazaar-NG -- distributed version control
 
2
#
 
3
# Copyright (C) 2005 by Canonical Ltd
 
4
#
 
5
# This program is free software; you can redistribute it and/or modify
 
6
# it under the terms of the GNU General Public License as published by
 
7
# the Free Software Foundation; either version 2 of the License, or
 
8
# (at your option) any later version.
 
9
#
 
10
# This program is distributed in the hope that it will be useful,
 
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
13
# GNU General Public License for more details.
 
14
#
 
15
# You should have received a copy of the GNU General Public License
 
16
# along with this program; if not, write to the Free Software
 
17
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
18
 
 
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 string
 
28
import sys
 
29
import time
 
30
import types
 
31
import tempfile
 
32
 
 
33
import bzrlib
 
34
from bzrlib.errors import (BzrError,
 
35
                           BzrBadParameterNotUnicode,
 
36
                           NoSuchFile,
 
37
                           PathNotChild,
 
38
                           )
 
39
from bzrlib.trace import mutter
 
40
 
 
41
 
 
42
def make_readonly(filename):
 
43
    """Make a filename read-only."""
 
44
    mod = os.stat(filename).st_mode
 
45
    mod = mod & 0777555
 
46
    os.chmod(filename, mod)
 
47
 
 
48
 
 
49
def make_writable(filename):
 
50
    mod = os.stat(filename).st_mode
 
51
    mod = mod | 0200
 
52
    os.chmod(filename, mod)
 
53
 
 
54
 
 
55
_QUOTE_RE = None
 
56
 
 
57
 
 
58
def quotefn(f):
 
59
    """Return a quoted filename filename
 
60
 
 
61
    This previously used backslash quoting, but that works poorly on
 
62
    Windows."""
 
63
    # TODO: I'm not really sure this is the best format either.x
 
64
    global _QUOTE_RE
 
65
    if _QUOTE_RE == None:
 
66
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
 
67
        
 
68
    if _QUOTE_RE.search(f):
 
69
        return '"' + f + '"'
 
70
    else:
 
71
        return f
 
72
 
 
73
 
 
74
def file_kind(f):
 
75
    mode = os.lstat(f)[ST_MODE]
 
76
    if S_ISREG(mode):
 
77
        return 'file'
 
78
    elif S_ISDIR(mode):
 
79
        return 'directory'
 
80
    elif S_ISLNK(mode):
 
81
        return 'symlink'
 
82
    elif S_ISCHR(mode):
 
83
        return 'chardev'
 
84
    elif S_ISBLK(mode):
 
85
        return 'block'
 
86
    elif S_ISFIFO(mode):
 
87
        return 'fifo'
 
88
    elif S_ISSOCK(mode):
 
89
        return 'socket'
 
90
    else:
 
91
        return 'unknown'
 
92
 
 
93
 
 
94
def kind_marker(kind):
 
95
    if kind == 'file':
 
96
        return ''
 
97
    elif kind == 'directory':
 
98
        return '/'
 
99
    elif kind == 'symlink':
 
100
        return '@'
 
101
    else:
 
102
        raise BzrError('invalid file kind %r' % kind)
 
103
 
 
104
def lexists(f):
 
105
    if hasattr(os.path, 'lexists'):
 
106
        return os.path.lexists(f)
 
107
    try:
 
108
        if hasattr(os, 'lstat'):
 
109
            os.lstat(f)
 
110
        else:
 
111
            os.stat(f)
 
112
        return True
 
113
    except OSError,e:
 
114
        if e.errno == errno.ENOENT:
 
115
            return False;
 
116
        else:
 
117
            raise BzrError("lstat/stat of (%r): %r" % (f, e))
 
118
 
 
119
def fancy_rename(old, new, rename_func, unlink_func):
 
120
    """A fancy rename, when you don't have atomic rename.
 
121
    
 
122
    :param old: The old path, to rename from
 
123
    :param new: The new path, to rename to
 
124
    :param rename_func: The potentially non-atomic rename function
 
125
    :param unlink_func: A way to delete the target file if the full rename succeeds
 
126
    """
 
127
 
 
128
    # sftp rename doesn't allow overwriting, so play tricks:
 
129
    import random
 
130
    base = os.path.basename(new)
 
131
    dirname = os.path.dirname(new)
 
132
    tmp_name = u'tmp.%s.%.9f.%d.%s' % (base, time.time(), os.getpid(), rand_chars(10))
 
133
    tmp_name = pathjoin(dirname, tmp_name)
 
134
 
 
135
    # Rename the file out of the way, but keep track if it didn't exist
 
136
    # We don't want to grab just any exception
 
137
    # something like EACCES should prevent us from continuing
 
138
    # The downside is that the rename_func has to throw an exception
 
139
    # with an errno = ENOENT, or NoSuchFile
 
140
    file_existed = False
 
141
    try:
 
142
        rename_func(new, tmp_name)
 
143
    except (NoSuchFile,), e:
 
144
        pass
 
145
    except IOError, e:
 
146
        # RBC 20060103 abstraction leakage: the paramiko SFTP clients rename
 
147
        # function raises an IOError with errno == None when a rename fails.
 
148
        # This then gets caught here.
 
149
        if e.errno not in (None, errno.ENOENT, errno.ENOTDIR):
 
150
            raise
 
151
    except Exception, e:
 
152
        if (not hasattr(e, 'errno') 
 
153
            or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
 
154
            raise
 
155
    else:
 
156
        file_existed = True
 
157
 
 
158
    success = False
 
159
    try:
 
160
        # This may throw an exception, in which case success will
 
161
        # not be set.
 
162
        rename_func(old, new)
 
163
        success = True
 
164
    finally:
 
165
        if file_existed:
 
166
            # If the file used to exist, rename it back into place
 
167
            # otherwise just delete it from the tmp location
 
168
            if success:
 
169
                unlink_func(tmp_name)
 
170
            else:
 
171
                rename_func(tmp_name, new)
 
172
 
 
173
# Default is to just use the python builtins
 
174
abspath = os.path.abspath
 
175
realpath = os.path.realpath
 
176
pathjoin = os.path.join
 
177
normpath = os.path.normpath
 
178
getcwd = os.getcwdu
 
179
mkdtemp = tempfile.mkdtemp
 
180
rename = os.rename
 
181
dirname = os.path.dirname
 
182
basename = os.path.basename
 
183
 
 
184
MIN_ABS_PATHLENGTH = 1
 
185
 
 
186
if os.name == "posix":
 
187
    # In Python 2.4.2 and older, os.path.abspath and os.path.realpath
 
188
    # choke on a Unicode string containing a relative path if
 
189
    # os.getcwd() returns a non-sys.getdefaultencoding()-encoded
 
190
    # string.
 
191
    _fs_enc = sys.getfilesystemencoding()
 
192
    def abspath(path):
 
193
        return os.path.abspath(path.encode(_fs_enc)).decode(_fs_enc)
 
194
 
 
195
    def realpath(path):
 
196
        return os.path.realpath(path.encode(_fs_enc)).decode(_fs_enc)
 
197
 
 
198
if sys.platform == 'win32':
 
199
    # We need to use the Unicode-aware os.path.abspath and
 
200
    # os.path.realpath on Windows systems.
 
201
    def abspath(path):
 
202
        return os.path.abspath(path).replace('\\', '/')
 
203
 
 
204
    def realpath(path):
 
205
        return os.path.realpath(path).replace('\\', '/')
 
206
 
 
207
    def pathjoin(*args):
 
208
        return os.path.join(*args).replace('\\', '/')
 
209
 
 
210
    def normpath(path):
 
211
        return os.path.normpath(path).replace('\\', '/')
 
212
 
 
213
    def getcwd():
 
214
        return os.getcwdu().replace('\\', '/')
 
215
 
 
216
    def mkdtemp(*args, **kwargs):
 
217
        return tempfile.mkdtemp(*args, **kwargs).replace('\\', '/')
 
218
 
 
219
    def rename(old, new):
 
220
        fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
 
221
 
 
222
    MIN_ABS_PATHLENGTH = 3
 
223
 
 
224
def normalizepath(f):
 
225
    if hasattr(os.path, 'realpath'):
 
226
        F = realpath
 
227
    else:
 
228
        F = abspath
 
229
    [p,e] = os.path.split(f)
 
230
    if e == "" or e == "." or e == "..":
 
231
        return F(f)
 
232
    else:
 
233
        return pathjoin(F(p), e)
 
234
 
 
235
 
 
236
def backup_file(fn):
 
237
    """Copy a file to a backup.
 
238
 
 
239
    Backups are named in GNU-style, with a ~ suffix.
 
240
 
 
241
    If the file is already a backup, it's not copied.
 
242
    """
 
243
    if fn[-1] == '~':
 
244
        return
 
245
    bfn = fn + '~'
 
246
 
 
247
    if has_symlinks() and os.path.islink(fn):
 
248
        target = os.readlink(fn)
 
249
        os.symlink(target, bfn)
 
250
        return
 
251
    inf = file(fn, 'rb')
 
252
    try:
 
253
        content = inf.read()
 
254
    finally:
 
255
        inf.close()
 
256
    
 
257
    outf = file(bfn, 'wb')
 
258
    try:
 
259
        outf.write(content)
 
260
    finally:
 
261
        outf.close()
 
262
 
 
263
 
 
264
def isdir(f):
 
265
    """True if f is an accessible directory."""
 
266
    try:
 
267
        return S_ISDIR(os.lstat(f)[ST_MODE])
 
268
    except OSError:
 
269
        return False
 
270
 
 
271
 
 
272
def isfile(f):
 
273
    """True if f is a regular file."""
 
274
    try:
 
275
        return S_ISREG(os.lstat(f)[ST_MODE])
 
276
    except OSError:
 
277
        return False
 
278
 
 
279
def islink(f):
 
280
    """True if f is a symlink."""
 
281
    try:
 
282
        return S_ISLNK(os.lstat(f)[ST_MODE])
 
283
    except OSError:
 
284
        return False
 
285
 
 
286
def is_inside(dir, fname):
 
287
    """True if fname is inside dir.
 
288
    
 
289
    The parameters should typically be passed to osutils.normpath first, so
 
290
    that . and .. and repeated slashes are eliminated, and the separators
 
291
    are canonical for the platform.
 
292
    
 
293
    The empty string as a dir name is taken as top-of-tree and matches 
 
294
    everything.
 
295
    
 
296
    >>> is_inside('src', pathjoin('src', 'foo.c'))
 
297
    True
 
298
    >>> is_inside('src', 'srccontrol')
 
299
    False
 
300
    >>> is_inside('src', pathjoin('src', 'a', 'a', 'a', 'foo.c'))
 
301
    True
 
302
    >>> is_inside('foo.c', 'foo.c')
 
303
    True
 
304
    >>> is_inside('foo.c', '')
 
305
    False
 
306
    >>> is_inside('', 'foo.c')
 
307
    True
 
308
    """
 
309
    # XXX: Most callers of this can actually do something smarter by 
 
310
    # looking at the inventory
 
311
    if dir == fname:
 
312
        return True
 
313
    
 
314
    if dir == '':
 
315
        return True
 
316
 
 
317
    if dir[-1] != '/':
 
318
        dir += '/'
 
319
 
 
320
    return fname.startswith(dir)
 
321
 
 
322
 
 
323
def is_inside_any(dir_list, fname):
 
324
    """True if fname is inside any of given dirs."""
 
325
    for dirname in dir_list:
 
326
        if is_inside(dirname, fname):
 
327
            return True
 
328
    else:
 
329
        return False
 
330
 
 
331
 
 
332
def pumpfile(fromfile, tofile):
 
333
    """Copy contents of one file to another."""
 
334
    BUFSIZE = 32768
 
335
    while True:
 
336
        b = fromfile.read(BUFSIZE)
 
337
        if not b:
 
338
            break
 
339
        tofile.write(b)
 
340
 
 
341
 
 
342
def file_iterator(input_file, readsize=32768):
 
343
    while True:
 
344
        b = input_file.read(readsize)
 
345
        if len(b) == 0:
 
346
            break
 
347
        yield b
 
348
 
 
349
 
 
350
def sha_file(f):
 
351
    if hasattr(f, 'tell'):
 
352
        assert f.tell() == 0
 
353
    s = sha.new()
 
354
    BUFSIZE = 128<<10
 
355
    while True:
 
356
        b = f.read(BUFSIZE)
 
357
        if not b:
 
358
            break
 
359
        s.update(b)
 
360
    return s.hexdigest()
 
361
 
 
362
 
 
363
 
 
364
def sha_strings(strings):
 
365
    """Return the sha-1 of concatenation of strings"""
 
366
    s = sha.new()
 
367
    map(s.update, strings)
 
368
    return s.hexdigest()
 
369
 
 
370
 
 
371
def sha_string(f):
 
372
    s = sha.new()
 
373
    s.update(f)
 
374
    return s.hexdigest()
 
375
 
 
376
 
 
377
def fingerprint_file(f):
 
378
    s = sha.new()
 
379
    b = f.read()
 
380
    s.update(b)
 
381
    size = len(b)
 
382
    return {'size': size,
 
383
            'sha1': s.hexdigest()}
 
384
 
 
385
 
 
386
def compare_files(a, b):
 
387
    """Returns true if equal in contents"""
 
388
    BUFSIZE = 4096
 
389
    while True:
 
390
        ai = a.read(BUFSIZE)
 
391
        bi = b.read(BUFSIZE)
 
392
        if ai != bi:
 
393
            return False
 
394
        if ai == '':
 
395
            return True
 
396
 
 
397
 
 
398
def local_time_offset(t=None):
 
399
    """Return offset of local zone from GMT, either at present or at time t."""
 
400
    # python2.3 localtime() can't take None
 
401
    if t == None:
 
402
        t = time.time()
 
403
        
 
404
    if time.localtime(t).tm_isdst and time.daylight:
 
405
        return -time.altzone
 
406
    else:
 
407
        return -time.timezone
 
408
 
 
409
    
 
410
def format_date(t, offset=0, timezone='original', date_fmt=None, 
 
411
                show_offset=True):
 
412
    ## TODO: Perhaps a global option to use either universal or local time?
 
413
    ## Or perhaps just let people set $TZ?
 
414
    assert isinstance(t, float)
 
415
    
 
416
    if timezone == 'utc':
 
417
        tt = time.gmtime(t)
 
418
        offset = 0
 
419
    elif timezone == 'original':
 
420
        if offset == None:
 
421
            offset = 0
 
422
        tt = time.gmtime(t + offset)
 
423
    elif timezone == 'local':
 
424
        tt = time.localtime(t)
 
425
        offset = local_time_offset(t)
 
426
    else:
 
427
        raise BzrError("unsupported timezone format %r" % timezone,
 
428
                       ['options are "utc", "original", "local"'])
 
429
    if date_fmt is None:
 
430
        date_fmt = "%a %Y-%m-%d %H:%M:%S"
 
431
    if show_offset:
 
432
        offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
 
433
    else:
 
434
        offset_str = ''
 
435
    return (time.strftime(date_fmt, tt) +  offset_str)
 
436
 
 
437
 
 
438
def compact_date(when):
 
439
    return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
 
440
    
 
441
 
 
442
 
 
443
def filesize(f):
 
444
    """Return size of given open file."""
 
445
    return os.fstat(f.fileno())[ST_SIZE]
 
446
 
 
447
 
 
448
# Define rand_bytes based on platform.
 
449
try:
 
450
    # Python 2.4 and later have os.urandom,
 
451
    # but it doesn't work on some arches
 
452
    os.urandom(1)
 
453
    rand_bytes = os.urandom
 
454
except (NotImplementedError, AttributeError):
 
455
    # If python doesn't have os.urandom, or it doesn't work,
 
456
    # then try to first pull random data from /dev/urandom
 
457
    if os.path.exists("/dev/urandom"):
 
458
        rand_bytes = file('/dev/urandom', 'rb').read
 
459
    # Otherwise, use this hack as a last resort
 
460
    else:
 
461
        # not well seeded, but better than nothing
 
462
        def rand_bytes(n):
 
463
            import random
 
464
            s = ''
 
465
            while n:
 
466
                s += chr(random.randint(0, 255))
 
467
                n -= 1
 
468
            return s
 
469
 
 
470
 
 
471
ALNUM = '0123456789abcdefghijklmnopqrstuvwxyz'
 
472
def rand_chars(num):
 
473
    """Return a random string of num alphanumeric characters
 
474
    
 
475
    The result only contains lowercase chars because it may be used on 
 
476
    case-insensitive filesystems.
 
477
    """
 
478
    s = ''
 
479
    for raw_byte in rand_bytes(num):
 
480
        s += ALNUM[ord(raw_byte) % 36]
 
481
    return s
 
482
 
 
483
 
 
484
## TODO: We could later have path objects that remember their list
 
485
## decomposition (might be too tricksy though.)
 
486
 
 
487
def splitpath(p):
 
488
    """Turn string into list of parts.
 
489
 
 
490
    >>> splitpath('a')
 
491
    ['a']
 
492
    >>> splitpath('a/b')
 
493
    ['a', 'b']
 
494
    >>> splitpath('a/./b')
 
495
    ['a', 'b']
 
496
    >>> splitpath('a/.b')
 
497
    ['a', '.b']
 
498
    >>> splitpath('a/../b')
 
499
    Traceback (most recent call last):
 
500
    ...
 
501
    BzrError: sorry, '..' not allowed in path
 
502
    """
 
503
    assert isinstance(p, types.StringTypes)
 
504
 
 
505
    # split on either delimiter because people might use either on
 
506
    # Windows
 
507
    ps = re.split(r'[\\/]', p)
 
508
 
 
509
    rps = []
 
510
    for f in ps:
 
511
        if f == '..':
 
512
            raise BzrError("sorry, %r not allowed in path" % f)
 
513
        elif (f == '.') or (f == ''):
 
514
            pass
 
515
        else:
 
516
            rps.append(f)
 
517
    return rps
 
518
 
 
519
def joinpath(p):
 
520
    assert isinstance(p, list)
 
521
    for f in p:
 
522
        if (f == '..') or (f == None) or (f == ''):
 
523
            raise BzrError("sorry, %r not allowed in path" % f)
 
524
    return pathjoin(*p)
 
525
 
 
526
 
 
527
def appendpath(p1, p2):
 
528
    if p1 == '':
 
529
        return p2
 
530
    else:
 
531
        return pathjoin(p1, p2)
 
532
    
 
533
 
 
534
def split_lines(s):
 
535
    """Split s into lines, but without removing the newline characters."""
 
536
    lines = s.split('\n')
 
537
    result = [line + '\n' for line in lines[:-1]]
 
538
    if lines[-1]:
 
539
        result.append(lines[-1])
 
540
    return result
 
541
 
 
542
 
 
543
def hardlinks_good():
 
544
    return sys.platform not in ('win32', 'cygwin', 'darwin')
 
545
 
 
546
 
 
547
def link_or_copy(src, dest):
 
548
    """Hardlink a file, or copy it if it can't be hardlinked."""
 
549
    if not hardlinks_good():
 
550
        copyfile(src, dest)
 
551
        return
 
552
    try:
 
553
        os.link(src, dest)
 
554
    except (OSError, IOError), e:
 
555
        if e.errno != errno.EXDEV:
 
556
            raise
 
557
        copyfile(src, dest)
 
558
 
 
559
def delete_any(full_path):
 
560
    """Delete a file or directory."""
 
561
    try:
 
562
        os.unlink(full_path)
 
563
    except OSError, e:
 
564
    # We may be renaming a dangling inventory id
 
565
        if e.errno not in (errno.EISDIR, errno.EACCES, errno.EPERM):
 
566
            raise
 
567
        os.rmdir(full_path)
 
568
 
 
569
 
 
570
def has_symlinks():
 
571
    if hasattr(os, 'symlink'):
 
572
        return True
 
573
    else:
 
574
        return False
 
575
        
 
576
 
 
577
def contains_whitespace(s):
 
578
    """True if there are any whitespace characters in s."""
 
579
    for ch in string.whitespace:
 
580
        if ch in s:
 
581
            return True
 
582
    else:
 
583
        return False
 
584
 
 
585
 
 
586
def contains_linebreaks(s):
 
587
    """True if there is any vertical whitespace in s."""
 
588
    for ch in '\f\n\r':
 
589
        if ch in s:
 
590
            return True
 
591
    else:
 
592
        return False
 
593
 
 
594
 
 
595
def relpath(base, path):
 
596
    """Return path relative to base, or raise exception.
 
597
 
 
598
    The path may be either an absolute path or a path relative to the
 
599
    current working directory.
 
600
 
 
601
    os.path.commonprefix (python2.4) has a bad bug that it works just
 
602
    on string prefixes, assuming that '/u' is a prefix of '/u2'.  This
 
603
    avoids that problem.
 
604
    """
 
605
 
 
606
    assert len(base) >= MIN_ABS_PATHLENGTH, ('Length of base must be equal or'
 
607
        ' exceed the platform minimum length (which is %d)' % 
 
608
        MIN_ABS_PATHLENGTH)
 
609
    rp = abspath(path)
 
610
 
 
611
    s = []
 
612
    head = rp
 
613
    while len(head) >= len(base):
 
614
        if head == base:
 
615
            break
 
616
        head, tail = os.path.split(head)
 
617
        if tail:
 
618
            s.insert(0, tail)
 
619
    else:
 
620
        # XXX This should raise a NotChildPath exception, as its not tied
 
621
        # to branch anymore.
 
622
        raise PathNotChild(rp, base)
 
623
 
 
624
    if s:
 
625
        return pathjoin(*s)
 
626
    else:
 
627
        return ''
 
628
 
 
629
 
 
630
def safe_unicode(unicode_or_utf8_string):
 
631
    """Coerce unicode_or_utf8_string into unicode.
 
632
 
 
633
    If it is unicode, it is returned.
 
634
    Otherwise it is decoded from utf-8. If a decoding error
 
635
    occurs, it is wrapped as a If the decoding fails, the exception is wrapped 
 
636
    as a BzrBadParameter exception.
 
637
    """
 
638
    if isinstance(unicode_or_utf8_string, unicode):
 
639
        return unicode_or_utf8_string
 
640
    try:
 
641
        return unicode_or_utf8_string.decode('utf8')
 
642
    except UnicodeDecodeError:
 
643
        raise BzrBadParameterNotUnicode(unicode_or_utf8_string)
 
644
 
 
645
 
 
646
def terminal_width():
 
647
    """Return estimated terminal width."""
 
648
 
 
649
    # TODO: Do something smart on Windows?
 
650
 
 
651
    # TODO: Is there anything that gets a better update when the window
 
652
    # is resized while the program is running? We could use the Python termcap
 
653
    # library.
 
654
    try:
 
655
        return int(os.environ['COLUMNS'])
 
656
    except (IndexError, KeyError, ValueError):
 
657
        return 80
 
658
 
 
659
def supports_executable():
 
660
    return sys.platform != "win32"
 
661
 
 
662
 
 
663
def strip_trailing_slash(path):
 
664
    """Strip trailing slash, except for root paths.
 
665
    The definition of 'root path' is platform-dependent.
 
666
    """
 
667
    if len(path) != MIN_ABS_PATHLENGTH and path[-1] == '/':
 
668
        return path[:-1]
 
669
    else:
 
670
        return path