Patchwork [6,of,7] py3: switch from iteritems to items

login
register
mail settings
Submitter timeless@mozdev.org
Date April 11, 2016, 10:49 p.m.
Message ID <eefe59718f1194473815.1460414940@waste.org>
Download mbox | patch
Permalink /patch/14535/
State Rejected
Headers show

Comments

timeless@mozdev.org - April 11, 2016, 10:49 p.m.
# HG changeset patch
# User timeless <timeless@mozdev.org>
# Date 1460271551 0
#      Sun Apr 10 06:59:11 2016 +0000
# Node ID eefe59718f11944738153111debc79f8b926a80a
# Parent  17073d80244c1c0c4670770c575cd051adba19be
py3: switch from iteritems to items

tests seem ok
Skipped test-convert-cvs-synthetic.t: missing feature: cvs client/server 1.12.* (not cvsnt)
Skipped test-convert-p4-filetypes.t: missing feature: Perforce server and client
Skipped test-convert-mtn.t: missing feature: monotone client (>= 1.0)
Skipped test-casecollision-merge.t: missing feature: case insensitive file system
Skipped test-convert-baz.t: missing feature: GNU Arch baz client
Skipped test-casefolding.t: missing feature: case insensitive file system
Skipped test-convert-p4.t: missing feature: Perforce server and client
Skipped test-convert-tla.t: missing feature: GNU Arch tla client
Skipped test-convert-darcs.t: missing feature: darcs client
Skipped test-verify-repo-operations.py: missing feature: allow slow tests
Skipped test-no-symlinks.t: system supports symbolic links
Skipped test-docker-packaging.t: missing feature: docker support
Skipped test-debian-packages.t: missing feature: debian packaging tools
Pierre-Yves David - April 13, 2016, 7:56 a.m.
On 04/11/2016 03:49 PM, timeless wrote:
> # HG changeset patch
> # User timeless <timeless@mozdev.org>
> # Date 1460271551 0
> #      Sun Apr 10 06:59:11 2016 +0000
> # Node ID eefe59718f11944738153111debc79f8b926a80a
> # Parent  17073d80244c1c0c4670770c575cd051adba19be
> py3: switch from iteritems to items

Wow this change is intrusive. I'm not sure about it. Most of these 
changes to non does not really matters but I'll have to take a second 
pass of what it means.

I'm curious about what other people think about this.

Patch 1-3 pushed.
Yuya Nishihara - April 13, 2016, 4:17 p.m.
On Wed, 13 Apr 2016 00:56:56 -0700, Pierre-Yves David wrote:
> On 04/11/2016 03:49 PM, timeless wrote:
> > # HG changeset patch
> > # User timeless <timeless@mozdev.org>
> > # Date 1460271551 0
> > #      Sun Apr 10 06:59:11 2016 +0000
> > # Node ID eefe59718f11944738153111debc79f8b926a80a
> > # Parent  17073d80244c1c0c4670770c575cd051adba19be
> > py3: switch from iteritems to items  
> 
> Wow this change is intrusive. I'm not sure about it. Most of these 
> changes to non does not really matters but I'll have to take a second 
> pass of what it means.
> 
> I'm curious about what other people think about this.

My question is what's the criteria to select util.iteritems(d) or d.items().

(I know we can't replace all d.iteritems() by dict.iteritems(d).)
timeless - April 13, 2016, 4:25 p.m.
as a note, if this is going to be taken, the skipped part of the
commit message should be dropped, it's there to highlight areas where
someone should be more careful since i don't have test coverage of
those files/modules.

Yuya Nishihara wrote:
> My question is what's the criteria to select util.iteritems(d) or d.items().
>
> (I know we can't replace all d.iteritems() by dict.iteritems(d).)

I replaced everything with .items(), and whenever something caused a
test failure, I dropped it from this commit. -- I suppose this
methodology could be noted in the commit message...

Generally the reason something can't be .items() is when we have our
own iteritems() function (often the class also has a items() function
as well). Or if we're not doing iteration.
Matt Mackall - April 13, 2016, 6:30 p.m.
On Mon, 2016-04-11 at 17:49 -0500, timeless wrote:
> # HG changeset patch
> # User timeless <timeless@mozdev.org>
> # Date 1460271551 0
> #      Sun Apr 10 06:59:11 2016 +0000
> # Node ID eefe59718f11944738153111debc79f8b926a80a
> # Parent  17073d80244c1c0c4670770c575cd051adba19be
> py3: switch from iteritems to items

Way too invasive.

-- 
Mathematics is the supreme nostalgia of our time.
timeless - April 15, 2016, 7:09 p.m.
Matt Mackall wrote:
>> # Parent  17073d80244c1c0c4670770c575cd051adba19be
>> py3: switch from iteritems to items
>
> Way too invasive.

Ok, I'll try to put together the code necessary for py3 to add an
iteritems method to dict.

one approach would be forbiddenfruit.curse --
https://github.com/clarete/forbiddenfruit

I saw a different method of doing it which looked nicer. But I'm not
sure I bookmarked it :(

Patch

diff --git a/contrib/dirstatenonnormalcheck.py b/contrib/dirstatenonnormalcheck.py
--- a/contrib/dirstatenonnormalcheck.py
+++ b/contrib/dirstatenonnormalcheck.py
@@ -16,7 +16,7 @@ 
 def nonnormalentries(dmap):
     """Compute nonnormal entries from dirstate's dmap"""
     res = set()
-    for f, e in dmap.iteritems():
+    for f, e in dmap.items():
         if e[0] != 'n' or e[3] == -1:
             res.add(f)
     return res
diff --git a/contrib/memory.py b/contrib/memory.py
--- a/contrib/memory.py
+++ b/contrib/memory.py
@@ -26,7 +26,7 @@ 
             if key in result:
                 result[key] = int(parts[1])
     ui.write_err(", ".join(["%s: %.1f MiB" % (key, value / 1024.0)
-                            for key, value in result.iteritems()]) + "\n")
+                            for key, value in result.items()]) + "\n")
 
 def extsetup(ui):
     atexit.register(memusage, ui)
diff --git a/contrib/synthrepo.py b/contrib/synthrepo.py
--- a/contrib/synthrepo.py
+++ b/contrib/synthrepo.py
@@ -215,7 +215,7 @@ 
                     linesinfilesadded[roundto(added, 5)] += 1
                 elif mar == 'r':
                     fileremoves += 1
-                for length, count in lineadd.iteritems():
+                for length, count in lineadd.items():
                     linelengths[length] += count
             fileschanged[filechanges] += 1
             filesadded[fileadds] += 1
@@ -224,14 +224,14 @@ 
 
     invchildren = zerodict()
 
-    for rev, count in children.iteritems():
+    for rev, count in children.items():
         invchildren[count] += 1
 
     if output != '-':
         ui.status(_('writing output to %s\n') % output)
 
     def pronk(d):
-        return sorted(d.iteritems(), key=lambda x: x[1], reverse=True)
+        return sorted(d.items(), key=lambda x: x[1], reverse=True)
 
     json.dump({'revs': len(revs),
                'initdirs': pronk(dirs),
@@ -510,6 +510,6 @@ 
         replacements[dirpath] = renamed
         return renamed
     result = []
-    for dirpath, count in dirs.iteritems():
+    for dirpath, count in dirs.items():
         result.append([rename(dirpath.lstrip(os.sep)), count])
     return result
diff --git a/hgext/chgserver.py b/hgext/chgserver.py
--- a/hgext/chgserver.py
+++ b/hgext/chgserver.py
@@ -112,7 +112,7 @@ 
     for section in _configsections:
         sectionitems.append(ui.configitems(section))
     sectionhash = _hashlist(sectionitems)
-    envitems = [(k, v) for k, v in os.environ.iteritems() if _envre.match(k)]
+    envitems = [(k, v) for k, v in os.environ.items() if _envre.match(k)]
     envhash = _hashlist(sorted(envitems))
     return sectionhash[:6] + envhash[:6]
 
@@ -255,7 +255,7 @@ 
                 return str(val)
             env = os.environ.copy()
             if environ:
-                env.update((k, py2shell(v)) for k, v in environ.iteritems())
+                env.update((k, py2shell(v)) for k, v in environ.items())
             env['HG'] = util.hgexecutable()
             rc = self._csystem(cmd, env, cwd)
             if rc and onerr:
@@ -324,7 +324,7 @@ 
 
     def __call__(self, cmd, environ, cwd):
         args = [util.quotecommand(cmd), os.path.abspath(cwd or '.')]
-        args.extend('%s=%s' % (k, v) for k, v in environ.iteritems())
+        args.extend('%s=%s' % (k, v) for k, v in environ.items())
         data = '\0'.join(args)
         self.out.write(struct.pack('>cI', self.channel, len(data)))
         self.out.write(data)
diff --git a/hgext/convert/bzr.py b/hgext/convert/bzr.py
--- a/hgext/convert/bzr.py
+++ b/hgext/convert/bzr.py
@@ -181,7 +181,7 @@ 
             if not branch.supports_tags():
                 return {}
             tagdict = branch.tags.get_tag_dict()
-            for name, rev in tagdict.iteritems():
+            for name, rev in tagdict.items():
                 bytetags[self.recode(name)] = rev
         return bytetags
 
diff --git a/hgext/convert/common.py b/hgext/convert/common.py
--- a/hgext/convert/common.py
+++ b/hgext/convert/common.py
@@ -323,7 +323,7 @@ 
 
     def _cmdline(self, cmd, *args, **kwargs):
         cmdline = [self.command, cmd] + list(args)
-        for k, v in kwargs.iteritems():
+        for k, v in kwargs.items():
             if len(k) == 1:
                 cmdline.append('-' + k)
             else:
diff --git a/hgext/convert/convcmd.py b/hgext/convert/convcmd.py
--- a/hgext/convert/convcmd.py
+++ b/hgext/convert/convcmd.py
@@ -532,7 +532,7 @@ 
                     if nrev and tagsparent:
                         # write another hash correspondence to override the
                         # previous one so we don't end up with extra tag heads
-                        tagsparents = [e for e in self.map.iteritems()
+                        tagsparents = [e for e in self.map.items()
                                        if e[1] == tagsparent]
                         if tagsparents:
                             self.map[tagsparents[0][0]] = nrev
diff --git a/hgext/convert/cvs.py b/hgext/convert/cvs.py
--- a/hgext/convert/cvs.py
+++ b/hgext/convert/cvs.py
@@ -281,7 +281,7 @@ 
         if full:
             raise error.Abort(_("convert from cvs does not support --full"))
         self._parse()
-        return sorted(self.files[rev].iteritems()), {}, set()
+        return sorted(self.files[rev].items()), {}, set()
 
     def getcommit(self, rev):
         self._parse()
diff --git a/hgext/convert/cvsps.py b/hgext/convert/cvsps.py
--- a/hgext/convert/cvsps.py
+++ b/hgext/convert/cvsps.py
@@ -429,7 +429,7 @@ 
 
             # find the branches starting from this revision
             branchpoints = set()
-            for branch, revision in branchmap.iteritems():
+            for branch, revision in branchmap.items():
                 revparts = tuple([int(i) for i in revision.split('.')])
                 if len(revparts) < 2: # bad tags
                     continue
diff --git a/hgext/convert/filemap.py b/hgext/convert/filemap.py
--- a/hgext/convert/filemap.py
+++ b/hgext/convert/filemap.py
@@ -111,7 +111,7 @@ 
         repo belong to the source repo and what parts don't."""
         if self.targetprefixes is None:
             self.targetprefixes = set()
-            for before, after in self.rename.iteritems():
+            for before, after in self.rename.items():
                 self.targetprefixes.add(after)
 
         # If "." is a target, then all target files are considered from the
diff --git a/hgext/convert/hg.py b/hgext/convert/hg.py
--- a/hgext/convert/hg.py
+++ b/hgext/convert/hg.py
@@ -129,7 +129,7 @@ 
 
         if missings:
             self.after()
-            for pbranch, heads in sorted(missings.iteritems()):
+            for pbranch, heads in sorted(missings.items()):
                 pbranchpath = os.path.join(self.path, pbranch)
                 prepo = hg.peer(self.ui, {}, pbranchpath)
                 self.ui.note(_('pulling from %s into %s\n') % (pbranch, branch))
@@ -209,7 +209,7 @@ 
             False, # followcopies
         )
 
-        for file, (action, info, msg) in actions.iteritems():
+        for file, (action, info, msg) in actions.items():
             if source.targetfilebelongstosource(file):
                 # If the file belongs to the source repo, ignore the p2
                 # since it will be covered by the existing fileset.
@@ -370,7 +370,7 @@ 
             tagparent = nodemod.nullid
 
         oldlines = set()
-        for branch, heads in self.repo.branchmap().iteritems():
+        for branch, heads in self.repo.branchmap().items():
             for h in heads:
                 if '.hgtags' in self.repo[h]:
                     oldlines.update(
@@ -520,7 +520,7 @@ 
         maappend = ma.append
         rappend = r.append
         d = ctx1.manifest().diff(ctx2.manifest())
-        for f, ((node1, flag1), (node2, flag2)) in d.iteritems():
+        for f, ((node1, flag1), (node2, flag2)) in d.items():
             if node2 is None:
                 rappend(f)
             else:
@@ -546,7 +546,7 @@ 
         cleanp2 = set()
         if len(parents) == 2:
             d = parents[1].manifest().diff(ctx.manifest(), clean=True)
-            for f, value in d.iteritems():
+            for f, value in d.items():
                 if value is None:
                     cleanp2.add(f)
         changes = [(f, rev) for f in files if f not in self.ignored]
diff --git a/hgext/convert/monotone.py b/hgext/convert/monotone.py
--- a/hgext/convert/monotone.py
+++ b/hgext/convert/monotone.py
@@ -90,7 +90,7 @@ 
     def mtnrunstdio(self, *args, **kwargs):
         # Prepare the command in automate stdio format
         command = []
-        for k, v in kwargs.iteritems():
+        for k, v in kwargs.items():
             command.append("%s:%s" % (len(k), k))
             if v:
                 command.append("%s:%s" % (len(v), v))
diff --git a/hgext/convert/subversion.py b/hgext/convert/subversion.py
--- a/hgext/convert/subversion.py
+++ b/hgext/convert/subversion.py
@@ -130,7 +130,7 @@ 
     def receiver(orig_paths, revnum, author, date, message, pool):
         paths = {}
         if orig_paths is not None:
-            for k, v in orig_paths.iteritems():
+            for k, v in orig_paths.items():
                 paths[k] = changedpath(v)
         pickle.dump((paths, revnum, author, date, message),
                     fp, protocol)
@@ -204,7 +204,7 @@ 
         def receiver(orig_paths, revnum, author, date, message, pool):
             paths = {}
             if orig_paths is not None:
-                for k, v in orig_paths.iteritems():
+                for k, v in orig_paths.items():
                     paths[k] = changedpath(v)
             self.append((paths, revnum, author, date, message))
 
@@ -482,7 +482,7 @@ 
             uuid, module, revnum = revsplit(rev)
             entries = svn.client.ls(self.baseurl + quote(module),
                                     optrev(revnum), True, self.ctx)
-            files = [n for n, e in entries.iteritems()
+            files = [n for n, e in entries.items()
                      if e.kind == svn.core.svn_node_file]
             self.removed = set()
 
@@ -565,7 +565,7 @@ 
                 if not origpaths:
                     origpaths = []
                 copies = [(e.copyfrom_path, e.copyfrom_rev, p) for p, e
-                          in origpaths.iteritems() if e.copyfrom_path]
+                          in origpaths.items() if e.copyfrom_path]
                 # Apply moves/copies from more specific to general
                 copies.sort(reverse=True)
 
@@ -593,7 +593,7 @@ 
                 # It happens with tools like cvs2svn. Such tags cannot
                 # be represented in mercurial.
                 addeds = dict((p, e.copyfrom_path) for p, e
-                              in origpaths.iteritems()
+                              in origpaths.items()
                               if e.action == 'A' and e.copyfrom_path)
                 badroots = set()
                 for destroot in addeds:
@@ -861,7 +861,7 @@ 
             parents = []
             # check whether this revision is the start of a branch or part
             # of a branch renaming
-            orig_paths = sorted(orig_paths.iteritems())
+            orig_paths = sorted(orig_paths.items())
             root_paths = [(p, e) for p, e in orig_paths
                           if self.module.startswith(p)]
             if root_paths:
@@ -1015,7 +1015,7 @@ 
         entries = svn.client.ls(rpath, optrev(revnum), True, self.ctx, pool)
         if path:
             path += '/'
-        return ((path + p) for p, e in entries.iteritems()
+        return ((path + p) for p, e in entries.items()
                 if e.kind == svn.core.svn_node_file)
 
     def getrelpath(self, path, module=None):
diff --git a/hgext/eol.py b/hgext/eol.py
--- a/hgext/eol.py
+++ b/hgext/eol.py
@@ -281,7 +281,7 @@ 
 
     if not repo.local():
         return
-    for name, fn in filters.iteritems():
+    for name, fn in filters.items():
         repo.adddatafilter(name, fn)
 
     ui.setconfig('patch', 'eol', 'auto', 'eol')
diff --git a/hgext/fsmonitor/__init__.py b/hgext/fsmonitor/__init__.py
--- a/hgext/fsmonitor/__init__.py
+++ b/hgext/fsmonitor/__init__.py
@@ -352,12 +352,12 @@ 
                          if f not in results and matchfn(f))
     else:
         if matchalways:
-            visit.update(f for f, st in dmap.iteritems()
+            visit.update(f for f, st in dmap.items()
                          if (f not in results and
                              (st[2] < 0 or st[0] != 'n' or fresh_instance)))
             visit.update(f for f in copymap if f not in results)
         else:
-            visit.update(f for f, st in dmap.iteritems()
+            visit.update(f for f, st in dmap.items()
                          if (f not in results and
                              (st[2] < 0 or st[0] != 'n' or fresh_instance)
                              and matchfn(f)))
diff --git a/hgext/fsmonitor/pywatchman/pybser.py b/hgext/fsmonitor/pywatchman/pybser.py
--- a/hgext/fsmonitor/pywatchman/pybser.py
+++ b/hgext/fsmonitor/pywatchman/pybser.py
@@ -156,7 +156,7 @@ 
             else:
                 raise RuntimeError('Cannot represent this mapping value')
             self.wpos += needed
-            for k, v in val.iteritems():
+            for k, v in val.items():
                 self.append_string(k)
                 self.append_recursive(v)
         elif isinstance(val, collections.Iterable) and isinstance(val, collections.Sized):
diff --git a/hgext/hgk.py b/hgext/hgk.py
--- a/hgext/hgk.py
+++ b/hgext/hgk.py
@@ -326,7 +326,7 @@ 
 def view(ui, repo, *etc, **opts):
     "start interactive history viewer"
     os.chdir(repo.root)
-    optstr = ' '.join(['--%s %s' % (k, v) for k, v in opts.iteritems() if v])
+    optstr = ' '.join(['--%s %s' % (k, v) for k, v in opts.items() if v])
     if repo.filtername is None:
         optstr += '--hidden'
 
diff --git a/hgext/histedit.py b/hgext/histedit.py
--- a/hgext/histedit.py
+++ b/hgext/histedit.py
@@ -1119,7 +1119,7 @@ 
 
     mapping, tmpnodes, created, ntm = processreplacement(state)
     if mapping:
-        for prec, succs in mapping.iteritems():
+        for prec, succs in mapping.items():
             if not succs:
                 ui.debug('histedit: %s is dropped\n' % node.short(prec))
             else:
@@ -1500,7 +1500,7 @@ 
         # if nothing got rewritten there is not purpose for this function
         return
     moves = []
-    for bk, old in sorted(repo._bookmarks.iteritems()):
+    for bk, old in sorted(repo._bookmarks.items()):
         if old == oldtopmost:
             # special case ensure bookmark stay on tip.
             #
diff --git a/hgext/keyword.py b/hgext/keyword.py
--- a/hgext/keyword.py
+++ b/hgext/keyword.py
@@ -444,7 +444,7 @@ 
         kwmaps = _defaultkwmaps(ui)
         if uikwmaps:
             ui.status(_('\tdisabling current template maps\n'))
-            for k, v in kwmaps.iteritems():
+            for k, v in kwmaps.items():
                 ui.setconfig('keywordmaps', k, v, 'keyword')
     else:
         ui.status(_('\n\tconfiguration using current keyword template maps\n'))
@@ -458,7 +458,7 @@ 
     ui.write('[extensions]\nkeyword =\n')
     demoitems('keyword', ui.configitems('keyword'))
     demoitems('keywordset', ui.configitems('keywordset'))
-    demoitems('keywordmaps', kwmaps.iteritems())
+    demoitems('keywordmaps', kwmaps.items())
     keywords = '$' + '$\n$'.join(sorted(kwmaps.keys())) + '$\n'
     repo.wvfs.write(fn, keywords)
     repo[None].add([fn])
diff --git a/hgext/largefiles/overrides.py b/hgext/largefiles/overrides.py
--- a/hgext/largefiles/overrides.py
+++ b/hgext/largefiles/overrides.py
@@ -560,7 +560,7 @@ 
     copies = orig(ctx1, ctx2, match=match)
     updated = {}
 
-    for k, v in copies.iteritems():
+    for k, v in copies.items():
         updated[lfutil.splitstandin(k) or k] = lfutil.splitstandin(v) or v
 
     return updated
diff --git a/hgext/largefiles/remotestore.py b/hgext/largefiles/remotestore.py
--- a/hgext/largefiles/remotestore.py
+++ b/hgext/largefiles/remotestore.py
@@ -31,7 +31,7 @@ 
 
     def exists(self, hashes):
         return dict((h, s == 0) for (h, s) in # dict-from-generator
-                    self._stat(hashes).iteritems())
+                    self._stat(hashes).items())
 
     def sendfile(self, filename, hash):
         self.ui.debug('remotestore: sendfile(%s, %s)\n' % (filename, hash))
diff --git a/hgext/mq.py b/hgext/mq.py
--- a/hgext/mq.py
+++ b/hgext/mq.py
@@ -1727,7 +1727,7 @@ 
                         # we can't copy a file created by the patch itself
                         if dst in copies:
                             del copies[dst]
-                    for src, dsts in copies.iteritems():
+                    for src, dsts in copies.items():
                         for dst in dsts:
                             repo.dirstate.copy(src, dst)
                 else:
@@ -3564,7 +3564,7 @@ 
     entry[1].extend(mqopt)
 
     def dotable(cmdtable):
-        for cmd, entry in cmdtable.iteritems():
+        for cmd, entry in cmdtable.items():
             cmd = cmdutil.parsealiases(cmd)[0]
             func = entry[0]
             if dispatch._cmdattr(ui, cmd, func, 'norepo'):
diff --git a/hgext/rebase.py b/hgext/rebase.py
--- a/hgext/rebase.py
+++ b/hgext/rebase.py
@@ -481,7 +481,7 @@ 
         if currentbookmarks:
             # Nodeids are needed to reset bookmarks
             nstate = {}
-            for k, v in state.iteritems():
+            for k, v in state.items():
                 if v > nullmerge:
                     nstate[repo[k].node()] = repo[v].node()
             # XXX this is the same as dest.node() for the non-continue path --
@@ -885,7 +885,7 @@ 
 def updatebookmarks(repo, targetnode, nstate, originalbookmarks, tr):
     'Move bookmarks to their correct changesets, and delete divergent ones'
     marks = repo._bookmarks
-    for k, v in originalbookmarks.iteritems():
+    for k, v in originalbookmarks.items():
         if v in nstate:
             # update the bookmarks for revs that have moved
             marks[k] = nstate[v]
@@ -926,7 +926,7 @@ 
     f.write('%d\n' % int(keep))
     f.write('%d\n' % int(keepbranches))
     f.write('%s\n' % (activebookmark or ''))
-    for d, v in state.iteritems():
+    for d, v in state.items():
         oldrev = repo[d].hex()
         if v >= 0:
             newrev = repo[v].hex()
@@ -1017,7 +1017,7 @@ 
         return False
 
     # We should be standing on the first as-of-yet unrebased commit.
-    firstunrebased = min([old for old, new in state.iteritems()
+    firstunrebased = min([old for old, new in state.items()
                           if new == nullrev])
     if firstunrebased in parents:
         return True
diff --git a/hgext/strip.py b/hgext/strip.py
--- a/hgext/strip.py
+++ b/hgext/strip.py
@@ -152,7 +152,7 @@ 
             # a revision we have to only delete the bookmark and not strip
             # anything. revsets cannot detect that case.
             nodetobookmarks = {}
-            for mark, node in repomarks.iteritems():
+            for mark, node in repomarks.items():
                 nodetobookmarks.setdefault(node, []).append(mark)
             for marks in nodetobookmarks.values():
                 if bookmarks.issuperset(marks):
diff --git a/hgext/win32text.py b/hgext/win32text.py
--- a/hgext/win32text.py
+++ b/hgext/win32text.py
@@ -167,7 +167,7 @@ 
 def reposetup(ui, repo):
     if not repo.local():
         return
-    for name, fn in _filters.iteritems():
+    for name, fn in _filters.items():
         repo.adddatafilter(name, fn)
 
 def extsetup(ui):
diff --git a/mercurial/archival.py b/mercurial/archival.py
--- a/mercurial/archival.py
+++ b/mercurial/archival.py
@@ -66,7 +66,7 @@ 
     }
 
 def guesskind(dest):
-    for kind, extensions in exts.iteritems():
+    for kind, extensions in exts.items():
         if any(dest.endswith(ext) for ext in extensions):
             return kind
     return None
diff --git a/mercurial/bookmarks.py b/mercurial/bookmarks.py
--- a/mercurial/bookmarks.py
+++ b/mercurial/bookmarks.py
@@ -178,7 +178,7 @@ 
         self._aclean = True
 
     def _write(self, fp):
-        for name, node in self.iteritems():
+        for name, node in self.items():
             fp.write("%s %s\n" % (hex(node), encoding.fromlocal(name)))
         self._clean = True
 
@@ -317,7 +317,7 @@ 
 
     d = {}
     hasnode = repo.changelog.hasnode
-    for k, v in marks.iteritems():
+    for k, v in marks.items():
         # don't expose local divergent bookmarks
         if hasnode(v) and ('@' not in k or k.endswith('@')):
             d[k] = hex(v)
diff --git a/mercurial/branchmap.py b/mercurial/branchmap.py
--- a/mercurial/branchmap.py
+++ b/mercurial/branchmap.py
@@ -222,7 +222,7 @@ 
         return heads
 
     def iterbranches(self):
-        for bn, heads in self.iteritems():
+        for bn, heads in self.items():
             yield (bn, heads) + self._branchtip(heads)
 
     def copy(self):
@@ -238,7 +238,7 @@ 
                 cachekey.append(hex(self.filteredhash))
             f.write(" ".join(cachekey) + '\n')
             nodecount = 0
-            for label, nodes in sorted(self.iteritems()):
+            for label, nodes in sorted(self.items()):
                 for node in nodes:
                     nodecount += 1
                     if node in self._closednodes:
@@ -278,7 +278,7 @@ 
         # if older branchheads are reachable from new ones, they aren't
         # really branchheads. Note checking parents is insufficient:
         # 1 (branch a) -> 2 (branch b) -> 3 (branch a)
-        for branch, newheadrevs in newbranches.iteritems():
+        for branch, newheadrevs in newbranches.items():
             bheads = self.setdefault(branch, [])
             bheadset = set(cl.rev(node) for node in bheads)
 
diff --git a/mercurial/context.py b/mercurial/context.py
--- a/mercurial/context.py
+++ b/mercurial/context.py
@@ -129,7 +129,7 @@ 
         deleted, unknown, ignored = s.deleted, s.unknown, s.ignored
         deletedset = set(deleted)
         d = mf1.diff(mf2, clean=listclean)
-        for fn, value in d.iteritems():
+        for fn, value in d.items():
             if fn in deletedset:
                 continue
             if value is None:
diff --git a/mercurial/copies.py b/mercurial/copies.py
--- a/mercurial/copies.py
+++ b/mercurial/copies.py
@@ -104,7 +104,7 @@ 
 def _chain(src, dst, a, b):
     '''chain two sets of copies a->b'''
     t = a.copy()
-    for k, v in b.iteritems():
+    for k, v in b.items():
         if v in t:
             # found a chain
             if t[v] != k:
@@ -212,7 +212,7 @@ 
     # arbitrarily pick one of the renames.
     f = _forwardcopies(b, a)
     r = {}
-    for k, v in sorted(f.iteritems()):
+    for k, v in sorted(f.items()):
         # remove copies
         if v in a:
             continue
@@ -407,7 +407,7 @@ 
 
     # examine each file copy for a potential directory move, which is
     # when all the files in a directory are moved to a new directory
-    for dst, src in fullcopy.iteritems():
+    for dst, src in fullcopy.items():
         dsrc, ddst = pathutil.dirname(src), pathutil.dirname(dst)
         if dsrc in invalid:
             # already seen to be uninteresting
@@ -544,7 +544,7 @@ 
         # of the function is much faster (and is required for carrying copy
         # metadata across the rebase anyway).
         exclude = pathcopies(repo[fromrev], repo[skiprev])
-    for dst, src in pathcopies(repo[fromrev], repo[rev]).iteritems():
+    for dst, src in pathcopies(repo[fromrev], repo[rev]).items():
         # copies.pathcopies returns backward renames, so dst might not
         # actually be in the dirstate
         if dst in exclude:
diff --git a/mercurial/crecord.py b/mercurial/crecord.py
--- a/mercurial/crecord.py
+++ b/mercurial/crecord.py
@@ -628,7 +628,7 @@ 
         scroll the screen down to show the new-selected item.
         """
         currentitem = self.currentselecteditem
-        nextitem = currentitem.previtem()
+        nextitem = currentitem.previtems()
         # if there's no previous item on this level, try choosing the parent
         if nextitem is None:
             nextitem = currentitem.parentitem()
@@ -669,14 +669,14 @@ 
         # todo: update docstring
 
         currentitem = self.currentselecteditem
-        nextitem = currentitem.nextitem()
+        nextitem = currentitem.nextitems()
         # if there's no previous item on this level, try choosing the parent's
         # nextitem.
         if nextitem is None:
             try:
                 nextitem = currentitem.parentitem().nextitem()
             except AttributeError:
-                # parentitem returned None, so nextitem() can't be called
+                # parentitem returned None, so nextitems() can't be called
                 nextitem = None
         if nextitem is None:
             # if no next item on parent-level, then no change...
diff --git a/mercurial/demandimport.py b/mercurial/demandimport.py
--- a/mercurial/demandimport.py
+++ b/mercurial/demandimport.py
@@ -51,6 +51,8 @@ 
 def _hgextimport(importfunc, name, globals, *args, **kwargs):
     try:
         return importfunc(name, globals, *args, **kwargs)
+    except SystemError:
+        raise
     except ImportError:
         if not globals:
             raise
diff --git a/mercurial/discovery.py b/mercurial/discovery.py
--- a/mercurial/discovery.py
+++ b/mercurial/discovery.py
@@ -182,7 +182,7 @@ 
 
     # A. register remote heads
     remotebranches = set()
-    for branch, heads in remote.branchmap().iteritems():
+    for branch, heads in remote.branchmap().items():
         remotebranches.add(branch)
         known = []
         unsynced = []
@@ -209,10 +209,10 @@ 
     # D. Update newmap with outgoing changes.
     # This will possibly add new heads and remove existing ones.
     newmap = branchmap.branchcache((branch, heads[1])
-                                 for branch, heads in headssum.iteritems()
+                                 for branch, heads in headssum.items()
                                  if heads[0] is not None)
     newmap.update(repo, (ctx.rev() for ctx in missingctx))
-    for branch, newheads in newmap.iteritems():
+    for branch, newheads in newmap.items():
         headssum[branch][1][:] = newheads
     return headssum
 
@@ -288,7 +288,7 @@ 
         headssum = _headssummary(repo, remote, outgoing)
     else:
         headssum = _oldheadssummary(repo, remoteheads, outgoing, inc)
-    newbranches = [branch for branch, heads in headssum.iteritems()
+    newbranches = [branch for branch, heads in headssum.items()
                    if heads[0] is None]
     # 1. Check for new branches on the remote.
     if newbranches and not newbranch:  # new branch requires --new-branch
@@ -312,7 +312,7 @@ 
         cctx = repo.set('%ld', outgoing.common)
         allfuturecommon = set(c.node() for c in cctx)
         allfuturecommon.update(allmissing)
-    for branch, heads in sorted(headssum.iteritems()):
+    for branch, heads in sorted(headssum.items()):
         remoteheads, newheads, unsyncedheads = heads
         candidate_newhs = set(newheads)
         # add unsynced data
diff --git a/mercurial/dispatch.py b/mercurial/dispatch.py
--- a/mercurial/dispatch.py
+++ b/mercurial/dispatch.py
@@ -393,7 +393,7 @@ 
 
         try:
             aliases, entry = cmdutil.findcmd(self.name, cmdtable)
-            for alias, e in cmdtable.iteritems():
+            for alias, e in cmdtable.items():
                 if e is entry:
                     self.cmd = alias
                     break
diff --git a/mercurial/extensions.py b/mercurial/extensions.py
--- a/mercurial/extensions.py
+++ b/mercurial/extensions.py
@@ -47,7 +47,7 @@ 
     try:
         mod = _extensions[name]
     except KeyError:
-        for k, v in _extensions.iteritems():
+        for k, v in _extensions.items():
             if k.endswith('.' + name) or k.endswith('/' + name):
                 mod = v
                 break
@@ -241,7 +241,7 @@ 
     '''
     assert callable(wrapper)
     aliases, entry = cmdutil.findcmd(command, table)
-    for alias, e in table.iteritems():
+    for alias, e in table.items():
         if e is entry:
             key = alias
             break
@@ -380,7 +380,7 @@ 
     try:
         from hgext import __index__
         return dict((name, gettext(desc))
-                    for name, desc in __index__.docs.iteritems()
+                    for name, desc in __index__.docs.items()
                     if name not in _order)
     except (ImportError, AttributeError):
         pass
@@ -390,7 +390,7 @@ 
         return {}
 
     exts = {}
-    for name, path in paths.iteritems():
+    for name, path in paths.items():
         doc = _disabledhelp(path)
         if doc:
             exts[name] = doc
@@ -449,7 +449,7 @@ 
         ext = findcmd(cmd, cmd, path)
     if not ext:
         # otherwise, interrogate each extension until there's a match
-        for name, path in paths.iteritems():
+        for name, path in paths.items():
             ext = findcmd(cmd, name, path)
             if ext:
                 break
@@ -471,7 +471,7 @@ 
 
 def notloaded():
     '''return short names of extensions that failed to load'''
-    return [name for name, mod in _extensions.iteritems() if mod is None]
+    return [name for name, mod in _extensions.items() if mod is None]
 
 def moduleversion(module):
     '''return version information from given module as a string'''
diff --git a/mercurial/fileset.py b/mercurial/fileset.py
--- a/mercurial/fileset.py
+++ b/mercurial/fileset.py
@@ -537,7 +537,7 @@ 
 def loadpredicate(ui, extname, registrarobj):
     """Load fileset predicates from specified registrarobj
     """
-    for name, func in registrarobj._table.iteritems():
+    for name, func in registrarobj._table.items():
         symbols[name] = func
         if func._callstatus:
             _statuscallers.add(name)
diff --git a/mercurial/help.py b/mercurial/help.py
--- a/mercurial/help.py
+++ b/mercurial/help.py
@@ -46,7 +46,7 @@ 
     '''return a text listing of the given extensions'''
     rst = []
     if exts:
-        for name, desc in sorted(exts.iteritems()):
+        for name, desc in sorted(exts.items()):
             if not showdeprecated and any(w in desc for w in _exclkeywords):
                 continue
             rst.append('%s:%s: %s\n' % (' ' * indent, name, desc))
@@ -131,7 +131,7 @@ 
             or (callable(doc) and lowercontains(doc(ui)))):
             results['topics'].append((names[0], header))
     from . import commands # avoid cycle
-    for cmd, entry in commands.table.iteritems():
+    for cmd, entry in commands.table.items():
         if len(entry) == 3:
             summary = entry[2]
         else:
@@ -147,8 +147,8 @@ 
                 continue
             results['commands'].append((cmdname, summary))
     for name, docs in itertools.chain(
-        extensions.enabled(False).iteritems(),
-        extensions.disabled().iteritems()):
+        extensions.enabled(False).items(),
+        extensions.disabled().items()):
         if not docs:
             continue
         mod = extensions.load(ui, name, '')
@@ -156,7 +156,7 @@ 
         if lowercontains(name) or lowercontains(docs):
             # extension docs are already translated
             results['extensions'].append((name, docs.splitlines()[0]))
-        for cmd, entry in getattr(mod, 'cmdtable', {}).iteritems():
+        for cmd, entry in getattr(mod, 'cmdtable', {}).items():
             if kw in cmd or (len(entry) > 2 and lowercontains(entry[2])):
                 cmdname = cmd.partition('|')[0].lstrip('^')
                 if entry[0].__doc__:
@@ -392,7 +392,7 @@ 
 
         h = {}
         cmds = {}
-        for c, e in commands.table.iteritems():
+        for c, e in commands.table.items():
             f = c.partition("|")[0]
             if select and not select(f):
                 continue
diff --git a/mercurial/hgweb/hgweb_mod.py b/mercurial/hgweb/hgweb_mod.py
--- a/mercurial/hgweb/hgweb_mod.py
+++ b/mercurial/hgweb/hgweb_mod.py
@@ -133,7 +133,7 @@ 
 
     def archivelist(self, nodeid):
         allowed = self.configlist('web', 'allow_archive')
-        for typ, spec in self.archivespecs.iteritems():
+        for typ, spec in self.archivespecs.items():
             if typ in allowed or self.configbool('web', 'allow%s' % typ):
                 yield {'type': typ, 'extension': spec[2], 'node': nodeid}
 
@@ -388,7 +388,7 @@ 
 
             if cmd == 'archive':
                 fn = req.form['node'][0]
-                for type_, spec in rctx.archivespecs.iteritems():
+                for type_, spec in rctx.archivespecs.items():
                     ext = spec[2]
                     if fn.endswith(ext):
                         req.form['node'] = [fn[:-len(ext)]]
diff --git a/mercurial/hgweb/request.py b/mercurial/hgweb/request.py
--- a/mercurial/hgweb/request.py
+++ b/mercurial/hgweb/request.py
@@ -47,7 +47,7 @@ 
                 form[name] = value
             del form[k]
     # And strip the values
-    for k, v in form.iteritems():
+    for k, v in form.items():
         form[k] = [i.strip() for i in v]
     return form
 
diff --git a/mercurial/hgweb/webutil.py b/mercurial/hgweb/webutil.py
--- a/mercurial/hgweb/webutil.py
+++ b/mercurial/hgweb/webutil.py
@@ -557,7 +557,7 @@ 
         return sessionvars(copy.copy(self.vars), self.start)
     def __iter__(self):
         separator = self.start
-        for key, value in sorted(self.vars.iteritems()):
+        for key, value in sorted(self.vars.items()):
             yield {'name': key, 'value': str(value), 'separator': separator}
             separator = '&'
 
diff --git a/mercurial/hgweb/wsgicgi.py b/mercurial/hgweb/wsgicgi.py
--- a/mercurial/hgweb/wsgicgi.py
+++ b/mercurial/hgweb/wsgicgi.py
@@ -25,7 +25,7 @@ 
     util.setbinary(sys.stdin)
     util.setbinary(sys.stdout)
 
-    environ = dict(os.environ.iteritems())
+    environ = dict(os.environ.items())
     environ.setdefault('PATH_INFO', '')
     if environ.get('SERVER_SOFTWARE', '').startswith('Microsoft-IIS'):
         # IIS includes script_name in PATH_INFO
diff --git a/mercurial/hook.py b/mercurial/hook.py
--- a/mercurial/hook.py
+++ b/mercurial/hook.py
@@ -134,14 +134,14 @@ 
         if tr and tr.writepending():
             env['HG_PENDING'] = repo.root
 
-    for k, v in args.iteritems():
+    for k, v in args.items():
         if callable(v):
             v = v()
         if isinstance(v, dict):
             # make the dictionary element order stable across Python
             # implementations
             v = ('{' +
-                 ', '.join('%r: %r' % i for i in sorted(v.iteritems())) +
+                 ', '.join('%r: %r' % i for i in sorted(v.items())) +
                  '}')
         env['HG_' + k.upper()] = v
 
diff --git a/mercurial/httpconnection.py b/mercurial/httpconnection.py
--- a/mercurial/httpconnection.py
+++ b/mercurial/httpconnection.py
@@ -77,7 +77,7 @@ 
     bestuser = None
     bestlen = 0
     bestauth = None
-    for group, auth in config.iteritems():
+    for group, auth in config.items():
         if user and user != auth.get('username', user):
             # If a username was set in the URI, the entry username
             # must either match it or be unset
diff --git a/mercurial/keepalive.py b/mercurial/keepalive.py
--- a/mercurial/keepalive.py
+++ b/mercurial/keepalive.py
@@ -211,7 +211,7 @@ 
 
     def close_all(self):
         """close all open connections"""
-        for host, conns in self._cm.get_all().iteritems():
+        for host, conns in self._cm.get_all().items():
             for h in conns:
                 self._cm.remove(h)
                 h.close()
diff --git a/mercurial/localrepo.py b/mercurial/localrepo.py
--- a/mercurial/localrepo.py
+++ b/mercurial/localrepo.py
@@ -460,7 +460,7 @@ 
     def bookmarkheads(self, bookmark):
         name = bookmark.split('@', 1)[0]
         heads = []
-        for mark, n in self._bookmarks.iteritems():
+        for mark, n in self._bookmarks.items():
             if mark.split('@', 1)[0] == name:
                 heads.append(n)
         return heads
@@ -715,7 +715,7 @@ 
             tags, tt = self._findtags()
         else:
             tags = self._tagscache.tags
-        for k, v in tags.iteritems():
+        for k, v in tags.items():
             try:
                 # ignore tags to unknown nodes
                 self.changelog.rev(v)
@@ -749,12 +749,12 @@ 
         # writing to the cache), but the rest of Mercurial wants them in
         # local encoding.
         tags = {}
-        for (name, (node, hist)) in alltags.iteritems():
+        for (name, (node, hist)) in alltags.items():
             if node != nullid:
                 tags[encoding.tolocal(name)] = node
         tags['tip'] = self.changelog.tip()
         tagtypes = dict([(encoding.tolocal(name), value)
-                         for (name, value) in tagtypes.iteritems()])
+                         for (name, value) in tagtypes.items()])
         return (tags, tagtypes)
 
     def tagtype(self, tagname):
@@ -772,7 +772,7 @@ 
         '''return a list of tags ordered by revision'''
         if not self._tagscache.tagslist:
             l = []
-            for t, n in self.tags().iteritems():
+            for t, n in self.tags().items():
                 l.append((self.changelog.rev(n), t, n))
             self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
 
@@ -782,7 +782,7 @@ 
         '''return the tags associated with a node'''
         if not self._tagscache.nodetagscache:
             nodetagscache = {}
-            for t, n in self._tagscache.tags.iteritems():
+            for t, n in self._tagscache.tags.items():
                 nodetagscache.setdefault(n, []).append(t)
             for tags in nodetagscache.itervalues():
                 tags.sort()
@@ -792,7 +792,7 @@ 
     def nodebookmarks(self, node):
         """return the list of bookmarks pointing to the specified node"""
         marks = []
-        for bookmark, n in self._bookmarks.iteritems():
+        for bookmark, n in self._bookmarks.items():
             if n == node:
                 marks.append(bookmark)
         return sorted(marks)
@@ -933,7 +933,7 @@ 
                 mf = matchmod.match(self.root, '', [pat])
                 fn = None
                 params = cmd
-                for name, filterfn in self._datafilters.iteritems():
+                for name, filterfn in self._datafilters.items():
                     if cmd.startswith(name):
                         fn = filterfn
                         params = cmd[len(name):].lstrip()
diff --git a/mercurial/lsprof.py b/mercurial/lsprof.py
--- a/mercurial/lsprof.py
+++ b/mercurial/lsprof.py
@@ -95,7 +95,7 @@ 
     try:
         mname = _fn2mod[code.co_filename]
     except KeyError:
-        for k, v in list(sys.modules.iteritems()):
+        for k, v in list(sys.modules.items()):
             if v is None:
                 continue
             if not isinstance(getattr(v, '__file__', None), str):
diff --git a/mercurial/match.py b/mercurial/match.py
--- a/mercurial/match.py
+++ b/mercurial/match.py
@@ -695,7 +695,7 @@ 
             continue
 
         linesyntax = syntax
-        for s, rels in syntaxes.iteritems():
+        for s, rels in syntaxes.items():
             if line.startswith(rels):
                 linesyntax = rels
                 line = line[len(rels):]
diff --git a/mercurial/merge.py b/mercurial/merge.py
--- a/mercurial/merge.py
+++ b/mercurial/merge.py
@@ -346,7 +346,7 @@ 
         if self.mergedriver:
             records.append(('m', '\0'.join([
                 self.mergedriver, self._mdstate])))
-        for d, v in self._state.iteritems():
+        for d, v in self._state.items():
             if v[0] == 'd':
                 records.append(('D', '\0'.join([d] + v)))
             # v[1] == local ('cd'), v[6] == other ('dc') -- not supported by
@@ -355,9 +355,9 @@ 
                 records.append(('C', '\0'.join([d] + v)))
             else:
                 records.append(('F', '\0'.join([d] + v)))
-        for filename, extras in sorted(self._stateextras.iteritems()):
+        for filename, extras in sorted(self._stateextras.items()):
             rawextras = '\0'.join('%s\0%s' % (k, v) for k, v in
-                                  extras.iteritems())
+                                  extras.items())
             records.append(('f', '%s\0%s' % (filename, rawextras)))
         if self._labels is not None:
             labels = '\0'.join(self._labels)
@@ -560,13 +560,13 @@ 
 
     def unresolvedcount(self):
         """get unresolved count for this merge (persistent)"""
-        return len([True for f, entry in self._state.iteritems()
+        return len([True for f, entry in self._state.items()
                     if entry[0] == 'u'])
 
     def actions(self):
         """return lists of actions to perform on the dirstate"""
         actions = {'r': [], 'f': [], 'a': [], 'am': [], 'g': []}
-        for f, (r, action) in self._results.iteritems():
+        for f, (r, action) in self._results.items():
             if action is not None:
                 actions[action].append((f, None, "merge result"))
         return actions
@@ -630,7 +630,7 @@ 
             elif config == 'warn':
                 warnconflicts.update(conflicts)
 
-        for f, (m, args, msg) in actions.iteritems():
+        for f, (m, args, msg) in actions.items():
             if m in ('c', 'dc'):
                 if _checkunknownfile(repo, wctx, mctx, f):
                     conflicts.add(f)
@@ -644,7 +644,7 @@ 
         collectconflicts(ignoredconflicts, ignoredconfig)
         collectconflicts(unknownconflicts, unknownconfig)
     else:
-        for f, (m, args, msg) in actions.iteritems():
+        for f, (m, args, msg) in actions.items():
             if m == 'cm':
                 fl2, anc = args
                 different = _checkunknownfile(repo, wctx, mctx, f)
@@ -686,7 +686,7 @@ 
     for f in sorted(warnconflicts):
         repo.ui.warn(_("%s: replacing untracked file\n") % f)
 
-    for f, (m, args, msg) in actions.iteritems():
+    for f, (m, args, msg) in actions.items():
         backup = f in conflicts
         if m == 'c':
             flags, = args
@@ -820,7 +820,7 @@ 
     diff = m1.diff(m2)
 
     actions = {}
-    for f, ((n1, fl1), (n2, fl2)) in diff.iteritems():
+    for f, ((n1, fl1), (n2, fl2)) in diff.items():
         if n1 and n2: # file exists on both local and remote side
             if f not in ma:
                 fa = copy.get(f, None)
@@ -968,7 +968,7 @@ 
             if renamedelete is None or len(renamedelete) < len(renamedelete1):
                 renamedelete = renamedelete1
 
-            for f, a in sorted(actions.iteritems()):
+            for f, a in sorted(actions.items()):
                 m, args, msg = a
                 repo.ui.debug(' %s: %s -> %s\n' % (f, msg, m))
                 if f in fbids:
@@ -1286,7 +1286,7 @@ 
     removed += msremoved
 
     extraactions = ms.actions()
-    for k, acts in extraactions.iteritems():
+    for k, acts in extraactions.items():
         actions[k].extend(acts)
 
     progress(_updating, None, total=numupdates, unit=_files)
@@ -1560,7 +1560,7 @@ 
 
         # Convert to dictionary-of-lists format
         actions = dict((m, []) for m in 'a am f g cd dc r dm dg m e k'.split())
-        for f, (m, args, msg) in actionbyfile.iteritems():
+        for f, (m, args, msg) in actionbyfile.items():
             if m not in actions:
                 actions[m] = []
             actions[m].append((f, args, msg))
@@ -1574,14 +1574,14 @@ 
                 _checkcollision(repo, wc.manifest(), actions)
 
         # divergent renames
-        for f, fl in sorted(diverge.iteritems()):
+        for f, fl in sorted(diverge.items()):
             repo.ui.warn(_("note: possible conflict - %s was renamed "
                            "multiple times to:\n") % f)
             for nf in fl:
                 repo.ui.warn(" %s\n" % nf)
 
         # rename and delete
-        for f, fl in sorted(renamedelete.iteritems()):
+        for f, fl in sorted(renamedelete.items()):
             repo.ui.warn(_("note: possible conflict - %s was deleted "
                            "and renamed to:\n") % f)
             for nf in fl:
diff --git a/mercurial/obsolete.py b/mercurial/obsolete.py
--- a/mercurial/obsolete.py
+++ b/mercurial/obsolete.py
@@ -203,7 +203,7 @@ 
                 # if content cannot be translated to nodeid drop the data.
                 parents = None
 
-        metadata = tuple(sorted(metadata.iteritems()))
+        metadata = tuple(sorted(metadata.items()))
 
         yield (pre, sucs, flags, metadata, date, parents)
 
@@ -231,7 +231,7 @@ 
     """Return encoded metadata string to string mapping.
 
     Assume no ':' in key and no '\0' in both key and value."""
-    for key, value in meta.iteritems():
+    for key, value in meta.items():
         if ':' in key or '\0' in key:
             raise ValueError("':' and '\0' are forbidden in metadata key'")
         if '\0' in value:
@@ -589,7 +589,7 @@ 
         if prec in succs:
             raise ValueError(_('in-marker cycle with %s') % node.hex(prec))
 
-        metadata = tuple(sorted(metadata.iteritems()))
+        metadata = tuple(sorted(metadata.items()))
 
         marker = (str(prec), tuple(succs), int(flag), metadata, date, parents)
         return bool(self.add(transaction, [marker]))
diff --git a/mercurial/patch.py b/mercurial/patch.py
--- a/mercurial/patch.py
+++ b/mercurial/patch.py
@@ -2254,7 +2254,7 @@ 
             removed = filterrel(removed)
             relfiltered = True
         # filter out copies where either side isn't inside the relative root
-        copy = dict(((dst, src) for (dst, src) in copy.iteritems()
+        copy = dict(((dst, src) for (dst, src) in copy.items()
                      if dst.startswith(relroot)
                      and src.startswith(relroot)))
 
diff --git a/mercurial/phases.py b/mercurial/phases.py
--- a/mercurial/phases.py
+++ b/mercurial/phases.py
@@ -430,7 +430,7 @@ 
     # build list from dictionary
     draftroots = []
     nodemap = repo.changelog.nodemap # to filter unknown nodes
-    for nhex, phase in roots.iteritems():
+    for nhex, phase in roots.items():
         if nhex == 'publishing': # ignore data related to publish option
             continue
         node = bin(nhex)
diff --git a/mercurial/pure/parsers.py b/mercurial/pure/parsers.py
--- a/mercurial/pure/parsers.py
+++ b/mercurial/pure/parsers.py
@@ -94,7 +94,7 @@ 
     cs = stringio()
     write = cs.write
     write("".join(pl))
-    for f, e in dmap.iteritems():
+    for f, e in dmap.items():
         if e[0] == 'n' and e[3] == now:
             # The file was last modified "simultaneously" with the current
             # write to dirstate (i.e. within the same second for file-
diff --git a/mercurial/revlog.py b/mercurial/revlog.py
--- a/mercurial/revlog.py
+++ b/mercurial/revlog.py
@@ -783,7 +783,7 @@ 
                     # But, obviously its parents aren't.
                     for p in self.parents(n):
                         heads.pop(p, None)
-        heads = [n for n, flag in heads.iteritems() if flag]
+        heads = [n for n, flag in heads.items() if flag]
         roots = list(roots)
         assert orderedout
         assert roots
diff --git a/mercurial/scmutil.py b/mercurial/scmutil.py
--- a/mercurial/scmutil.py
+++ b/mercurial/scmutil.py
@@ -107,7 +107,7 @@ 
             del subpaths[subpath]
             missing.add(subpath)
 
-    for subpath, ctx in sorted(subpaths.iteritems()):
+    for subpath, ctx in sorted(subpaths.items()):
         yield subpath, ctx.sub(subpath)
 
     # Yield an empty subrepo based on ctx1 for anything only in ctx2.  That way,
@@ -993,7 +993,7 @@ 
     dirstate = repo.dirstate
     walkresults = dirstate.walk(matcher, sorted(ctx.substate), True, False,
                                 full=False)
-    for abs, st in walkresults.iteritems():
+    for abs, st in walkresults.items():
         dstate = dirstate[abs]
         if dstate == '?' and audit_path.check(abs):
             unknown.append(abs)
@@ -1031,7 +1031,7 @@ 
     with repo.wlock():
         wctx.forget(deleted)
         wctx.add(unknown)
-        for new, old in renames.iteritems():
+        for new, old in renames.items():
             wctx.copy(old, new)
 
 def dirstatecopy(ui, repo, wctx, src, dst, dryrun=False, cwd=None):
diff --git a/mercurial/similar.py b/mercurial/similar.py
--- a/mercurial/similar.py
+++ b/mercurial/similar.py
@@ -78,7 +78,7 @@ 
                 copies[a] = (r, myscore)
     repo.ui.progress(_('searching'), None)
 
-    for dest, v in copies.iteritems():
+    for dest, v in copies.items():
         source, score = v
         yield source, dest, score
 
diff --git a/mercurial/sshpeer.py b/mercurial/sshpeer.py
--- a/mercurial/sshpeer.py
+++ b/mercurial/sshpeer.py
@@ -236,7 +236,7 @@ 
         for op, argsdict in req:
             args = ','.join('%s=%s' % (wireproto.escapearg(k),
                                        wireproto.escapearg(v))
-                            for k, v in argsdict.iteritems())
+                            for k, v in argsdict.items())
             cmds.append('%s %s' % (op, args))
         rsp = self._callstream("batch", cmds=';'.join(cmds))
         available = self._getamount()
@@ -269,10 +269,10 @@ 
             else:
                 wireargs[k] = args[k]
                 del args[k]
-        for k, v in sorted(wireargs.iteritems()):
+        for k, v in sorted(wireargs.items()):
             self.pipeo.write("%s %d\n" % (k, len(v)))
             if isinstance(v, dict):
-                for dk, dv in v.iteritems():
+                for dk, dv in v.items():
                     self.pipeo.write("%s %d\n" % (dk, len(dv)))
                     self.pipeo.write(dv)
             else:
diff --git a/mercurial/store.py b/mercurial/store.py
--- a/mercurial/store.py
+++ b/mercurial/store.py
@@ -89,7 +89,7 @@ 
     for x in range(ord("A"), ord("Z") + 1) + [ord(e)]:
         cmap[chr(x)] = e + chr(x).lower()
     dmap = {}
-    for k, v in cmap.iteritems():
+    for k, v in cmap.items():
         dmap[v] = k
     def decode(s):
         i = 0
diff --git a/mercurial/subrepo.py b/mercurial/subrepo.py
--- a/mercurial/subrepo.py
+++ b/mercurial/subrepo.py
@@ -190,7 +190,7 @@ 
             r = "%s:%s:%s" % r
         repo.ui.debug("  subrepo %s: %s %s\n" % (s, msg, r))
 
-    for s, l in sorted(s1.iteritems()):
+    for s, l in sorted(s1.items()):
         a = sa.get(s, nullstate)
         ld = l # local state with possible dirty flag for compares
         if wctx.sub(s).dirty():
@@ -1670,7 +1670,7 @@ 
             for b in rev2branch[self._state[1]]:
                 if b.startswith('refs/remotes/origin/'):
                     return True
-        for b, revision in branch2rev.iteritems():
+        for b, revision in branch2rev.items():
             if b.startswith('refs/remotes/origin/'):
                 if self._gitisancestor(self._state[1], revision):
                     return True
diff --git a/mercurial/tags.py b/mercurial/tags.py
--- a/mercurial/tags.py
+++ b/mercurial/tags.py
@@ -234,7 +234,7 @@ 
     dictionaries, alltags and tagtypes, that contain all tag
     info (global across all heads plus local).'''
 
-    for name, nodehist in filetags.iteritems():
+    for name, nodehist in filetags.items():
         if name not in alltags:
             alltags[name] = nodehist
             tagtypes[name] = tagtype
@@ -389,7 +389,7 @@ 
     # we keep them in UTF-8 throughout this module.  If we converted
     # them local encoding on input, we would lose info writing them to
     # the cache.
-    for (name, (node, hist)) in sorted(cachetags.iteritems()):
+    for (name, (node, hist)) in sorted(cachetags.items()):
         for n in hist:
             cachefile.write("%s %s\n" % (hex(n), name))
         cachefile.write("%s %s\n" % (hex(node), name))
diff --git a/mercurial/templatefilters.py b/mercurial/templatefilters.py
--- a/mercurial/templatefilters.py
+++ b/mercurial/templatefilters.py
@@ -227,7 +227,7 @@ 
         return '"%s"' % encoding.jsonescape(obj, paranoid=True)
     elif util.safehasattr(obj, 'keys'):
         out = []
-        for k, v in sorted(obj.iteritems()):
+        for k, v in sorted(obj.items()):
             s = '%s: %s' % (json(k), json(v))
             out.append(s)
         return '{' + ', '.join(out) + '}'
@@ -426,7 +426,7 @@ 
 def loadfilter(ui, extname, registrarobj):
     """Load template filter from specified registrarobj
     """
-    for name, func in registrarobj._table.iteritems():
+    for name, func in registrarobj._table.items():
         filters[name] = func
 
 # tell hggettext to extract docstrings from these functions:
diff --git a/mercurial/templater.py b/mercurial/templater.py
--- a/mercurial/templater.py
+++ b/mercurial/templater.py
@@ -1076,7 +1076,7 @@ 
 def loadfunction(ui, extname, registrarobj):
     """Load template function from specified registrarobj
     """
-    for name, func in registrarobj._table.iteritems():
+    for name, func in registrarobj._table.items():
         funcs[name] = func
 
 # tell hggettext to extract docstrings from these functions:
diff --git a/mercurial/url.py b/mercurial/url.py
--- a/mercurial/url.py
+++ b/mercurial/url.py
@@ -232,7 +232,7 @@ 
             [(x, self.headers[x]) for x in self.headers
              if x.lower().startswith('proxy-')])
     self.send('CONNECT %s HTTP/1.0\r\n' % self.realhostport)
-    for header in proxyheaders.iteritems():
+    for header in proxyheaders.items():
         self.send('%s: %s\r\n' % header)
     self.send('\r\n')
 
diff --git a/mercurial/verify.py b/mercurial/verify.py
--- a/mercurial/verify.py
+++ b/mercurial/verify.py
@@ -281,10 +281,10 @@ 
                 ui.progress(_('checking'), currentsubdir[0], total=subdircount,
                             unit=_('manifests'))
 
-        for subdir, linkrevs in subdirnodes.iteritems():
+        for subdir, linkrevs in subdirnodes.items():
             subdirfilenodes = self._verifymanifest(linkrevs, subdir, storefiles,
                                                    progress)
-            for f, onefilenodes in subdirfilenodes.iteritems():
+            for f, onefilenodes in subdirfilenodes.items():
                 filenodes.setdefault(f, {}).update(onefilenodes)
 
         if not dir and subdirnodes:
@@ -423,7 +423,7 @@ 
 
             # cross-check
             if f in filenodes:
-                fns = [(lr, n) for n, lr in filenodes[f].iteritems()]
+                fns = [(lr, n) for n, lr in filenodes[f].items()]
                 for lr, node in sorted(fns):
                     self.err(lr, _("manifest refers to unknown revision %s") %
                              short(node), f)
diff --git a/mercurial/wireproto.py b/mercurial/wireproto.py
--- a/mercurial/wireproto.py
+++ b/mercurial/wireproto.py
@@ -228,7 +228,7 @@ 
         cmds = []
         for op, argsdict in req:
             args = ','.join('%s=%s' % (escapearg(k), escapearg(v))
-                            for k, v in argsdict.iteritems())
+                            for k, v in argsdict.items())
             cmds.append('%s %s' % (op, args))
         rsp = self._callstream("batch", cmds=';'.join(cmds))
         # TODO this response parsing is probably suboptimal for large
@@ -374,7 +374,7 @@ 
             kwargs['bundlecaps'] = sorted(bundlecaps)
         else:
             bundlecaps = () # kwargs could have it to None
-        for key, value in kwargs.iteritems():
+        for key, value in kwargs.items():
             if value is None:
                 continue
             keytype = gboptsmap.get(key)
@@ -633,7 +633,7 @@ 
 def branchmap(repo, proto):
     branchmap = repo.branchmap()
     heads = []
-    for branch, nodes in branchmap.iteritems():
+    for branch, nodes in branchmap.items():
         branchname = urlreq.quote(encoding.fromlocal(branch))
         branchnodes = encodelist(nodes)
         heads.append('%s %s' % (branchname, branchnodes))
@@ -728,7 +728,7 @@ 
 @wireprotocommand('getbundle', '*')
 def getbundle(repo, proto, others):
     opts = options('getbundle', gboptsmap.keys(), others)
-    for k, v in opts.iteritems():
+    for k, v in opts.items():
         keytype = gboptsmap[k]
         if keytype == 'nodes':
             opts[k] = decodelist(v)
diff --git a/tests/fakedirstatewritetime.py b/tests/fakedirstatewritetime.py
--- a/tests/fakedirstatewritetime.py
+++ b/tests/fakedirstatewritetime.py
@@ -19,7 +19,7 @@ 
     # execute what original parsers.pack_dirstate should do actually
     # for consistency
     actualnow = int(now)
-    for f, e in dmap.iteritems():
+    for f, e in dmap.items():
         if e[0] == 'n' and e[3] == actualnow:
             e = parsers.dirstatetuple(e[0], e[1], e[2], -1)
             dmap[f] = e
diff --git a/tests/hghave b/tests/hghave
--- a/tests/hghave
+++ b/tests/hghave
@@ -13,13 +13,13 @@ 
 checks = hghave.checks
 
 def list_features():
-    for name, feature in sorted(checks.iteritems()):
+    for name, feature in sorted(checks.items()):
         desc = feature[1]
         print(name + ':', desc)
 
 def test_features():
     failed = 0
-    for name, feature in checks.iteritems():
+    for name, feature in checks.items():
         check, _ = feature
         try:
             check()
diff --git a/tests/printenv.py b/tests/printenv.py
--- a/tests/printenv.py
+++ b/tests/printenv.py
@@ -34,7 +34,7 @@ 
 
 # variables with empty values may not exist on all platforms, filter
 # them now for portability sake.
-env = [(k, v) for k, v in os.environ.iteritems()
+env = [(k, v) for k, v in os.environ.items()
        if k.startswith("HG_") and v]
 env.sort()
 
diff --git a/tests/test-duplicateoptions.py b/tests/test-duplicateoptions.py
--- a/tests/test-duplicateoptions.py
+++ b/tests/test-duplicateoptions.py
@@ -30,7 +30,7 @@ 
     option[0] and globalshort.add(option[0])
     option[1] and globallong.add(option[1])
 
-for cmd, entry in commands.table.iteritems():
+for cmd, entry in commands.table.items():
     seenshort = globalshort.copy()
     seenlong = globallong.copy()
     for option in entry[1]:
diff --git a/tests/test-hgweb-auth.py b/tests/test-hgweb-auth.py
--- a/tests/test-hgweb-auth.py
+++ b/tests/test-hgweb-auth.py
@@ -19,7 +19,7 @@ 
 
 def writeauth(items):
     ui = origui.copy()
-    for name, value in items.iteritems():
+    for name, value in items.items():
         ui.setconfig('auth', name, value)
     return ui
 
@@ -36,7 +36,7 @@ 
         for name in ('.username', '.password'):
             if (p + name) not in auth:
                 auth[p + name] = p
-    auth = dict((k, v) for k, v in auth.iteritems() if v is not None)
+    auth = dict((k, v) for k, v in auth.items() if v is not None)
 
     ui = writeauth(auth)
 
diff --git a/tests/test-pathencode.py b/tests/test-pathencode.py
--- a/tests/test-pathencode.py
+++ b/tests/test-pathencode.py
@@ -49,7 +49,7 @@ 
         counts.pop(c, None)
     t = sum(counts.itervalues()) / 100.0
     fp.write('probtable = (')
-    for i, (k, v) in enumerate(sorted(counts.iteritems(), key=lambda x: x[1],
+    for i, (k, v) in enumerate(sorted(counts.items(), key=lambda x: x[1],
                                       reverse=True)):
         if (i % 5) == 0:
             fp.write('\n    ')