import os, subprocess, sys
from hglib import error
try:
from io import BytesIO
except ImportError:
from cStringIO import StringIO as BytesIO
if sys.version_info[0] > 2:
izip = zip
integertypes = (int,)
def b(s):
return s.encode('latin-1')
else:
from itertools import izip
integertypes = (long, int)
bytes = str
def b(s):
return s
def strtobytes(s):
return str(s).encode('latin-1')
def grouper(n, iterable):
args = [iter(iterable)] * n
return izip(*args)
def eatlines(s, n):
cs = BytesIO(s)
for line in cs:
n -= 1
if n == 0:
return cs.read()
return b('')
def skiplines(s, prefix):
cs = BytesIO(s)
for line in cs:
if not line.startswith(prefix):
return line + cs.read()
return b('')
def _cmdval(val):
if isinstance(val, bytes):
return val
else:
return strtobytes(val)
def cmdbuilder(name, *args, **kwargs):
cmd = [name]
for arg, val in kwargs.items():
if val is None:
continue
arg = arg.encode('latin-1').replace(b('_'), b('-'))
if arg != b('-'):
if len(arg) == 1:
arg = b('-') + arg
else:
arg = b('--') + arg
if isinstance(val, bool):
if val:
cmd.append(arg)
elif isinstance(val, list):
for v in val:
cmd.append(arg)
cmd.append(_cmdval(v))
else:
cmd.append(arg)
cmd.append(_cmdval(val))
for a in args:
if a is not None:
cmd.append(a)
return cmd
class reterrorhandler(object):
def __init__(self, args, allowed=None):
self.args = args
self.ret = 0
if allowed is None:
self.allowed = [1]
else:
self.allowed = allowed
def __call__(self, ret, out, err):
self.ret = ret
if ret not in self.allowed:
raise error.CommandError(self.args, ret, out, err)
return out
def __nonzero__(self):
return self.ret == 0
def __bool__(self):
return self.__nonzero__()
class propertycache(object):
def __init__(self, func):
self.func = func
self.name = func.__name__
def __get__(self, obj, type=None):
result = self.func(obj)
setattr(obj, self.name, result)
return result
close_fds = os.name == 'posix'
startupinfo = None
if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
def popen(args, env=None):
environ = None
if env:
environ = dict(os.environ)
environ.update(env)
return subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, close_fds=close_fds,
startupinfo=startupinfo, env=environ)