2012-08-16 00:38:42 +04:00
|
|
|
# util.py - Mercurial utility functions and platform specific implementations
|
2009-04-26 03:13:08 +04:00
|
|
|
#
|
|
|
|
# Copyright 2005 K. Thananchayan <thananck@yahoo.com>
|
|
|
|
# Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
|
|
|
|
# Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com>
|
|
|
|
#
|
|
|
|
# This software may be used and distributed according to the terms of the
|
2010-01-20 07:20:08 +03:00
|
|
|
# GNU General Public License version 2 or any later version.
|
2009-04-26 03:24:49 +04:00
|
|
|
|
2012-08-16 00:38:42 +04:00
|
|
|
"""Mercurial utility functions and platform specific implementations.
|
2009-04-26 03:24:49 +04:00
|
|
|
|
|
|
|
This contains helper routines that are independent of the SCM core and
|
|
|
|
hide platform-specific details from the core.
|
|
|
|
"""
|
2005-06-22 07:31:13 +04:00
|
|
|
|
2014-09-28 18:57:47 +04:00
|
|
|
import i18n
|
|
|
|
_ = i18n._
|
2013-11-07 01:48:06 +04:00
|
|
|
import error, osutil, encoding
|
2014-07-16 01:35:19 +04:00
|
|
|
import errno, shutil, sys, tempfile, traceback
|
|
|
|
import re as remod
|
2013-11-07 01:48:06 +04:00
|
|
|
import os, time, datetime, calendar, textwrap, signal, collections
|
2015-01-11 06:18:31 +03:00
|
|
|
import imp, socket, urllib, struct
|
2014-12-04 16:43:40 +03:00
|
|
|
import gc
|
2006-12-04 01:16:33 +03:00
|
|
|
|
2011-07-21 13:05:26 +04:00
|
|
|
if os.name == 'nt':
|
2011-07-23 14:29:52 +04:00
|
|
|
import windows as platform
|
2011-07-21 13:05:26 +04:00
|
|
|
else:
|
2011-07-23 14:29:52 +04:00
|
|
|
import posix as platform
|
|
|
|
|
2011-07-25 16:03:02 +04:00
|
|
|
cachestat = platform.cachestat
|
2011-07-23 14:29:52 +04:00
|
|
|
checkexec = platform.checkexec
|
|
|
|
checklink = platform.checklink
|
2011-08-02 15:18:56 +04:00
|
|
|
copymode = platform.copymode
|
2011-07-23 14:29:52 +04:00
|
|
|
executablepath = platform.executablepath
|
|
|
|
expandglobs = platform.expandglobs
|
|
|
|
explainexit = platform.explainexit
|
|
|
|
findexe = platform.findexe
|
|
|
|
gethgcmd = platform.gethgcmd
|
|
|
|
getuser = platform.getuser
|
|
|
|
groupmembers = platform.groupmembers
|
|
|
|
groupname = platform.groupname
|
|
|
|
hidewindow = platform.hidewindow
|
|
|
|
isexec = platform.isexec
|
|
|
|
isowner = platform.isowner
|
|
|
|
localpath = platform.localpath
|
|
|
|
lookupreg = platform.lookupreg
|
|
|
|
makedir = platform.makedir
|
|
|
|
nlinks = platform.nlinks
|
|
|
|
normpath = platform.normpath
|
2011-11-16 00:25:11 +04:00
|
|
|
normcase = platform.normcase
|
2011-07-23 14:29:52 +04:00
|
|
|
openhardlinks = platform.openhardlinks
|
|
|
|
oslink = platform.oslink
|
|
|
|
parsepatchoutput = platform.parsepatchoutput
|
|
|
|
pconvert = platform.pconvert
|
|
|
|
popen = platform.popen
|
|
|
|
posixfile = platform.posixfile
|
|
|
|
quotecommand = platform.quotecommand
|
2014-08-16 07:02:18 +04:00
|
|
|
readpipe = platform.readpipe
|
2011-07-23 14:29:52 +04:00
|
|
|
rename = platform.rename
|
|
|
|
samedevice = platform.samedevice
|
|
|
|
samefile = platform.samefile
|
|
|
|
samestat = platform.samestat
|
|
|
|
setbinary = platform.setbinary
|
|
|
|
setflags = platform.setflags
|
|
|
|
setsignalhandler = platform.setsignalhandler
|
|
|
|
shellquote = platform.shellquote
|
|
|
|
spawndetached = platform.spawndetached
|
2012-09-14 23:08:17 +04:00
|
|
|
split = platform.split
|
2011-07-23 14:29:52 +04:00
|
|
|
sshargs = platform.sshargs
|
2012-12-04 00:40:24 +04:00
|
|
|
statfiles = getattr(osutil, 'statfiles', platform.statfiles)
|
2013-04-03 22:35:27 +04:00
|
|
|
statisexec = platform.statisexec
|
|
|
|
statislink = platform.statislink
|
2011-07-23 14:29:52 +04:00
|
|
|
termwidth = platform.termwidth
|
|
|
|
testpid = platform.testpid
|
|
|
|
umask = platform.umask
|
|
|
|
unlink = platform.unlink
|
|
|
|
unlinkpath = platform.unlinkpath
|
|
|
|
username = platform.username
|
2011-07-21 13:05:26 +04:00
|
|
|
|
2008-04-05 00:36:40 +04:00
|
|
|
# Python compatibility
|
|
|
|
|
2011-12-16 00:59:22 +04:00
|
|
|
_notset = object()
|
|
|
|
|
|
|
|
def safehasattr(thing, attr):
|
|
|
|
return getattr(thing, attr, _notset) is not _notset
|
|
|
|
|
2011-10-31 23:22:11 +04:00
|
|
|
def sha1(s=''):
|
2011-11-01 00:41:39 +04:00
|
|
|
'''
|
|
|
|
Low-overhead wrapper around Python's SHA support
|
|
|
|
|
|
|
|
>>> f = _fastsha1
|
|
|
|
>>> a = sha1()
|
|
|
|
>>> a = f()
|
|
|
|
>>> a.hexdigest()
|
|
|
|
'da39a3ee5e6b4b0d3255bfef95601890afd80709'
|
|
|
|
'''
|
|
|
|
|
2009-05-05 00:14:52 +04:00
|
|
|
return _fastsha1(s)
|
|
|
|
|
2011-10-31 23:22:11 +04:00
|
|
|
def _fastsha1(s=''):
|
2009-05-05 00:14:52 +04:00
|
|
|
# This function will import sha1 from hashlib or sha (whichever is
|
|
|
|
# available) and overwrite itself with it on the first call.
|
|
|
|
# Subsequent calls will go directly to the imported function.
|
2010-08-18 02:38:19 +04:00
|
|
|
if sys.version_info >= (2, 5):
|
2009-05-05 00:14:52 +04:00
|
|
|
from hashlib import sha1 as _sha1
|
2010-08-18 02:38:19 +04:00
|
|
|
else:
|
2009-05-04 22:29:05 +04:00
|
|
|
from sha import sha as _sha1
|
2009-05-08 11:59:15 +04:00
|
|
|
global _fastsha1, sha1
|
|
|
|
_fastsha1 = sha1 = _sha1
|
2008-04-05 00:36:40 +04:00
|
|
|
return _sha1(s)
|
|
|
|
|
2014-09-24 11:00:47 +04:00
|
|
|
def md5(s=''):
|
|
|
|
try:
|
|
|
|
from hashlib import md5 as _md5
|
|
|
|
except ImportError:
|
|
|
|
from md5 import md5 as _md5
|
|
|
|
global md5
|
|
|
|
md5 = _md5
|
|
|
|
return _md5(s)
|
|
|
|
|
2014-10-16 12:02:51 +04:00
|
|
|
DIGESTS = {
|
|
|
|
'md5': md5,
|
|
|
|
'sha1': sha1,
|
|
|
|
}
|
|
|
|
# List of digest types from strongest to weakest
|
|
|
|
DIGESTS_BY_STRENGTH = ['sha1', 'md5']
|
|
|
|
|
|
|
|
try:
|
|
|
|
import hashlib
|
|
|
|
DIGESTS.update({
|
|
|
|
'sha512': hashlib.sha512,
|
|
|
|
})
|
|
|
|
DIGESTS_BY_STRENGTH.insert(0, 'sha512')
|
|
|
|
except ImportError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
for k in DIGESTS_BY_STRENGTH:
|
|
|
|
assert k in DIGESTS
|
|
|
|
|
|
|
|
class digester(object):
|
|
|
|
"""helper to compute digests.
|
|
|
|
|
|
|
|
This helper can be used to compute one or more digests given their name.
|
|
|
|
|
|
|
|
>>> d = digester(['md5', 'sha1'])
|
|
|
|
>>> d.update('foo')
|
|
|
|
>>> [k for k in sorted(d)]
|
|
|
|
['md5', 'sha1']
|
|
|
|
>>> d['md5']
|
|
|
|
'acbd18db4cc2f85cedef654fccc4a4d8'
|
|
|
|
>>> d['sha1']
|
|
|
|
'0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33'
|
|
|
|
>>> digester.preferred(['md5', 'sha1'])
|
|
|
|
'sha1'
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, digests, s=''):
|
|
|
|
self._hashes = {}
|
|
|
|
for k in digests:
|
|
|
|
if k not in DIGESTS:
|
|
|
|
raise Abort(_('unknown digest type: %s') % k)
|
|
|
|
self._hashes[k] = DIGESTS[k]()
|
|
|
|
if s:
|
|
|
|
self.update(s)
|
|
|
|
|
|
|
|
def update(self, data):
|
|
|
|
for h in self._hashes.values():
|
|
|
|
h.update(data)
|
|
|
|
|
|
|
|
def __getitem__(self, key):
|
|
|
|
if key not in DIGESTS:
|
|
|
|
raise Abort(_('unknown digest type: %s') % k)
|
|
|
|
return self._hashes[key].hexdigest()
|
|
|
|
|
|
|
|
def __iter__(self):
|
|
|
|
return iter(self._hashes)
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def preferred(supported):
|
|
|
|
"""returns the strongest digest type in both supported and DIGESTS."""
|
|
|
|
|
|
|
|
for k in DIGESTS_BY_STRENGTH:
|
|
|
|
if k in supported:
|
|
|
|
return k
|
|
|
|
return None
|
|
|
|
|
2014-10-16 12:03:21 +04:00
|
|
|
class digestchecker(object):
|
|
|
|
"""file handle wrapper that additionally checks content against a given
|
|
|
|
size and digests.
|
|
|
|
|
|
|
|
d = digestchecker(fh, size, {'md5': '...'})
|
|
|
|
|
|
|
|
When multiple digests are given, all of them are validated.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, fh, size, digests):
|
|
|
|
self._fh = fh
|
|
|
|
self._size = size
|
|
|
|
self._got = 0
|
|
|
|
self._digests = dict(digests)
|
|
|
|
self._digester = digester(self._digests.keys())
|
|
|
|
|
|
|
|
def read(self, length=-1):
|
|
|
|
content = self._fh.read(length)
|
|
|
|
self._digester.update(content)
|
|
|
|
self._got += len(content)
|
|
|
|
return content
|
|
|
|
|
|
|
|
def validate(self):
|
|
|
|
if self._size != self._got:
|
|
|
|
raise Abort(_('size mismatch: expected %d, got %d') %
|
|
|
|
(self._size, self._got))
|
|
|
|
for k, v in self._digests.items():
|
|
|
|
if v != self._digester[k]:
|
2014-10-23 18:35:10 +04:00
|
|
|
# i18n: first parameter is a digest name
|
2014-10-16 12:03:21 +04:00
|
|
|
raise Abort(_('%s mismatch: expected %s, got %s') %
|
|
|
|
(k, v, self._digester[k]))
|
|
|
|
|
2010-07-15 05:59:43 +04:00
|
|
|
try:
|
2011-12-16 01:27:11 +04:00
|
|
|
buffer = buffer
|
2010-07-15 05:59:43 +04:00
|
|
|
except NameError:
|
2011-12-16 01:27:11 +04:00
|
|
|
if sys.version_info[0] < 3:
|
|
|
|
def buffer(sliceable, offset=0):
|
|
|
|
return sliceable[offset:]
|
|
|
|
else:
|
|
|
|
def buffer(sliceable, offset=0):
|
|
|
|
return memoryview(sliceable)[offset:]
|
2010-03-23 13:36:19 +03:00
|
|
|
|
2009-05-03 01:05:35 +04:00
|
|
|
import subprocess
|
|
|
|
closefds = os.name == 'posix'
|
2010-01-02 18:03:25 +03:00
|
|
|
|
2015-01-11 06:18:31 +03:00
|
|
|
def unpacker(fmt):
|
|
|
|
"""create a struct unpacker for the specified format"""
|
|
|
|
try:
|
|
|
|
# 2.5+
|
|
|
|
return struct.Struct(fmt).unpack
|
2015-01-14 03:15:02 +03:00
|
|
|
except AttributeError:
|
2015-01-11 06:18:31 +03:00
|
|
|
# 2.4
|
2015-01-15 03:57:00 +03:00
|
|
|
return lambda buf: struct.unpack(fmt, buf)
|
2015-01-11 06:18:31 +03:00
|
|
|
|
2010-01-02 18:42:00 +03:00
|
|
|
def popen2(cmd, env=None, newlines=False):
|
2009-07-09 13:59:18 +04:00
|
|
|
# Setting bufsize to -1 lets the system decide the buffer size.
|
|
|
|
# The default for bufsize is 0, meaning unbuffered. This leads to
|
|
|
|
# poor performance on Mac OS X: http://bugs.python.org/issue4194
|
|
|
|
p = subprocess.Popen(cmd, shell=True, bufsize=-1,
|
2009-07-09 04:01:18 +04:00
|
|
|
close_fds=closefds,
|
2010-01-02 18:03:25 +03:00
|
|
|
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
2010-01-02 18:42:00 +03:00
|
|
|
universal_newlines=newlines,
|
|
|
|
env=env)
|
2009-05-03 01:05:35 +04:00
|
|
|
return p.stdin, p.stdout
|
2010-01-02 18:03:25 +03:00
|
|
|
|
2010-01-02 18:42:00 +03:00
|
|
|
def popen3(cmd, env=None, newlines=False):
|
2013-03-09 04:59:36 +04:00
|
|
|
stdin, stdout, stderr, p = popen4(cmd, env, newlines)
|
|
|
|
return stdin, stdout, stderr
|
|
|
|
|
|
|
|
def popen4(cmd, env=None, newlines=False):
|
2009-07-09 13:59:18 +04:00
|
|
|
p = subprocess.Popen(cmd, shell=True, bufsize=-1,
|
2009-07-09 04:01:18 +04:00
|
|
|
close_fds=closefds,
|
2009-05-03 01:05:35 +04:00
|
|
|
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
2010-01-02 18:03:25 +03:00
|
|
|
stderr=subprocess.PIPE,
|
2010-01-02 18:42:00 +03:00
|
|
|
universal_newlines=newlines,
|
|
|
|
env=env)
|
2013-03-09 04:59:36 +04:00
|
|
|
return p.stdin, p.stdout, p.stderr, p
|
2008-10-05 23:35:26 +04:00
|
|
|
|
2009-01-11 03:02:38 +03:00
|
|
|
def version():
|
|
|
|
"""Return version information if available."""
|
|
|
|
try:
|
|
|
|
import __version__
|
|
|
|
return __version__.version
|
|
|
|
except ImportError:
|
|
|
|
return 'unknown'
|
|
|
|
|
2006-07-13 20:40:01 +04:00
|
|
|
# used by parsedate
|
2006-12-06 22:13:31 +03:00
|
|
|
defaultdateformats = (
|
|
|
|
'%Y-%m-%d %H:%M:%S',
|
|
|
|
'%Y-%m-%d %I:%M:%S%p',
|
|
|
|
'%Y-%m-%d %H:%M',
|
|
|
|
'%Y-%m-%d %I:%M%p',
|
|
|
|
'%Y-%m-%d',
|
|
|
|
'%m-%d',
|
|
|
|
'%m/%d',
|
|
|
|
'%m/%d/%y',
|
|
|
|
'%m/%d/%Y',
|
|
|
|
'%a %b %d %H:%M:%S %Y',
|
|
|
|
'%a %b %d %I:%M:%S%p %Y',
|
2007-06-25 16:46:20 +04:00
|
|
|
'%a, %d %b %Y %H:%M:%S', # GNU coreutils "/bin/date --rfc-2822"
|
2006-12-06 22:13:31 +03:00
|
|
|
'%b %d %H:%M:%S %Y',
|
2006-12-07 00:11:44 +03:00
|
|
|
'%b %d %I:%M:%S%p %Y',
|
|
|
|
'%b %d %H:%M:%S',
|
2006-12-06 22:13:31 +03:00
|
|
|
'%b %d %I:%M:%S%p',
|
|
|
|
'%b %d %H:%M',
|
|
|
|
'%b %d %I:%M%p',
|
|
|
|
'%b %d %Y',
|
|
|
|
'%b %d',
|
|
|
|
'%H:%M:%S',
|
2009-08-21 13:52:57 +04:00
|
|
|
'%I:%M:%S%p',
|
2006-12-06 22:13:31 +03:00
|
|
|
'%H:%M',
|
|
|
|
'%I:%M%p',
|
|
|
|
)
|
2006-07-13 20:40:01 +04:00
|
|
|
|
2006-12-07 00:11:44 +03:00
|
|
|
extendeddateformats = defaultdateformats + (
|
|
|
|
"%Y",
|
|
|
|
"%Y-%m",
|
|
|
|
"%b",
|
|
|
|
"%b %Y",
|
|
|
|
)
|
|
|
|
|
2006-09-22 19:19:25 +04:00
|
|
|
def cachefunc(func):
|
|
|
|
'''cache the result of function calls'''
|
2006-09-22 19:58:22 +04:00
|
|
|
# XXX doesn't handle keywords args
|
2014-02-15 14:52:26 +04:00
|
|
|
if func.func_code.co_argcount == 0:
|
|
|
|
cache = []
|
|
|
|
def f():
|
|
|
|
if len(cache) == 0:
|
|
|
|
cache.append(func())
|
|
|
|
return cache[0]
|
|
|
|
return f
|
2006-09-22 19:19:25 +04:00
|
|
|
cache = {}
|
|
|
|
if func.func_code.co_argcount == 1:
|
2006-09-22 19:58:22 +04:00
|
|
|
# we gain a small amount of time because
|
|
|
|
# we don't need to pack/unpack the list
|
2006-09-22 19:19:25 +04:00
|
|
|
def f(arg):
|
|
|
|
if arg not in cache:
|
|
|
|
cache[arg] = func(arg)
|
|
|
|
return cache[arg]
|
|
|
|
else:
|
|
|
|
def f(*args):
|
|
|
|
if args not in cache:
|
|
|
|
cache[args] = func(*args)
|
|
|
|
return cache[args]
|
|
|
|
|
|
|
|
return f
|
|
|
|
|
2012-06-02 04:05:31 +04:00
|
|
|
try:
|
|
|
|
collections.deque.remove
|
|
|
|
deque = collections.deque
|
|
|
|
except AttributeError:
|
|
|
|
# python 2.4 lacks deque.remove
|
|
|
|
class deque(collections.deque):
|
|
|
|
def remove(self, val):
|
|
|
|
for i, v in enumerate(self):
|
|
|
|
if v == val:
|
|
|
|
del self[i]
|
|
|
|
break
|
|
|
|
|
2014-02-23 04:56:31 +04:00
|
|
|
class sortdict(dict):
|
|
|
|
'''a simple sorted dictionary'''
|
|
|
|
def __init__(self, data=None):
|
|
|
|
self._list = []
|
|
|
|
if data:
|
|
|
|
self.update(data)
|
|
|
|
def copy(self):
|
|
|
|
return sortdict(self)
|
|
|
|
def __setitem__(self, key, val):
|
|
|
|
if key in self:
|
|
|
|
self._list.remove(key)
|
|
|
|
self._list.append(key)
|
|
|
|
dict.__setitem__(self, key, val)
|
|
|
|
def __iter__(self):
|
|
|
|
return self._list.__iter__()
|
|
|
|
def update(self, src):
|
|
|
|
for k in src:
|
|
|
|
self[k] = src[k]
|
|
|
|
def clear(self):
|
|
|
|
dict.clear(self)
|
|
|
|
self._list = []
|
|
|
|
def items(self):
|
|
|
|
return [(k, self[k]) for k in self._list]
|
|
|
|
def __delitem__(self, key):
|
|
|
|
dict.__delitem__(self, key)
|
|
|
|
self._list.remove(key)
|
2014-10-02 21:39:37 +04:00
|
|
|
def pop(self, key, *args, **kwargs):
|
|
|
|
dict.pop(self, key, *args, **kwargs)
|
|
|
|
try:
|
|
|
|
self._list.remove(key)
|
|
|
|
except ValueError:
|
|
|
|
pass
|
2014-02-23 04:56:31 +04:00
|
|
|
def keys(self):
|
|
|
|
return self._list
|
|
|
|
def iterkeys(self):
|
|
|
|
return self._list.__iter__()
|
2014-11-10 00:15:28 +03:00
|
|
|
def iteritems(self):
|
|
|
|
for k in self._list:
|
|
|
|
yield k, self[k]
|
2014-10-15 23:39:19 +04:00
|
|
|
def insert(self, index, key, val):
|
|
|
|
self._list.insert(index, key)
|
|
|
|
dict.__setitem__(self, key, val)
|
2014-02-23 04:56:31 +04:00
|
|
|
|
2013-02-09 19:41:46 +04:00
|
|
|
class lrucachedict(object):
|
|
|
|
'''cache most recent gets from or sets to this dictionary'''
|
|
|
|
def __init__(self, maxsize):
|
|
|
|
self._cache = {}
|
|
|
|
self._maxsize = maxsize
|
|
|
|
self._order = deque()
|
|
|
|
|
|
|
|
def __getitem__(self, key):
|
|
|
|
value = self._cache[key]
|
|
|
|
self._order.remove(key)
|
|
|
|
self._order.append(key)
|
|
|
|
return value
|
|
|
|
|
|
|
|
def __setitem__(self, key, value):
|
|
|
|
if key not in self._cache:
|
|
|
|
if len(self._cache) >= self._maxsize:
|
|
|
|
del self._cache[self._order.popleft()]
|
|
|
|
else:
|
|
|
|
self._order.remove(key)
|
|
|
|
self._cache[key] = value
|
|
|
|
self._order.append(key)
|
|
|
|
|
|
|
|
def __contains__(self, key):
|
|
|
|
return key in self._cache
|
|
|
|
|
2013-09-07 00:16:21 +04:00
|
|
|
def clear(self):
|
|
|
|
self._cache.clear()
|
|
|
|
self._order = deque()
|
|
|
|
|
2009-07-10 02:10:07 +04:00
|
|
|
def lrucachefunc(func):
|
|
|
|
'''cache most recent results of function calls'''
|
|
|
|
cache = {}
|
2012-06-02 04:05:31 +04:00
|
|
|
order = deque()
|
2009-07-10 02:10:07 +04:00
|
|
|
if func.func_code.co_argcount == 1:
|
|
|
|
def f(arg):
|
|
|
|
if arg not in cache:
|
|
|
|
if len(cache) > 20:
|
2012-05-15 21:46:23 +04:00
|
|
|
del cache[order.popleft()]
|
2009-07-10 02:10:07 +04:00
|
|
|
cache[arg] = func(arg)
|
|
|
|
else:
|
|
|
|
order.remove(arg)
|
|
|
|
order.append(arg)
|
|
|
|
return cache[arg]
|
|
|
|
else:
|
|
|
|
def f(*args):
|
|
|
|
if args not in cache:
|
|
|
|
if len(cache) > 20:
|
2012-05-15 21:46:23 +04:00
|
|
|
del cache[order.popleft()]
|
2009-07-10 02:10:07 +04:00
|
|
|
cache[args] = func(*args)
|
|
|
|
else:
|
|
|
|
order.remove(args)
|
|
|
|
order.append(args)
|
|
|
|
return cache[args]
|
|
|
|
|
|
|
|
return f
|
|
|
|
|
2009-04-27 01:50:44 +04:00
|
|
|
class propertycache(object):
|
|
|
|
def __init__(self, func):
|
|
|
|
self.func = func
|
|
|
|
self.name = func.__name__
|
|
|
|
def __get__(self, obj, type=None):
|
|
|
|
result = self.func(obj)
|
2012-10-08 22:02:20 +04:00
|
|
|
self.cachevalue(obj, result)
|
2009-04-27 01:50:44 +04:00
|
|
|
return result
|
|
|
|
|
2012-10-08 22:02:20 +04:00
|
|
|
def cachevalue(self, obj, value):
|
2013-10-23 21:49:56 +04:00
|
|
|
# __dict__ assignment required to bypass __setattr__ (eg: repoview)
|
2013-09-30 16:36:11 +04:00
|
|
|
obj.__dict__[self.name] = value
|
2012-10-08 22:02:20 +04:00
|
|
|
|
2005-09-21 22:44:08 +04:00
|
|
|
def pipefilter(s, cmd):
|
|
|
|
'''filter string S through command CMD, returning its output'''
|
2009-05-07 03:33:44 +04:00
|
|
|
p = subprocess.Popen(cmd, shell=True, close_fds=closefds,
|
|
|
|
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
|
|
|
|
pout, perr = p.communicate(s)
|
|
|
|
return pout
|
2005-06-22 07:31:13 +04:00
|
|
|
|
2005-09-21 22:44:08 +04:00
|
|
|
def tempfilter(s, cmd):
|
|
|
|
'''filter string S through a pair of temporary files with CMD.
|
|
|
|
CMD is used as a template to create the real command to be run,
|
|
|
|
with the strings INFILE and OUTFILE replaced by the real names of
|
|
|
|
the temporary files generated.'''
|
|
|
|
inname, outname = None, None
|
|
|
|
try:
|
2006-04-30 23:11:22 +04:00
|
|
|
infd, inname = tempfile.mkstemp(prefix='hg-filter-in-')
|
2005-09-21 22:44:08 +04:00
|
|
|
fp = os.fdopen(infd, 'wb')
|
|
|
|
fp.write(s)
|
|
|
|
fp.close()
|
2006-04-30 23:11:22 +04:00
|
|
|
outfd, outname = tempfile.mkstemp(prefix='hg-filter-out-')
|
2005-09-21 22:44:08 +04:00
|
|
|
os.close(outfd)
|
|
|
|
cmd = cmd.replace('INFILE', inname)
|
|
|
|
cmd = cmd.replace('OUTFILE', outname)
|
|
|
|
code = os.system(cmd)
|
2007-06-08 18:24:43 +04:00
|
|
|
if sys.platform == 'OpenVMS' and code & 1:
|
|
|
|
code = 0
|
2010-01-25 09:05:27 +03:00
|
|
|
if code:
|
|
|
|
raise Abort(_("command '%s' failed: %s") %
|
2011-05-06 17:31:09 +04:00
|
|
|
(cmd, explainexit(code)))
|
2010-12-24 17:23:01 +03:00
|
|
|
fp = open(outname, 'rb')
|
|
|
|
r = fp.read()
|
|
|
|
fp.close()
|
|
|
|
return r
|
2005-09-21 22:44:08 +04:00
|
|
|
finally:
|
|
|
|
try:
|
2010-01-25 09:05:27 +03:00
|
|
|
if inname:
|
|
|
|
os.unlink(inname)
|
2011-04-23 01:51:25 +04:00
|
|
|
except OSError:
|
2010-01-25 09:05:27 +03:00
|
|
|
pass
|
2005-09-21 22:44:08 +04:00
|
|
|
try:
|
2010-01-25 09:05:27 +03:00
|
|
|
if outname:
|
|
|
|
os.unlink(outname)
|
2011-04-23 01:51:25 +04:00
|
|
|
except OSError:
|
2010-01-25 09:05:27 +03:00
|
|
|
pass
|
2005-09-21 22:44:08 +04:00
|
|
|
|
|
|
|
filtertable = {
|
|
|
|
'tempfile:': tempfilter,
|
|
|
|
'pipe:': pipefilter,
|
|
|
|
}
|
|
|
|
|
|
|
|
def filter(s, cmd):
|
|
|
|
"filter a string through a command that transforms its input to its output"
|
|
|
|
for name, fn in filtertable.iteritems():
|
|
|
|
if cmd.startswith(name):
|
|
|
|
return fn(s, cmd[len(name):].lstrip())
|
|
|
|
return pipefilter(s, cmd)
|
|
|
|
|
2005-08-24 06:58:46 +04:00
|
|
|
def binary(s):
|
2008-04-08 15:19:36 +04:00
|
|
|
"""return true if a string is binary data"""
|
2009-04-22 19:14:58 +04:00
|
|
|
return bool(s and '\0' in s)
|
2005-08-24 06:58:46 +04:00
|
|
|
|
2008-11-22 02:51:40 +03:00
|
|
|
def increasingchunks(source, min=1024, max=65536):
|
|
|
|
'''return no less than min bytes per chunk while data remains,
|
|
|
|
doubling min after each chunk until it reaches max'''
|
|
|
|
def log2(x):
|
|
|
|
if not x:
|
|
|
|
return 0
|
|
|
|
i = 0
|
|
|
|
while x:
|
|
|
|
x >>= 1
|
|
|
|
i += 1
|
|
|
|
return i - 1
|
|
|
|
|
|
|
|
buf = []
|
|
|
|
blen = 0
|
|
|
|
for chunk in source:
|
|
|
|
buf.append(chunk)
|
|
|
|
blen += len(chunk)
|
|
|
|
if blen >= min:
|
|
|
|
if min < max:
|
|
|
|
min = min << 1
|
|
|
|
nmin = 1 << log2(blen)
|
|
|
|
if nmin > min:
|
|
|
|
min = nmin
|
|
|
|
if min > max:
|
|
|
|
min = max
|
|
|
|
yield ''.join(buf)
|
|
|
|
blen = 0
|
|
|
|
buf = []
|
|
|
|
if buf:
|
|
|
|
yield ''.join(buf)
|
|
|
|
|
2009-04-03 22:20:52 +04:00
|
|
|
Abort = error.Abort
|
2005-06-28 14:38:33 +04:00
|
|
|
|
2010-01-25 09:05:27 +03:00
|
|
|
def always(fn):
|
|
|
|
return True
|
|
|
|
|
|
|
|
def never(fn):
|
|
|
|
return False
|
2005-07-18 18:54:21 +04:00
|
|
|
|
2014-12-04 16:43:40 +03:00
|
|
|
def nogc(func):
|
|
|
|
"""disable garbage collector
|
|
|
|
|
|
|
|
Python's garbage collector triggers a GC each time a certain number of
|
|
|
|
container objects (the number being defined by gc.get_threshold()) are
|
|
|
|
allocated even when marked not to be tracked by the collector. Tracking has
|
|
|
|
no effect on when GCs are triggered, only on what objects the GC looks
|
2014-04-18 00:47:38 +04:00
|
|
|
into. As a workaround, disable GC while building complex (huge)
|
2014-12-04 16:43:40 +03:00
|
|
|
containers.
|
|
|
|
|
|
|
|
This garbage collector issue have been fixed in 2.7.
|
|
|
|
"""
|
|
|
|
def wrapper(*args, **kwargs):
|
|
|
|
gcenabled = gc.isenabled()
|
|
|
|
gc.disable()
|
|
|
|
try:
|
|
|
|
return func(*args, **kwargs)
|
|
|
|
finally:
|
|
|
|
if gcenabled:
|
|
|
|
gc.enable()
|
|
|
|
return wrapper
|
|
|
|
|
2007-03-16 06:22:57 +03:00
|
|
|
def pathto(root, n1, n2):
|
2005-08-13 03:06:52 +04:00
|
|
|
'''return the relative path from one place to another.
|
2007-03-16 06:22:57 +03:00
|
|
|
root should use os.sep to separate directories
|
2006-11-15 23:56:47 +03:00
|
|
|
n1 should use os.sep to separate directories
|
|
|
|
n2 should use "/" to separate directories
|
|
|
|
returns an os.sep-separated path.
|
2007-03-16 06:22:57 +03:00
|
|
|
|
|
|
|
If n1 is a relative path, it's assumed it's
|
|
|
|
relative to root.
|
|
|
|
n2 should always be relative to root.
|
2006-11-15 23:56:47 +03:00
|
|
|
'''
|
2010-01-25 09:05:27 +03:00
|
|
|
if not n1:
|
|
|
|
return localpath(n2)
|
2007-03-16 06:22:58 +03:00
|
|
|
if os.path.isabs(n1):
|
|
|
|
if os.path.splitdrive(root)[0] != os.path.splitdrive(n1)[0]:
|
|
|
|
return os.path.join(root, localpath(n2))
|
|
|
|
n2 = '/'.join((pconvert(root), n2))
|
2008-01-09 15:30:36 +03:00
|
|
|
a, b = splitpath(n1), n2.split('/')
|
2005-11-14 04:59:35 +03:00
|
|
|
a.reverse()
|
|
|
|
b.reverse()
|
2005-08-12 23:16:58 +04:00
|
|
|
while a and b and a[-1] == b[-1]:
|
2005-11-14 04:59:35 +03:00
|
|
|
a.pop()
|
|
|
|
b.pop()
|
2005-08-12 23:16:58 +04:00
|
|
|
b.reverse()
|
2008-02-15 15:38:37 +03:00
|
|
|
return os.sep.join((['..'] * len(a)) + b) or '.'
|
2005-08-12 23:16:58 +04:00
|
|
|
|
2011-05-06 17:10:29 +04:00
|
|
|
def mainfrozen():
|
2007-12-20 23:02:51 +03:00
|
|
|
"""return True if we are a frozen executable.
|
|
|
|
|
|
|
|
The code supports py2exe (most common, Windows only) and tools/freeze
|
|
|
|
(portable, not much used).
|
|
|
|
"""
|
2011-07-26 01:04:40 +04:00
|
|
|
return (safehasattr(sys, "frozen") or # new py2exe
|
|
|
|
safehasattr(sys, "importers") or # old py2exe
|
2007-12-20 23:02:51 +03:00
|
|
|
imp.is_frozen("__main__")) # tools/freeze
|
|
|
|
|
2014-09-28 18:57:06 +04:00
|
|
|
# the location of data files matching the source code
|
|
|
|
if mainfrozen():
|
|
|
|
# executable version (py2exe) doesn't support __file__
|
|
|
|
datapath = os.path.dirname(sys.executable)
|
|
|
|
else:
|
|
|
|
datapath = os.path.dirname(__file__)
|
|
|
|
|
2014-09-28 18:57:47 +04:00
|
|
|
i18n.setdatapath(datapath)
|
|
|
|
|
2014-09-28 18:57:06 +04:00
|
|
|
_hgexecutable = None
|
|
|
|
|
2007-08-05 00:25:12 +04:00
|
|
|
def hgexecutable():
|
|
|
|
"""return location of the 'hg' executable.
|
2007-06-23 22:21:10 +04:00
|
|
|
|
2007-08-05 00:25:12 +04:00
|
|
|
Defaults to $HG or 'hg' in the search path.
|
2007-06-23 22:21:10 +04:00
|
|
|
"""
|
2007-08-05 00:25:12 +04:00
|
|
|
if _hgexecutable is None:
|
2008-04-10 02:27:57 +04:00
|
|
|
hg = os.environ.get('HG')
|
2011-07-23 08:18:18 +04:00
|
|
|
mainmod = sys.modules['__main__']
|
2008-04-10 02:27:57 +04:00
|
|
|
if hg:
|
2011-05-06 17:13:46 +04:00
|
|
|
_sethgexecutable(hg)
|
2011-05-06 17:10:29 +04:00
|
|
|
elif mainfrozen():
|
2011-05-06 17:13:46 +04:00
|
|
|
_sethgexecutable(sys.executable)
|
2011-07-23 08:18:18 +04:00
|
|
|
elif os.path.basename(getattr(mainmod, '__file__', '')) == 'hg':
|
|
|
|
_sethgexecutable(mainmod.__file__)
|
2007-12-20 23:02:51 +03:00
|
|
|
else:
|
2011-05-08 22:35:46 +04:00
|
|
|
exe = findexe('hg') or os.path.basename(sys.argv[0])
|
2011-05-06 17:13:46 +04:00
|
|
|
_sethgexecutable(exe)
|
2007-08-05 00:25:12 +04:00
|
|
|
return _hgexecutable
|
|
|
|
|
2011-05-06 17:13:46 +04:00
|
|
|
def _sethgexecutable(path):
|
2007-08-05 00:25:12 +04:00
|
|
|
"""set location of the 'hg' executable"""
|
2007-06-23 22:21:10 +04:00
|
|
|
global _hgexecutable
|
2007-08-05 00:25:12 +04:00
|
|
|
_hgexecutable = path
|
2007-06-23 22:21:10 +04:00
|
|
|
|
2010-07-01 03:15:23 +04:00
|
|
|
def system(cmd, environ={}, cwd=None, onerr=None, errprefix=None, out=None):
|
2006-03-11 09:24:19 +03:00
|
|
|
'''enhanced shell command execution.
|
2006-03-11 09:42:59 +03:00
|
|
|
run with environment maybe modified, maybe in different dir.
|
|
|
|
|
2014-11-08 07:14:19 +03:00
|
|
|
if command fails and onerr is None, return status, else raise onerr
|
|
|
|
object as exception.
|
2010-07-01 03:15:23 +04:00
|
|
|
|
|
|
|
if out is specified, it is assumed to be a file-like object that has a
|
|
|
|
write() method. stdout and stderr will be redirected to out.'''
|
2011-02-18 05:35:01 +03:00
|
|
|
try:
|
|
|
|
sys.stdout.flush()
|
|
|
|
except Exception:
|
|
|
|
pass
|
2006-07-12 19:59:20 +04:00
|
|
|
def py2shell(val):
|
|
|
|
'convert python object into string that is useful to shell'
|
2009-05-20 12:50:23 +04:00
|
|
|
if val is None or val is False:
|
2006-07-12 19:59:20 +04:00
|
|
|
return '0'
|
2009-05-20 12:50:23 +04:00
|
|
|
if val is True:
|
2006-07-12 19:59:20 +04:00
|
|
|
return '1'
|
|
|
|
return str(val)
|
2006-12-16 07:38:18 +03:00
|
|
|
origcmd = cmd
|
2010-12-22 22:25:00 +03:00
|
|
|
cmd = quotecommand(cmd)
|
2013-09-14 00:40:04 +04:00
|
|
|
if sys.platform == 'plan9' and (sys.version_info[0] == 2
|
|
|
|
and sys.version_info[1] < 7):
|
2012-04-08 23:43:41 +04:00
|
|
|
# subprocess kludge to work around issues in half-baked Python
|
|
|
|
# ports, notably bichued/python:
|
|
|
|
if not cwd is None:
|
|
|
|
os.chdir(cwd)
|
|
|
|
rc = os.system(cmd)
|
2010-07-01 03:15:23 +04:00
|
|
|
else:
|
2012-04-08 23:43:41 +04:00
|
|
|
env = dict(os.environ)
|
|
|
|
env.update((k, py2shell(v)) for k, v in environ.iteritems())
|
|
|
|
env['HG'] = hgexecutable()
|
|
|
|
if out is None or out == sys.__stdout__:
|
|
|
|
rc = subprocess.call(cmd, shell=True, close_fds=closefds,
|
|
|
|
env=env, cwd=cwd)
|
|
|
|
else:
|
|
|
|
proc = subprocess.Popen(cmd, shell=True, close_fds=closefds,
|
|
|
|
env=env, cwd=cwd, stdout=subprocess.PIPE,
|
|
|
|
stderr=subprocess.STDOUT)
|
2014-08-30 19:38:14 +04:00
|
|
|
while True:
|
|
|
|
line = proc.stdout.readline()
|
|
|
|
if not line:
|
|
|
|
break
|
2012-04-08 23:43:41 +04:00
|
|
|
out.write(line)
|
|
|
|
proc.wait()
|
|
|
|
rc = proc.returncode
|
|
|
|
if sys.platform == 'OpenVMS' and rc & 1:
|
|
|
|
rc = 0
|
2009-09-21 00:19:18 +04:00
|
|
|
if rc and onerr:
|
|
|
|
errmsg = '%s %s' % (os.path.basename(origcmd.split(None, 1)[0]),
|
2011-05-06 17:31:09 +04:00
|
|
|
explainexit(rc)[0])
|
2009-09-21 00:19:18 +04:00
|
|
|
if errprefix:
|
|
|
|
errmsg = '%s: %s' % (errprefix, errmsg)
|
2014-11-08 07:14:19 +03:00
|
|
|
raise onerr(errmsg)
|
2009-09-21 00:19:18 +04:00
|
|
|
return rc
|
2005-06-28 14:38:33 +04:00
|
|
|
|
2008-11-19 01:02:14 +03:00
|
|
|
def checksignature(func):
|
|
|
|
'''wrap a function with code to check for calling errors'''
|
|
|
|
def check(*args, **kwargs):
|
|
|
|
try:
|
|
|
|
return func(*args, **kwargs)
|
|
|
|
except TypeError:
|
|
|
|
if len(traceback.extract_tb(sys.exc_info()[2])) == 1:
|
2009-01-12 22:51:43 +03:00
|
|
|
raise error.SignatureError
|
2008-11-19 01:02:14 +03:00
|
|
|
raise
|
|
|
|
|
|
|
|
return check
|
|
|
|
|
2015-01-05 23:39:09 +03:00
|
|
|
def copyfile(src, dest, hardlink=False):
|
2009-02-09 16:55:42 +03:00
|
|
|
"copy a file, preserving mode and atime/mtime"
|
2013-01-10 03:44:23 +04:00
|
|
|
if os.path.lexists(dest):
|
|
|
|
unlink(dest)
|
2015-01-05 23:39:09 +03:00
|
|
|
if hardlink:
|
|
|
|
try:
|
|
|
|
oslink(src, dest)
|
|
|
|
return
|
|
|
|
except (IOError, OSError):
|
|
|
|
pass # fall back to normal copy
|
2007-03-22 06:20:56 +03:00
|
|
|
if os.path.islink(src):
|
|
|
|
os.symlink(os.readlink(src), dest)
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
shutil.copyfile(src, dest)
|
2010-12-07 12:03:05 +03:00
|
|
|
shutil.copymode(src, dest)
|
2007-03-22 06:20:56 +03:00
|
|
|
except shutil.Error, inst:
|
|
|
|
raise Abort(str(inst))
|
2006-11-13 22:26:57 +03:00
|
|
|
|
Add support for cloning with hardlinks on windows.
In order to use hardlinks, the win32file module is needed, and this is
present in ActivePython. If it isn't present, or hardlinks are not supported
on the underlying filesystem, a regular copy is used.
When using hardlinks the biggest benefit is probably the saving in space,
but cloning can be much quicker. For example cloning the Xen tree
(non trivial) without an update goes from about 95s to 15s.
Unix-like platforms should be unaffected, although should be more tolerant on
filesystems that don't support hard links.
(tweaked by mpm to deal with new copyfiles function)
--- hg.orig/mercurial/commands.py 2005-09-13 19:32:53.000000000 -0500
+++ hg/mercurial/commands.py 2005-09-14 12:11:34.000000000 -0500
@@ -620,10 +620,6 @@ def clone(ui, source, dest=None, **opts)
if other.dev() != -1:
abspath = os.path.abspath(source)
- copyfile = (os.stat(dest).st_dev == other.dev()
- and getattr(os, 'link', None) or shutil.copy2)
- if copyfile is not shutil.copy2:
- ui.note("cloning by hardlink\n")
# we use a lock here because if we race with commit, we can
# end up with extra data in the cloned revlogs that's not
@@ -638,7 +634,7 @@ def clone(ui, source, dest=None, **opts)
for f in files.split():
src = os.path.join(source, ".hg", f)
dst = os.path.join(dest, ".hg", f)
- util.copyfiles(src, dst, copyfile)
+ util.copyfiles(src, dst)
repo = hg.repository(ui, dest)
Index: hg/mercurial/util.py
===================================================================
--- hg.orig/mercurial/util.py 2005-09-08 00:15:25.000000000 -0500
+++ hg/mercurial/util.py 2005-09-14 12:16:49.000000000 -0500
@@ -12,7 +12,7 @@ platform-specific details from the core.
import os, errno
from demandload import *
-demandload(globals(), "re cStringIO")
+demandload(globals(), "re cStringIO shutil")
def binary(s):
"""return true if a string is binary data using diff's heuristic"""
@@ -217,17 +217,28 @@ def rename(src, dst):
os.unlink(dst)
os.rename(src, dst)
-def copyfiles(src, dst, copyfile):
- """Copy a directory tree, files are copied using 'copyfile'."""
+def copyfiles(src, dst, hardlink=None):
+ """Copy a directory tree using hardlinks if possible"""
+
+ if hardlink is None:
+ hardlink = (os.stat(src).st_dev ==
+ os.stat(os.path.dirname(dst)).st_dev)
if os.path.isdir(src):
os.mkdir(dst)
for name in os.listdir(src):
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
- copyfiles(srcname, dstname, copyfile)
+ copyfiles(srcname, dstname, hardlink)
else:
- copyfile(src, dst)
+ if hardlink:
+ try:
+ os_link(src, dst)
+ except:
+ hardlink = False
+ shutil.copy2(src, dst)
+ else:
+ shutil.copy2(src, dst)
def opener(base):
"""
@@ -244,13 +255,13 @@ def opener(base):
if mode[0] != "r":
try:
- s = os.stat(f)
+ nlink = nlinks(f)
except OSError:
d = os.path.dirname(f)
if not os.path.isdir(d):
os.makedirs(d)
else:
- if s.st_nlink > 1:
+ if nlink > 1:
file(f + ".tmp", "wb").write(file(f, "rb").read())
rename(f+".tmp", f)
@@ -266,10 +277,41 @@ def _makelock_file(info, pathname):
def _readlock_file(pathname):
return file(pathname).read()
+def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ return os.stat(pathname).st_nlink
+
+if hasattr(os, 'link'):
+ os_link = os.link
+else:
+ def os_link(src, dst):
+ raise OSError(0, "Hardlinks not supported")
+
# Platform specific variants
if os.name == 'nt':
nulldev = 'NUL:'
+ try: # ActivePython can create hard links using win32file module
+ import win32file
+
+ def os_link(src, dst): # NB will only succeed on NTFS
+ win32file.CreateHardLink(dst, src)
+
+ def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ try:
+ fh = win32file.CreateFile(pathname,
+ win32file.GENERIC_READ, win32file.FILE_SHARE_READ,
+ None, win32file.OPEN_EXISTING, 0, None)
+ res = win32file.GetFileInformationByHandle(fh)
+ fh.Close()
+ return res[7]
+ except:
+ return os.stat(pathname).st_nlink
+
+ except ImportError:
+ pass
+
def is_exec(f, last):
return last
2005-09-14 21:22:20 +04:00
|
|
|
def copyfiles(src, dst, hardlink=None):
|
|
|
|
"""Copy a directory tree using hardlinks if possible"""
|
|
|
|
|
|
|
|
if hardlink is None:
|
|
|
|
hardlink = (os.stat(src).st_dev ==
|
|
|
|
os.stat(os.path.dirname(dst)).st_dev)
|
2005-09-08 06:21:38 +04:00
|
|
|
|
2010-05-31 15:47:51 +04:00
|
|
|
num = 0
|
2005-09-08 06:21:38 +04:00
|
|
|
if os.path.isdir(src):
|
|
|
|
os.mkdir(dst)
|
2007-10-06 02:01:06 +04:00
|
|
|
for name, kind in osutil.listdir(src):
|
2005-09-08 06:21:38 +04:00
|
|
|
srcname = os.path.join(src, name)
|
|
|
|
dstname = os.path.join(dst, name)
|
2010-05-31 15:47:51 +04:00
|
|
|
hardlink, n = copyfiles(srcname, dstname, hardlink)
|
|
|
|
num += n
|
2005-09-08 06:21:38 +04:00
|
|
|
else:
|
Add support for cloning with hardlinks on windows.
In order to use hardlinks, the win32file module is needed, and this is
present in ActivePython. If it isn't present, or hardlinks are not supported
on the underlying filesystem, a regular copy is used.
When using hardlinks the biggest benefit is probably the saving in space,
but cloning can be much quicker. For example cloning the Xen tree
(non trivial) without an update goes from about 95s to 15s.
Unix-like platforms should be unaffected, although should be more tolerant on
filesystems that don't support hard links.
(tweaked by mpm to deal with new copyfiles function)
--- hg.orig/mercurial/commands.py 2005-09-13 19:32:53.000000000 -0500
+++ hg/mercurial/commands.py 2005-09-14 12:11:34.000000000 -0500
@@ -620,10 +620,6 @@ def clone(ui, source, dest=None, **opts)
if other.dev() != -1:
abspath = os.path.abspath(source)
- copyfile = (os.stat(dest).st_dev == other.dev()
- and getattr(os, 'link', None) or shutil.copy2)
- if copyfile is not shutil.copy2:
- ui.note("cloning by hardlink\n")
# we use a lock here because if we race with commit, we can
# end up with extra data in the cloned revlogs that's not
@@ -638,7 +634,7 @@ def clone(ui, source, dest=None, **opts)
for f in files.split():
src = os.path.join(source, ".hg", f)
dst = os.path.join(dest, ".hg", f)
- util.copyfiles(src, dst, copyfile)
+ util.copyfiles(src, dst)
repo = hg.repository(ui, dest)
Index: hg/mercurial/util.py
===================================================================
--- hg.orig/mercurial/util.py 2005-09-08 00:15:25.000000000 -0500
+++ hg/mercurial/util.py 2005-09-14 12:16:49.000000000 -0500
@@ -12,7 +12,7 @@ platform-specific details from the core.
import os, errno
from demandload import *
-demandload(globals(), "re cStringIO")
+demandload(globals(), "re cStringIO shutil")
def binary(s):
"""return true if a string is binary data using diff's heuristic"""
@@ -217,17 +217,28 @@ def rename(src, dst):
os.unlink(dst)
os.rename(src, dst)
-def copyfiles(src, dst, copyfile):
- """Copy a directory tree, files are copied using 'copyfile'."""
+def copyfiles(src, dst, hardlink=None):
+ """Copy a directory tree using hardlinks if possible"""
+
+ if hardlink is None:
+ hardlink = (os.stat(src).st_dev ==
+ os.stat(os.path.dirname(dst)).st_dev)
if os.path.isdir(src):
os.mkdir(dst)
for name in os.listdir(src):
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
- copyfiles(srcname, dstname, copyfile)
+ copyfiles(srcname, dstname, hardlink)
else:
- copyfile(src, dst)
+ if hardlink:
+ try:
+ os_link(src, dst)
+ except:
+ hardlink = False
+ shutil.copy2(src, dst)
+ else:
+ shutil.copy2(src, dst)
def opener(base):
"""
@@ -244,13 +255,13 @@ def opener(base):
if mode[0] != "r":
try:
- s = os.stat(f)
+ nlink = nlinks(f)
except OSError:
d = os.path.dirname(f)
if not os.path.isdir(d):
os.makedirs(d)
else:
- if s.st_nlink > 1:
+ if nlink > 1:
file(f + ".tmp", "wb").write(file(f, "rb").read())
rename(f+".tmp", f)
@@ -266,10 +277,41 @@ def _makelock_file(info, pathname):
def _readlock_file(pathname):
return file(pathname).read()
+def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ return os.stat(pathname).st_nlink
+
+if hasattr(os, 'link'):
+ os_link = os.link
+else:
+ def os_link(src, dst):
+ raise OSError(0, "Hardlinks not supported")
+
# Platform specific variants
if os.name == 'nt':
nulldev = 'NUL:'
+ try: # ActivePython can create hard links using win32file module
+ import win32file
+
+ def os_link(src, dst): # NB will only succeed on NTFS
+ win32file.CreateHardLink(dst, src)
+
+ def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ try:
+ fh = win32file.CreateFile(pathname,
+ win32file.GENERIC_READ, win32file.FILE_SHARE_READ,
+ None, win32file.OPEN_EXISTING, 0, None)
+ res = win32file.GetFileInformationByHandle(fh)
+ fh.Close()
+ return res[7]
+ except:
+ return os.stat(pathname).st_nlink
+
+ except ImportError:
+ pass
+
def is_exec(f, last):
return last
2005-09-14 21:22:20 +04:00
|
|
|
if hardlink:
|
|
|
|
try:
|
2011-05-06 17:34:34 +04:00
|
|
|
oslink(src, dst)
|
2006-04-06 04:17:07 +04:00
|
|
|
except (IOError, OSError):
|
Add support for cloning with hardlinks on windows.
In order to use hardlinks, the win32file module is needed, and this is
present in ActivePython. If it isn't present, or hardlinks are not supported
on the underlying filesystem, a regular copy is used.
When using hardlinks the biggest benefit is probably the saving in space,
but cloning can be much quicker. For example cloning the Xen tree
(non trivial) without an update goes from about 95s to 15s.
Unix-like platforms should be unaffected, although should be more tolerant on
filesystems that don't support hard links.
(tweaked by mpm to deal with new copyfiles function)
--- hg.orig/mercurial/commands.py 2005-09-13 19:32:53.000000000 -0500
+++ hg/mercurial/commands.py 2005-09-14 12:11:34.000000000 -0500
@@ -620,10 +620,6 @@ def clone(ui, source, dest=None, **opts)
if other.dev() != -1:
abspath = os.path.abspath(source)
- copyfile = (os.stat(dest).st_dev == other.dev()
- and getattr(os, 'link', None) or shutil.copy2)
- if copyfile is not shutil.copy2:
- ui.note("cloning by hardlink\n")
# we use a lock here because if we race with commit, we can
# end up with extra data in the cloned revlogs that's not
@@ -638,7 +634,7 @@ def clone(ui, source, dest=None, **opts)
for f in files.split():
src = os.path.join(source, ".hg", f)
dst = os.path.join(dest, ".hg", f)
- util.copyfiles(src, dst, copyfile)
+ util.copyfiles(src, dst)
repo = hg.repository(ui, dest)
Index: hg/mercurial/util.py
===================================================================
--- hg.orig/mercurial/util.py 2005-09-08 00:15:25.000000000 -0500
+++ hg/mercurial/util.py 2005-09-14 12:16:49.000000000 -0500
@@ -12,7 +12,7 @@ platform-specific details from the core.
import os, errno
from demandload import *
-demandload(globals(), "re cStringIO")
+demandload(globals(), "re cStringIO shutil")
def binary(s):
"""return true if a string is binary data using diff's heuristic"""
@@ -217,17 +217,28 @@ def rename(src, dst):
os.unlink(dst)
os.rename(src, dst)
-def copyfiles(src, dst, copyfile):
- """Copy a directory tree, files are copied using 'copyfile'."""
+def copyfiles(src, dst, hardlink=None):
+ """Copy a directory tree using hardlinks if possible"""
+
+ if hardlink is None:
+ hardlink = (os.stat(src).st_dev ==
+ os.stat(os.path.dirname(dst)).st_dev)
if os.path.isdir(src):
os.mkdir(dst)
for name in os.listdir(src):
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
- copyfiles(srcname, dstname, copyfile)
+ copyfiles(srcname, dstname, hardlink)
else:
- copyfile(src, dst)
+ if hardlink:
+ try:
+ os_link(src, dst)
+ except:
+ hardlink = False
+ shutil.copy2(src, dst)
+ else:
+ shutil.copy2(src, dst)
def opener(base):
"""
@@ -244,13 +255,13 @@ def opener(base):
if mode[0] != "r":
try:
- s = os.stat(f)
+ nlink = nlinks(f)
except OSError:
d = os.path.dirname(f)
if not os.path.isdir(d):
os.makedirs(d)
else:
- if s.st_nlink > 1:
+ if nlink > 1:
file(f + ".tmp", "wb").write(file(f, "rb").read())
rename(f+".tmp", f)
@@ -266,10 +277,41 @@ def _makelock_file(info, pathname):
def _readlock_file(pathname):
return file(pathname).read()
+def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ return os.stat(pathname).st_nlink
+
+if hasattr(os, 'link'):
+ os_link = os.link
+else:
+ def os_link(src, dst):
+ raise OSError(0, "Hardlinks not supported")
+
# Platform specific variants
if os.name == 'nt':
nulldev = 'NUL:'
+ try: # ActivePython can create hard links using win32file module
+ import win32file
+
+ def os_link(src, dst): # NB will only succeed on NTFS
+ win32file.CreateHardLink(dst, src)
+
+ def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ try:
+ fh = win32file.CreateFile(pathname,
+ win32file.GENERIC_READ, win32file.FILE_SHARE_READ,
+ None, win32file.OPEN_EXISTING, 0, None)
+ res = win32file.GetFileInformationByHandle(fh)
+ fh.Close()
+ return res[7]
+ except:
+ return os.stat(pathname).st_nlink
+
+ except ImportError:
+ pass
+
def is_exec(f, last):
return last
2005-09-14 21:22:20 +04:00
|
|
|
hardlink = False
|
2005-12-16 10:32:44 +03:00
|
|
|
shutil.copy(src, dst)
|
Add support for cloning with hardlinks on windows.
In order to use hardlinks, the win32file module is needed, and this is
present in ActivePython. If it isn't present, or hardlinks are not supported
on the underlying filesystem, a regular copy is used.
When using hardlinks the biggest benefit is probably the saving in space,
but cloning can be much quicker. For example cloning the Xen tree
(non trivial) without an update goes from about 95s to 15s.
Unix-like platforms should be unaffected, although should be more tolerant on
filesystems that don't support hard links.
(tweaked by mpm to deal with new copyfiles function)
--- hg.orig/mercurial/commands.py 2005-09-13 19:32:53.000000000 -0500
+++ hg/mercurial/commands.py 2005-09-14 12:11:34.000000000 -0500
@@ -620,10 +620,6 @@ def clone(ui, source, dest=None, **opts)
if other.dev() != -1:
abspath = os.path.abspath(source)
- copyfile = (os.stat(dest).st_dev == other.dev()
- and getattr(os, 'link', None) or shutil.copy2)
- if copyfile is not shutil.copy2:
- ui.note("cloning by hardlink\n")
# we use a lock here because if we race with commit, we can
# end up with extra data in the cloned revlogs that's not
@@ -638,7 +634,7 @@ def clone(ui, source, dest=None, **opts)
for f in files.split():
src = os.path.join(source, ".hg", f)
dst = os.path.join(dest, ".hg", f)
- util.copyfiles(src, dst, copyfile)
+ util.copyfiles(src, dst)
repo = hg.repository(ui, dest)
Index: hg/mercurial/util.py
===================================================================
--- hg.orig/mercurial/util.py 2005-09-08 00:15:25.000000000 -0500
+++ hg/mercurial/util.py 2005-09-14 12:16:49.000000000 -0500
@@ -12,7 +12,7 @@ platform-specific details from the core.
import os, errno
from demandload import *
-demandload(globals(), "re cStringIO")
+demandload(globals(), "re cStringIO shutil")
def binary(s):
"""return true if a string is binary data using diff's heuristic"""
@@ -217,17 +217,28 @@ def rename(src, dst):
os.unlink(dst)
os.rename(src, dst)
-def copyfiles(src, dst, copyfile):
- """Copy a directory tree, files are copied using 'copyfile'."""
+def copyfiles(src, dst, hardlink=None):
+ """Copy a directory tree using hardlinks if possible"""
+
+ if hardlink is None:
+ hardlink = (os.stat(src).st_dev ==
+ os.stat(os.path.dirname(dst)).st_dev)
if os.path.isdir(src):
os.mkdir(dst)
for name in os.listdir(src):
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
- copyfiles(srcname, dstname, copyfile)
+ copyfiles(srcname, dstname, hardlink)
else:
- copyfile(src, dst)
+ if hardlink:
+ try:
+ os_link(src, dst)
+ except:
+ hardlink = False
+ shutil.copy2(src, dst)
+ else:
+ shutil.copy2(src, dst)
def opener(base):
"""
@@ -244,13 +255,13 @@ def opener(base):
if mode[0] != "r":
try:
- s = os.stat(f)
+ nlink = nlinks(f)
except OSError:
d = os.path.dirname(f)
if not os.path.isdir(d):
os.makedirs(d)
else:
- if s.st_nlink > 1:
+ if nlink > 1:
file(f + ".tmp", "wb").write(file(f, "rb").read())
rename(f+".tmp", f)
@@ -266,10 +277,41 @@ def _makelock_file(info, pathname):
def _readlock_file(pathname):
return file(pathname).read()
+def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ return os.stat(pathname).st_nlink
+
+if hasattr(os, 'link'):
+ os_link = os.link
+else:
+ def os_link(src, dst):
+ raise OSError(0, "Hardlinks not supported")
+
# Platform specific variants
if os.name == 'nt':
nulldev = 'NUL:'
+ try: # ActivePython can create hard links using win32file module
+ import win32file
+
+ def os_link(src, dst): # NB will only succeed on NTFS
+ win32file.CreateHardLink(dst, src)
+
+ def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ try:
+ fh = win32file.CreateFile(pathname,
+ win32file.GENERIC_READ, win32file.FILE_SHARE_READ,
+ None, win32file.OPEN_EXISTING, 0, None)
+ res = win32file.GetFileInformationByHandle(fh)
+ fh.Close()
+ return res[7]
+ except:
+ return os.stat(pathname).st_nlink
+
+ except ImportError:
+ pass
+
def is_exec(f, last):
return last
2005-09-14 21:22:20 +04:00
|
|
|
else:
|
2005-12-16 10:32:44 +03:00
|
|
|
shutil.copy(src, dst)
|
2010-05-31 15:47:51 +04:00
|
|
|
num += 1
|
2005-07-14 18:30:49 +04:00
|
|
|
|
2010-05-31 15:47:51 +04:00
|
|
|
return hardlink, num
|
2010-05-28 19:28:34 +04:00
|
|
|
|
2011-05-08 00:25:20 +04:00
|
|
|
_winreservednames = '''con prn aux nul
|
2011-04-06 20:09:43 +04:00
|
|
|
com1 com2 com3 com4 com5 com6 com7 com8 com9
|
|
|
|
lpt1 lpt2 lpt3 lpt4 lpt5 lpt6 lpt7 lpt8 lpt9'''.split()
|
2011-05-08 00:25:20 +04:00
|
|
|
_winreservedchars = ':*?"<>|'
|
2011-04-06 20:09:43 +04:00
|
|
|
def checkwinfilename(path):
|
2013-11-08 15:35:50 +04:00
|
|
|
r'''Check that the base-relative path is a valid filename on Windows.
|
2011-04-06 20:09:43 +04:00
|
|
|
Returns None if the path is ok, or a UI string describing the problem.
|
|
|
|
|
|
|
|
>>> checkwinfilename("just/a/normal/path")
|
|
|
|
>>> checkwinfilename("foo/bar/con.xml")
|
|
|
|
"filename contains 'con', which is reserved on Windows"
|
|
|
|
>>> checkwinfilename("foo/con.xml/bar")
|
|
|
|
"filename contains 'con', which is reserved on Windows"
|
|
|
|
>>> checkwinfilename("foo/bar/xml.con")
|
|
|
|
>>> checkwinfilename("foo/bar/AUX/bla.txt")
|
|
|
|
"filename contains 'AUX', which is reserved on Windows"
|
|
|
|
>>> checkwinfilename("foo/bar/bla:.txt")
|
|
|
|
"filename contains ':', which is reserved on Windows"
|
|
|
|
>>> checkwinfilename("foo/bar/b\07la.txt")
|
2013-11-08 15:35:50 +04:00
|
|
|
"filename contains '\\x07', which is invalid on Windows"
|
2011-04-06 20:09:43 +04:00
|
|
|
>>> checkwinfilename("foo/bar/bla ")
|
|
|
|
"filename ends with ' ', which is not allowed on Windows"
|
2011-10-25 01:57:14 +04:00
|
|
|
>>> checkwinfilename("../bar")
|
2013-11-08 15:35:50 +04:00
|
|
|
>>> checkwinfilename("foo\\")
|
|
|
|
"filename ends with '\\', which is invalid on Windows"
|
|
|
|
>>> checkwinfilename("foo\\/bar")
|
|
|
|
"directory name ends with '\\', which is invalid on Windows"
|
2011-04-06 20:09:43 +04:00
|
|
|
'''
|
2013-11-08 15:35:50 +04:00
|
|
|
if path.endswith('\\'):
|
|
|
|
return _("filename ends with '\\', which is invalid on Windows")
|
|
|
|
if '\\/' in path:
|
|
|
|
return _("directory name ends with '\\', which is invalid on Windows")
|
2011-04-06 20:09:43 +04:00
|
|
|
for n in path.replace('\\', '/').split('/'):
|
|
|
|
if not n:
|
|
|
|
continue
|
|
|
|
for c in n:
|
2011-05-08 00:25:20 +04:00
|
|
|
if c in _winreservedchars:
|
2011-04-06 20:09:43 +04:00
|
|
|
return _("filename contains '%s', which is reserved "
|
|
|
|
"on Windows") % c
|
|
|
|
if ord(c) <= 31:
|
2011-04-16 22:08:43 +04:00
|
|
|
return _("filename contains %r, which is invalid "
|
2011-04-06 20:09:43 +04:00
|
|
|
"on Windows") % c
|
|
|
|
base = n.split('.')[0]
|
2011-05-08 00:25:20 +04:00
|
|
|
if base and base.lower() in _winreservednames:
|
2011-04-06 20:09:43 +04:00
|
|
|
return _("filename contains '%s', which is reserved "
|
|
|
|
"on Windows") % base
|
|
|
|
t = n[-1]
|
2011-10-25 01:57:14 +04:00
|
|
|
if t in '. ' and n not in '..':
|
2011-04-06 20:09:43 +04:00
|
|
|
return _("filename ends with '%s', which is not allowed "
|
|
|
|
"on Windows") % t
|
|
|
|
|
2009-03-26 21:54:44 +03:00
|
|
|
if os.name == 'nt':
|
2011-04-06 20:09:43 +04:00
|
|
|
checkosfilename = checkwinfilename
|
2011-07-23 14:29:52 +04:00
|
|
|
else:
|
|
|
|
checkosfilename = platform.checkosfilename
|
2009-03-26 21:54:44 +03:00
|
|
|
|
|
|
|
def makelock(info, pathname):
|
|
|
|
try:
|
|
|
|
return os.symlink(info, pathname)
|
|
|
|
except OSError, why:
|
|
|
|
if why.errno == errno.EEXIST:
|
|
|
|
raise
|
|
|
|
except AttributeError: # no symlink in os
|
|
|
|
pass
|
|
|
|
|
2005-07-15 01:51:47 +04:00
|
|
|
ld = os.open(pathname, os.O_CREAT | os.O_WRONLY | os.O_EXCL)
|
|
|
|
os.write(ld, info)
|
|
|
|
os.close(ld)
|
|
|
|
|
2009-03-26 21:54:44 +03:00
|
|
|
def readlock(pathname):
|
|
|
|
try:
|
|
|
|
return os.readlink(pathname)
|
|
|
|
except OSError, why:
|
|
|
|
if why.errno not in (errno.EINVAL, errno.ENOSYS):
|
|
|
|
raise
|
|
|
|
except AttributeError: # no symlink in os
|
|
|
|
pass
|
2010-12-24 17:23:01 +03:00
|
|
|
fp = posixfile(pathname)
|
|
|
|
r = fp.read()
|
|
|
|
fp.close()
|
|
|
|
return r
|
2005-07-15 01:51:47 +04:00
|
|
|
|
2006-05-03 01:30:00 +04:00
|
|
|
def fstat(fp):
|
|
|
|
'''stat file object that may not have fileno method.'''
|
|
|
|
try:
|
|
|
|
return os.fstat(fp.fileno())
|
|
|
|
except AttributeError:
|
|
|
|
return os.stat(fp.name)
|
|
|
|
|
2006-12-05 02:10:29 +03:00
|
|
|
# File system features
|
|
|
|
|
2008-06-26 22:58:24 +04:00
|
|
|
def checkcase(path):
|
2006-12-05 02:10:29 +03:00
|
|
|
"""
|
2013-02-11 03:43:12 +04:00
|
|
|
Return true if the given path is on a case-sensitive filesystem
|
2006-12-05 02:10:29 +03:00
|
|
|
|
|
|
|
Requires a path (like /foo/.hg) ending with a foldable final
|
|
|
|
directory component.
|
|
|
|
"""
|
|
|
|
s1 = os.stat(path)
|
|
|
|
d, b = os.path.split(path)
|
2011-12-16 16:09:40 +04:00
|
|
|
b2 = b.upper()
|
|
|
|
if b == b2:
|
|
|
|
b2 = b.lower()
|
|
|
|
if b == b2:
|
|
|
|
return True # no evidence against case sensitivity
|
|
|
|
p2 = os.path.join(d, b2)
|
2006-12-05 02:10:29 +03:00
|
|
|
try:
|
|
|
|
s2 = os.stat(p2)
|
|
|
|
if s2 == s1:
|
|
|
|
return False
|
|
|
|
return True
|
2011-04-23 01:51:25 +04:00
|
|
|
except OSError:
|
2006-12-05 02:10:29 +03:00
|
|
|
return True
|
|
|
|
|
2012-06-02 02:26:20 +04:00
|
|
|
try:
|
|
|
|
import re2
|
|
|
|
_re2 = None
|
|
|
|
except ImportError:
|
|
|
|
_re2 = False
|
|
|
|
|
2014-07-16 01:40:43 +04:00
|
|
|
class _re(object):
|
2014-07-16 02:01:52 +04:00
|
|
|
def _checkre2(self):
|
|
|
|
global _re2
|
|
|
|
try:
|
|
|
|
# check if match works, see issue3964
|
|
|
|
_re2 = bool(re2.match(r'\[([^\[]+)\]', '[ui]'))
|
|
|
|
except ImportError:
|
|
|
|
_re2 = False
|
|
|
|
|
2014-07-16 01:40:43 +04:00
|
|
|
def compile(self, pat, flags=0):
|
|
|
|
'''Compile a regular expression, using re2 if possible
|
|
|
|
|
|
|
|
For best performance, use only re2-compatible regexp features. The
|
|
|
|
only flags from the re module that are re2-compatible are
|
|
|
|
IGNORECASE and MULTILINE.'''
|
|
|
|
if _re2 is None:
|
2014-07-16 02:01:52 +04:00
|
|
|
self._checkre2()
|
2014-07-16 01:40:43 +04:00
|
|
|
if _re2 and (flags & ~(remod.IGNORECASE | remod.MULTILINE)) == 0:
|
|
|
|
if flags & remod.IGNORECASE:
|
|
|
|
pat = '(?i)' + pat
|
|
|
|
if flags & remod.MULTILINE:
|
|
|
|
pat = '(?m)' + pat
|
|
|
|
try:
|
|
|
|
return re2.compile(pat)
|
|
|
|
except re2.error:
|
|
|
|
pass
|
|
|
|
return remod.compile(pat, flags)
|
|
|
|
|
2014-07-16 02:14:45 +04:00
|
|
|
@propertycache
|
|
|
|
def escape(self):
|
|
|
|
'''Return the version of escape corresponding to self.compile.
|
|
|
|
|
|
|
|
This is imperfect because whether re2 or re is used for a particular
|
|
|
|
function depends on the flags, etc, but it's the best we can do.
|
|
|
|
'''
|
|
|
|
global _re2
|
|
|
|
if _re2 is None:
|
|
|
|
self._checkre2()
|
|
|
|
if _re2:
|
|
|
|
return re2.escape
|
|
|
|
else:
|
|
|
|
return remod.escape
|
|
|
|
|
2014-07-16 01:40:43 +04:00
|
|
|
re = _re()
|
2012-06-02 02:26:20 +04:00
|
|
|
|
2008-06-06 22:23:23 +04:00
|
|
|
_fspathcache = {}
|
|
|
|
def fspath(name, root):
|
|
|
|
'''Get name in the case stored in the filesystem
|
|
|
|
|
2011-12-16 16:09:40 +04:00
|
|
|
The name should be relative to root, and be normcase-ed for efficiency.
|
|
|
|
|
|
|
|
Note that this function is unnecessary, and should not be
|
2008-06-06 22:23:23 +04:00
|
|
|
called, for case-sensitive filesystems (simply because it's expensive).
|
2011-12-16 16:09:40 +04:00
|
|
|
|
2011-12-16 16:09:40 +04:00
|
|
|
The root should be normcase-ed, too.
|
2008-06-06 22:23:23 +04:00
|
|
|
'''
|
2014-10-24 22:39:39 +04:00
|
|
|
def _makefspathcacheentry(dir):
|
|
|
|
return dict((normcase(n), n) for n in os.listdir(dir))
|
2011-12-16 16:09:40 +04:00
|
|
|
|
2008-06-06 22:23:23 +04:00
|
|
|
seps = os.sep
|
|
|
|
if os.altsep:
|
|
|
|
seps = seps + os.altsep
|
|
|
|
# Protect backslashes. This gets silly very quickly.
|
|
|
|
seps.replace('\\','\\\\')
|
2014-07-16 01:35:19 +04:00
|
|
|
pattern = remod.compile(r'([^%s]+)|([%s]+)' % (seps, seps))
|
2011-12-16 16:09:40 +04:00
|
|
|
dir = os.path.normpath(root)
|
2008-06-06 22:23:23 +04:00
|
|
|
result = []
|
|
|
|
for part, sep in pattern.findall(name):
|
|
|
|
if sep:
|
|
|
|
result.append(sep)
|
|
|
|
continue
|
|
|
|
|
2011-12-23 19:51:14 +04:00
|
|
|
if dir not in _fspathcache:
|
2014-10-24 22:39:39 +04:00
|
|
|
_fspathcache[dir] = _makefspathcacheentry(dir)
|
2011-12-23 19:51:14 +04:00
|
|
|
contents = _fspathcache[dir]
|
2008-06-06 22:23:23 +04:00
|
|
|
|
2014-10-24 22:39:39 +04:00
|
|
|
found = contents.get(part)
|
2011-12-16 16:09:40 +04:00
|
|
|
if not found:
|
2011-12-23 19:52:06 +04:00
|
|
|
# retry "once per directory" per "dirstate.walk" which
|
|
|
|
# may take place for each patches of "hg qpush", for example
|
2014-10-24 22:39:39 +04:00
|
|
|
_fspathcache[dir] = contents = _makefspathcacheentry(dir)
|
|
|
|
found = contents.get(part)
|
2011-12-16 16:09:40 +04:00
|
|
|
|
|
|
|
result.append(found or part)
|
2011-12-16 16:09:40 +04:00
|
|
|
dir = os.path.join(dir, part)
|
2008-06-06 22:23:23 +04:00
|
|
|
|
|
|
|
return ''.join(result)
|
|
|
|
|
2010-11-07 20:21:29 +03:00
|
|
|
def checknlink(testfile):
|
|
|
|
'''check whether hardlink count reporting works properly'''
|
|
|
|
|
2010-12-14 00:38:06 +03:00
|
|
|
# testfile may be open, so we need a separate file for checking to
|
|
|
|
# work around issue2543 (or testfile may get lost on Samba shares)
|
|
|
|
f1 = testfile + ".hgtmp1"
|
|
|
|
if os.path.lexists(f1):
|
|
|
|
return False
|
2010-11-07 20:21:29 +03:00
|
|
|
try:
|
2010-12-14 00:38:06 +03:00
|
|
|
posixfile(f1, 'w').close()
|
|
|
|
except IOError:
|
2010-11-07 20:21:29 +03:00
|
|
|
return False
|
|
|
|
|
2010-12-14 00:38:06 +03:00
|
|
|
f2 = testfile + ".hgtmp2"
|
|
|
|
fd = None
|
2010-11-07 20:21:29 +03:00
|
|
|
try:
|
2010-12-14 00:38:06 +03:00
|
|
|
try:
|
2011-05-06 17:34:34 +04:00
|
|
|
oslink(f1, f2)
|
2010-12-14 00:38:06 +03:00
|
|
|
except OSError:
|
|
|
|
return False
|
|
|
|
|
2010-11-07 20:21:29 +03:00
|
|
|
# nlinks() may behave differently for files on Windows shares if
|
|
|
|
# the file is open.
|
2011-02-02 15:51:22 +03:00
|
|
|
fd = posixfile(f2)
|
2010-12-14 00:38:06 +03:00
|
|
|
return nlinks(f2) > 1
|
2010-11-07 20:21:29 +03:00
|
|
|
finally:
|
2010-12-14 00:38:06 +03:00
|
|
|
if fd is not None:
|
|
|
|
fd.close()
|
|
|
|
for f in (f1, f2):
|
|
|
|
try:
|
|
|
|
os.unlink(f)
|
|
|
|
except OSError:
|
|
|
|
pass
|
2010-11-07 20:21:29 +03:00
|
|
|
|
2008-01-09 15:30:35 +03:00
|
|
|
def endswithsep(path):
|
|
|
|
'''Check path ends with os.sep or os.altsep.'''
|
|
|
|
return path.endswith(os.sep) or os.altsep and path.endswith(os.altsep)
|
|
|
|
|
2008-01-09 15:30:36 +03:00
|
|
|
def splitpath(path):
|
|
|
|
'''Split path by os.sep.
|
|
|
|
Note that this function does not use os.altsep because this is
|
|
|
|
an alternative of simple "xxx.split(os.sep)".
|
|
|
|
It is recommended to use os.path.normpath() before using this
|
|
|
|
function if need.'''
|
|
|
|
return path.split(os.sep)
|
|
|
|
|
2008-02-04 04:29:05 +03:00
|
|
|
def gui():
|
|
|
|
'''Are we running in a GUI?'''
|
2011-03-23 11:43:34 +03:00
|
|
|
if sys.platform == 'darwin':
|
|
|
|
if 'SSH_CONNECTION' in os.environ:
|
|
|
|
# handle SSH access to a box where the user is logged in
|
|
|
|
return False
|
|
|
|
elif getattr(osutil, 'isgui', None):
|
|
|
|
# check if a CoreGraphics session is available
|
|
|
|
return osutil.isgui()
|
|
|
|
else:
|
|
|
|
# pure build; use a safe default
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
return os.name == "nt" or os.environ.get("DISPLAY")
|
2008-02-04 04:29:05 +03:00
|
|
|
|
2008-02-09 23:38:54 +03:00
|
|
|
def mktempcopy(name, emptyok=False, createmode=None):
|
2007-07-12 00:40:41 +04:00
|
|
|
"""Create a temporary file with the same contents from name
|
2006-05-03 01:30:00 +04:00
|
|
|
|
2007-07-12 00:40:41 +04:00
|
|
|
The permission bits are copied from the original file.
|
|
|
|
|
|
|
|
If the temporary file is going to be truncated immediately, you
|
|
|
|
can use emptyok=True as an optimization.
|
|
|
|
|
|
|
|
Returns the name of the temporary file.
|
2006-05-03 01:30:00 +04:00
|
|
|
"""
|
2007-07-12 00:40:41 +04:00
|
|
|
d, fn = os.path.split(name)
|
|
|
|
fd, temp = tempfile.mkstemp(prefix='.%s-' % fn, dir=d)
|
|
|
|
os.close(fd)
|
|
|
|
# Temporary files are created with mode 0600, which is usually not
|
|
|
|
# what we want. If the original file already exists, just copy
|
|
|
|
# its mode. Otherwise, manually obey umask.
|
2011-08-02 14:29:48 +04:00
|
|
|
copymode(name, temp, createmode)
|
2007-07-12 00:40:41 +04:00
|
|
|
if emptyok:
|
|
|
|
return temp
|
|
|
|
try:
|
2006-05-03 01:30:00 +04:00
|
|
|
try:
|
2007-07-12 00:40:41 +04:00
|
|
|
ifp = posixfile(name, "rb")
|
|
|
|
except IOError, inst:
|
|
|
|
if inst.errno == errno.ENOENT:
|
|
|
|
return temp
|
|
|
|
if not getattr(inst, 'filename', None):
|
|
|
|
inst.filename = name
|
|
|
|
raise
|
|
|
|
ofp = posixfile(temp, "wb")
|
|
|
|
for chunk in filechunkiter(ifp):
|
|
|
|
ofp.write(chunk)
|
|
|
|
ifp.close()
|
|
|
|
ofp.close()
|
2012-05-13 15:18:06 +04:00
|
|
|
except: # re-raises
|
2007-07-12 00:40:41 +04:00
|
|
|
try: os.unlink(temp)
|
2012-05-13 15:17:31 +04:00
|
|
|
except OSError: pass
|
2007-07-12 00:40:41 +04:00
|
|
|
raise
|
|
|
|
return temp
|
|
|
|
|
2009-06-10 17:10:21 +04:00
|
|
|
class atomictempfile(object):
|
2012-08-16 00:38:42 +04:00
|
|
|
'''writable file object that atomically updates a file
|
2007-07-12 00:40:41 +04:00
|
|
|
|
2011-04-25 01:30:50 +04:00
|
|
|
All writes will go to a temporary copy of the original file. Call
|
2011-08-26 04:21:04 +04:00
|
|
|
close() when you are done writing, and atomictempfile will rename
|
|
|
|
the temporary copy to the original name, making the changes
|
|
|
|
visible. If the object is destroyed without being closed, all your
|
|
|
|
writes are discarded.
|
2011-04-25 01:30:50 +04:00
|
|
|
'''
|
2010-05-21 14:54:40 +04:00
|
|
|
def __init__(self, name, mode='w+b', createmode=None):
|
2011-04-25 03:25:10 +04:00
|
|
|
self.__name = name # permanent name
|
|
|
|
self._tempname = mktempcopy(name, emptyok=('w' in mode),
|
|
|
|
createmode=createmode)
|
|
|
|
self._fp = posixfile(self._tempname, mode)
|
2009-03-26 23:12:11 +03:00
|
|
|
|
2011-04-25 03:25:10 +04:00
|
|
|
# delegated methods
|
|
|
|
self.write = self._fp.write
|
2012-07-24 02:38:43 +04:00
|
|
|
self.seek = self._fp.seek
|
|
|
|
self.tell = self._fp.tell
|
2011-04-25 03:25:10 +04:00
|
|
|
self.fileno = self._fp.fileno
|
2007-07-12 00:40:41 +04:00
|
|
|
|
2011-08-26 04:21:04 +04:00
|
|
|
def close(self):
|
2009-06-13 15:14:02 +04:00
|
|
|
if not self._fp.closed:
|
2009-03-26 23:12:11 +03:00
|
|
|
self._fp.close()
|
2011-04-25 03:25:10 +04:00
|
|
|
rename(self._tempname, localpath(self.__name))
|
2007-07-12 00:40:41 +04:00
|
|
|
|
2011-08-26 04:21:04 +04:00
|
|
|
def discard(self):
|
2009-06-13 15:14:02 +04:00
|
|
|
if not self._fp.closed:
|
2006-05-08 19:20:56 +04:00
|
|
|
try:
|
2011-04-25 03:25:10 +04:00
|
|
|
os.unlink(self._tempname)
|
|
|
|
except OSError:
|
|
|
|
pass
|
2009-06-13 15:14:02 +04:00
|
|
|
self._fp.close()
|
2006-05-03 01:30:00 +04:00
|
|
|
|
2010-12-07 18:03:42 +03:00
|
|
|
def __del__(self):
|
2011-07-26 01:04:40 +04:00
|
|
|
if safehasattr(self, '_fp'): # constructor actually did something
|
2011-08-26 04:21:04 +04:00
|
|
|
self.discard()
|
2010-12-07 18:03:42 +03:00
|
|
|
|
2013-02-16 14:44:13 +04:00
|
|
|
def makedirs(name, mode=None, notindexed=False):
|
2008-02-09 23:38:54 +03:00
|
|
|
"""recursive directory creation with parent mode inheritance"""
|
|
|
|
try:
|
2013-02-16 14:44:13 +04:00
|
|
|
makedir(name, notindexed)
|
2008-02-09 23:38:54 +03:00
|
|
|
except OSError, err:
|
|
|
|
if err.errno == errno.EEXIST:
|
|
|
|
return
|
2011-08-25 13:03:16 +04:00
|
|
|
if err.errno != errno.ENOENT or not name:
|
|
|
|
raise
|
|
|
|
parent = os.path.dirname(os.path.abspath(name))
|
|
|
|
if parent == name:
|
2008-02-09 23:38:54 +03:00
|
|
|
raise
|
2013-02-16 14:44:13 +04:00
|
|
|
makedirs(parent, mode, notindexed)
|
|
|
|
makedir(name, notindexed)
|
2011-08-22 02:35:42 +04:00
|
|
|
if mode is not None:
|
|
|
|
os.chmod(name, mode)
|
2008-02-09 23:38:54 +03:00
|
|
|
|
2014-11-19 12:35:14 +03:00
|
|
|
def ensuredirs(name, mode=None, notindexed=False):
|
|
|
|
"""race-safe recursive directory creation
|
|
|
|
|
|
|
|
Newly created directories are marked as "not to be indexed by
|
|
|
|
the content indexing service", if ``notindexed`` is specified
|
|
|
|
for "write" mode access.
|
|
|
|
"""
|
2013-02-14 00:20:10 +04:00
|
|
|
if os.path.isdir(name):
|
|
|
|
return
|
|
|
|
parent = os.path.dirname(os.path.abspath(name))
|
|
|
|
if parent != name:
|
2014-11-19 12:35:14 +03:00
|
|
|
ensuredirs(parent, mode, notindexed)
|
2013-02-12 04:15:12 +04:00
|
|
|
try:
|
2014-11-19 12:35:14 +03:00
|
|
|
makedir(name, notindexed)
|
2013-02-12 04:15:12 +04:00
|
|
|
except OSError, err:
|
|
|
|
if err.errno == errno.EEXIST and os.path.isdir(name):
|
|
|
|
# someone else seems to have won a directory creation race
|
|
|
|
return
|
|
|
|
raise
|
2013-02-14 00:20:10 +04:00
|
|
|
if mode is not None:
|
|
|
|
os.chmod(name, mode)
|
2013-02-12 04:15:12 +04:00
|
|
|
|
2011-05-01 13:46:49 +04:00
|
|
|
def readfile(path):
|
2011-05-07 23:12:35 +04:00
|
|
|
fp = open(path, 'rb')
|
2011-05-01 13:46:49 +04:00
|
|
|
try:
|
2011-05-01 13:56:24 +04:00
|
|
|
return fp.read()
|
2011-05-01 13:46:49 +04:00
|
|
|
finally:
|
|
|
|
fp.close()
|
|
|
|
|
2011-05-02 12:11:05 +04:00
|
|
|
def writefile(path, text):
|
|
|
|
fp = open(path, 'wb')
|
|
|
|
try:
|
|
|
|
fp.write(text)
|
|
|
|
finally:
|
|
|
|
fp.close()
|
|
|
|
|
|
|
|
def appendfile(path, text):
|
|
|
|
fp = open(path, 'ab')
|
2011-05-01 13:46:49 +04:00
|
|
|
try:
|
|
|
|
fp.write(text)
|
|
|
|
finally:
|
|
|
|
fp.close()
|
|
|
|
|
2005-09-05 01:11:51 +04:00
|
|
|
class chunkbuffer(object):
|
|
|
|
"""Allow arbitrary sized chunks of data to be efficiently read from an
|
|
|
|
iterator over chunks of arbitrary size."""
|
2005-09-05 01:21:53 +04:00
|
|
|
|
2007-10-11 09:46:48 +04:00
|
|
|
def __init__(self, in_iter):
|
2005-09-05 01:11:51 +04:00
|
|
|
"""in_iter is the iterator that's iterating over the input chunks.
|
|
|
|
targetsize is how big a buffer to try to maintain."""
|
2010-07-25 15:10:57 +04:00
|
|
|
def splitbig(chunks):
|
|
|
|
for chunk in chunks:
|
|
|
|
if len(chunk) > 2**20:
|
|
|
|
pos = 0
|
|
|
|
while pos < len(chunk):
|
|
|
|
end = pos + 2 ** 18
|
|
|
|
yield chunk[pos:end]
|
|
|
|
pos = end
|
|
|
|
else:
|
|
|
|
yield chunk
|
|
|
|
self.iter = splitbig(in_iter)
|
2012-06-06 03:52:20 +04:00
|
|
|
self._queue = deque()
|
2005-09-05 01:11:51 +04:00
|
|
|
|
2014-04-11 09:10:26 +04:00
|
|
|
def read(self, l=None):
|
2005-09-05 01:21:53 +04:00
|
|
|
"""Read L bytes of data from the iterator of chunks of data.
|
2014-04-11 09:10:26 +04:00
|
|
|
Returns less than L bytes if the iterator runs dry.
|
|
|
|
|
2014-04-18 00:47:38 +04:00
|
|
|
If size parameter is omitted, read everything"""
|
2010-08-06 21:18:33 +04:00
|
|
|
left = l
|
2012-11-27 01:42:52 +04:00
|
|
|
buf = []
|
2012-06-06 03:52:20 +04:00
|
|
|
queue = self._queue
|
2014-04-11 09:10:26 +04:00
|
|
|
while left is None or left > 0:
|
2010-08-06 21:18:33 +04:00
|
|
|
# refill the queue
|
|
|
|
if not queue:
|
|
|
|
target = 2**18
|
|
|
|
for chunk in self.iter:
|
|
|
|
queue.append(chunk)
|
|
|
|
target -= len(chunk)
|
|
|
|
if target <= 0:
|
|
|
|
break
|
|
|
|
if not queue:
|
2005-09-05 01:11:51 +04:00
|
|
|
break
|
2010-08-06 21:18:33 +04:00
|
|
|
|
2012-05-15 21:46:23 +04:00
|
|
|
chunk = queue.popleft()
|
2014-04-11 09:10:26 +04:00
|
|
|
if left is not None:
|
|
|
|
left -= len(chunk)
|
|
|
|
if left is not None and left < 0:
|
2012-05-15 21:46:23 +04:00
|
|
|
queue.appendleft(chunk[left:])
|
2012-11-27 01:42:52 +04:00
|
|
|
buf.append(chunk[:left])
|
2010-07-24 17:20:29 +04:00
|
|
|
else:
|
2012-11-27 01:42:52 +04:00
|
|
|
buf.append(chunk)
|
2005-09-05 01:11:51 +04:00
|
|
|
|
2012-11-27 01:42:52 +04:00
|
|
|
return ''.join(buf)
|
2010-08-29 06:49:53 +04:00
|
|
|
|
2006-06-21 02:13:17 +04:00
|
|
|
def filechunkiter(f, size=65536, limit=None):
|
|
|
|
"""Create a generator that produces the data in the file size
|
|
|
|
(default 65536) bytes at a time, up to optional limit (default is
|
|
|
|
to read all data). Chunks may be less than size bytes if the
|
|
|
|
chunk is the last chunk in the file, or the file is a socket or
|
|
|
|
some other type of file that sometimes reads less data than is
|
|
|
|
requested."""
|
|
|
|
assert size >= 0
|
|
|
|
assert limit is None or limit >= 0
|
|
|
|
while True:
|
2010-01-25 09:05:27 +03:00
|
|
|
if limit is None:
|
|
|
|
nbytes = size
|
|
|
|
else:
|
|
|
|
nbytes = min(limit, size)
|
2006-06-21 02:13:17 +04:00
|
|
|
s = nbytes and f.read(nbytes)
|
2010-01-25 09:05:27 +03:00
|
|
|
if not s:
|
|
|
|
break
|
|
|
|
if limit:
|
|
|
|
limit -= len(s)
|
2005-09-05 01:11:51 +04:00
|
|
|
yield s
|
2005-09-23 09:46:50 +04:00
|
|
|
|
2013-06-04 04:20:45 +04:00
|
|
|
def makedate(timestamp=None):
|
|
|
|
'''Return a unix timestamp (or the current time) as a (unixtime,
|
|
|
|
offset) tuple based off the local timezone.'''
|
|
|
|
if timestamp is None:
|
|
|
|
timestamp = time.time()
|
2013-06-04 04:20:44 +04:00
|
|
|
if timestamp < 0:
|
2010-11-24 21:31:43 +03:00
|
|
|
hint = _("check your clock")
|
2013-06-04 04:20:44 +04:00
|
|
|
raise Abort(_("negative timestamp: %d") % timestamp, hint=hint)
|
|
|
|
delta = (datetime.datetime.utcfromtimestamp(timestamp) -
|
|
|
|
datetime.datetime.fromtimestamp(timestamp))
|
2011-11-13 04:29:26 +04:00
|
|
|
tz = delta.days * 86400 + delta.seconds
|
2013-06-04 04:20:44 +04:00
|
|
|
return timestamp, tz
|
2005-09-23 21:28:55 +04:00
|
|
|
|
2008-03-12 01:42:41 +03:00
|
|
|
def datestr(date=None, format='%a %b %d %H:%M:%S %Y %1%2'):
|
2005-09-23 10:19:47 +04:00
|
|
|
"""represent a (unixtime, offset) tuple as a localized time.
|
|
|
|
unixtime is seconds since the epoch, and offset is the time zone's
|
2006-03-22 10:29:21 +03:00
|
|
|
number of seconds away from UTC. if timezone is false, do not
|
|
|
|
append time zone to string."""
|
2005-09-23 10:19:47 +04:00
|
|
|
t, tz = date or makedate()
|
2010-11-23 15:11:40 +03:00
|
|
|
if t < 0:
|
|
|
|
t = 0 # time.gmtime(lt) fails on Windows for lt < -43200
|
|
|
|
tz = 0
|
2013-11-08 01:24:23 +04:00
|
|
|
if "%1" in format or "%2" in format or "%z" in format:
|
2008-03-12 01:42:41 +03:00
|
|
|
sign = (tz > 0) and "-" or "+"
|
2009-07-05 13:00:44 +04:00
|
|
|
minutes = abs(tz) // 60
|
2013-11-08 01:24:23 +04:00
|
|
|
format = format.replace("%z", "%1%2")
|
2009-07-05 13:00:44 +04:00
|
|
|
format = format.replace("%1", "%c%02d" % (sign, minutes // 60))
|
2008-03-12 01:42:41 +03:00
|
|
|
format = format.replace("%2", "%02d" % (minutes % 60))
|
2011-09-23 20:02:27 +04:00
|
|
|
try:
|
|
|
|
t = time.gmtime(float(t) - tz)
|
|
|
|
except ValueError:
|
|
|
|
# time was out of range
|
|
|
|
t = time.gmtime(sys.maxint)
|
|
|
|
s = time.strftime(format, t)
|
2006-03-22 10:29:21 +03:00
|
|
|
return s
|
2006-02-27 22:32:10 +03:00
|
|
|
|
2008-02-16 15:33:38 +03:00
|
|
|
def shortdate(date=None):
|
|
|
|
"""turn (timestamp, tzoff) tuple into iso 8631 date."""
|
2008-03-12 01:42:41 +03:00
|
|
|
return datestr(date, format='%Y-%m-%d')
|
2008-02-16 15:33:38 +03:00
|
|
|
|
2007-10-03 00:46:59 +04:00
|
|
|
def strdate(string, format, defaults=[]):
|
2006-06-30 20:47:35 +04:00
|
|
|
"""parse a localized time string and return a (unixtime, offset) tuple.
|
|
|
|
if the string cannot be parsed, ValueError is raised."""
|
2006-12-06 22:13:42 +03:00
|
|
|
def timezone(string):
|
|
|
|
tz = string.split()[-1]
|
|
|
|
if tz[0] in "+-" and len(tz) == 5 and tz[1:].isdigit():
|
2008-03-12 01:42:41 +03:00
|
|
|
sign = (tz[0] == "+") and 1 or -1
|
|
|
|
hours = int(tz[1:3])
|
|
|
|
minutes = int(tz[3:5])
|
|
|
|
return -sign * (hours * 60 + minutes) * 60
|
2010-09-24 21:46:54 +04:00
|
|
|
if tz == "GMT" or tz == "UTC":
|
2006-12-06 22:13:42 +03:00
|
|
|
return 0
|
|
|
|
return None
|
2006-06-30 20:47:35 +04:00
|
|
|
|
2006-10-03 14:33:14 +04:00
|
|
|
# NOTE: unixtime = localunixtime + offset
|
2006-12-06 22:13:42 +03:00
|
|
|
offset, date = timezone(string), string
|
2010-11-22 20:15:58 +03:00
|
|
|
if offset is not None:
|
2006-12-06 22:13:42 +03:00
|
|
|
date = " ".join(string.split()[:-1])
|
2006-12-06 22:13:31 +03:00
|
|
|
|
2006-12-07 00:11:44 +03:00
|
|
|
# add missing elements from defaults
|
2010-12-29 23:04:47 +03:00
|
|
|
usenow = False # default to using biased defaults
|
|
|
|
for part in ("S", "M", "HI", "d", "mb", "yY"): # decreasing specificity
|
2006-12-07 00:11:44 +03:00
|
|
|
found = [True for p in part if ("%"+p) in format]
|
|
|
|
if not found:
|
2010-12-29 23:04:47 +03:00
|
|
|
date += "@" + defaults[part][usenow]
|
2006-12-07 00:11:44 +03:00
|
|
|
format += "@%" + part[0]
|
2010-12-29 23:04:47 +03:00
|
|
|
else:
|
|
|
|
# We've found a specific time element, less specific time
|
|
|
|
# elements are relative to today
|
|
|
|
usenow = True
|
2006-12-06 22:13:31 +03:00
|
|
|
|
2006-10-03 14:33:18 +04:00
|
|
|
timetuple = time.strptime(date, format)
|
|
|
|
localunixtime = int(calendar.timegm(timetuple))
|
|
|
|
if offset is None:
|
|
|
|
# local timezone
|
|
|
|
unixtime = int(time.mktime(timetuple))
|
|
|
|
offset = unixtime - localunixtime
|
|
|
|
else:
|
|
|
|
unixtime = localunixtime + offset
|
2006-10-03 14:33:14 +04:00
|
|
|
return unixtime, offset
|
2006-06-30 20:47:35 +04:00
|
|
|
|
2010-12-29 23:04:47 +03:00
|
|
|
def parsedate(date, formats=None, bias={}):
|
|
|
|
"""parse a localized date/time and return a (unixtime, offset) tuple.
|
2008-02-17 23:34:28 +03:00
|
|
|
|
2006-06-30 20:47:35 +04:00
|
|
|
The date may be a "unixtime offset" string or in one of the specified
|
2008-02-17 23:34:28 +03:00
|
|
|
formats. If the date already is a (unixtime, offset) tuple, it is returned.
|
2013-01-23 21:51:45 +04:00
|
|
|
|
|
|
|
>>> parsedate(' today ') == parsedate(\
|
|
|
|
datetime.date.today().strftime('%b %d'))
|
|
|
|
True
|
|
|
|
>>> parsedate( 'yesterday ') == parsedate((datetime.date.today() -\
|
|
|
|
datetime.timedelta(days=1)\
|
|
|
|
).strftime('%b %d'))
|
|
|
|
True
|
2013-02-10 01:39:22 +04:00
|
|
|
>>> now, tz = makedate()
|
|
|
|
>>> strnow, strtz = parsedate('now')
|
|
|
|
>>> (strnow - now) < 1
|
|
|
|
True
|
|
|
|
>>> tz == strtz
|
|
|
|
True
|
2008-02-17 23:34:28 +03:00
|
|
|
"""
|
|
|
|
if not date:
|
2006-12-06 22:13:27 +03:00
|
|
|
return 0, 0
|
2008-03-12 01:42:51 +03:00
|
|
|
if isinstance(date, tuple) and len(date) == 2:
|
2008-02-17 23:34:28 +03:00
|
|
|
return date
|
2006-07-13 20:40:01 +04:00
|
|
|
if not formats:
|
|
|
|
formats = defaultdateformats
|
2008-02-17 23:34:28 +03:00
|
|
|
date = date.strip()
|
2013-01-23 21:51:45 +04:00
|
|
|
|
2013-02-10 01:39:22 +04:00
|
|
|
if date == _('now'):
|
|
|
|
return makedate()
|
2013-01-23 21:51:45 +04:00
|
|
|
if date == _('today'):
|
|
|
|
date = datetime.date.today().strftime('%b %d')
|
|
|
|
elif date == _('yesterday'):
|
|
|
|
date = (datetime.date.today() -
|
|
|
|
datetime.timedelta(days=1)).strftime('%b %d')
|
|
|
|
|
2006-06-30 20:47:35 +04:00
|
|
|
try:
|
2008-02-17 23:34:28 +03:00
|
|
|
when, offset = map(int, date.split(' '))
|
2006-06-30 20:48:06 +04:00
|
|
|
except ValueError:
|
2006-12-07 00:11:44 +03:00
|
|
|
# fill out defaults
|
|
|
|
now = makedate()
|
2010-12-29 23:04:47 +03:00
|
|
|
defaults = {}
|
2010-12-02 05:43:06 +03:00
|
|
|
for part in ("d", "mb", "yY", "HI", "M", "S"):
|
2010-12-29 23:04:47 +03:00
|
|
|
# this piece is for rounding the specific end of unknowns
|
|
|
|
b = bias.get(part)
|
|
|
|
if b is None:
|
2006-12-07 00:11:44 +03:00
|
|
|
if part[0] in "HMS":
|
2010-12-29 23:04:47 +03:00
|
|
|
b = "00"
|
2006-12-07 00:11:44 +03:00
|
|
|
else:
|
2010-12-29 23:04:47 +03:00
|
|
|
b = "0"
|
|
|
|
|
|
|
|
# this piece is for matching the generic end to today's date
|
|
|
|
n = datestr(now, "%" + part[0])
|
|
|
|
|
|
|
|
defaults[part] = (b, n)
|
2006-12-07 00:11:44 +03:00
|
|
|
|
2006-06-30 20:48:06 +04:00
|
|
|
for format in formats:
|
|
|
|
try:
|
2008-02-17 23:34:28 +03:00
|
|
|
when, offset = strdate(date, format, defaults)
|
2008-02-13 18:46:43 +03:00
|
|
|
except (ValueError, OverflowError):
|
2006-06-30 20:48:06 +04:00
|
|
|
pass
|
|
|
|
else:
|
|
|
|
break
|
|
|
|
else:
|
2010-08-30 08:29:44 +04:00
|
|
|
raise Abort(_('invalid date: %r') % date)
|
2006-06-30 20:48:06 +04:00
|
|
|
# validate explicit (probably user-specified) date and
|
|
|
|
# time zone offset. values must fit in signed 32 bits for
|
|
|
|
# current 32-bit linux runtimes. timezones go from UTC-12
|
|
|
|
# to UTC+14
|
|
|
|
if abs(when) > 0x7fffffff:
|
2006-12-06 22:13:26 +03:00
|
|
|
raise Abort(_('date exceeds 32 bits: %d') % when)
|
2010-11-24 21:31:43 +03:00
|
|
|
if when < 0:
|
|
|
|
raise Abort(_('negative date value: %d') % when)
|
2006-06-30 20:48:06 +04:00
|
|
|
if offset < -50400 or offset > 43200:
|
2006-12-06 22:13:26 +03:00
|
|
|
raise Abort(_('impossible time zone offset: %d') % offset)
|
2006-06-30 20:48:06 +04:00
|
|
|
return when, offset
|
2006-06-30 20:47:35 +04:00
|
|
|
|
2006-12-07 00:11:44 +03:00
|
|
|
def matchdate(date):
|
|
|
|
"""Return a function that matches a given date match specifier
|
|
|
|
|
|
|
|
Formats include:
|
|
|
|
|
|
|
|
'{date}' match a given date to the accuracy provided
|
|
|
|
|
|
|
|
'<{date}' on or before a given date
|
|
|
|
|
|
|
|
'>{date}' on or after a given date
|
|
|
|
|
2010-12-29 23:04:47 +03:00
|
|
|
>>> p1 = parsedate("10:29:59")
|
|
|
|
>>> p2 = parsedate("10:30:00")
|
|
|
|
>>> p3 = parsedate("10:30:59")
|
|
|
|
>>> p4 = parsedate("10:31:00")
|
|
|
|
>>> p5 = parsedate("Sep 15 10:30:00 1999")
|
|
|
|
>>> f = matchdate("10:30")
|
|
|
|
>>> f(p1[0])
|
|
|
|
False
|
|
|
|
>>> f(p2[0])
|
|
|
|
True
|
|
|
|
>>> f(p3[0])
|
|
|
|
True
|
|
|
|
>>> f(p4[0])
|
|
|
|
False
|
|
|
|
>>> f(p5[0])
|
|
|
|
False
|
2006-12-07 00:11:44 +03:00
|
|
|
"""
|
|
|
|
|
|
|
|
def lower(date):
|
2014-03-12 21:19:20 +04:00
|
|
|
d = {'mb': "1", 'd': "1"}
|
2008-03-12 01:42:51 +03:00
|
|
|
return parsedate(date, extendeddateformats, d)[0]
|
2006-12-07 00:11:44 +03:00
|
|
|
|
|
|
|
def upper(date):
|
2014-03-12 21:19:20 +04:00
|
|
|
d = {'mb': "12", 'HI': "23", 'M': "59", 'S': "59"}
|
2010-12-02 05:43:06 +03:00
|
|
|
for days in ("31", "30", "29"):
|
2006-12-07 00:11:44 +03:00
|
|
|
try:
|
|
|
|
d["d"] = days
|
|
|
|
return parsedate(date, extendeddateformats, d)[0]
|
2012-05-12 18:02:45 +04:00
|
|
|
except Abort:
|
2006-12-07 00:11:44 +03:00
|
|
|
pass
|
|
|
|
d["d"] = "28"
|
|
|
|
return parsedate(date, extendeddateformats, d)[0]
|
|
|
|
|
2009-04-01 20:11:00 +04:00
|
|
|
date = date.strip()
|
2011-03-28 01:48:58 +04:00
|
|
|
|
|
|
|
if not date:
|
|
|
|
raise Abort(_("dates cannot consist entirely of whitespace"))
|
|
|
|
elif date[0] == "<":
|
2011-04-04 18:39:22 +04:00
|
|
|
if not date[1:]:
|
2011-04-05 12:01:39 +04:00
|
|
|
raise Abort(_("invalid day spec, use '<DATE'"))
|
2006-12-07 00:11:44 +03:00
|
|
|
when = upper(date[1:])
|
|
|
|
return lambda x: x <= when
|
|
|
|
elif date[0] == ">":
|
2011-04-04 18:39:22 +04:00
|
|
|
if not date[1:]:
|
2011-04-05 12:01:39 +04:00
|
|
|
raise Abort(_("invalid day spec, use '>DATE'"))
|
2006-12-07 00:11:44 +03:00
|
|
|
when = lower(date[1:])
|
|
|
|
return lambda x: x >= when
|
|
|
|
elif date[0] == "-":
|
|
|
|
try:
|
|
|
|
days = int(date[1:])
|
|
|
|
except ValueError:
|
|
|
|
raise Abort(_("invalid day spec: %s") % date[1:])
|
2011-04-05 12:55:47 +04:00
|
|
|
if days < 0:
|
2015-01-18 03:01:14 +03:00
|
|
|
raise Abort(_('%s must be nonnegative (see "hg help dates")')
|
2011-04-05 12:55:47 +04:00
|
|
|
% date[1:])
|
2006-12-07 00:11:44 +03:00
|
|
|
when = makedate()[0] - days * 3600 * 24
|
2006-12-07 00:29:17 +03:00
|
|
|
return lambda x: x >= when
|
2006-12-07 00:11:44 +03:00
|
|
|
elif " to " in date:
|
|
|
|
a, b = date.split(" to ")
|
|
|
|
start, stop = lower(a), upper(b)
|
|
|
|
return lambda x: x >= start and x <= stop
|
|
|
|
else:
|
|
|
|
start, stop = lower(date), upper(date)
|
|
|
|
return lambda x: x >= start and x <= stop
|
|
|
|
|
2006-02-27 22:32:10 +03:00
|
|
|
def shortuser(user):
|
|
|
|
"""Return a short representation of a user name or email address."""
|
|
|
|
f = user.find('@')
|
|
|
|
if f >= 0:
|
|
|
|
user = user[:f]
|
|
|
|
f = user.find('<')
|
|
|
|
if f >= 0:
|
2010-01-25 09:05:27 +03:00
|
|
|
user = user[f + 1:]
|
2006-09-27 22:34:52 +04:00
|
|
|
f = user.find(' ')
|
|
|
|
if f >= 0:
|
|
|
|
user = user[:f]
|
2006-10-27 20:30:20 +04:00
|
|
|
f = user.find('.')
|
|
|
|
if f >= 0:
|
|
|
|
user = user[:f]
|
2006-02-27 22:32:10 +03:00
|
|
|
return user
|
2006-03-13 03:21:59 +03:00
|
|
|
|
2012-03-28 18:06:20 +04:00
|
|
|
def emailuser(user):
|
|
|
|
"""Return the user portion of an email address."""
|
|
|
|
f = user.find('@')
|
|
|
|
if f >= 0:
|
|
|
|
user = user[:f]
|
|
|
|
f = user.find('<')
|
|
|
|
if f >= 0:
|
|
|
|
user = user[f + 1:]
|
|
|
|
return user
|
|
|
|
|
2008-01-31 23:44:19 +03:00
|
|
|
def email(author):
|
|
|
|
'''get email of author.'''
|
|
|
|
r = author.find('>')
|
2010-01-25 09:05:27 +03:00
|
|
|
if r == -1:
|
|
|
|
r = None
|
|
|
|
return author[author.find('<') + 1:r]
|
2008-01-31 23:44:19 +03:00
|
|
|
|
2010-12-25 15:59:00 +03:00
|
|
|
def ellipsis(text, maxlength=400):
|
util: replace 'ellipsis' implementation by 'encoding.trim'
Before this patch, 'util.ellipsis' tried to avoid splitting at
intermediate multi-byte sequence, but its implementation was incorrect.
Internal function '_ellipsis' trims specified unicode sequence not at
most maxlength 'columns in display', but at most maxlength number of
'unicode characters'.
def _ellipsis(text, maxlength):
if len(text) <= maxlength:
return text, False
else:
return "%s..." % (text[:maxlength - 3]), True
In many encodings, number of unicode characters can be different from
columns in display.
This patch replaces 'ellipsis' implementation by 'encoding.trim',
which can trim string at most maxlength columns in display correctly,
even though specified string contains multi-byte characters.
'_ellipsis' is removed in this patch, because it is referred only from
'ellipsis'.
2014-07-05 21:56:41 +04:00
|
|
|
"""Trim string to at most maxlength (default: 400) columns in display."""
|
|
|
|
return encoding.trim(text, maxlength, ellipsis='...')
|
2006-12-03 00:35:17 +03:00
|
|
|
|
2013-03-01 00:51:18 +04:00
|
|
|
def unitcountfn(*unittable):
|
|
|
|
'''return a function that renders a readable count of some quantity'''
|
|
|
|
|
|
|
|
def go(count):
|
|
|
|
for multiplier, divisor, format in unittable:
|
|
|
|
if count >= divisor * multiplier:
|
|
|
|
return format % (count / float(divisor))
|
|
|
|
return unittable[-1][2] % count
|
|
|
|
|
|
|
|
return go
|
|
|
|
|
|
|
|
bytecount = unitcountfn(
|
2012-04-13 05:22:18 +04:00
|
|
|
(100, 1 << 30, _('%.0f GB')),
|
|
|
|
(10, 1 << 30, _('%.1f GB')),
|
|
|
|
(1, 1 << 30, _('%.2f GB')),
|
|
|
|
(100, 1 << 20, _('%.0f MB')),
|
|
|
|
(10, 1 << 20, _('%.1f MB')),
|
|
|
|
(1, 1 << 20, _('%.2f MB')),
|
|
|
|
(100, 1 << 10, _('%.0f KB')),
|
|
|
|
(10, 1 << 10, _('%.1f KB')),
|
|
|
|
(1, 1 << 10, _('%.2f KB')),
|
|
|
|
(1, 1, _('%.0f bytes')),
|
|
|
|
)
|
|
|
|
|
2007-09-11 01:36:01 +04:00
|
|
|
def uirepr(s):
|
|
|
|
# Avoid double backslash in Windows path repr()
|
|
|
|
return repr(s).replace('\\\\', '\\')
|
2008-12-25 11:48:24 +03:00
|
|
|
|
2011-01-29 02:02:29 +03:00
|
|
|
# delay import of textwrap
|
|
|
|
def MBTextWrapper(**kwargs):
|
|
|
|
class tw(textwrap.TextWrapper):
|
|
|
|
"""
|
2011-08-26 23:56:12 +04:00
|
|
|
Extend TextWrapper for width-awareness.
|
2011-01-29 02:02:29 +03:00
|
|
|
|
2011-08-26 23:56:12 +04:00
|
|
|
Neither number of 'bytes' in any encoding nor 'characters' is
|
|
|
|
appropriate to calculate terminal columns for specified string.
|
2011-01-29 02:02:29 +03:00
|
|
|
|
2011-08-26 23:56:12 +04:00
|
|
|
Original TextWrapper implementation uses built-in 'len()' directly,
|
|
|
|
so overriding is needed to use width information of each characters.
|
|
|
|
|
|
|
|
In addition, characters classified into 'ambiguous' width are
|
2012-08-16 00:38:42 +04:00
|
|
|
treated as wide in East Asian area, but as narrow in other.
|
2011-08-26 23:56:12 +04:00
|
|
|
|
|
|
|
This requires use decision to determine width of such characters.
|
2011-01-29 02:02:29 +03:00
|
|
|
"""
|
|
|
|
def __init__(self, **kwargs):
|
|
|
|
textwrap.TextWrapper.__init__(self, **kwargs)
|
|
|
|
|
2011-08-26 23:56:12 +04:00
|
|
|
# for compatibility between 2.4 and 2.6
|
|
|
|
if getattr(self, 'drop_whitespace', None) is None:
|
|
|
|
self.drop_whitespace = kwargs.get('drop_whitespace', True)
|
|
|
|
|
2011-08-07 01:52:20 +04:00
|
|
|
def _cutdown(self, ucstr, space_left):
|
2011-01-29 02:02:29 +03:00
|
|
|
l = 0
|
2011-08-26 23:56:12 +04:00
|
|
|
colwidth = encoding.ucolwidth
|
2011-01-29 02:02:29 +03:00
|
|
|
for i in xrange(len(ucstr)):
|
2011-08-26 23:56:12 +04:00
|
|
|
l += colwidth(ucstr[i])
|
2011-01-29 02:02:29 +03:00
|
|
|
if space_left < l:
|
2011-08-07 01:52:20 +04:00
|
|
|
return (ucstr[:i], ucstr[i:])
|
|
|
|
return ucstr, ''
|
2011-01-29 02:02:29 +03:00
|
|
|
|
|
|
|
# overriding of base class
|
|
|
|
def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):
|
|
|
|
space_left = max(width - cur_len, 1)
|
|
|
|
|
|
|
|
if self.break_long_words:
|
|
|
|
cut, res = self._cutdown(reversed_chunks[-1], space_left)
|
|
|
|
cur_line.append(cut)
|
|
|
|
reversed_chunks[-1] = res
|
|
|
|
elif not cur_line:
|
|
|
|
cur_line.append(reversed_chunks.pop())
|
|
|
|
|
2011-08-26 23:56:12 +04:00
|
|
|
# this overriding code is imported from TextWrapper of python 2.6
|
|
|
|
# to calculate columns of string by 'encoding.ucolwidth()'
|
|
|
|
def _wrap_chunks(self, chunks):
|
|
|
|
colwidth = encoding.ucolwidth
|
|
|
|
|
|
|
|
lines = []
|
|
|
|
if self.width <= 0:
|
|
|
|
raise ValueError("invalid width %r (must be > 0)" % self.width)
|
|
|
|
|
|
|
|
# Arrange in reverse order so items can be efficiently popped
|
|
|
|
# from a stack of chucks.
|
|
|
|
chunks.reverse()
|
|
|
|
|
|
|
|
while chunks:
|
|
|
|
|
|
|
|
# Start the list of chunks that will make up the current line.
|
|
|
|
# cur_len is just the length of all the chunks in cur_line.
|
|
|
|
cur_line = []
|
|
|
|
cur_len = 0
|
|
|
|
|
|
|
|
# Figure out which static string will prefix this line.
|
|
|
|
if lines:
|
|
|
|
indent = self.subsequent_indent
|
|
|
|
else:
|
|
|
|
indent = self.initial_indent
|
|
|
|
|
|
|
|
# Maximum width for this line.
|
|
|
|
width = self.width - len(indent)
|
|
|
|
|
|
|
|
# First chunk on line is whitespace -- drop it, unless this
|
2012-08-16 00:38:42 +04:00
|
|
|
# is the very beginning of the text (i.e. no lines started yet).
|
2011-08-26 23:56:12 +04:00
|
|
|
if self.drop_whitespace and chunks[-1].strip() == '' and lines:
|
|
|
|
del chunks[-1]
|
|
|
|
|
|
|
|
while chunks:
|
|
|
|
l = colwidth(chunks[-1])
|
|
|
|
|
|
|
|
# Can at least squeeze this chunk onto the current line.
|
|
|
|
if cur_len + l <= width:
|
|
|
|
cur_line.append(chunks.pop())
|
|
|
|
cur_len += l
|
|
|
|
|
|
|
|
# Nope, this line is full.
|
|
|
|
else:
|
|
|
|
break
|
|
|
|
|
|
|
|
# The current line is full, and the next chunk is too big to
|
|
|
|
# fit on *any* line (not just this one).
|
|
|
|
if chunks and colwidth(chunks[-1]) > width:
|
|
|
|
self._handle_long_word(chunks, cur_line, cur_len, width)
|
|
|
|
|
|
|
|
# If the last chunk on this line is all whitespace, drop it.
|
|
|
|
if (self.drop_whitespace and
|
|
|
|
cur_line and cur_line[-1].strip() == ''):
|
|
|
|
del cur_line[-1]
|
|
|
|
|
|
|
|
# Convert current line back to a string and store it in list
|
|
|
|
# of all lines (return value).
|
|
|
|
if cur_line:
|
|
|
|
lines.append(indent + ''.join(cur_line))
|
|
|
|
|
|
|
|
return lines
|
|
|
|
|
2011-01-29 02:02:29 +03:00
|
|
|
global MBTextWrapper
|
|
|
|
MBTextWrapper = tw
|
|
|
|
return tw(**kwargs)
|
replace Python standard textwrap by MBCS sensitive one for i18n text
Mercurial has problem around text wrapping/filling in MBCS encoding
environment, because standard 'textwrap' module of Python can not
treat it correctly. It splits byte sequence for one character into two
lines.
According to unicode specification, "east asian width" classifies
characters into:
W(ide), N(arrow), F(ull-width), H(alf-width), A(mbiguous)
W/N/F/H can be always recognized as 2/1/2/1 bytes in byte sequence,
but 'A' can not. Size of 'A' depends on language in which it is used.
Unicode specification says:
If the context(= language) cannot be established reliably they
should be treated as narrow characters by default
but many of class 'A' characters are full-width, at least, in Japanese
environment.
So, this patch treats class 'A' characters as full-width always for
safety wrapping.
This patch focuses only on MBCS safe-ness, not on writing/printing
rule strict wrapping for each languages
MBCS sensitive textwrap class is originally implemented
by ITO Nobuaki <daydream.trippers@gmail.com>.
2010-06-06 12:20:10 +04:00
|
|
|
|
2010-10-11 03:02:52 +04:00
|
|
|
def wrap(line, width, initindent='', hangindent=''):
|
replace Python standard textwrap by MBCS sensitive one for i18n text
Mercurial has problem around text wrapping/filling in MBCS encoding
environment, because standard 'textwrap' module of Python can not
treat it correctly. It splits byte sequence for one character into two
lines.
According to unicode specification, "east asian width" classifies
characters into:
W(ide), N(arrow), F(ull-width), H(alf-width), A(mbiguous)
W/N/F/H can be always recognized as 2/1/2/1 bytes in byte sequence,
but 'A' can not. Size of 'A' depends on language in which it is used.
Unicode specification says:
If the context(= language) cannot be established reliably they
should be treated as narrow characters by default
but many of class 'A' characters are full-width, at least, in Japanese
environment.
So, this patch treats class 'A' characters as full-width always for
safety wrapping.
This patch focuses only on MBCS safe-ness, not on writing/printing
rule strict wrapping for each languages
MBCS sensitive textwrap class is originally implemented
by ITO Nobuaki <daydream.trippers@gmail.com>.
2010-06-06 12:20:10 +04:00
|
|
|
maxindent = max(len(hangindent), len(initindent))
|
|
|
|
if width <= maxindent:
|
2009-09-03 23:07:06 +04:00
|
|
|
# adjust for weird terminal size
|
replace Python standard textwrap by MBCS sensitive one for i18n text
Mercurial has problem around text wrapping/filling in MBCS encoding
environment, because standard 'textwrap' module of Python can not
treat it correctly. It splits byte sequence for one character into two
lines.
According to unicode specification, "east asian width" classifies
characters into:
W(ide), N(arrow), F(ull-width), H(alf-width), A(mbiguous)
W/N/F/H can be always recognized as 2/1/2/1 bytes in byte sequence,
but 'A' can not. Size of 'A' depends on language in which it is used.
Unicode specification says:
If the context(= language) cannot be established reliably they
should be treated as narrow characters by default
but many of class 'A' characters are full-width, at least, in Japanese
environment.
So, this patch treats class 'A' characters as full-width always for
safety wrapping.
This patch focuses only on MBCS safe-ness, not on writing/printing
rule strict wrapping for each languages
MBCS sensitive textwrap class is originally implemented
by ITO Nobuaki <daydream.trippers@gmail.com>.
2010-06-06 12:20:10 +04:00
|
|
|
width = max(78, maxindent + 1)
|
2011-08-07 01:52:20 +04:00
|
|
|
line = line.decode(encoding.encoding, encoding.encodingmode)
|
|
|
|
initindent = initindent.decode(encoding.encoding, encoding.encodingmode)
|
|
|
|
hangindent = hangindent.decode(encoding.encoding, encoding.encodingmode)
|
replace Python standard textwrap by MBCS sensitive one for i18n text
Mercurial has problem around text wrapping/filling in MBCS encoding
environment, because standard 'textwrap' module of Python can not
treat it correctly. It splits byte sequence for one character into two
lines.
According to unicode specification, "east asian width" classifies
characters into:
W(ide), N(arrow), F(ull-width), H(alf-width), A(mbiguous)
W/N/F/H can be always recognized as 2/1/2/1 bytes in byte sequence,
but 'A' can not. Size of 'A' depends on language in which it is used.
Unicode specification says:
If the context(= language) cannot be established reliably they
should be treated as narrow characters by default
but many of class 'A' characters are full-width, at least, in Japanese
environment.
So, this patch treats class 'A' characters as full-width always for
safety wrapping.
This patch focuses only on MBCS safe-ness, not on writing/printing
rule strict wrapping for each languages
MBCS sensitive textwrap class is originally implemented
by ITO Nobuaki <daydream.trippers@gmail.com>.
2010-06-06 12:20:10 +04:00
|
|
|
wrapper = MBTextWrapper(width=width,
|
|
|
|
initial_indent=initindent,
|
|
|
|
subsequent_indent=hangindent)
|
2011-08-07 01:52:20 +04:00
|
|
|
return wrapper.fill(line).encode(encoding.encoding)
|
2009-06-24 21:15:58 +04:00
|
|
|
|
2009-03-23 12:41:42 +03:00
|
|
|
def iterlines(iterator):
|
|
|
|
for chunk in iterator:
|
|
|
|
for line in chunk.splitlines():
|
|
|
|
yield line
|
2009-10-19 23:19:28 +04:00
|
|
|
|
|
|
|
def expandpath(path):
|
|
|
|
return os.path.expanduser(os.path.expandvars(path))
|
2010-01-06 23:11:58 +03:00
|
|
|
|
|
|
|
def hgcmd():
|
|
|
|
"""Return the command used to execute current hg
|
|
|
|
|
|
|
|
This is different from hgexecutable() because on Windows we want
|
|
|
|
to avoid things opening new shell windows like batch files, so we
|
|
|
|
get either the python call or current executable.
|
|
|
|
"""
|
2011-05-06 17:10:29 +04:00
|
|
|
if mainfrozen():
|
2010-01-06 23:11:58 +03:00
|
|
|
return [sys.executable]
|
|
|
|
return gethgcmd()
|
2010-02-06 18:50:00 +03:00
|
|
|
|
|
|
|
def rundetached(args, condfn):
|
|
|
|
"""Execute the argument list in a detached process.
|
2010-02-08 17:18:49 +03:00
|
|
|
|
2010-02-06 18:50:00 +03:00
|
|
|
condfn is a callable which is called repeatedly and should return
|
|
|
|
True once the child process is known to have started successfully.
|
|
|
|
At this point, the child process PID is returned. If the child
|
|
|
|
process fails to start or finishes before condfn() evaluates to
|
|
|
|
True, return -1.
|
|
|
|
"""
|
|
|
|
# Windows case is easier because the child process is either
|
|
|
|
# successfully starting and validating the condition or exiting
|
|
|
|
# on failure. We just poll on its PID. On Unix, if the child
|
|
|
|
# process fails to start, it will be left in a zombie state until
|
|
|
|
# the parent wait on it, which we cannot do since we expect a long
|
|
|
|
# running process on success. Instead we listen for SIGCHLD telling
|
|
|
|
# us our child process terminated.
|
|
|
|
terminated = set()
|
|
|
|
def handler(signum, frame):
|
|
|
|
terminated.add(os.wait())
|
|
|
|
prevhandler = None
|
2011-07-26 01:04:40 +04:00
|
|
|
SIGCHLD = getattr(signal, 'SIGCHLD', None)
|
|
|
|
if SIGCHLD is not None:
|
|
|
|
prevhandler = signal.signal(SIGCHLD, handler)
|
2010-02-06 18:50:00 +03:00
|
|
|
try:
|
|
|
|
pid = spawndetached(args)
|
|
|
|
while not condfn():
|
|
|
|
if ((pid in terminated or not testpid(pid))
|
|
|
|
and not condfn()):
|
|
|
|
return -1
|
|
|
|
time.sleep(0.1)
|
|
|
|
return pid
|
|
|
|
finally:
|
|
|
|
if prevhandler is not None:
|
|
|
|
signal.signal(signal.SIGCHLD, prevhandler)
|
2010-02-13 03:59:09 +03:00
|
|
|
|
2010-02-16 17:31:35 +03:00
|
|
|
try:
|
|
|
|
any, all = any, all
|
|
|
|
except NameError:
|
|
|
|
def any(iterable):
|
|
|
|
for i in iterable:
|
|
|
|
if i:
|
|
|
|
return True
|
|
|
|
return False
|
2010-02-13 03:59:09 +03:00
|
|
|
|
2010-02-16 17:31:35 +03:00
|
|
|
def all(iterable):
|
|
|
|
for i in iterable:
|
|
|
|
if not i:
|
|
|
|
return False
|
|
|
|
return True
|
2010-04-27 00:30:40 +04:00
|
|
|
|
2011-02-11 03:32:40 +03:00
|
|
|
def interpolate(prefix, mapping, s, fn=None, escape_prefix=False):
|
util: add an interpolate() function to for replacing multiple values
util.interpolate can be used to replace multiple items in a string all at once
(and optionally apply a function to the replacement), without worrying about
recursing:
>>> import util
>>> s = '$foo, $spam'
>>> util.interpolate(r'\$', { 'foo': 'bar', 'spam': 'eggs' }, s)
'bar, eggs'
>>> util.interpolate(r'\$', { 'foo': 'spam', 'spam': 'foo' }, s)
'spam, foo'
>>> util.interpolate(r'\$', { 'foo': 'spam', 'spam': 'foo' }, s, lambda s: s.upper())
'SPAM, FOO'
The patch also changes filemerge.py to use this new function.
2010-08-19 02:18:26 +04:00
|
|
|
"""Return the result of interpolating items in the mapping into string s.
|
|
|
|
|
|
|
|
prefix is a single character string, or a two character string with
|
|
|
|
a backslash as the first character if the prefix needs to be escaped in
|
|
|
|
a regular expression.
|
|
|
|
|
|
|
|
fn is an optional function that will be applied to the replacement text
|
|
|
|
just before replacement.
|
2011-02-11 03:32:40 +03:00
|
|
|
|
|
|
|
escape_prefix is an optional flag that allows using doubled prefix for
|
|
|
|
its escaping.
|
util: add an interpolate() function to for replacing multiple values
util.interpolate can be used to replace multiple items in a string all at once
(and optionally apply a function to the replacement), without worrying about
recursing:
>>> import util
>>> s = '$foo, $spam'
>>> util.interpolate(r'\$', { 'foo': 'bar', 'spam': 'eggs' }, s)
'bar, eggs'
>>> util.interpolate(r'\$', { 'foo': 'spam', 'spam': 'foo' }, s)
'spam, foo'
>>> util.interpolate(r'\$', { 'foo': 'spam', 'spam': 'foo' }, s, lambda s: s.upper())
'SPAM, FOO'
The patch also changes filemerge.py to use this new function.
2010-08-19 02:18:26 +04:00
|
|
|
"""
|
|
|
|
fn = fn or (lambda s: s)
|
2011-02-11 03:32:40 +03:00
|
|
|
patterns = '|'.join(mapping.keys())
|
|
|
|
if escape_prefix:
|
|
|
|
patterns += '|' + prefix
|
|
|
|
if len(prefix) > 1:
|
|
|
|
prefix_char = prefix[1:]
|
|
|
|
else:
|
|
|
|
prefix_char = prefix
|
|
|
|
mapping[prefix_char] = prefix_char
|
2014-07-16 01:35:19 +04:00
|
|
|
r = remod.compile(r'%s(%s)' % (prefix, patterns))
|
util: add an interpolate() function to for replacing multiple values
util.interpolate can be used to replace multiple items in a string all at once
(and optionally apply a function to the replacement), without worrying about
recursing:
>>> import util
>>> s = '$foo, $spam'
>>> util.interpolate(r'\$', { 'foo': 'bar', 'spam': 'eggs' }, s)
'bar, eggs'
>>> util.interpolate(r'\$', { 'foo': 'spam', 'spam': 'foo' }, s)
'spam, foo'
>>> util.interpolate(r'\$', { 'foo': 'spam', 'spam': 'foo' }, s, lambda s: s.upper())
'SPAM, FOO'
The patch also changes filemerge.py to use this new function.
2010-08-19 02:18:26 +04:00
|
|
|
return r.sub(lambda x: fn(mapping[x.group()[1:]]), s)
|
|
|
|
|
2010-08-28 20:31:07 +04:00
|
|
|
def getport(port):
|
|
|
|
"""Return the port for a given network service.
|
|
|
|
|
|
|
|
If port is an integer, it's returned as is. If it's a string, it's
|
|
|
|
looked up using socket.getservbyname(). If there's no matching
|
|
|
|
service, util.Abort is raised.
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
return int(port)
|
|
|
|
except ValueError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
try:
|
|
|
|
return socket.getservbyname(port)
|
|
|
|
except socket.error:
|
|
|
|
raise Abort(_("no port number associated with service '%s'") % port)
|
2010-08-29 06:50:35 +04:00
|
|
|
|
2010-08-30 19:28:25 +04:00
|
|
|
_booleans = {'1': True, 'yes': True, 'true': True, 'on': True, 'always': True,
|
|
|
|
'0': False, 'no': False, 'false': False, 'off': False,
|
|
|
|
'never': False}
|
2010-08-29 06:50:35 +04:00
|
|
|
|
|
|
|
def parsebool(s):
|
|
|
|
"""Parse s into a boolean.
|
|
|
|
|
|
|
|
If s is not a valid boolean, returns None.
|
|
|
|
"""
|
|
|
|
return _booleans.get(s.lower(), None)
|
2011-04-30 20:43:20 +04:00
|
|
|
|
2011-04-30 20:43:23 +04:00
|
|
|
_hexdig = '0123456789ABCDEFabcdef'
|
|
|
|
_hextochr = dict((a + b, chr(int(a + b, 16)))
|
|
|
|
for a in _hexdig for b in _hexdig)
|
|
|
|
|
|
|
|
def _urlunquote(s):
|
2012-08-16 00:39:18 +04:00
|
|
|
"""Decode HTTP/HTML % encoding.
|
|
|
|
|
|
|
|
>>> _urlunquote('abc%20def')
|
|
|
|
'abc def'
|
|
|
|
"""
|
2011-04-30 20:43:23 +04:00
|
|
|
res = s.split('%')
|
|
|
|
# fastpath
|
|
|
|
if len(res) == 1:
|
|
|
|
return s
|
|
|
|
s = res[0]
|
|
|
|
for item in res[1:]:
|
|
|
|
try:
|
|
|
|
s += _hextochr[item[:2]] + item[2:]
|
|
|
|
except KeyError:
|
|
|
|
s += '%' + item
|
|
|
|
except UnicodeDecodeError:
|
|
|
|
s += unichr(int(item[:2], 16)) + item[2:]
|
|
|
|
return s
|
|
|
|
|
2011-04-30 20:43:20 +04:00
|
|
|
class url(object):
|
2011-05-01 17:49:13 +04:00
|
|
|
r"""Reliable URL parser.
|
2011-04-30 20:43:20 +04:00
|
|
|
|
|
|
|
This parses URLs and provides attributes for the following
|
|
|
|
components:
|
|
|
|
|
|
|
|
<scheme>://<user>:<passwd>@<host>:<port>/<path>?<query>#<fragment>
|
|
|
|
|
|
|
|
Missing components are set to None. The only exception is
|
|
|
|
fragment, which is set to '' if present but empty.
|
|
|
|
|
|
|
|
If parsefragment is False, fragment is included in query. If
|
|
|
|
parsequery is False, query is included in path. If both are
|
|
|
|
False, both fragment and query are included in path.
|
|
|
|
|
|
|
|
See http://www.ietf.org/rfc/rfc2396.txt for more information.
|
|
|
|
|
|
|
|
Note that for backward compatibility reasons, bundle URLs do not
|
|
|
|
take host names. That means 'bundle://../' has a path of '../'.
|
|
|
|
|
|
|
|
Examples:
|
|
|
|
|
|
|
|
>>> url('http://www.ietf.org/rfc/rfc2396.txt')
|
|
|
|
<url scheme: 'http', host: 'www.ietf.org', path: 'rfc/rfc2396.txt'>
|
|
|
|
>>> url('ssh://[::1]:2200//home/joe/repo')
|
|
|
|
<url scheme: 'ssh', host: '[::1]', port: '2200', path: '/home/joe/repo'>
|
|
|
|
>>> url('file:///home/joe/repo')
|
|
|
|
<url scheme: 'file', path: '/home/joe/repo'>
|
2011-07-23 02:11:35 +04:00
|
|
|
>>> url('file:///c:/temp/foo/')
|
|
|
|
<url scheme: 'file', path: 'c:/temp/foo/'>
|
2011-04-30 20:43:20 +04:00
|
|
|
>>> url('bundle:foo')
|
|
|
|
<url scheme: 'bundle', path: 'foo'>
|
|
|
|
>>> url('bundle://../foo')
|
|
|
|
<url scheme: 'bundle', path: '../foo'>
|
2011-05-01 17:49:13 +04:00
|
|
|
>>> url(r'c:\foo\bar')
|
|
|
|
<url path: 'c:\\foo\\bar'>
|
2011-06-21 01:45:33 +04:00
|
|
|
>>> url(r'\\blah\blah\blah')
|
|
|
|
<url path: '\\\\blah\\blah\\blah'>
|
2011-09-11 02:49:19 +04:00
|
|
|
>>> url(r'\\blah\blah\blah#baz')
|
|
|
|
<url path: '\\\\blah\\blah\\blah', fragment: 'baz'>
|
2013-11-21 01:03:15 +04:00
|
|
|
>>> url(r'file:///C:\users\me')
|
|
|
|
<url scheme: 'file', path: 'C:\\users\\me'>
|
2011-04-30 20:43:20 +04:00
|
|
|
|
|
|
|
Authentication credentials:
|
|
|
|
|
|
|
|
>>> url('ssh://joe:xyz@x/repo')
|
|
|
|
<url scheme: 'ssh', user: 'joe', passwd: 'xyz', host: 'x', path: 'repo'>
|
|
|
|
>>> url('ssh://joe@x/repo')
|
|
|
|
<url scheme: 'ssh', user: 'joe', host: 'x', path: 'repo'>
|
|
|
|
|
|
|
|
Query strings and fragments:
|
|
|
|
|
|
|
|
>>> url('http://host/a?b#c')
|
|
|
|
<url scheme: 'http', host: 'host', path: 'a', query: 'b', fragment: 'c'>
|
|
|
|
>>> url('http://host/a?b#c', parsequery=False, parsefragment=False)
|
|
|
|
<url scheme: 'http', host: 'host', path: 'a?b#c'>
|
|
|
|
"""
|
|
|
|
|
|
|
|
_safechars = "!~*'()+"
|
2013-11-21 01:03:15 +04:00
|
|
|
_safepchars = "/!~*'()+:\\"
|
2014-07-16 01:35:19 +04:00
|
|
|
_matchscheme = remod.compile(r'^[a-zA-Z0-9+.\-]+:').match
|
2011-04-30 20:43:20 +04:00
|
|
|
|
|
|
|
def __init__(self, path, parsequery=True, parsefragment=True):
|
|
|
|
# We slowly chomp away at path until we have only the path left
|
|
|
|
self.scheme = self.user = self.passwd = self.host = None
|
|
|
|
self.port = self.path = self.query = self.fragment = None
|
|
|
|
self._localpath = True
|
|
|
|
self._hostport = ''
|
|
|
|
self._origpath = path
|
|
|
|
|
2011-09-11 02:49:19 +04:00
|
|
|
if parsefragment and '#' in path:
|
|
|
|
path, self.fragment = path.split('#', 1)
|
|
|
|
if not path:
|
|
|
|
path = None
|
|
|
|
|
2011-06-21 01:45:33 +04:00
|
|
|
# special case for Windows drive letters and UNC paths
|
|
|
|
if hasdriveletter(path) or path.startswith(r'\\'):
|
2011-04-30 20:43:20 +04:00
|
|
|
self.path = path
|
|
|
|
return
|
|
|
|
|
|
|
|
# For compatibility reasons, we can't handle bundle paths as
|
|
|
|
# normal URLS
|
|
|
|
if path.startswith('bundle:'):
|
|
|
|
self.scheme = 'bundle'
|
|
|
|
path = path[7:]
|
|
|
|
if path.startswith('//'):
|
|
|
|
path = path[2:]
|
|
|
|
self.path = path
|
|
|
|
return
|
|
|
|
|
|
|
|
if self._matchscheme(path):
|
|
|
|
parts = path.split(':', 1)
|
|
|
|
if parts[0]:
|
|
|
|
self.scheme, path = parts
|
|
|
|
self._localpath = False
|
|
|
|
|
|
|
|
if not path:
|
|
|
|
path = None
|
|
|
|
if self._localpath:
|
|
|
|
self.path = ''
|
|
|
|
return
|
|
|
|
else:
|
|
|
|
if self._localpath:
|
|
|
|
self.path = path
|
|
|
|
return
|
|
|
|
|
|
|
|
if parsequery and '?' in path:
|
|
|
|
path, self.query = path.split('?', 1)
|
|
|
|
if not path:
|
|
|
|
path = None
|
|
|
|
if not self.query:
|
|
|
|
self.query = None
|
|
|
|
|
|
|
|
# // is required to specify a host/authority
|
|
|
|
if path and path.startswith('//'):
|
|
|
|
parts = path[2:].split('/', 1)
|
|
|
|
if len(parts) > 1:
|
|
|
|
self.host, path = parts
|
|
|
|
else:
|
|
|
|
self.host = parts[0]
|
|
|
|
path = None
|
|
|
|
if not self.host:
|
|
|
|
self.host = None
|
2011-08-04 04:51:29 +04:00
|
|
|
# path of file:///d is /d
|
|
|
|
# path of file:///d:/ is d:/, not /d:/
|
2011-07-23 02:11:35 +04:00
|
|
|
if path and not hasdriveletter(path):
|
2011-04-30 20:43:20 +04:00
|
|
|
path = '/' + path
|
|
|
|
|
|
|
|
if self.host and '@' in self.host:
|
|
|
|
self.user, self.host = self.host.rsplit('@', 1)
|
|
|
|
if ':' in self.user:
|
|
|
|
self.user, self.passwd = self.user.split(':', 1)
|
|
|
|
if not self.host:
|
|
|
|
self.host = None
|
|
|
|
|
|
|
|
# Don't split on colons in IPv6 addresses without ports
|
|
|
|
if (self.host and ':' in self.host and
|
|
|
|
not (self.host.startswith('[') and self.host.endswith(']'))):
|
|
|
|
self._hostport = self.host
|
|
|
|
self.host, self.port = self.host.rsplit(':', 1)
|
|
|
|
if not self.host:
|
|
|
|
self.host = None
|
|
|
|
|
|
|
|
if (self.host and self.scheme == 'file' and
|
|
|
|
self.host not in ('localhost', '127.0.0.1', '[::1]')):
|
|
|
|
raise Abort(_('file:// URLs can only refer to localhost'))
|
|
|
|
|
|
|
|
self.path = path
|
|
|
|
|
2011-07-31 23:00:44 +04:00
|
|
|
# leave the query string escaped
|
2011-04-30 20:43:20 +04:00
|
|
|
for a in ('user', 'passwd', 'host', 'port',
|
2011-07-31 23:00:44 +04:00
|
|
|
'path', 'fragment'):
|
2011-04-30 20:43:20 +04:00
|
|
|
v = getattr(self, a)
|
|
|
|
if v is not None:
|
2011-04-30 20:43:23 +04:00
|
|
|
setattr(self, a, _urlunquote(v))
|
2011-04-30 20:43:20 +04:00
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
attrs = []
|
|
|
|
for a in ('scheme', 'user', 'passwd', 'host', 'port', 'path',
|
|
|
|
'query', 'fragment'):
|
|
|
|
v = getattr(self, a)
|
|
|
|
if v is not None:
|
|
|
|
attrs.append('%s: %r' % (a, v))
|
|
|
|
return '<url %s>' % ', '.join(attrs)
|
|
|
|
|
|
|
|
def __str__(self):
|
2011-05-01 17:49:13 +04:00
|
|
|
r"""Join the URL's components back into a URL string.
|
2011-04-30 20:43:20 +04:00
|
|
|
|
|
|
|
Examples:
|
|
|
|
|
2011-11-07 06:25:10 +04:00
|
|
|
>>> str(url('http://user:pw@host:80/c:/bob?fo:oo#ba:ar'))
|
|
|
|
'http://user:pw@host:80/c:/bob?fo:oo#ba:ar'
|
2011-07-31 23:00:44 +04:00
|
|
|
>>> str(url('http://user:pw@host:80/?foo=bar&baz=42'))
|
|
|
|
'http://user:pw@host:80/?foo=bar&baz=42'
|
|
|
|
>>> str(url('http://user:pw@host:80/?foo=bar%3dbaz'))
|
|
|
|
'http://user:pw@host:80/?foo=bar%3dbaz'
|
2011-04-30 20:43:20 +04:00
|
|
|
>>> str(url('ssh://user:pw@[::1]:2200//home/joe#'))
|
|
|
|
'ssh://user:pw@[::1]:2200//home/joe#'
|
|
|
|
>>> str(url('http://localhost:80//'))
|
|
|
|
'http://localhost:80//'
|
|
|
|
>>> str(url('http://localhost:80/'))
|
|
|
|
'http://localhost:80/'
|
|
|
|
>>> str(url('http://localhost:80'))
|
|
|
|
'http://localhost:80/'
|
|
|
|
>>> str(url('bundle:foo'))
|
|
|
|
'bundle:foo'
|
|
|
|
>>> str(url('bundle://../foo'))
|
|
|
|
'bundle:../foo'
|
|
|
|
>>> str(url('path'))
|
|
|
|
'path'
|
2011-05-12 18:41:56 +04:00
|
|
|
>>> str(url('file:///tmp/foo/bar'))
|
|
|
|
'file:///tmp/foo/bar'
|
2011-12-04 21:22:25 +04:00
|
|
|
>>> str(url('file:///c:/tmp/foo/bar'))
|
2011-12-06 03:48:40 +04:00
|
|
|
'file:///c:/tmp/foo/bar'
|
2011-05-01 17:49:13 +04:00
|
|
|
>>> print url(r'bundle:foo\bar')
|
|
|
|
bundle:foo\bar
|
2013-11-21 01:03:15 +04:00
|
|
|
>>> print url(r'file:///D:\data\hg')
|
|
|
|
file:///D:\data\hg
|
2011-04-30 20:43:20 +04:00
|
|
|
"""
|
|
|
|
if self._localpath:
|
|
|
|
s = self.path
|
|
|
|
if self.scheme == 'bundle':
|
|
|
|
s = 'bundle:' + s
|
|
|
|
if self.fragment:
|
|
|
|
s += '#' + self.fragment
|
|
|
|
return s
|
|
|
|
|
|
|
|
s = self.scheme + ':'
|
2011-05-12 18:41:56 +04:00
|
|
|
if self.user or self.passwd or self.host:
|
|
|
|
s += '//'
|
2011-12-04 21:22:25 +04:00
|
|
|
elif self.scheme and (not self.path or self.path.startswith('/')
|
|
|
|
or hasdriveletter(self.path)):
|
2011-04-30 20:43:20 +04:00
|
|
|
s += '//'
|
2011-12-04 21:22:25 +04:00
|
|
|
if hasdriveletter(self.path):
|
|
|
|
s += '/'
|
2011-04-30 20:43:20 +04:00
|
|
|
if self.user:
|
|
|
|
s += urllib.quote(self.user, safe=self._safechars)
|
|
|
|
if self.passwd:
|
|
|
|
s += ':' + urllib.quote(self.passwd, safe=self._safechars)
|
|
|
|
if self.user or self.passwd:
|
|
|
|
s += '@'
|
|
|
|
if self.host:
|
|
|
|
if not (self.host.startswith('[') and self.host.endswith(']')):
|
|
|
|
s += urllib.quote(self.host)
|
|
|
|
else:
|
|
|
|
s += self.host
|
|
|
|
if self.port:
|
|
|
|
s += ':' + urllib.quote(self.port)
|
|
|
|
if self.host:
|
|
|
|
s += '/'
|
|
|
|
if self.path:
|
2011-07-31 23:00:44 +04:00
|
|
|
# TODO: similar to the query string, we should not unescape the
|
|
|
|
# path when we store it, the path might contain '%2f' = '/',
|
|
|
|
# which we should *not* escape.
|
2011-04-30 20:43:20 +04:00
|
|
|
s += urllib.quote(self.path, safe=self._safepchars)
|
|
|
|
if self.query:
|
2011-07-31 23:00:44 +04:00
|
|
|
# we store the query in escaped form.
|
|
|
|
s += '?' + self.query
|
2011-04-30 20:43:20 +04:00
|
|
|
if self.fragment is not None:
|
|
|
|
s += '#' + urllib.quote(self.fragment, safe=self._safepchars)
|
|
|
|
return s
|
|
|
|
|
|
|
|
def authinfo(self):
|
|
|
|
user, passwd = self.user, self.passwd
|
|
|
|
try:
|
|
|
|
self.user, self.passwd = None, None
|
|
|
|
s = str(self)
|
|
|
|
finally:
|
|
|
|
self.user, self.passwd = user, passwd
|
|
|
|
if not self.user:
|
|
|
|
return (s, None)
|
2011-08-06 16:10:59 +04:00
|
|
|
# authinfo[1] is passed to urllib2 password manager, and its
|
|
|
|
# URIs must not contain credentials. The host is passed in the
|
|
|
|
# URIs list because Python < 2.4.3 uses only that to search for
|
|
|
|
# a password.
|
2011-08-05 23:05:40 +04:00
|
|
|
return (s, (None, (s, self.host),
|
2011-04-30 20:43:20 +04:00
|
|
|
self.user, self.passwd or ''))
|
|
|
|
|
2011-06-30 01:01:06 +04:00
|
|
|
def isabs(self):
|
|
|
|
if self.scheme and self.scheme != 'file':
|
|
|
|
return True # remote URL
|
|
|
|
if hasdriveletter(self.path):
|
|
|
|
return True # absolute for our purposes - can't be joined()
|
|
|
|
if self.path.startswith(r'\\'):
|
|
|
|
return True # Windows UNC path
|
|
|
|
if self.path.startswith('/'):
|
|
|
|
return True # POSIX-style
|
|
|
|
return False
|
|
|
|
|
2011-04-30 20:43:20 +04:00
|
|
|
def localpath(self):
|
|
|
|
if self.scheme == 'file' or self.scheme == 'bundle':
|
|
|
|
path = self.path or '/'
|
|
|
|
# For Windows, we need to promote hosts containing drive
|
|
|
|
# letters to paths with drive letters.
|
|
|
|
if hasdriveletter(self._hostport):
|
|
|
|
path = self._hostport + '/' + self.path
|
2011-11-16 03:10:56 +04:00
|
|
|
elif (self.host is not None and self.path
|
|
|
|
and not hasdriveletter(path)):
|
2011-04-30 20:43:20 +04:00
|
|
|
path = '/' + path
|
|
|
|
return path
|
|
|
|
return self._origpath
|
|
|
|
|
2014-02-04 02:47:41 +04:00
|
|
|
def islocal(self):
|
|
|
|
'''whether localpath will return something that posixfile can open'''
|
|
|
|
return (not self.scheme or self.scheme == 'file'
|
|
|
|
or self.scheme == 'bundle')
|
|
|
|
|
2011-04-30 20:43:20 +04:00
|
|
|
def hasscheme(path):
|
|
|
|
return bool(url(path).scheme)
|
|
|
|
|
|
|
|
def hasdriveletter(path):
|
2011-12-04 21:22:25 +04:00
|
|
|
return path and path[1:2] == ':' and path[0:1].isalpha()
|
2011-04-30 20:43:20 +04:00
|
|
|
|
2011-07-01 19:37:09 +04:00
|
|
|
def urllocalpath(path):
|
2011-04-30 20:43:20 +04:00
|
|
|
return url(path, parsequery=False, parsefragment=False).localpath()
|
|
|
|
|
|
|
|
def hidepassword(u):
|
|
|
|
'''hide user credential in a url string'''
|
|
|
|
u = url(u)
|
|
|
|
if u.passwd:
|
|
|
|
u.passwd = '***'
|
|
|
|
return str(u)
|
|
|
|
|
|
|
|
def removeauth(u):
|
|
|
|
'''remove all authentication information from a url string'''
|
|
|
|
u = url(u)
|
|
|
|
u.user = u.passwd = None
|
|
|
|
return str(u)
|
2011-06-02 01:43:34 +04:00
|
|
|
|
|
|
|
def isatty(fd):
|
|
|
|
try:
|
|
|
|
return fd.isatty()
|
|
|
|
except AttributeError:
|
|
|
|
return False
|
2013-03-01 01:11:42 +04:00
|
|
|
|
|
|
|
timecount = unitcountfn(
|
|
|
|
(1, 1e3, _('%.0f s')),
|
|
|
|
(100, 1, _('%.1f s')),
|
|
|
|
(10, 1, _('%.2f s')),
|
|
|
|
(1, 1, _('%.3f s')),
|
|
|
|
(100, 0.001, _('%.1f ms')),
|
|
|
|
(10, 0.001, _('%.2f ms')),
|
|
|
|
(1, 0.001, _('%.3f ms')),
|
|
|
|
(100, 0.000001, _('%.1f us')),
|
|
|
|
(10, 0.000001, _('%.2f us')),
|
|
|
|
(1, 0.000001, _('%.3f us')),
|
|
|
|
(100, 0.000000001, _('%.1f ns')),
|
|
|
|
(10, 0.000000001, _('%.2f ns')),
|
|
|
|
(1, 0.000000001, _('%.3f ns')),
|
|
|
|
)
|
|
|
|
|
|
|
|
_timenesting = [0]
|
|
|
|
|
|
|
|
def timed(func):
|
|
|
|
'''Report the execution time of a function call to stderr.
|
|
|
|
|
|
|
|
During development, use as a decorator when you need to measure
|
|
|
|
the cost of a function, e.g. as follows:
|
|
|
|
|
|
|
|
@util.timed
|
|
|
|
def foo(a, b, c):
|
|
|
|
pass
|
|
|
|
'''
|
|
|
|
|
|
|
|
def wrapper(*args, **kwargs):
|
|
|
|
start = time.time()
|
|
|
|
indent = 2
|
|
|
|
_timenesting[0] += indent
|
|
|
|
try:
|
|
|
|
return func(*args, **kwargs)
|
|
|
|
finally:
|
|
|
|
elapsed = time.time() - start
|
|
|
|
_timenesting[0] -= indent
|
|
|
|
sys.stderr.write('%s%s: %s\n' %
|
|
|
|
(' ' * _timenesting[0], func.__name__,
|
|
|
|
timecount(elapsed)))
|
|
|
|
return wrapper
|
2013-05-15 02:16:43 +04:00
|
|
|
|
|
|
|
_sizeunits = (('m', 2**20), ('k', 2**10), ('g', 2**30),
|
|
|
|
('kb', 2**10), ('mb', 2**20), ('gb', 2**30), ('b', 1))
|
|
|
|
|
|
|
|
def sizetoint(s):
|
|
|
|
'''Convert a space specifier to a byte count.
|
|
|
|
|
|
|
|
>>> sizetoint('30')
|
|
|
|
30
|
|
|
|
>>> sizetoint('2.2kb')
|
|
|
|
2252
|
|
|
|
>>> sizetoint('6M')
|
|
|
|
6291456
|
|
|
|
'''
|
|
|
|
t = s.strip().lower()
|
|
|
|
try:
|
|
|
|
for k, u in _sizeunits:
|
|
|
|
if t.endswith(k):
|
|
|
|
return int(float(t[:-len(k)]) * u)
|
|
|
|
return int(t)
|
|
|
|
except ValueError:
|
|
|
|
raise error.ParseError(_("couldn't parse size: %s") % s)
|
2013-05-14 22:23:15 +04:00
|
|
|
|
|
|
|
class hooks(object):
|
|
|
|
'''A collection of hook functions that can be used to extend a
|
|
|
|
function's behaviour. Hooks are called in lexicographic order,
|
|
|
|
based on the names of their sources.'''
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
self._hooks = []
|
|
|
|
|
|
|
|
def add(self, source, hook):
|
|
|
|
self._hooks.append((source, hook))
|
|
|
|
|
|
|
|
def __call__(self, *args):
|
|
|
|
self._hooks.sort(key=lambda x: x[0])
|
2014-04-15 19:37:24 +04:00
|
|
|
results = []
|
2013-05-14 22:23:15 +04:00
|
|
|
for source, hook in self._hooks:
|
2014-04-15 19:37:24 +04:00
|
|
|
results.append(hook(*args))
|
|
|
|
return results
|
2014-01-13 02:28:21 +04:00
|
|
|
|
2014-02-20 05:38:36 +04:00
|
|
|
def debugstacktrace(msg='stacktrace', skip=0, f=sys.stderr, otherf=sys.stdout):
|
2014-01-13 02:28:21 +04:00
|
|
|
'''Writes a message to f (stderr) with a nicely formatted stacktrace.
|
2014-02-20 05:38:36 +04:00
|
|
|
Skips the 'skip' last entries. By default it will flush stdout first.
|
2014-01-13 02:28:21 +04:00
|
|
|
It can be used everywhere and do intentionally not require an ui object.
|
|
|
|
Not be used in production code but very convenient while developing.
|
|
|
|
'''
|
2014-02-20 05:38:36 +04:00
|
|
|
if otherf:
|
|
|
|
otherf.flush()
|
2014-01-13 02:28:21 +04:00
|
|
|
f.write('%s at:\n' % msg)
|
|
|
|
entries = [('%s:%s' % (fn, ln), func)
|
|
|
|
for fn, ln, func, _text in traceback.extract_stack()[:-skip - 1]]
|
|
|
|
if entries:
|
|
|
|
fnmax = max(len(entry[0]) for entry in entries)
|
|
|
|
for fnln, func in entries:
|
|
|
|
f.write(' %-*s in %s\n' % (fnmax, fnln, func))
|
2014-02-20 05:38:36 +04:00
|
|
|
f.flush()
|
2014-01-13 02:28:21 +04:00
|
|
|
|
|
|
|
# convenient shortcut
|
|
|
|
dst = debugstacktrace
|