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
from stat import (S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE,
20
S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
21
from cStringIO import StringIO
31
from bzrlib.errors import BzrError
32
from bzrlib.trace import mutter
35
def make_readonly(filename):
36
"""Make a filename read-only."""
37
mod = os.stat(filename).st_mode
39
os.chmod(filename, mod)
42
def make_writable(filename):
43
mod = os.stat(filename).st_mode
45
os.chmod(filename, mod)
52
"""Return a quoted filename filename
54
This previously used backslash quoting, but that works poorly on
56
# TODO: I'm not really sure this is the best format either.x
59
_QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
61
if _QUOTE_RE.search(f):
68
mode = os.lstat(f)[ST_MODE]
87
def kind_marker(kind):
90
elif kind == 'directory':
92
elif kind == 'symlink':
95
raise BzrError('invalid file kind %r' % kind)
99
"""Copy a file to a backup.
101
Backups are named in GNU-style, with a ~ suffix.
103
If the file is already a backup, it's not copied.
115
outf = file(bfn, 'wb')
129
"""True if f is an accessible directory."""
131
return S_ISDIR(os.lstat(f)[ST_MODE])
137
"""True if f is a regular file."""
139
return S_ISREG(os.lstat(f)[ST_MODE])
144
def is_inside(dir, fname):
145
"""True if fname is inside dir.
147
The parameters should typically be passed to os.path.normpath first, so
148
that . and .. and repeated slashes are eliminated, and the separators
149
are canonical for the platform.
151
The empty string as a dir name is taken as top-of-tree and matches
154
>>> is_inside('src', os.path.join('src', 'foo.c'))
156
>>> is_inside('src', 'srccontrol')
158
>>> is_inside('src', os.path.join('src', 'a', 'a', 'a', 'foo.c'))
160
>>> is_inside('foo.c', 'foo.c')
162
>>> is_inside('foo.c', '')
164
>>> is_inside('', 'foo.c')
167
# XXX: Most callers of this can actually do something smarter by
168
# looking at the inventory
175
if dir[-1] != os.sep:
178
return fname.startswith(dir)
181
def is_inside_any(dir_list, fname):
182
"""True if fname is inside any of given dirs."""
183
for dirname in dir_list:
184
if is_inside(dirname, fname):
190
def pumpfile(fromfile, tofile):
191
"""Copy contents of one file to another."""
192
tofile.write(fromfile.read())
196
if hasattr(f, 'tell'):
209
def sha_strings(strings):
210
"""Return the sha-1 of concatenation of strings"""
212
map(s.update, strings)
222
def fingerprint_file(f):
227
return {'size': size,
228
'sha1': s.hexdigest()}
232
"""Return per-user configuration directory.
234
By default this is ~/.bzr.conf/
236
TODO: Global option --config-dir to override this.
238
return os.path.join(os.path.expanduser("~"), ".bzr.conf")
242
"""Calculate automatic user identification.
244
Returns (realname, email).
246
Only used when none is set in the environment or the id file.
248
This previously used the FQDN as the default domain, but that can
249
be very slow on machines where DNS is broken. So now we simply
254
# XXX: Any good way to get real user name on win32?
259
w = pwd.getpwuid(uid)
260
gecos = w.pw_gecos.decode(bzrlib.user_encoding)
261
username = w.pw_name.decode(bzrlib.user_encoding)
262
comma = gecos.find(',')
266
realname = gecos[:comma]
272
realname = username = getpass.getuser().decode(bzrlib.user_encoding)
274
return realname, (username + '@' + socket.gethostname())
277
def _get_user_id(branch):
278
"""Return the full user id from a file or environment variable.
280
e.g. "John Hacker <jhacker@foo.org>"
283
A branch to use for a per-branch configuration, or None.
285
The following are searched in order:
288
2. .bzr/email for this branch.
292
v = os.environ.get('BZREMAIL')
294
return v.decode(bzrlib.user_encoding)
298
return (branch.controlfile("email", "r")
300
.decode(bzrlib.user_encoding)
303
if e.errno != errno.ENOENT:
309
return (open(os.path.join(config_dir(), "email"))
311
.decode(bzrlib.user_encoding)
314
if e.errno != errno.ENOENT:
317
v = os.environ.get('EMAIL')
319
return v.decode(bzrlib.user_encoding)
324
def username(branch):
325
"""Return email-style username.
327
Something similar to 'Martin Pool <mbp@sourcefrog.net>'
329
TODO: Check it's reasonably well-formed.
331
v = _get_user_id(branch)
335
name, email = _auto_user_id()
337
return '%s <%s>' % (name, email)
342
def user_email(branch):
343
"""Return just the email component of a username."""
344
e = _get_user_id(branch)
346
m = re.search(r'[\w+.-]+@[\w+.-]+', e)
348
raise BzrError("%r doesn't seem to contain "
349
"a reasonable email address" % e)
352
return _auto_user_id()[1]
355
def compare_files(a, b):
356
"""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:
503
"""Split s into lines, but without removing the newline characters."""
504
return StringIO(s).readlines()