~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: Robert Collins
  • Date: 2005-10-15 00:32:03 UTC
  • mto: This revision was merged to the branch mainline in revision 1456.
  • Revision ID: robertc@lifelesslap.robertcollins.net-20051015003203-38a52da69f847663
add some documentation on options

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 sys
 
28
import time
 
29
import types
21
30
 
 
31
import bzrlib
22
32
from bzrlib.errors import BzrError
23
33
from bzrlib.trace import mutter
24
 
import bzrlib
 
34
 
25
35
 
26
36
def make_readonly(filename):
27
37
    """Make a filename read-only."""
28
 
    # TODO: probably needs to be fixed for windows
29
38
    mod = os.stat(filename).st_mode
30
39
    mod = mod & 0777555
31
40
    os.chmod(filename, mod)
48
57
    # TODO: I'm not really sure this is the best format either.x
49
58
    global _QUOTE_RE
50
59
    if _QUOTE_RE == None:
51
 
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/_~-])')
 
60
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
52
61
        
53
62
    if _QUOTE_RE.search(f):
54
63
        return '"' + f + '"'
64
73
        return 'directory'
65
74
    elif S_ISLNK(mode):
66
75
        return 'symlink'
 
76
    elif S_ISCHR(mode):
 
77
        return 'chardev'
 
78
    elif S_ISBLK(mode):
 
79
        return 'block'
 
80
    elif S_ISFIFO(mode):
 
81
        return 'fifo'
 
82
    elif S_ISSOCK(mode):
 
83
        return 'socket'
67
84
    else:
68
 
        raise BzrError("can't handle file kind with mode %o of %r" % (mode, f))
 
85
        return 'unknown'
69
86
 
70
87
 
71
88
def kind_marker(kind):
78
95
    else:
79
96
        raise BzrError('invalid file kind %r' % kind)
80
97
 
 
98
def lexists(f):
 
99
    try:
 
100
        if hasattr(os, 'lstat'):
 
101
            os.lstat(f)
 
102
        else:
 
103
            os.stat(f)
 
104
        return True
 
105
    except OSError,e:
 
106
        if e.errno == errno.ENOENT:
 
107
            return False;
 
108
        else:
 
109
            raise BzrError("lstat/stat of (%r): %r" % (f, e))
81
110
 
 
111
def normalizepath(f):
 
112
    if hasattr(os.path, 'realpath'):
 
113
        F = os.path.realpath
 
114
    else:
 
115
        F = os.path.abspath
 
116
    [p,e] = os.path.split(f)
 
117
    if e == "" or e == "." or e == "..":
 
118
        return F(f)
 
119
    else:
 
120
        return os.path.join(F(p), e)
 
121
    
82
122
 
83
123
def backup_file(fn):
84
124
    """Copy a file to a backup.
87
127
 
88
128
    If the file is already a backup, it's not copied.
89
129
    """
90
 
    import os
91
130
    if fn[-1] == '~':
92
131
        return
93
132
    bfn = fn + '~'
94
133
 
 
134
    if has_symlinks() and os.path.islink(fn):
 
135
        target = os.readlink(fn)
 
136
        os.symlink(target, bfn)
 
137
        return
95
138
    inf = file(fn, 'rb')
96
139
    try:
97
140
        content = inf.read()
104
147
    finally:
105
148
        outf.close()
106
149
 
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
 
 
 
150
if os.name == 'nt':
 
151
    import shutil
 
152
    rename = shutil.move
 
153
else:
 
154
    rename = os.rename
119
155
 
120
156
 
121
157
def isdir(f):
126
162
        return False
127
163
 
128
164
 
129
 
 
130
165
def isfile(f):
131
166
    """True if f is a regular file."""
132
167
    try:
134
169
    except OSError:
135
170
        return False
136
171
 
 
172
def islink(f):
 
173
    """True if f is a symlink."""
 
174
    try:
 
175
        return S_ISLNK(os.lstat(f)[ST_MODE])
 
176
    except OSError:
 
177
        return False
137
178
 
138
179
def is_inside(dir, fname):
139
180
    """True if fname is inside dir.
145
186
    The empty string as a dir name is taken as top-of-tree and matches 
146
187
    everything.
147
188
    
148
 
    >>> is_inside('src', 'src/foo.c')
 
189
    >>> is_inside('src', os.path.join('src', 'foo.c'))
149
190
    True
150
191
    >>> is_inside('src', 'srccontrol')
151
192
    False
152
 
    >>> is_inside('src', 'src/a/a/a/foo.c')
 
193
    >>> is_inside('src', os.path.join('src', 'a', 'a', 'a', 'foo.c'))
153
194
    True
154
195
    >>> is_inside('foo.c', 'foo.c')
155
196
    True
165
206
    
166
207
    if dir == '':
167
208
        return True
168
 
    
 
209
 
169
210
    if dir[-1] != os.sep:
170
211
        dir += os.sep
171
 
    
 
212
 
172
213
    return fname.startswith(dir)
173
214
 
174
215
 
186
227
    tofile.write(fromfile.read())
187
228
 
188
229
 
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())
195
 
 
196
 
 
197
230
def sha_file(f):
198
 
    import sha
199
231
    if hasattr(f, 'tell'):
200
232
        assert f.tell() == 0
201
233
    s = sha.new()
208
240
    return s.hexdigest()
209
241
 
210
242
 
 
243
 
 
244
def sha_strings(strings):
 
245
    """Return the sha-1 of concatenation of strings"""
 
246
    s = sha.new()
 
247
    map(s.update, strings)
 
248
    return s.hexdigest()
 
249
 
 
250
 
211
251
def sha_string(f):
212
 
    import sha
213
252
    s = sha.new()
214
253
    s.update(f)
215
254
    return s.hexdigest()
216
255
 
217
256
 
218
 
 
219
257
def fingerprint_file(f):
220
 
    import sha
221
258
    s = sha.new()
222
259
    b = f.read()
223
260
    s.update(b)
226
263
            'sha1': s.hexdigest()}
227
264
 
228
265
 
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
266
def compare_files(a, b):
354
267
    """Returns true if equal in contents"""
355
268
    BUFSIZE = 4096
362
275
            return True
363
276
 
364
277
 
365
 
 
366
278
def local_time_offset(t=None):
367
279
    """Return offset of local zone from GMT, either at present or at time t."""
368
280
    # python2.3 localtime() can't take None
407
319
    """Return size of given open file."""
408
320
    return os.fstat(f.fileno())[ST_SIZE]
409
321
 
410
 
 
411
 
if hasattr(os, 'urandom'): # python 2.4 and later
 
322
# Define rand_bytes based on platform.
 
323
try:
 
324
    # Python 2.4 and later have os.urandom,
 
325
    # but it doesn't work on some arches
 
326
    os.urandom(1)
412
327
    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
 
 
 
328
except (NotImplementedError, AttributeError):
 
329
    # If python doesn't have os.urandom, or it doesn't work,
 
330
    # then try to first pull random data from /dev/urandom
 
331
    if os.path.exists("/dev/urandom"):
 
332
        rand_bytes = file('/dev/urandom', 'rb').read
 
333
    # Otherwise, use this hack as a last resort
 
334
    else:
 
335
        # not well seeded, but better than nothing
 
336
        def rand_bytes(n):
 
337
            import random
 
338
            s = ''
 
339
            while n:
 
340
                s += chr(random.randint(0, 255))
 
341
                n -= 1
 
342
            return s
425
343
 
426
344
## TODO: We could later have path objects that remember their list
427
345
## decomposition (might be too tricksy though.)
473
391
        return os.path.join(p1, p2)
474
392
    
475
393
 
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"""
 
394
def split_lines(s):
 
395
    """Split s into lines, but without removing the newline characters."""
 
396
    return StringIO(s).readlines()
 
397
 
 
398
 
 
399
def hardlinks_good():
 
400
    return sys.platform not in ('win32', 'cygwin', 'darwin')
 
401
 
 
402
 
 
403
def link_or_copy(src, dest):
 
404
    """Hardlink a file, or copy it if it can't be hardlinked."""
 
405
    if not hardlinks_good():
 
406
        copyfile(src, dest)
 
407
        return
486
408
    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
 
 
 
409
        os.link(src, dest)
 
410
    except (OSError, IOError), e:
 
411
        if e.errno != errno.EXDEV:
 
412
            raise
 
413
        copyfile(src, dest)
 
414
 
 
415
 
 
416
def has_symlinks():
 
417
    if hasattr(os, 'symlink'):
 
418
        return True
 
419
    else:
 
420
        return False