global: use pycompat.xrange()
authorGregory Szorc <gregory.szorc@gmail.com>
Wed, 01 Aug 2018 13:00:45 -0700
changeset 47112 e7aa113b14f77959ad4039d873b57100a4d56b31
parent 47111 7eba8f83129bc0642d19ee72ae335d0d1846803e
child 47113 882ef6949bdc303f2dba206c8ab2743daf98439b
push id837
push usergszorc@mozilla.com
push dateFri, 03 Aug 2018 01:30:56 +0000
global: use pycompat.xrange() On Python 3, our module importer automatically rewrites xrange() to pycompat.xrange(). We want to move away from the custom importer on Python 3. This commit converts all instances of xrange() to use pycompat.xrange(). Differential Revision: https://phab.mercurial-scm.org/D4032
hgext/acl.py
hgext/beautifygraph.py
hgext/blackbox.py
hgext/censor.py
hgext/convert/cvsps.py
hgext/eol.py
hgext/hgk.py
hgext/histedit.py
hgext/mq.py
hgext/narrow/narrowchangegroup.py
hgext/shelve.py
hgext/win32text.py
mercurial/ancestor.py
mercurial/bundle2.py
mercurial/changegroup.py
mercurial/changelog.py
mercurial/cmdutil.py
mercurial/commands.py
mercurial/context.py
mercurial/dagop.py
mercurial/dagparser.py
mercurial/debugcommands.py
mercurial/diffhelper.py
mercurial/encoding.py
mercurial/graphmod.py
mercurial/hgweb/webcommands.py
mercurial/hgweb/webutil.py
mercurial/httppeer.py
mercurial/localrepo.py
mercurial/mdiff.py
mercurial/minirst.py
mercurial/obsolete.py
mercurial/patch.py
mercurial/phases.py
mercurial/pure/osutil.py
mercurial/pvec.py
mercurial/repair.py
mercurial/repoview.py
mercurial/revlog.py
mercurial/revsetlang.py
mercurial/scmutil.py
mercurial/server.py
mercurial/simplemerge.py
mercurial/smartset.py
mercurial/store.py
mercurial/streamclone.py
mercurial/templatefilters.py
mercurial/treediscovery.py
mercurial/utils/stringutil.py
mercurial/win32.py
mercurial/wireprotoserver.py
mercurial/wireprotov1peer.py
--- a/hgext/acl.py
+++ b/hgext/acl.py
@@ -215,16 +215,17 @@ 3) Deny access to a file to anyone but u
 
 from __future__ import absolute_import
 
 from mercurial.i18n import _
 from mercurial import (
     error,
     extensions,
     match,
+    pycompat,
     registrar,
     util,
 )
 from mercurial.utils import (
     procutil,
 )
 
 urlreq = util.urlreq
@@ -398,17 +399,17 @@ def _txnhook(ui, repo, hooktype, node, s
         ui.readconfig(cfg, sections=['acl.groups', 'acl.allow.branches',
             'acl.deny.branches', 'acl.allow', 'acl.deny'])
 
     allowbranches = buildmatch(ui, None, user, 'acl.allow.branches')
     denybranches = buildmatch(ui, None, user, 'acl.deny.branches')
     allow = buildmatch(ui, repo, user, 'acl.allow')
     deny = buildmatch(ui, repo, user, 'acl.deny')
 
-    for rev in xrange(repo[node].rev(), len(repo)):
+    for rev in pycompat.xrange(repo[node].rev(), len(repo)):
         ctx = repo[rev]
         branch = ctx.branch()
         if denybranches and denybranches(branch):
             raise error.Abort(_('acl: user "%s" denied on branch "%s"'
                                ' (changeset "%s")')
                                % (user, branch, ctx))
         if allowbranches and not allowbranches(branch):
             raise error.Abort(_('acl: user "%s" not allowed on branch "%s"'
--- a/hgext/beautifygraph.py
+++ b/hgext/beautifygraph.py
@@ -13,16 +13,17 @@
 
 from __future__ import absolute_import
 
 from mercurial.i18n import _
 from mercurial import (
     encoding,
     extensions,
     graphmod,
+    pycompat,
     templatekw,
 )
 
 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
 # be specifying the version(s) of Mercurial they are tested with, or
 # leave the attribute unspecified.
 testedwith = 'ships-with-hg-core'
@@ -48,17 +49,17 @@ def prettyedge(before, edge, after):
         if after  == ' ' and not before == ' ':
             return '\xE2\x94\xA4' # U+2524 ┤
         return '\xE2\x94\xBC' # U+253C ┼
     return edge
 
 def convertedges(line):
     line = ' %s ' % line
     pretty = []
-    for idx in xrange(len(line) - 2):
+    for idx in pycompat.xrange(len(line) - 2):
         pretty.append(prettyedge(line[idx], line[idx + 1], line[idx + 2]))
     return ''.join(pretty)
 
 def getprettygraphnode(orig, *args, **kwargs):
     node = orig(*args, **kwargs)
     if node == 'o':
         return '\xE2\x97\x8B' # U+25CB ○
     if node == '@':
--- a/hgext/blackbox.py
+++ b/hgext/blackbox.py
@@ -40,16 +40,17 @@ from __future__ import absolute_import
 import errno
 import re
 
 from mercurial.i18n import _
 from mercurial.node import hex
 
 from mercurial import (
     encoding,
+    pycompat,
     registrar,
     ui as uimod,
     util,
 )
 from mercurial.utils import (
     dateutil,
     procutil,
 )
@@ -106,17 +107,17 @@ def _openlogfile(ui, vfs):
         try:
             st = vfs.stat(name)
         except OSError:
             pass
         else:
             if st.st_size >= maxsize:
                 path = vfs.join(name)
                 maxfiles = ui.configint('blackbox', 'maxfiles')
-                for i in xrange(maxfiles - 1, 1, -1):
+                for i in pycompat.xrange(maxfiles - 1, 1, -1):
                     rotate(oldpath='%s.%d' % (path, i - 1),
                            newpath='%s.%d' % (path, i))
                 rotate(oldpath=path,
                        newpath=maxfiles > 0 and path + '.1')
     return vfs(name, 'a')
 
 def wrapui(ui):
     class blackboxui(ui.__class__):
--- a/hgext/censor.py
+++ b/hgext/censor.py
@@ -27,16 +27,17 @@ revisions if they are allowed by the "ce
 
 from __future__ import absolute_import
 
 from mercurial.i18n import _
 from mercurial.node import short
 
 from mercurial import (
     error,
+    pycompat,
     registrar,
     revlog,
     scmutil,
     util,
 )
 
 cmdtable = {}
 command = registrar.command(cmdtable)
@@ -155,17 +156,17 @@ def _docensor(ui, repo, path, rev='', to
         dataread.seek(flog.length(r), 1)
         return newcomp
 
     # Rewrite censored revlog entry with (padded) tombstone data.
     pad = ' ' * (flog.rawsize(crev) - len(tombstone))
     offset += rewrite(crev, offset, tombstone + pad, revlog.REVIDX_ISCENSORED)
 
     # Rewrite all following filelog revisions fixing up offsets and deltas.
-    for srev in xrange(crev + 1, len(flog)):
+    for srev in pycompat.xrange(crev + 1, len(flog)):
         if crev in flog.parentrevs(srev):
             # Immediate children of censored node must be re-added as fulltext.
             try:
                 revdata = flog.revision(srev)
             except error.CensoredNodeError as e:
                 revdata = e.tombstone
             dlen = rewrite(srev, offset, revdata)
         else:
--- a/hgext/convert/cvsps.py
+++ b/hgext/convert/cvsps.py
@@ -758,17 +758,17 @@ def createchangeset(ui, log, fuzz=60, me
         if c.branch in branches:
             p = branches[c.branch]
         else:
             # first changeset on a new branch
             # the parent is a changeset with the branch in its
             # branchpoints such that it is the latest possible
             # commit without any intervening, unrelated commits.
 
-            for candidate in xrange(i):
+            for candidate in pycompat.xrange(i):
                 if c.branch not in changesets[candidate].branchpoints:
                     if p is not None:
                         break
                     continue
                 p = candidate
 
         c.parents = []
         if p is not None:
--- a/hgext/eol.py
+++ b/hgext/eol.py
@@ -261,17 +261,17 @@ def ensureenabled(ui):
     ui.setconfig('extensions', 'eol', '', source='internal')
     extensions.loadall(ui, ['eol'])
 
 def _checkhook(ui, repo, node, headsonly):
     # Get revisions to check and touched files at the same time
     ensureenabled(ui)
     files = set()
     revs = set()
-    for rev in xrange(repo[node].rev(), len(repo)):
+    for rev in pycompat.xrange(repo[node].rev(), len(repo)):
         revs.add(rev)
         if headsonly:
             ctx = repo[rev]
             files.update(ctx.files())
             for pctx in ctx.parents():
                 revs.discard(pctx.rev())
     failed = []
     for rev in revs:
--- a/hgext/hgk.py
+++ b/hgext/hgk.py
@@ -222,39 +222,39 @@ def revtree(ui, args, repo, full="tree",
         chunk = 100
         while True:
             if chunk > i:
                 chunk = i
                 i = 0
             else:
                 i -= chunk
 
-            for x in xrange(chunk):
+            for x in pycompat.xrange(chunk):
                 if i + x >= count:
                     l[chunk - x:] = [0] * (chunk - x)
                     break
                 if full is not None:
                     if (i + x) in repo:
                         l[x] = repo[i + x]
                         l[x].changeset() # force reading
                 else:
                     if (i + x) in repo:
                         l[x] = 1
-            for x in xrange(chunk - 1, -1, -1):
+            for x in pycompat.xrange(chunk - 1, -1, -1):
                 if l[x] != 0:
                     yield (i + x, full is not None and l[x] or None)
             if i == 0:
                 break
 
     # calculate and return the reachability bitmask for sha
     def is_reachable(ar, reachable, sha):
         if len(ar) == 0:
             return 1
         mask = 0
-        for i in xrange(len(ar)):
+        for i in pycompat.xrange(len(ar)):
             if sha in reachable[i]:
                 mask |= 1 << i
 
         return mask
 
     reachable = []
     stop_sha1 = []
     want_sha1 = []
--- a/hgext/histedit.py
+++ b/hgext/histedit.py
@@ -381,28 +381,28 @@ class histeditstate(object):
 
         keep = lines[index] == 'True'
         index += 1
 
         # Rules
         rules = []
         rulelen = int(lines[index])
         index += 1
-        for i in xrange(rulelen):
+        for i in pycompat.xrange(rulelen):
             ruleaction = lines[index]
             index += 1
             rule = lines[index]
             index += 1
             rules.append((ruleaction, rule))
 
         # Replacements
         replacements = []
         replacementlen = int(lines[index])
         index += 1
-        for i in xrange(replacementlen):
+        for i in pycompat.xrange(replacementlen):
             replacement = lines[index]
             original = node.bin(replacement[:40])
             succ = [node.bin(replacement[i:i + 40]) for i in
                     range(40, len(replacement), 40)]
             replacements.append((original, succ))
             index += 1
 
         backupfile = lines[index]
--- a/hgext/mq.py
+++ b/hgext/mq.py
@@ -409,17 +409,17 @@ class patchheader(object):
     __str__ = encoding.strmethod(__bytes__)
 
     def _delmsg(self):
         '''Remove existing message, keeping the rest of the comments fields.
         If comments contains 'subject: ', message will prepend
         the field and a blank line.'''
         if self.message:
             subj = 'subject: ' + self.message[0].lower()
-            for i in xrange(len(self.comments)):
+            for i in pycompat.xrange(len(self.comments)):
                 if subj == self.comments[i].lower():
                     del self.comments[i]
                     self.message = self.message[2:]
                     break
         ci = 0
         for mi in self.message:
             while mi != self.comments[ci]:
                 ci += 1
@@ -1795,17 +1795,17 @@ class queue(object):
                     # Drop useless copy information
                     for f in list(repo.dirstate.copies()):
                         repo.dirstate.copy(None, f)
                 for f in r:
                     repo.dirstate.remove(f)
                 # if the patch excludes a modified file, mark that
                 # file with mtime=0 so status can see it.
                 mm = []
-                for i in xrange(len(m) - 1, -1, -1):
+                for i in pycompat.xrange(len(m) - 1, -1, -1):
                     if not match1(m[i]):
                         mm.append(m[i])
                         del m[i]
                 for f in m:
                     repo.dirstate.normal(f)
                 for f in mm:
                     repo.dirstate.normallookup(f)
                 for f in forget:
@@ -1903,17 +1903,17 @@ class queue(object):
     def unapplied(self, repo, patch=None):
         if patch and patch not in self.series:
             raise error.Abort(_("patch %s is not in series file") % patch)
         if not patch:
             start = self.seriesend()
         else:
             start = self.series.index(patch) + 1
         unapplied = []
-        for i in xrange(start, len(self.series)):
+        for i in pycompat.xrange(start, len(self.series)):
             pushable, reason = self.pushable(i)
             if pushable:
                 unapplied.append((i, self.series[i]))
             self.explainpushable(i)
         return unapplied
 
     def qseries(self, repo, missing=None, start=0, length=None, status=None,
                 summary=False):
@@ -1941,17 +1941,17 @@ class queue(object):
             self.ui.write('\n')
 
         applied = set([p.name for p in self.applied])
         if length is None:
             length = len(self.series) - start
         if not missing:
             if self.ui.verbose:
                 idxwidth = len("%d" % (start + length - 1))
-            for i in xrange(start, start + length):
+            for i in pycompat.xrange(start, start + length):
                 patch = self.series[i]
                 if patch in applied:
                     char, state = 'A', 'applied'
                 elif self.pushable(i)[0]:
                     char, state = 'U', 'unapplied'
                 else:
                     char, state = 'G', 'guarded'
                 pfx = ''
@@ -2086,17 +2086,17 @@ class queue(object):
         """If all_patches is False, return the index of the next pushable patch
         in the series, or the series length. If all_patches is True, return the
         index of the first patch past the last applied one.
         """
         end = 0
         def nextpatch(start):
             if all_patches or start >= len(self.series):
                 return start
-            for i in xrange(start, len(self.series)):
+            for i in pycompat.xrange(start, len(self.series)):
                 p, reason = self.pushable(i)
                 if p:
                     return i
                 self.explainpushable(i)
             return len(self.series)
         if self.applied:
             p = self.applied[-1].name
             try:
@@ -2871,17 +2871,17 @@ def guard(ui, repo, *args, **opts):
     q = repo.mq
     applied = set(p.name for p in q.applied)
     patch = None
     args = list(args)
     if opts.get(r'list'):
         if args or opts.get(r'none'):
             raise error.Abort(_('cannot mix -l/--list with options or '
                                'arguments'))
-        for i in xrange(len(q.series)):
+        for i in pycompat.xrange(len(q.series)):
             status(i)
         return
     if not args or args[0][0:1] in '-+':
         if not q.applied:
             raise error.Abort(_('no patches applied'))
         patch = q.applied[-1].name
     if patch is None and args[0][0:1] not in '-+':
         patch = args.pop(0)
@@ -3174,24 +3174,26 @@ def select(ui, repo, *args, **opts):
     Returns 0 on success.'''
 
     q = repo.mq
     opts = pycompat.byteskwargs(opts)
     guards = q.active()
     pushable = lambda i: q.pushable(q.applied[i].name)[0]
     if args or opts.get('none'):
         old_unapplied = q.unapplied(repo)
-        old_guarded = [i for i in xrange(len(q.applied)) if not pushable(i)]
+        old_guarded = [i for i in pycompat.xrange(len(q.applied))
+                       if not pushable(i)]
         q.setactive(args)
         q.savedirty()
         if not args:
             ui.status(_('guards deactivated\n'))
         if not opts.get('pop') and not opts.get('reapply'):
             unapplied = q.unapplied(repo)
-            guarded = [i for i in xrange(len(q.applied)) if not pushable(i)]
+            guarded = [i for i in pycompat.xrange(len(q.applied))
+                       if not pushable(i)]
             if len(unapplied) != len(old_unapplied):
                 ui.status(_('number of unguarded, unapplied patches has '
                             'changed from %d to %d\n') %
                           (len(old_unapplied), len(unapplied)))
             if len(guarded) != len(old_guarded):
                 ui.status(_('number of guarded, applied patches has changed '
                             'from %d to %d\n') %
                           (len(old_guarded), len(guarded)))
@@ -3220,17 +3222,17 @@ def select(ui, repo, *args, **opts):
             ui.note(_('active guards:\n'))
             for g in guards:
                 ui.write(g, '\n')
         else:
             ui.write(_('no active guards\n'))
     reapply = opts.get('reapply') and q.applied and q.applied[-1].name
     popped = False
     if opts.get('pop') or opts.get('reapply'):
-        for i in xrange(len(q.applied)):
+        for i in pycompat.xrange(len(q.applied)):
             if not pushable(i):
                 ui.status(_('popping guarded patches\n'))
                 popped = True
                 if i == 0:
                     q.pop(repo, all=True)
                 else:
                     q.pop(repo, q.applied[i - 1].name)
                 break
--- a/hgext/narrow/narrowchangegroup.py
+++ b/hgext/narrow/narrowchangegroup.py
@@ -11,16 +11,17 @@ from mercurial.i18n import _
 from mercurial import (
     changegroup,
     error,
     extensions,
     manifest,
     match as matchmod,
     mdiff,
     node,
+    pycompat,
     revlog,
     util,
 )
 
 def setup():
 
     def _cgmatcher(cgpacker):
         localmatcher = cgpacker._repo.narrowmatch()
@@ -327,17 +328,17 @@ def setup():
                     # is pointed to by linknode. "Know" is in scare
                     # quotes because I haven't done enough examination
                     # of edge cases to convince myself this is really
                     # a fact - it works for all the (admittedly
                     # thorough) cases in our testsuite, but I would be
                     # somewhat unsurprised to find a case in the wild
                     # where this breaks down a bit. That said, I don't
                     # know if it would hurt anything.
-                    for i in xrange(rev, 0, -1):
+                    for i in pycompat.xrange(rev, 0, -1):
                         if revlog.linkrev(i) == clrev:
                             return i
                     # We failed to resolve a parent for this node, so
                     # we crash the changegroup construction.
                     raise error.Abort(
                         'unable to resolve parent while packing %r %r'
                         ' for changeset %r' % (revlog.indexfile, rev, clrev))
             return node.nullrev
--- a/hgext/shelve.py
+++ b/hgext/shelve.py
@@ -778,17 +778,17 @@ def _rebaserestoredcommit(ui, repo, opts
         ui.status(_('rebasing shelved changes\n'))
         stats = merge.graft(repo, shelvectx, shelvectx.p1(),
                            labels=['shelve', 'working-copy'],
                            keepconflictparent=True)
         if stats.unresolvedcount:
             tr.close()
 
             nodestoremove = [repo.changelog.node(rev)
-                             for rev in xrange(oldtiprev, len(repo))]
+                             for rev in pycompat.xrange(oldtiprev, len(repo))]
             shelvedstate.save(repo, basename, pctx, tmpwctx, nodestoremove,
                               branchtorestore, opts.get('keep'), activebookmark)
             raise error.InterventionRequired(
                 _("unresolved conflicts (see 'hg resolve', then "
                   "'hg unshelve --continue')"))
 
         with repo.dirstate.parentchange():
             repo.setparents(tmpwctx.node(), nodemod.nullid)
--- a/hgext/win32text.py
+++ b/hgext/win32text.py
@@ -44,16 +44,17 @@ pushed or pulled::
 from __future__ import absolute_import
 
 import re
 from mercurial.i18n import _
 from mercurial.node import (
     short,
 )
 from mercurial import (
+    pycompat,
     registrar,
 )
 from mercurial.utils import (
     stringutil,
 )
 
 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
@@ -136,17 +137,18 @@ def forbidnewline(ui, repo, hooktype, no
     halt = False
     seen = set()
     # we try to walk changesets in reverse order from newest to
     # oldest, so that if we see a file multiple times, we take the
     # newest version as canonical. this prevents us from blocking a
     # changegroup that contains an unacceptable commit followed later
     # by a commit that fixes the problem.
     tip = repo['tip']
-    for rev in xrange(repo.changelog.tiprev(), repo[node].rev() - 1, -1):
+    for rev in pycompat.xrange(repo.changelog.tiprev(),
+                               repo[node].rev() - 1, -1):
         c = repo[rev]
         for f in c.files():
             if f in seen or f not in tip or f not in c:
                 continue
             seen.add(f)
             data = c[f].data()
             if not stringutil.binary(data) and newline in data:
                 if not halt:
--- a/mercurial/ancestor.py
+++ b/mercurial/ancestor.py
@@ -6,16 +6,19 @@
 # GNU General Public License version 2 or any later version.
 
 from __future__ import absolute_import
 
 import collections
 import heapq
 
 from .node import nullrev
+from . import (
+    pycompat,
+)
 
 def commonancestorsheads(pfunc, *nodes):
     """Returns a set with the heads of all common ancestors of all nodes,
     heads(::nodes[0] and ::nodes[1] and ...) .
 
     pfunc must return a list of parent vertices for a given vertex.
     """
     if not isinstance(nodes, set):
@@ -169,17 +172,17 @@ class incrementalmissingancestors(object
         # anything in revs > start is definitely not an ancestor of bases
         # revs <= start needs to be investigated
         start = max(bases)
         keepcount = sum(1 for r in revs if r > start)
         if len(revs) == keepcount:
             # no revs to consider
             return
 
-        for curr in xrange(start, min(revs) - 1, -1):
+        for curr in pycompat.xrange(start, min(revs) - 1, -1):
             if curr not in bases:
                 continue
             revs.discard(curr)
             bases.update(pfunc(curr))
             if len(revs) == keepcount:
                 # no more potential revs to discard
                 break
 
@@ -210,17 +213,17 @@ class incrementalmissingancestors(object
         # Now we walk down in reverse topo order, adding parents of nodes
         # already visited to the sets while maintaining the invariants. When a
         # node is found in both revsvisit and basesvisit, it is removed from
         # revsvisit and added to bothvisit. When revsvisit becomes empty, there
         # are no more ancestors of revs that aren't also ancestors of bases, so
         # exit.
 
         missing = []
-        for curr in xrange(start, nullrev, -1):
+        for curr in pycompat.xrange(start, nullrev, -1):
             if not revsvisit:
                 break
 
             if curr in bothvisit:
                 bothvisit.remove(curr)
                 # curr's parents might have made it into revsvisit through
                 # another path
                 for p in pfunc(curr):
--- a/mercurial/bundle2.py
+++ b/mercurial/bundle2.py
@@ -2218,21 +2218,21 @@ def handlerbc(op, inpart):
     rawheader = inpart.read(rbcstruct.size)
     cache = op.repo.revbranchcache()
     cl = op.repo.unfiltered().changelog
     while rawheader:
         header = rbcstruct.unpack(rawheader)
         total += header[1] + header[2]
         utf8branch = inpart.read(header[0])
         branch = encoding.tolocal(utf8branch)
-        for x in xrange(header[1]):
+        for x in pycompat.xrange(header[1]):
             node = inpart.read(20)
             rev = cl.rev(node)
             cache.setdata(branch, rev, node, False)
-        for x in xrange(header[2]):
+        for x in pycompat.xrange(header[2]):
             node = inpart.read(20)
             rev = cl.rev(node)
             cache.setdata(branch, rev, node, True)
         rawheader = inpart.read(rbcstruct.size)
     cache.write()
 
 @parthandler('pushvars')
 def bundle2getvars(op, part):
--- a/mercurial/changegroup.py
+++ b/mercurial/changegroup.py
@@ -320,17 +320,17 @@ class cg1unpacker(object):
                                             total=changesets)
             self._unpackmanifests(repo, revmap, trp, progress)
 
             needfiles = {}
             if repo.ui.configbool('server', 'validate'):
                 cl = repo.changelog
                 ml = repo.manifestlog
                 # validate incoming csets have their manifests
-                for cset in xrange(clstart, clend):
+                for cset in pycompat.xrange(clstart, clend):
                     mfnode = cl.changelogrevision(cset).manifest
                     mfest = ml[mfnode].readdelta()
                     # store file cgnodes we must see
                     for f, n in mfest.iteritems():
                         needfiles.setdefault(f, set()).add(n)
 
             # process the files
             repo.ui.status(_("adding file changes\n"))
@@ -362,17 +362,17 @@ class cg1unpacker(object):
                     hookargs = dict(tr.hookargs)
                 else:
                     hookargs = dict(tr.hookargs)
                     hookargs['node'] = hex(cl.node(clstart))
                     hookargs['node_last'] = hex(cl.node(clend - 1))
                 repo.hook('pretxnchangegroup',
                           throw=True, **pycompat.strkwargs(hookargs))
 
-            added = [cl.node(r) for r in xrange(clstart, clend)]
+            added = [cl.node(r) for r in pycompat.xrange(clstart, clend)]
             phaseall = None
             if srctype in ('push', 'serve'):
                 # Old servers can not push the boundary themselves.
                 # New servers won't push the boundary if changeset already
                 # exists locally as secret
                 #
                 # We should not use added here but the list of all change in
                 # the bundle
@@ -563,17 +563,17 @@ class cg1packer(object):
         p = revlog.parentrevs(revs[0])[0]
         revs.insert(0, p)
 
         # build deltas
         progress = None
         if units is not None:
             progress = self._repo.ui.makeprogress(_('bundling'), unit=units,
                                                   total=(len(revs) - 1))
-        for r in xrange(len(revs) - 1):
+        for r in pycompat.xrange(len(revs) - 1):
             if progress:
                 progress.update(r + 1)
             prev, curr = revs[r], revs[r + 1]
             linknode = lookup(revlog.node(curr))
             for c in self.revchunk(revlog, curr, prev, linknode):
                 yield c
 
         if progress:
@@ -984,17 +984,17 @@ def _addchangegroupfiles(repo, source, r
             deltas = source.deltaiter()
             if not fl.addgroup(deltas, revmap, trp):
                 raise error.Abort(_("received file revlog group is empty"))
         except error.CensoredBaseError as e:
             raise error.Abort(_("received delta base is censored: %s") % e)
         revisions += len(fl) - o
         if f in needfiles:
             needs = needfiles[f]
-            for new in xrange(o, len(fl)):
+            for new in pycompat.xrange(o, len(fl)):
                 n = fl.node(new)
                 if n in needs:
                     needs.remove(n)
                 else:
                     raise error.Abort(
                         _("received spurious file revlog entry"))
             if not needs:
                 del needfiles[f]
--- a/mercurial/changelog.py
+++ b/mercurial/changelog.py
@@ -308,17 +308,17 @@ class changelog(revlog.revlog):
 
         self._realopener = opener
         self._delayed = False
         self._delaybuf = None
         self._divert = False
         self.filteredrevs = frozenset()
 
     def tiprev(self):
-        for i in xrange(len(self) -1, -2, -1):
+        for i in pycompat.xrange(len(self) -1, -2, -1):
             if i not in self.filteredrevs:
                 return i
 
     def tip(self):
         """filtered version of revlog.tip"""
         return self.node(self.tiprev())
 
     def __contains__(self, rev):
@@ -327,17 +327,17 @@ class changelog(revlog.revlog):
                 and rev not in self.filteredrevs)
 
     def __iter__(self):
         """filtered version of revlog.__iter__"""
         if len(self.filteredrevs) == 0:
             return revlog.revlog.__iter__(self)
 
         def filterediter():
-            for i in xrange(len(self)):
+            for i in pycompat.xrange(len(self)):
                 if i not in self.filteredrevs:
                     yield i
 
         return filterediter()
 
     def revs(self, start=0, stop=None):
         """filtered version of revlog.revs"""
         for i in super(changelog, self).revs(start, stop):
@@ -558,13 +558,13 @@ class changelog(revlog.revlog):
         # revision on the transaction.
         rev = len(self)
         node = super(changelog, self)._addrevision(node, rawtext, transaction,
                                                    *args, **kwargs)
         revs = transaction.changes.get('revs')
         if revs is not None:
             if revs:
                 assert revs[-1] + 1 == rev
-                revs = xrange(revs[0], rev + 1)
+                revs = pycompat.xrange(revs[0], rev + 1)
             else:
-                revs = xrange(rev, rev + 1)
+                revs = pycompat.xrange(rev, rev + 1)
             transaction.changes['revs'] = revs
         return node
--- a/mercurial/cmdutil.py
+++ b/mercurial/cmdutil.py
@@ -1750,17 +1750,17 @@ def walkfilerevs(repo, match, follow, re
         Only files, no patterns.  Check the history of each file.
 
         Examines filelog entries within minrev, maxrev linkrev range
         Returns an iterator yielding (linkrev, parentlinkrevs, copied)
         tuples in backwards order
         """
         cl_count = len(repo)
         revs = []
-        for j in xrange(0, last + 1):
+        for j in pycompat.xrange(0, last + 1):
             linkrev = filelog.linkrev(j)
             if linkrev < minrev:
                 continue
             # only yield rev for which we have the changelog, it can
             # happen while doing "hg log" during a pull or commit
             if linkrev >= cl_count:
                 break
 
@@ -1961,17 +1961,17 @@ def walkchangerevs(repo, match, opts, pr
         wanted = lazywantedset()
 
     # it might be worthwhile to do this in the iterator if the rev range
     # is descending and the prune args are all within that range
     for rev in opts.get('prune', ()):
         rev = repo[rev].rev()
         ff = _followfilter(repo)
         stop = min(revs[0], revs[-1])
-        for x in xrange(rev, stop - 1, -1):
+        for x in pycompat.xrange(rev, stop - 1, -1):
             if ff.match(x):
                 wanted = wanted - [x]
 
     # Now that wanted is correctly initialized, we can iterate over the
     # revision range, yielding only revisions in wanted.
     def iterate():
         if follow and match.always():
             ff = _followfilter(repo, onlyfirst=opts.get('follow_first'))
@@ -1980,17 +1980,17 @@ def walkchangerevs(repo, match, opts, pr
         else:
             def want(rev):
                 return rev in wanted
 
         it = iter(revs)
         stopiteration = False
         for windowsize in increasingwindows():
             nrevs = []
-            for i in xrange(windowsize):
+            for i in pycompat.xrange(windowsize):
                 rev = next(it, None)
                 if rev is None:
                     stopiteration = True
                     break
                 elif want(rev):
                     nrevs.append(rev)
             for rev in sorted(nrevs):
                 fns = fncache.get(rev)
--- a/mercurial/commands.py
+++ b/mercurial/commands.py
@@ -2602,25 +2602,25 @@ def grep(ui, repo, pattern, *pats, **opt
         for lnum, cstart, cend, line in matchlines(body):
             s = linestate(line, lnum, cstart, cend)
             m.append(s)
 
     def difflinestates(a, b):
         sm = difflib.SequenceMatcher(None, a, b)
         for tag, alo, ahi, blo, bhi in sm.get_opcodes():
             if tag == 'insert':
-                for i in xrange(blo, bhi):
+                for i in pycompat.xrange(blo, bhi):
                     yield ('+', b[i])
             elif tag == 'delete':
-                for i in xrange(alo, ahi):
+                for i in pycompat.xrange(alo, ahi):
                     yield ('-', a[i])
             elif tag == 'replace':
-                for i in xrange(alo, ahi):
+                for i in pycompat.xrange(alo, ahi):
                     yield ('-', a[i])
-                for i in xrange(blo, bhi):
+                for i in pycompat.xrange(blo, bhi):
                     yield ('+', b[i])
 
     def display(fm, fn, ctx, pstates, states):
         rev = scmutil.intrev(ctx)
         if fm.isplain():
             formatuser = ui.shortuser
         else:
             formatuser = str
--- a/mercurial/context.py
+++ b/mercurial/context.py
@@ -1891,17 +1891,17 @@ class overlayworkingctx(committablectx):
             else:
                 raise error.Abort("error: '%s' conflicts with file '%s' in "
                                   "%s." % (path, component,
                                            self.p1().rev()))
 
         # Test that each new directory to be created to write this path from p2
         # is not a file in p1.
         components = path.split('/')
-        for i in xrange(len(components)):
+        for i in pycompat.xrange(len(components)):
             component = "/".join(components[0:i])
             if component in self.p1():
                 fail(path, component)
 
         # Test the other direction -- that this path from p2 isn't a directory
         # in p1 (test that p1 doesn't any paths matching `path/*`).
         match = matchmod.match('/', '', [path + '/'], default=b'relpath')
         matches = self.p1().manifest().matches(match)
--- a/mercurial/dagop.py
+++ b/mercurial/dagop.py
@@ -190,17 +190,17 @@ def _genrevdescendants(repo, revs, follo
                     seen.add(i)
                     yield i
                     break
 
 def _builddescendantsmap(repo, startrev, followfirst):
     """Build map of 'rev -> child revs', offset from startrev"""
     cl = repo.changelog
     nullrev = node.nullrev
-    descmap = [[] for _rev in xrange(startrev, len(cl))]
+    descmap = [[] for _rev in pycompat.xrange(startrev, len(cl))]
     for currev in cl.revs(startrev + 1):
         p1rev, p2rev = cl.parentrevs(currev)
         if p1rev >= startrev:
             descmap[p1rev - startrev].append(currev)
         if not followfirst and p2rev != nullrev and p2rev >= startrev:
             descmap[p2rev - startrev].append(currev)
     return descmap
 
@@ -430,30 +430,30 @@ def _annotatepair(parents, childfctx, ch
         #   diff hunks 1:1, dropping lines as necessary.
         # * Repeat the last line as a last resort.
 
         # First, replace as much as possible without repeating the last line.
         remaining = [(parent, []) for parent, _blocks in pblocks]
         for idx, (parent, blocks) in enumerate(pblocks):
             for (a1, a2, b1, b2), _t in blocks:
                 if a2 - a1 >= b2 - b1:
-                    for bk in xrange(b1, b2):
+                    for bk in pycompat.xrange(b1, b2):
                         if child.fctxs[bk] == childfctx:
                             ak = min(a1 + (bk - b1), a2 - 1)
                             child.fctxs[bk] = parent.fctxs[ak]
                             child.linenos[bk] = parent.linenos[ak]
                             child.skips[bk] = True
                 else:
                     remaining[idx][1].append((a1, a2, b1, b2))
 
         # Then, look at anything left, which might involve repeating the last
         # line.
         for parent, blocks in remaining:
             for a1, a2, b1, b2 in blocks:
-                for bk in xrange(b1, b2):
+                for bk in pycompat.xrange(b1, b2):
                     if child.fctxs[bk] == childfctx:
                         ak = min(a1 + (bk - b1), a2 - 1)
                         child.fctxs[bk] = parent.fctxs[ak]
                         child.linenos[bk] = parent.linenos[ak]
                         child.skips[bk] = True
     return child
 
 def annotate(base, parents, skiprevs=None, diffopts=None):
--- a/mercurial/dagparser.py
+++ b/mercurial/dagparser.py
@@ -217,17 +217,17 @@ def parsedag(desc):
         if c == '.':
             yield 'n', (r, [p1])
             p1 = r
             r += 1
             c = nextch()
         elif c == '+':
             c, digs = nextrun(nextch(), pycompat.bytestr(string.digits))
             n = int(digs)
-            for i in xrange(0, n):
+            for i in pycompat.xrange(0, n):
                 yield 'n', (r, [p1])
                 p1 = r
                 r += 1
         elif c in '*/':
             if c == '*':
                 c = nextch()
             c, pref = nextstring(c)
             prefs = [pref]
--- a/mercurial/debugcommands.py
+++ b/mercurial/debugcommands.py
@@ -172,17 +172,18 @@ def debugbuilddag(ui, repo, text=None,
     total = 0
     for type, data in dagparser.parsedag(text):
         if type == 'n':
             total += 1
 
     if mergeable_file:
         linesperrev = 2
         # make a file with k lines per rev
-        initialmergedlines = ['%d' % i for i in xrange(0, total * linesperrev)]
+        initialmergedlines = ['%d' % i
+                              for i in pycompat.xrange(0, total * linesperrev)]
         initialmergedlines.append("")
 
     tags = []
     progress = ui.makeprogress(_('building'), unit=_('revisions'),
                                total=total)
     with progress, repo.wlock(), repo.lock(), repo.transaction("builddag"):
         at = -1
         atbranch = 'default'
@@ -2013,17 +2014,17 @@ def debugrevlog(ui, repo, file_=None, **
 
     if opts.get("dump"):
         numrevs = len(r)
         ui.write(("# rev p1rev p2rev start   end deltastart base   p1   p2"
                  " rawsize totalsize compression heads chainlen\n"))
         ts = 0
         heads = set()
 
-        for rev in xrange(numrevs):
+        for rev in pycompat.xrange(numrevs):
             dbase = r.deltaparent(rev)
             if dbase == -1:
                 dbase = rev
             cbase = r.chainbase(rev)
             clen = r.chainlen(rev)
             p1, p2 = r.parentrevs(rev)
             rs = r.rawsize(rev)
             ts = ts + rs
@@ -2074,17 +2075,17 @@ def debugrevlog(ui, repo, file_=None, **
     def addsize(size, l):
         if l[0] is None or size < l[0]:
             l[0] = size
         if size > l[1]:
             l[1] = size
         l[2] += size
 
     numrevs = len(r)
-    for rev in xrange(numrevs):
+    for rev in pycompat.xrange(numrevs):
         p1, p2 = r.parentrevs(rev)
         delta = r.deltaparent(rev)
         if format > 0:
             addsize(r.rawsize(rev), datasize)
         if p2 != nullrev:
             nummerges += 1
         size = r.length(rev)
         if delta == nullrev:
--- a/mercurial/diffhelper.py
+++ b/mercurial/diffhelper.py
@@ -6,32 +6,33 @@
 # GNU General Public License version 2 or any later version.
 
 from __future__ import absolute_import
 
 from .i18n import _
 
 from . import (
     error,
+    pycompat,
 )
 
 def addlines(fp, hunk, lena, lenb, a, b):
     """Read lines from fp into the hunk
 
     The hunk is parsed into two arrays, a and b. a gets the old state of
     the text, b gets the new state. The control char from the hunk is saved
     when inserting into a, but not b (for performance while deleting files.)
     """
     while True:
         todoa = lena - len(a)
         todob = lenb - len(b)
         num = max(todoa, todob)
         if num == 0:
             break
-        for i in xrange(num):
+        for i in pycompat.xrange(num):
             s = fp.readline()
             if not s:
                 raise error.ParseError(_('incomplete hunk'))
             if s == "\\ No newline at end of file\n":
                 fixnewline(hunk, a, b)
                 continue
             if s == '\n' or s == '\r\n':
                 # Some patches may be missing the control char
@@ -66,12 +67,12 @@ def testhunk(a, b, bstart):
 
     a is assumed to have a control char at the start of each line, this char
     is ignored in the compare.
     """
     alen = len(a)
     blen = len(b)
     if alen > blen - bstart or bstart < 0:
         return False
-    for i in xrange(alen):
+    for i in pycompat.xrange(alen):
         if a[i][1:] != b[i + bstart]:
             return False
     return True
--- a/mercurial/encoding.py
+++ b/mercurial/encoding.py
@@ -246,17 +246,17 @@ def ucolwidth(d):
     eaw = getattr(unicodedata, 'east_asian_width', None)
     if eaw is not None:
         return sum([eaw(c) in _wide and 2 or 1 for c in d])
     return len(d)
 
 def getcols(s, start, c):
     '''Use colwidth to find a c-column substring of s starting at byte
     index start'''
-    for x in xrange(start + c, len(s)):
+    for x in pycompat.xrange(start + c, len(s)):
         t = s[start:x]
         if colwidth(t) == c:
             return t
 
 def trim(s, width, ellipsis='', leftside=False):
     """Trim string 's' to at most 'width' columns (including 'ellipsis').
 
     If 'leftside' is True, left side of string 's' is trimmed.
@@ -341,17 +341,17 @@ def trim(s, width, ellipsis='', leftside
         return ellipsis[:width + len(ellipsis)]
 
     if leftside:
         uslice = lambda i: u[i:]
         concat = lambda s: ellipsis + s
     else:
         uslice = lambda i: u[:-i]
         concat = lambda s: s + ellipsis
-    for i in xrange(1, len(u)):
+    for i in pycompat.xrange(1, len(u)):
         usub = uslice(i)
         if ucolwidth(usub) <= width:
             return concat(usub.encode(_sysstr(encoding)))
     return ellipsis # no enough room for multi-column characters
 
 def lower(s):
     "best-effort encoding-aware case-folding of local string s"
     try:
--- a/mercurial/graphmod.py
+++ b/mercurial/graphmod.py
@@ -17,16 +17,17 @@ context of the graph returned. Type is a
 Data depends on type.
 """
 
 from __future__ import absolute_import
 
 from .node import nullrev
 from . import (
     dagop,
+    pycompat,
     smartset,
     util,
 )
 
 CHANGESET = 'C'
 PARENT = 'P'
 GRANDPARENT = 'G'
 MISSINGPARENT = 'M'
@@ -421,26 +422,26 @@ def ascii(ui, state, type, char, text, c
     nodeline.extend(
         _getnodelineedgestail(
             echars, idx, state['lastindex'], ncols, coldiff,
             state['lastcoldiff'], fix_nodeline_tail))
 
     # shift_interline is the line containing the non-vertical
     # edges between this entry and the next
     shift_interline = echars[:idx * 2]
-    for i in xrange(2 + coldiff):
+    for i in pycompat.xrange(2 + coldiff):
         shift_interline.append(' ')
     count = ncols - idx - 1
     if coldiff == -1:
-        for i in xrange(count):
+        for i in pycompat.xrange(count):
             shift_interline.extend(['/', ' '])
     elif coldiff == 0:
         shift_interline.extend(echars[(idx + 1) * 2:ncols * 2])
     else:
-        for i in xrange(count):
+        for i in pycompat.xrange(count):
             shift_interline.extend(['\\', ' '])
 
     # draw edges from the current node to its parents
     _drawedges(echars, edges, nodeline, shift_interline)
 
     # lines is the list of all graph lines to print
     lines = [nodeline]
     if add_padding_line:
--- a/mercurial/hgweb/webcommands.py
+++ b/mercurial/hgweb/webcommands.py
@@ -210,17 +210,17 @@ def _search(web):
         yield ctx
 
     def keywordsearch(query):
         lower = encoding.lower
         qw = lower(query).split()
 
         def revgen():
             cl = web.repo.changelog
-            for i in xrange(len(web.repo) - 1, 0, -100):
+            for i in pycompat.xrange(len(web.repo) - 1, 0, -100):
                 l = []
                 for j in cl.revs(max(0, i - 99), i):
                     ctx = web.repo[j]
                     l.append(ctx)
                 l.reverse()
                 for e in l:
                     yield e
 
--- a/mercurial/hgweb/webutil.py
+++ b/mercurial/hgweb/webutil.py
@@ -608,31 +608,31 @@ def _compline(type, leftlineno, leftline
         'rightline': rightline or '',
     }
 
 def _getcompblockgen(context, leftlines, rightlines, opcodes):
     for type, llo, lhi, rlo, rhi in opcodes:
         len1 = lhi - llo
         len2 = rhi - rlo
         count = min(len1, len2)
-        for i in xrange(count):
+        for i in pycompat.xrange(count):
             yield _compline(type=type,
                             leftlineno=llo + i + 1,
                             leftline=leftlines[llo + i],
                             rightlineno=rlo + i + 1,
                             rightline=rightlines[rlo + i])
         if len1 > len2:
-            for i in xrange(llo + count, lhi):
+            for i in pycompat.xrange(llo + count, lhi):
                 yield _compline(type=type,
                                 leftlineno=i + 1,
                                 leftline=leftlines[i],
                                 rightlineno=None,
                                 rightline=None)
         elif len2 > len1:
-            for i in xrange(rlo + count, rhi):
+            for i in pycompat.xrange(rlo + count, rhi):
                 yield _compline(type=type,
                                 leftlineno=None,
                                 leftline=None,
                                 rightlineno=i + 1,
                                 rightline=rightlines[i])
 
 def _getcompblock(leftlines, rightlines, opcodes):
     args = (leftlines, rightlines, opcodes)
--- a/mercurial/httppeer.py
+++ b/mercurial/httppeer.py
@@ -59,17 +59,17 @@ def encodevalueinheaders(value, header, 
     # and not a unicode: we're just getting the encoded length anyway,
     # and using an r-string to make it portable between Python 2 and 3
     # doesn't work because then the \r is a literal backslash-r
     # instead of a carriage return.
     valuelen = limit - len(fmt % r'000') - len(': \r\n')
     result = []
 
     n = 0
-    for i in xrange(0, len(value), valuelen):
+    for i in pycompat.xrange(0, len(value), valuelen):
         n += 1
         result.append((fmt % str(n), pycompat.strurl(value[i:i + valuelen])))
 
     return result
 
 def _wraphttpresponse(resp):
     """Wrap an HTTPResponse with common error handlers.
 
--- a/mercurial/localrepo.py
+++ b/mercurial/localrepo.py
@@ -845,17 +845,17 @@ class localrepository(object):
     def __getitem__(self, changeid):
         if changeid is None:
             return context.workingctx(self)
         if isinstance(changeid, context.basectx):
             return changeid
         if isinstance(changeid, slice):
             # wdirrev isn't contiguous so the slice shouldn't include it
             return [context.changectx(self, i)
-                    for i in xrange(*changeid.indices(len(self)))
+                    for i in pycompat.xrange(*changeid.indices(len(self)))
                     if i not in self.changelog.filteredrevs]
         try:
             return context.changectx(self, changeid)
         except error.WdirUnsupported:
             return context.workingctx(self)
 
     def __contains__(self, changeid):
         """True if the given changeid exists
@@ -1380,17 +1380,17 @@ class localrepository(object):
                                      "journal",
                                      "undo",
                                      aftertrans(renames),
                                      self.store.createmode,
                                      validator=validate,
                                      releasefn=releasefn,
                                      checkambigfiles=_cachedfiles,
                                      name=desc)
-        tr.changes['revs'] = xrange(0, 0)
+        tr.changes['revs'] = pycompat.xrange(0, 0)
         tr.changes['obsmarkers'] = set()
         tr.changes['phases'] = {}
         tr.changes['bookmarks'] = {}
 
         tr.hookargs['txnid'] = txnid
         # note: writing the fncache only during finalize mean that the file is
         # outdated when running hooks. As fncache is used for streaming clone,
         # this is not expected to break anything that happen during the hooks.
--- a/mercurial/mdiff.py
+++ b/mercurial/mdiff.py
@@ -352,17 +352,17 @@ def _unidiff(t1, t2, opts=defaultopts):
         blen = b2 - bstart + aend - a2
 
         func = ""
         if opts.showfunc:
             lastpos, func = lastfunc
             # walk backwards from the start of the context up to the start of
             # the previous hunk context until we find a line starting with an
             # alphanumeric char.
-            for i in xrange(astart - 1, lastpos - 1, -1):
+            for i in pycompat.xrange(astart - 1, lastpos - 1, -1):
                 if l1[i][0:1].isalnum():
                     func = b' ' + l1[i].rstrip()
                     # split long function name if ASCII. otherwise we have no
                     # idea where the multi-byte boundary is, so just leave it.
                     if encoding.isasciistr(func):
                         func = func[:41]
                     lastfunc[1] = func
                     break
@@ -376,34 +376,34 @@ def _unidiff(t1, t2, opts=defaultopts):
             astart += 1
         if blen:
             bstart += 1
 
         hunkrange = astart, alen, bstart, blen
         hunklines = (
             ["@@ -%d,%d +%d,%d @@%s\n" % (hunkrange + (func,))]
             + delta
-            + [' ' + l1[x] for x in xrange(a2, aend)]
+            + [' ' + l1[x] for x in pycompat.xrange(a2, aend)]
         )
         # If either file ends without a newline and the last line of
         # that file is part of a hunk, a marker is printed. If the
         # last line of both files is identical and neither ends in
         # a newline, print only one marker. That's the only case in
         # which the hunk can end in a shared line without a newline.
         skip = False
         if not t1.endswith('\n') and astart + alen == len(l1) + 1:
-            for i in xrange(len(hunklines) - 1, -1, -1):
+            for i in pycompat.xrange(len(hunklines) - 1, -1, -1):
                 if hunklines[i].startswith(('-', ' ')):
                     if hunklines[i].startswith(' '):
                         skip = True
                     hunklines[i] += '\n'
                     hunklines.insert(i + 1, _missing_newline_marker)
                     break
         if not skip and not t2.endswith('\n') and bstart + blen == len(l2) + 1:
-            for i in xrange(len(hunklines) - 1, -1, -1):
+            for i in pycompat.xrange(len(hunklines) - 1, -1, -1):
                 if hunklines[i].startswith('+'):
                     hunklines[i] += '\n'
                     hunklines.insert(i + 1, _missing_newline_marker)
                     break
         yield hunkrange, hunklines
 
     # bdiff.blocks gives us the matching sequences in the files.  The loop
     # below finds the spaces between those matching sequences and translates
--- a/mercurial/minirst.py
+++ b/mercurial/minirst.py
@@ -311,17 +311,17 @@ def findtables(blocks):
             _tablere.match(block['lines'][0]) and
             block['lines'][0] == block['lines'][-1]):
             block['type'] = 'table'
             block['header'] = False
             div = block['lines'][0]
 
             # column markers are ASCII so we can calculate column
             # position in bytes
-            columns = [x for x in xrange(len(div))
+            columns = [x for x in pycompat.xrange(len(div))
                        if div[x:x + 1] == '=' and (x == 0 or
                                                    div[x - 1:x] == ' ')]
             rows = []
             for l in block['lines'][1:-1]:
                 if l == div:
                     block['header'] = True
                     continue
                 row = []
@@ -680,17 +680,17 @@ def format(text, width=80, indent=0, kee
             parents.append(i)
             if name == section:
                 if lastparents != parents:
                     llen = len(lastparents)
                     plen = len(parents)
                     if llen and llen != plen:
                         collapse = False
                     s = []
-                    for j in xrange(3, plen - 1):
+                    for j in pycompat.xrange(3, plen - 1):
                         parent = parents[j]
                         if (j >= llen or
                             lastparents[j] != parent):
                             s.append(len(blocks))
                             sec = sections[parent][2]
                             blocks.append(sec[0])
                             blocks.append(sec[-1])
                     if s:
--- a/mercurial/obsolete.py
+++ b/mercurial/obsolete.py
@@ -389,17 +389,17 @@ def _fm1purereadmarkers(data, off, stop)
             else:
                 o3 = o2 + sha1size * numpar
                 parents = unpack(sha1fmt * numpar, data[o2:o3])
 
         # read metadata
         off = o3 + metasize * nummeta
         metapairsize = unpack('>' + (metafmt * nummeta), data[o3:off])
         metadata = []
-        for idx in xrange(0, len(metapairsize), 2):
+        for idx in pycompat.xrange(0, len(metapairsize), 2):
             o1 = off + metapairsize[idx]
             o2 = o1 + metapairsize[idx + 1]
             metadata.append((data[off:o1], data[o1:o2]))
             off = o2
 
         yield (prec, sucs, flags, tuple(metadata), (secs, tz * 60), parents)
 
 def _fm1encodeonemarker(marker):
--- a/mercurial/patch.py
+++ b/mercurial/patch.py
@@ -810,17 +810,17 @@ class patchfile(object):
                 self.dirty = True
             return 0
 
         # ok, we couldn't match the hunk. Lets look for offsets and fuzz it
         self.hash = {}
         for x, s in enumerate(self.lines):
             self.hash.setdefault(s, []).append(x)
 
-        for fuzzlen in xrange(self.ui.configint("patch", "fuzz") + 1):
+        for fuzzlen in pycompat.xrange(self.ui.configint("patch", "fuzz") + 1):
             for toponly in [True, False]:
                 old, oldstart, new, newstart = h.fuzzit(fuzzlen, toponly)
                 oldstart = oldstart + self.offset + self.skew
                 oldstart = min(oldstart, len(self.lines))
                 if old:
                     cand = self.findlines(old[0][1:], oldstart)
                 else:
                     # Only adding lines with no or fuzzed context, just
@@ -1281,17 +1281,17 @@ class hunk(object):
             raise PatchError(_("bad hunk #%d") % self.number)
         self.starta, aend = m.groups()
         self.starta = int(self.starta)
         if aend is None:
             aend = self.starta
         self.lena = int(aend) - self.starta
         if self.starta:
             self.lena += 1
-        for x in xrange(self.lena):
+        for x in pycompat.xrange(self.lena):
             l = lr.readline()
             if l.startswith('---'):
                 # lines addition, old block is empty
                 lr.push(l)
                 break
             s = l[2:]
             if l.startswith('- ') or l.startswith('! '):
                 u = '-' + s
@@ -1315,17 +1315,17 @@ class hunk(object):
         self.startb, bend = m.groups()
         self.startb = int(self.startb)
         if bend is None:
             bend = self.startb
         self.lenb = int(bend) - self.startb
         if self.startb:
             self.lenb += 1
         hunki = 1
-        for x in xrange(self.lenb):
+        for x in pycompat.xrange(self.lenb):
             l = lr.readline()
             if l.startswith('\ '):
                 # XXX: the only way to hit this is with an invalid line range.
                 # The no-eol marker is not counted in the line range, but I
                 # guess there are diff(1) out there which behave differently.
                 s = self.b[-1][:-1]
                 self.b[-1] = s
                 self.hunk[hunki - 1] = s
@@ -1391,24 +1391,24 @@ class hunk(object):
         # this removes context lines from the top and bottom of list 'l'.  It
         # checks the hunk to make sure only context lines are removed, and then
         # returns a new shortened list of lines.
         fuzz = min(fuzz, len(old))
         if fuzz:
             top = 0
             bot = 0
             hlen = len(self.hunk)
-            for x in xrange(hlen - 1):
+            for x in pycompat.xrange(hlen - 1):
                 # the hunk starts with the @@ line, so use x+1
                 if self.hunk[x + 1].startswith(' '):
                     top += 1
                 else:
                     break
             if not toponly:
-                for x in xrange(hlen - 1):
+                for x in pycompat.xrange(hlen - 1):
                     if self.hunk[hlen - bot - 1].startswith(' '):
                         bot += 1
                     else:
                         break
 
             bot = min(fuzz, bot)
             top = min(fuzz, top)
             return old[top:len(old) - bot], new[top:len(new) - bot], top
--- a/mercurial/phases.py
+++ b/mercurial/phases.py
@@ -369,17 +369,17 @@ class phasecache(object):
             phasetracking = None
         else:
             phasetracking = tr.changes.get('phases')
 
         repo = repo.unfiltered()
 
         changes = set() # set of revisions to be changed
         delroots = [] # set of root deleted by this path
-        for phase in xrange(targetphase + 1, len(allphases)):
+        for phase in pycompat.xrange(targetphase + 1, len(allphases)):
             # filter nodes that are not in a compatible phase already
             nodes = [n for n in nodes
                      if self.phase(repo, repo[n].rev()) >= phase]
             if not nodes:
                 break # no roots to move anymore
 
             olds = self.phaseroots[phase]
 
@@ -415,17 +415,17 @@ class phasecache(object):
             and phasetracking is not None):
 
             # find the affected revisions
             new = self.phaseroots[targetphase]
             old = oldroots[targetphase]
             affected = set(repo.revs('(%ln::) - (%ln::)', new, old))
 
             # find the phase of the affected revision
-            for phase in xrange(targetphase, -1, -1):
+            for phase in pycompat.xrange(targetphase, -1, -1):
                 if phase:
                     roots = oldroots[phase]
                     revs = set(repo.revs('%ln::%ld', roots, affected))
                     affected -= revs
                 else: # public phase
                     revs = affected
                 for r in revs:
                     _trackphasechange(phasetracking, r, phase, targetphase)
--- a/mercurial/pure/osutil.py
+++ b/mercurial/pure/osutil.py
@@ -145,17 +145,17 @@ if not pycompat.iswindows:
         if not cmsg:
             return []
         if (cmsg.cmsg_level != socket.SOL_SOCKET or
             cmsg.cmsg_type != _SCM_RIGHTS):
             return []
         rfds = ctypes.cast(cmsg.cmsg_data, ctypes.POINTER(ctypes.c_int))
         rfdscount = ((cmsg.cmsg_len - _cmsghdr.cmsg_data.offset) /
                      ctypes.sizeof(ctypes.c_int))
-        return [rfds[i] for i in xrange(rfdscount)]
+        return [rfds[i] for i in pycompat.xrange(rfdscount)]
 
 else:
     import msvcrt
 
     _kernel32 = ctypes.windll.kernel32
 
     _DWORD = ctypes.c_ulong
     _LPCSTR = _LPSTR = ctypes.c_char_p
--- a/mercurial/pvec.py
+++ b/mercurial/pvec.py
@@ -47,16 +47,17 @@ Uses:
 - can be used to find a heuristic divergence measure between changesets on
   different branches
 '''
 
 from __future__ import absolute_import
 
 from .node import nullrev
 from . import (
+    pycompat,
     util,
 )
 
 _size = 448 # 70 chars b85-encoded
 _bytes = _size / 8
 _depthbits = 24
 _depthbytes = _depthbits / 8
 _vecbytes = _bytes - _depthbytes
@@ -67,17 +68,17 @@ def _bin(bs):
     '''convert a bytestring to a long'''
     v = 0
     for b in bs:
         v = v * 256 + ord(b)
     return v
 
 def _str(v, l):
     bs = ""
-    for p in xrange(l):
+    for p in pycompat.xrange(l):
         bs = chr(v & 255) + bs
         v >>= 8
     return bs
 
 def _split(b):
     '''depth and bitvec'''
     return _bin(b[:_depthbytes]), _bin(b[_depthbytes:])
 
@@ -86,17 +87,17 @@ def _join(depth, bitvec):
 
 def _hweight(x):
     c = 0
     while x:
         if x & 1:
             c += 1
         x >>= 1
     return c
-_htab = [_hweight(x) for x in xrange(256)]
+_htab = [_hweight(x) for x in pycompat.xrange(256)]
 
 def _hamming(a, b):
     '''find the hamming distance between two longs'''
     d = a ^ b
     c = 0
     while d:
         c += _htab[d & 0xff]
         d >>= 8
@@ -147,17 +148,17 @@ def _flipbit(v, node):
 def ctxpvec(ctx):
     '''construct a pvec for ctx while filling in the cache'''
     r = ctx.repo()
     if not util.safehasattr(r, "_pveccache"):
         r._pveccache = {}
     pvc = r._pveccache
     if ctx.rev() not in pvc:
         cl = r.changelog
-        for n in xrange(ctx.rev() + 1):
+        for n in pycompat.xrange(ctx.rev() + 1):
             if n not in pvc:
                 node = cl.node(n)
                 p1, p2 = cl.parentrevs(n)
                 if p1 == nullrev:
                     # start with a 'random' vector at root
                     pvc[n] = (0, _bin((node * 3)[:_vecbytes]))
                 elif p2 == nullrev:
                     d, v = pvc[p1]
--- a/mercurial/repair.py
+++ b/mercurial/repair.py
@@ -19,16 +19,17 @@ from .node import (
 from . import (
     bundle2,
     changegroup,
     discovery,
     error,
     exchange,
     obsolete,
     obsutil,
+    pycompat,
     util,
 )
 from .utils import (
     stringutil,
 )
 
 def backupbundle(repo, bases, heads, node, suffix, compress=True,
                  obsolescence=True):
@@ -65,17 +66,17 @@ def backupbundle(repo, bases, heads, nod
     }
     return bundle2.writenewbundle(repo.ui, repo, 'strip', name, bundletype,
                                   outgoing, contentopts, vfs, compression=comp)
 
 def _collectfiles(repo, striprev):
     """find out the filelogs affected by the strip"""
     files = set()
 
-    for x in xrange(striprev, len(repo)):
+    for x in pycompat.xrange(striprev, len(repo)):
         files.update(repo[x].files())
 
     return sorted(files)
 
 def _collectrevlog(revlog, striprev):
     _, brokenset = revlog.getstrippoint(striprev)
     return [revlog.linkrev(r) for r in brokenset]
 
@@ -194,17 +195,17 @@ def strip(ui, repo, nodelist, backup=Tru
                 tr.startgroup()
                 cl.strip(striprev, tr)
                 stripmanifest(repo, striprev, tr, files)
 
                 for fn in files:
                     repo.file(fn).strip(striprev, tr)
                 tr.endgroup()
 
-                for i in xrange(offset, len(tr.entries)):
+                for i in pycompat.xrange(offset, len(tr.entries)):
                     file, troffset, ignore = tr.entries[i]
                     with repo.svfs(file, 'a', checkambig=True) as fp:
                         fp.truncate(troffset)
                     if troffset == 0:
                         repo.store.markremoved(file)
 
                 deleteobsmarkers(repo.obsstore, stripobsidx)
                 del repo.obsstore
--- a/mercurial/repoview.py
+++ b/mercurial/repoview.py
@@ -123,17 +123,17 @@ def computeimpactable(repo, visibilityex
     assert not repo.changelog.filteredrevs
     cl = repo.changelog
     firstmutable = len(cl)
     for roots in repo._phasecache.phaseroots[1:]:
         if roots:
             firstmutable = min(firstmutable, min(cl.rev(r) for r in roots))
     # protect from nullrev root
     firstmutable = max(0, firstmutable)
-    return frozenset(xrange(firstmutable, len(cl)))
+    return frozenset(pycompat.xrange(firstmutable, len(cl)))
 
 # function to compute filtered set
 #
 # When adding a new filter you MUST update the table at:
 #     mercurial.branchmap.subsettable
 # Otherwise your filter will have to recompute all its branches cache
 # from scratch (very slow).
 filtertable = {'visible': computehidden,
--- a/mercurial/revlog.py
+++ b/mercurial/revlog.py
@@ -1061,30 +1061,30 @@ class revlog(object):
 
     def tip(self):
         return self.node(len(self.index) - 2)
     def __contains__(self, rev):
         return 0 <= rev < len(self)
     def __len__(self):
         return len(self.index) - 1
     def __iter__(self):
-        return iter(xrange(len(self)))
+        return iter(pycompat.xrange(len(self)))
     def revs(self, start=0, stop=None):
         """iterate over all rev in this revlog (from start to stop)"""
         step = 1
         length = len(self)
         if stop is not None:
             if start > stop:
                 step = -1
             stop += step
             if stop > length:
                 stop = length
         else:
             stop = length
-        return xrange(start, stop, step)
+        return pycompat.xrange(start, stop, step)
 
     @util.propertycache
     def nodemap(self):
         self.rev(self.node(0))
         return self._nodecache
 
     def hasnode(self, node):
         try:
@@ -1131,17 +1131,17 @@ class revlog(object):
             # pure python cache lookup failed
             n = self._nodecache
             i = self.index
             p = self._nodepos
             if p is None:
                 p = len(i) - 2
             else:
                 assert p < len(i)
-            for r in xrange(p, -1, -1):
+            for r in pycompat.xrange(p, -1, -1):
                 v = i[r][7]
                 n[v] = r
                 if v == node:
                     self._nodepos = r - 1
                     return r
             if node == wdirid or node in wdirfilenodeids:
                 raise error.WdirUnsupported
             raise LookupError(node, self.indexfile, _('no node'))
@@ -2784,17 +2784,17 @@ class revlog(object):
             end += rev * self._io.size
 
         transaction.add(self.indexfile, end)
 
         # then reset internal state in memory to forget those revisions
         self._cache = None
         self._chaininfocache = {}
         self._chunkclear()
-        for x in xrange(rev, len(self)):
+        for x in pycompat.xrange(rev, len(self)):
             del self.nodemap[self.node(x)]
 
         del self.index[rev:-1]
         self._nodepos = None
 
     def checksize(self):
         expected = 0
         if len(self):
--- a/mercurial/revsetlang.py
+++ b/mercurial/revsetlang.py
@@ -58,17 +58,17 @@ symbols = {}
 
 _quoteletters = {'"', "'"}
 _simpleopletters = set(pycompat.iterbytestr("()[]#:=,-|&+!~^%"))
 
 # default set of valid characters for the initial letter of symbols
 _syminitletters = set(pycompat.iterbytestr(
     string.ascii_letters.encode('ascii') +
     string.digits.encode('ascii') +
-    '._@')) | set(map(pycompat.bytechr, xrange(128, 256)))
+    '._@')) | set(map(pycompat.bytechr, pycompat.xrange(128, 256)))
 
 # default set of valid characters for non-initial letters of symbols
 _symletters = _syminitletters | set(pycompat.iterbytestr('-/'))
 
 def tokenize(program, lookup=None, syminitletters=None, symletters=None):
     '''
     Parse a revset statement into a stream of tokens
 
--- a/mercurial/scmutil.py
+++ b/mercurial/scmutil.py
@@ -1537,17 +1537,17 @@ def registersummarycallback(repo, otr, t
                 msg = getinstabilitymessage(delta, instability)
                 if msg:
                     repo.ui.warn(msg)
 
     if txmatch(_reportnewcssource):
         @reportsummary
         def reportnewcs(repo, tr):
             """Report the range of new revisions pulled/unbundled."""
-            newrevs = tr.changes.get('revs', xrange(0, 0))
+            newrevs = tr.changes.get('revs', pycompat.xrange(0, 0))
             if not newrevs:
                 return
 
             # Compute the bounds of new revisions' range, excluding obsoletes.
             unfi = repo.unfiltered()
             revs = unfi.revs('%ld and not obsolete()', newrevs)
             if not revs:
                 # Got only obsoletes.
@@ -1560,17 +1560,17 @@ def registersummarycallback(repo, otr, t
                 revrange = '%s:%s' % (minrev, maxrev)
             repo.ui.status(_('new changesets %s\n') % revrange)
 
         @reportsummary
         def reportphasechanges(repo, tr):
             """Report statistics of phase changes for changesets pre-existing
             pull/unbundle.
             """
-            newrevs = tr.changes.get('revs', xrange(0, 0))
+            newrevs = tr.changes.get('revs', pycompat.xrange(0, 0))
             phasetracking = tr.changes.get('phases', {})
             if not phasetracking:
                 return
             published = [
                 rev for rev, (old, new) in phasetracking.iteritems()
                 if new == phases.public and rev not in newrevs
             ]
             if not published:
--- a/mercurial/server.py
+++ b/mercurial/server.py
@@ -74,17 +74,17 @@ def runservice(opts, parentfn=None, init
         lockfd, lockpath = pycompat.mkstemp(prefix='hg-service-')
         os.close(lockfd)
         try:
             if not runargs:
                 runargs = procutil.hgcmd() + pycompat.sysargv[1:]
             runargs.append('--daemon-postexec=unlink:%s' % lockpath)
             # Don't pass --cwd to the child process, because we've already
             # changed directory.
-            for i in xrange(1, len(runargs)):
+            for i in pycompat.xrange(1, len(runargs)):
                 if runargs[i].startswith('--cwd='):
                     del runargs[i]
                     break
                 elif runargs[i].startswith('--cwd'):
                     del runargs[i:i + 2]
                     break
             def condfn():
                 return not os.path.exists(lockpath)
--- a/mercurial/simplemerge.py
+++ b/mercurial/simplemerge.py
@@ -53,17 +53,18 @@ def intersect(ra, rb):
     else:
         return None
 
 def compare_range(a, astart, aend, b, bstart, bend):
     """Compare a[astart:aend] == b[bstart:bend], without slicing.
     """
     if (aend - astart) != (bend - bstart):
         return False
-    for ia, ib in zip(xrange(astart, aend), xrange(bstart, bend)):
+    for ia, ib in zip(pycompat.xrange(astart, aend),
+                      pycompat.xrange(bstart, bend)):
         if a[ia] != b[ib]:
             return False
     else:
         return True
 
 class Merge3Text(object):
     """3-way merge of texts.
 
--- a/mercurial/smartset.py
+++ b/mercurial/smartset.py
@@ -147,21 +147,21 @@ class abstractsmartset(object):
             raise error.ProgrammingError('negative index not allowed')
         return self._slice(start, stop)
 
     def _slice(self, start, stop):
         # sub classes may override this. start and stop must not be negative,
         # but start > stop is allowed, which should be an empty set.
         ys = []
         it = iter(self)
-        for x in xrange(start):
+        for x in pycompat.xrange(start):
             y = next(it, None)
             if y is None:
                 break
-        for x in xrange(stop - start):
+        for x in pycompat.xrange(stop - start):
             y = next(it, None)
             if y is None:
                 break
             ys.append(y)
         return baseset(ys, datarepr=('slice=%d:%d %r', start, stop, self))
 
 class baseset(abstractsmartset):
     """Basic data structure that represents a revset and contains the basic
@@ -1000,23 +1000,23 @@ class _spanset(abstractsmartset):
 
     def __iter__(self):
         if self._ascending:
             return self.fastasc()
         else:
             return self.fastdesc()
 
     def fastasc(self):
-        iterrange = xrange(self._start, self._end)
+        iterrange = pycompat.xrange(self._start, self._end)
         if self._hiddenrevs:
             return self._iterfilter(iterrange)
         return iter(iterrange)
 
     def fastdesc(self):
-        iterrange = xrange(self._end - 1, self._start - 1, -1)
+        iterrange = pycompat.xrange(self._end - 1, self._start - 1, -1)
         if self._hiddenrevs:
             return self._iterfilter(iterrange)
         return iter(iterrange)
 
     def __contains__(self, rev):
         hidden = self._hiddenrevs
         return ((self._start <= rev < self._end)
                 and not (hidden and rev in hidden))
--- a/mercurial/store.py
+++ b/mercurial/store.py
@@ -113,26 +113,27 @@ def _buildencodefun():
         cmap[xchr(x)] = e + xchr(x).lower()
 
     dmap = {}
     for k, v in cmap.iteritems():
         dmap[v] = k
     def decode(s):
         i = 0
         while i < len(s):
-            for l in xrange(1, 4):
+            for l in pycompat.xrange(1, 4):
                 try:
                     yield dmap[s[i:i + l]]
                     i += l
                     break
                 except KeyError:
                     pass
             else:
                 raise KeyError
-    return (lambda s: ''.join([cmap[s[c:c + 1]] for c in xrange(len(s))]),
+    return (lambda s: ''.join([cmap[s[c:c + 1]]
+                               for c in pycompat.xrange(len(s))]),
             lambda s: ''.join(list(decode(s))))
 
 _encodefname, _decodefname = _buildencodefun()
 
 def encodefilename(s):
     '''
     >>> encodefilename(b'foo.i/bar.d/bla.hg/hi:world?/HELLO')
     'foo.i.hg/bar.d.hg/bla.hg.hg/hi~3aworld~3f/_h_e_l_l_o'
@@ -154,17 +155,17 @@ def _buildlowerencodefun():
     >>> f(b'HELLO')
     'hello'
     >>> f(b'hello:world?')
     'hello~3aworld~3f'
     >>> f(b'the\\x07quick\\xADshot')
     'the~07quick~adshot'
     '''
     xchr = pycompat.bytechr
-    cmap = dict([(xchr(x), xchr(x)) for x in xrange(127)])
+    cmap = dict([(xchr(x), xchr(x)) for x in pycompat.xrange(127)])
     for x in _reserved():
         cmap[xchr(x)] = "~%02x" % x
     for x in range(ord("A"), ord("Z") + 1):
         cmap[xchr(x)] = xchr(x).lower()
     def lowerencode(s):
         return "".join([cmap[c] for c in pycompat.iterbytestr(s)])
     return lowerencode
 
--- a/mercurial/streamclone.py
+++ b/mercurial/streamclone.py
@@ -353,17 +353,17 @@ def consumev1(repo, fp, filecount, bytec
         # regardless of transaction nesting.
         #
         # But transaction nesting can't be simply prohibited, because
         # nesting occurs also in ordinary case (e.g. enabling
         # clonebundles).
 
         with repo.transaction('clone'):
             with repo.svfs.backgroundclosing(repo.ui, expectedcount=filecount):
-                for i in xrange(filecount):
+                for i in pycompat.xrange(filecount):
                     # XXX doesn't support '\n' or '\r' in filenames
                     l = fp.readline()
                     try:
                         name, size = l.split('\0', 1)
                         size = int(size)
                     except (ValueError, TypeError):
                         raise error.ResponseError(
                             _('unexpected response from remote server:'), l)
--- a/mercurial/templatefilters.py
+++ b/mercurial/templatefilters.py
@@ -114,17 +114,17 @@ def commondir(filelist):
     """
     def common(a, b):
         if len(a) > len(b):
             a = b[:len(a)]
         elif len(b) > len(a):
             b = b[:len(a)]
         if a == b:
             return a
-        for i in xrange(len(a)):
+        for i in pycompat.xrange(len(a)):
             if a[i] != b[i]:
                 return a[:i]
         return a
     try:
         if not filelist:
             return ""
         dirlist = [f.lstrip('/').split('/')[:-1] for f in filelist]
         if len(dirlist) == 1:
@@ -261,17 +261,17 @@ def isodatesec(text):
     return dateutil.datestr(text, '%Y-%m-%d %H:%M:%S %1%2')
 
 def indent(text, prefix):
     '''indent each non-empty line of text after first with prefix.'''
     lines = text.splitlines()
     num_lines = len(lines)
     endswithnewline = text[-1:] == '\n'
     def indenter():
-        for i in xrange(num_lines):
+        for i in pycompat.xrange(num_lines):
             l = lines[i]
             if i and l.strip():
                 yield prefix
             yield l
             if i < num_lines - 1 or endswithnewline:
                 yield '\n'
     return "".join(indenter())
 
--- a/mercurial/treediscovery.py
+++ b/mercurial/treediscovery.py
@@ -11,16 +11,17 @@ import collections
 
 from .i18n import _
 from .node import (
     nullid,
     short,
 )
 from . import (
     error,
+    pycompat,
 )
 
 def findcommonincoming(repo, remote, heads=None, force=False):
     """Return a tuple (common, fetch, heads) used to identify the common
     subset of nodes between repo and remote.
 
     "common" is a list of (at least) the heads of the common subset.
     "fetch" is a list of roots of the nodes that would be incoming, to be
@@ -106,17 +107,17 @@ def findcommonincoming(repo, remote, hea
                         req.add(p)
             seen.add(n[0])
 
         if r:
             reqcnt += 1
             progress.increment()
             repo.ui.debug("request %d: %s\n" %
                         (reqcnt, " ".join(map(short, r))))
-            for p in xrange(0, len(r), 10):
+            for p in pycompat.xrange(0, len(r), 10):
                 with remote.commandexecutor() as e:
                     branches = e.callcommand('branches', {
                         'nodes': r[p:p + 10],
                     }).result()
 
                 for b in branches:
                     repo.ui.debug("received %s:%s\n" %
                                   (short(b[0]), short(b[1])))
--- a/mercurial/utils/stringutil.py
+++ b/mercurial/utils/stringutil.py
@@ -459,17 +459,17 @@ def _MBTextWrapper(**kwargs):
         In addition, characters classified into 'ambiguous' width are
         treated as wide in East Asian area, but as narrow in other.
 
         This requires use decision to determine width of such characters.
         """
         def _cutdown(self, ucstr, space_left):
             l = 0
             colwidth = encoding.ucolwidth
-            for i in xrange(len(ucstr)):
+            for i in pycompat.xrange(len(ucstr)):
                 l += colwidth(ucstr[i])
                 if space_left < l:
                     return (ucstr[:i], ucstr[i:])
             return ucstr, ''
 
         # overriding of base class
         def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):
             space_left = max(width - cur_len, 1)
--- a/mercurial/win32.py
+++ b/mercurial/win32.py
@@ -610,17 +610,17 @@ def unlink(f):
     #   during that time and cannot be used for recreating a new file under
     #   that same name ("zombie file"). Directories containing such zombie files
     #   cannot be removed or moved.
     # A file that has been opened with posixfile can be renamed, so we rename
     # f to a random temporary name before calling os.unlink on it. This allows
     # callers to recreate f immediately while having other readers do their
     # implicit zombie filename blocking on a temporary name.
 
-    for tries in xrange(10):
+    for tries in pycompat.xrange(10):
         temp = '%s-%08x' % (f, random.randint(0, 0xffffffff))
         try:
             os.rename(f, temp)  # raises OSError EEXIST if temp exists
             break
         except OSError as e:
             if e.errno != errno.EEXIST:
                 raise
     else:
--- a/mercurial/wireprotoserver.py
+++ b/mercurial/wireprotoserver.py
@@ -497,24 +497,24 @@ class sshv1protocolhandler(object):
 
     @property
     def name(self):
         return wireprototypes.SSHV1
 
     def getargs(self, args):
         data = {}
         keys = args.split()
-        for n in xrange(len(keys)):
+        for n in pycompat.xrange(len(keys)):
             argline = self._fin.readline()[:-1]
             arg, l = argline.split()
             if arg not in keys:
                 raise error.Abort(_("unexpected parameter %r") % arg)
             if arg == '*':
                 star = {}
-                for k in xrange(int(l)):
+                for k in pycompat.xrange(int(l)):
                     argline = self._fin.readline()[:-1]
                     arg, l = argline.split()
                     val = self._fin.read(int(l))
                     star[arg] = val
                 data['*'] = star
             else:
                 val = self._fin.read(int(l))
                 data[arg] = val
--- a/mercurial/wireprotov1peer.py
+++ b/mercurial/wireprotov1peer.py
@@ -492,17 +492,17 @@ class wirepeer(repository.peer):
             br = [tuple(wireprototypes.decodelist(b)) for b in d.splitlines()]
             return br
         except ValueError:
             self._abort(error.ResponseError(_("unexpected response:"), d))
 
     def between(self, pairs):
         batch = 8 # avoid giant requests
         r = []
-        for i in xrange(0, len(pairs), batch):
+        for i in pycompat.xrange(0, len(pairs), batch):
             n = " ".join([wireprototypes.encodelist(p, '-')
                           for p in pairs[i:i + batch]])
             d = self._call("between", pairs=n)
             try:
                 r.extend(l and wireprototypes.decodelist(l) or []
                          for l in d.splitlines())
             except ValueError:
                 self._abort(error.ResponseError(_("unexpected response:"), d))