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 shutil import copyfile
20
from stat import (S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE,
21
S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
22
from cStringIO import StringIO
35
from bzrlib.errors import (BzrError,
36
BzrBadParameterNotUnicode,
41
from bzrlib.symbol_versioning import *
42
from bzrlib.trace import mutter
43
import bzrlib.win32console
46
def make_readonly(filename):
47
"""Make a filename read-only."""
48
mod = os.stat(filename).st_mode
50
os.chmod(filename, mod)
53
def make_writable(filename):
54
mod = os.stat(filename).st_mode
56
os.chmod(filename, mod)
63
"""Return a quoted filename filename
65
This previously used backslash quoting, but that works poorly on
67
# TODO: I'm not really sure this is the best format either.x
70
_QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
72
if _QUOTE_RE.search(f):
79
mode = os.lstat(f)[ST_MODE]
98
def kind_marker(kind):
101
elif kind == 'directory':
103
elif kind == 'symlink':
106
raise BzrError('invalid file kind %r' % kind)
108
lexists = getattr(os.path, 'lexists', None)
112
if hasattr(os, 'lstat'):
118
if e.errno == errno.ENOENT:
121
raise BzrError("lstat/stat of (%r): %r" % (f, e))
124
def fancy_rename(old, new, rename_func, unlink_func):
125
"""A fancy rename, when you don't have atomic rename.
127
:param old: The old path, to rename from
128
:param new: The new path, to rename to
129
:param rename_func: The potentially non-atomic rename function
130
:param unlink_func: A way to delete the target file if the full rename succeeds
133
# sftp rename doesn't allow overwriting, so play tricks:
135
base = os.path.basename(new)
136
dirname = os.path.dirname(new)
137
tmp_name = u'tmp.%s.%.9f.%d.%s' % (base, time.time(), os.getpid(), rand_chars(10))
138
tmp_name = pathjoin(dirname, tmp_name)
140
# Rename the file out of the way, but keep track if it didn't exist
141
# We don't want to grab just any exception
142
# something like EACCES should prevent us from continuing
143
# The downside is that the rename_func has to throw an exception
144
# with an errno = ENOENT, or NoSuchFile
147
rename_func(new, tmp_name)
148
except (NoSuchFile,), e:
151
# RBC 20060103 abstraction leakage: the paramiko SFTP clients rename
152
# function raises an IOError with errno == None when a rename fails.
153
# This then gets caught here.
154
if e.errno not in (None, errno.ENOENT, errno.ENOTDIR):
157
if (not hasattr(e, 'errno')
158
or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
165
# This may throw an exception, in which case success will
167
rename_func(old, new)
171
# If the file used to exist, rename it back into place
172
# otherwise just delete it from the tmp location
174
unlink_func(tmp_name)
176
rename_func(tmp_name, new)
178
# Default is to just use the python builtins, but these can be rebound on
179
# particular platforms.
180
abspath = os.path.abspath
181
realpath = os.path.realpath
182
pathjoin = os.path.join
183
normpath = os.path.normpath
185
mkdtemp = tempfile.mkdtemp
187
dirname = os.path.dirname
188
basename = os.path.basename
189
rmtree = shutil.rmtree
191
MIN_ABS_PATHLENGTH = 1
193
if os.name == "posix":
194
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
195
# choke on a Unicode string containing a relative path if
196
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
198
_fs_enc = sys.getfilesystemencoding()
200
return os.path.abspath(path.encode(_fs_enc)).decode(_fs_enc)
203
return os.path.realpath(path.encode(_fs_enc)).decode(_fs_enc)
205
if sys.platform == 'win32':
206
# We need to use the Unicode-aware os.path.abspath and
207
# os.path.realpath on Windows systems.
209
return os.path.abspath(path).replace('\\', '/')
212
return os.path.realpath(path).replace('\\', '/')
215
return os.path.join(*args).replace('\\', '/')
218
return os.path.normpath(path).replace('\\', '/')
221
return os.getcwdu().replace('\\', '/')
223
def mkdtemp(*args, **kwargs):
224
return tempfile.mkdtemp(*args, **kwargs).replace('\\', '/')
226
def rename(old, new):
227
fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
229
MIN_ABS_PATHLENGTH = 3
231
def _win32_delete_readonly(function, path, excinfo):
232
"""Error handler for shutil.rmtree function [for win32]
233
Helps to remove files and dirs marked as read-only.
235
type_, value = excinfo[:2]
236
if function in (os.remove, os.rmdir) \
237
and type_ == OSError \
238
and value.errno == errno.EACCES:
239
bzrlib.osutils.make_writable(path)
244
def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
245
"""Replacer for shutil.rmtree: could remove readonly dirs/files"""
246
return shutil.rmtree(path, ignore_errors, onerror)
249
def normalizepath(f):
250
if hasattr(os.path, 'realpath'):
254
[p,e] = os.path.split(f)
255
if e == "" or e == "." or e == "..":
258
return pathjoin(F(p), e)
262
"""Copy a file to a backup.
264
Backups are named in GNU-style, with a ~ suffix.
266
If the file is already a backup, it's not copied.
272
if has_symlinks() and os.path.islink(fn):
273
target = os.readlink(fn)
274
os.symlink(target, bfn)
282
outf = file(bfn, 'wb')
290
"""True if f is an accessible directory."""
292
return S_ISDIR(os.lstat(f)[ST_MODE])
298
"""True if f is a regular file."""
300
return S_ISREG(os.lstat(f)[ST_MODE])
305
"""True if f is a symlink."""
307
return S_ISLNK(os.lstat(f)[ST_MODE])
311
def is_inside(dir, fname):
312
"""True if fname is inside dir.
314
The parameters should typically be passed to osutils.normpath first, so
315
that . and .. and repeated slashes are eliminated, and the separators
316
are canonical for the platform.
318
The empty string as a dir name is taken as top-of-tree and matches
321
>>> is_inside('src', pathjoin('src', 'foo.c'))
323
>>> is_inside('src', 'srccontrol')
325
>>> is_inside('src', pathjoin('src', 'a', 'a', 'a', 'foo.c'))
327
>>> is_inside('foo.c', 'foo.c')
329
>>> is_inside('foo.c', '')
331
>>> is_inside('', 'foo.c')
334
# XXX: Most callers of this can actually do something smarter by
335
# looking at the inventory
345
return fname.startswith(dir)
348
def is_inside_any(dir_list, fname):
349
"""True if fname is inside any of given dirs."""
350
for dirname in dir_list:
351
if is_inside(dirname, fname):
357
def pumpfile(fromfile, tofile):
358
"""Copy contents of one file to another."""
361
b = fromfile.read(BUFSIZE)
367
def file_iterator(input_file, readsize=32768):
369
b = input_file.read(readsize)
376
if hasattr(f, 'tell'):
389
def sha_strings(strings):
390
"""Return the sha-1 of concatenation of strings"""
392
map(s.update, strings)
402
def fingerprint_file(f):
407
return {'size': size,
408
'sha1': s.hexdigest()}
411
def compare_files(a, b):
412
"""Returns true if equal in contents"""
423
def local_time_offset(t=None):
424
"""Return offset of local zone from GMT, either at present or at time t."""
425
# python2.3 localtime() can't take None
429
if time.localtime(t).tm_isdst and time.daylight:
432
return -time.timezone
435
def format_date(t, offset=0, timezone='original', date_fmt=None,
437
## TODO: Perhaps a global option to use either universal or local time?
438
## Or perhaps just let people set $TZ?
439
assert isinstance(t, float)
441
if timezone == 'utc':
444
elif timezone == 'original':
447
tt = time.gmtime(t + offset)
448
elif timezone == 'local':
449
tt = time.localtime(t)
450
offset = local_time_offset(t)
452
raise BzrError("unsupported timezone format %r" % timezone,
453
['options are "utc", "original", "local"'])
455
date_fmt = "%a %Y-%m-%d %H:%M:%S"
457
offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
460
return (time.strftime(date_fmt, tt) + offset_str)
463
def compact_date(when):
464
return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
469
"""Return size of given open file."""
470
return os.fstat(f.fileno())[ST_SIZE]
473
# Define rand_bytes based on platform.
475
# Python 2.4 and later have os.urandom,
476
# but it doesn't work on some arches
478
rand_bytes = os.urandom
479
except (NotImplementedError, AttributeError):
480
# If python doesn't have os.urandom, or it doesn't work,
481
# then try to first pull random data from /dev/urandom
482
if os.path.exists("/dev/urandom"):
483
rand_bytes = file('/dev/urandom', 'rb').read
484
# Otherwise, use this hack as a last resort
486
# not well seeded, but better than nothing
491
s += chr(random.randint(0, 255))
496
ALNUM = '0123456789abcdefghijklmnopqrstuvwxyz'
498
"""Return a random string of num alphanumeric characters
500
The result only contains lowercase chars because it may be used on
501
case-insensitive filesystems.
504
for raw_byte in rand_bytes(num):
505
s += ALNUM[ord(raw_byte) % 36]
509
## TODO: We could later have path objects that remember their list
510
## decomposition (might be too tricksy though.)
513
"""Turn string into list of parts.
519
>>> splitpath('a/./b')
521
>>> splitpath('a/.b')
523
>>> splitpath('a/../b')
524
Traceback (most recent call last):
526
BzrError: sorry, '..' not allowed in path
528
assert isinstance(p, types.StringTypes)
530
# split on either delimiter because people might use either on
532
ps = re.split(r'[\\/]', p)
537
raise BzrError("sorry, %r not allowed in path" % f)
538
elif (f == '.') or (f == ''):
545
assert isinstance(p, list)
547
if (f == '..') or (f == None) or (f == ''):
548
raise BzrError("sorry, %r not allowed in path" % f)
552
@deprecated_function(zero_nine)
553
def appendpath(p1, p2):
557
return pathjoin(p1, p2)
561
"""Split s into lines, but without removing the newline characters."""
562
lines = s.split('\n')
563
result = [line + '\n' for line in lines[:-1]]
565
result.append(lines[-1])
569
def hardlinks_good():
570
return sys.platform not in ('win32', 'cygwin', 'darwin')
573
def link_or_copy(src, dest):
574
"""Hardlink a file, or copy it if it can't be hardlinked."""
575
if not hardlinks_good():
580
except (OSError, IOError), e:
581
if e.errno != errno.EXDEV:
585
def delete_any(full_path):
586
"""Delete a file or directory."""
590
# We may be renaming a dangling inventory id
591
if e.errno not in (errno.EISDIR, errno.EACCES, errno.EPERM):
597
if hasattr(os, 'symlink'):
603
def contains_whitespace(s):
604
"""True if there are any whitespace characters in s."""
605
for ch in string.whitespace:
612
def contains_linebreaks(s):
613
"""True if there is any vertical whitespace in s."""
621
def relpath(base, path):
622
"""Return path relative to base, or raise exception.
624
The path may be either an absolute path or a path relative to the
625
current working directory.
627
os.path.commonprefix (python2.4) has a bad bug that it works just
628
on string prefixes, assuming that '/u' is a prefix of '/u2'. This
632
assert len(base) >= MIN_ABS_PATHLENGTH, ('Length of base must be equal or'
633
' exceed the platform minimum length (which is %d)' %
639
while len(head) >= len(base):
642
head, tail = os.path.split(head)
646
# XXX This should raise a NotChildPath exception, as its not tied
648
raise PathNotChild(rp, base)
656
def safe_unicode(unicode_or_utf8_string):
657
"""Coerce unicode_or_utf8_string into unicode.
659
If it is unicode, it is returned.
660
Otherwise it is decoded from utf-8. If a decoding error
661
occurs, it is wrapped as a If the decoding fails, the exception is wrapped
662
as a BzrBadParameter exception.
664
if isinstance(unicode_or_utf8_string, unicode):
665
return unicode_or_utf8_string
667
return unicode_or_utf8_string.decode('utf8')
668
except UnicodeDecodeError:
669
raise BzrBadParameterNotUnicode(unicode_or_utf8_string)
672
def terminal_width():
673
"""Return estimated terminal width."""
674
if sys.platform == 'win32':
675
import bzrlib.win32console
676
return bzrlib.win32console.get_console_size()[0]
679
import struct, fcntl, termios
680
s = struct.pack('HHHH', 0, 0, 0, 0)
681
x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
682
width = struct.unpack('HHHH', x)[1]
687
width = int(os.environ['COLUMNS'])
695
def supports_executable():
696
return sys.platform != "win32"
699
def strip_trailing_slash(path):
700
"""Strip trailing slash, except for root paths.
701
The definition of 'root path' is platform-dependent.
703
if len(path) != MIN_ABS_PATHLENGTH and path[-1] == '/':
709
_validWin32PathRE = re.compile(r'^([A-Za-z]:[/\\])?[^:<>*"?\|]*$')
712
def check_legal_path(path):
713
"""Check whether the supplied path is legal.
714
This is only required on Windows, so we don't test on other platforms
717
if sys.platform != "win32":
719
if _validWin32PathRE.match(path) is None:
720
raise IllegalPath(path)