~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: mbp at sourcefrog
  • Date: 2005-03-30 22:27:17 UTC
  • Revision ID: mbp@sourcefrog.net-20050330222717-027b5837127b938d
experiment with new nested inventory file format
not used by default yet

Show diffs side-by-side

added added

removed removed

Lines of Context:
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
 
19
import os, types, re, time, types
20
20
from stat import S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE
21
21
 
22
 
from bzrlib.errors import BzrError
23
 
from bzrlib.trace import mutter
24
 
import bzrlib
 
22
from errors import bailout
25
23
 
26
24
def make_readonly(filename):
27
25
    """Make a filename read-only."""
39
37
 
40
38
_QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/_~-])')
41
39
def quotefn(f):
42
 
    """Return a quoted filename filename
43
 
 
44
 
    This previously used backslash quoting, but that works poorly on
45
 
    Windows."""
46
 
    # TODO: I'm not really sure this is the best format either.x
47
 
    if _QUOTE_RE.search(f):
48
 
        return '"' + f + '"'
49
 
    else:
50
 
        return f
 
40
    """Return shell-quoted filename"""
 
41
    ## We could be a bit more terse by using double-quotes etc
 
42
    f = _QUOTE_RE.sub(r'\\\1', f)
 
43
    if f[0] == '~':
 
44
        f[0:1] = r'\~' 
 
45
    return f
51
46
 
52
47
 
53
48
def file_kind(f):
59
54
    elif S_ISLNK(mode):
60
55
        return 'symlink'
61
56
    else:
62
 
        raise BzrError("can't handle file kind with mode %o of %r" % (mode, f))
63
 
 
64
 
 
65
 
def kind_marker(kind):
66
 
    if kind == 'file':
67
 
        return ''
68
 
    elif kind == 'directory':
69
 
        return '/'
70
 
    elif kind == 'symlink':
71
 
        return '@'
72
 
    else:
73
 
        raise BzrError('invalid file kind %r' % kind)
74
 
 
75
 
 
76
 
 
77
 
def backup_file(fn):
78
 
    """Copy a file to a backup.
79
 
 
80
 
    Backups are named in GNU-style, with a ~ suffix.
81
 
 
82
 
    If the file is already a backup, it's not copied.
83
 
    """
84
 
    import os
85
 
    if fn[-1] == '~':
86
 
        return
87
 
    bfn = fn + '~'
88
 
 
89
 
    inf = file(fn, 'rb')
90
 
    try:
91
 
        content = inf.read()
92
 
    finally:
93
 
        inf.close()
94
 
    
95
 
    outf = file(bfn, 'wb')
96
 
    try:
97
 
        outf.write(content)
98
 
    finally:
99
 
        outf.close()
100
 
 
101
 
def rename(path_from, path_to):
102
 
    """Basically the same as os.rename() just special for win32"""
103
 
    if sys.platform == 'win32':
104
 
        try:
105
 
            os.remove(path_to)
106
 
        except OSError, e:
107
 
            if e.errno != e.ENOENT:
108
 
                raise
109
 
    os.rename(path_from, path_to)
110
 
 
111
 
 
 
57
        bailout("can't handle file kind with mode %o of %r" % (mode, f)) 
112
58
 
113
59
 
114
60
 
129
75
        return False
130
76
 
131
77
 
132
 
def is_inside(dir, fname):
133
 
    """True if fname is inside dir.
134
 
    """
135
 
    return os.path.commonprefix([dir, fname]) == dir
136
 
 
137
 
 
138
 
def is_inside_any(dir_list, fname):
139
 
    """True if fname is inside any of given dirs."""
140
 
    # quick scan for perfect match
141
 
    if fname in dir_list:
142
 
        return True
143
 
    
144
 
    for dirname in dir_list:
145
 
        if is_inside(dirname, fname):
146
 
            return True
147
 
    else:
148
 
        return False
149
 
 
150
 
 
151
78
def pumpfile(fromfile, tofile):
152
79
    """Copy contents of one file to another."""
153
80
    tofile.write(fromfile.read())
155
82
 
156
83
def uuid():
157
84
    """Return a new UUID"""
 
85
    
 
86
    ## XXX: Could alternatively read /proc/sys/kernel/random/uuid on
 
87
    ## Linux, but we need something portable for other systems;
 
88
    ## preferably an implementation in Python.
158
89
    try:
159
 
        return file('/proc/sys/kernel/random/uuid').readline().rstrip('\n')
 
90
        return chomp(file('/proc/sys/kernel/random/uuid').readline())
160
91
    except IOError:
161
92
        return chomp(os.popen('uuidgen').readline())
162
93
 
163
94
 
 
95
def chomp(s):
 
96
    if s and (s[-1] == '\n'):
 
97
        return s[:-1]
 
98
    else:
 
99
        return s
 
100
 
 
101
 
164
102
def sha_file(f):
165
103
    import sha
 
104
    ## TODO: Maybe read in chunks to handle big files
166
105
    if hasattr(f, 'tell'):
167
106
        assert f.tell() == 0
168
107
    s = sha.new()
169
 
    BUFSIZE = 128<<10
170
 
    while True:
171
 
        b = f.read(BUFSIZE)
172
 
        if not b:
173
 
            break
174
 
        s.update(b)
 
108
    s.update(f.read())
175
109
    return s.hexdigest()
176
110
 
177
111
 
193
127
            'sha1': s.hexdigest()}
194
128
 
195
129
 
196
 
def config_dir():
197
 
    """Return per-user configuration directory.
198
 
 
199
 
    By default this is ~/.bzr.conf/
200
 
    
201
 
    TODO: Global option --config-dir to override this.
202
 
    """
203
 
    return os.path.expanduser("~/.bzr.conf")
204
 
 
205
 
 
206
 
def _auto_user_id():
207
 
    """Calculate automatic user identification.
208
 
 
209
 
    Returns (realname, email).
210
 
 
211
 
    Only used when none is set in the environment or the id file.
212
 
 
213
 
    This previously used the FQDN as the default domain, but that can
214
 
    be very slow on machines where DNS is broken.  So now we simply
215
 
    use the hostname.
216
 
    """
 
130
 
 
131
def username():
 
132
    """Return email-style username.
 
133
 
 
134
    Something similar to 'Martin Pool <mbp@sourcefrog.net>'
 
135
 
 
136
    :todo: Check it's reasonably well-formed.
 
137
 
 
138
    :todo: Allow taking it from a dotfile to help people on windows
 
139
           who can't easily set variables.
 
140
 
 
141
    :todo: Cope without pwd module, which is only on unix. 
 
142
    """
 
143
    e = os.environ.get('BZREMAIL') or os.environ.get('EMAIL')
 
144
    if e: return e
 
145
 
217
146
    import socket
218
 
 
219
 
    # XXX: Any good way to get real user name on win32?
220
 
 
 
147
    
221
148
    try:
222
149
        import pwd
223
150
        uid = os.getuid()
224
151
        w = pwd.getpwuid(uid)
225
 
        gecos = w.pw_gecos.decode(bzrlib.user_encoding)
226
 
        username = w.pw_name.decode(bzrlib.user_encoding)
 
152
        gecos = w.pw_gecos
227
153
        comma = gecos.find(',')
228
154
        if comma == -1:
229
155
            realname = gecos
230
156
        else:
231
157
            realname = gecos[:comma]
232
 
        if not realname:
233
 
            realname = username
234
 
 
 
158
        return '%s <%s@%s>' % (realname, w.pw_name, socket.getfqdn())
235
159
    except ImportError:
236
 
        import getpass
237
 
        realname = username = getpass.getuser().decode(bzrlib.user_encoding)
238
 
 
239
 
    return realname, (username + '@' + socket.gethostname())
240
 
 
241
 
 
242
 
def _get_user_id():
243
 
    """Return the full user id from a file or environment variable.
244
 
 
245
 
    TODO: Allow taking this from a file in the branch directory too
246
 
    for per-branch ids."""
247
 
    v = os.environ.get('BZREMAIL')
248
 
    if v:
249
 
        return v.decode(bzrlib.user_encoding)
250
 
    
251
 
    try:
252
 
        return (open(os.path.join(config_dir(), "email"))
253
 
                .read()
254
 
                .decode(bzrlib.user_encoding)
255
 
                .rstrip("\r\n"))
256
 
    except IOError, e:
257
 
        if e.errno != errno.ENOENT:
258
 
            raise e
259
 
 
260
 
    v = os.environ.get('EMAIL')
261
 
    if v:
262
 
        return v.decode(bzrlib.user_encoding)
263
 
    else:    
264
 
        return None
265
 
 
266
 
 
267
 
def username():
268
 
    """Return email-style username.
269
 
 
270
 
    Something similar to 'Martin Pool <mbp@sourcefrog.net>'
271
 
 
272
 
    TODO: Check it's reasonably well-formed.
273
 
    """
274
 
    v = _get_user_id()
275
 
    if v:
276
 
        return v
277
 
    
278
 
    name, email = _auto_user_id()
279
 
    if name:
280
 
        return '%s <%s>' % (name, email)
281
 
    else:
282
 
        return email
283
 
 
284
 
 
285
 
_EMAIL_RE = re.compile(r'[\w+.-]+@[\w+.-]+')
 
160
        pass
 
161
 
 
162
    import getpass, socket
 
163
    return '<%s@%s>' % (getpass.getuser(), socket.getfqdn())
 
164
 
 
165
 
286
166
def user_email():
287
167
    """Return just the email component of a username."""
288
 
    e = _get_user_id()
 
168
    e = os.environ.get('BZREMAIL') or os.environ.get('EMAIL')
289
169
    if e:
290
 
        m = _EMAIL_RE.search(e)
 
170
        import re
 
171
        m = re.search(r'[\w+.-]+@[\w+.-]+', e)
291
172
        if not m:
292
 
            raise BzrError("%r doesn't seem to contain a reasonable email address" % e)
 
173
            bailout('%r is not a reasonable email address' % e)
293
174
        return m.group(0)
294
175
 
295
 
    return _auto_user_id()[1]
 
176
 
 
177
    import getpass, socket
 
178
    return '%s@%s' % (getpass.getuser(), socket.getfqdn())
 
179
 
296
180
    
297
181
 
298
182
 
299
183
def compare_files(a, b):
300
184
    """Returns true if equal in contents"""
 
185
    # TODO: don't read the whole thing in one go.
301
186
    BUFSIZE = 4096
302
187
    while True:
303
188
        ai = a.read(BUFSIZE)
312
197
def local_time_offset(t=None):
313
198
    """Return offset of local zone from GMT, either at present or at time t."""
314
199
    # python2.3 localtime() can't take None
315
 
    if t == None:
 
200
    if t is None:
316
201
        t = time.time()
317
202
        
318
203
    if time.localtime(t).tm_isdst and time.daylight:
324
209
def format_date(t, offset=0, timezone='original'):
325
210
    ## TODO: Perhaps a global option to use either universal or local time?
326
211
    ## Or perhaps just let people set $TZ?
 
212
    import time
 
213
    
327
214
    assert isinstance(t, float)
328
215
    
329
216
    if timezone == 'utc':
337
224
        tt = time.localtime(t)
338
225
        offset = local_time_offset(t)
339
226
    else:
340
 
        raise BzrError("unsupported timezone format %r",
 
227
        bailout("unsupported timezone format %r",
341
228
                ['options are "utc", "original", "local"'])
342
229
 
343
230
    return (time.strftime("%a %Y-%m-%d %H:%M:%S", tt)
356
243
 
357
244
if hasattr(os, 'urandom'): # python 2.4 and later
358
245
    rand_bytes = os.urandom
359
 
elif sys.platform == 'linux2':
360
 
    rand_bytes = file('/dev/urandom', 'rb').read
361
246
else:
362
 
    # not well seeded, but better than nothing
363
 
    def rand_bytes(n):
364
 
        import random
365
 
        s = ''
366
 
        while n:
367
 
            s += chr(random.randint(0, 255))
368
 
            n -= 1
369
 
        return s
 
247
    # FIXME: No good on non-Linux
 
248
    _rand_file = file('/dev/urandom', 'rb')
 
249
    rand_bytes = _rand_file.read
370
250
 
371
251
 
372
252
## TODO: We could later have path objects that remember their list
386
266
    >>> splitpath('a/../b')
387
267
    Traceback (most recent call last):
388
268
    ...
389
 
    BzrError: sorry, '..' not allowed in path
 
269
    BzrError: ("sorry, '..' not allowed in path", [])
390
270
    """
391
271
    assert isinstance(p, types.StringTypes)
392
 
 
393
 
    # split on either delimiter because people might use either on
394
 
    # Windows
395
 
    ps = re.split(r'[\\/]', p)
396
 
 
397
 
    rps = []
 
272
    ps = [f for f in p.split('/') if f != '.']
398
273
    for f in ps:
399
274
        if f == '..':
400
 
            raise BzrError("sorry, %r not allowed in path" % f)
401
 
        elif (f == '.') or (f == ''):
402
 
            pass
403
 
        else:
404
 
            rps.append(f)
405
 
    return rps
 
275
            bailout("sorry, %r not allowed in path" % f)
 
276
    return ps
406
277
 
407
278
def joinpath(p):
408
279
    assert isinstance(p, list)
409
280
    for f in p:
410
 
        if (f == '..') or (f == None) or (f == ''):
411
 
            raise BzrError("sorry, %r not allowed in path" % f)
412
 
    return os.path.join(*p)
 
281
        if (f == '..') or (f is None) or (f == ''):
 
282
            bailout("sorry, %r not allowed in path" % f)
 
283
    return '/'.join(p)
413
284
 
414
285
 
415
286
def appendpath(p1, p2):
416
287
    if p1 == '':
417
288
        return p2
418
289
    else:
419
 
        return os.path.join(p1, p2)
 
290
        return p1 + '/' + p2
420
291
    
421
292
 
422
293
def extern_command(cmd, ignore_errors = False):
423
294
    mutter('external command: %s' % `cmd`)
424
295
    if os.system(cmd):
425
296
        if not ignore_errors:
426
 
            raise BzrError('command failed')
427
 
 
428
 
 
429
 
def _read_config_value(name):
430
 
    """Read a config value from the file ~/.bzr.conf/<name>
431
 
    Return None if the file does not exist"""
432
 
    try:
433
 
        f = file(os.path.join(config_dir(), name), "r")
434
 
        return f.read().decode(bzrlib.user_encoding).rstrip("\r\n")
435
 
    except IOError, e:
436
 
        if e.errno == errno.ENOENT:
437
 
            return None
438
 
        raise
439
 
 
440
 
 
441
 
def _get_editor():
442
 
    """Return a sequence of possible editor binaries for the current platform"""
443
 
    e = _read_config_value("editor")
444
 
    if e is not None:
445
 
        yield e
446
 
        
447
 
    if os.name == "windows":
448
 
        yield "notepad.exe"
449
 
    elif os.name == "posix":
450
 
        try:
451
 
            yield os.environ["EDITOR"]
452
 
        except KeyError:
453
 
            yield "/usr/bin/vi"
454
 
 
455
 
 
456
 
def _run_editor(filename):
457
 
    """Try to execute an editor to edit the commit message. Returns True on success,
458
 
    False on failure"""
459
 
    for e in _get_editor():
460
 
        x = os.spawnvp(os.P_WAIT, e, (e, filename))
461
 
        if x == 0:
462
 
            return True
463
 
        elif x == 127:
464
 
            continue
465
 
        else:
466
 
            break
467
 
    raise BzrError("Could not start any editor. Please specify $EDITOR or use ~/.bzr.conf/editor")
468
 
    return False
469
 
                          
470
 
 
471
 
def get_text_message(infotext, ignoreline = "default"):
472
 
    import tempfile
473
 
    
474
 
    if ignoreline == "default":
475
 
        ignoreline = "-- This line and the following will be ignored --"
476
 
        
477
 
    try:
478
 
        tmp_fileno, msgfilename = tempfile.mkstemp()
479
 
        msgfile = os.close(tmp_fileno)
480
 
        if infotext is not None and infotext != "":
481
 
            hasinfo = True
482
 
            msgfile = file(msgfilename, "w")
483
 
            msgfile.write("\n\n%s\n\n%s" % (ignoreline, infotext))
484
 
            msgfile.close()
485
 
        else:
486
 
            hasinfo = False
487
 
 
488
 
        if not _run_editor(msgfilename):
489
 
            return None
490
 
        
491
 
        started = False
492
 
        msg = []
493
 
        lastline, nlines = 0, 0
494
 
        for line in file(msgfilename, "r"):
495
 
            stripped_line = line.strip()
496
 
            # strip empty line before the log message starts
497
 
            if not started:
498
 
                if stripped_line != "":
499
 
                    started = True
500
 
                else:
501
 
                    continue
502
 
            # check for the ignore line only if there
503
 
            # is additional information at the end
504
 
            if hasinfo and stripped_line == ignoreline:
505
 
                break
506
 
            nlines += 1
507
 
            # keep track of the last line that had some content
508
 
            if stripped_line != "":
509
 
                lastline = nlines
510
 
            msg.append(line)
511
 
            
512
 
        if len(msg) == 0:
513
 
            return None
514
 
        # delete empty lines at the end
515
 
        del msg[lastline:]
516
 
        # add a newline at the end, if needed
517
 
        if not msg[-1].endswith("\n"):
518
 
            return "%s%s" % ("".join(msg), "\n")
519
 
        else:
520
 
            return "".join(msg)
521
 
    finally:
522
 
        # delete the msg file in any case
523
 
        try: os.unlink(msgfilename)
524
 
        except IOError: pass
 
297
            bailout('command failed')
 
298