~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: John Arbash Meinel
  • Date: 2005-12-01 21:11:49 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-20051201211149-adf18296c664f8d5
Refactoring Exceptions found some places where the wrong exception was caught.

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, sys
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 string
 
28
import sys
 
29
import time
 
30
import types
 
31
import tempfile
21
32
 
22
 
from bzrlib.errors import BzrError
 
33
import bzrlib
 
34
from bzrlib.errors import BzrError, PathNotChild
23
35
from bzrlib.trace import mutter
24
 
import bzrlib
 
36
 
25
37
 
26
38
def make_readonly(filename):
27
39
    """Make a filename read-only."""
28
 
    # TODO: probably needs to be fixed for windows
29
40
    mod = os.stat(filename).st_mode
30
41
    mod = mod & 0777555
31
42
    os.chmod(filename, mod)
48
59
    # TODO: I'm not really sure this is the best format either.x
49
60
    global _QUOTE_RE
50
61
    if _QUOTE_RE == None:
51
 
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/_~-])')
 
62
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
52
63
        
53
64
    if _QUOTE_RE.search(f):
54
65
        return '"' + f + '"'
64
75
        return 'directory'
65
76
    elif S_ISLNK(mode):
66
77
        return 'symlink'
 
78
    elif S_ISCHR(mode):
 
79
        return 'chardev'
 
80
    elif S_ISBLK(mode):
 
81
        return 'block'
 
82
    elif S_ISFIFO(mode):
 
83
        return 'fifo'
 
84
    elif S_ISSOCK(mode):
 
85
        return 'socket'
67
86
    else:
68
 
        raise BzrError("can't handle file kind with mode %o of %r" % (mode, f))
 
87
        return 'unknown'
69
88
 
70
89
 
71
90
def kind_marker(kind):
78
97
    else:
79
98
        raise BzrError('invalid file kind %r' % kind)
80
99
 
 
100
def lexists(f):
 
101
    if hasattr(os.path, 'lexists'):
 
102
        return os.path.lexists(f)
 
103
    try:
 
104
        if hasattr(os, 'lstat'):
 
105
            os.lstat(f)
 
106
        else:
 
107
            os.stat(f)
 
108
        return True
 
109
    except OSError,e:
 
110
        if e.errno == errno.ENOENT:
 
111
            return False;
 
112
        else:
 
113
            raise BzrError("lstat/stat of (%r): %r" % (f, e))
 
114
 
 
115
if os.name == "posix":
 
116
    # In Python 2.4.2 and older, os.path.abspath and os.path.realpath
 
117
    # choke on a Unicode string containing a relative path if
 
118
    # os.getcwd() returns a non-sys.getdefaultencoding()-encoded
 
119
    # string.
 
120
    _fs_enc = sys.getfilesystemencoding()
 
121
    def abspath(path):
 
122
        return os.path.abspath(path.encode(_fs_enc)).decode(_fs_enc)
 
123
    def realpath(path):
 
124
        return os.path.realpath(path.encode(_fs_enc)).decode(_fs_enc)
 
125
    pathjoin = os.path.join
 
126
    normpath = os.path.normpath
 
127
    getcwd = os.getcwdu
 
128
    mkdtemp = tempfile.mkdtemp
 
129
else:
 
130
    # We need to use the Unicode-aware os.path.abspath and
 
131
    # os.path.realpath on Windows systems.
 
132
    def abspath(path):
 
133
        return os.path.abspath(path).replace('\\', '/')
 
134
    def realpath(path):
 
135
        return os.path.realpath(path).replace('\\', '/')
 
136
    def pathjoin(*args):
 
137
        return os.path.join(*args).replace('\\', '/')
 
138
    def normpath(path):
 
139
        return os.path.normpath(path).replace('\\', '/')
 
140
    def getcwd():
 
141
        return os.getcwdu().replace('\\', '/')
 
142
    def mkdtemp(*args, **kwargs):
 
143
        return tempfile.mkdtemp(*args, **kwargs).replace('\\', '/')
 
144
# Because these shrink the path, we can use the original
 
145
# versions on any platform
 
146
dirname = os.path.dirname
 
147
basename = os.path.basename
 
148
 
 
149
def normalizepath(f):
 
150
    if hasattr(os.path, 'realpath'):
 
151
        F = realpath
 
152
    else:
 
153
        F = abspath
 
154
    [p,e] = os.path.split(f)
 
155
    if e == "" or e == "." or e == "..":
 
156
        return F(f)
 
157
    else:
 
158
        return pathjoin(F(p), e)
81
159
 
82
160
 
83
161
def backup_file(fn):
87
165
 
88
166
    If the file is already a backup, it's not copied.
89
167
    """
90
 
    import os
91
168
    if fn[-1] == '~':
92
169
        return
93
170
    bfn = fn + '~'
94
171
 
 
172
    if has_symlinks() and os.path.islink(fn):
 
173
        target = os.readlink(fn)
 
174
        os.symlink(target, bfn)
 
175
        return
95
176
    inf = file(fn, 'rb')
96
177
    try:
97
178
        content = inf.read()
104
185
    finally:
105
186
        outf.close()
106
187
 
107
 
def rename(path_from, path_to):
108
 
    """Basically the same as os.rename() just special for win32"""
109
 
    if sys.platform == 'win32':
110
 
        try:
111
 
            os.remove(path_to)
112
 
        except OSError, e:
113
 
            if e.errno != e.ENOENT:
114
 
                raise
115
 
    os.rename(path_from, path_to)
116
 
 
117
 
 
118
 
 
 
188
if os.name == 'nt':
 
189
    import shutil
 
190
    rename = shutil.move
 
191
else:
 
192
    rename = os.rename
119
193
 
120
194
 
121
195
def isdir(f):
126
200
        return False
127
201
 
128
202
 
129
 
 
130
203
def isfile(f):
131
204
    """True if f is a regular file."""
132
205
    try:
134
207
    except OSError:
135
208
        return False
136
209
 
 
210
def islink(f):
 
211
    """True if f is a symlink."""
 
212
    try:
 
213
        return S_ISLNK(os.lstat(f)[ST_MODE])
 
214
    except OSError:
 
215
        return False
137
216
 
138
217
def is_inside(dir, fname):
139
218
    """True if fname is inside dir.
140
219
    
141
 
    The parameters should typically be passed to os.path.normpath first, so
 
220
    The parameters should typically be passed to osutils.normpath first, so
142
221
    that . and .. and repeated slashes are eliminated, and the separators
143
222
    are canonical for the platform.
144
223
    
145
224
    The empty string as a dir name is taken as top-of-tree and matches 
146
225
    everything.
147
226
    
148
 
    >>> is_inside('src', 'src/foo.c')
 
227
    >>> is_inside('src', pathjoin('src', 'foo.c'))
149
228
    True
150
229
    >>> is_inside('src', 'srccontrol')
151
230
    False
152
 
    >>> is_inside('src', 'src/a/a/a/foo.c')
 
231
    >>> is_inside('src', pathjoin('src', 'a', 'a', 'a', 'foo.c'))
153
232
    True
154
233
    >>> is_inside('foo.c', 'foo.c')
155
234
    True
165
244
    
166
245
    if dir == '':
167
246
        return True
168
 
    
169
 
    if dir[-1] != os.sep:
170
 
        dir += os.sep
171
 
    
 
247
 
 
248
    if dir[-1] != '/':
 
249
        dir += '/'
 
250
 
172
251
    return fname.startswith(dir)
173
252
 
174
253
 
183
262
 
184
263
def pumpfile(fromfile, tofile):
185
264
    """Copy contents of one file to another."""
186
 
    tofile.write(fromfile.read())
187
 
 
188
 
 
189
 
def uuid():
190
 
    """Return a new UUID"""
191
 
    try:
192
 
        return file('/proc/sys/kernel/random/uuid').readline().rstrip('\n')
193
 
    except IOError:
194
 
        return chomp(os.popen('uuidgen').readline())
 
265
    BUFSIZE = 32768
 
266
    while True:
 
267
        b = fromfile.read(BUFSIZE)
 
268
        if not b:
 
269
            break
 
270
        tofile.write(b)
195
271
 
196
272
 
197
273
def sha_file(f):
198
 
    import sha
199
274
    if hasattr(f, 'tell'):
200
275
        assert f.tell() == 0
201
276
    s = sha.new()
208
283
    return s.hexdigest()
209
284
 
210
285
 
 
286
 
 
287
def sha_strings(strings):
 
288
    """Return the sha-1 of concatenation of strings"""
 
289
    s = sha.new()
 
290
    map(s.update, strings)
 
291
    return s.hexdigest()
 
292
 
 
293
 
211
294
def sha_string(f):
212
 
    import sha
213
295
    s = sha.new()
214
296
    s.update(f)
215
297
    return s.hexdigest()
216
298
 
217
299
 
218
 
 
219
300
def fingerprint_file(f):
220
 
    import sha
221
301
    s = sha.new()
222
302
    b = f.read()
223
303
    s.update(b)
226
306
            'sha1': s.hexdigest()}
227
307
 
228
308
 
229
 
def config_dir():
230
 
    """Return per-user configuration directory.
231
 
 
232
 
    By default this is ~/.bzr.conf/
233
 
    
234
 
    TODO: Global option --config-dir to override this.
235
 
    """
236
 
    return os.path.expanduser("~/.bzr.conf")
237
 
 
238
 
 
239
 
def _auto_user_id():
240
 
    """Calculate automatic user identification.
241
 
 
242
 
    Returns (realname, email).
243
 
 
244
 
    Only used when none is set in the environment or the id file.
245
 
 
246
 
    This previously used the FQDN as the default domain, but that can
247
 
    be very slow on machines where DNS is broken.  So now we simply
248
 
    use the hostname.
249
 
    """
250
 
    import socket
251
 
 
252
 
    # XXX: Any good way to get real user name on win32?
253
 
 
254
 
    try:
255
 
        import pwd
256
 
        uid = os.getuid()
257
 
        w = pwd.getpwuid(uid)
258
 
        gecos = w.pw_gecos.decode(bzrlib.user_encoding)
259
 
        username = w.pw_name.decode(bzrlib.user_encoding)
260
 
        comma = gecos.find(',')
261
 
        if comma == -1:
262
 
            realname = gecos
263
 
        else:
264
 
            realname = gecos[:comma]
265
 
        if not realname:
266
 
            realname = username
267
 
 
268
 
    except ImportError:
269
 
        import getpass
270
 
        realname = username = getpass.getuser().decode(bzrlib.user_encoding)
271
 
 
272
 
    return realname, (username + '@' + socket.gethostname())
273
 
 
274
 
 
275
 
def _get_user_id(branch):
276
 
    """Return the full user id from a file or environment variable.
277
 
 
278
 
    e.g. "John Hacker <jhacker@foo.org>"
279
 
 
280
 
    branch
281
 
        A branch to use for a per-branch configuration, or None.
282
 
 
283
 
    The following are searched in order:
284
 
 
285
 
    1. $BZREMAIL
286
 
    2. .bzr/email for this branch.
287
 
    3. ~/.bzr.conf/email
288
 
    4. $EMAIL
289
 
    """
290
 
    v = os.environ.get('BZREMAIL')
291
 
    if v:
292
 
        return v.decode(bzrlib.user_encoding)
293
 
 
294
 
    if branch:
295
 
        try:
296
 
            return (branch.controlfile("email", "r") 
297
 
                    .read()
298
 
                    .decode(bzrlib.user_encoding)
299
 
                    .rstrip("\r\n"))
300
 
        except IOError, e:
301
 
            if e.errno != errno.ENOENT:
302
 
                raise
303
 
        except BzrError, e:
304
 
            pass
305
 
    
306
 
    try:
307
 
        return (open(os.path.join(config_dir(), "email"))
308
 
                .read()
309
 
                .decode(bzrlib.user_encoding)
310
 
                .rstrip("\r\n"))
311
 
    except IOError, e:
312
 
        if e.errno != errno.ENOENT:
313
 
            raise e
314
 
 
315
 
    v = os.environ.get('EMAIL')
316
 
    if v:
317
 
        return v.decode(bzrlib.user_encoding)
318
 
    else:    
319
 
        return None
320
 
 
321
 
 
322
 
def username(branch):
323
 
    """Return email-style username.
324
 
 
325
 
    Something similar to 'Martin Pool <mbp@sourcefrog.net>'
326
 
 
327
 
    TODO: Check it's reasonably well-formed.
328
 
    """
329
 
    v = _get_user_id(branch)
330
 
    if v:
331
 
        return v
332
 
    
333
 
    name, email = _auto_user_id()
334
 
    if name:
335
 
        return '%s <%s>' % (name, email)
336
 
    else:
337
 
        return email
338
 
 
339
 
 
340
 
def user_email(branch):
341
 
    """Return just the email component of a username."""
342
 
    e = _get_user_id(branch)
343
 
    if e:
344
 
        m = re.search(r'[\w+.-]+@[\w+.-]+', e)
345
 
        if not m:
346
 
            raise BzrError("%r doesn't seem to contain a reasonable email address" % e)
347
 
        return m.group(0)
348
 
 
349
 
    return _auto_user_id()[1]
350
 
    
351
 
 
352
 
 
353
309
def compare_files(a, b):
354
310
    """Returns true if equal in contents"""
355
311
    BUFSIZE = 4096
362
318
            return True
363
319
 
364
320
 
365
 
 
366
321
def local_time_offset(t=None):
367
322
    """Return offset of local zone from GMT, either at present or at time t."""
368
323
    # python2.3 localtime() can't take None
375
330
        return -time.timezone
376
331
 
377
332
    
378
 
def format_date(t, offset=0, timezone='original'):
 
333
def format_date(t, offset=0, timezone='original', date_fmt=None, 
 
334
                show_offset=True):
379
335
    ## TODO: Perhaps a global option to use either universal or local time?
380
336
    ## Or perhaps just let people set $TZ?
381
337
    assert isinstance(t, float)
393
349
    else:
394
350
        raise BzrError("unsupported timezone format %r" % timezone,
395
351
                       ['options are "utc", "original", "local"'])
396
 
 
397
 
    return (time.strftime("%a %Y-%m-%d %H:%M:%S", tt)
398
 
            + ' %+03d%02d' % (offset / 3600, (offset / 60) % 60))
 
352
    if date_fmt is None:
 
353
        date_fmt = "%a %Y-%m-%d %H:%M:%S"
 
354
    if show_offset:
 
355
        offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
 
356
    else:
 
357
        offset_str = ''
 
358
    return (time.strftime(date_fmt, tt) +  offset_str)
399
359
 
400
360
 
401
361
def compact_date(when):
407
367
    """Return size of given open file."""
408
368
    return os.fstat(f.fileno())[ST_SIZE]
409
369
 
410
 
 
411
 
if hasattr(os, 'urandom'): # python 2.4 and later
 
370
# Define rand_bytes based on platform.
 
371
try:
 
372
    # Python 2.4 and later have os.urandom,
 
373
    # but it doesn't work on some arches
 
374
    os.urandom(1)
412
375
    rand_bytes = os.urandom
413
 
elif sys.platform == 'linux2':
414
 
    rand_bytes = file('/dev/urandom', 'rb').read
415
 
else:
416
 
    # not well seeded, but better than nothing
417
 
    def rand_bytes(n):
418
 
        import random
419
 
        s = ''
420
 
        while n:
421
 
            s += chr(random.randint(0, 255))
422
 
            n -= 1
423
 
        return s
424
 
 
 
376
except (NotImplementedError, AttributeError):
 
377
    # If python doesn't have os.urandom, or it doesn't work,
 
378
    # then try to first pull random data from /dev/urandom
 
379
    if os.path.exists("/dev/urandom"):
 
380
        rand_bytes = file('/dev/urandom', 'rb').read
 
381
    # Otherwise, use this hack as a last resort
 
382
    else:
 
383
        # not well seeded, but better than nothing
 
384
        def rand_bytes(n):
 
385
            import random
 
386
            s = ''
 
387
            while n:
 
388
                s += chr(random.randint(0, 255))
 
389
                n -= 1
 
390
            return s
425
391
 
426
392
## TODO: We could later have path objects that remember their list
427
393
## decomposition (might be too tricksy though.)
463
429
    for f in p:
464
430
        if (f == '..') or (f == None) or (f == ''):
465
431
            raise BzrError("sorry, %r not allowed in path" % f)
466
 
    return os.path.join(*p)
 
432
    return pathjoin(*p)
467
433
 
468
434
 
469
435
def appendpath(p1, p2):
470
436
    if p1 == '':
471
437
        return p2
472
438
    else:
473
 
        return os.path.join(p1, p2)
 
439
        return pathjoin(p1, p2)
474
440
    
475
441
 
476
 
def extern_command(cmd, ignore_errors = False):
477
 
    mutter('external command: %s' % `cmd`)
478
 
    if os.system(cmd):
479
 
        if not ignore_errors:
480
 
            raise BzrError('command failed')
481
 
 
482
 
 
483
 
def _read_config_value(name):
484
 
    """Read a config value from the file ~/.bzr.conf/<name>
485
 
    Return None if the file does not exist"""
486
 
    try:
487
 
        f = file(os.path.join(config_dir(), name), "r")
488
 
        return f.read().decode(bzrlib.user_encoding).rstrip("\r\n")
489
 
    except IOError, e:
490
 
        if e.errno == errno.ENOENT:
491
 
            return None
492
 
        raise
493
 
 
494
 
 
 
442
def split_lines(s):
 
443
    """Split s into lines, but without removing the newline characters."""
 
444
    return StringIO(s).readlines()
 
445
 
 
446
 
 
447
def hardlinks_good():
 
448
    return sys.platform not in ('win32', 'cygwin', 'darwin')
 
449
 
 
450
 
 
451
def link_or_copy(src, dest):
 
452
    """Hardlink a file, or copy it if it can't be hardlinked."""
 
453
    if not hardlinks_good():
 
454
        copyfile(src, dest)
 
455
        return
 
456
    try:
 
457
        os.link(src, dest)
 
458
    except (OSError, IOError), e:
 
459
        if e.errno != errno.EXDEV:
 
460
            raise
 
461
        copyfile(src, dest)
 
462
 
 
463
 
 
464
def has_symlinks():
 
465
    if hasattr(os, 'symlink'):
 
466
        return True
 
467
    else:
 
468
        return False
 
469
        
 
470
 
 
471
def contains_whitespace(s):
 
472
    """True if there are any whitespace characters in s."""
 
473
    for ch in string.whitespace:
 
474
        if ch in s:
 
475
            return True
 
476
    else:
 
477
        return False
 
478
 
 
479
 
 
480
def contains_linebreaks(s):
 
481
    """True if there is any vertical whitespace in s."""
 
482
    for ch in '\f\n\r':
 
483
        if ch in s:
 
484
            return True
 
485
    else:
 
486
        return False
 
487
 
 
488
 
 
489
def relpath(base, path):
 
490
    """Return path relative to base, or raise exception.
 
491
 
 
492
    The path may be either an absolute path or a path relative to the
 
493
    current working directory.
 
494
 
 
495
    os.path.commonprefix (python2.4) has a bad bug that it works just
 
496
    on string prefixes, assuming that '/u' is a prefix of '/u2'.  This
 
497
    avoids that problem."""
 
498
    rp = abspath(path)
 
499
 
 
500
    s = []
 
501
    head = rp
 
502
    while len(head) >= len(base):
 
503
        if head == base:
 
504
            break
 
505
        head, tail = os.path.split(head)
 
506
        if tail:
 
507
            s.insert(0, tail)
 
508
    else:
 
509
        # XXX This should raise a NotChildPath exception, as its not tied
 
510
        # to branch anymore.
 
511
        raise PathNotChild(rp, base)
 
512
 
 
513
    if s:
 
514
        return pathjoin(*s)
 
515
    else:
 
516
        return ''
 
517
 
 
518
 
 
519
 
 
520
def terminal_width():
 
521
    """Return estimated terminal width."""
 
522
 
 
523
    # TODO: Do something smart on Windows?
 
524
 
 
525
    # TODO: Is there anything that gets a better update when the window
 
526
    # is resized while the program is running? We could use the Python termcap
 
527
    # library.
 
528
    try:
 
529
        return int(os.environ['COLUMNS'])
 
530
    except (IndexError, KeyError, ValueError):
 
531
        return 80