~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-11 23:23:53 UTC
  • Revision ID: mbp@sourcefrog.net-20050311232353-f5e33da490872c6a
Add .bzrignore file

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"""
158
 
    try:
159
 
        return file('/proc/sys/kernel/random/uuid').readline().rstrip('\n')
160
 
    except IOError:
161
 
        return chomp(os.popen('uuidgen').readline())
 
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.
 
89
    bailout('uuids not allowed!')
 
90
    return chomp(os.popen('uuidgen').readline())
 
91
 
 
92
def chomp(s):
 
93
    if s and (s[-1] == '\n'):
 
94
        return s[:-1]
 
95
    else:
 
96
        return s
162
97
 
163
98
 
164
99
def sha_file(f):
165
100
    import sha
 
101
    ## TODO: Maybe read in chunks to handle big files
166
102
    if hasattr(f, 'tell'):
167
103
        assert f.tell() == 0
168
104
    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)
 
105
    s.update(f.read())
175
106
    return s.hexdigest()
176
107
 
177
108
 
183
114
 
184
115
 
185
116
 
186
 
def fingerprint_file(f):
187
 
    import sha
188
 
    s = sha.new()
189
 
    b = f.read()
190
 
    s.update(b)
191
 
    size = len(b)
192
 
    return {'size': size,
193
 
            'sha1': s.hexdigest()}
194
 
 
195
 
 
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
 
    """
 
117
def username():
 
118
    """Return email-style username.
 
119
 
 
120
    Something similar to 'Martin Pool <mbp@sourcefrog.net>'
 
121
 
 
122
    :todo: Check it's reasonably well-formed.
 
123
 
 
124
    :todo: Allow taking it from a dotfile to help people on windows
 
125
           who can't easily set variables.
 
126
 
 
127
    :todo: Cope without pwd module, which is only on unix. 
 
128
    """
 
129
    e = os.environ.get('BZREMAIL') or os.environ.get('EMAIL')
 
130
    if e: return e
 
131
 
217
132
    import socket
218
 
 
219
 
    # XXX: Any good way to get real user name on win32?
220
 
 
 
133
    
221
134
    try:
222
135
        import pwd
223
136
        uid = os.getuid()
224
137
        w = pwd.getpwuid(uid)
225
 
        gecos = w.pw_gecos.decode(bzrlib.user_encoding)
226
 
        username = w.pw_name.decode(bzrlib.user_encoding)
227
 
        comma = gecos.find(',')
228
 
        if comma == -1:
229
 
            realname = gecos
230
 
        else:
231
 
            realname = gecos[:comma]
232
 
        if not realname:
233
 
            realname = username
234
 
 
 
138
        realname, junk = w.pw_gecos.split(',', 1)
 
139
        return '%s <%s@%s>' % (realname, w.pw_name, socket.getfqdn())
235
140
    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+.-]+')
 
141
        pass
 
142
 
 
143
    import getpass, socket
 
144
    return '<%s@%s>' % (getpass.getuser(), socket.getfqdn())
 
145
 
 
146
 
286
147
def user_email():
287
148
    """Return just the email component of a username."""
288
 
    e = _get_user_id()
 
149
    e = os.environ.get('BZREMAIL') or os.environ.get('EMAIL')
289
150
    if e:
290
 
        m = _EMAIL_RE.search(e)
 
151
        import re
 
152
        m = re.search(r'[\w+.-]+@[\w+.-]+', e)
291
153
        if not m:
292
 
            raise BzrError("%r doesn't seem to contain a reasonable email address" % e)
 
154
            bailout('%r is not a reasonable email address' % e)
293
155
        return m.group(0)
294
156
 
295
 
    return _auto_user_id()[1]
 
157
 
 
158
    import getpass, socket
 
159
    return '%s@%s' % (getpass.getuser(), socket.getfqdn())
 
160
 
296
161
    
297
162
 
298
163
 
299
164
def compare_files(a, b):
300
165
    """Returns true if equal in contents"""
301
 
    BUFSIZE = 4096
302
 
    while True:
303
 
        ai = a.read(BUFSIZE)
304
 
        bi = b.read(BUFSIZE)
305
 
        if ai != bi:
306
 
            return False
307
 
        if ai == '':
308
 
            return True
309
 
 
310
 
 
311
 
 
312
 
def local_time_offset(t=None):
313
 
    """Return offset of local zone from GMT, either at present or at time t."""
314
 
    # python2.3 localtime() can't take None
315
 
    if t == None:
316
 
        t = time.time()
317
 
        
318
 
    if time.localtime(t).tm_isdst and time.daylight:
 
166
    # TODO: don't read the whole thing in one go.
 
167
    result = a.read() == b.read()
 
168
    return result
 
169
 
 
170
 
 
171
 
 
172
def local_time_offset():
 
173
    if time.daylight:
319
174
        return -time.altzone
320
175
    else:
321
176
        return -time.timezone
324
179
def format_date(t, offset=0, timezone='original'):
325
180
    ## TODO: Perhaps a global option to use either universal or local time?
326
181
    ## Or perhaps just let people set $TZ?
 
182
    import time
 
183
    
327
184
    assert isinstance(t, float)
328
185
    
329
186
    if timezone == 'utc':
335
192
        tt = time.gmtime(t + offset)
336
193
    elif timezone == 'local':
337
194
        tt = time.localtime(t)
338
 
        offset = local_time_offset(t)
 
195
        offset = local_time_offset()
339
196
    else:
340
 
        raise BzrError("unsupported timezone format %r",
 
197
        bailout("unsupported timezone format %r",
341
198
                ['options are "utc", "original", "local"'])
342
199
 
343
200
    return (time.strftime("%a %Y-%m-%d %H:%M:%S", tt)
356
213
 
357
214
if hasattr(os, 'urandom'): # python 2.4 and later
358
215
    rand_bytes = os.urandom
359
 
elif sys.platform == 'linux2':
360
 
    rand_bytes = file('/dev/urandom', 'rb').read
361
216
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
 
217
    # FIXME: No good on non-Linux
 
218
    _rand_file = file('/dev/urandom', 'rb')
 
219
    rand_bytes = _rand_file.read
370
220
 
371
221
 
372
222
## TODO: We could later have path objects that remember their list
386
236
    >>> splitpath('a/../b')
387
237
    Traceback (most recent call last):
388
238
    ...
389
 
    BzrError: sorry, '..' not allowed in path
 
239
    BzrError: ("sorry, '..' not allowed in path", [])
390
240
    """
391
241
    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 = []
 
242
    ps = [f for f in p.split('/') if f != '.']
398
243
    for f in ps:
399
244
        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
 
245
            bailout("sorry, %r not allowed in path" % f)
 
246
    return ps
406
247
 
407
248
def joinpath(p):
408
249
    assert isinstance(p, list)
409
250
    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)
 
251
        if (f == '..') or (f is None) or (f == ''):
 
252
            bailout("sorry, %r not allowed in path" % f)
 
253
    return '/'.join(p)
413
254
 
414
255
 
415
256
def appendpath(p1, p2):
416
257
    if p1 == '':
417
258
        return p2
418
259
    else:
419
 
        return os.path.join(p1, p2)
 
260
        return p1 + '/' + p2
420
261
    
421
262
 
422
263
def extern_command(cmd, ignore_errors = False):
423
264
    mutter('external command: %s' % `cmd`)
424
265
    if os.system(cmd):
425
266
        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
 
267
            bailout('command failed')
 
268