1
# Bazaar-NG -- distributed version control
 
 
3
# Copyright (C) 2005 by Canonical Ltd
 
 
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.
 
 
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.
 
 
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
 
 
19
import os, types, re, time, errno, sys
 
 
21
from cStringIO import StringIO
 
 
23
from stat import S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE
 
 
25
from bzrlib.errors import BzrError
 
 
26
from bzrlib.trace import mutter
 
 
29
def make_readonly(filename):
 
 
30
    """Make a filename read-only."""
 
 
31
    # TODO: probably needs to be fixed for windows
 
 
32
    mod = os.stat(filename).st_mode
 
 
34
    os.chmod(filename, mod)
 
 
37
def make_writable(filename):
 
 
38
    mod = os.stat(filename).st_mode
 
 
40
    os.chmod(filename, mod)
 
 
47
    """Return a quoted filename filename
 
 
49
    This previously used backslash quoting, but that works poorly on
 
 
51
    # TODO: I'm not really sure this is the best format either.x
 
 
54
        _QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/_~-])')
 
 
56
    if _QUOTE_RE.search(f):
 
 
63
    mode = os.lstat(f)[ST_MODE]
 
 
71
        raise BzrError("can't handle file kind with mode %o of %r" % (mode, f))
 
 
74
def kind_marker(kind):
 
 
77
    elif kind == 'directory':
 
 
79
    elif kind == 'symlink':
 
 
82
        raise BzrError('invalid file kind %r' % kind)
 
 
87
    """Copy a file to a backup.
 
 
89
    Backups are named in GNU-style, with a ~ suffix.
 
 
91
    If the file is already a backup, it's not copied.
 
 
103
    outf = file(bfn, 'wb')
 
 
109
def rename(path_from, path_to):
 
 
110
    """Basically the same as os.rename() just special for win32"""
 
 
111
    if sys.platform == 'win32':
 
 
115
            if e.errno != e.ENOENT:
 
 
117
    os.rename(path_from, path_to)
 
 
124
    """True if f is an accessible directory."""
 
 
126
        return S_ISDIR(os.lstat(f)[ST_MODE])
 
 
133
    """True if f is a regular file."""
 
 
135
        return S_ISREG(os.lstat(f)[ST_MODE])
 
 
140
def is_inside(dir, fname):
 
 
141
    """True if fname is inside dir.
 
 
143
    The parameters should typically be passed to os.path.normpath first, so
 
 
144
    that . and .. and repeated slashes are eliminated, and the separators
 
 
145
    are canonical for the platform.
 
 
147
    The empty string as a dir name is taken as top-of-tree and matches 
 
 
150
    >>> is_inside('src', 'src/foo.c')
 
 
152
    >>> is_inside('src', 'srccontrol')
 
 
154
    >>> is_inside('src', 'src/a/a/a/foo.c')
 
 
156
    >>> is_inside('foo.c', 'foo.c')
 
 
158
    >>> is_inside('foo.c', '')
 
 
160
    >>> is_inside('', 'foo.c')
 
 
163
    # XXX: Most callers of this can actually do something smarter by 
 
 
164
    # looking at the inventory
 
 
171
    if dir[-1] != os.sep:
 
 
174
    return fname.startswith(dir)
 
 
177
def is_inside_any(dir_list, fname):
 
 
178
    """True if fname is inside any of given dirs."""
 
 
179
    for dirname in dir_list:
 
 
180
        if is_inside(dirname, fname):
 
 
186
def pumpfile(fromfile, tofile):
 
 
187
    """Copy contents of one file to another."""
 
 
188
    tofile.write(fromfile.read())
 
 
192
    """Return a new UUID"""
 
 
194
        return file('/proc/sys/kernel/random/uuid').readline().rstrip('\n')
 
 
196
        return chomp(os.popen('uuidgen').readline())
 
 
200
    if hasattr(f, 'tell'):
 
 
213
def sha_strings(strings):
 
 
214
    """Return the sha-1 of concatenation of strings"""
 
 
216
    map(s.update, strings)
 
 
227
def fingerprint_file(f):
 
 
232
    return {'size': size,
 
 
233
            'sha1': s.hexdigest()}
 
 
237
    """Return per-user configuration directory.
 
 
239
    By default this is ~/.bzr.conf/
 
 
241
    TODO: Global option --config-dir to override this.
 
 
243
    return os.path.expanduser("~/.bzr.conf")
 
 
247
    """Calculate automatic user identification.
 
 
249
    Returns (realname, email).
 
 
251
    Only used when none is set in the environment or the id file.
 
 
253
    This previously used the FQDN as the default domain, but that can
 
 
254
    be very slow on machines where DNS is broken.  So now we simply
 
 
259
    # XXX: Any good way to get real user name on win32?
 
 
264
        w = pwd.getpwuid(uid)
 
 
265
        gecos = w.pw_gecos.decode(bzrlib.user_encoding)
 
 
266
        username = w.pw_name.decode(bzrlib.user_encoding)
 
 
267
        comma = gecos.find(',')
 
 
271
            realname = gecos[:comma]
 
 
277
        realname = username = getpass.getuser().decode(bzrlib.user_encoding)
 
 
279
    return realname, (username + '@' + socket.gethostname())
 
 
282
def _get_user_id(branch):
 
 
283
    """Return the full user id from a file or environment variable.
 
 
285
    e.g. "John Hacker <jhacker@foo.org>"
 
 
288
        A branch to use for a per-branch configuration, or None.
 
 
290
    The following are searched in order:
 
 
293
    2. .bzr/email for this branch.
 
 
297
    v = os.environ.get('BZREMAIL')
 
 
299
        return v.decode(bzrlib.user_encoding)
 
 
303
            return (branch.controlfile("email", "r") 
 
 
305
                    .decode(bzrlib.user_encoding)
 
 
308
            if e.errno != errno.ENOENT:
 
 
314
        return (open(os.path.join(config_dir(), "email"))
 
 
316
                .decode(bzrlib.user_encoding)
 
 
319
        if e.errno != errno.ENOENT:
 
 
322
    v = os.environ.get('EMAIL')
 
 
324
        return v.decode(bzrlib.user_encoding)
 
 
329
def username(branch):
 
 
330
    """Return email-style username.
 
 
332
    Something similar to 'Martin Pool <mbp@sourcefrog.net>'
 
 
334
    TODO: Check it's reasonably well-formed.
 
 
336
    v = _get_user_id(branch)
 
 
340
    name, email = _auto_user_id()
 
 
342
        return '%s <%s>' % (name, email)
 
 
347
def user_email(branch):
 
 
348
    """Return just the email component of a username."""
 
 
349
    e = _get_user_id(branch)
 
 
351
        m = re.search(r'[\w+.-]+@[\w+.-]+', e)
 
 
353
            raise BzrError("%r doesn't seem to contain a reasonable email address" % e)
 
 
356
    return _auto_user_id()[1]
 
 
360
def compare_files(a, b):
 
 
361
    """Returns true if equal in contents"""
 
 
373
def local_time_offset(t=None):
 
 
374
    """Return offset of local zone from GMT, either at present or at time t."""
 
 
375
    # python2.3 localtime() can't take None
 
 
379
    if time.localtime(t).tm_isdst and time.daylight:
 
 
382
        return -time.timezone
 
 
385
def format_date(t, offset=0, timezone='original'):
 
 
386
    ## TODO: Perhaps a global option to use either universal or local time?
 
 
387
    ## Or perhaps just let people set $TZ?
 
 
388
    assert isinstance(t, float)
 
 
390
    if timezone == 'utc':
 
 
393
    elif timezone == 'original':
 
 
396
        tt = time.gmtime(t + offset)
 
 
397
    elif timezone == 'local':
 
 
398
        tt = time.localtime(t)
 
 
399
        offset = local_time_offset(t)
 
 
401
        raise BzrError("unsupported timezone format %r" % timezone,
 
 
402
                       ['options are "utc", "original", "local"'])
 
 
404
    return (time.strftime("%a %Y-%m-%d %H:%M:%S", tt)
 
 
405
            + ' %+03d%02d' % (offset / 3600, (offset / 60) % 60))
 
 
408
def compact_date(when):
 
 
409
    return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
 
 
414
    """Return size of given open file."""
 
 
415
    return os.fstat(f.fileno())[ST_SIZE]
 
 
418
if hasattr(os, 'urandom'): # python 2.4 and later
 
 
419
    rand_bytes = os.urandom
 
 
420
elif sys.platform == 'linux2':
 
 
421
    rand_bytes = file('/dev/urandom', 'rb').read
 
 
423
    # not well seeded, but better than nothing
 
 
428
            s += chr(random.randint(0, 255))
 
 
433
## TODO: We could later have path objects that remember their list
 
 
434
## decomposition (might be too tricksy though.)
 
 
437
    """Turn string into list of parts.
 
 
443
    >>> splitpath('a/./b')
 
 
445
    >>> splitpath('a/.b')
 
 
447
    >>> splitpath('a/../b')
 
 
448
    Traceback (most recent call last):
 
 
450
    BzrError: sorry, '..' not allowed in path
 
 
452
    assert isinstance(p, types.StringTypes)
 
 
454
    # split on either delimiter because people might use either on
 
 
456
    ps = re.split(r'[\\/]', p)
 
 
461
            raise BzrError("sorry, %r not allowed in path" % f)
 
 
462
        elif (f == '.') or (f == ''):
 
 
469
    assert isinstance(p, list)
 
 
471
        if (f == '..') or (f == None) or (f == ''):
 
 
472
            raise BzrError("sorry, %r not allowed in path" % f)
 
 
473
    return os.path.join(*p)
 
 
476
def appendpath(p1, p2):
 
 
480
        return os.path.join(p1, p2)
 
 
483
def extern_command(cmd, ignore_errors = False):
 
 
484
    mutter('external command: %s' % `cmd`)
 
 
486
        if not ignore_errors:
 
 
487
            raise BzrError('command failed')
 
 
490
def _read_config_value(name):
 
 
491
    """Read a config value from the file ~/.bzr.conf/<name>
 
 
492
    Return None if the file does not exist"""
 
 
494
        f = file(os.path.join(config_dir(), name), "r")
 
 
495
        return f.read().decode(bzrlib.user_encoding).rstrip("\r\n")
 
 
497
        if e.errno == errno.ENOENT:
 
 
504
    """Split s into lines, but without removing the newline characters."""
 
 
505
    return StringIO(s).readlines()