/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: Robert Collins
  • Date: 2005-09-28 05:25:54 UTC
  • mfrom: (1185.1.42)
  • mto: (1092.2.18)
  • mto: This revision was merged to the branch mainline in revision 1397.
  • Revision ID: robertc@robertcollins.net-20050928052554-beb985505f77ea6a
update symlink branch to integration

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