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
20
from stat import (S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE,
21
S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
23
from bzrlib.errors import BzrError
24
from bzrlib.trace import mutter
27
def make_readonly(filename):
28
"""Make a filename read-only."""
29
# TODO: probably needs to be fixed for windows
30
mod = os.stat(filename).st_mode
32
os.chmod(filename, mod)
35
def make_writable(filename):
36
mod = os.stat(filename).st_mode
38
os.chmod(filename, mod)
45
"""Return a quoted filename filename
47
This previously used backslash quoting, but that works poorly on
49
# TODO: I'm not really sure this is the best format either.x
52
_QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/_~-])')
54
if _QUOTE_RE.search(f):
61
mode = os.lstat(f)[ST_MODE]
80
def kind_marker(kind):
83
elif kind == 'directory':
85
elif kind == 'symlink':
88
raise BzrError('invalid file kind %r' % kind)
93
"""Copy a file to a backup.
95
Backups are named in GNU-style, with a ~ suffix.
97
If the file is already a backup, it's not copied.
110
outf = file(bfn, 'wb')
124
"""True if f is an accessible directory."""
126
return S_ISDIR(os.lstat(f)[ST_MODE])
132
"""True if f is a regular file."""
134
return S_ISREG(os.lstat(f)[ST_MODE])
139
def is_inside(dir, fname):
140
"""True if fname is inside dir.
142
The parameters should typically be passed to os.path.normpath first, so
143
that . and .. and repeated slashes are eliminated, and the separators
144
are canonical for the platform.
146
The empty string as a dir name is taken as top-of-tree and matches
149
>>> is_inside('src', os.path.join('src', 'foo.c'))
151
>>> is_inside('src', 'srccontrol')
153
>>> is_inside('src', os.path.join('src', 'a', 'a', 'a', 'foo.c'))
155
>>> is_inside('foo.c', 'foo.c')
157
>>> is_inside('foo.c', '')
159
>>> is_inside('', 'foo.c')
162
# XXX: Most callers of this can actually do something smarter by
163
# looking at the inventory
170
if dir[-1] != os.sep:
173
return fname.startswith(dir)
176
def is_inside_any(dir_list, fname):
177
"""True if fname is inside any of given dirs."""
178
for dirname in dir_list:
179
if is_inside(dirname, fname):
185
def pumpfile(fromfile, tofile):
186
"""Copy contents of one file to another."""
187
tofile.write(fromfile.read())
191
"""Return a new UUID"""
193
return file('/proc/sys/kernel/random/uuid').readline().rstrip('\n')
195
return chomp(os.popen('uuidgen').readline())
200
if hasattr(f, 'tell'):
220
def fingerprint_file(f):
226
return {'size': size,
227
'sha1': s.hexdigest()}
231
"""Return per-user configuration directory.
233
By default this is ~/.bzr.conf/
235
TODO: Global option --config-dir to override this.
237
return os.path.expanduser("~/.bzr.conf")
241
"""Calculate automatic user identification.
243
Returns (realname, email).
245
Only used when none is set in the environment or the id file.
247
This previously used the FQDN as the default domain, but that can
248
be very slow on machines where DNS is broken. So now we simply
253
# XXX: Any good way to get real user name on win32?
258
w = pwd.getpwuid(uid)
259
gecos = w.pw_gecos.decode(bzrlib.user_encoding)
260
username = w.pw_name.decode(bzrlib.user_encoding)
261
comma = gecos.find(',')
265
realname = gecos[:comma]
271
realname = username = getpass.getuser().decode(bzrlib.user_encoding)
273
return realname, (username + '@' + socket.gethostname())
276
def _get_user_id(branch):
277
"""Return the full user id from a file or environment variable.
279
e.g. "John Hacker <jhacker@foo.org>"
282
A branch to use for a per-branch configuration, or None.
284
The following are searched in order:
287
2. .bzr/email for this branch.
291
v = os.environ.get('BZREMAIL')
293
return v.decode(bzrlib.user_encoding)
297
return (branch.controlfile("email", "r")
299
.decode(bzrlib.user_encoding)
302
if e.errno != errno.ENOENT:
308
return (open(os.path.join(config_dir(), "email"))
310
.decode(bzrlib.user_encoding)
313
if e.errno != errno.ENOENT:
316
v = os.environ.get('EMAIL')
318
return v.decode(bzrlib.user_encoding)
323
def username(branch):
324
"""Return email-style username.
326
Something similar to 'Martin Pool <mbp@sourcefrog.net>'
328
TODO: Check it's reasonably well-formed.
330
v = _get_user_id(branch)
334
name, email = _auto_user_id()
336
return '%s <%s>' % (name, email)
341
def user_email(branch):
342
"""Return just the email component of a username."""
343
e = _get_user_id(branch)
345
m = re.search(r'[\w+.-]+@[\w+.-]+', e)
347
raise BzrError("%r doesn't seem to contain a reasonable email address" % e)
350
return _auto_user_id()[1]
354
def compare_files(a, b):
355
"""Returns true if equal in contents"""
367
def local_time_offset(t=None):
368
"""Return offset of local zone from GMT, either at present or at time t."""
369
# python2.3 localtime() can't take None
373
if time.localtime(t).tm_isdst and time.daylight:
376
return -time.timezone
379
def format_date(t, offset=0, timezone='original'):
380
## TODO: Perhaps a global option to use either universal or local time?
381
## Or perhaps just let people set $TZ?
382
assert isinstance(t, float)
384
if timezone == 'utc':
387
elif timezone == 'original':
390
tt = time.gmtime(t + offset)
391
elif timezone == 'local':
392
tt = time.localtime(t)
393
offset = local_time_offset(t)
395
raise BzrError("unsupported timezone format %r" % timezone,
396
['options are "utc", "original", "local"'])
398
return (time.strftime("%a %Y-%m-%d %H:%M:%S", tt)
399
+ ' %+03d%02d' % (offset / 3600, (offset / 60) % 60))
402
def compact_date(when):
403
return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
408
"""Return size of given open file."""
409
return os.fstat(f.fileno())[ST_SIZE]
411
# Define rand_bytes based on platform.
413
# Python 2.4 and later have os.urandom,
414
# but it doesn't work on some arches
416
rand_bytes = os.urandom
417
except (NotImplementedError, AttributeError):
418
# If python doesn't have os.urandom, or it doesn't work,
419
# then try to first pull random data from /dev/urandom
420
if os.path.exists("/dev/urandom"):
421
rand_bytes = file('/dev/urandom', 'rb').read
422
# Otherwise, use this hack as a last resort
424
# not well seeded, but better than nothing
429
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: