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)
30
from bzrlib.errors import BzrError
31
from bzrlib.trace import mutter
34
def make_readonly(filename):
35
"""Make a filename read-only."""
36
mod = os.stat(filename).st_mode
38
os.chmod(filename, mod)
41
def make_writable(filename):
42
mod = os.stat(filename).st_mode
44
os.chmod(filename, mod)
51
"""Return a quoted filename filename
53
This previously used backslash quoting, but that works poorly on
55
# TODO: I'm not really sure this is the best format either.x
58
_QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
60
if _QUOTE_RE.search(f):
67
mode = os.lstat(f)[ST_MODE]
86
def kind_marker(kind):
89
elif kind == 'directory':
91
elif kind == 'symlink':
94
raise BzrError('invalid file kind %r' % kind)
98
if hasattr(os, 'lstat'):
104
if e.errno == errno.ENOENT:
107
raise BzrError("lstat/stat of (%r): %r" % (f, e))
109
def normalizepath(f):
110
if hasattr(os.path, 'realpath'):
114
[p,e] = os.path.split(f)
115
if e == "" or e == "." or e == "..":
118
return os.path.join(F(p), e)
122
"""Copy a file to a backup.
124
Backups are named in GNU-style, with a ~ suffix.
126
If the file is already a backup, it's not copied.
138
outf = file(bfn, 'wb')
152
"""True if f is an accessible directory."""
154
return S_ISDIR(os.lstat(f)[ST_MODE])
160
"""True if f is a regular file."""
162
return S_ISREG(os.lstat(f)[ST_MODE])
167
"""True if f is a symlink."""
169
return S_ISLNK(os.lstat(f)[ST_MODE])
173
def is_inside(dir, fname):
174
"""True if fname is inside dir.
176
The parameters should typically be passed to os.path.normpath first, so
177
that . and .. and repeated slashes are eliminated, and the separators
178
are canonical for the platform.
180
The empty string as a dir name is taken as top-of-tree and matches
183
>>> is_inside('src', os.path.join('src', 'foo.c'))
185
>>> is_inside('src', 'srccontrol')
187
>>> is_inside('src', os.path.join('src', 'a', 'a', 'a', 'foo.c'))
189
>>> is_inside('foo.c', 'foo.c')
191
>>> is_inside('foo.c', '')
193
>>> is_inside('', 'foo.c')
196
# XXX: Most callers of this can actually do something smarter by
197
# looking at the inventory
204
if dir[-1] != os.sep:
207
return fname.startswith(dir)
210
def is_inside_any(dir_list, fname):
211
"""True if fname is inside any of given dirs."""
212
for dirname in dir_list:
213
if is_inside(dirname, fname):
219
def pumpfile(fromfile, tofile):
220
"""Copy contents of one file to another."""
221
tofile.write(fromfile.read())
225
if hasattr(f, 'tell'):
243
def fingerprint_file(f):
248
return {'size': size,
249
'sha1': s.hexdigest()}
253
"""Return per-user configuration directory.
255
By default this is ~/.bzr.conf/
257
TODO: Global option --config-dir to override this.
259
return os.path.join(os.path.expanduser("~"), ".bzr.conf")
263
"""Calculate automatic user identification.
265
Returns (realname, email).
267
Only used when none is set in the environment or the id file.
269
This previously used the FQDN as the default domain, but that can
270
be very slow on machines where DNS is broken. So now we simply
275
# XXX: Any good way to get real user name on win32?
280
w = pwd.getpwuid(uid)
281
gecos = w.pw_gecos.decode(bzrlib.user_encoding)
282
username = w.pw_name.decode(bzrlib.user_encoding)
283
comma = gecos.find(',')
287
realname = gecos[:comma]
293
realname = username = getpass.getuser().decode(bzrlib.user_encoding)
295
return realname, (username + '@' + socket.gethostname())
298
def _get_user_id(branch):
299
"""Return the full user id from a file or environment variable.
301
e.g. "John Hacker <jhacker@foo.org>"
304
A branch to use for a per-branch configuration, or None.
306
The following are searched in order:
309
2. .bzr/email for this branch.
313
v = os.environ.get('BZREMAIL')
315
return v.decode(bzrlib.user_encoding)
319
return (branch.controlfile("email", "r")
321
.decode(bzrlib.user_encoding)
324
if e.errno != errno.ENOENT:
330
return (open(os.path.join(config_dir(), "email"))
332
.decode(bzrlib.user_encoding)
335
if e.errno != errno.ENOENT:
338
v = os.environ.get('EMAIL')
340
return v.decode(bzrlib.user_encoding)
345
def username(branch):
346
"""Return email-style username.
348
Something similar to 'Martin Pool <mbp@sourcefrog.net>'
350
TODO: Check it's reasonably well-formed.
352
v = _get_user_id(branch)
356
name, email = _auto_user_id()
358
return '%s <%s>' % (name, email)
363
def user_email(branch):
364
"""Return just the email component of a username."""
365
e = _get_user_id(branch)
367
m = re.search(r'[\w+.-]+@[\w+.-]+', e)
369
raise BzrError("%r doesn't seem to contain "
370
"a reasonable email address" % e)
373
return _auto_user_id()[1]
376
def compare_files(a, b):
377
"""Returns true if equal in contents"""
388
def local_time_offset(t=None):
389
"""Return offset of local zone from GMT, either at present or at time t."""
390
# python2.3 localtime() can't take None
394
if time.localtime(t).tm_isdst and time.daylight:
397
return -time.timezone
400
def format_date(t, offset=0, timezone='original'):
401
## TODO: Perhaps a global option to use either universal or local time?
402
## Or perhaps just let people set $TZ?
403
assert isinstance(t, float)
405
if timezone == 'utc':
408
elif timezone == 'original':
411
tt = time.gmtime(t + offset)
412
elif timezone == 'local':
413
tt = time.localtime(t)
414
offset = local_time_offset(t)
416
raise BzrError("unsupported timezone format %r" % timezone,
417
['options are "utc", "original", "local"'])
419
return (time.strftime("%a %Y-%m-%d %H:%M:%S", tt)
420
+ ' %+03d%02d' % (offset / 3600, (offset / 60) % 60))
423
def compact_date(when):
424
return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
429
"""Return size of given open file."""
430
return os.fstat(f.fileno())[ST_SIZE]
432
# Define rand_bytes based on platform.
434
# Python 2.4 and later have os.urandom,
435
# but it doesn't work on some arches
437
rand_bytes = os.urandom
438
except (NotImplementedError, AttributeError):
439
# If python doesn't have os.urandom, or it doesn't work,
440
# then try to first pull random data from /dev/urandom
441
if os.path.exists("/dev/urandom"):
442
rand_bytes = file('/dev/urandom', 'rb').read
443
# Otherwise, use this hack as a last resort
445
# not well seeded, but better than nothing
450
s += chr(random.randint(0, 255))
454
## TODO: We could later have path objects that remember their list
455
## decomposition (might be too tricksy though.)
458
"""Turn string into list of parts.
464
>>> splitpath('a/./b')
466
>>> splitpath('a/.b')
468
>>> splitpath('a/../b')
469
Traceback (most recent call last):
471
BzrError: sorry, '..' not allowed in path
473
assert isinstance(p, types.StringTypes)
475
# split on either delimiter because people might use either on
477
ps = re.split(r'[\\/]', p)
482
raise BzrError("sorry, %r not allowed in path" % f)
483
elif (f == '.') or (f == ''):
490
assert isinstance(p, list)
492
if (f == '..') or (f == None) or (f == ''):
493
raise BzrError("sorry, %r not allowed in path" % f)
494
return os.path.join(*p)
497
def appendpath(p1, p2):
501
return os.path.join(p1, p2)
504
def extern_command(cmd, ignore_errors = False):
505
mutter('external command: %s' % `cmd`)
507
if not ignore_errors:
508
raise BzrError('command failed')
511
def _read_config_value(name):
512
"""Read a config value from the file ~/.bzr.conf/<name>
513
Return None if the file does not exist"""
515
f = file(os.path.join(config_dir(), name), "r")
516
return f.read().decode(bzrlib.user_encoding).rstrip("\r\n")
518
if e.errno == errno.ENOENT: