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 cStringIO import StringIO
22
from stat import S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE
24
from bzrlib.errors import BzrError
25
from bzrlib.trace import mutter
28
def make_readonly(filename):
29
"""Make a filename read-only."""
30
# TODO: probably needs to be fixed for windows
31
mod = os.stat(filename).st_mode
33
os.chmod(filename, mod)
36
def make_writable(filename):
37
mod = os.stat(filename).st_mode
39
os.chmod(filename, mod)
46
"""Return a quoted filename filename
48
This previously used backslash quoting, but that works poorly on
50
# TODO: I'm not really sure this is the best format either.x
53
_QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/_~-])')
55
if _QUOTE_RE.search(f):
62
mode = os.lstat(f)[ST_MODE]
70
raise BzrError("can't handle file kind with mode %o of %r" % (mode, f))
73
def kind_marker(kind):
76
elif kind == 'directory':
78
elif kind == 'symlink':
81
raise BzrError('invalid file kind %r' % kind)
86
"""Copy a file to a backup.
88
Backups are named in GNU-style, with a ~ suffix.
90
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())
201
if hasattr(f, 'tell'):
221
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.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 a reasonable email address" % e)
351
return _auto_user_id()[1]
355
def compare_files(a, b):
356
"""Returns true if equal in contents"""
368
def local_time_offset(t=None):
369
"""Return offset of local zone from GMT, either at present or at time t."""
370
# python2.3 localtime() can't take None
374
if time.localtime(t).tm_isdst and time.daylight:
377
return -time.timezone
380
def format_date(t, offset=0, timezone='original'):
381
## TODO: Perhaps a global option to use either universal or local time?
382
## Or perhaps just let people set $TZ?
383
assert isinstance(t, float)
385
if timezone == 'utc':
388
elif timezone == 'original':
391
tt = time.gmtime(t + offset)
392
elif timezone == 'local':
393
tt = time.localtime(t)
394
offset = local_time_offset(t)
396
raise BzrError("unsupported timezone format %r" % timezone,
397
['options are "utc", "original", "local"'])
399
return (time.strftime("%a %Y-%m-%d %H:%M:%S", tt)
400
+ ' %+03d%02d' % (offset / 3600, (offset / 60) % 60))
403
def compact_date(when):
404
return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
409
"""Return size of given open file."""
410
return os.fstat(f.fileno())[ST_SIZE]
413
if hasattr(os, 'urandom'): # python 2.4 and later
414
rand_bytes = os.urandom
415
elif sys.platform == 'linux2':
416
rand_bytes = file('/dev/urandom', 'rb').read
418
# not well seeded, but better than nothing
423
s += chr(random.randint(0, 255))
428
## TODO: We could later have path objects that remember their list
429
## decomposition (might be too tricksy though.)
432
"""Turn string into list of parts.
438
>>> splitpath('a/./b')
440
>>> splitpath('a/.b')
442
>>> splitpath('a/../b')
443
Traceback (most recent call last):
445
BzrError: sorry, '..' not allowed in path
447
assert isinstance(p, types.StringTypes)
449
# split on either delimiter because people might use either on
451
ps = re.split(r'[\\/]', p)
456
raise BzrError("sorry, %r not allowed in path" % f)
457
elif (f == '.') or (f == ''):
464
assert isinstance(p, list)
466
if (f == '..') or (f == None) or (f == ''):
467
raise BzrError("sorry, %r not allowed in path" % f)
468
return os.path.join(*p)
471
def appendpath(p1, p2):
475
return os.path.join(p1, p2)
478
def extern_command(cmd, ignore_errors = False):
479
mutter('external command: %s' % `cmd`)
481
if not ignore_errors:
482
raise BzrError('command failed')
485
def _read_config_value(name):
486
"""Read a config value from the file ~/.bzr.conf/<name>
487
Return None if the file does not exist"""
489
f = file(os.path.join(config_dir(), name), "r")
490
return f.read().decode(bzrlib.user_encoding).rstrip("\r\n")
492
if e.errno == errno.ENOENT:
499
"""Split s into lines, but without removing the newline characters."""
500
return StringIO(s).readlines()