~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/osutils.py

  • Committer: Martin Pool
  • Date: 2005-07-21 11:57:44 UTC
  • Revision ID: mbp@sourcefrog.net-20050721115744-e450602f7f11efa5
- fix up self reference in msvc lock object

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
import os, types, re, time, errno, sys
 
20
from stat import S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE
 
21
 
 
22
from bzrlib.errors import BzrError
 
23
from bzrlib.trace import mutter
 
24
import bzrlib
 
25
 
 
26
def make_readonly(filename):
 
27
    """Make a filename read-only."""
 
28
    # TODO: probably needs to be fixed for windows
 
29
    mod = os.stat(filename).st_mode
 
30
    mod = mod & 0777555
 
31
    os.chmod(filename, mod)
 
32
 
 
33
 
 
34
def make_writable(filename):
 
35
    mod = os.stat(filename).st_mode
 
36
    mod = mod | 0200
 
37
    os.chmod(filename, mod)
 
38
 
 
39
 
 
40
_QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/_~-])')
 
41
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
 
51
 
 
52
 
 
53
def file_kind(f):
 
54
    mode = os.lstat(f)[ST_MODE]
 
55
    if S_ISREG(mode):
 
56
        return 'file'
 
57
    elif S_ISDIR(mode):
 
58
        return 'directory'
 
59
    elif S_ISLNK(mode):
 
60
        return 'symlink'
 
61
    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
 
 
112
 
 
113
 
 
114
 
 
115
def isdir(f):
 
116
    """True if f is an accessible directory."""
 
117
    try:
 
118
        return S_ISDIR(os.lstat(f)[ST_MODE])
 
119
    except OSError:
 
120
        return False
 
121
 
 
122
 
 
123
 
 
124
def isfile(f):
 
125
    """True if f is a regular file."""
 
126
    try:
 
127
        return S_ISREG(os.lstat(f)[ST_MODE])
 
128
    except OSError:
 
129
        return False
 
130
 
 
131
 
 
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
def pumpfile(fromfile, tofile):
 
152
    """Copy contents of one file to another."""
 
153
    tofile.write(fromfile.read())
 
154
 
 
155
 
 
156
def uuid():
 
157
    """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())
 
162
 
 
163
 
 
164
def sha_file(f):
 
165
    import sha
 
166
    if hasattr(f, 'tell'):
 
167
        assert f.tell() == 0
 
168
    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)
 
175
    return s.hexdigest()
 
176
 
 
177
 
 
178
def sha_string(f):
 
179
    import sha
 
180
    s = sha.new()
 
181
    s.update(f)
 
182
    return s.hexdigest()
 
183
 
 
184
 
 
185
 
 
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
    """
 
217
    import socket
 
218
 
 
219
    # XXX: Any good way to get real user name on win32?
 
220
 
 
221
    try:
 
222
        import pwd
 
223
        uid = os.getuid()
 
224
        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
 
 
235
    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+.-]+')
 
286
def user_email():
 
287
    """Return just the email component of a username."""
 
288
    e = _get_user_id()
 
289
    if e:
 
290
        m = _EMAIL_RE.search(e)
 
291
        if not m:
 
292
            raise BzrError("%r doesn't seem to contain a reasonable email address" % e)
 
293
        return m.group(0)
 
294
 
 
295
    return _auto_user_id()[1]
 
296
    
 
297
 
 
298
 
 
299
def compare_files(a, b):
 
300
    """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:
 
319
        return -time.altzone
 
320
    else:
 
321
        return -time.timezone
 
322
 
 
323
    
 
324
def format_date(t, offset=0, timezone='original'):
 
325
    ## TODO: Perhaps a global option to use either universal or local time?
 
326
    ## Or perhaps just let people set $TZ?
 
327
    assert isinstance(t, float)
 
328
    
 
329
    if timezone == 'utc':
 
330
        tt = time.gmtime(t)
 
331
        offset = 0
 
332
    elif timezone == 'original':
 
333
        if offset == None:
 
334
            offset = 0
 
335
        tt = time.gmtime(t + offset)
 
336
    elif timezone == 'local':
 
337
        tt = time.localtime(t)
 
338
        offset = local_time_offset(t)
 
339
    else:
 
340
        raise BzrError("unsupported timezone format %r",
 
341
                ['options are "utc", "original", "local"'])
 
342
 
 
343
    return (time.strftime("%a %Y-%m-%d %H:%M:%S", tt)
 
344
            + ' %+03d%02d' % (offset / 3600, (offset / 60) % 60))
 
345
 
 
346
 
 
347
def compact_date(when):
 
348
    return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
 
349
    
 
350
 
 
351
 
 
352
def filesize(f):
 
353
    """Return size of given open file."""
 
354
    return os.fstat(f.fileno())[ST_SIZE]
 
355
 
 
356
 
 
357
if hasattr(os, 'urandom'): # python 2.4 and later
 
358
    rand_bytes = os.urandom
 
359
elif sys.platform == 'linux2':
 
360
    rand_bytes = file('/dev/urandom', 'rb').read
 
361
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
 
370
 
 
371
 
 
372
## TODO: We could later have path objects that remember their list
 
373
## decomposition (might be too tricksy though.)
 
374
 
 
375
def splitpath(p):
 
376
    """Turn string into list of parts.
 
377
 
 
378
    >>> splitpath('a')
 
379
    ['a']
 
380
    >>> splitpath('a/b')
 
381
    ['a', 'b']
 
382
    >>> splitpath('a/./b')
 
383
    ['a', 'b']
 
384
    >>> splitpath('a/.b')
 
385
    ['a', '.b']
 
386
    >>> splitpath('a/../b')
 
387
    Traceback (most recent call last):
 
388
    ...
 
389
    BzrError: sorry, '..' not allowed in path
 
390
    """
 
391
    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 = []
 
398
    for f in ps:
 
399
        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
 
406
 
 
407
def joinpath(p):
 
408
    assert isinstance(p, list)
 
409
    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)
 
413
 
 
414
 
 
415
def appendpath(p1, p2):
 
416
    if p1 == '':
 
417
        return p2
 
418
    else:
 
419
        return os.path.join(p1, p2)
 
420
    
 
421
 
 
422
def extern_command(cmd, ignore_errors = False):
 
423
    mutter('external command: %s' % `cmd`)
 
424
    if os.system(cmd):
 
425
        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