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.trace import mutter
44
def make_readonly(filename):
45
"""Make a filename read-only."""
46
mod = os.stat(filename).st_mode
48
os.chmod(filename, mod)
51
def make_writable(filename):
52
mod = os.stat(filename).st_mode
54
os.chmod(filename, mod)
61
"""Return a quoted filename filename
63
This previously used backslash quoting, but that works poorly on
65
# TODO: I'm not really sure this is the best format either.x
68
_QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
70
if _QUOTE_RE.search(f):
77
mode = os.lstat(f)[ST_MODE]
96
def kind_marker(kind):
99
elif kind == 'directory':
101
elif kind == 'symlink':
104
raise BzrError('invalid file kind %r' % kind)
107
if hasattr(os.path, 'lexists'):
108
return os.path.lexists(f)
110
if hasattr(os, 'lstat'):
116
if e.errno == errno.ENOENT:
119
raise BzrError("lstat/stat of (%r): %r" % (f, e))
121
def fancy_rename(old, new, rename_func, unlink_func):
122
"""A fancy rename, when you don't have atomic rename.
124
:param old: The old path, to rename from
125
:param new: The new path, to rename to
126
:param rename_func: The potentially non-atomic rename function
127
:param unlink_func: A way to delete the target file if the full rename succeeds
130
# sftp rename doesn't allow overwriting, so play tricks:
132
base = os.path.basename(new)
133
dirname = os.path.dirname(new)
134
tmp_name = u'tmp.%s.%.9f.%d.%s' % (base, time.time(), os.getpid(), rand_chars(10))
135
tmp_name = pathjoin(dirname, tmp_name)
137
# Rename the file out of the way, but keep track if it didn't exist
138
# We don't want to grab just any exception
139
# something like EACCES should prevent us from continuing
140
# The downside is that the rename_func has to throw an exception
141
# with an errno = ENOENT, or NoSuchFile
144
rename_func(new, tmp_name)
145
except (NoSuchFile,), e:
148
# RBC 20060103 abstraction leakage: the paramiko SFTP clients rename
149
# function raises an IOError with errno == None when a rename fails.
150
# This then gets caught here.
151
if e.errno not in (None, errno.ENOENT, errno.ENOTDIR):
154
if (not hasattr(e, 'errno')
155
or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
162
# This may throw an exception, in which case success will
164
rename_func(old, new)
168
# If the file used to exist, rename it back into place
169
# otherwise just delete it from the tmp location
171
unlink_func(tmp_name)
173
rename_func(tmp_name, new)
175
# Default is to just use the python builtins
176
abspath = os.path.abspath
177
realpath = os.path.realpath
178
pathjoin = os.path.join
179
normpath = os.path.normpath
181
mkdtemp = tempfile.mkdtemp
183
dirname = os.path.dirname
184
basename = os.path.basename
186
MIN_ABS_PATHLENGTH = 1
188
if os.name == "posix":
189
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
190
# choke on a Unicode string containing a relative path if
191
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
193
_fs_enc = sys.getfilesystemencoding()
195
return os.path.abspath(path.encode(_fs_enc)).decode(_fs_enc)
198
return os.path.realpath(path.encode(_fs_enc)).decode(_fs_enc)
200
if sys.platform == 'win32':
201
# We need to use the Unicode-aware os.path.abspath and
202
# os.path.realpath on Windows systems.
204
return os.path.abspath(path).replace('\\', '/')
207
return os.path.realpath(path).replace('\\', '/')
210
return os.path.join(*args).replace('\\', '/')
213
return os.path.normpath(path).replace('\\', '/')
216
return os.getcwdu().replace('\\', '/')
218
def mkdtemp(*args, **kwargs):
219
return tempfile.mkdtemp(*args, **kwargs).replace('\\', '/')
221
def rename(old, new):
222
fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
224
MIN_ABS_PATHLENGTH = 3
226
def normalizepath(f):
227
if hasattr(os.path, 'realpath'):
231
[p,e] = os.path.split(f)
232
if e == "" or e == "." or e == "..":
235
return pathjoin(F(p), e)
239
"""Copy a file to a backup.
241
Backups are named in GNU-style, with a ~ suffix.
243
If the file is already a backup, it's not copied.
249
if has_symlinks() and os.path.islink(fn):
250
target = os.readlink(fn)
251
os.symlink(target, bfn)
259
outf = file(bfn, 'wb')
267
"""True if f is an accessible directory."""
269
return S_ISDIR(os.lstat(f)[ST_MODE])
275
"""True if f is a regular file."""
277
return S_ISREG(os.lstat(f)[ST_MODE])
282
"""True if f is a symlink."""
284
return S_ISLNK(os.lstat(f)[ST_MODE])
288
def is_inside(dir, fname):
289
"""True if fname is inside dir.
291
The parameters should typically be passed to osutils.normpath first, so
292
that . and .. and repeated slashes are eliminated, and the separators
293
are canonical for the platform.
295
The empty string as a dir name is taken as top-of-tree and matches
298
>>> is_inside('src', pathjoin('src', 'foo.c'))
300
>>> is_inside('src', 'srccontrol')
302
>>> is_inside('src', pathjoin('src', 'a', 'a', 'a', 'foo.c'))
304
>>> is_inside('foo.c', 'foo.c')
306
>>> is_inside('foo.c', '')
308
>>> is_inside('', 'foo.c')
311
# XXX: Most callers of this can actually do something smarter by
312
# looking at the inventory
322
return fname.startswith(dir)
325
def is_inside_any(dir_list, fname):
326
"""True if fname is inside any of given dirs."""
327
for dirname in dir_list:
328
if is_inside(dirname, fname):
334
def pumpfile(fromfile, tofile):
335
"""Copy contents of one file to another."""
338
b = fromfile.read(BUFSIZE)
344
def file_iterator(input_file, readsize=32768):
346
b = input_file.read(readsize)
353
if hasattr(f, 'tell'):
366
def sha_strings(strings):
367
"""Return the sha-1 of concatenation of strings"""
369
map(s.update, strings)
379
def fingerprint_file(f):
384
return {'size': size,
385
'sha1': s.hexdigest()}
388
def compare_files(a, b):
389
"""Returns true if equal in contents"""
400
def local_time_offset(t=None):
401
"""Return offset of local zone from GMT, either at present or at time t."""
402
# python2.3 localtime() can't take None
406
if time.localtime(t).tm_isdst and time.daylight:
409
return -time.timezone
412
def format_date(t, offset=0, timezone='original', date_fmt=None,
414
## TODO: Perhaps a global option to use either universal or local time?
415
## Or perhaps just let people set $TZ?
416
assert isinstance(t, float)
418
if timezone == 'utc':
421
elif timezone == 'original':
424
tt = time.gmtime(t + offset)
425
elif timezone == 'local':
426
tt = time.localtime(t)
427
offset = local_time_offset(t)
429
raise BzrError("unsupported timezone format %r" % timezone,
430
['options are "utc", "original", "local"'])
432
date_fmt = "%a %Y-%m-%d %H:%M:%S"
434
offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
437
return (time.strftime(date_fmt, tt) + offset_str)
440
def compact_date(when):
441
return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
446
"""Return size of given open file."""
447
return os.fstat(f.fileno())[ST_SIZE]
450
# Define rand_bytes based on platform.
452
# Python 2.4 and later have os.urandom,
453
# but it doesn't work on some arches
455
rand_bytes = os.urandom
456
except (NotImplementedError, AttributeError):
457
# If python doesn't have os.urandom, or it doesn't work,
458
# then try to first pull random data from /dev/urandom
459
if os.path.exists("/dev/urandom"):
460
rand_bytes = file('/dev/urandom', 'rb').read
461
# Otherwise, use this hack as a last resort
463
# not well seeded, but better than nothing
468
s += chr(random.randint(0, 255))
473
ALNUM = '0123456789abcdefghijklmnopqrstuvwxyz'
475
"""Return a random string of num alphanumeric characters
477
The result only contains lowercase chars because it may be used on
478
case-insensitive filesystems.
481
for raw_byte in rand_bytes(num):
482
s += ALNUM[ord(raw_byte) % 36]
486
## TODO: We could later have path objects that remember their list
487
## decomposition (might be too tricksy though.)
490
"""Turn string into list of parts.
496
>>> splitpath('a/./b')
498
>>> splitpath('a/.b')
500
>>> splitpath('a/../b')
501
Traceback (most recent call last):
503
BzrError: sorry, '..' not allowed in path
505
assert isinstance(p, types.StringTypes)
507
# split on either delimiter because people might use either on
509
ps = re.split(r'[\\/]', p)
514
raise BzrError("sorry, %r not allowed in path" % f)
515
elif (f == '.') or (f == ''):
522
assert isinstance(p, list)
524
if (f == '..') or (f == None) or (f == ''):
525
raise BzrError("sorry, %r not allowed in path" % f)
529
def appendpath(p1, p2):
533
return pathjoin(p1, p2)
537
"""Split s into lines, but without removing the newline characters."""
538
lines = s.split('\n')
539
result = [line + '\n' for line in lines[:-1]]
541
result.append(lines[-1])
545
def hardlinks_good():
546
return sys.platform not in ('win32', 'cygwin', 'darwin')
549
def link_or_copy(src, dest):
550
"""Hardlink a file, or copy it if it can't be hardlinked."""
551
if not hardlinks_good():
556
except (OSError, IOError), e:
557
if e.errno != errno.EXDEV:
561
def delete_any(full_path):
562
"""Delete a file or directory."""
566
# We may be renaming a dangling inventory id
567
if e.errno not in (errno.EISDIR, errno.EACCES, errno.EPERM):
573
if hasattr(os, 'symlink'):
579
def contains_whitespace(s):
580
"""True if there are any whitespace characters in s."""
581
for ch in string.whitespace:
588
def contains_linebreaks(s):
589
"""True if there is any vertical whitespace in s."""
597
def relpath(base, path):
598
"""Return path relative to base, or raise exception.
600
The path may be either an absolute path or a path relative to the
601
current working directory.
603
os.path.commonprefix (python2.4) has a bad bug that it works just
604
on string prefixes, assuming that '/u' is a prefix of '/u2'. This
608
assert len(base) >= MIN_ABS_PATHLENGTH, ('Length of base must be equal or'
609
' exceed the platform minimum length (which is %d)' %
615
while len(head) >= len(base):
618
head, tail = os.path.split(head)
622
# XXX This should raise a NotChildPath exception, as its not tied
624
raise PathNotChild(rp, base)
632
def safe_unicode(unicode_or_utf8_string):
633
"""Coerce unicode_or_utf8_string into unicode.
635
If it is unicode, it is returned.
636
Otherwise it is decoded from utf-8. If a decoding error
637
occurs, it is wrapped as a If the decoding fails, the exception is wrapped
638
as a BzrBadParameter exception.
640
if isinstance(unicode_or_utf8_string, unicode):
641
return unicode_or_utf8_string
643
return unicode_or_utf8_string.decode('utf8')
644
except UnicodeDecodeError:
645
raise BzrBadParameterNotUnicode(unicode_or_utf8_string)
648
_platform_normalizes_filenames = False
649
if sys.platform == 'darwin':
650
_platform_normalizes_filenames = True
653
def normalizes_filenames():
654
"""Return True if this platform normalizes unicode filenames.
656
Mac OSX does, Windows/Linux do not.
658
return _platform_normalizes_filenames
661
if _platform_normalizes_filenames:
662
def unicode_filename(path):
663
"""Make sure 'path' is a properly normalized filename.
665
On platforms where the system normalizes filenames (Mac OSX),
666
you can access a file by any path which will normalize
668
Internally, bzr only supports NFC/NFKC normalization, since
669
that is the standard for XML documents.
670
So we return an normalized path, and indicate this has been
673
:return: (path, is_normalized) Return a path which can
674
access the file, and whether or not this path is
677
return unicodedata.normalize('NFKC', path), True
679
def unicode_filename(path):
680
"""Make sure 'path' is a properly normalized filename.
682
On platforms where the system does not normalize filenames
683
(Windows, Linux), you have to access a file by its exact path.
684
Internally, bzr only supports NFC/NFKC normalization, since
685
that is the standard for XML documents.
686
So we return the original path, and indicate if this is
689
:return: (path, is_normalized) Return a path which can
690
access the file, and whether or not this path is
693
return path, unicodedata.normalize('NFKC', path) == path
696
def terminal_width():
697
"""Return estimated terminal width."""
699
# TODO: Do something smart on Windows?
701
# TODO: Is there anything that gets a better update when the window
702
# is resized while the program is running? We could use the Python termcap
705
return int(os.environ['COLUMNS'])
706
except (IndexError, KeyError, ValueError):
709
def supports_executable():
710
return sys.platform != "win32"
713
def strip_trailing_slash(path):
714
"""Strip trailing slash, except for root paths.
715
The definition of 'root path' is platform-dependent.
717
if len(path) != MIN_ABS_PATHLENGTH and path[-1] == '/':
723
_validWin32PathRE = re.compile(r'^([A-Za-z]:[/\\])?[^:<>*"?\|]*$')
726
def check_legal_path(path):
727
"""Check whether the supplied path is legal.
728
This is only required on Windows, so we don't test on other platforms
731
if sys.platform != "win32":
733
if _validWin32PathRE.match(path) is None:
734
raise IllegalPath(path)