~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: mbp at sourcefrog
  • Date: 2005-04-09 06:21:44 UTC
  • Revision ID: mbp@sourcefrog.net-20050409062144-e47a4b64106e4c21af99beaf
debugĀ output

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
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, BzrError
 
23
from trace import mutter
25
24
 
26
25
def make_readonly(filename):
27
26
    """Make a filename read-only."""
39
38
 
40
39
_QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/_~-])')
41
40
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
 
41
    """Return shell-quoted filename"""
 
42
    ## We could be a bit more terse by using double-quotes etc
 
43
    f = _QUOTE_RE.sub(r'\\\1', f)
 
44
    if f[0] == '~':
 
45
        f[0:1] = r'\~' 
 
46
    return f
51
47
 
52
48
 
53
49
def file_kind(f):
59
55
    elif S_ISLNK(mode):
60
56
        return 'symlink'
61
57
    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
 
 
 
58
        raise BzrError("can't handle file kind with mode %o of %r" % (mode, f)) 
112
59
 
113
60
 
114
61
 
129
76
        return False
130
77
 
131
78
 
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
79
def pumpfile(fromfile, tofile):
152
80
    """Copy contents of one file to another."""
153
81
    tofile.write(fromfile.read())
155
83
 
156
84
def uuid():
157
85
    """Return a new UUID"""
 
86
    
 
87
    ## XXX: Could alternatively read /proc/sys/kernel/random/uuid on
 
88
    ## Linux, but we need something portable for other systems;
 
89
    ## preferably an implementation in Python.
158
90
    try:
159
 
        return file('/proc/sys/kernel/random/uuid').readline().rstrip('\n')
 
91
        return chomp(file('/proc/sys/kernel/random/uuid').readline())
160
92
    except IOError:
161
93
        return chomp(os.popen('uuidgen').readline())
162
94
 
163
95
 
 
96
def chomp(s):
 
97
    if s and (s[-1] == '\n'):
 
98
        return s[:-1]
 
99
    else:
 
100
        return s
 
101
 
 
102
 
164
103
def sha_file(f):
165
104
    import sha
 
105
    ## TODO: Maybe read in chunks to handle big files
166
106
    if hasattr(f, 'tell'):
167
107
        assert f.tell() == 0
168
108
    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)
 
109
    s.update(f.read())
175
110
    return s.hexdigest()
176
111
 
177
112
 
193
128
            'sha1': s.hexdigest()}
194
129
 
195
130
 
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
 
    """
 
131
 
 
132
def username():
 
133
    """Return email-style username.
 
134
 
 
135
    Something similar to 'Martin Pool <mbp@sourcefrog.net>'
 
136
 
 
137
    :todo: Check it's reasonably well-formed.
 
138
 
 
139
    :todo: Allow taking it from a dotfile to help people on windows
 
140
           who can't easily set variables.
 
141
 
 
142
    :todo: Cope without pwd module, which is only on unix. 
 
143
    """
 
144
    e = os.environ.get('BZREMAIL') or os.environ.get('EMAIL')
 
145
    if e: return e
 
146
 
217
147
    import socket
218
 
 
219
 
    # XXX: Any good way to get real user name on win32?
220
 
 
 
148
    
221
149
    try:
222
150
        import pwd
223
151
        uid = os.getuid()
224
152
        w = pwd.getpwuid(uid)
225
 
        gecos = w.pw_gecos.decode(bzrlib.user_encoding)
226
 
        username = w.pw_name.decode(bzrlib.user_encoding)
 
153
        gecos = w.pw_gecos
227
154
        comma = gecos.find(',')
228
155
        if comma == -1:
229
156
            realname = gecos
230
157
        else:
231
158
            realname = gecos[:comma]
232
 
        if not realname:
233
 
            realname = username
234
 
 
 
159
        return '%s <%s@%s>' % (realname, w.pw_name, socket.getfqdn())
235
160
    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
 
161
        pass
 
162
 
 
163
    import getpass, socket
 
164
    return '<%s@%s>' % (getpass.getuser(), socket.getfqdn())
283
165
 
284
166
 
285
167
_EMAIL_RE = re.compile(r'[\w+.-]+@[\w+.-]+')
286
168
def user_email():
287
169
    """Return just the email component of a username."""
288
 
    e = _get_user_id()
 
170
    e = os.environ.get('BZREMAIL') or os.environ.get('EMAIL')
289
171
    if e:
290
172
        m = _EMAIL_RE.search(e)
291
173
        if not m:
292
 
            raise BzrError("%r doesn't seem to contain a reasonable email address" % e)
 
174
            bailout('%r is not a reasonable email address' % e)
293
175
        return m.group(0)
294
176
 
295
 
    return _auto_user_id()[1]
 
177
 
 
178
    import getpass, socket
 
179
    return '%s@%s' % (getpass.getuser(), socket.getfqdn())
 
180
 
296
181
    
297
182
 
298
183
 
299
184
def compare_files(a, b):
300
185
    """Returns true if equal in contents"""
 
186
    # TODO: don't read the whole thing in one go.
301
187
    BUFSIZE = 4096
302
188
    while True:
303
189
        ai = a.read(BUFSIZE)
337
223
        tt = time.localtime(t)
338
224
        offset = local_time_offset(t)
339
225
    else:
340
 
        raise BzrError("unsupported timezone format %r",
 
226
        bailout("unsupported timezone format %r",
341
227
                ['options are "utc", "original", "local"'])
342
228
 
343
229
    return (time.strftime("%a %Y-%m-%d %H:%M:%S", tt)
356
242
 
357
243
if hasattr(os, 'urandom'): # python 2.4 and later
358
244
    rand_bytes = os.urandom
359
 
elif sys.platform == 'linux2':
360
 
    rand_bytes = file('/dev/urandom', 'rb').read
361
245
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
 
246
    # FIXME: No good on non-Linux
 
247
    _rand_file = file('/dev/urandom', 'rb')
 
248
    rand_bytes = _rand_file.read
370
249
 
371
250
 
372
251
## TODO: We could later have path objects that remember their list
386
265
    >>> splitpath('a/../b')
387
266
    Traceback (most recent call last):
388
267
    ...
389
 
    BzrError: sorry, '..' not allowed in path
 
268
    BzrError: ("sorry, '..' not allowed in path", [])
390
269
    """
391
270
    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 = []
 
271
    ps = [f for f in p.split('/') if (f != '.' and f != '')]
398
272
    for f in ps:
399
273
        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
 
274
            bailout("sorry, %r not allowed in path" % f)
 
275
    return ps
406
276
 
407
277
def joinpath(p):
408
278
    assert isinstance(p, list)
409
279
    for f in p:
410
280
        if (f == '..') or (f == None) or (f == ''):
411
 
            raise BzrError("sorry, %r not allowed in path" % f)
412
 
    return os.path.join(*p)
 
281
            bailout("sorry, %r not allowed in path" % f)
 
282
    return '/'.join(p)
413
283
 
414
284
 
415
285
def appendpath(p1, p2):
416
286
    if p1 == '':
417
287
        return p2
418
288
    else:
419
 
        return os.path.join(p1, p2)
 
289
        return p1 + '/' + p2
420
290
    
421
291
 
422
292
def extern_command(cmd, ignore_errors = False):
423
293
    mutter('external command: %s' % `cmd`)
424
294
    if os.system(cmd):
425
295
        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
 
296
            bailout('command failed')
 
297