1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
from cStringIO import StringIO
21
from stat import (S_ISREG, S_ISDIR, S_ISLNK, ST_MODE, ST_SIZE,
22
S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK)
26
from bzrlib.lazy_import import lazy_import
27
lazy_import(globals(), """
29
from datetime import datetime
31
from ntpath import (abspath as _nt_abspath,
33
normpath as _nt_normpath,
34
realpath as _nt_realpath,
35
splitdrive as _nt_splitdrive,
43
from tempfile import (
55
# sha and md5 modules are deprecated in python2.6 but hashlib is available as
57
if sys.version_info < (2, 5):
58
import md5 as _mod_md5
60
import sha as _mod_sha
70
from bzrlib import symbol_versioning
71
from bzrlib.symbol_versioning import (
74
from bzrlib.trace import mutter
77
# On win32, O_BINARY is used to indicate the file should
78
# be opened in binary mode, rather than text mode.
79
# On other platforms, O_BINARY doesn't exist, because
80
# they always open in binary mode, so it is okay to
81
# OR with 0 on those platforms
82
O_BINARY = getattr(os, 'O_BINARY', 0)
85
def make_readonly(filename):
86
"""Make a filename read-only."""
87
mod = os.lstat(filename).st_mode
88
if not stat.S_ISLNK(mod):
90
os.chmod(filename, mod)
93
def make_writable(filename):
94
mod = os.lstat(filename).st_mode
95
if not stat.S_ISLNK(mod):
97
os.chmod(filename, mod)
100
def minimum_path_selection(paths):
101
"""Return the smallset subset of paths which are outside paths.
103
:param paths: A container (and hence not None) of paths.
104
:return: A set of paths sufficient to include everything in paths via
105
is_inside_any, drawn from the paths parameter.
110
other_paths = paths.difference([path])
111
if not is_inside_any(other_paths, path):
112
# this is a top level path, we must check it.
113
search_paths.add(path)
121
"""Return a quoted filename filename
123
This previously used backslash quoting, but that works poorly on
125
# TODO: I'm not really sure this is the best format either.x
127
if _QUOTE_RE is None:
128
_QUOTE_RE = re.compile(r'([^a-zA-Z0-9.,:/\\_~-])')
130
if _QUOTE_RE.search(f):
136
_directory_kind = 'directory'
139
"""Return the current umask"""
140
# Assume that people aren't messing with the umask while running
141
# XXX: This is not thread safe, but there is no way to get the
142
# umask without setting it
150
_directory_kind: "/",
152
'tree-reference': '+',
156
def kind_marker(kind):
158
return _kind_marker_map[kind]
160
raise errors.BzrError('invalid file kind %r' % kind)
163
lexists = getattr(os.path, 'lexists', None)
167
stat = getattr(os, 'lstat', os.stat)
171
if e.errno == errno.ENOENT:
174
raise errors.BzrError("lstat/stat of (%r): %r" % (f, e))
177
def fancy_rename(old, new, rename_func, unlink_func):
178
"""A fancy rename, when you don't have atomic rename.
180
:param old: The old path, to rename from
181
:param new: The new path, to rename to
182
:param rename_func: The potentially non-atomic rename function
183
:param unlink_func: A way to delete the target file if the full rename succeeds
186
# sftp rename doesn't allow overwriting, so play tricks:
188
base = os.path.basename(new)
189
dirname = os.path.dirname(new)
190
tmp_name = u'tmp.%s.%.9f.%d.%s' % (base, time.time(), os.getpid(), rand_chars(10))
191
tmp_name = pathjoin(dirname, tmp_name)
193
# Rename the file out of the way, but keep track if it didn't exist
194
# We don't want to grab just any exception
195
# something like EACCES should prevent us from continuing
196
# The downside is that the rename_func has to throw an exception
197
# with an errno = ENOENT, or NoSuchFile
200
rename_func(new, tmp_name)
201
except (errors.NoSuchFile,), e:
204
# RBC 20060103 abstraction leakage: the paramiko SFTP clients rename
205
# function raises an IOError with errno is None when a rename fails.
206
# This then gets caught here.
207
if e.errno not in (None, errno.ENOENT, errno.ENOTDIR):
210
if (getattr(e, 'errno', None) is None
211
or e.errno not in (errno.ENOENT, errno.ENOTDIR)):
219
# This may throw an exception, in which case success will
221
rename_func(old, new)
223
except (IOError, OSError), e:
224
# source and target may be aliases of each other (e.g. on a
225
# case-insensitive filesystem), so we may have accidentally renamed
226
# source by when we tried to rename target
227
if not (file_existed and e.errno in (None, errno.ENOENT)):
231
# If the file used to exist, rename it back into place
232
# otherwise just delete it from the tmp location
234
unlink_func(tmp_name)
236
rename_func(tmp_name, new)
239
# In Python 2.4.2 and older, os.path.abspath and os.path.realpath
240
# choke on a Unicode string containing a relative path if
241
# os.getcwd() returns a non-sys.getdefaultencoding()-encoded
243
_fs_enc = sys.getfilesystemencoding() or 'utf-8'
244
def _posix_abspath(path):
245
# jam 20060426 rather than encoding to fsencoding
246
# copy posixpath.abspath, but use os.getcwdu instead
247
if not posixpath.isabs(path):
248
path = posixpath.join(getcwd(), path)
249
return posixpath.normpath(path)
252
def _posix_realpath(path):
253
return posixpath.realpath(path.encode(_fs_enc)).decode(_fs_enc)
256
def _win32_fixdrive(path):
257
"""Force drive letters to be consistent.
259
win32 is inconsistent whether it returns lower or upper case
260
and even if it was consistent the user might type the other
261
so we force it to uppercase
262
running python.exe under cmd.exe return capital C:\\
263
running win32 python inside a cygwin shell returns lowercase c:\\
265
drive, path = _nt_splitdrive(path)
266
return drive.upper() + path
269
def _win32_abspath(path):
270
# Real _nt_abspath doesn't have a problem with a unicode cwd
271
return _win32_fixdrive(_nt_abspath(unicode(path)).replace('\\', '/'))
274
def _win98_abspath(path):
275
"""Return the absolute version of a path.
276
Windows 98 safe implementation (python reimplementation
277
of Win32 API function GetFullPathNameW)
282
# \\HOST\path => //HOST/path
283
# //HOST/path => //HOST/path
284
# path => C:/cwd/path
287
# check for absolute path
288
drive = _nt_splitdrive(path)[0]
289
if drive == '' and path[:2] not in('//','\\\\'):
291
# we cannot simply os.path.join cwd and path
292
# because os.path.join('C:','/path') produce '/path'
293
# and this is incorrect
294
if path[:1] in ('/','\\'):
295
cwd = _nt_splitdrive(cwd)[0]
297
path = cwd + '\\' + path
298
return _win32_fixdrive(_nt_normpath(path).replace('\\', '/'))
300
if win32utils.winver == 'Windows 98':
301
_win32_abspath = _win98_abspath
304
def _win32_realpath(path):
305
# Real _nt_realpath doesn't have a problem with a unicode cwd
306
return _win32_fixdrive(_nt_realpath(unicode(path)).replace('\\', '/'))
309
def _win32_pathjoin(*args):
310
return _nt_join(*args).replace('\\', '/')
313
def _win32_normpath(path):
314
return _win32_fixdrive(_nt_normpath(unicode(path)).replace('\\', '/'))
318
return _win32_fixdrive(os.getcwdu().replace('\\', '/'))
321
def _win32_mkdtemp(*args, **kwargs):
322
return _win32_fixdrive(tempfile.mkdtemp(*args, **kwargs).replace('\\', '/'))
325
def _win32_rename(old, new):
326
"""We expect to be able to atomically replace 'new' with old.
328
On win32, if new exists, it must be moved out of the way first,
332
fancy_rename(old, new, rename_func=os.rename, unlink_func=os.unlink)
334
if e.errno in (errno.EPERM, errno.EACCES, errno.EBUSY, errno.EINVAL):
335
# If we try to rename a non-existant file onto cwd, we get
336
# EPERM or EACCES instead of ENOENT, this will raise ENOENT
337
# if the old path doesn't exist, sometimes we get EACCES
338
# On Linux, we seem to get EBUSY, on Mac we get EINVAL
344
return unicodedata.normalize('NFC', os.getcwdu())
347
# Default is to just use the python builtins, but these can be rebound on
348
# particular platforms.
349
abspath = _posix_abspath
350
realpath = _posix_realpath
351
pathjoin = os.path.join
352
normpath = os.path.normpath
355
dirname = os.path.dirname
356
basename = os.path.basename
357
split = os.path.split
358
splitext = os.path.splitext
359
# These were already imported into local scope
360
# mkdtemp = tempfile.mkdtemp
361
# rmtree = shutil.rmtree
363
MIN_ABS_PATHLENGTH = 1
366
if sys.platform == 'win32':
367
abspath = _win32_abspath
368
realpath = _win32_realpath
369
pathjoin = _win32_pathjoin
370
normpath = _win32_normpath
371
getcwd = _win32_getcwd
372
mkdtemp = _win32_mkdtemp
373
rename = _win32_rename
375
MIN_ABS_PATHLENGTH = 3
377
def _win32_delete_readonly(function, path, excinfo):
378
"""Error handler for shutil.rmtree function [for win32]
379
Helps to remove files and dirs marked as read-only.
381
exception = excinfo[1]
382
if function in (os.remove, os.rmdir) \
383
and isinstance(exception, OSError) \
384
and exception.errno == errno.EACCES:
390
def rmtree(path, ignore_errors=False, onerror=_win32_delete_readonly):
391
"""Replacer for shutil.rmtree: could remove readonly dirs/files"""
392
return shutil.rmtree(path, ignore_errors, onerror)
393
elif sys.platform == 'darwin':
397
def get_terminal_encoding():
398
"""Find the best encoding for printing to the screen.
400
This attempts to check both sys.stdout and sys.stdin to see
401
what encoding they are in, and if that fails it falls back to
402
bzrlib.user_encoding.
403
The problem is that on Windows, locale.getpreferredencoding()
404
is not the same encoding as that used by the console:
405
http://mail.python.org/pipermail/python-list/2003-May/162357.html
407
On my standard US Windows XP, the preferred encoding is
408
cp1252, but the console is cp437
410
output_encoding = getattr(sys.stdout, 'encoding', None)
411
if not output_encoding:
412
input_encoding = getattr(sys.stdin, 'encoding', None)
413
if not input_encoding:
414
output_encoding = bzrlib.user_encoding
415
mutter('encoding stdout as bzrlib.user_encoding %r', output_encoding)
417
output_encoding = input_encoding
418
mutter('encoding stdout as sys.stdin encoding %r', output_encoding)
420
mutter('encoding stdout as sys.stdout encoding %r', output_encoding)
421
if output_encoding == 'cp0':
422
# invalid encoding (cp0 means 'no codepage' on Windows)
423
output_encoding = bzrlib.user_encoding
424
mutter('cp0 is invalid encoding.'
425
' encoding stdout as bzrlib.user_encoding %r', output_encoding)
428
codecs.lookup(output_encoding)
430
sys.stderr.write('bzr: warning:'
431
' unknown terminal encoding %s.\n'
432
' Using encoding %s instead.\n'
433
% (output_encoding, bzrlib.user_encoding)
435
output_encoding = bzrlib.user_encoding
437
return output_encoding
440
def normalizepath(f):
441
if getattr(os.path, 'realpath', None) is not None:
445
[p,e] = os.path.split(f)
446
if e == "" or e == "." or e == "..":
449
return pathjoin(F(p), e)
453
"""True if f is an accessible directory."""
455
return S_ISDIR(os.lstat(f)[ST_MODE])
461
"""True if f is a regular file."""
463
return S_ISREG(os.lstat(f)[ST_MODE])
468
"""True if f is a symlink."""
470
return S_ISLNK(os.lstat(f)[ST_MODE])
474
def is_inside(dir, fname):
475
"""True if fname is inside dir.
477
The parameters should typically be passed to osutils.normpath first, so
478
that . and .. and repeated slashes are eliminated, and the separators
479
are canonical for the platform.
481
The empty string as a dir name is taken as top-of-tree and matches
484
# XXX: Most callers of this can actually do something smarter by
485
# looking at the inventory
495
return fname.startswith(dir)
498
def is_inside_any(dir_list, fname):
499
"""True if fname is inside any of given dirs."""
500
for dirname in dir_list:
501
if is_inside(dirname, fname):
506
def is_inside_or_parent_of_any(dir_list, fname):
507
"""True if fname is a child or a parent of any of the given files."""
508
for dirname in dir_list:
509
if is_inside(dirname, fname) or is_inside(fname, dirname):
514
def pumpfile(from_file, to_file, read_length=-1, buff_size=32768):
515
"""Copy contents of one file to another.
517
The read_length can either be -1 to read to end-of-file (EOF) or
518
it can specify the maximum number of bytes to read.
520
The buff_size represents the maximum size for each read operation
521
performed on from_file.
523
:return: The number of bytes copied.
527
# read specified number of bytes
529
while read_length > 0:
530
num_bytes_to_read = min(read_length, buff_size)
532
block = from_file.read(num_bytes_to_read)
538
actual_bytes_read = len(block)
539
read_length -= actual_bytes_read
540
length += actual_bytes_read
544
block = from_file.read(buff_size)
553
def pump_string_file(bytes, file_handle, segment_size=None):
554
"""Write bytes to file_handle in many smaller writes.
556
:param bytes: The string to write.
557
:param file_handle: The file to write to.
559
# Write data in chunks rather than all at once, because very large
560
# writes fail on some platforms (e.g. Windows with SMB mounted
563
segment_size = 5242880 # 5MB
564
segments = range(len(bytes) / segment_size + 1)
565
write = file_handle.write
566
for segment_index in segments:
567
segment = buffer(bytes, segment_index * segment_size, segment_size)
571
def file_iterator(input_file, readsize=32768):
573
b = input_file.read(readsize)
580
"""Calculate the hexdigest of an open file.
582
The file cursor should be already at the start.
594
def sha_file_by_name(fname):
595
"""Calculate the SHA1 of a file by reading the full text"""
597
f = os.open(fname, os.O_RDONLY | O_BINARY)
600
b = os.read(f, 1<<16)
608
def sha_strings(strings, _factory=sha):
609
"""Return the sha-1 of concatenation of strings"""
611
map(s.update, strings)
615
def sha_string(f, _factory=sha):
616
return _factory(f).hexdigest()
619
def fingerprint_file(f):
621
return {'size': len(b),
622
'sha1': sha(b).hexdigest()}
625
def compare_files(a, b):
626
"""Returns true if equal in contents"""
637
def local_time_offset(t=None):
638
"""Return offset of local zone from GMT, either at present or at time t."""
641
offset = datetime.fromtimestamp(t) - datetime.utcfromtimestamp(t)
642
return offset.days * 86400 + offset.seconds
644
weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
646
def format_date(t, offset=0, timezone='original', date_fmt=None,
648
"""Return a formatted date string.
650
:param t: Seconds since the epoch.
651
:param offset: Timezone offset in seconds east of utc.
652
:param timezone: How to display the time: 'utc', 'original' for the
653
timezone specified by offset, or 'local' for the process's current
655
:param date_fmt: strftime format.
656
:param show_offset: Whether to append the timezone.
658
(date_fmt, tt, offset_str) = \
659
_format_date(t, offset, timezone, date_fmt, show_offset)
660
date_fmt = date_fmt.replace('%a', weekdays[tt[6]])
661
date_str = time.strftime(date_fmt, tt)
662
return date_str + offset_str
664
def format_local_date(t, offset=0, timezone='original', date_fmt=None,
666
"""Return an unicode date string formatted according to the current locale.
668
:param t: Seconds since the epoch.
669
:param offset: Timezone offset in seconds east of utc.
670
:param timezone: How to display the time: 'utc', 'original' for the
671
timezone specified by offset, or 'local' for the process's current
673
:param date_fmt: strftime format.
674
:param show_offset: Whether to append the timezone.
676
(date_fmt, tt, offset_str) = \
677
_format_date(t, offset, timezone, date_fmt, show_offset)
678
date_str = time.strftime(date_fmt, tt)
679
if not isinstance(date_str, unicode):
680
date_str = date_str.decode(bzrlib.user_encoding, 'replace')
681
return date_str + offset_str
683
def _format_date(t, offset, timezone, date_fmt, show_offset):
684
if timezone == 'utc':
687
elif timezone == 'original':
690
tt = time.gmtime(t + offset)
691
elif timezone == 'local':
692
tt = time.localtime(t)
693
offset = local_time_offset(t)
695
raise errors.UnsupportedTimezoneFormat(timezone)
697
date_fmt = "%a %Y-%m-%d %H:%M:%S"
699
offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
702
return (date_fmt, tt, offset_str)
705
def compact_date(when):
706
return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
709
def format_delta(delta):
710
"""Get a nice looking string for a time delta.
712
:param delta: The time difference in seconds, can be positive or negative.
713
positive indicates time in the past, negative indicates time in the
714
future. (usually time.time() - stored_time)
715
:return: String formatted to show approximate resolution
721
direction = 'in the future'
725
if seconds < 90: # print seconds up to 90 seconds
727
return '%d second %s' % (seconds, direction,)
729
return '%d seconds %s' % (seconds, direction)
731
minutes = int(seconds / 60)
732
seconds -= 60 * minutes
737
if minutes < 90: # print minutes, seconds up to 90 minutes
739
return '%d minute, %d second%s %s' % (
740
minutes, seconds, plural_seconds, direction)
742
return '%d minutes, %d second%s %s' % (
743
minutes, seconds, plural_seconds, direction)
745
hours = int(minutes / 60)
746
minutes -= 60 * hours
753
return '%d hour, %d minute%s %s' % (hours, minutes,
754
plural_minutes, direction)
755
return '%d hours, %d minute%s %s' % (hours, minutes,
756
plural_minutes, direction)
759
"""Return size of given open file."""
760
return os.fstat(f.fileno())[ST_SIZE]
763
# Define rand_bytes based on platform.
765
# Python 2.4 and later have os.urandom,
766
# but it doesn't work on some arches
768
rand_bytes = os.urandom
769
except (NotImplementedError, AttributeError):
770
# If python doesn't have os.urandom, or it doesn't work,
771
# then try to first pull random data from /dev/urandom
773
rand_bytes = file('/dev/urandom', 'rb').read
774
# Otherwise, use this hack as a last resort
775
except (IOError, OSError):
776
# not well seeded, but better than nothing
781
s += chr(random.randint(0, 255))
786
ALNUM = '0123456789abcdefghijklmnopqrstuvwxyz'
788
"""Return a random string of num alphanumeric characters
790
The result only contains lowercase chars because it may be used on
791
case-insensitive filesystems.
794
for raw_byte in rand_bytes(num):
795
s += ALNUM[ord(raw_byte) % 36]
799
## TODO: We could later have path objects that remember their list
800
## decomposition (might be too tricksy though.)
803
"""Turn string into list of parts."""
804
# split on either delimiter because people might use either on
806
ps = re.split(r'[\\/]', p)
811
raise errors.BzrError("sorry, %r not allowed in path" % f)
812
elif (f == '.') or (f == ''):
820
if (f == '..') or (f is None) or (f == ''):
821
raise errors.BzrError("sorry, %r not allowed in path" % f)
826
"""Split s into lines, but without removing the newline characters."""
827
lines = s.split('\n')
828
result = [line + '\n' for line in lines[:-1]]
830
result.append(lines[-1])
834
def hardlinks_good():
835
return sys.platform not in ('win32', 'cygwin', 'darwin')
838
def link_or_copy(src, dest):
839
"""Hardlink a file, or copy it if it can't be hardlinked."""
840
if not hardlinks_good():
841
shutil.copyfile(src, dest)
845
except (OSError, IOError), e:
846
if e.errno != errno.EXDEV:
848
shutil.copyfile(src, dest)
851
# Look Before You Leap (LBYL) is appropriate here instead of Easier to Ask for
852
# Forgiveness than Permission (EAFP) because:
853
# - root can damage a solaris file system by using unlink,
854
# - unlink raises different exceptions on different OSes (linux: EISDIR, win32:
855
# EACCES, OSX: EPERM) when invoked on a directory.
856
def delete_any(path):
857
"""Delete a file or directory."""
858
if isdir(path): # Takes care of symlinks
865
if getattr(os, 'symlink', None) is not None:
872
if getattr(os, 'link', None) is not None:
878
def host_os_dereferences_symlinks():
879
return (has_symlinks()
880
and sys.platform not in ('cygwin', 'win32'))
883
def contains_whitespace(s):
884
"""True if there are any whitespace characters in s."""
885
# string.whitespace can include '\xa0' in certain locales, because it is
886
# considered "non-breaking-space" as part of ISO-8859-1. But it
887
# 1) Isn't a breaking whitespace
888
# 2) Isn't one of ' \t\r\n' which are characters we sometimes use as
890
# 3) '\xa0' isn't unicode safe since it is >128.
892
# This should *not* be a unicode set of characters in case the source
893
# string is not a Unicode string. We can auto-up-cast the characters since
894
# they are ascii, but we don't want to auto-up-cast the string in case it
896
for ch in ' \t\n\r\v\f':
903
def contains_linebreaks(s):
904
"""True if there is any vertical whitespace in s."""
912
def relpath(base, path):
913
"""Return path relative to base, or raise exception.
915
The path may be either an absolute path or a path relative to the
916
current working directory.
918
os.path.commonprefix (python2.4) has a bad bug that it works just
919
on string prefixes, assuming that '/u' is a prefix of '/u2'. This
923
if len(base) < MIN_ABS_PATHLENGTH:
924
# must have space for e.g. a drive letter
925
raise ValueError('%r is too short to calculate a relative path'
932
while len(head) >= len(base):
935
head, tail = os.path.split(head)
939
raise errors.PathNotChild(rp, base)
947
def safe_unicode(unicode_or_utf8_string):
948
"""Coerce unicode_or_utf8_string into unicode.
950
If it is unicode, it is returned.
951
Otherwise it is decoded from utf-8. If a decoding error
952
occurs, it is wrapped as a If the decoding fails, the exception is wrapped
953
as a BzrBadParameter exception.
955
if isinstance(unicode_or_utf8_string, unicode):
956
return unicode_or_utf8_string
958
return unicode_or_utf8_string.decode('utf8')
959
except UnicodeDecodeError:
960
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
963
def safe_utf8(unicode_or_utf8_string):
964
"""Coerce unicode_or_utf8_string to a utf8 string.
966
If it is a str, it is returned.
967
If it is Unicode, it is encoded into a utf-8 string.
969
if isinstance(unicode_or_utf8_string, str):
970
# TODO: jam 20070209 This is overkill, and probably has an impact on
971
# performance if we are dealing with lots of apis that want a
974
# Make sure it is a valid utf-8 string
975
unicode_or_utf8_string.decode('utf-8')
976
except UnicodeDecodeError:
977
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
978
return unicode_or_utf8_string
979
return unicode_or_utf8_string.encode('utf-8')
982
_revision_id_warning = ('Unicode revision ids were deprecated in bzr 0.15.'
983
' Revision id generators should be creating utf8'
987
def safe_revision_id(unicode_or_utf8_string, warn=True):
988
"""Revision ids should now be utf8, but at one point they were unicode.
990
:param unicode_or_utf8_string: A possibly Unicode revision_id. (can also be
992
:param warn: Functions that are sanitizing user data can set warn=False
993
:return: None or a utf8 revision id.
995
if (unicode_or_utf8_string is None
996
or unicode_or_utf8_string.__class__ == str):
997
return unicode_or_utf8_string
999
symbol_versioning.warn(_revision_id_warning, DeprecationWarning,
1001
return cache_utf8.encode(unicode_or_utf8_string)
1004
_file_id_warning = ('Unicode file ids were deprecated in bzr 0.15. File id'
1005
' generators should be creating utf8 file ids.')
1008
def safe_file_id(unicode_or_utf8_string, warn=True):
1009
"""File ids should now be utf8, but at one point they were unicode.
1011
This is the same as safe_utf8, except it uses the cached encode functions
1012
to save a little bit of performance.
1014
:param unicode_or_utf8_string: A possibly Unicode file_id. (can also be
1016
:param warn: Functions that are sanitizing user data can set warn=False
1017
:return: None or a utf8 file id.
1019
if (unicode_or_utf8_string is None
1020
or unicode_or_utf8_string.__class__ == str):
1021
return unicode_or_utf8_string
1023
symbol_versioning.warn(_file_id_warning, DeprecationWarning,
1025
return cache_utf8.encode(unicode_or_utf8_string)
1028
_platform_normalizes_filenames = False
1029
if sys.platform == 'darwin':
1030
_platform_normalizes_filenames = True
1033
def normalizes_filenames():
1034
"""Return True if this platform normalizes unicode filenames.
1036
Mac OSX does, Windows/Linux do not.
1038
return _platform_normalizes_filenames
1041
def _accessible_normalized_filename(path):
1042
"""Get the unicode normalized path, and if you can access the file.
1044
On platforms where the system normalizes filenames (Mac OSX),
1045
you can access a file by any path which will normalize correctly.
1046
On platforms where the system does not normalize filenames
1047
(Windows, Linux), you have to access a file by its exact path.
1049
Internally, bzr only supports NFC normalization, since that is
1050
the standard for XML documents.
1052
So return the normalized path, and a flag indicating if the file
1053
can be accessed by that path.
1056
return unicodedata.normalize('NFC', unicode(path)), True
1059
def _inaccessible_normalized_filename(path):
1060
__doc__ = _accessible_normalized_filename.__doc__
1062
normalized = unicodedata.normalize('NFC', unicode(path))
1063
return normalized, normalized == path
1066
if _platform_normalizes_filenames:
1067
normalized_filename = _accessible_normalized_filename
1069
normalized_filename = _inaccessible_normalized_filename
1072
def terminal_width():
1073
"""Return estimated terminal width."""
1074
if sys.platform == 'win32':
1075
return win32utils.get_console_size()[0]
1078
import struct, fcntl, termios
1079
s = struct.pack('HHHH', 0, 0, 0, 0)
1080
x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
1081
width = struct.unpack('HHHH', x)[1]
1086
width = int(os.environ['COLUMNS'])
1095
def supports_executable():
1096
return sys.platform != "win32"
1099
def supports_posix_readonly():
1100
"""Return True if 'readonly' has POSIX semantics, False otherwise.
1102
Notably, a win32 readonly file cannot be deleted, unlike POSIX where the
1103
directory controls creation/deletion, etc.
1105
And under win32, readonly means that the directory itself cannot be
1106
deleted. The contents of a readonly directory can be changed, unlike POSIX
1107
where files in readonly directories cannot be added, deleted or renamed.
1109
return sys.platform != "win32"
1112
def set_or_unset_env(env_variable, value):
1113
"""Modify the environment, setting or removing the env_variable.
1115
:param env_variable: The environment variable in question
1116
:param value: The value to set the environment to. If None, then
1117
the variable will be removed.
1118
:return: The original value of the environment variable.
1120
orig_val = os.environ.get(env_variable)
1122
if orig_val is not None:
1123
del os.environ[env_variable]
1125
if isinstance(value, unicode):
1126
value = value.encode(bzrlib.user_encoding)
1127
os.environ[env_variable] = value
1131
_validWin32PathRE = re.compile(r'^([A-Za-z]:[/\\])?[^:<>*"?\|]*$')
1134
def check_legal_path(path):
1135
"""Check whether the supplied path is legal.
1136
This is only required on Windows, so we don't test on other platforms
1139
if sys.platform != "win32":
1141
if _validWin32PathRE.match(path) is None:
1142
raise errors.IllegalPath(path)
1145
_WIN32_ERROR_DIRECTORY = 267 # Similar to errno.ENOTDIR
1147
def _is_error_enotdir(e):
1148
"""Check if this exception represents ENOTDIR.
1150
Unfortunately, python is very inconsistent about the exception
1151
here. The cases are:
1152
1) Linux, Mac OSX all versions seem to set errno == ENOTDIR
1153
2) Windows, Python2.4, uses errno == ERROR_DIRECTORY (267)
1154
which is the windows error code.
1155
3) Windows, Python2.5 uses errno == EINVAL and
1156
winerror == ERROR_DIRECTORY
1158
:param e: An Exception object (expected to be OSError with an errno
1159
attribute, but we should be able to cope with anything)
1160
:return: True if this represents an ENOTDIR error. False otherwise.
1162
en = getattr(e, 'errno', None)
1163
if (en == errno.ENOTDIR
1164
or (sys.platform == 'win32'
1165
and (en == _WIN32_ERROR_DIRECTORY
1166
or (en == errno.EINVAL
1167
and getattr(e, 'winerror', None) == _WIN32_ERROR_DIRECTORY)
1173
def walkdirs(top, prefix=""):
1174
"""Yield data about all the directories in a tree.
1176
This yields all the data about the contents of a directory at a time.
1177
After each directory has been yielded, if the caller has mutated the list
1178
to exclude some directories, they are then not descended into.
1180
The data yielded is of the form:
1181
((directory-relpath, directory-path-from-top),
1182
[(relpath, basename, kind, lstat, path-from-top), ...]),
1183
- directory-relpath is the relative path of the directory being returned
1184
with respect to top. prefix is prepended to this.
1185
- directory-path-from-root is the path including top for this directory.
1186
It is suitable for use with os functions.
1187
- relpath is the relative path within the subtree being walked.
1188
- basename is the basename of the path
1189
- kind is the kind of the file now. If unknown then the file is not
1190
present within the tree - but it may be recorded as versioned. See
1192
- lstat is the stat data *if* the file was statted.
1193
- planned, not implemented:
1194
path_from_tree_root is the path from the root of the tree.
1196
:param prefix: Prefix the relpaths that are yielded with 'prefix'. This
1197
allows one to walk a subtree but get paths that are relative to a tree
1199
:return: an iterator over the dirs.
1201
#TODO there is a bit of a smell where the results of the directory-
1202
# summary in this, and the path from the root, may not agree
1203
# depending on top and prefix - i.e. ./foo and foo as a pair leads to
1204
# potentially confusing output. We should make this more robust - but
1205
# not at a speed cost. RBC 20060731
1207
_directory = _directory_kind
1208
_listdir = os.listdir
1209
_kind_from_mode = file_kind_from_stat_mode
1210
pending = [(safe_unicode(prefix), "", _directory, None, safe_unicode(top))]
1212
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1213
relroot, _, _, _, top = pending.pop()
1215
relprefix = relroot + u'/'
1218
top_slash = top + u'/'
1221
append = dirblock.append
1223
names = sorted(_listdir(top))
1225
if not _is_error_enotdir(e):
1229
abspath = top_slash + name
1230
statvalue = _lstat(abspath)
1231
kind = _kind_from_mode(statvalue.st_mode)
1232
append((relprefix + name, name, kind, statvalue, abspath))
1233
yield (relroot, top), dirblock
1235
# push the user specified dirs from dirblock
1236
pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1239
class DirReader(object):
1240
"""An interface for reading directories."""
1242
def top_prefix_to_starting_dir(self, top, prefix=""):
1243
"""Converts top and prefix to a starting dir entry
1245
:param top: A utf8 path
1246
:param prefix: An optional utf8 path to prefix output relative paths
1248
:return: A tuple starting with prefix, and ending with the native
1251
raise NotImplementedError(self.top_prefix_to_starting_dir)
1253
def read_dir(self, prefix, top):
1254
"""Read a specific dir.
1256
:param prefix: A utf8 prefix to be preprended to the path basenames.
1257
:param top: A natively encoded path to read.
1258
:return: A list of the directories contents. Each item contains:
1259
(utf8_relpath, utf8_name, kind, lstatvalue, native_abspath)
1261
raise NotImplementedError(self.read_dir)
1264
_selected_dir_reader = None
1267
def _walkdirs_utf8(top, prefix=""):
1268
"""Yield data about all the directories in a tree.
1270
This yields the same information as walkdirs() only each entry is yielded
1271
in utf-8. On platforms which have a filesystem encoding of utf8 the paths
1272
are returned as exact byte-strings.
1274
:return: yields a tuple of (dir_info, [file_info])
1275
dir_info is (utf8_relpath, path-from-top)
1276
file_info is (utf8_relpath, utf8_name, kind, lstat, path-from-top)
1277
if top is an absolute path, path-from-top is also an absolute path.
1278
path-from-top might be unicode or utf8, but it is the correct path to
1279
pass to os functions to affect the file in question. (such as os.lstat)
1281
global _selected_dir_reader
1282
if _selected_dir_reader is None:
1283
fs_encoding = _fs_enc.upper()
1284
if win32utils.winver == 'Windows NT':
1285
# Win98 doesn't have unicode apis like FindFirstFileW
1286
# TODO: We possibly could support Win98 by falling back to the
1287
# original FindFirstFile, and using TCHAR instead of WCHAR,
1288
# but that gets a bit tricky, and requires custom compiling
1291
from bzrlib._walkdirs_win32 import Win32ReadDir
1293
_selected_dir_reader = UnicodeDirReader()
1295
_selected_dir_reader = Win32ReadDir()
1296
elif fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
1297
# ANSI_X3.4-1968 is a form of ASCII
1298
_selected_dir_reader = UnicodeDirReader()
1301
from bzrlib._readdir_pyx import UTF8DirReader
1303
# No optimised code path
1304
_selected_dir_reader = UnicodeDirReader()
1306
_selected_dir_reader = UTF8DirReader()
1307
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1308
# But we don't actually uses 1-3 in pending, so set them to None
1309
pending = [[_selected_dir_reader.top_prefix_to_starting_dir(top, prefix)]]
1310
read_dir = _selected_dir_reader.read_dir
1311
_directory = _directory_kind
1313
relroot, _, _, _, top = pending[-1].pop()
1316
dirblock = sorted(read_dir(relroot, top))
1317
yield (relroot, top), dirblock
1318
# push the user specified dirs from dirblock
1319
next = [d for d in reversed(dirblock) if d[2] == _directory]
1321
pending.append(next)
1324
class UnicodeDirReader(DirReader):
1325
"""A dir reader for non-utf8 file systems, which transcodes."""
1327
__slots__ = ['_utf8_encode']
1330
self._utf8_encode = codecs.getencoder('utf8')
1332
def top_prefix_to_starting_dir(self, top, prefix=""):
1333
"""See DirReader.top_prefix_to_starting_dir."""
1334
return (safe_utf8(prefix), None, None, None, safe_unicode(top))
1336
def read_dir(self, prefix, top):
1337
"""Read a single directory from a non-utf8 file system.
1339
top, and the abspath element in the output are unicode, all other paths
1340
are utf8. Local disk IO is done via unicode calls to listdir etc.
1342
This is currently the fallback code path when the filesystem encoding is
1343
not UTF-8. It may be better to implement an alternative so that we can
1344
safely handle paths that are not properly decodable in the current
1347
See DirReader.read_dir for details.
1349
_utf8_encode = self._utf8_encode
1351
_listdir = os.listdir
1352
_kind_from_mode = file_kind_from_stat_mode
1355
relprefix = prefix + '/'
1358
top_slash = top + u'/'
1361
append = dirblock.append
1362
for name in sorted(_listdir(top)):
1364
name_utf8 = _utf8_encode(name)[0]
1365
except UnicodeDecodeError:
1366
raise errors.BadFilenameEncoding(
1367
_utf8_encode(relprefix)[0] + name, _fs_enc)
1368
abspath = top_slash + name
1369
statvalue = _lstat(abspath)
1370
kind = _kind_from_mode(statvalue.st_mode)
1371
append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
1375
def copy_tree(from_path, to_path, handlers={}):
1376
"""Copy all of the entries in from_path into to_path.
1378
:param from_path: The base directory to copy.
1379
:param to_path: The target directory. If it does not exist, it will
1381
:param handlers: A dictionary of functions, which takes a source and
1382
destinations for files, directories, etc.
1383
It is keyed on the file kind, such as 'directory', 'symlink', or 'file'
1384
'file', 'directory', and 'symlink' should always exist.
1385
If they are missing, they will be replaced with 'os.mkdir()',
1386
'os.readlink() + os.symlink()', and 'shutil.copy2()', respectively.
1388
# Now, just copy the existing cached tree to the new location
1389
# We use a cheap trick here.
1390
# Absolute paths are prefixed with the first parameter
1391
# relative paths are prefixed with the second.
1392
# So we can get both the source and target returned
1393
# without any extra work.
1395
def copy_dir(source, dest):
1398
def copy_link(source, dest):
1399
"""Copy the contents of a symlink"""
1400
link_to = os.readlink(source)
1401
os.symlink(link_to, dest)
1403
real_handlers = {'file':shutil.copy2,
1404
'symlink':copy_link,
1405
'directory':copy_dir,
1407
real_handlers.update(handlers)
1409
if not os.path.exists(to_path):
1410
real_handlers['directory'](from_path, to_path)
1412
for dir_info, entries in walkdirs(from_path, prefix=to_path):
1413
for relpath, name, kind, st, abspath in entries:
1414
real_handlers[kind](abspath, relpath)
1417
def path_prefix_key(path):
1418
"""Generate a prefix-order path key for path.
1420
This can be used to sort paths in the same way that walkdirs does.
1422
return (dirname(path) , path)
1425
def compare_paths_prefix_order(path_a, path_b):
1426
"""Compare path_a and path_b to generate the same order walkdirs uses."""
1427
key_a = path_prefix_key(path_a)
1428
key_b = path_prefix_key(path_b)
1429
return cmp(key_a, key_b)
1432
_cached_user_encoding = None
1435
def get_user_encoding(use_cache=True):
1436
"""Find out what the preferred user encoding is.
1438
This is generally the encoding that is used for command line parameters
1439
and file contents. This may be different from the terminal encoding
1440
or the filesystem encoding.
1442
:param use_cache: Enable cache for detected encoding.
1443
(This parameter is turned on by default,
1444
and required only for selftesting)
1446
:return: A string defining the preferred user encoding
1448
global _cached_user_encoding
1449
if _cached_user_encoding is not None and use_cache:
1450
return _cached_user_encoding
1452
if sys.platform == 'darwin':
1453
# python locale.getpreferredencoding() always return
1454
# 'mac-roman' on darwin. That's a lie.
1455
sys.platform = 'posix'
1457
if os.environ.get('LANG', None) is None:
1458
# If LANG is not set, we end up with 'ascii', which is bad
1459
# ('mac-roman' is more than ascii), so we set a default which
1460
# will give us UTF-8 (which appears to work in all cases on
1461
# OSX). Users are still free to override LANG of course, as
1462
# long as it give us something meaningful. This work-around
1463
# *may* not be needed with python 3k and/or OSX 10.5, but will
1464
# work with them too -- vila 20080908
1465
os.environ['LANG'] = 'en_US.UTF-8'
1468
sys.platform = 'darwin'
1473
user_encoding = locale.getpreferredencoding()
1474
except locale.Error, e:
1475
sys.stderr.write('bzr: warning: %s\n'
1476
' Could not determine what text encoding to use.\n'
1477
' This error usually means your Python interpreter\n'
1478
' doesn\'t support the locale set by $LANG (%s)\n'
1479
" Continuing with ascii encoding.\n"
1480
% (e, os.environ.get('LANG')))
1481
user_encoding = 'ascii'
1483
# Windows returns 'cp0' to indicate there is no code page. So we'll just
1484
# treat that as ASCII, and not support printing unicode characters to the
1487
# For python scripts run under vim, we get '', so also treat that as ASCII
1488
if user_encoding in (None, 'cp0', ''):
1489
user_encoding = 'ascii'
1493
codecs.lookup(user_encoding)
1495
sys.stderr.write('bzr: warning:'
1496
' unknown encoding %s.'
1497
' Continuing with ascii encoding.\n'
1500
user_encoding = 'ascii'
1503
_cached_user_encoding = user_encoding
1505
return user_encoding
1508
def get_host_name():
1509
"""Return the current unicode host name.
1511
This is meant to be used in place of socket.gethostname() because that
1512
behaves inconsistently on different platforms.
1514
if sys.platform == "win32":
1516
return win32utils.get_host_name()
1519
return socket.gethostname().decode(get_user_encoding())
1522
def recv_all(socket, bytes):
1523
"""Receive an exact number of bytes.
1525
Regular Socket.recv() may return less than the requested number of bytes,
1526
dependning on what's in the OS buffer. MSG_WAITALL is not available
1527
on all platforms, but this should work everywhere. This will return
1528
less than the requested amount if the remote end closes.
1530
This isn't optimized and is intended mostly for use in testing.
1533
while len(b) < bytes:
1534
new = socket.recv(bytes - len(b))
1541
def send_all(socket, bytes):
1542
"""Send all bytes on a socket.
1544
Regular socket.sendall() can give socket error 10053 on Windows. This
1545
implementation sends no more than 64k at a time, which avoids this problem.
1548
for pos in xrange(0, len(bytes), chunk_size):
1549
socket.sendall(bytes[pos:pos+chunk_size])
1552
def dereference_path(path):
1553
"""Determine the real path to a file.
1555
All parent elements are dereferenced. But the file itself is not
1557
:param path: The original path. May be absolute or relative.
1558
:return: the real path *to* the file
1560
parent, base = os.path.split(path)
1561
# The pathjoin for '.' is a workaround for Python bug #1213894.
1562
# (initial path components aren't dereferenced)
1563
return pathjoin(realpath(pathjoin('.', parent)), base)
1566
def supports_mapi():
1567
"""Return True if we can use MAPI to launch a mail client."""
1568
return sys.platform == "win32"
1571
def resource_string(package, resource_name):
1572
"""Load a resource from a package and return it as a string.
1574
Note: Only packages that start with bzrlib are currently supported.
1576
This is designed to be a lightweight implementation of resource
1577
loading in a way which is API compatible with the same API from
1579
http://peak.telecommunity.com/DevCenter/PkgResources#basic-resource-access.
1580
If and when pkg_resources becomes a standard library, this routine
1583
# Check package name is within bzrlib
1584
if package == "bzrlib":
1585
resource_relpath = resource_name
1586
elif package.startswith("bzrlib."):
1587
package = package[len("bzrlib."):].replace('.', os.sep)
1588
resource_relpath = pathjoin(package, resource_name)
1590
raise errors.BzrError('resource package %s not in bzrlib' % package)
1592
# Map the resource to a file and read its contents
1593
base = dirname(bzrlib.__file__)
1594
if getattr(sys, 'frozen', None): # bzr.exe
1595
base = abspath(pathjoin(base, '..', '..'))
1596
filename = pathjoin(base, resource_relpath)
1597
return open(filename, 'rU').read()
1600
def file_kind_from_stat_mode_thunk(mode):
1601
global file_kind_from_stat_mode
1602
if file_kind_from_stat_mode is file_kind_from_stat_mode_thunk:
1604
from bzrlib._readdir_pyx import UTF8DirReader
1605
file_kind_from_stat_mode = UTF8DirReader().kind_from_mode
1607
from bzrlib._readdir_py import (
1608
_kind_from_mode as file_kind_from_stat_mode
1610
return file_kind_from_stat_mode(mode)
1611
file_kind_from_stat_mode = file_kind_from_stat_mode_thunk
1614
def file_kind(f, _lstat=os.lstat):
1616
return file_kind_from_stat_mode(_lstat(f).st_mode)
1618
if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
1619
raise errors.NoSuchFile(f)