709
517
def local_time_offset(t=None):
710
518
"""Return offset of local zone from GMT, either at present or at time t."""
519
# python2.3 localtime() can't take None
713
offset = datetime.fromtimestamp(t) - datetime.utcfromtimestamp(t)
714
return offset.days * 86400 + offset.seconds
716
weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
717
_default_format_by_weekday_num = [wd + " %Y-%m-%d %H:%M:%S" for wd in weekdays]
720
def format_date(t, offset=0, timezone='original', date_fmt=None,
523
if time.localtime(t).tm_isdst and time.daylight:
526
return -time.timezone
529
def format_date(t, offset=0, timezone='original', date_fmt=None,
721
530
show_offset=True):
722
"""Return a formatted date string.
724
:param t: Seconds since the epoch.
725
:param offset: Timezone offset in seconds east of utc.
726
:param timezone: How to display the time: 'utc', 'original' for the
727
timezone specified by offset, or 'local' for the process's current
729
:param date_fmt: strftime format.
730
:param show_offset: Whether to append the timezone.
732
(date_fmt, tt, offset_str) = \
733
_format_date(t, offset, timezone, date_fmt, show_offset)
734
date_fmt = date_fmt.replace('%a', weekdays[tt[6]])
735
date_str = time.strftime(date_fmt, tt)
736
return date_str + offset_str
739
# Cache of formatted offset strings
743
def format_date_with_offset_in_original_timezone(t, offset=0,
744
_cache=_offset_cache):
745
"""Return a formatted date string in the original timezone.
747
This routine may be faster then format_date.
749
:param t: Seconds since the epoch.
750
:param offset: Timezone offset in seconds east of utc.
754
tt = time.gmtime(t + offset)
755
date_fmt = _default_format_by_weekday_num[tt[6]]
756
date_str = time.strftime(date_fmt, tt)
757
offset_str = _cache.get(offset, None)
758
if offset_str is None:
759
offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
760
_cache[offset] = offset_str
761
return date_str + offset_str
764
def format_local_date(t, offset=0, timezone='original', date_fmt=None,
766
"""Return an unicode date string formatted according to the current locale.
768
:param t: Seconds since the epoch.
769
:param offset: Timezone offset in seconds east of utc.
770
:param timezone: How to display the time: 'utc', 'original' for the
771
timezone specified by offset, or 'local' for the process's current
773
:param date_fmt: strftime format.
774
:param show_offset: Whether to append the timezone.
776
(date_fmt, tt, offset_str) = \
777
_format_date(t, offset, timezone, date_fmt, show_offset)
778
date_str = time.strftime(date_fmt, tt)
779
if not isinstance(date_str, unicode):
780
date_str = date_str.decode(get_user_encoding(), 'replace')
781
return date_str + offset_str
784
def _format_date(t, offset, timezone, date_fmt, show_offset):
531
## TODO: Perhaps a global option to use either universal or local time?
532
## Or perhaps just let people set $TZ?
533
assert isinstance(t, float)
785
535
if timezone == 'utc':
786
536
tt = time.gmtime(t)
788
538
elif timezone == 'original':
791
541
tt = time.gmtime(t + offset)
792
542
elif timezone == 'local':
793
543
tt = time.localtime(t)
794
544
offset = local_time_offset(t)
796
raise errors.UnsupportedTimezoneFormat(timezone)
546
raise BzrError("unsupported timezone format %r" % timezone,
547
['options are "utc", "original", "local"'])
797
548
if date_fmt is None:
798
549
date_fmt = "%a %Y-%m-%d %H:%M:%S"
800
551
offset_str = ' %+03d%02d' % (offset / 3600, (offset / 60) % 60)
803
return (date_fmt, tt, offset_str)
554
return (time.strftime(date_fmt, tt) + offset_str)
806
557
def compact_date(when):
807
558
return time.strftime('%Y%m%d%H%M%S', time.gmtime(when))
810
def format_delta(delta):
811
"""Get a nice looking string for a time delta.
813
:param delta: The time difference in seconds, can be positive or negative.
814
positive indicates time in the past, negative indicates time in the
815
future. (usually time.time() - stored_time)
816
:return: String formatted to show approximate resolution
822
direction = 'in the future'
826
if seconds < 90: # print seconds up to 90 seconds
828
return '%d second %s' % (seconds, direction,)
830
return '%d seconds %s' % (seconds, direction)
832
minutes = int(seconds / 60)
833
seconds -= 60 * minutes
838
if minutes < 90: # print minutes, seconds up to 90 minutes
840
return '%d minute, %d second%s %s' % (
841
minutes, seconds, plural_seconds, direction)
843
return '%d minutes, %d second%s %s' % (
844
minutes, seconds, plural_seconds, direction)
846
hours = int(minutes / 60)
847
minutes -= 60 * hours
854
return '%d hour, %d minute%s %s' % (hours, minutes,
855
plural_minutes, direction)
856
return '%d hours, %d minute%s %s' % (hours, minutes,
857
plural_minutes, direction)
860
563
"""Return size of given open file."""
1135
723
avoids that problem.
1138
if len(base) < MIN_ABS_PATHLENGTH:
1139
# must have space for e.g. a drive letter
1140
raise ValueError('%r is too short to calculate a relative path'
726
assert len(base) >= MIN_ABS_PATHLENGTH, ('Length of base must be equal or'
727
' exceed the platform minimum length (which is %d)' %
1143
730
rp = abspath(path)
1148
if len(head) <= len(base) and head != base:
1149
raise errors.PathNotChild(rp, base)
734
while len(head) >= len(base):
1150
735
if head == base:
1152
head, tail = split(head)
737
head, tail = os.path.split(head)
741
raise PathNotChild(rp, base)
1157
return pathjoin(*reversed(s))
1162
def _cicp_canonical_relpath(base, path):
1163
"""Return the canonical path relative to base.
1165
Like relpath, but on case-insensitive-case-preserving file-systems, this
1166
will return the relpath as stored on the file-system rather than in the
1167
case specified in the input string, for all existing portions of the path.
1169
This will cause O(N) behaviour if called for every path in a tree; if you
1170
have a number of paths to convert, you should use canonical_relpaths().
1172
# TODO: it should be possible to optimize this for Windows by using the
1173
# win32 API FindFiles function to look for the specified name - but using
1174
# os.listdir() still gives us the correct, platform agnostic semantics in
1177
rel = relpath(base, path)
1178
# '.' will have been turned into ''
1182
abs_base = abspath(base)
1184
_listdir = os.listdir
1186
# use an explicit iterator so we can easily consume the rest on early exit.
1187
bit_iter = iter(rel.split('/'))
1188
for bit in bit_iter:
1191
next_entries = _listdir(current)
1192
except OSError: # enoent, eperm, etc
1193
# We can't find this in the filesystem, so just append the
1195
current = pathjoin(current, bit, *list(bit_iter))
1197
for look in next_entries:
1198
if lbit == look.lower():
1199
current = pathjoin(current, look)
1202
# got to the end, nothing matched, so we just return the
1203
# non-existing bits as they were specified (the filename may be
1204
# the target of a move, for example).
1205
current = pathjoin(current, bit, *list(bit_iter))
1207
return current[len(abs_base):].lstrip('/')
1209
# XXX - TODO - we need better detection/integration of case-insensitive
1210
# file-systems; Linux often sees FAT32 devices (or NFS-mounted OSX
1211
# filesystems), for example, so could probably benefit from the same basic
1212
# support there. For now though, only Windows and OSX get that support, and
1213
# they get it for *all* file-systems!
1214
if sys.platform in ('win32', 'darwin'):
1215
canonical_relpath = _cicp_canonical_relpath
1217
canonical_relpath = relpath
1219
def canonical_relpaths(base, paths):
1220
"""Create an iterable to canonicalize a sequence of relative paths.
1222
The intent is for this implementation to use a cache, vastly speeding
1223
up multiple transformations in the same directory.
1225
# but for now, we haven't optimized...
1226
return [canonical_relpath(base, p) for p in paths]
1228
749
def safe_unicode(unicode_or_utf8_string):
1229
750
"""Coerce unicode_or_utf8_string into unicode.
1231
752
If it is unicode, it is returned.
1232
Otherwise it is decoded from utf-8. If decoding fails, the exception is
1233
wrapped in a BzrBadParameterNotUnicode exception.
753
Otherwise it is decoded from utf-8. If a decoding error
754
occurs, it is wrapped as a If the decoding fails, the exception is wrapped
755
as a BzrBadParameter exception.
1235
757
if isinstance(unicode_or_utf8_string, unicode):
1236
758
return unicode_or_utf8_string
1238
760
return unicode_or_utf8_string.decode('utf8')
1239
761
except UnicodeDecodeError:
1240
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
1243
def safe_utf8(unicode_or_utf8_string):
1244
"""Coerce unicode_or_utf8_string to a utf8 string.
1246
If it is a str, it is returned.
1247
If it is Unicode, it is encoded into a utf-8 string.
1249
if isinstance(unicode_or_utf8_string, str):
1250
# TODO: jam 20070209 This is overkill, and probably has an impact on
1251
# performance if we are dealing with lots of apis that want a
1254
# Make sure it is a valid utf-8 string
1255
unicode_or_utf8_string.decode('utf-8')
1256
except UnicodeDecodeError:
1257
raise errors.BzrBadParameterNotUnicode(unicode_or_utf8_string)
1258
return unicode_or_utf8_string
1259
return unicode_or_utf8_string.encode('utf-8')
1262
_revision_id_warning = ('Unicode revision ids were deprecated in bzr 0.15.'
1263
' Revision id generators should be creating utf8'
1267
def safe_revision_id(unicode_or_utf8_string, warn=True):
1268
"""Revision ids should now be utf8, but at one point they were unicode.
1270
:param unicode_or_utf8_string: A possibly Unicode revision_id. (can also be
1272
:param warn: Functions that are sanitizing user data can set warn=False
1273
:return: None or a utf8 revision id.
1275
if (unicode_or_utf8_string is None
1276
or unicode_or_utf8_string.__class__ == str):
1277
return unicode_or_utf8_string
1279
symbol_versioning.warn(_revision_id_warning, DeprecationWarning,
1281
return cache_utf8.encode(unicode_or_utf8_string)
1284
_file_id_warning = ('Unicode file ids were deprecated in bzr 0.15. File id'
1285
' generators should be creating utf8 file ids.')
1288
def safe_file_id(unicode_or_utf8_string, warn=True):
1289
"""File ids should now be utf8, but at one point they were unicode.
1291
This is the same as safe_utf8, except it uses the cached encode functions
1292
to save a little bit of performance.
1294
:param unicode_or_utf8_string: A possibly Unicode file_id. (can also be
1296
:param warn: Functions that are sanitizing user data can set warn=False
1297
:return: None or a utf8 file id.
1299
if (unicode_or_utf8_string is None
1300
or unicode_or_utf8_string.__class__ == str):
1301
return unicode_or_utf8_string
1303
symbol_versioning.warn(_file_id_warning, DeprecationWarning,
1305
return cache_utf8.encode(unicode_or_utf8_string)
762
raise BzrBadParameterNotUnicode(unicode_or_utf8_string)
1308
765
_platform_normalizes_filenames = False
1318
775
return _platform_normalizes_filenames
1321
def _accessible_normalized_filename(path):
1322
"""Get the unicode normalized path, and if you can access the file.
1324
On platforms where the system normalizes filenames (Mac OSX),
1325
you can access a file by any path which will normalize correctly.
1326
On platforms where the system does not normalize filenames
1327
(Windows, Linux), you have to access a file by its exact path.
1329
Internally, bzr only supports NFC normalization, since that is
1330
the standard for XML documents.
1332
So return the normalized path, and a flag indicating if the file
1333
can be accessed by that path.
1336
return unicodedata.normalize('NFC', unicode(path)), True
1339
def _inaccessible_normalized_filename(path):
1340
__doc__ = _accessible_normalized_filename.__doc__
1342
normalized = unicodedata.normalize('NFC', unicode(path))
1343
return normalized, normalized == path
1346
778
if _platform_normalizes_filenames:
1347
normalized_filename = _accessible_normalized_filename
779
def unicode_filename(path):
780
"""Make sure 'path' is a properly normalized filename.
782
On platforms where the system normalizes filenames (Mac OSX),
783
you can access a file by any path which will normalize
785
Internally, bzr only supports NFC/NFKC normalization, since
786
that is the standard for XML documents.
787
So we return an normalized path, and indicate this has been
790
:return: (path, is_normalized) Return a path which can
791
access the file, and whether or not this path is
794
return unicodedata.normalize('NFKC', path), True
1349
normalized_filename = _inaccessible_normalized_filename
1352
default_terminal_width = 80
1353
"""The default terminal width for ttys.
1355
This is defined so that higher levels can share a common fallback value when
1356
terminal_width() returns None.
796
def unicode_filename(path):
797
"""Make sure 'path' is a properly normalized filename.
799
On platforms where the system does not normalize filenames
800
(Windows, Linux), you have to access a file by its exact path.
801
Internally, bzr only supports NFC/NFKC normalization, since
802
that is the standard for XML documents.
803
So we return the original path, and indicate if this is
806
:return: (path, is_normalized) Return a path which can
807
access the file, and whether or not this path is
810
return path, unicodedata.normalize('NFKC', path) == path
1360
813
def terminal_width():
1361
"""Return terminal width.
1363
None is returned if the width can't established precisely.
1366
- if BZR_COLUMNS is set, returns its value
1367
- if there is no controlling terminal, returns None
1368
- if COLUMNS is set, returns its value,
1370
From there, we need to query the OS to get the size of the controlling
1374
- get termios.TIOCGWINSZ
1375
- if an error occurs or a negative value is obtained, returns None
1379
- win32utils.get_console_size() decides,
1380
- returns None on error (provided default value)
1383
# If BZR_COLUMNS is set, take it, user is always right
1385
return int(os.environ['BZR_COLUMNS'])
1386
except (KeyError, ValueError):
1389
isatty = getattr(sys.stdout, 'isatty', None)
1390
if isatty is None or not isatty():
1391
# Don't guess, setting BZR_COLUMNS is the recommended way to override.
1394
# If COLUMNS is set, take it, the terminal knows better (even inside a
1395
# given terminal, the application can decide to set COLUMNS to a lower
1396
# value (splitted screen) or a bigger value (scroll bars))
1398
return int(os.environ['COLUMNS'])
1399
except (KeyError, ValueError):
1402
width, height = _terminal_size(None, None)
1404
# Consider invalid values as meaning no width
1410
def _win32_terminal_size(width, height):
1411
width, height = win32utils.get_console_size(defaultx=width, defaulty=height)
1412
return width, height
1415
def _ioctl_terminal_size(width, height):
814
"""Return estimated terminal width."""
815
if sys.platform == 'win32':
816
import bzrlib.win32console
817
return bzrlib.win32console.get_console_size()[0]
1417
820
import struct, fcntl, termios
1418
821
s = struct.pack('HHHH', 0, 0, 0, 0)
1419
822
x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
1420
height, width = struct.unpack('HHHH', x)[0:2]
1421
except (IOError, AttributeError):
823
width = struct.unpack('HHHH', x)[1]
1423
return width, height
1425
_terminal_size = None
1426
"""Returns the terminal size as (width, height).
1428
:param width: Default value for width.
1429
:param height: Default value for height.
1431
This is defined specifically for each OS and query the size of the controlling
1432
terminal. If any error occurs, the provided default values should be returned.
1434
if sys.platform == 'win32':
1435
_terminal_size = _win32_terminal_size
1437
_terminal_size = _ioctl_terminal_size
1440
def _terminal_size_changed(signum, frame):
1441
"""Set COLUMNS upon receiving a SIGnal for WINdow size CHange."""
1442
width, height = _terminal_size(None, None)
1443
if width is not None:
1444
os.environ['COLUMNS'] = str(width)
1447
_registered_sigwinch = False
1449
def watch_sigwinch():
1450
"""Register for SIGWINCH, once and only once."""
1451
global _registered_sigwinch
1452
if not _registered_sigwinch:
1453
if sys.platform == 'win32':
1454
# Martin (gz) mentioned WINDOW_BUFFER_SIZE_RECORD from
1455
# ReadConsoleInput but I've no idea how to plug that in
1456
# the current design -- vila 20091216
828
width = int(os.environ['COLUMNS'])
1459
signal.signal(signal.SIGWINCH, _terminal_size_changed)
1460
_registered_sigwinch = True
1463
836
def supports_executable():
1464
837
return sys.platform != "win32"
1467
def supports_posix_readonly():
1468
"""Return True if 'readonly' has POSIX semantics, False otherwise.
1470
Notably, a win32 readonly file cannot be deleted, unlike POSIX where the
1471
directory controls creation/deletion, etc.
1473
And under win32, readonly means that the directory itself cannot be
1474
deleted. The contents of a readonly directory can be changed, unlike POSIX
1475
where files in readonly directories cannot be added, deleted or renamed.
1477
return sys.platform != "win32"
1480
def set_or_unset_env(env_variable, value):
1481
"""Modify the environment, setting or removing the env_variable.
1483
:param env_variable: The environment variable in question
1484
:param value: The value to set the environment to. If None, then
1485
the variable will be removed.
1486
:return: The original value of the environment variable.
1488
orig_val = os.environ.get(env_variable)
1490
if orig_val is not None:
1491
del os.environ[env_variable]
1493
if isinstance(value, unicode):
1494
value = value.encode(get_user_encoding())
1495
os.environ[env_variable] = value
1499
840
_validWin32PathRE = re.compile(r'^([A-Za-z]:[/\\])?[^:<>*"?\|]*$')
1502
843
def check_legal_path(path):
1503
"""Check whether the supplied path is legal.
844
"""Check whether the supplied path is legal.
1504
845
This is only required on Windows, so we don't test on other platforms
1507
848
if sys.platform != "win32":
1509
850
if _validWin32PathRE.match(path) is None:
1510
raise errors.IllegalPath(path)
1513
_WIN32_ERROR_DIRECTORY = 267 # Similar to errno.ENOTDIR
1515
def _is_error_enotdir(e):
1516
"""Check if this exception represents ENOTDIR.
1518
Unfortunately, python is very inconsistent about the exception
1519
here. The cases are:
1520
1) Linux, Mac OSX all versions seem to set errno == ENOTDIR
1521
2) Windows, Python2.4, uses errno == ERROR_DIRECTORY (267)
1522
which is the windows error code.
1523
3) Windows, Python2.5 uses errno == EINVAL and
1524
winerror == ERROR_DIRECTORY
1526
:param e: An Exception object (expected to be OSError with an errno
1527
attribute, but we should be able to cope with anything)
1528
:return: True if this represents an ENOTDIR error. False otherwise.
1530
en = getattr(e, 'errno', None)
1531
if (en == errno.ENOTDIR
1532
or (sys.platform == 'win32'
1533
and (en == _WIN32_ERROR_DIRECTORY
1534
or (en == errno.EINVAL
1535
and getattr(e, 'winerror', None) == _WIN32_ERROR_DIRECTORY)
851
raise IllegalPath(path)
1541
854
def walkdirs(top, prefix=""):
1542
855
"""Yield data about all the directories in a tree.
1544
857
This yields all the data about the contents of a directory at a time.
1545
858
After each directory has been yielded, if the caller has mutated the list
1546
859
to exclude some directories, they are then not descended into.
1548
861
The data yielded is of the form:
1549
((directory-relpath, directory-path-from-top),
1550
[(relpath, basename, kind, lstat, path-from-top), ...]),
1551
- directory-relpath is the relative path of the directory being returned
1552
with respect to top. prefix is prepended to this.
1553
- directory-path-from-root is the path including top for this directory.
1554
It is suitable for use with os functions.
1555
- relpath is the relative path within the subtree being walked.
1556
- basename is the basename of the path
1557
- kind is the kind of the file now. If unknown then the file is not
1558
present within the tree - but it may be recorded as versioned. See
1560
- lstat is the stat data *if* the file was statted.
1561
- planned, not implemented:
1562
path_from_tree_root is the path from the root of the tree.
862
[(relpath, basename, kind, lstat, path_from_top), ...]
1564
:param prefix: Prefix the relpaths that are yielded with 'prefix'. This
864
:param prefix: Prefix the relpaths that are yielded with 'prefix'. This
1565
865
allows one to walk a subtree but get paths that are relative to a tree
1566
866
rooted higher up.
1567
867
:return: an iterator over the dirs.
1569
#TODO there is a bit of a smell where the results of the directory-
1570
# summary in this, and the path from the root, may not agree
1571
# depending on top and prefix - i.e. ./foo and foo as a pair leads to
1572
# potentially confusing output. We should make this more robust - but
1573
# not at a speed cost. RBC 20060731
1575
871
_directory = _directory_kind
1576
_listdir = os.listdir
1577
_kind_from_mode = file_kind_from_stat_mode
1578
pending = [(safe_unicode(prefix), "", _directory, None, safe_unicode(top))]
873
pending = [(prefix, "", _directory, None, top)]
876
currentdir = pending.pop()
1580
877
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1581
relroot, _, _, _, top = pending.pop()
1583
relprefix = relroot + u'/'
1586
top_slash = top + u'/'
1589
append = dirblock.append
1591
names = sorted(_listdir(top))
1593
if not _is_error_enotdir(e):
1597
abspath = top_slash + name
1598
statvalue = _lstat(abspath)
1599
kind = _kind_from_mode(statvalue.st_mode)
1600
append((relprefix + name, name, kind, statvalue, abspath))
1601
yield (relroot, top), dirblock
1603
# push the user specified dirs from dirblock
1604
pending.extend(d for d in reversed(dirblock) if d[2] == _directory)
1607
class DirReader(object):
1608
"""An interface for reading directories."""
1610
def top_prefix_to_starting_dir(self, top, prefix=""):
1611
"""Converts top and prefix to a starting dir entry
1613
:param top: A utf8 path
1614
:param prefix: An optional utf8 path to prefix output relative paths
1616
:return: A tuple starting with prefix, and ending with the native
1619
raise NotImplementedError(self.top_prefix_to_starting_dir)
1621
def read_dir(self, prefix, top):
1622
"""Read a specific dir.
1624
:param prefix: A utf8 prefix to be preprended to the path basenames.
1625
:param top: A natively encoded path to read.
1626
:return: A list of the directories contents. Each item contains:
1627
(utf8_relpath, utf8_name, kind, lstatvalue, native_abspath)
1629
raise NotImplementedError(self.read_dir)
1632
_selected_dir_reader = None
1635
def _walkdirs_utf8(top, prefix=""):
1636
"""Yield data about all the directories in a tree.
1638
This yields the same information as walkdirs() only each entry is yielded
1639
in utf-8. On platforms which have a filesystem encoding of utf8 the paths
1640
are returned as exact byte-strings.
1642
:return: yields a tuple of (dir_info, [file_info])
1643
dir_info is (utf8_relpath, path-from-top)
1644
file_info is (utf8_relpath, utf8_name, kind, lstat, path-from-top)
1645
if top is an absolute path, path-from-top is also an absolute path.
1646
path-from-top might be unicode or utf8, but it is the correct path to
1647
pass to os functions to affect the file in question. (such as os.lstat)
1649
global _selected_dir_reader
1650
if _selected_dir_reader is None:
1651
fs_encoding = _fs_enc.upper()
1652
if sys.platform == "win32" and win32utils.winver == 'Windows NT':
1653
# Win98 doesn't have unicode apis like FindFirstFileW
1654
# TODO: We possibly could support Win98 by falling back to the
1655
# original FindFirstFile, and using TCHAR instead of WCHAR,
1656
# but that gets a bit tricky, and requires custom compiling
1659
from bzrlib._walkdirs_win32 import Win32ReadDir
1660
_selected_dir_reader = Win32ReadDir()
1663
elif fs_encoding in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
1664
# ANSI_X3.4-1968 is a form of ASCII
1666
from bzrlib._readdir_pyx import UTF8DirReader
1667
_selected_dir_reader = UTF8DirReader()
1668
except ImportError, e:
1669
failed_to_load_extension(e)
1672
if _selected_dir_reader is None:
1673
# Fallback to the python version
1674
_selected_dir_reader = UnicodeDirReader()
1676
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1677
# But we don't actually uses 1-3 in pending, so set them to None
1678
pending = [[_selected_dir_reader.top_prefix_to_starting_dir(top, prefix)]]
1679
read_dir = _selected_dir_reader.read_dir
1680
_directory = _directory_kind
1682
relroot, _, _, _, top = pending[-1].pop()
1685
dirblock = sorted(read_dir(relroot, top))
1686
yield (relroot, top), dirblock
1687
# push the user specified dirs from dirblock
1688
next = [d for d in reversed(dirblock) if d[2] == _directory]
1690
pending.append(next)
1693
class UnicodeDirReader(DirReader):
1694
"""A dir reader for non-utf8 file systems, which transcodes."""
1696
__slots__ = ['_utf8_encode']
1699
self._utf8_encode = codecs.getencoder('utf8')
1701
def top_prefix_to_starting_dir(self, top, prefix=""):
1702
"""See DirReader.top_prefix_to_starting_dir."""
1703
return (safe_utf8(prefix), None, None, None, safe_unicode(top))
1705
def read_dir(self, prefix, top):
1706
"""Read a single directory from a non-utf8 file system.
1708
top, and the abspath element in the output are unicode, all other paths
1709
are utf8. Local disk IO is done via unicode calls to listdir etc.
1711
This is currently the fallback code path when the filesystem encoding is
1712
not UTF-8. It may be better to implement an alternative so that we can
1713
safely handle paths that are not properly decodable in the current
1716
See DirReader.read_dir for details.
1718
_utf8_encode = self._utf8_encode
1720
_listdir = os.listdir
1721
_kind_from_mode = file_kind_from_stat_mode
1724
relprefix = prefix + '/'
1727
top_slash = top + u'/'
1730
append = dirblock.append
880
relroot = currentdir[0] + '/'
1731
883
for name in sorted(_listdir(top)):
1733
name_utf8 = _utf8_encode(name)[0]
1734
except UnicodeDecodeError:
1735
raise errors.BadFilenameEncoding(
1736
_utf8_encode(relprefix)[0] + name, _fs_enc)
1737
abspath = top_slash + name
1738
statvalue = _lstat(abspath)
1739
kind = _kind_from_mode(statvalue.st_mode)
1740
append((relprefix + name_utf8, name_utf8, kind, statvalue, abspath))
1744
def copy_tree(from_path, to_path, handlers={}):
1745
"""Copy all of the entries in from_path into to_path.
1747
:param from_path: The base directory to copy.
1748
:param to_path: The target directory. If it does not exist, it will
1750
:param handlers: A dictionary of functions, which takes a source and
1751
destinations for files, directories, etc.
1752
It is keyed on the file kind, such as 'directory', 'symlink', or 'file'
1753
'file', 'directory', and 'symlink' should always exist.
1754
If they are missing, they will be replaced with 'os.mkdir()',
1755
'os.readlink() + os.symlink()', and 'shutil.copy2()', respectively.
1757
# Now, just copy the existing cached tree to the new location
1758
# We use a cheap trick here.
1759
# Absolute paths are prefixed with the first parameter
1760
# relative paths are prefixed with the second.
1761
# So we can get both the source and target returned
1762
# without any extra work.
1764
def copy_dir(source, dest):
1767
def copy_link(source, dest):
1768
"""Copy the contents of a symlink"""
1769
link_to = os.readlink(source)
1770
os.symlink(link_to, dest)
1772
real_handlers = {'file':shutil.copy2,
1773
'symlink':copy_link,
1774
'directory':copy_dir,
1776
real_handlers.update(handlers)
1778
if not os.path.exists(to_path):
1779
real_handlers['directory'](from_path, to_path)
1781
for dir_info, entries in walkdirs(from_path, prefix=to_path):
1782
for relpath, name, kind, st, abspath in entries:
1783
real_handlers[kind](abspath, relpath)
884
abspath = top + '/' + name
885
statvalue = lstat(abspath)
886
dirblock.append ((relroot + name, name, file_kind_from_stat_mode(statvalue.st_mode), statvalue, abspath))
888
# push the user specified dirs from dirblock
889
for dir in reversed(dirblock):
890
if dir[2] == _directory:
1786
894
def path_prefix_key(path):
1796
904
key_a = path_prefix_key(path_a)
1797
905
key_b = path_prefix_key(path_b)
1798
906
return cmp(key_a, key_b)
1801
_cached_user_encoding = None
1804
def get_user_encoding(use_cache=True):
1805
"""Find out what the preferred user encoding is.
1807
This is generally the encoding that is used for command line parameters
1808
and file contents. This may be different from the terminal encoding
1809
or the filesystem encoding.
1811
:param use_cache: Enable cache for detected encoding.
1812
(This parameter is turned on by default,
1813
and required only for selftesting)
1815
:return: A string defining the preferred user encoding
1817
global _cached_user_encoding
1818
if _cached_user_encoding is not None and use_cache:
1819
return _cached_user_encoding
1821
if sys.platform == 'darwin':
1822
# python locale.getpreferredencoding() always return
1823
# 'mac-roman' on darwin. That's a lie.
1824
sys.platform = 'posix'
1826
if os.environ.get('LANG', None) is None:
1827
# If LANG is not set, we end up with 'ascii', which is bad
1828
# ('mac-roman' is more than ascii), so we set a default which
1829
# will give us UTF-8 (which appears to work in all cases on
1830
# OSX). Users are still free to override LANG of course, as
1831
# long as it give us something meaningful. This work-around
1832
# *may* not be needed with python 3k and/or OSX 10.5, but will
1833
# work with them too -- vila 20080908
1834
os.environ['LANG'] = 'en_US.UTF-8'
1837
sys.platform = 'darwin'
1842
user_encoding = locale.getpreferredencoding()
1843
except locale.Error, e:
1844
sys.stderr.write('bzr: warning: %s\n'
1845
' Could not determine what text encoding to use.\n'
1846
' This error usually means your Python interpreter\n'
1847
' doesn\'t support the locale set by $LANG (%s)\n'
1848
" Continuing with ascii encoding.\n"
1849
% (e, os.environ.get('LANG')))
1850
user_encoding = 'ascii'
1852
# Windows returns 'cp0' to indicate there is no code page. So we'll just
1853
# treat that as ASCII, and not support printing unicode characters to the
1856
# For python scripts run under vim, we get '', so also treat that as ASCII
1857
if user_encoding in (None, 'cp0', ''):
1858
user_encoding = 'ascii'
1862
codecs.lookup(user_encoding)
1864
sys.stderr.write('bzr: warning:'
1865
' unknown encoding %s.'
1866
' Continuing with ascii encoding.\n'
1869
user_encoding = 'ascii'
1872
_cached_user_encoding = user_encoding
1874
return user_encoding
1877
def get_host_name():
1878
"""Return the current unicode host name.
1880
This is meant to be used in place of socket.gethostname() because that
1881
behaves inconsistently on different platforms.
1883
if sys.platform == "win32":
1885
return win32utils.get_host_name()
1888
return socket.gethostname().decode(get_user_encoding())
1891
def recv_all(socket, bytes):
1892
"""Receive an exact number of bytes.
1894
Regular Socket.recv() may return less than the requested number of bytes,
1895
dependning on what's in the OS buffer. MSG_WAITALL is not available
1896
on all platforms, but this should work everywhere. This will return
1897
less than the requested amount if the remote end closes.
1899
This isn't optimized and is intended mostly for use in testing.
1902
while len(b) < bytes:
1903
new = until_no_eintr(socket.recv, bytes - len(b))
1910
def send_all(socket, bytes, report_activity=None):
1911
"""Send all bytes on a socket.
1913
Regular socket.sendall() can give socket error 10053 on Windows. This
1914
implementation sends no more than 64k at a time, which avoids this problem.
1916
:param report_activity: Call this as bytes are read, see
1917
Transport._report_activity
1920
for pos in xrange(0, len(bytes), chunk_size):
1921
block = bytes[pos:pos+chunk_size]
1922
if report_activity is not None:
1923
report_activity(len(block), 'write')
1924
until_no_eintr(socket.sendall, block)
1927
def dereference_path(path):
1928
"""Determine the real path to a file.
1930
All parent elements are dereferenced. But the file itself is not
1932
:param path: The original path. May be absolute or relative.
1933
:return: the real path *to* the file
1935
parent, base = os.path.split(path)
1936
# The pathjoin for '.' is a workaround for Python bug #1213894.
1937
# (initial path components aren't dereferenced)
1938
return pathjoin(realpath(pathjoin('.', parent)), base)
1941
def supports_mapi():
1942
"""Return True if we can use MAPI to launch a mail client."""
1943
return sys.platform == "win32"
1946
def resource_string(package, resource_name):
1947
"""Load a resource from a package and return it as a string.
1949
Note: Only packages that start with bzrlib are currently supported.
1951
This is designed to be a lightweight implementation of resource
1952
loading in a way which is API compatible with the same API from
1954
http://peak.telecommunity.com/DevCenter/PkgResources#basic-resource-access.
1955
If and when pkg_resources becomes a standard library, this routine
1958
# Check package name is within bzrlib
1959
if package == "bzrlib":
1960
resource_relpath = resource_name
1961
elif package.startswith("bzrlib."):
1962
package = package[len("bzrlib."):].replace('.', os.sep)
1963
resource_relpath = pathjoin(package, resource_name)
1965
raise errors.BzrError('resource package %s not in bzrlib' % package)
1967
# Map the resource to a file and read its contents
1968
base = dirname(bzrlib.__file__)
1969
if getattr(sys, 'frozen', None): # bzr.exe
1970
base = abspath(pathjoin(base, '..', '..'))
1971
filename = pathjoin(base, resource_relpath)
1972
return open(filename, 'rU').read()
1975
def file_kind_from_stat_mode_thunk(mode):
1976
global file_kind_from_stat_mode
1977
if file_kind_from_stat_mode is file_kind_from_stat_mode_thunk:
1979
from bzrlib._readdir_pyx import UTF8DirReader
1980
file_kind_from_stat_mode = UTF8DirReader().kind_from_mode
1981
except ImportError, e:
1982
# This is one time where we won't warn that an extension failed to
1983
# load. The extension is never available on Windows anyway.
1984
from bzrlib._readdir_py import (
1985
_kind_from_mode as file_kind_from_stat_mode
1987
return file_kind_from_stat_mode(mode)
1988
file_kind_from_stat_mode = file_kind_from_stat_mode_thunk
1991
def file_kind(f, _lstat=os.lstat):
1993
return file_kind_from_stat_mode(_lstat(f).st_mode)
1995
if getattr(e, 'errno', None) in (errno.ENOENT, errno.ENOTDIR):
1996
raise errors.NoSuchFile(f)
2000
def until_no_eintr(f, *a, **kw):
2001
"""Run f(*a, **kw), retrying if an EINTR error occurs."""
2002
# Borrowed from Twisted's twisted.python.util.untilConcludes function.
2006
except (IOError, OSError), e:
2007
if e.errno == errno.EINTR:
2011
def re_compile_checked(re_string, flags=0, where=""):
2012
"""Return a compiled re, or raise a sensible error.
2014
This should only be used when compiling user-supplied REs.
2016
:param re_string: Text form of regular expression.
2017
:param flags: eg re.IGNORECASE
2018
:param where: Message explaining to the user the context where
2019
it occurred, eg 'log search filter'.
2021
# from https://bugs.launchpad.net/bzr/+bug/251352
2023
re_obj = re.compile(re_string, flags)
2028
where = ' in ' + where
2029
# despite the name 'error' is a type
2030
raise errors.BzrCommandError('Invalid regular expression%s: %r: %s'
2031
% (where, re_string, e))
2034
if sys.platform == "win32":
2037
return msvcrt.getch()
2042
fd = sys.stdin.fileno()
2043
settings = termios.tcgetattr(fd)
2046
ch = sys.stdin.read(1)
2048
termios.tcsetattr(fd, termios.TCSADRAIN, settings)
2052
if sys.platform == 'linux2':
2053
def _local_concurrency():
2055
prefix = 'processor'
2056
for line in file('/proc/cpuinfo', 'rb'):
2057
if line.startswith(prefix):
2058
concurrency = int(line[line.find(':')+1:]) + 1
2060
elif sys.platform == 'darwin':
2061
def _local_concurrency():
2062
return subprocess.Popen(['sysctl', '-n', 'hw.availcpu'],
2063
stdout=subprocess.PIPE).communicate()[0]
2064
elif sys.platform[0:7] == 'freebsd':
2065
def _local_concurrency():
2066
return subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
2067
stdout=subprocess.PIPE).communicate()[0]
2068
elif sys.platform == 'sunos5':
2069
def _local_concurrency():
2070
return subprocess.Popen(['psrinfo', '-p',],
2071
stdout=subprocess.PIPE).communicate()[0]
2072
elif sys.platform == "win32":
2073
def _local_concurrency():
2074
# This appears to return the number of cores.
2075
return os.environ.get('NUMBER_OF_PROCESSORS')
2077
def _local_concurrency():
2082
_cached_local_concurrency = None
2084
def local_concurrency(use_cache=True):
2085
"""Return how many processes can be run concurrently.
2087
Rely on platform specific implementations and default to 1 (one) if
2088
anything goes wrong.
2090
global _cached_local_concurrency
2092
if _cached_local_concurrency is not None and use_cache:
2093
return _cached_local_concurrency
2095
concurrency = os.environ.get('BZR_CONCURRENCY', None)
2096
if concurrency is None:
2098
concurrency = _local_concurrency()
2099
except (OSError, IOError):
2102
concurrency = int(concurrency)
2103
except (TypeError, ValueError):
2106
_cached_concurrency = concurrency
2110
class UnicodeOrBytesToBytesWriter(codecs.StreamWriter):
2111
"""A stream writer that doesn't decode str arguments."""
2113
def __init__(self, encode, stream, errors='strict'):
2114
codecs.StreamWriter.__init__(self, stream, errors)
2115
self.encode = encode
2117
def write(self, object):
2118
if type(object) is str:
2119
self.stream.write(object)
2121
data, _ = self.encode(object, self.errors)
2122
self.stream.write(data)
2124
if sys.platform == 'win32':
2125
def open_file(filename, mode='r', bufsize=-1):
2126
"""This function is used to override the ``open`` builtin.
2128
But it uses O_NOINHERIT flag so the file handle is not inherited by
2129
child processes. Deleting or renaming a closed file opened with this
2130
function is not blocking child processes.
2132
writing = 'w' in mode
2133
appending = 'a' in mode
2134
updating = '+' in mode
2135
binary = 'b' in mode
2138
# see http://msdn.microsoft.com/en-us/library/yeby3zcb%28VS.71%29.aspx
2139
# for flags for each modes.
2149
flags |= os.O_WRONLY
2150
flags |= os.O_CREAT | os.O_TRUNC
2155
flags |= os.O_WRONLY
2156
flags |= os.O_CREAT | os.O_APPEND
2161
flags |= os.O_RDONLY
2163
return os.fdopen(os.open(filename, flags), mode, bufsize)