/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: John Arbash Meinel
  • Date: 2005-12-01 18:16:47 UTC
  • mto: (1185.50.19 bzr-jam-integration)
  • mto: This revision was merged to the branch mainline in revision 1532.
  • Revision ID: john@arbash-meinel.com-20051201181647-2d65af900f14ba6a
Switched os.path.abspath and os.path.realpath to osutils.* (still passes on cygwin)

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
 
 
32
import bzrlib
 
33
from bzrlib.errors import BzrError, NotBranchError
 
34
from bzrlib.trace import mutter
 
35
 
 
36
 
 
37
def make_readonly(filename):
 
38
    """Make a filename read-only."""
 
39
    mod = os.stat(filename).st_mode
 
40
    mod = mod & 0777555
 
41
    os.chmod(filename, mod)
 
42
 
 
43
 
 
44
def make_writable(filename):
 
45
    mod = os.stat(filename).st_mode
 
46
    mod = mod | 0200
 
47
    os.chmod(filename, mod)
 
48
 
 
49
 
 
50
_QUOTE_RE = None
 
51
 
 
52
 
 
53
def quotefn(f):
 
54
    """Return a quoted filename filename
 
55
 
 
56
    This previously used backslash quoting, but that works poorly on
 
57
    Windows."""
 
58
    # TODO: I'm not really sure this is the best format either.x
 
59
    global _QUOTE_RE
 
60
    if _QUOTE_RE == None:
 
61
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
 
62
        
 
63
    if _QUOTE_RE.search(f):
 
64
        return '"' + f + '"'
 
65
    else:
 
66
        return f
 
67
 
 
68
 
 
69
def file_kind(f):
 
70
    mode = os.lstat(f)[ST_MODE]
 
71
    if S_ISREG(mode):
 
72
        return 'file'
 
73
    elif S_ISDIR(mode):
 
74
        return 'directory'
 
75
    elif S_ISLNK(mode):
 
76
        return 'symlink'
 
77
    elif S_ISCHR(mode):
 
78
        return 'chardev'
 
79
    elif S_ISBLK(mode):
 
80
        return 'block'
 
81
    elif S_ISFIFO(mode):
 
82
        return 'fifo'
 
83
    elif S_ISSOCK(mode):
 
84
        return 'socket'
 
85
    else:
 
86
        return 'unknown'
 
87
 
 
88
 
 
89
def kind_marker(kind):
 
90
    if kind == 'file':
 
91
        return ''
 
92
    elif kind == 'directory':
 
93
        return '/'
 
94
    elif kind == 'symlink':
 
95
        return '@'
 
96
    else:
 
97
        raise BzrError('invalid file kind %r' % kind)
 
98
 
 
99
def lexists(f):
 
100
    if hasattr(os.path, 'lexists'):
 
101
        return os.path.lexists(f)
 
102
    try:
 
103
        if hasattr(os, 'lstat'):
 
104
            os.lstat(f)
 
105
        else:
 
106
            os.stat(f)
 
107
        return True
 
108
    except OSError,e:
 
109
        if e.errno == errno.ENOENT:
 
110
            return False;
 
111
        else:
 
112
            raise BzrError("lstat/stat of (%r): %r" % (f, e))
 
113
 
 
114
if os.name == "posix":
 
115
    # In Python 2.4.2 and older, os.path.abspath and os.path.realpath
 
116
    # choke on a Unicode string containing a relative path if
 
117
    # os.getcwd() returns a non-sys.getdefaultencoding()-encoded
 
118
    # string.
 
119
    _fs_enc = sys.getfilesystemencoding()
 
120
    def abspath(path):
 
121
        return os.path.abspath(path.encode(_fs_enc)).decode(_fs_enc)
 
122
    def realpath(path):
 
123
        return os.path.realpath(path.encode(_fs_enc)).decode(_fs_enc)
 
124
    pathjoin = os.path.join
 
125
else:
 
126
    # We need to use the Unicode-aware os.path.abspath and
 
127
    # os.path.realpath on Windows systems.
 
128
    def abspath(path):
 
129
        return os.path.abspath(path).replace('\\', '/')
 
130
    def realpath(path):
 
131
        return os.path.realpath(path).replace('\\', '/')
 
132
    def pathjoin(*args):
 
133
        return os.path.join(*args).replace('\\', '/')
 
134
# Because these shrink the path, we can use the original
 
135
# versions on any platform
 
136
dirname = os.path.dirname
 
137
basename = os.path.basename
 
138
 
 
139
def normalizepath(f):
 
140
    if hasattr(os.path, 'realpath'):
 
141
        F = realpath
 
142
    else:
 
143
        F = abspath
 
144
    [p,e] = os.path.split(f)
 
145
    if e == "" or e == "." or e == "..":
 
146
        return F(f)
 
147
    else:
 
148
        return pathjoin(F(p), e)
 
149
 
 
150
 
 
151
def backup_file(fn):
 
152
    """Copy a file to a backup.
 
153
 
 
154
    Backups are named in GNU-style, with a ~ suffix.
 
155
 
 
156
    If the file is already a backup, it's not copied.
 
157
    """
 
158
    if fn[-1] == '~':
 
159
        return
 
160
    bfn = fn + '~'
 
161
 
 
162
    if has_symlinks() and os.path.islink(fn):
 
163
        target = os.readlink(fn)
 
164
        os.symlink(target, bfn)
 
165
        return
 
166
    inf = file(fn, 'rb')
 
167
    try:
 
168
        content = inf.read()
 
169
    finally:
 
170
        inf.close()
 
171
    
 
172
    outf = file(bfn, 'wb')
 
173
    try:
 
174
        outf.write(content)
 
175
    finally:
 
176
        outf.close()
 
177
 
 
178
if os.name == 'nt':
 
179
    import shutil
 
180
    rename = shutil.move
 
181
else:
 
182
    rename = os.rename
 
183
 
 
184
 
 
185
def isdir(f):
 
186
    """True if f is an accessible directory."""
 
187
    try:
 
188
        return S_ISDIR(os.lstat(f)[ST_MODE])
 
189
    except OSError:
 
190
        return False
 
191
 
 
192
 
 
193
def isfile(f):
 
194
    """True if f is a regular file."""
 
195
    try:
 
196
        return S_ISREG(os.lstat(f)[ST_MODE])
 
197
    except OSError:
 
198
        return False
 
199
 
 
200
def islink(f):
 
201
    """True if f is a symlink."""
 
202
    try:
 
203
        return S_ISLNK(os.lstat(f)[ST_MODE])
 
204
    except OSError:
 
205
        return False
 
206
 
 
207
def is_inside(dir, fname):
 
208
    """True if fname is inside dir.
 
209
    
 
210
    The parameters should typically be passed to os.path.normpath first, so
 
211
    that . and .. and repeated slashes are eliminated, and the separators
 
212
    are canonical for the platform.
 
213
    
 
214
    The empty string as a dir name is taken as top-of-tree and matches 
 
215
    everything.
 
216
    
 
217
    >>> is_inside('src', pathjoin('src', 'foo.c'))
 
218
    True
 
219
    >>> is_inside('src', 'srccontrol')
 
220
    False
 
221
    >>> is_inside('src', pathjoin('src', 'a', 'a', 'a', 'foo.c'))
 
222
    True
 
223
    >>> is_inside('foo.c', 'foo.c')
 
224
    True
 
225
    >>> is_inside('foo.c', '')
 
226
    False
 
227
    >>> is_inside('', 'foo.c')
 
228
    True
 
229
    """
 
230
    # XXX: Most callers of this can actually do something smarter by 
 
231
    # looking at the inventory
 
232
    if dir == fname:
 
233
        return True
 
234
    
 
235
    if dir == '':
 
236
        return True
 
237
 
 
238
    if dir[-1] != '/':
 
239
        dir += '/'
 
240
 
 
241
    return fname.startswith(dir)
 
242
 
 
243
 
 
244
def is_inside_any(dir_list, fname):
 
245
    """True if fname is inside any of given dirs."""
 
246
    for dirname in dir_list:
 
247
        if is_inside(dirname, fname):
 
248
            return True
 
249
    else:
 
250
        return False
 
251
 
 
252
 
 
253
def pumpfile(fromfile, tofile):
 
254
    """Copy contents of one file to another."""
 
255
    BUFSIZE = 32768
 
256
    while True:
 
257
        b = fromfile.read(BUFSIZE)
 
258
        if not b:
 
259
            break
 
260
        tofile.write(b)
 
261
 
 
262
 
 
263
def sha_file(f):
 
264
    if hasattr(f, 'tell'):
 
265
        assert f.tell() == 0
 
266
    s = sha.new()
 
267
    BUFSIZE = 128<<10
 
268
    while True:
 
269
        b = f.read(BUFSIZE)
 
270
        if not b:
 
271
            break
 
272
        s.update(b)
 
273
    return s.hexdigest()
 
274
 
 
275
 
 
276
 
 
277
def sha_strings(strings):
 
278
    """Return the sha-1 of concatenation of strings"""
 
279
    s = sha.new()
 
280
    map(s.update, strings)
 
281
    return s.hexdigest()
 
282
 
 
283
 
 
284
def sha_string(f):
 
285
    s = sha.new()
 
286
    s.update(f)
 
287
    return s.hexdigest()
 
288
 
 
289
 
 
290
def fingerprint_file(f):
 
291
    s = sha.new()
 
292
    b = f.read()
 
293
    s.update(b)
 
294
    size = len(b)
 
295
    return {'size': size,
 
296
            'sha1': s.hexdigest()}
 
297
 
 
298
 
 
299
def compare_files(a, b):
 
300
    """Returns true if equal in contents"""
 
301
    BUFSIZE = 4096
 
302
    while True:
 
303
        ai = a.read(BUFSIZE)
 
304
        bi = b.read(BUFSIZE)
 
305
        if ai != bi:
 
306
            return False
 
307
        if ai == '':
 
308
            return True
 
309
 
 
310
 
 
311
def local_time_offset(t=None):
 
312
    """Return offset of local zone from GMT, either at present or at time t."""
 
313
    # python2.3 localtime() can't take None
 
314
    if t == None:
 
315
        t = time.time()
 
316
        
 
317
    if time.localtime(t).tm_isdst and time.daylight:
 
318
        return -time.altzone
 
319
    else:
 
320
        return -time.timezone
 
321
 
 
322
    
 
323
def format_date(t, offset=0, timezone='original', date_fmt=None, 
 
324
                show_offset=True):
 
325
    ## TODO: Perhaps a global option to use either universal or local time?
 
326
    ## Or perhaps just let people set $TZ?
 
327
    assert isinstance(t, float)
 
328
    
 
329
    if timezone == 'utc':
 
330
        tt = time.gmtime(t)
 
331
        offset = 0
 
332
    elif timezone == 'original':
 
333
        if offset == None:
 
334
            offset = 0
 
335
        tt = time.gmtime(t + offset)
 
336
    elif timezone == 'local':
 
337
        tt = time.localtime(t)
 
338
        offset = local_time_offset(t)
 
339
    else:
 
340
        raise BzrError("unsupported timezone format %r" % timezone,
 
341
                       ['options are "utc", "original", "local"'])
 
342
    if date_fmt is None:
 
343
        date_fmt = "%a %Y-%m-%d %H:%M:%S"
 
344
    if show_offset:
 
345
        offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
 
346
    else:
 
347
        offset_str = ''
 
348
    return (time.strftime(date_fmt, tt) +  offset_str)
 
349
 
 
350
 
 
351
def compact_date(when):
 
352
    return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
 
353
    
 
354
 
 
355
 
 
356
def filesize(f):
 
357
    """Return size of given open file."""
 
358
    return os.fstat(f.fileno())[ST_SIZE]
 
359
 
 
360
# Define rand_bytes based on platform.
 
361
try:
 
362
    # Python 2.4 and later have os.urandom,
 
363
    # but it doesn't work on some arches
 
364
    os.urandom(1)
 
365
    rand_bytes = os.urandom
 
366
except (NotImplementedError, AttributeError):
 
367
    # If python doesn't have os.urandom, or it doesn't work,
 
368
    # then try to first pull random data from /dev/urandom
 
369
    if os.path.exists("/dev/urandom"):
 
370
        rand_bytes = file('/dev/urandom', 'rb').read
 
371
    # Otherwise, use this hack as a last resort
 
372
    else:
 
373
        # not well seeded, but better than nothing
 
374
        def rand_bytes(n):
 
375
            import random
 
376
            s = ''
 
377
            while n:
 
378
                s += chr(random.randint(0, 255))
 
379
                n -= 1
 
380
            return s
 
381
 
 
382
## TODO: We could later have path objects that remember their list
 
383
## decomposition (might be too tricksy though.)
 
384
 
 
385
def splitpath(p):
 
386
    """Turn string into list of parts.
 
387
 
 
388
    >>> splitpath('a')
 
389
    ['a']
 
390
    >>> splitpath('a/b')
 
391
    ['a', 'b']
 
392
    >>> splitpath('a/./b')
 
393
    ['a', 'b']
 
394
    >>> splitpath('a/.b')
 
395
    ['a', '.b']
 
396
    >>> splitpath('a/../b')
 
397
    Traceback (most recent call last):
 
398
    ...
 
399
    BzrError: sorry, '..' not allowed in path
 
400
    """
 
401
    assert isinstance(p, types.StringTypes)
 
402
 
 
403
    # split on either delimiter because people might use either on
 
404
    # Windows
 
405
    ps = re.split(r'[\\/]', p)
 
406
 
 
407
    rps = []
 
408
    for f in ps:
 
409
        if f == '..':
 
410
            raise BzrError("sorry, %r not allowed in path" % f)
 
411
        elif (f == '.') or (f == ''):
 
412
            pass
 
413
        else:
 
414
            rps.append(f)
 
415
    return rps
 
416
 
 
417
def joinpath(p):
 
418
    assert isinstance(p, list)
 
419
    for f in p:
 
420
        if (f == '..') or (f == None) or (f == ''):
 
421
            raise BzrError("sorry, %r not allowed in path" % f)
 
422
    return pathjoin(*p)
 
423
 
 
424
 
 
425
def appendpath(p1, p2):
 
426
    if p1 == '':
 
427
        return p2
 
428
    else:
 
429
        return pathjoin(p1, p2)
 
430
    
 
431
 
 
432
def split_lines(s):
 
433
    """Split s into lines, but without removing the newline characters."""
 
434
    return StringIO(s).readlines()
 
435
 
 
436
 
 
437
def hardlinks_good():
 
438
    return sys.platform not in ('win32', 'cygwin', 'darwin')
 
439
 
 
440
 
 
441
def link_or_copy(src, dest):
 
442
    """Hardlink a file, or copy it if it can't be hardlinked."""
 
443
    if not hardlinks_good():
 
444
        copyfile(src, dest)
 
445
        return
 
446
    try:
 
447
        os.link(src, dest)
 
448
    except (OSError, IOError), e:
 
449
        if e.errno != errno.EXDEV:
 
450
            raise
 
451
        copyfile(src, dest)
 
452
 
 
453
 
 
454
def has_symlinks():
 
455
    if hasattr(os, 'symlink'):
 
456
        return True
 
457
    else:
 
458
        return False
 
459
        
 
460
 
 
461
def contains_whitespace(s):
 
462
    """True if there are any whitespace characters in s."""
 
463
    for ch in string.whitespace:
 
464
        if ch in s:
 
465
            return True
 
466
    else:
 
467
        return False
 
468
 
 
469
 
 
470
def contains_linebreaks(s):
 
471
    """True if there is any vertical whitespace in s."""
 
472
    for ch in '\f\n\r':
 
473
        if ch in s:
 
474
            return True
 
475
    else:
 
476
        return False
 
477
 
 
478
 
 
479
def relpath(base, path):
 
480
    """Return path relative to base, or raise exception.
 
481
 
 
482
    The path may be either an absolute path or a path relative to the
 
483
    current working directory.
 
484
 
 
485
    os.path.commonprefix (python2.4) has a bad bug that it works just
 
486
    on string prefixes, assuming that '/u' is a prefix of '/u2'.  This
 
487
    avoids that problem."""
 
488
    rp = abspath(path)
 
489
 
 
490
    s = []
 
491
    head = rp
 
492
    while len(head) >= len(base):
 
493
        if head == base:
 
494
            break
 
495
        head, tail = os.path.split(head)
 
496
        if tail:
 
497
            s.insert(0, tail)
 
498
    else:
 
499
        # XXX This should raise a NotChildPath exception, as its not tied
 
500
        # to branch anymore.
 
501
        raise NotBranchError("path %r is not within branch %r" % (rp, base))
 
502
 
 
503
    if s:
 
504
        return pathjoin(*s)
 
505
    else:
 
506
        return ''
 
507
 
 
508
 
 
509
 
 
510
def terminal_width():
 
511
    """Return estimated terminal width."""
 
512
 
 
513
    # TODO: Do something smart on Windows?
 
514
 
 
515
    # TODO: Is there anything that gets a better update when the window
 
516
    # is resized while the program is running? We could use the Python termcap
 
517
    # library.
 
518
    try:
 
519
        return int(os.environ['COLUMNS'])
 
520
    except (IndexError, KeyError, ValueError):
 
521
        return 80