def _send(self, path, data): e = None rdata = None # print request if debugrequests and debug are both on if self.debugrequests: self.ui.debug("%s\n" % json.dumps(cleandict(data))) if self._getheader("Content-Encoding") == "gzip": buffer = util.stringio() with gzip.GzipFile(fileobj=buffer, mode="w") as compressed: compressed.write(pycompat.encodeutf8(json.dumps(data))) compressed.flush() rdata = buffer.getvalue() else: rdata = pycompat.encodeutf8(json.dumps(data)) # exponential backoff here on failure, 1s, 2s, 4s, 8s, 16s etc sl = 1 for attempt in range(MAX_CONNECT_RETRIES): try: self.connection.request("POST", path, rdata, self.headers) resp = self.connection.getresponse() if resp.status == httplib.UNAUTHORIZED: raise ccerror.RegistrationError(self.ui, _("unauthorized client")) if resp.status == httplib.FORBIDDEN: raise ccerror.RegistrationError(self.ui, _("forbidden client")) if resp.status == httplib.BAD_REQUEST: raise ccerror.BadRequestError(self.ui, resp.reason) if resp.status != httplib.OK: raise ccerror.ServiceError( self.ui, "%d %s" % (resp.status, resp.reason) ) if resp.getheader("Content-Encoding") == "gzip": resp = gzip.GzipFile(fileobj=util.stringio(resp.read())) data = json.load(resp) # print response if debugrequests and debug are both on if self.debugrequests: self.ui.debug("%s\n" % json.dumps(cleandict(data))) if "error" in data: raise ccerror.ServiceError(self.ui, data["error"]) return data except httplib.HTTPException: self.connection.close() self.connection.connect() except (socket.timeout, socket.gaierror) as e: raise error.Abort( _("network error: %s") % e, hint=_("check your network connection") ) except socket.error as e: if "SSL" in str(e): raise ccerror.TLSAccessError(self.ui, str(e)) raise ccerror.ServiceError(self.ui, str(e)) except ssl.CertificateError as e: raise ccerror.TLSAccessError(self.ui, str(e)) time.sleep(sl) sl *= 2 if e: raise ccerror.ServiceError(self.ui, str(e))
def _hg(*args, **kwargs): stdin = kwargs.get("stdin") or "" encoding.setfromenviron() cwdbefore = os.getcwd() fout = util.stringio() fin = util.stringio(stdin) status = bindings.commands.run(["hg"] + list(args), fin, fout, fout) cwdafter = os.getcwd() if cwdafter != cwdbefore: # Revert side effect of --cwd os.chdir(cwdbefore) buf = fout.getvalue().rstrip() return (status, buf)
def _hg(*args, **kwargs): stdin = kwargs.get("stdin") or "" encoding.setfromenviron() cwdbefore = os.getcwd() fout = util.stringio() fin = util.stringio(pycompat.encodeutf8(stdin)) sysargs = ["hg"] + list(args) pycompat.sysargv = sysargs status = bindings.commands.run(sysargs, fin, fout, fout) cwdafter = os.getcwd() if cwdafter != cwdbefore: # Revert side effect of --cwd os.chdir(cwdbefore) buf = fout.getvalue().rstrip() return (status, pycompat.decodeutf8(buf, errors="surrogateescape"))
def c(args): """Run command with args and take its output. Example:: c(['log', '-r.']) c('log -r.') %trace c('log -r.') """ if isinstance(args, str): args = shlex.split(args) ui = globals()["ui"] fin = util.stringio() fout = util.stringio() bindings.commands.run(["hg"] + args, fin, fout, ui.ferr) return fout.getvalue()
def hgcmd(cmdname, *args, **additional_opts): cmdargs = ["hg", *cmdname.split(), *args] for flagname, flagvalue in additional_opts.items(): flagname = flagname.replace("_", "-") if isinstance(flagvalue, list): cmdargs += [f"--{flagname}={v}" for v in flagvalue] else: cmdargs += [f"--{flagname}={flagvalue}"] fin = util.stringio() fout = ferr = util.stringio() status = bindings.commands.run(cmdargs, fin, fout, ferr) output = fout.getvalue().decode() if status != 0: output += f"[{status}]\n" return output
def __init__(self, part): # copy "public properties" self.type = part.type self.id = part.id self.mandatory = part.mandatory self.mandatoryparams = part.mandatoryparams self.advisoryparams = part.advisoryparams self.params = part.params self.mandatorykeys = part.mandatorykeys # copy the buffer self._io = util.stringio(part.read())
def _parsechunk(hunk): """(crecord.uihunk or patch.recordhunk) -> (path, (a1, a2, [bline]))""" if type(hunk) not in (crecord.uihunk, patch.recordhunk): return None, None path = hunk.header.filename() a1 = hunk.fromline + len(hunk.before) - 1 # remove before and after context hunk.before = hunk.after = [] buf = util.stringio() hunk.write(buf) patchlines = mdiff.splitnewlines(buf.getvalue()) # hunk.prettystr() will update hunk.removed a2 = a1 + hunk.removed blines = [l[1:] for l in patchlines[1:] if l[0:1] != b"-"] return path, (a1, a2, blines)
def split_lines(t): return util.stringio(t).readlines()
def _send(self, path, data): e = None rdata = None # print request if debugrequests and debug are both on if self.debugrequests: self.ui.debug("%s\n" % json.dumps(cleandict(data), indent=4)) if self._getheader("Content-Encoding") == "gzip": buffer = util.stringio() with gzip.GzipFile(fileobj=buffer, mode="w") as compressed: compressed.write(json.dumps(data)) compressed.flush() rdata = buffer.getvalue() else: rdata = json.dumps(data) # exponential backoff here on failure, 1s, 2s, 4s, 8s, 16s etc sl = 1 def _tlserror(e): # build tls error with all configuration details details = [] if self.client_certs: details.append( _("* client cert file used '%s'") % self.client_certs) if self.ca_certs: details.append( _("* certificate authority file used '%s'") % self.ca_certs) return ccerror.TLSAccessError(self.ui, str(e), details) for attempt in range(MAX_CONNECT_RETRIES): try: self.connection.request("POST", path, rdata, self.headers) resp = self.connection.getresponse() if resp.status == httplib.UNAUTHORIZED: raise ccerror.RegistrationError( self.ui, _("unauthorized client (token is invalid)")) if resp.status != httplib.OK: raise ccerror.ServiceError( self.ui, "%d %s" % (resp.status, resp.reason)) if resp.getheader("Content-Encoding") == "gzip": resp = gzip.GzipFile(fileobj=util.stringio(resp.read())) data = json.load(resp) # print response if debugrequests and debug are both on if self.debugrequests: self.ui.debug("%s\n" % json.dumps(cleandict(data), indent=4)) return data except httplib.HTTPException: self.connection.close() self.connection.connect() except (socket.timeout, socket.gaierror) as e: raise error.Abort(_("network error: %s") % e, hint=_("check your network connection")) except socket.error as e: if "SSL" in str(e): raise _tlserror(e) raise ccerror.ServiceError(self.ui, str(e)) except ssl.CertificateError as e: raise _tlserror(e) time.sleep(sl) sl *= 2 if e: raise ccerror.ServiceError(self.ui, str(e))