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'):
214
def sha_strings(strings):
215
"""Return the sha-1 of concatenation of strings"""
217
map(s.update, strings)
229
def fingerprint_file(f):
235
return {'size': size,
236
'sha1': s.hexdigest()}
240
"""Return per-user configuration directory.
242
By default this is ~/.bzr.conf/
244
TODO: Global option --config-dir to override this.
246
return os.path.expanduser("~/.bzr.conf")
250
"""Calculate automatic user identification.
252
Returns (realname, email).
254
Only used when none is set in the environment or the id file.
256
This previously used the FQDN as the default domain, but that can
257
be very slow on machines where DNS is broken. So now we simply
262
# XXX: Any good way to get real user name on win32?
267
w = pwd.getpwuid(uid)
268
gecos = w.pw_gecos.decode(bzrlib.user_encoding)
269
username = w.pw_name.decode(bzrlib.user_encoding)
270
comma = gecos.find(',')
274
realname = gecos[:comma]
280
realname = username = getpass.getuser().decode(bzrlib.user_encoding)
282
return realname, (username + '@' + socket.gethostname())
285
def _get_user_id(branch):
286
"""Return the full user id from a file or environment variable.
288
e.g. "John Hacker <jhacker@foo.org>"
291
A branch to use for a per-branch configuration, or None.
293
The following are searched in order:
296
2. .bzr/email for this branch.
300
v = os.environ.get('BZREMAIL')
302
return v.decode(bzrlib.user_encoding)
306
return (branch.controlfile("email", "r")
308
.decode(bzrlib.user_encoding)
311
if e.errno != errno.ENOENT:
317
return (open(os.path.join(config_dir(), "email"))
319
.decode(bzrlib.user_encoding)
322
if e.errno != errno.ENOENT:
325
v = os.environ.get('EMAIL')
327
return v.decode(bzrlib.user_encoding)
332
def username(branch):
333
"""Return email-style username.
335
Something similar to 'Martin Pool <mbp@sourcefrog.net>'
337
TODO: Check it's reasonably well-formed.
339
v = _get_user_id(branch)
343
name, email = _auto_user_id()
345
return '%s <%s>' % (name, email)
350
def user_email(branch):
351
"""Return just the email component of a username."""
352
e = _get_user_id(branch)
354
m = re.search(r'[\w+.-]+@[\w+.-]+', e)
356
raise BzrError("%r doesn't seem to contain a reasonable email address" % e)
359
return _auto_user_id()[1]
363
def compare_files(a, b):
364
"""Returns true if equal in contents"""
376
def local_time_offset(t=None):
377
"""Return offset of local zone from GMT, either at present or at time t."""
378
# python2.3 localtime() can't take None
382
if time.localtime(t).tm_isdst and time.daylight:
385
return -time.timezone
388
def format_date(t, offset=0, timezone='original'):
389
## TODO: Perhaps a global option to use either universal or local time?
390
## Or perhaps just let people set $TZ?
391
assert isinstance(t, float)
393
if timezone == 'utc':
396
elif timezone == 'original':
399
tt = time.gmtime(t + offset)
400
elif timezone == 'local':
401
tt = time.localtime(t)
402
offset = local_time_offset(t)
404
raise BzrError("unsupported timezone format %r" % timezone,
405
['options are "utc", "original", "local"'])
407
return (time.strftime("%a %Y-%m-%d %H:%M:%S", tt)
408
+ ' %+03d%02d' % (offset / 3600, (offset / 60) % 60))
411
def compact_date(when):
412
return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
417
"""Return size of given open file."""
418
return os.fstat(f.fileno())[ST_SIZE]
421
if hasattr(os, 'urandom'): # python 2.4 and later
422
rand_bytes = os.urandom
423
elif sys.platform == 'linux2':
424
rand_bytes = file('/dev/urandom', 'rb').read
426
# not well seeded, but better than nothing
431
s += chr(random.randint(0, 255))
436
## TODO: We could later have path objects that remember their list
437
## decomposition (might be too tricksy though.)
440
"""Turn string into list of parts.
446
>>> splitpath('a/./b')
448
>>> splitpath('a/.b')
450
>>> splitpath('a/../b')
451
Traceback (most recent call last):
453
BzrError: sorry, '..' not allowed in path
455
assert isinstance(p, types.StringTypes)
457
# split on either delimiter because people might use either on
459
ps = re.split(r'[\\/]', p)
464
raise BzrError("sorry, %r not allowed in path" % f)
465
elif (f == '.') or (f == ''):
472
assert isinstance(p, list)
474
if (f == '..') or (f == None) or (f == ''):
475
raise BzrError("sorry, %r not allowed in path" % f)
476
return os.path.join(*p)
479
def appendpath(p1, p2):
483
return os.path.join(p1, p2)
486
def extern_command(cmd, ignore_errors = False):
487
mutter('external command: %s' % `cmd`)
489
if not ignore_errors:
490
raise BzrError('command failed')
493
def _read_config_value(name):
494
"""Read a config value from the file ~/.bzr.conf/<name>
495
Return None if the file does not exist"""
497
f = file(os.path.join(config_dir(), name), "r")
498
return f.read().decode(bzrlib.user_encoding).rstrip("\r\n")
500
if e.errno == errno.ENOENT:
507
"""Split s into lines, but without removing the newline characters."""
508
return StringIO(s).readlines()