changeset 588:4d9e2d2a2c19 next

Merge
author Augie Fackler <raf@durin42.com>
date Sun, 11 Nov 2012 17:12:55 -0600
parents 24d4741674a6 (diff) 1ab57b19cb3a (current diff)
children 2af1d664f498 2320ab6ada36
files hggit/git_handler.py
diffstat 69 files changed, 4019 insertions(+), 3434 deletions(-) [+]
line wrap: on
line diff
--- a/DESIGN.txt
+++ b/DESIGN.txt
@@ -63,7 +63,3 @@
 And you should see output like this:
 .
 # Ran 1 tests, 0 skipped, 0 failed.
-
-Note that due to limitations of Dulwich at the moment, the tests need to
-start a git-daemon process. Right now, they use the default port, so will
-skip if they detect an already-running git-daemon.
--- a/Makefile
+++ b/Makefile
@@ -25,7 +25,7 @@
 # latest Ubuntu LTS release (2.0.2 for 12.04 LTS) may be dropped if they
 # interfere with new development.  The latest released minor version should be
 # listed for each major version; earlier minor versions are not needed.
-all-version-tests: tests-1.7.5 tests-1.8.4 tests-1.9.3 tests-2.0.2 \
-                   tests-2.1.2 tests-2.2.3 tests-2.3.1 tests-tip
+all-version-tests: tests-1.9.3 tests-2.0.2 tests-2.1.2 tests-2.2.3 \
+                   tests-2.3.1 tests-tip
 
 .PHONY: tests all-version-tests
--- a/README.md
+++ b/README.md
@@ -24,8 +24,8 @@
 This plugin is implemented entirely in Python - there are no Git
 binary dependencies, you do not need to have Git installed on your
 system.  The only dependencies are Mercurial and Dulwich.  The plugin
-is known to work on Hg versions 1.3 through 1.5 and requires at least
-Dulwich 0.6.0.
+is known to work on Hg versions 1.9.3 through 2.3.1 and requires at least
+Dulwich 0.8.6.
 
 Usage
 =====
@@ -74,15 +74,15 @@
 That will pull down any commits that have been pushed to the server in
 the meantime and give you a new head that you can merge in.
 
-Hg-Git can also be used to convert a Mercurial repository to Git.  As
-Dulwich doesn't support local repositories yet, the easiest way is to
-setup up a local SSH server.  Then use the following commands to
-convert the repository (it assumes your running this in $HOME).
+Hg-Git can also be used to convert a Mercurial repository to Git.  You can use
+a local repository or a remote repository accessed via SSH, HTTP or HTTPS.  Use
+the following commands to convert the repository (it assumes your running this
+in $HOME).
 
     $ mkdir git-repo; cd git-repo; git init; cd ..
     $ cd hg-repo
     $ hg bookmarks hg
-    $ hg push git+ssh://localhost:git-repo
+    $ hg push ../git-repo
 
 The hg bookmark is necessary to prevent problems as otherwise hg-git
 pushes to the currently checked out branch confusing Git. This will
@@ -123,8 +123,7 @@
 Hg Bookmarks Integration
 ========================
 
-If you have the bookmarks extension enabled, Hg-Git will use it. It
-will push your bookmarks up to the Git server as branches and will
+Hg-Git pushes your bookmarks up to the Git server as branches and will
 pull Git branches down and set them up as bookmarks.
 
 Installing
@@ -134,21 +133,16 @@
 your `~/.hgrc` file look something like this:
 
     [extensions]
-    hgext.bookmarks =
     hggit = [path-to]/hg-git/hggit
 
-That will enable the Hg-Git extension for you.  The bookmarks section
-is not compulsory, but it makes some things a bit nicer for you.
+That will enable the Hg-Git extension for you.
 
 This plugin is currently tested against the following Mercurial versions:
- * 1.6.4
- * 1.7.5
- * 1.8.4
  * 1.9.3
  * 2.0.2
  * 2.1.2
  * 2.2.3
- * 2.3
+ * 2.3.1
 
 Configuration
 =============
--- a/hggit/__init__.py
+++ b/hggit/__init__.py
@@ -24,6 +24,7 @@
 from mercurial import bundlerepo
 from mercurial import commands
 from mercurial import demandimport
+from mercurial import discovery
 from mercurial import extensions
 from mercurial import help
 from mercurial import hg
@@ -41,6 +42,9 @@
 import gitrepo, hgrepo
 from git_handler import GitHandler
 
+testedwith = '1.9.3 2.0.2 2.1.2 2.2.3 2.3.1'
+buglink = 'https://bitbucket.org/durin42/hg-git/issues'
+
 # support for `hg clone git://github.com/defunkt/facebox.git`
 # also hg clone git+ssh://git@github.com/schacon/simplegit.git
 _gitschemes = ('git', 'git+ssh', 'git+http', 'git+https')
@@ -142,25 +146,24 @@
     return ret
 extensions.wrapfunction(localrepo.localrepository, 'nodetags', sortednodetags)
 
-try:
-    from mercurial import discovery
-    kwname = 'heads'
-    if hg.util.version() >= '1.7':
-        kwname = 'remoteheads'
-    if getattr(discovery, 'findcommonoutgoing', None):
-        kwname = 'onlyheads'
-    def findoutgoing(orig, local, remote, *args, **kwargs):
-        if isinstance(remote, gitrepo.gitrepo):
-            raise hgutil.Abort(
-                'hg-git outgoing support is broken')
-        return orig(local, remote, *args, **kwargs)
-    if getattr(discovery, 'findoutgoing', None):
-        extensions.wrapfunction(discovery, 'findoutgoing', findoutgoing)
-    else:
-        extensions.wrapfunction(discovery, 'findcommonoutgoing',
-                                findoutgoing)
-except ImportError:
-    pass
+def findcommonoutgoing(orig, repo, other, *args, **kwargs):
+    if isinstance(other, gitrepo.gitrepo):
+        git = GitHandler(repo, repo.ui)
+        heads = git.get_refs(other.path)[0]
+        kw = {}
+        kw.update(kwargs)
+        for val, k in zip(args,
+                ('onlyheads', 'force', 'commoninc', 'portable')):
+            kw[k] = val
+        force = kw.get('force', False)
+        commoninc = kw.get('commoninc', None)
+        if commoninc is None:
+            commoninc = discovery.findcommonincoming(repo, other,
+                heads=heads, force=force)
+            kw['commoninc'] = commoninc
+        return orig(repo, other, **kw)
+    return orig(repo, other, *args, **kwargs)
+extensions.wrapfunction(discovery, 'findcommonoutgoing', findcommonoutgoing)
 
 def getremotechanges(orig, ui, repo, other, *args, **opts):
     if isinstance(other, gitrepo.gitrepo):
@@ -181,6 +184,14 @@
     # 1.7+
     pass
 
+def peer(orig, uiorrepo, *args, **opts):
+    newpeer = orig(uiorrepo, *args, **opts)
+    if isinstance(newpeer, gitrepo.gitrepo):
+        if isinstance(uiorrepo, localrepo.localrepository):
+            newpeer.localrepo = uiorrepo
+    return newpeer
+extensions.wrapfunction(hg, 'peer', peer)
+
 def revset_fromgit(repo, subset, x):
     '''``fromgit()``
     Select changesets that originate from Git.
--- a/hggit/git_handler.py
+++ b/hggit/git_handler.py
@@ -1,11 +1,13 @@
 import os, math, urllib, re
+import stat, posixpath, StringIO
 
-from dulwich.errors import HangupException, GitProtocolError
+from dulwich.errors import HangupException, GitProtocolError, UpdateRefsError
 from dulwich.index import commit_tree
-from dulwich.objects import Blob, Commit, Tag, Tree, parse_timezone
+from dulwich.objects import Blob, Commit, Tag, Tree, parse_timezone, S_IFGITLINK
 from dulwich.pack import create_delta, apply_delta
 from dulwich.repo import Repo
 from dulwich import client
+from dulwich import config as dul_config
 
 try:
     from mercurial import bookmarks
@@ -27,6 +29,24 @@
 import util
 from overlay import overlayrepo
 
+RE_GIT_AUTHOR = re.compile('^(.*?) ?\<(.*?)(?:\>(.*))?$')
+
+RE_GIT_SANITIZE_AUTHOR = re.compile('[<>\n]')
+
+RE_GIT_AUTHOR_EXTRA = re.compile('^(.*?)\ ext:\((.*)\) <(.*)\>$')
+
+# Test for git:// and git+ssh:// URI.
+# Support several URL forms, including separating the
+# host and path with either a / or : (sepr)
+RE_GIT_URI = re.compile(
+    r'^(?P<scheme>git([+]ssh)?://)(?P<host>.*?)(:(?P<port>\d+))?'
+    r'(?P<sepr>[:/])(?P<path>.*)$')
+
+RE_NEWLINES = re.compile('[\r\n]')
+RE_GIT_PROGRESS = re.compile('\((\d+)/(\d+)\)')
+
+RE_AUTHOR_FILE = re.compile('\s*=\s*')
+
 class GitProgress(object):
     """convert git server progress strings into mercurial progress"""
     def __init__(self, ui):
@@ -38,7 +58,7 @@
     def progress(self, msg):
         # 'Counting objects: 33640, done.\n'
         # 'Compressing objects:   0% (1/9955)   \r
-        msgs = re.split('[\r\n]', self.msgbuf + msg)
+        msgs = RE_NEWLINES.split(self.msgbuf + msg)
         self.msgbuf = msgs.pop()
 
         for msg in msgs:
@@ -49,7 +69,7 @@
                 continue
             topic = td[0]
 
-            m = re.search('\((\d+)/(\d+)\)', data)
+            m = RE_GIT_PROGRESS.search(data)
             if m:
                 if self.lasttopic and self.lasttopic != topic:
                     self.flush()
@@ -113,15 +133,17 @@
     def init_author_file(self):
         self.author_map = {}
         if self.ui.config('git', 'authors'):
-            with open(self.repo.wjoin(
-                self.ui.config('git', 'authors')
-            )) as f:
+            f = open(self.repo.wjoin(
+                self.ui.config('git', 'authors')))
+            try:
                 for line in f:
                     line = line.strip()
                     if not line or line.startswith('#'):
                         continue
-                    from_, to = re.split(r'\s*=\s*', line, 2)
+                    from_, to = RE_AUTHOR_FILE.split(line, 2)
                     self.author_map[from_] = to
+            finally:
+                f.close()
 
     ## FILE LOAD AND SAVE METHODS
 
@@ -231,8 +253,7 @@
             old_refs.update(refs)
             to_push = set(self.local_heads().values() + self.tags.values())
             new_refs.update(self.get_changed_refs(refs, to_push, True))
-            # don't push anything
-            return {}
+            return refs # always return the same refs to make the send a no-op
 
         try:
             client.send_pack(path, changed, lambda have, want: [])
@@ -258,7 +279,10 @@
         if remote_name and new_refs:
             for ref, new_sha in new_refs.iteritems():
                 if new_sha != old_refs.get(ref):
-                    self.ui.status("    %s::%s => GIT:%s\n" %
+                    self.ui.note("    %s::%s => GIT:%s\n" %
+                                   (remote_name, ref, new_sha[0:8]))
+                else:
+                    self.ui.debug("    %s::%s => GIT:%s\n" %
                                    (remote_name, ref, new_sha[0:8]))
 
             self.update_remote_branches(remote_name, new_refs)
@@ -315,7 +339,7 @@
         export = [node for node in nodes if not hex(node) in self._map_hg]
         total = len(export)
         if total:
-            self.ui.status(_("exporting hg objects to git\n"))
+            self.ui.note(_("exporting hg objects to git\n"))
         for i, rev in enumerate(export):
             util.progress(self.ui, 'exporting', i, total=total)
             ctx = self.repo.changectx(rev)
@@ -372,6 +396,10 @@
             hgsha = hex(parent.node())
             git_sha = self.map_git_get(hgsha)
             if git_sha:
+                if git_sha not in self.git.object_store:
+                    raise hgutil.Abort(_('Parent SHA-1 not present in Git'
+                                         'repo: %s' % git_sha))
+
                 commit.parents.append(git_sha)
 
         commit.message = self.get_git_message(ctx)
@@ -380,6 +408,10 @@
             commit.encoding = extra['encoding']
 
         tree_sha = commit_tree(self.git.object_store, self.iterblobs(ctx))
+        if tree_sha not in self.git.object_store:
+            raise hgutil.Abort(_('Tree SHA-1 not present in Git repo: %s' %
+                tree_sha))
+
         commit.tree = tree_sha
 
         self.git.object_store.add_object(commit)
@@ -432,19 +464,17 @@
         >>> g('Typo in hgrc >but.hg-git@handles.it.gracefully>')
         'Typo in hgrc ?but.hg-git@handles.it.gracefully'
         """
-        return re.sub('[<>\n]', '?', name.lstrip('< ').rstrip('> '))
+        return RE_GIT_SANITIZE_AUTHOR.sub('?', name.lstrip('< ').rstrip('> '))
 
     def get_git_author(self, ctx):
         # hg authors might not have emails
         author = ctx.user()
 
         # see if a translation exists
-        if author in self.author_map:
-            author = self.author_map[author]
+        author = self.author_map.get(author, author)
 
         # check for git author pattern compliance
-        regex = re.compile('^(.*?) ?\<(.*?)(?:\>(.*))?$')
-        a = regex.match(author)
+        a = RE_GIT_AUTHOR.match(author)
 
         if a:
             name = self.get_valid_git_username_email(a.group(1))
@@ -521,7 +551,24 @@
         return message
 
     def iterblobs(self, ctx):
+        if '.hgsubstate' in ctx:
+            hgsub = util.OrderedDict()
+            if '.hgsub' in ctx:
+                hgsub = util.parse_hgsub(ctx['.hgsub'].data().splitlines())
+            hgsubstate = util.parse_hgsubstate(ctx['.hgsubstate'].data().splitlines())
+            for path, sha in hgsubstate.iteritems():
+                try:
+                    if path in hgsub and not hgsub[path].startswith('[git]'):
+                        # some other kind of a repository (e.g. [hg])
+                        # that keeps its state in .hgsubstate, shall ignore
+                        continue
+                    yield path, sha, S_IFGITLINK
+                except ValueError:
+                    pass
+
         for f in ctx:
+            if f == '.hgsubstate' or f == '.hgsub':
+                continue
             fctx = ctx[f]
             blobid = self.map_git_get(hex(fctx.filenode()))
 
@@ -641,6 +688,35 @@
         # get a list of the changed, added, removed files
         files = self.get_files_changed(commit)
 
+        # Handle gitlinks: collect
+        gitlinks = self.collect_gitlinks(commit.tree)
+        git_commit_tree = self.git[commit.tree]
+
+        # Analyze hgsubstate and build an updated version
+        # using SHAs from gitlinks
+        hgsubstate = None
+        if gitlinks:
+            hgsubstate = util.parse_hgsubstate(self.git_file_readlines(git_commit_tree, '.hgsubstate'))
+            for path, sha in gitlinks:
+                hgsubstate[path] = sha
+            # in case .hgsubstate wasn't among changed files
+            # force its inclusion
+            files['.hgsubstate'] = (False, 0100644, None)
+
+        # Analyze .hgsub and merge with .gitmodules
+        hgsub = None
+        gitmodules = self.parse_gitmodules(git_commit_tree)
+        if gitmodules or gitlinks:
+            hgsub = util.parse_hgsub(self.git_file_readlines(git_commit_tree, '.hgsub'))
+            for (sm_path, sm_url, sm_name) in gitmodules:
+                hgsub[sm_path] = '[git]' + sm_url
+            files['.hgsub'] = (False, 0100644, None)
+        elif commit.parents and '.gitmodules' in self.git[self.git[commit.parents[0]].tree]:
+            # no .gitmodules in this commit, however present in the parent
+            # mark its hg counterpart as deleted (assuming .hgsub is there
+            # due to the same import_git_commit process
+            files['.hgsub'] = (True, 0100644, None)
+
         date = (commit.author_time, -commit.author_timezone)
         text = strip_message
 
@@ -658,8 +734,7 @@
 
         # convert extra data back to the end
         if ' ext:' in commit.author:
-            regex = re.compile('^(.*?)\ ext:\((.*)\) <(.*)\>$')
-            m = regex.match(commit.author)
+            m = RE_GIT_AUTHOR_EXTRA.match(commit.author)
             if m:
                 name = m.group(1)
                 ex = urllib.unquote(m.group(2))
@@ -701,9 +776,17 @@
                 if delete:
                     raise IOError
 
-                data = self.git[sha].data
-                copied_path = hg_renames.get(f)
-                e = self.convert_git_int_mode(mode)
+                if not sha: # indicates there's no git counterpart
+                    e = ''
+                    copied_path = None
+                    if '.hgsubstate' == f:
+                        data = util.serialize_hgsubstate(hgsubstate)
+                    elif '.hgsub' == f:
+                        data = util.serialize_hgsub(hgsub)
+                else:
+                    data = self.git[sha].data
+                    copied_path = hg_renames.get(f)
+                    e = self.convert_git_int_mode(mode)
             else:
                 # it's a converged file
                 fc = context.filectx(self.repo, f, changeid=memctx.p1().rev())
@@ -795,7 +878,8 @@
 
         genpack = self.git.object_store.generate_pack_contents
         try:
-            self.ui.status(_("creating and sending data\n"))
+            self.ui.status(_("searching for changes\n"))
+            self.ui.note(_("creating and sending data\n"))
             new_refs = client.send_pack(path, changed, genpack)
             return old_refs, new_refs
         except (HangupException, GitProtocolError), e:
@@ -806,15 +890,17 @@
 
         #The remote repo is empty and the local one doesn't have bookmarks/tags
         if refs.keys()[0] == 'capabilities^{}':
-            del new_refs['capabilities^{}']
             if not self.local_heads():
-                tip = hex(self.repo.lookup('tip'))
-                try:
-                    commands.bookmark(self.ui, self.repo, 'master', tip, force=True)
-                except NameError:
-                    bookmarks.bookmark(self.ui, self.repo, 'master', tip, force=True)
-                bookmarks.setcurrent(self.repo, 'master')
-                new_refs['refs/heads/master'] = self.map_git_get(tip)
+                tip = self.repo.lookup('tip')
+                if tip != nullid:
+                    del new_refs['capabilities^{}']
+                    tip = hex(tip)
+                    try:
+                        commands.bookmark(self.ui, self.repo, 'master', tip, force=True)
+                    except NameError:
+                        bookmarks.bookmark(self.ui, self.repo, 'master', tip, force=True)
+                    bookmarks.setcurrent(self.repo, 'master')
+                    new_refs['refs/heads/master'] = self.map_git_get(tip)
 
         for rev in revs:
             ctx = self.repo[rev]
@@ -883,7 +969,7 @@
         return new_refs
 
 
-    def fetch_pack(self, remote_name, heads):
+    def fetch_pack(self, remote_name, heads=None):
         client, path = self.get_transport_and_path(remote_name)
         graphwalker = self.git.get_graph_walker()
         def determine_wants(refs):
@@ -1166,6 +1252,57 @@
 
         return files
 
+    def collect_gitlinks(self, tree_id):
+        """Walk the tree and collect all gitlink entries
+          :param tree_id: sha of the commit tree
+          :return: list of tuples (commit sha, full entry path)
+        """
+        queue = [(tree_id, '')]
+        gitlinks = []
+        while queue:
+            e, path = queue.pop(0)
+            o = self.git.object_store[e]
+            for (name, mode, sha) in o.iteritems():
+                if mode == S_IFGITLINK:
+                    gitlinks.append((posixpath.join(path, name), sha))
+                elif stat.S_ISDIR(mode):
+                    queue.append((sha, posixpath.join(path, name)))
+        return gitlinks
+
+    def parse_gitmodules(self, tree_obj):
+        """Parse .gitmodules from a git tree specified by tree_obj
+
+           :return: list of tuples (submodule path, url, name),
+           where name is quoted part of the section's name, or
+           empty list if nothing found
+        """
+        rv = []
+        try:
+            unused_mode,gitmodules_sha = tree_obj['.gitmodules']
+        except KeyError:
+            return rv
+        gitmodules_content = self.git[gitmodules_sha].data
+        fo = StringIO.StringIO(gitmodules_content)
+        tt = dul_config.ConfigFile.from_file(fo)
+        for section in tt.keys():
+            section_kind, section_name = section
+            if section_kind == 'submodule':
+                sm_path = tt.get(section, 'path')
+                sm_url  = tt.get(section, 'url')
+                rv.append((sm_path, sm_url, section_name))
+        return rv
+
+    def git_file_readlines(self, tree_obj, fname):
+        """Read content of a named entry from the git commit tree
+
+           :return: list of lines
+        """
+        if fname in tree_obj:
+            unused_mode, sha = tree_obj[fname]
+            content = self.git[sha].data
+            return content.splitlines()
+        return []
+
     def remote_name(self, remote):
         names = [name for name, path in self.paths if path == remote]
         if names:
@@ -1200,14 +1337,7 @@
         if not issubclass(client.get_ssh_vendor, _ssh.SSHVendor):
             client.get_ssh_vendor = _ssh.generate_ssh_vendor(self.ui)
 
-        # Test for git:// and git+ssh:// URI.
-        #  Support several URL forms, including separating the
-        #  host and path with either a / or : (sepr)
-        git_pattern = re.compile(
-            r'^(?P<scheme>git([+]ssh)?://)(?P<host>.*?)(:(?P<port>\d+))?'
-            r'(?P<sepr>[:/])(?P<path>.*)$'
-        )
-        git_match = git_pattern.match(uri)
+        git_match = RE_GIT_URI.match(uri)
         if git_match:
             res = git_match.groupdict()
             transport = client.SSHGitClient if 'ssh' in res['scheme'] else client.TCPGitClient
--- a/hggit/gitrepo.py
+++ b/hggit/gitrepo.py
@@ -1,3 +1,4 @@
+import os
 from mercurial import util
 try:
     from mercurial.error import RepoError
@@ -11,6 +12,10 @@
 
 from git_handler import GitHandler
 
+from overlay import overlayrepo
+
+from mercurial.node import bin
+
 class gitrepo(peerrepository):
     capabilities = ['lookup']
 
@@ -22,6 +27,13 @@
             raise util.Abort('Cannot create a git repository.')
         self.ui = ui
         self.path = path
+        self.localrepo = None
+        self.handler = None
+
+    def _initializehandler(self):
+        if self.handler is None and self.localrepo is not None:
+            self.handler = GitHandler(self.localrepo, self.localrepo.ui)
+        return self.handler
 
     def url(self):
         return self.path
@@ -38,6 +50,22 @@
         return []
 
     def listkeys(self, namespace):
+        if namespace == 'namespaces':
+            return {'bookmarks':''}
+        elif namespace == 'bookmarks':
+            handler = self._initializehandler()
+            if handler:
+                handler.export_commits()
+                refs = handler.fetch_pack(self.path)
+                reqrefs = refs
+                convertlist, commits = handler.getnewgitcommits(reqrefs)
+                newcommits = [bin(c) for c in commits]
+                b = overlayrepo(handler, newcommits, refs)
+                stripped_refs = dict([
+                    (ref[11:], b.node(refs[ref]))
+                        for ref in refs.keys()
+                            if ref.startswith('refs/heads/')])
+                return stripped_refs
         return {}
 
     def pushkey(self, namespace, key, old, new):
--- a/hggit/help/git.rst
+++ b/hggit/help/git.rst
@@ -14,12 +14,16 @@
   http://code.google.com/p/guava-libraries
   ssh://git@github.com:schacon/hg-git.git
   git://github.com/schacon/hg-git.git
+  ../hg-git (local file path)
 
-For protocols other than git://, it isn't clear whether these should be
-interpreted as Mercurial or Git URLs. Thus, to specify that a URL should
+For the HTTP, HTTPS, and SSH protocols, it isn't clear based solely on
+the URL whether the remote repository should be treated as a Mercurial
+repository or a Git repository.  Thus, to specify that a URL should
 use Git, prepend the URL with "git+". For example, an HTTPS URL would
 start with "git+https://". Also, note that Git doesn't require the
-specification of the protocol for SSH, but Mercurial does.
+specification of the protocol for SSH, but Mercurial does.  Hg-Git
+automatically detects whether file paths should be treated as Git repositories
+by their contents.
 
 If you are starting from an existing Hg repository, you have to set up a
 Git repository somewhere that you have push access to, add a path entry
@@ -72,11 +76,3 @@
 
 Revsets are accepted by several Mercurial commands for specifying revisions.
 See ``hg help revsets`` for details.
-
-Limitations
------------
-
-- Cloning/pushing/pulling local Git repositories is not supported (due to
-  lack of support in Dulwich)
-- The `hg incoming` and `hg outgoing` commands are not currently
-  supported.
\ No newline at end of file
--- a/hggit/overlay.py
+++ b/hggit/overlay.py
@@ -234,6 +234,12 @@
             return self.handler.repo[n]
         return overlaychangectx(self, n)
 
+    def node(self, n):
+        """Returns an Hg or Git hash for the specified Git hash"""
+        if bin(n) in self.revmap:
+            return n
+        return self.handler.map_hg_get(n)
+
     def nodebookmarks(self, n):
         return self.refmap.get(n, [])
 
--- a/hggit/util.py
+++ b/hggit/util.py
@@ -1,5 +1,37 @@
 """Compatability functions for old Mercurial versions."""
+try:
+    from collections import OrderedDict
+except ImportError:
+    from ordereddict import OrderedDict
 
 def progress(ui, *args, **kwargs):
     """Shim for progress on hg < 1.4. Remove when 1.3 is dropped."""
     getattr(ui, 'progress', lambda *x, **kw: None)(*args, **kwargs)
+
+def parse_hgsub(lines):
+    """Fills OrderedDict with hgsub file content passed as list of lines"""
+    rv = OrderedDict()
+    for l in lines:
+        ls = l.strip();
+        if not ls or ls[0] == '#': continue
+        name, value = l.split('=', 1)
+        rv[name.strip()] = value.strip()
+    return rv
+
+def serialize_hgsub(data):
+    """Produces a string from OrderedDict hgsub content"""
+    return ''.join(['%s = %s\n' % (n,v) for n,v in data.iteritems()])
+
+def parse_hgsubstate(lines):
+    """Fills OrderedDict with hgsubtate file content passed as list of lines"""
+    rv = OrderedDict()
+    for l in lines:
+        ls = l.strip();
+        if not ls or ls[0] == '#': continue
+        value, name = l.split(' ', 1)
+        rv[name.strip()] = value.strip()
+    return rv
+
+def serialize_hgsubstate(data):
+    """Produces a string from OrderedDict hgsubstate content"""
+    return ''.join(['%s %s\n' % (data[n], n) for n in sorted(data)])
--- a/setup.py
+++ b/setup.py
@@ -3,9 +3,15 @@
 except:
     from distutils.core import setup
 
+try:
+    from collections import OrderedDict
+    extra_req = []
+except ImportError:
+    extra_req = ['ordereddict>=1.1']
+
 setup(
     name='hg-git',
-    version='0.3.4',
+    version='0.4.0',
     author='Scott Chacon',
     maintainer='Augie Fackler',
     maintainer_email='durin42@gmail.com',
@@ -20,5 +26,5 @@
     license='GPLv2',
     packages=['hggit'],
     package_data={ 'hggit': ['help/git.rst'] },
-    install_requires=['dulwich>=0.8.0'],
+    install_requires=['dulwich>=0.8.6'] + extra_req,
 )
new file mode 100755
--- /dev/null
+++ b/tests/hghave
@@ -0,0 +1,77 @@
+#!/usr/bin/env python
+"""Test the running system for features availability. Exit with zero
+if all features are there, non-zero otherwise. If a feature name is
+prefixed with "no-", the absence of feature is tested.
+"""
+import optparse
+import sys
+import hghave
+
+checks = hghave.checks
+
+def list_features():
+    for name, feature in checks.iteritems():
+        desc = feature[1]
+        print name + ':', desc
+
+def test_features():
+    failed = 0
+    for name, feature in checks.iteritems():
+        check, _ = feature
+        try:
+            check()
+        except Exception, e:
+            print "feature %s failed:  %s" % (name, e)
+            failed += 1
+    return failed
+
+parser = optparse.OptionParser("%prog [options] [features]")
+parser.add_option("--test-features", action="store_true",
+                  help="test available features")
+parser.add_option("--list-features", action="store_true",
+                  help="list available features")
+parser.add_option("-q", "--quiet", action="store_true",
+                  help="check features silently")
+
+if __name__ == '__main__':
+    options, args = parser.parse_args()
+    if options.list_features:
+        list_features()
+        sys.exit(0)
+
+    if options.test_features:
+        sys.exit(test_features())
+
+    quiet = options.quiet
+
+    failures = 0
+
+    def error(msg):
+        global failures
+        if not quiet:
+            sys.stderr.write(msg + '\n')
+        failures += 1
+
+    for feature in args:
+        negate = feature.startswith('no-')
+        if negate:
+            feature = feature[3:]
+
+        if feature not in checks:
+            error('skipped: unknown feature: ' + feature)
+            continue
+
+        check, desc = checks[feature]
+        try:
+            available = check()
+        except Exception, e:
+            error('hghave check failed: ' + feature)
+            continue
+
+        if not negate and not available:
+            error('skipped: missing feature: ' + desc)
+        elif negate and available:
+            error('skipped: system supports %s' % desc)
+
+    if failures != 0:
+        sys.exit(1)
new file mode 100755
--- /dev/null
+++ b/tests/hghave.py
@@ -0,0 +1,308 @@
+import os, stat, socket
+import re
+import sys
+import tempfile
+
+tempprefix = 'hg-hghave-'
+
+def matchoutput(cmd, regexp, ignorestatus=False):
+    """Return True if cmd executes successfully and its output
+    is matched by the supplied regular expression.
+    """
+    r = re.compile(regexp)
+    fh = os.popen(cmd)
+    s = fh.read()
+    try:
+        ret = fh.close()
+    except IOError:
+        # Happen in Windows test environment
+        ret = 1
+    return (ignorestatus or ret is None) and r.search(s)
+
+def has_baz():
+    return matchoutput('baz --version 2>&1', r'baz Bazaar version')
+
+def has_bzr():
+    try:
+        import bzrlib
+        return bzrlib.__doc__ is not None
+    except ImportError:
+        return False
+
+def has_bzr114():
+    try:
+        import bzrlib
+        return (bzrlib.__doc__ is not None
+                and bzrlib.version_info[:2] >= (1, 14))
+    except ImportError:
+        return False
+
+def has_cvs():
+    re = r'Concurrent Versions System.*?server'
+    return matchoutput('cvs --version 2>&1', re) and not has_msys()
+
+def has_darcs():
+    return matchoutput('darcs --version', r'2\.[2-9]', True)
+
+def has_mtn():
+    return matchoutput('mtn --version', r'monotone', True) and not matchoutput(
+        'mtn --version', r'monotone 0\.', True)
+
+def has_eol_in_paths():
+    try:
+        fd, path = tempfile.mkstemp(dir='.', prefix=tempprefix, suffix='\n\r')
+        os.close(fd)
+        os.remove(path)
+        return True
+    except (IOError, OSError):
+        return False
+
+def has_executablebit():
+    try:
+        EXECFLAGS = stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
+        fh, fn = tempfile.mkstemp(dir='.', prefix=tempprefix)
+        try:
+            os.close(fh)
+            m = os.stat(fn).st_mode & 0777
+            new_file_has_exec = m & EXECFLAGS
+            os.chmod(fn, m ^ EXECFLAGS)
+            exec_flags_cannot_flip = ((os.stat(fn).st_mode & 0777) == m)
+        finally:
+            os.unlink(fn)
+    except (IOError, OSError):
+        # we don't care, the user probably won't be able to commit anyway
+        return False
+    return not (new_file_has_exec or exec_flags_cannot_flip)
+
+def has_icasefs():
+    # Stolen from mercurial.util
+    fd, path = tempfile.mkstemp(dir='.', prefix=tempprefix)
+    os.close(fd)
+    try:
+        s1 = os.stat(path)
+        d, b = os.path.split(path)
+        p2 = os.path.join(d, b.upper())
+        if path == p2:
+            p2 = os.path.join(d, b.lower())
+        try:
+            s2 = os.stat(p2)
+            return s2 == s1
+        except OSError:
+            return False
+    finally:
+        os.remove(path)
+
+def has_inotify():
+    try:
+        import hgext.inotify.linux.watcher
+    except ImportError:
+        return False
+    name = tempfile.mktemp(dir='.', prefix=tempprefix)
+    sock = socket.socket(socket.AF_UNIX)
+    try:
+        sock.bind(name)
+    except socket.error, err:
+        return False
+    sock.close()
+    os.unlink(name)
+    return True
+
+def has_fifo():
+    if getattr(os, "mkfifo", None) is None:
+        return False
+    name = tempfile.mktemp(dir='.', prefix=tempprefix)
+    try:
+        os.mkfifo(name)
+        os.unlink(name)
+        return True
+    except OSError:
+        return False
+
+def has_cacheable_fs():
+    from mercurial import util
+
+    fd, path = tempfile.mkstemp(dir='.', prefix=tempprefix)
+    os.close(fd)
+    try:
+        return util.cachestat(path).cacheable()
+    finally:
+        os.remove(path)
+
+def has_lsprof():
+    try:
+        import _lsprof
+        return True
+    except ImportError:
+        return False
+
+def has_gettext():
+    return matchoutput('msgfmt --version', 'GNU gettext-tools')
+
+def has_git():
+    return matchoutput('git --version 2>&1', r'^git version')
+
+def has_docutils():
+    try:
+        from docutils.core import publish_cmdline
+        return True
+    except ImportError:
+        return False
+
+def getsvnversion():
+    m = matchoutput('svn --version 2>&1', r'^svn,\s+version\s+(\d+)\.(\d+)')
+    if not m:
+        return (0, 0)
+    return (int(m.group(1)), int(m.group(2)))
+
+def has_svn15():
+    return getsvnversion() >= (1, 5)
+
+def has_svn13():
+    return getsvnversion() >= (1, 3)
+
+def has_svn():
+    return matchoutput('svn --version 2>&1', r'^svn, version') and \
+        matchoutput('svnadmin --version 2>&1', r'^svnadmin, version')
+
+def has_svn_bindings():
+    try:
+        import svn.core
+        version = svn.core.SVN_VER_MAJOR, svn.core.SVN_VER_MINOR
+        if version < (1, 4):
+            return False
+        return True
+    except ImportError:
+        return False
+
+def has_p4():
+    return (matchoutput('p4 -V', r'Rev\. P4/') and
+            matchoutput('p4d -V', r'Rev\. P4D/'))
+
+def has_symlink():
+    if getattr(os, "symlink", None) is None:
+        return False
+    name = tempfile.mktemp(dir='.', prefix=tempprefix)
+    try:
+        os.symlink(".", name)
+        os.unlink(name)
+        return True
+    except (OSError, AttributeError):
+        return False
+
+def has_hardlink():
+    from mercurial import util
+    fh, fn = tempfile.mkstemp(dir='.', prefix=tempprefix)
+    os.close(fh)
+    name = tempfile.mktemp(dir='.', prefix=tempprefix)
+    try:
+        try:
+            util.oslink(fn, name)
+            os.unlink(name)
+            return True
+        except OSError:
+            return False
+    finally:
+        os.unlink(fn)
+
+def has_tla():
+    return matchoutput('tla --version 2>&1', r'The GNU Arch Revision')
+
+def has_gpg():
+    return matchoutput('gpg --version 2>&1', r'GnuPG')
+
+def has_unix_permissions():
+    d = tempfile.mkdtemp(dir='.', prefix=tempprefix)
+    try:
+        fname = os.path.join(d, 'foo')
+        for umask in (077, 007, 022):
+            os.umask(umask)
+            f = open(fname, 'w')
+            f.close()
+            mode = os.stat(fname).st_mode
+            os.unlink(fname)
+            if mode & 0777 != ~umask & 0666:
+                return False
+        return True
+    finally:
+        os.rmdir(d)
+
+def has_pyflakes():
+    return matchoutput("sh -c \"echo 'import re' 2>&1 | pyflakes\"",
+                       r"<stdin>:1: 're' imported but unused",
+                       True)
+
+def has_pygments():
+    try:
+        import pygments
+        return True
+    except ImportError:
+        return False
+
+def has_outer_repo():
+    # failing for other reasons than 'no repo' imply that there is a repo
+    return not matchoutput('hg root 2>&1',
+                           r'abort: no repository found', True)
+
+def has_ssl():
+    try:
+        import ssl
+        import OpenSSL
+        OpenSSL.SSL.Context
+        return True
+    except ImportError:
+        return False
+
+def has_windows():
+    return os.name == 'nt'
+
+def has_system_sh():
+    return os.name != 'nt'
+
+def has_serve():
+    return os.name != 'nt' # gross approximation
+
+def has_tic():
+    return matchoutput('test -x "`which tic`"', '')
+
+def has_msys():
+    return os.getenv('MSYSTEM')
+
+checks = {
+    "true": (lambda: True, "yak shaving"),
+    "false": (lambda: False, "nail clipper"),
+    "baz": (has_baz, "GNU Arch baz client"),
+    "bzr": (has_bzr, "Canonical's Bazaar client"),
+    "bzr114": (has_bzr114, "Canonical's Bazaar client >= 1.14"),
+    "cacheable": (has_cacheable_fs, "cacheable filesystem"),
+    "cvs": (has_cvs, "cvs client/server"),
+    "darcs": (has_darcs, "darcs client"),
+    "docutils": (has_docutils, "Docutils text processing library"),
+    "eol-in-paths": (has_eol_in_paths, "end-of-lines in paths"),
+    "execbit": (has_executablebit, "executable bit"),
+    "fifo": (has_fifo, "named pipes"),
+    "gettext": (has_gettext, "GNU Gettext (msgfmt)"),
+    "git": (has_git, "git command line client"),
+    "gpg": (has_gpg, "gpg client"),
+    "hardlink": (has_hardlink, "hardlinks"),
+    "icasefs": (has_icasefs, "case insensitive file system"),
+    "inotify": (has_inotify, "inotify extension support"),
+    "lsprof": (has_lsprof, "python lsprof module"),
+    "mtn": (has_mtn, "monotone client (>= 1.0)"),
+    "outer-repo": (has_outer_repo, "outer repo"),
+    "p4": (has_p4, "Perforce server and client"),
+    "pyflakes": (has_pyflakes, "Pyflakes python linter"),
+    "pygments": (has_pygments, "Pygments source highlighting library"),
+    "serve": (has_serve, "platform and python can manage 'hg serve -d'"),
+    "ssl": (has_ssl, "python >= 2.6 ssl module and python OpenSSL"),
+    "svn": (has_svn, "subversion client and admin tools"),
+    "svn13": (has_svn13, "subversion client and admin tools >= 1.3"),
+    "svn15": (has_svn15, "subversion client and admin tools >= 1.5"),
+    "svn-bindings": (has_svn_bindings, "subversion python bindings"),
+    "symlink": (has_symlink, "symbolic links"),
+    "system-sh": (has_system_sh, "system() uses sh"),
+    "tic": (has_tic, "terminfo compiler"),
+    "tla": (has_tla, "GNU Arch tla client"),
+    "unix-permissions": (has_unix_permissions, "unix-style permissions"),
+    "windows": (has_windows, "Windows"),
+    "msys": (has_msys, "Windows with MSYS"),
+}
--- a/tests/latin-1-encoding
+++ b/tests/latin-1-encoding
@@ -5,14 +5,14 @@
 GIT_AUTHOR_NAME='tést èncödîng'; export GIT_AUTHOR_NAME
 echo beta > beta
 git add beta
-commit -m 'add beta'
+fn_git_commit -m 'add beta'
 
 echo gamma > gamma
 git add gamma
-commit -m 'add gämmâ'
+fn_git_commit -m 'add gämmâ'
 
 # test the commit encoding field
 git config i18n.commitencoding latin-1
 echo delta > delta
 git add delta
-commit -m 'add déltà'
+fn_git_commit -m 'add déltà'
old mode 100644
new mode 100755
--- a/tests/run-tests.py
+++ b/tests/run-tests.py
@@ -5,39 +5,92 @@
 # Copyright 2006 Matt Mackall <mpm@selenic.com>
 #
 # This software may be used and distributed according to the terms of the
-# GNU General Public License version 2, incorporated herein by reference.
+# GNU General Public License version 2 or any later version.
 
+# Modifying this script is tricky because it has many modes:
+#   - serial (default) vs parallel (-jN, N > 1)
+#   - no coverage (default) vs coverage (-c, -C, -s)
+#   - temp install (default) vs specific hg script (--with-hg, --local)
+#   - tests are a mix of shell scripts and Python scripts
+#
+# If you change this script, it is recommended that you ensure you
+# haven't broken it by running it in various modes with a representative
+# sample of test scripts.  For example:
+#
+#  1) serial, no coverage, temp install:
+#      ./run-tests.py test-s*
+#  2) serial, no coverage, local hg:
+#      ./run-tests.py --local test-s*
+#  3) serial, coverage, temp install:
+#      ./run-tests.py -c test-s*
+#  4) serial, coverage, local hg:
+#      ./run-tests.py -c --local test-s*      # unsupported
+#  5) parallel, no coverage, temp install:
+#      ./run-tests.py -j2 test-s*
+#  6) parallel, no coverage, local hg:
+#      ./run-tests.py -j2 --local test-s*
+#  7) parallel, coverage, temp install:
+#      ./run-tests.py -j2 -c test-s*          # currently broken
+#  8) parallel, coverage, local install:
+#      ./run-tests.py -j2 -c --local test-s*  # unsupported (and broken)
+#  9) parallel, custom tmp dir:
+#      ./run-tests.py -j2 --tmpdir /tmp/myhgtests
+#
+# (You could use any subset of the tests: test-s* happens to match
+# enough that it's worth doing parallel runs, few enough that it
+# completes fairly quickly, includes both shell and Python scripts, and
+# includes some scripts that run daemon processes.)
+
+from distutils import version
 import difflib
 import errno
 import optparse
 import os
-try:
-    import subprocess
-    subprocess.Popen  # trigger ImportError early
-    closefds = os.name == 'posix'
-    def Popen4(cmd, bufsize=-1):
-        p = subprocess.Popen(cmd, shell=True, bufsize=bufsize,
-                             close_fds=closefds,
-                             stdin=subprocess.PIPE, stdout=subprocess.PIPE,
-                             stderr=subprocess.STDOUT)
-        p.fromchild = p.stdout
-        p.tochild = p.stdin
-        p.childerr = p.stderr
-        return p
-except ImportError:
-    subprocess = None
-    from popen2 import Popen4
 import shutil
+import subprocess
 import signal
 import sys
 import tempfile
 import time
+import re
+import threading
+
+processlock = threading.Lock()
+
+closefds = os.name == 'posix'
+def Popen4(cmd, wd, timeout):
+    processlock.acquire()
+    p = subprocess.Popen(cmd, shell=True, bufsize=-1, cwd=wd,
+                         close_fds=closefds,
+                         stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+                         stderr=subprocess.STDOUT)
+    processlock.release()
+
+    p.fromchild = p.stdout
+    p.tochild = p.stdin
+    p.childerr = p.stderr
+
+    p.timeout = False
+    if timeout:
+        def t():
+            start = time.time()
+            while time.time() - start < timeout and p.returncode is None:
+                time.sleep(.1)
+            p.timeout = True
+            if p.returncode is None:
+                terminate(p)
+        threading.Thread(target=t).start()
+
+    return p
 
 # reserved exit code to skip test (used by hghave)
 SKIPPED_STATUS = 80
 SKIPPED_PREFIX = 'skipped: '
 FAILED_PREFIX  = 'hghave check failed: '
-PYTHON = sys.executable
+PYTHON = sys.executable.replace('\\', '/')
+IMPL_PATH = 'PYTHONPATH'
+if 'java' in sys.platform:
+    IMPL_PATH = 'JYTHONPATH'
 
 requiredtools = ["python", "diff", "grep", "unzip", "gunzip", "bunzip2", "sed"]
 
@@ -45,73 +98,180 @@
     'jobs': ('HGTEST_JOBS', 1),
     'timeout': ('HGTEST_TIMEOUT', 180),
     'port': ('HGTEST_PORT', 20059),
+    'shell': ('HGTEST_SHELL', 'sh'),
 }
 
+def parselistfiles(files, listtype, warn=True):
+    entries = dict()
+    for filename in files:
+        try:
+            path = os.path.expanduser(os.path.expandvars(filename))
+            f = open(path, "r")
+        except IOError, err:
+            if err.errno != errno.ENOENT:
+                raise
+            if warn:
+                print "warning: no such %s file: %s" % (listtype, filename)
+            continue
+
+        for line in f.readlines():
+            line = line.split('#', 1)[0].strip()
+            if line:
+                entries[line] = filename
+
+        f.close()
+    return entries
+
 def parseargs():
     parser = optparse.OptionParser("%prog [options] [tests]")
+
+    # keep these sorted
+    parser.add_option("--blacklist", action="append",
+        help="skip tests listed in the specified blacklist file")
+    parser.add_option("--whitelist", action="append",
+        help="always run tests listed in the specified whitelist file")
     parser.add_option("-C", "--annotate", action="store_true",
         help="output files annotated with coverage")
     parser.add_option("--child", type="int",
         help="run as child process, summary to given fd")
     parser.add_option("-c", "--cover", action="store_true",
         help="print a test coverage report")
+    parser.add_option("-d", "--debug", action="store_true",
+        help="debug mode: write output of test scripts to console"
+             " rather than capturing and diff'ing it (disables timeout)")
     parser.add_option("-f", "--first", action="store_true",
         help="exit on the first test failure")
+    parser.add_option("-H", "--htmlcov", action="store_true",
+        help="create an HTML report of the coverage of the files")
+    parser.add_option("--inotify", action="store_true",
+        help="enable inotify extension when running tests")
     parser.add_option("-i", "--interactive", action="store_true",
         help="prompt to accept changed output")
     parser.add_option("-j", "--jobs", type="int",
         help="number of jobs to run in parallel"
              " (default: $%s or %d)" % defaults['jobs'])
     parser.add_option("--keep-tmpdir", action="store_true",
-        help="keep temporary directory after running tests"
-             " (best used with --tmpdir)")
-    parser.add_option("-R", "--restart", action="store_true",
-        help="restart at last error")
+        help="keep temporary directory after running tests")
+    parser.add_option("-k", "--keywords",
+        help="run tests matching keywords")
+    parser.add_option("-l", "--local", action="store_true",
+        help="shortcut for --with-hg=<testdir>/../hg")
+    parser.add_option("-n", "--nodiff", action="store_true",
+        help="skip showing test changes")
     parser.add_option("-p", "--port", type="int",
         help="port on which servers should listen"
              " (default: $%s or %d)" % defaults['port'])
+    parser.add_option("--pure", action="store_true",
+        help="use pure Python code instead of C extensions")
+    parser.add_option("-R", "--restart", action="store_true",
+        help="restart at last error")
     parser.add_option("-r", "--retest", action="store_true",
         help="retest failed tests")
-    parser.add_option("-s", "--cover_stdlib", action="store_true",
-        help="print a test coverage report inc. standard libraries")
+    parser.add_option("-S", "--noskips", action="store_true",
+        help="don't report skip tests verbosely")
+    parser.add_option("--shell", type="string",
+        help="shell to use (default: $%s or %s)" % defaults['shell'])
     parser.add_option("-t", "--timeout", type="int",
         help="kill errant tests after TIMEOUT seconds"
              " (default: $%s or %d)" % defaults['timeout'])
     parser.add_option("--tmpdir", type="string",
-        help="run tests in the given temporary directory")
+        help="run tests in the given temporary directory"
+             " (implies --keep-tmpdir)")
     parser.add_option("-v", "--verbose", action="store_true",
         help="output verbose messages")
-    parser.add_option("-n", "--nodiff", action="store_true",
-        help="skip showing test changes")
+    parser.add_option("--view", type="string",
+        help="external diff viewer")
     parser.add_option("--with-hg", type="string",
-        help="test existing install at given location")
-    parser.add_option("--pure", action="store_true",
-        help="use pure Python code instead of C extensions")
+        metavar="HG",
+        help="test using specified hg script rather than a "
+             "temporary installation")
+    parser.add_option("-3", "--py3k-warnings", action="store_true",
+        help="enable Py3k warnings on Python 2.6+")
+    parser.add_option('--extra-config-opt', action="append",
+                      help='set the given config opt in the test hgrc')
 
-    for option, default in defaults.items():
-        defaults[option] = int(os.environ.get(*default))
+    for option, (envvar, default) in defaults.items():
+        defaults[option] = type(default)(os.environ.get(envvar, default))
     parser.set_defaults(**defaults)
     (options, args) = parser.parse_args()
 
+    # jython is always pure
+    if 'java' in sys.platform or '__pypy__' in sys.modules:
+        options.pure = True
+
+    if options.with_hg:
+        options.with_hg = os.path.expanduser(options.with_hg)
+        if not (os.path.isfile(options.with_hg) and
+                os.access(options.with_hg, os.X_OK)):
+            parser.error('--with-hg must specify an executable hg script')
+        if not os.path.basename(options.with_hg) == 'hg':
+            sys.stderr.write('warning: --with-hg should specify an hg script\n')
+    if options.local:
+        testdir = os.path.dirname(os.path.realpath(sys.argv[0]))
+        hgbin = os.path.join(os.path.dirname(testdir), 'hg')
+        if os.name != 'nt' and not os.access(hgbin, os.X_OK):
+            parser.error('--local specified, but %r not found or not executable'
+                         % hgbin)
+        options.with_hg = hgbin
+
+    options.anycoverage = options.cover or options.annotate or options.htmlcov
+    if options.anycoverage:
+        try:
+            import coverage
+            covver = version.StrictVersion(coverage.__version__).version
+            if covver < (3, 3):
+                parser.error('coverage options require coverage 3.3 or later')
+        except ImportError:
+            parser.error('coverage options now require the coverage package')
+
+    if options.anycoverage and options.local:
+        # this needs some path mangling somewhere, I guess
+        parser.error("sorry, coverage options do not work when --local "
+                     "is specified")
+
     global vlog
-    options.anycoverage = (options.cover or
-                           options.cover_stdlib or
-                           options.annotate)
-
     if options.verbose:
+        if options.jobs > 1 or options.child is not None:
+            pid = "[%d]" % os.getpid()
+        else:
+            pid = None
         def vlog(*msg):
+            iolock.acquire()
+            if pid:
+                print pid,
             for m in msg:
                 print m,
             print
+            sys.stdout.flush()
+            iolock.release()
     else:
         vlog = lambda *msg: None
 
+    if options.tmpdir:
+        options.tmpdir = os.path.expanduser(options.tmpdir)
+
     if options.jobs < 1:
-        print >> sys.stderr, 'ERROR: -j/--jobs must be positive'
-        sys.exit(1)
+        parser.error('--jobs must be positive')
     if options.interactive and options.jobs > 1:
         print '(--interactive overrides --jobs)'
         options.jobs = 1
+    if options.interactive and options.debug:
+        parser.error("-i/--interactive and -d/--debug are incompatible")
+    if options.debug:
+        if options.timeout != defaults['timeout']:
+            sys.stderr.write(
+                'warning: --timeout option ignored with --debug\n')
+        options.timeout = 0
+    if options.py3k_warnings:
+        if sys.version_info[:2] < (2, 6) or sys.version_info[:2] >= (3, 0):
+            parser.error('--py3k-warnings can only be used on Python 2.6+')
+    if options.blacklist:
+        options.blacklist = parselistfiles(options.blacklist, 'blacklist')
+    if options.whitelist:
+        options.whitelisted = parselistfiles(options.whitelist, 'whitelist',
+                                             warn=options.child is None)
+    else:
+        options.whitelisted = {}
 
     return (options, args)
 
@@ -134,7 +294,7 @@
             if last:
                 lines.append(last)
             return lines
-        lines.append(text[i:n+1])
+        lines.append(text[i:n + 1])
         i = n + 1
 
 def parsehghaveoutput(lines):
@@ -154,16 +314,16 @@
 
     return missing, failed
 
-def showdiff(expected, output):
-    for line in difflib.unified_diff(expected, output,
-            "Expected output", "Test output"):
+def showdiff(expected, output, ref, err):
+    print
+    for line in difflib.unified_diff(expected, output, ref, err):
         sys.stdout.write(line)
 
 def findprogram(program):
     """Search PATH for a executable program"""
     for p in os.environ.get('PATH', os.defpath).split(os.pathsep):
         name = os.path.join(p, program)
-        if os.access(name, os.X_OK):
+        if os.name == 'nt' or os.access(name, os.X_OK):
             return name
     return None
 
@@ -179,22 +339,56 @@
         else:
             print "WARNING: Did not find prerequisite tool: "+p
 
+def terminate(proc):
+    """Terminate subprocess (with fallback for Python versions < 2.6)"""
+    vlog('# Terminating process %d' % proc.pid)
+    try:
+        getattr(proc, 'terminate', lambda : os.kill(proc.pid, signal.SIGTERM))()
+    except OSError:
+        pass
+
+def killdaemons():
+    # Kill off any leftover daemon processes
+    try:
+        fp = open(DAEMON_PIDS)
+        for line in fp:
+            try:
+                pid = int(line)
+            except ValueError:
+                continue
+            try:
+                os.kill(pid, 0)
+                vlog('# Killing daemon process %d' % pid)
+                os.kill(pid, signal.SIGTERM)
+                time.sleep(0.1)
+                os.kill(pid, 0)
+                vlog('# Daemon process %d is stuck - really killing it' % pid)
+                os.kill(pid, signal.SIGKILL)
+            except OSError, err:
+                if err.errno != errno.ESRCH:
+                    raise
+        fp.close()
+        os.unlink(DAEMON_PIDS)
+    except IOError:
+        pass
+
 def cleanup(options):
     if not options.keep_tmpdir:
-        if options.verbose:
-            print "# Cleaning up HGTMP", HGTMP
+        vlog("# Cleaning up HGTMP", HGTMP)
         shutil.rmtree(HGTMP, True)
 
 def usecorrectpython():
     # some tests run python interpreter. they must use same
     # interpreter we use or bad things will happen.
     exedir, exename = os.path.split(sys.executable)
-    if exename == 'python':
-        path = findprogram('python')
+    if exename in ('python', 'python.exe'):
+        path = findprogram(exename)
         if os.path.dirname(path) == exedir:
             return
+    else:
+        exename = 'python'
     vlog('# Making python executable in test path use correct Python')
-    mypython = os.path.join(BINDIR, 'python')
+    mypython = os.path.join(BINDIR, exename)
     try:
         os.symlink(sys.executable, mypython)
     except AttributeError:
@@ -203,17 +397,27 @@
         shutil.copymode(sys.executable, mypython)
 
 def installhg(options):
-    global PYTHON
     vlog("# Performing temporary installation of HG")
     installerrs = os.path.join("tests", "install.err")
     pure = options.pure and "--pure" or ""
 
     # Run installer in hg root
-    os.chdir(os.path.join(os.path.dirname(sys.argv[0]), '..'))
+    script = os.path.realpath(sys.argv[0])
+    hgroot = os.path.dirname(os.path.dirname(script))
+    os.chdir(hgroot)
+    nohome = '--home=""'
+    if os.name == 'nt':
+        # The --home="" trick works only on OS where os.sep == '/'
+        # because of a distutils convert_path() fast-path. Avoid it at
+        # least on Windows for now, deal with .pydistutils.cfg bugs
+        # when they happen.
+        nohome = ''
     cmd = ('%s setup.py %s clean --all'
+           ' build --build-base="%s"'
            ' install --force --prefix="%s" --install-lib="%s"'
-           ' --install-scripts="%s" >%s 2>&1'
-           % (sys.executable, pure, INST, PYTHONDIR, BINDIR, installerrs))
+           ' --install-scripts="%s" %s >%s 2>&1'
+           % (sys.executable, pure, os.path.join(HGTMP, "build"),
+              INST, PYTHONDIR, BINDIR, nohome, installerrs))
     vlog("# Running", cmd)
     if os.system(cmd) == 0:
         if not options.verbose:
@@ -226,19 +430,7 @@
         sys.exit(1)
     os.chdir(TESTDIR)
 
-    os.environ["PATH"] = "%s%s%s" % (BINDIR, os.pathsep, os.environ["PATH"])
-
-    pydir = os.pathsep.join([PYTHONDIR, TESTDIR])
-    pythonpath = os.environ.get("PYTHONPATH")
-    if pythonpath:
-        pythonpath = pydir + os.pathsep + pythonpath
-    else:
-        pythonpath = pydir
-    os.environ["PYTHONPATH"] = pythonpath
-
     usecorrectpython()
-    global hgpkg
-    hgpkg = _hgpath()
 
     vlog("# Installing dummy diffstat")
     f = open(os.path.join(BINDIR, 'diffstat'), 'w')
@@ -252,260 +444,629 @@
     f.close()
     os.chmod(os.path.join(BINDIR, 'diffstat'), 0700)
 
-    if options.anycoverage:
-        vlog("# Installing coverage wrapper")
-        os.environ['COVERAGE_FILE'] = COVERAGE_FILE
-        if os.path.exists(COVERAGE_FILE):
-            os.unlink(COVERAGE_FILE)
-        # Create a wrapper script to invoke hg via coverage.py
-        os.rename(os.path.join(BINDIR, "hg"), os.path.join(BINDIR, "_hg.py"))
+    if options.py3k_warnings and not options.anycoverage:
+        vlog("# Updating hg command to enable Py3k Warnings switch")
+        f = open(os.path.join(BINDIR, 'hg'), 'r')
+        lines = [line.rstrip() for line in f]
+        lines[0] += ' -3'
+        f.close()
         f = open(os.path.join(BINDIR, 'hg'), 'w')
-        f.write('#!' + sys.executable + '\n')
-        f.write('import sys, os; os.execv(sys.executable, [sys.executable, '
-                '"%s", "-x", "%s"] + sys.argv[1:])\n' %
-                (os.path.join(TESTDIR, 'coverage.py'),
-                 os.path.join(BINDIR, '_hg.py')))
+        for line in lines:
+            f.write(line + '\n')
+        f.close()
+
+    hgbat = os.path.join(BINDIR, 'hg.bat')
+    if os.path.isfile(hgbat):
+        # hg.bat expects to be put in bin/scripts while run-tests.py
+        # installation layout put it in bin/ directly. Fix it
+        f = open(hgbat, 'rb')
+        data = f.read()
         f.close()
-        os.chmod(os.path.join(BINDIR, 'hg'), 0700)
-        PYTHON = '"%s" "%s" -x' % (sys.executable,
-                                   os.path.join(TESTDIR,'coverage.py'))
+        if '"%~dp0..\python" "%~dp0hg" %*' in data:
+            data = data.replace('"%~dp0..\python" "%~dp0hg" %*',
+                                '"%~dp0python" "%~dp0hg" %*')
+            f = open(hgbat, 'wb')
+            f.write(data)
+            f.close()
+        else:
+            print 'WARNING: cannot fix hg.bat reference to python.exe'
 
-def _hgpath():
-    cmd = '%s -c "import mercurial; print mercurial.__path__[0]"'
-    hgpath = os.popen(cmd % PYTHON)
-    path = hgpath.read().strip()
-    hgpath.close()
-    return path
+    if options.anycoverage:
+        custom = os.path.join(TESTDIR, 'sitecustomize.py')
+        target = os.path.join(PYTHONDIR, 'sitecustomize.py')
+        vlog('# Installing coverage trigger to %s' % target)
+        shutil.copyfile(custom, target)
+        rc = os.path.join(TESTDIR, '.coveragerc')
+        vlog('# Installing coverage rc to %s' % rc)
+        os.environ['COVERAGE_PROCESS_START'] = rc
+        fn = os.path.join(INST, '..', '.coverage')
+        os.environ['COVERAGE_FILE'] = fn
 
 def outputcoverage(options):
-    vlog("# Producing coverage report")
-    omit = [BINDIR, TESTDIR, PYTHONDIR]
-    if not options.cover_stdlib:
-        # Exclude as system paths (ignoring empty strings seen on win)
-        omit += [x for x in sys.path if x != '']
-    omit = ','.join(omit)
+
+    vlog('# Producing coverage report')
     os.chdir(PYTHONDIR)
-    cmd = '"%s" "%s" -i -r "--omit=%s"' % (
-        sys.executable, os.path.join(TESTDIR, 'coverage.py'), omit)
-    vlog("# Running: "+cmd)
-    os.system(cmd)
+
+    def covrun(*args):
+        cmd = 'coverage %s' % ' '.join(args)
+        vlog('# Running: %s' % cmd)
+        os.system(cmd)
+
+    if options.child:
+        return
+
+    covrun('-c')
+    omit = ','.join(os.path.join(x, '*') for x in [BINDIR, TESTDIR])
+    covrun('-i', '-r', '"--omit=%s"' % omit) # report
+    if options.htmlcov:
+        htmldir = os.path.join(TESTDIR, 'htmlcov')
+        covrun('-i', '-b', '"--directory=%s"' % htmldir, '"--omit=%s"' % omit)
     if options.annotate:
         adir = os.path.join(TESTDIR, 'annotated')
         if not os.path.isdir(adir):
             os.mkdir(adir)
-        cmd = '"%s" "%s" -i -a "--directory=%s" "--omit=%s"' % (
-            sys.executable, os.path.join(TESTDIR, 'coverage.py'),
-            adir, omit)
-        vlog("# Running: "+cmd)
-        os.system(cmd)
+        covrun('-i', '-a', '"--directory=%s"' % adir, '"--omit=%s"' % omit)
+
+def pytest(test, wd, options, replacements):
+    py3kswitch = options.py3k_warnings and ' -3' or ''
+    cmd = '%s%s "%s"' % (PYTHON, py3kswitch, test)
+    vlog("# Running", cmd)
+    return run(cmd, wd, options, replacements)
+
+def shtest(test, wd, options, replacements):
+    cmd = '%s "%s"' % (options.shell, test)
+    vlog("# Running", cmd)
+    return run(cmd, wd, options, replacements)
+
+needescape = re.compile(r'[\x00-\x08\x0b-\x1f\x7f-\xff]').search
+escapesub = re.compile(r'[\x00-\x08\x0b-\x1f\\\x7f-\xff]').sub
+escapemap = dict((chr(i), r'\x%02x' % i) for i in range(256))
+escapemap.update({'\\': '\\\\', '\r': r'\r'})
+def escapef(m):
+    return escapemap[m.group(0)]
+def stringescape(s):
+    return escapesub(escapef, s)
+
+def rematch(el, l):
+    try:
+        # ensure that the regex matches to the end of the string
+        return re.match(el + r'\Z', l)
+    except re.error:
+        # el is an invalid regex
+        return False
+
+def globmatch(el, l):
+    # The only supported special characters are * and ? plus / which also
+    # matches \ on windows. Escaping of these caracters is supported.
+    i, n = 0, len(el)
+    res = ''
+    while i < n:
+        c = el[i]
+        i += 1
+        if c == '\\' and el[i] in '*?\\/':
+            res += el[i - 1:i + 1]
+            i += 1
+        elif c == '*':
+            res += '.*'
+        elif c == '?':
+            res += '.'
+        elif c == '/' and os.name == 'nt':
+            res += '[/\\\\]'
+        else:
+            res += re.escape(c)
+    return rematch(res, l)
+
+def linematch(el, l):
+    if el == l: # perfect match (fast)
+        return True
+    if (el and
+        (el.endswith(" (re)\n") and rematch(el[:-6] + '\n', l) or
+         el.endswith(" (glob)\n") and globmatch(el[:-8] + '\n', l) or
+         el.endswith(" (esc)\n") and
+             (el[:-7].decode('string-escape') + '\n' == l or
+              el[:-7].decode('string-escape').replace('\r', '') +
+                  '\n' == l and os.name == 'nt'))):
+        return True
+    return False
+
+def tsttest(test, wd, options, replacements):
+    # We generate a shell script which outputs unique markers to line
+    # up script results with our source. These markers include input
+    # line number and the last return code
+    salt = "SALT" + str(time.time())
+    def addsalt(line, inpython):
+        if inpython:
+            script.append('%s %d 0\n' % (salt, line))
+        else:
+            script.append('echo %s %s $?\n' % (salt, line))
+
+    # After we run the shell script, we re-unify the script output
+    # with non-active parts of the source, with synchronization by our
+    # SALT line number markers. The after table contains the
+    # non-active components, ordered by line number
+    after = {}
+    pos = prepos = -1
+
+    # Expected shellscript output
+    expected = {}
+
+    # We keep track of whether or not we're in a Python block so we
+    # can generate the surrounding doctest magic
+    inpython = False
+
+    # True or False when in a true or false conditional section
+    skipping = None
+
+    def hghave(reqs):
+        # TODO: do something smarter when all other uses of hghave is gone
+        tdir = TESTDIR.replace('\\', '/')
+        proc = Popen4('%s -c "%s/hghave %s"' %
+                      (options.shell, tdir, ' '.join(reqs)), wd, 0)
+        proc.communicate()
+        ret = proc.wait()
+        if wifexited(ret):
+            ret = os.WEXITSTATUS(ret)
+        return ret == 0
+
+    f = open(test)
+    t = f.readlines()
+    f.close()
 
-class Timeout(Exception):
-    pass
+    script = []
+    if options.debug:
+        script.append('set -x\n')
+    if os.getenv('MSYSTEM'):
+        script.append('alias pwd="pwd -W"\n')
+    for n, l in enumerate(t):
+        if not l.endswith('\n'):
+            l += '\n'
+        if l.startswith('#if'):
+            if skipping is not None:
+                after.setdefault(pos, []).append('  !!! nested #if\n')
+            skipping = not hghave(l.split()[1:])
+            after.setdefault(pos, []).append(l)
+        elif l.startswith('#else'):
+            if skipping is None:
+                after.setdefault(pos, []).append('  !!! missing #if\n')
+            skipping = not skipping
+            after.setdefault(pos, []).append(l)
+        elif l.startswith('#endif'):
+            if skipping is None:
+                after.setdefault(pos, []).append('  !!! missing #if\n')
+            skipping = None
+            after.setdefault(pos, []).append(l)
+        elif skipping:
+            after.setdefault(pos, []).append(l)
+        elif l.startswith('  >>> '): # python inlines
+            after.setdefault(pos, []).append(l)
+            prepos = pos
+            pos = n
+            if not inpython:
+                # we've just entered a Python block, add the header
+                inpython = True
+                addsalt(prepos, False) # make sure we report the exit code
+                script.append('%s -m heredoctest <<EOF\n' % PYTHON)
+            addsalt(n, True)
+            script.append(l[2:])
+        elif l.startswith('  ... '): # python inlines
+            after.setdefault(prepos, []).append(l)
+            script.append(l[2:])
+        elif l.startswith('  $ '): # commands
+            if inpython:
+                script.append("EOF\n")
+                inpython = False
+            after.setdefault(pos, []).append(l)
+            prepos = pos
+            pos = n
+            addsalt(n, False)
+            cmd = l[4:].split()
+            if len(cmd) == 2 and cmd[0] == 'cd':
+                l = '  $ cd %s || exit 1\n' % cmd[1]
+            script.append(l[4:])
+        elif l.startswith('  > '): # continuations
+            after.setdefault(prepos, []).append(l)
+            script.append(l[4:])
+        elif l.startswith('  '): # results
+            # queue up a list of expected results
+            expected.setdefault(pos, []).append(l[2:])
+        else:
+            if inpython:
+                script.append("EOF\n")
+                inpython = False
+            # non-command/result - queue up for merged output
+            after.setdefault(pos, []).append(l)
 
-def alarmed(signum, frame):
-    raise Timeout
+    if inpython:
+        script.append("EOF\n")
+    if skipping is not None:
+        after.setdefault(pos, []).append('  !!! missing #endif\n')
+    addsalt(n + 1, False)
+
+    # Write out the script and execute it
+    fd, name = tempfile.mkstemp(suffix='hg-tst')
+    try:
+        for l in script:
+            os.write(fd, l)
+        os.close(fd)
+
+        cmd = '%s "%s"' % (options.shell, name)
+        vlog("# Running", cmd)
+        exitcode, output = run(cmd, wd, options, replacements)
+        # do not merge output if skipped, return hghave message instead
+        # similarly, with --debug, output is None
+        if exitcode == SKIPPED_STATUS or output is None:
+            return exitcode, output
+    finally:
+        os.remove(name)
+
+    # Merge the script output back into a unified test
+
+    pos = -1
+    postout = []
+    ret = 0
+    for n, l in enumerate(output):
+        lout, lcmd = l, None
+        if salt in l:
+            lout, lcmd = l.split(salt, 1)
 
-def run(cmd, options):
+        if lout:
+            if lcmd:
+                # output block had no trailing newline, clean up
+                lout += ' (no-eol)\n'
+
+            # find the expected output at the current position
+            el = None
+            if pos in expected and expected[pos]:
+                el = expected[pos].pop(0)
+
+            if linematch(el, lout):
+                postout.append("  " + el)
+            else:
+                if needescape(lout):
+                    lout = stringescape(lout.rstrip('\n')) + " (esc)\n"
+                postout.append("  " + lout) # let diff deal with it
+
+        if lcmd:
+            # add on last return code
+            ret = int(lcmd.split()[1])
+            if ret != 0:
+                postout.append("  [%s]\n" % ret)
+            if pos in after:
+                # merge in non-active test bits
+                postout += after.pop(pos)
+            pos = int(lcmd.split()[0])
+
+    if pos in after:
+        postout += after.pop(pos)
+
+    return exitcode, postout
+
+wifexited = getattr(os, "WIFEXITED", lambda x: False)
+def run(cmd, wd, options, replacements):
     """Run command in a sub-process, capturing the output (stdout and stderr).
-    Return the exist code, and output."""
+    Return a tuple (exitcode, output).  output is None in debug mode."""
     # TODO: Use subprocess.Popen if we're running on Python 2.4
-    if os.name == 'nt' or sys.platform.startswith('java'):
-        tochild, fromchild = os.popen4(cmd)
-        tochild.close()
-        output = fromchild.read()
-        ret = fromchild.close()
-        if ret == None:
-            ret = 0
-    else:
-        proc = Popen4(cmd)
-        try:
-            output = ''
-            proc.tochild.close()
-            output = proc.fromchild.read()
-            ret = proc.wait()
-            if os.WIFEXITED(ret):
-                ret = os.WEXITSTATUS(ret)
-        except Timeout:
-            vlog('# Process %d timed out - killing it' % proc.pid)
-            os.kill(proc.pid, signal.SIGTERM)
-            ret = proc.wait()
-            if ret == 0:
-                ret = signal.SIGTERM << 8
-            output += ("\n### Abort: timeout after %d seconds.\n"
-                       % options.timeout)
+    if options.debug:
+        proc = subprocess.Popen(cmd, shell=True, cwd=wd)
+        ret = proc.wait()
+        return (ret, None)
+
+    proc = Popen4(cmd, wd, options.timeout)
+    def cleanup():
+        terminate(proc)
+        ret = proc.wait()
+        if ret == 0:
+            ret = signal.SIGTERM << 8
+        killdaemons()
+        return ret
+
+    output = ''
+    proc.tochild.close()
+
+    try:
+        output = proc.fromchild.read()
+    except KeyboardInterrupt:
+        vlog('# Handling keyboard interrupt')
+        cleanup()
+        raise
+
+    ret = proc.wait()
+    if wifexited(ret):
+        ret = os.WEXITSTATUS(ret)
+
+    if proc.timeout:
+        ret = 'timeout'
+
+    if ret:
+        killdaemons()
+
+    for s, r in replacements:
+        output = re.sub(s, r, output)
     return ret, splitnewlines(output)
 
-def runone(options, test, skips, fails):
+def runone(options, test):
     '''tristate output:
     None -> skipped
     True -> passed
     False -> failed'''
 
+    global results, resultslock, iolock
+
+    testpath = os.path.join(TESTDIR, test)
+
+    def result(l, e):
+        resultslock.acquire()
+        results[l].append(e)
+        resultslock.release()
+
     def skip(msg):
         if not options.verbose:
-            skips.append((test, msg))
+            result('s', (test, msg))
         else:
-            print "\nSkipping %s: %s" % (test, msg)
+            iolock.acquire()
+            print "\nSkipping %s: %s" % (testpath, msg)
+            iolock.release()
         return None
 
-    def fail(msg):
-        fails.append((test, msg))
+    def fail(msg, ret):
         if not options.nodiff:
-            print "\nERROR: %s %s" % (test, msg)
-        return None
+            iolock.acquire()
+            print "\nERROR: %s %s" % (testpath, msg)
+            iolock.release()
+        if (not ret and options.interactive
+            and os.path.exists(testpath + ".err")):
+            iolock.acquire()
+            print "Accept this change? [n] ",
+            answer = sys.stdin.readline().strip()
+            iolock.release()
+            if answer.lower() in "y yes".split():
+                if test.endswith(".t"):
+                    rename(testpath + ".err", testpath)
+                else:
+                    rename(testpath + ".err", testpath + ".out")
+                result('p', test)
+                return
+        result('f', (test, msg))
+
+    def success():
+        result('p', test)
+
+    def ignore(msg):
+        result('i', (test, msg))
+
+    if (os.path.basename(test).startswith("test-") and '~' not in test and
+        ('.' not in test or test.endswith('.py') or
+         test.endswith('.bat') or test.endswith('.t'))):
+        if not os.path.exists(test):
+            skip("doesn't exist")
+            return None
+    else:
+        vlog('# Test file', test, 'not supported, ignoring')
+        return None # not a supported test, don't record
+
+    if not (options.whitelisted and test in options.whitelisted):
+        if options.blacklist and test in options.blacklist:
+            skip("blacklisted")
+            return None
+
+        if options.retest and not os.path.exists(test + ".err"):
+            ignore("not retesting")
+            return None
+
+        if options.keywords:
+            fp = open(test)
+            t = fp.read().lower() + test.lower()
+            fp.close()
+            for k in options.keywords.lower().split():
+                if k in t:
+                    break
+                else:
+                    ignore("doesn't match keyword")
+                    return None
 
     vlog("# Test", test)
 
     # create a fresh hgrc
-    hgrc = file(HGRCPATH, 'w+')
+    hgrc = open(HGRCPATH, 'w+')
     hgrc.write('[ui]\n')
     hgrc.write('slash = True\n')
     hgrc.write('[defaults]\n')
     hgrc.write('backout = -d "0 0"\n')
     hgrc.write('commit = -d "0 0"\n')
-    hgrc.write('debugrawcommit = -d "0 0"\n')
     hgrc.write('tag = -d "0 0"\n')
+    if options.inotify:
+        hgrc.write('[extensions]\n')
+        hgrc.write('inotify=\n')
+        hgrc.write('[inotify]\n')
+        hgrc.write('pidfile=%s\n' % DAEMON_PIDS)
+        hgrc.write('appendpid=True\n')
+    if options.extra_config_opt:
+        for opt in options.extra_config_opt:
+            section, key = opt.split('.', 1)
+            assert '=' in key, ('extra config opt %s must '
+                                'have an = for assignment' % opt)
+            hgrc.write('[%s]\n%s\n' % (section, key))
     hgrc.close()
 
+    ref = os.path.join(TESTDIR, test+".out")
     err = os.path.join(TESTDIR, test+".err")
-    ref = os.path.join(TESTDIR, test+".out")
-    testpath = os.path.join(TESTDIR, test)
-
     if os.path.exists(err):
         os.remove(err)       # Remove any previous output files
-
-    # Make a tmp subdirectory to work in
-    tmpd = os.path.join(HGTMP, test)
-    os.mkdir(tmpd)
-    os.chdir(tmpd)
-
     try:
         tf = open(testpath)
         firstline = tf.readline().rstrip()
         tf.close()
-    except:
+    except IOError:
         firstline = ''
     lctest = test.lower()
 
     if lctest.endswith('.py') or firstline == '#!/usr/bin/env python':
-        cmd = '%s "%s"' % (PYTHON, testpath)
-    elif lctest.endswith('.bat'):
-        # do not run batch scripts on non-windows
-        if os.name != 'nt':
-            return skip("batch script")
-        # To reliably get the error code from batch files on WinXP,
-        # the "cmd /c call" prefix is needed. Grrr
-        cmd = 'cmd /c call "%s"' % testpath
+        runner = pytest
+    elif lctest.endswith('.t'):
+        runner = tsttest
+        ref = testpath
     else:
-        # do not run shell scripts on windows
-        if os.name == 'nt':
-            return skip("shell script")
         # do not try to run non-executable programs
-        if not os.path.exists(testpath):
-            return fail("does not exist")
-        elif not os.access(testpath, os.X_OK):
+        if not os.access(testpath, os.X_OK):
             return skip("not executable")
-        cmd = '"%s"' % testpath
+        runner = shtest
+
+    # Make a tmp subdirectory to work in
+    testtmp = os.environ["TESTTMP"] = os.environ["HOME"] = \
+        os.path.join(HGTMP, os.path.basename(test))
 
-    if options.timeout > 0:
-        signal.alarm(options.timeout)
+    replacements = [
+        (r':%s\b' % options.port, ':$HGPORT'),
+        (r':%s\b' % (options.port + 1), ':$HGPORT1'),
+        (r':%s\b' % (options.port + 2), ':$HGPORT2'),
+        ]
+    if os.name == 'nt':
+        replacements.append((r'\r\n', '\n'))
+        replacements.append(
+            (''.join(c.isalpha() and '[%s%s]' % (c.lower(), c.upper()) or
+                     c in '/\\' and r'[/\\]' or
+                     c.isdigit() and c or
+                     '\\' + c
+                     for c in testtmp), '$TESTTMP'))
+    else:
+        replacements.append((re.escape(testtmp), '$TESTTMP'))
 
-    vlog("# Running", cmd)
-    ret, out = run(cmd, options)
+    os.mkdir(testtmp)
+    ret, out = runner(testpath, testtmp, options, replacements)
     vlog("# Ret was:", ret)
 
-    if options.timeout > 0:
-        signal.alarm(0)
-
     mark = '.'
 
     skipped = (ret == SKIPPED_STATUS)
-    # If reference output file exists, check test output against it
-    if os.path.exists(ref):
+
+    # If we're not in --debug mode and reference output file exists,
+    # check test output against it.
+    if options.debug:
+        refout = None                   # to match "out is None"
+    elif os.path.exists(ref):
         f = open(ref, "r")
-        refout = splitnewlines(f.read())
+        refout = list(splitnewlines(f.read()))
         f.close()
     else:
         refout = []
-    if skipped:
-        mark = 's'
-        missing, failed = parsehghaveoutput(out)
-        if not missing:
-            missing = ['irrelevant']
-        if failed:
-            fail("hghave failed checking for %s" % failed[-1])
-            skipped = False
-        else:
-            skip(missing[-1])
-    elif out != refout:
-        mark = '!'
-        if ret:
-            fail("output changed and returned error code %d" % ret)
-        else:
-            fail("output changed")
-        if not options.nodiff:
-            showdiff(refout, out)
-        ret = 1
-    elif ret:
-        mark = '!'
-        fail("returned error code %d" % ret)
 
-    if not options.verbose:
-        sys.stdout.write(mark)
-        sys.stdout.flush()
-
-    if ret != 0 and not skipped:
+    if (ret != 0 or out != refout) and not skipped and not options.debug:
         # Save errors to a file for diagnosis
         f = open(err, "wb")
         for line in out:
             f.write(line)
         f.close()
 
-    # Kill off any leftover daemon processes
-    try:
-        fp = file(DAEMON_PIDS)
-        for line in fp:
-            try:
-                pid = int(line)
-            except ValueError:
-                continue
-            try:
-                os.kill(pid, 0)
-                vlog('# Killing daemon process %d' % pid)
-                os.kill(pid, signal.SIGTERM)
-                time.sleep(0.25)
-                os.kill(pid, 0)
-                vlog('# Daemon process %d is stuck - really killing it' % pid)
-                os.kill(pid, signal.SIGKILL)
-            except OSError, err:
-                if err.errno != errno.ESRCH:
-                    raise
-        fp.close()
-        os.unlink(DAEMON_PIDS)
-    except IOError:
-        pass
+    if skipped:
+        mark = 's'
+        if out is None:                 # debug mode: nothing to parse
+            missing = ['unknown']
+            failed = None
+        else:
+            missing, failed = parsehghaveoutput(out)
+        if not missing:
+            missing = ['irrelevant']
+        if failed:
+            fail("hghave failed checking for %s" % failed[-1], ret)
+            skipped = False
+        else:
+            skip(missing[-1])
+    elif ret == 'timeout':
+        mark = 't'
+        fail("timed out", ret)
+    elif out != refout:
+        mark = '!'
+        if not options.nodiff:
+            iolock.acquire()
+            if options.view:
+                os.system("%s %s %s" % (options.view, ref, err))
+            else:
+                showdiff(refout, out, ref, err)
+            iolock.release()
+        if ret:
+            fail("output changed and returned error code %d" % ret, ret)
+        else:
+            fail("output changed", ret)
+        ret = 1
+    elif ret:
+        mark = '!'
+        fail("returned error code %d" % ret, ret)
+    else:
+        success()
 
-    os.chdir(TESTDIR)
+    if not options.verbose:
+        iolock.acquire()
+        sys.stdout.write(mark)
+        sys.stdout.flush()
+        iolock.release()
+
+    killdaemons()
+
     if not options.keep_tmpdir:
-        shutil.rmtree(tmpd, True)
+        shutil.rmtree(testtmp, True)
     if skipped:
         return None
     return ret == 0
 
-def runchildren(options, expecthg, tests):
-    if not options.with_hg:
+_hgpath = None
+
+def _gethgpath():
+    """Return the path to the mercurial package that is actually found by
+    the current Python interpreter."""
+    global _hgpath
+    if _hgpath is not None:
+        return _hgpath
+
+    cmd = '%s -c "import mercurial; print mercurial.__path__[0]"'
+    pipe = os.popen(cmd % PYTHON)
+    try:
+        _hgpath = pipe.read().strip()
+    finally:
+        pipe.close()
+    return _hgpath
+
+def _checkhglib(verb):
+    """Ensure that the 'mercurial' package imported by python is
+    the one we expect it to be.  If not, print a warning to stderr."""
+    expecthg = os.path.join(PYTHONDIR, 'mercurial')
+    actualhg = _gethgpath()
+    if os.path.abspath(actualhg) != os.path.abspath(expecthg):
+        sys.stderr.write('warning: %s with unexpected mercurial lib: %s\n'
+                         '         (expected %s)\n'
+                         % (verb, actualhg, expecthg))
+
+def runchildren(options, tests):
+    if INST:
         installhg(options)
-        if hgpkg != expecthg:
-            print '# Testing unexpected mercurial: %s' % hgpkg
+        _checkhglib("Testing")
 
     optcopy = dict(options.__dict__)
     optcopy['jobs'] = 1
-    optcopy['with_hg'] = INST
+
+    # Because whitelist has to override keyword matches, we have to
+    # actually load the whitelist in the children as well, so we allow
+    # the list of whitelist files to pass through and be parsed in the
+    # children, but not the dict of whitelisted tests resulting from
+    # the parse, used here to override blacklisted tests.
+    whitelist = optcopy['whitelisted'] or []
+    del optcopy['whitelisted']
+
+    blacklist = optcopy['blacklist'] or []
+    del optcopy['blacklist']
+    blacklisted = []
+
+    if optcopy['with_hg'] is None:
+        optcopy['with_hg'] = os.path.join(BINDIR, "hg")
+    optcopy.pop('anycoverage', None)
+
     opts = []
     for opt, value in optcopy.iteritems():
         name = '--' + opt.replace('_', '-')
         if value is True:
             opts.append(name)
+        elif isinstance(value, list):
+            for v in value:
+                opts.append(name + '=' + str(v))
         elif value is not None:
             opts.append(name + '=' + str(value))
 
@@ -513,18 +1074,27 @@
     jobs = [[] for j in xrange(options.jobs)]
     while tests:
         for job in jobs:
-            if not tests: break
-            job.append(tests.pop())
+            if not tests:
+                break
+            test = tests.pop()
+            if test not in whitelist and test in blacklist:
+                blacklisted.append(test)
+            else:
+                job.append(test)
     fps = {}
+
     for j, job in enumerate(jobs):
         if not job:
             continue
         rfd, wfd = os.pipe()
         childopts = ['--child=%d' % wfd, '--port=%d' % (options.port + j * 3)]
+        childtmp = os.path.join(HGTMP, 'child%d' % j)
+        childopts += ['--tmpdir', childtmp]
         cmdline = [PYTHON, sys.argv[0]] + opts + childopts + job
         vlog(' '.join(cmdline))
         fps[os.spawnvp(os.P_NOWAIT, cmdline[0], cmdline)] = os.fdopen(rfd, 'r')
         os.close(wfd)
+    signal.signal(signal.SIGINT, signal.SIG_IGN)
     failures = 0
     tested, skipped, failed = 0, 0, 0
     skips = []
@@ -533,7 +1103,10 @@
         pid, status = os.wait()
         fp = fps.pop(pid)
         l = fp.read().splitlines()
-        test, skip, fail = map(int, l[:3])
+        try:
+            test, skip, fail = map(int, l[:3])
+        except ValueError:
+            test, skip, fail = 0, 0, 0
         split = -fail or len(l)
         for s in l[3:split]:
             skips.append(s.split(" ", 1))
@@ -545,41 +1118,42 @@
         vlog('pid %d exited, status %d' % (pid, status))
         failures |= status
     print
-    for s in skips:
-        print "Skipped %s: %s" % (s[0], s[1])
+    skipped += len(blacklisted)
+    if not options.noskips:
+        for s in skips:
+            print "Skipped %s: %s" % (s[0], s[1])
+        for s in blacklisted:
+            print "Skipped %s: blacklisted" % s
     for s in fails:
         print "Failed %s: %s" % (s[0], s[1])
 
-    if hgpkg != expecthg:
-        print '# Tested unexpected mercurial: %s' % hgpkg
+    _checkhglib("Tested")
     print "# Ran %d tests, %d skipped, %d failed." % (
         tested, skipped, failed)
+
+    if options.anycoverage:
+        outputcoverage(options)
     sys.exit(failures != 0)
 
-def runtests(options, expecthg, tests):
+results = dict(p=[], f=[], s=[], i=[])
+resultslock = threading.Lock()
+iolock = threading.Lock()
+
+def runqueue(options, tests, results):
+    for test in tests:
+        ret = runone(options, test)
+        if options.first and ret is not None and not ret:
+            break
+
+def runtests(options, tests):
     global DAEMON_PIDS, HGRCPATH
     DAEMON_PIDS = os.environ["DAEMON_PIDS"] = os.path.join(HGTMP, 'daemon.pids')
     HGRCPATH = os.environ["HGRCPATH"] = os.path.join(HGTMP, '.hgrc')
 
     try:
-        if not options.with_hg:
+        if INST:
             installhg(options)
-
-            if hgpkg != expecthg:
-                print '# Testing unexpected mercurial: %s' % hgpkg
-
-        if options.timeout > 0:
-            try:
-                signal.signal(signal.SIGALRM, alarmed)
-                vlog('# Running tests with %d-second timeout' %
-                     options.timeout)
-            except AttributeError:
-                print 'WARNING: cannot run tests with timeouts'
-                options.timeout = 0
-
-        tested = 0
-        failed = 0
-        skipped = 0
+            _checkhglib("Testing")
 
         if options.restart:
             orig = list(tests)
@@ -591,47 +1165,30 @@
                 print "running all tests"
                 tests = orig
 
-        skips = []
-        fails = []
-        for test in tests:
-            if options.retest and not os.path.exists(test + ".err"):
-                skipped += 1
-                continue
-            ret = runone(options, test, skips, fails)
-            if ret is None:
-                skipped += 1
-            elif not ret:
-                if options.interactive:
-                    print "Accept this change? [n] ",
-                    answer = sys.stdin.readline().strip()
-                    if answer.lower() in "y yes".split():
-                        rename(test + ".err", test + ".out")
-                        tested += 1
-                        fails.pop()
-                        continue
-                failed += 1
-                if options.first:
-                    break
-            tested += 1
+        runqueue(options, tests, results)
+
+        failed = len(results['f'])
+        tested = len(results['p']) + failed
+        skipped = len(results['s'])
+        ignored = len(results['i'])
 
         if options.child:
             fp = os.fdopen(options.child, 'w')
             fp.write('%d\n%d\n%d\n' % (tested, skipped, failed))
-            for s in skips:
+            for s in results['s']:
                 fp.write("%s %s\n" % s)
-            for s in fails:
+            for s in results['f']:
                 fp.write("%s %s\n" % s)
             fp.close()
         else:
             print
-            for s in skips:
+            for s in results['s']:
                 print "Skipped %s: %s" % s
-            for s in fails:
+            for s in results['f']:
                 print "Failed %s: %s" % s
-            if hgpkg != expecthg:
-                print '# Tested unexpected mercurial: %s' % hgpkg
+            _checkhglib("Tested")
             print "# Ran %d tests, %d skipped, %d failed." % (
-                tested, skipped, failed)
+                tested, skipped + ignored, failed)
 
         if options.anycoverage:
             outputcoverage(options)
@@ -642,7 +1199,6 @@
     if failed:
         sys.exit(1)
 
-hgpkg = None
 def main():
     (options, args) = parseargs()
     if not options.child:
@@ -650,17 +1206,57 @@
 
         checktools()
 
+    if len(args) == 0:
+        args = os.listdir(".")
+    args.sort()
+
+    tests = args
+
     # Reset some environment variables to well-known values so that
     # the tests produce repeatable output.
-    os.environ['LANG'] = os.environ['LC_ALL'] = 'C'
+    os.environ['LANG'] = os.environ['LC_ALL'] = os.environ['LANGUAGE'] = 'C'
     os.environ['TZ'] = 'GMT'
     os.environ["EMAIL"] = "Foo Bar <foo.bar@example.com>"
     os.environ['CDPATH'] = ''
+    os.environ['COLUMNS'] = '80'
+    os.environ['GREP_OPTIONS'] = ''
+    os.environ['http_proxy'] = ''
+    os.environ['no_proxy'] = ''
+    os.environ['NO_PROXY'] = ''
+    os.environ['TERM'] = 'xterm'
+
+    # unset env related to hooks
+    for k in os.environ.keys():
+        if k.startswith('HG_'):
+            # can't remove on solaris
+            os.environ[k] = ''
+            del os.environ[k]
 
     global TESTDIR, HGTMP, INST, BINDIR, PYTHONDIR, COVERAGE_FILE
     TESTDIR = os.environ["TESTDIR"] = os.getcwd()
-    HGTMP = os.environ['HGTMP'] = os.path.realpath(tempfile.mkdtemp('', 'hgtests.',
-                                                   options.tmpdir))
+    if options.tmpdir:
+        options.keep_tmpdir = True
+        tmpdir = options.tmpdir
+        if os.path.exists(tmpdir):
+            # Meaning of tmpdir has changed since 1.3: we used to create
+            # HGTMP inside tmpdir; now HGTMP is tmpdir.  So fail if
+            # tmpdir already exists.
+            sys.exit("error: temp dir %r already exists" % tmpdir)
+
+            # Automatically removing tmpdir sounds convenient, but could
+            # really annoy anyone in the habit of using "--tmpdir=/tmp"
+            # or "--tmpdir=$HOME".
+            #vlog("# Removing temp dir", tmpdir)
+            #shutil.rmtree(tmpdir)
+        os.makedirs(tmpdir)
+    else:
+        d = None
+        if os.name == 'nt':
+            # without this, we get the default temp dir location, but
+            # in all lowercase, which causes troubles with paths (issue3490)
+            d = os.getenv('TMP')
+        tmpdir = tempfile.mkdtemp('', 'hgtests.', d)
+    HGTMP = os.environ['HGTMP'] = os.path.realpath(tmpdir)
     DAEMON_PIDS = None
     HGRCPATH = None
 
@@ -674,35 +1270,55 @@
     os.environ["HGPORT2"] = str(options.port + 2)
 
     if options.with_hg:
-        INST = options.with_hg
+        INST = None
+        BINDIR = os.path.dirname(os.path.realpath(options.with_hg))
+
+        # This looks redundant with how Python initializes sys.path from
+        # the location of the script being executed.  Needed because the
+        # "hg" specified by --with-hg is not the only Python script
+        # executed in the test suite that needs to import 'mercurial'
+        # ... which means it's not really redundant at all.
+        PYTHONDIR = BINDIR
     else:
         INST = os.path.join(HGTMP, "install")
-    BINDIR = os.environ["BINDIR"] = os.path.join(INST, "bin")
-    PYTHONDIR = os.path.join(INST, "lib", "python")
-    COVERAGE_FILE = os.path.join(TESTDIR, ".coverage")
+        BINDIR = os.environ["BINDIR"] = os.path.join(INST, "bin")
+        PYTHONDIR = os.path.join(INST, "lib", "python")
 
-    expecthg = os.path.join(HGTMP, 'install', 'lib', 'python', 'mercurial')
+    os.environ["BINDIR"] = BINDIR
+    os.environ["PYTHON"] = PYTHON
+
+    if not options.child:
+        path = [BINDIR] + os.environ["PATH"].split(os.pathsep)
+        os.environ["PATH"] = os.pathsep.join(path)
 
-    if len(args) == 0:
-        args = os.listdir(".")
-        args.sort()
+        # Include TESTDIR in PYTHONPATH so that out-of-tree extensions
+        # can run .../tests/run-tests.py test-foo where test-foo
+        # adds an extension to HGRC
+        pypath = [PYTHONDIR, TESTDIR]
+        # We have to augment PYTHONPATH, rather than simply replacing
+        # it, in case external libraries are only available via current
+        # PYTHONPATH.  (In particular, the Subversion bindings on OS X
+        # are in /opt/subversion.)
+        oldpypath = os.environ.get(IMPL_PATH)
+        if oldpypath:
+            pypath.append(oldpypath)
+        os.environ[IMPL_PATH] = os.pathsep.join(pypath)
 
-    tests = []
-    for test in args:
-        if (test.startswith("test-") and '~' not in test and
-            ('.' not in test or test.endswith('.py') or
-             test.endswith('.bat'))):
-            tests.append(test)
+    COVERAGE_FILE = os.path.join(TESTDIR, ".coverage")
 
     vlog("# Using TESTDIR", TESTDIR)
     vlog("# Using HGTMP", HGTMP)
+    vlog("# Using PATH", os.environ["PATH"])
+    vlog("# Using", IMPL_PATH, os.environ[IMPL_PATH])
 
     try:
         if len(tests) > 1 and options.jobs > 1:
-            runchildren(options, expecthg, tests)
+            runchildren(options, tests)
         else:
-            runtests(options, expecthg, tests)
+            runtests(options, tests)
     finally:
+        time.sleep(.1)
         cleanup(options)
 
-main()
+if __name__ == '__main__':
+    main()
new file mode 100644
--- /dev/null
+++ b/tests/test-bookmark-workflow.t
@@ -0,0 +1,168 @@
+This test demonstrates how Hg works with remote Hg bookmarks compared with
+remote branches via Hg-Git.  Ideally, they would behave identically.  In
+practice, some differences are unavoidable, but we should try to minimize
+them.
+
+This test should not bother testing the behavior of bookmark creation,
+deletion, activation, deactivation, etc.  These behaviors, while important to
+the end user, don't vary at all when Hg-Git is in use.  Only the synchonization
+of bookmarks should be considered "under test", and mutation of bookmarks
+locally is only to provide a test fixture.
+
+Load commonly used test logic
+  $ . "$TESTDIR/testutil"
+
+Skip if Mercurial < 2.1; workflow was different before that
+  $ python -c 'from mercurial import util ; assert \
+  >  util.version() != "unknown" and util.version() >= "2.1"' || exit 80
+
+  $ gitcount=10
+  $ gitcommit()
+  > {
+  >     GIT_AUTHOR_DATE="2007-01-01 00:00:$gitcount +0000"
+  >     GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"
+  >     git commit "$@" >/dev/null 2>/dev/null || echo "git commit error"
+  >     gitcount=`expr $gitcount + 1`
+  > }
+  $ hgcount=10
+  $ hgcommit()
+  > {
+  >     HGDATE="2007-01-01 00:00:$hgcount +0000"
+  >     hg commit -u "test <test@example.org>" -d "$HGDATE" "$@" >/dev/null 2>/dev/null || echo "hg commit error"
+  >     hgcount=`expr $hgcount + 1`
+  > }
+  $ gitstate()
+  > {
+  >     git log --format="  %h \"%s\" refs:%d" $@ | sed 's/HEAD, //'
+  > }
+  $ hgstate()
+  > {
+  >     hg log --template "  {rev} {node|short} \"{desc}\" bookmarks: [{bookmarks}]\n" $@
+  > }
+  $ hggitstate()
+  > {
+  >     hg log --template "  {rev} {node|short} {gitnode|short} \"{desc}\" bookmarks: [{bookmarks}]\n" $@
+  > }
+
+Initialize remote hg and git repos with equivalent initial contents
+  $ hg init hgremoterepo
+  $ cd hgremoterepo
+  $ hg bookmark master
+  $ for f in alpha beta gamma delta; do
+  >     echo $f > $f; hg add $f; hgcommit -m "add $f"
+  > done
+  $ hg bookmark -r 1 b1
+  $ hgstate
+    3 fc2664cac217 "add delta" bookmarks: [master]
+    2 d85ced7ae9d6 "add gamma" bookmarks: []
+    1 7bcd915dc873 "add beta" bookmarks: [b1]
+    0 3442585be8a6 "add alpha" bookmarks: []
+  $ cd ..
+  $ git init -q gitremoterepo
+  $ cd gitremoterepo
+  $ for f in alpha beta gamma delta; do
+  >     echo $f > $f; git add $f; gitcommit -m "add $f"
+  > done
+  $ git branch b1 9497a4e
+  $ gitstate
+    55b133e "add delta" refs: (master)
+    d338971 "add gamma" refs:
+    9497a4e "add beta" refs: (b1)
+    7eeab2e "add alpha" refs:
+  $ cd ..
+
+Cloning transfers all bookmarks from remote to local
+  $ hg clone -q hgremoterepo purehglocalrepo
+  $ cd purehglocalrepo
+  $ hgstate
+    3 fc2664cac217 "add delta" bookmarks: [master]
+    2 d85ced7ae9d6 "add gamma" bookmarks: []
+    1 7bcd915dc873 "add beta" bookmarks: [b1]
+    0 3442585be8a6 "add alpha" bookmarks: []
+  $ cd ..
+  $ hg clone -q gitremoterepo hggitlocalrepo
+  $ cd hggitlocalrepo
+  $ hggitstate
+    3 fc2664cac217 55b133e1d558 "add delta" bookmarks: [master]
+    2 d85ced7ae9d6 d338971a96e2 "add gamma" bookmarks: []
+    1 7bcd915dc873 9497a4ee62e1 "add beta" bookmarks: [b1]
+    0 3442585be8a6 7eeab2ea75ec "add alpha" bookmarks: []
+  $ cd ..
+
+No changes
+  $ cd purehglocalrepo
+  $ hg outgoing
+  comparing with $TESTTMP/hgremoterepo
+  searching for changes
+  no changes found
+  [1]
+  $ hg outgoing -B
+  comparing with $TESTTMP/hgremoterepo
+  searching for changed bookmarks
+  no changed bookmarks found
+  [1]
+  $ hg push
+  pushing to $TESTTMP/hgremoterepo
+  searching for changes
+  no changes found
+  [1]
+  $ cd ..
+  $ cd hggitlocalrepo
+  $ hg outgoing
+  comparing with $TESTTMP/gitremoterepo
+  searching for changes
+  no changes found
+  [1]
+  $ hg outgoing -B
+  comparing with $TESTTMP/gitremoterepo
+  searching for changed bookmarks
+  no changed bookmarks found
+  [1]
+  $ hg push
+  pushing to $TESTTMP/gitremoterepo
+  searching for changes
+  no changes found
+  [1]
+  $ cd ..
+
+Changed bookmarks, but not revs
+  $ cd purehglocalrepo
+  $ hg bookmark -fr 2 b1
+  $ hg bookmark -r 0 b2
+  $ hgstate
+    3 fc2664cac217 "add delta" bookmarks: [master]
+    2 d85ced7ae9d6 "add gamma" bookmarks: [b1]
+    1 7bcd915dc873 "add beta" bookmarks: []
+    0 3442585be8a6 "add alpha" bookmarks: [b2]
+  $ hg outgoing
+  comparing with $TESTTMP/hgremoterepo
+  searching for changes
+  no changes found
+  [1]
+As of 2.3, Mercurial's outgoing -B doesn't actually show changed bookmarks
+It only shows "new" bookmarks.  Thus, b1 doesn't show up.
+  $ hg outgoing -B
+  comparing with $TESTTMP/hgremoterepo
+  searching for changed bookmarks
+     b2                        3442585be8a6
+  $ cd ..
+  $ cd hggitlocalrepo
+  $ hg bookmark -fr 2 b1
+  $ hg bookmark -r 0 b2
+  $ hgstate
+    3 fc2664cac217 "add delta" bookmarks: [master]
+    2 d85ced7ae9d6 "add gamma" bookmarks: [b1]
+    1 7bcd915dc873 "add beta" bookmarks: []
+    0 3442585be8a6 "add alpha" bookmarks: [b2]
+  $ hg outgoing
+  comparing with $TESTTMP/gitremoterepo
+  searching for changes
+  no changes found
+  [1]
+As of 2.3, Mercurial's outgoing -B doesn't actually show changed bookmarks
+It only shows "new" bookmarks.  Thus, b1 doesn't show up.
+  $ hg outgoing -B
+  comparing with $TESTTMP/gitremoterepo
+  searching for changed bookmarks
+     b2                        3442585be8a6
+  $ cd ..
rename from tests/test-pull
rename to tests/test-clone.t
--- a/tests/test-pull
+++ b/tests/test-clone.t
@@ -1,67 +1,52 @@
-#!/bin/sh
-
-# Fails for some reason, need to investigate
-# "$TESTDIR/hghave" git || exit 80
-
-# bail if the user does not have dulwich
-python -c 'import dulwich, dulwich.repo' || exit 80
-
-# bail early if the user is already running git-daemon
-echo hi | nc localhost 9418 2>/dev/null && exit 80
-
-echo "[extensions]" >> $HGRCPATH
-echo "hggit=$(echo $(dirname $(dirname $0)))/hggit" >> $HGRCPATH
-echo 'hgext.graphlog =' >> $HGRCPATH
-echo 'hgext.bookmarks =' >> $HGRCPATH
-
-GIT_AUTHOR_NAME='test'; export GIT_AUTHOR_NAME
-GIT_AUTHOR_EMAIL='test@example.org'; export GIT_AUTHOR_EMAIL
-GIT_AUTHOR_DATE="2007-01-01 00:00:00 +0000"; export GIT_AUTHOR_DATE
-GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME"; export GIT_COMMITTER_NAME
-GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"; export GIT_COMMITTER_EMAIL
-GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"; export GIT_COMMITTER_DATE
+Load commonly used test logic
+  $ . "$TESTDIR/testutil"
 
-count=10
-commit()
-{
-    GIT_AUTHOR_DATE="2007-01-01 00:00:$count +0000"
-    GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"
-    git commit "$@" >/dev/null 2>/dev/null || echo "git commit error"
-    count=`expr $count + 1`
-}
+  $ git init gitrepo
+  Initialized empty Git repository in $TESTTMP/gitrepo/.git/
+  $ cd gitrepo
+  $ echo alpha > alpha
+  $ git add alpha
+  $ fn_git_commit -m 'add alpha'
 
-mkdir gitrepo
-cd gitrepo
-git init | python -c "import sys; print sys.stdin.read().replace('$(dirname $(pwd))/', '')"
-echo alpha > alpha
-git add alpha
-commit -m 'add alpha'
+  $ git tag alpha
 
-git tag alpha
-
-git checkout -b beta 2>&1 | sed s/\'/\"/g
-echo beta > beta
-git add beta
-commit -m 'add beta'
+  $ git checkout -b beta 2>&1 | sed s/\'/\"/g
+  Switched to a new branch "beta"
+  $ echo beta > beta
+  $ git add beta
+  $ fn_git_commit -m 'add beta'
 
 
-cd ..
-git daemon --base-path="$(pwd)"\
- --listen=localhost\
- --export-all\
- --pid-file="$DAEMON_PIDS" \
- --detach --reuseaddr
-
-echo % clone a tag
-hg clone -r alpha git://localhost/gitrepo hgrepo-a | grep -v '^updating'
-cd hgrepo-a
-hg log --graph | egrep -v ': *(beta|master)'
-
-cd ..
-echo % clone a branch
-hg clone -r beta git://localhost/gitrepo hgrepo-b | grep -v '^updating'
-cd hgrepo-b
-hg log --graph | egrep -v ': *(beta|master)'
-
-
-cd ..
+  $ cd ..
+clone a tag
+  $ hg clone -r alpha gitrepo hgrepo-a | grep -v '^updating'
+  importing git objects into hg
+  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  $ hg -R hgrepo-a log --graph | egrep -v ': *(beta|master)'
+  @  changeset:   0:3442585be8a6
+     tag:         alpha
+     tag:         default/master
+     tag:         tip
+     user:        test <test@example.org>
+     date:        Mon Jan 01 00:00:10 2007 +0000
+     summary:     add alpha
+  
+clone a branch
+  $ hg clone -r beta gitrepo hgrepo-b | grep -v '^updating'
+  importing git objects into hg
+  2 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  $ hg -R hgrepo-b log --graph | egrep -v ': *(beta|master)'
+  @  changeset:   1:7bcd915dc873
+  |  tag:         default/beta
+  |  tag:         tip
+  |  user:        test <test@example.org>
+  |  date:        Mon Jan 01 00:00:11 2007 +0000
+  |  summary:     add beta
+  |
+  o  changeset:   0:3442585be8a6
+     tag:         alpha
+     tag:         default/master
+     user:        test <test@example.org>
+     date:        Mon Jan 01 00:00:10 2007 +0000
+     summary:     add alpha
+  
deleted file mode 100644
--- a/tests/test-conflict-1.out
+++ /dev/null
@@ -1,38 +0,0 @@
-1 files updated, 0 files merged, 0 files removed, 0 files unresolved
-created new head
-warning: conflicts during merge.
-merging afile failed!
-0 files updated, 0 files merged, 0 files removed, 1 files unresolved
-use 'hg resolve' to retry unresolved file merges or 'hg update -C' to abandon
-@    3:2,1   6c53bc0f062f   1970-01-01 00:00 +0000   test
-|\     merge to C
-| |
-| o  2:0   ea82b67264a1   1970-01-01 00:00 +0000   test
-| |    A->C
-| |
-o |  1   7205e83b5a3f   1970-01-01 00:00 +0000   test
-|/     A->B
-|
-o  0   5d1a6b64f9d0   1970-01-01 00:00 +0000   test
-     origin
-
-Initialized empty Git repository in gitrepo/
-
-pushing to git://localhost/gitrepo
-exporting hg objects to git
-creating and sending data
-importing git objects into hg
-1 files updated, 0 files merged, 0 files removed, 0 files unresolved
-% expect the same revision ids as above
-@    3:1,2   6c53bc0f062f   1970-01-01 00:00 +0000   test
-|\     merge to C
-| |
-| o  2:0   7205e83b5a3f   1970-01-01 00:00 +0000   test
-| |    A->B
-| |
-o |  1   ea82b67264a1   1970-01-01 00:00 +0000   test
-|/     A->C
-|
-o  0   5d1a6b64f9d0   1970-01-01 00:00 +0000   test
-     origin
-
old mode 100755
new mode 100644
rename from tests/test-conflict-1
rename to tests/test-conflict-1.t
--- a/tests/test-conflict-1
+++ b/tests/test-conflict-1.t
@@ -1,63 +1,71 @@
-#!/bin/sh
-
-# Fails for some reason, need to investigate
-# "$TESTDIR/hghave" git || exit 80
+Load commonly used test logic
+  $ . "$TESTDIR/testutil"
 
-# bail if the user does not have dulwich
-python -c 'import dulwich, dulwich.repo' || exit 80
+  $ hg init hgrepo1
+  $ cd hgrepo1
+  $ echo A > afile
+  $ hg add afile
+  $ hg ci -m "origin"
 
-# bail early if the user is already running git-daemon
-echo hi | nc localhost 9418 2>/dev/null && exit 80
+  $ echo B > afile
+  $ hg ci -m "A->B"
 
-echo "[extensions]" >> $HGRCPATH
-echo "hggit=$(echo $(dirname $(dirname $0)))/hggit" >> $HGRCPATH
-echo 'hgext.graphlog =' >> $HGRCPATH
-echo 'hgext.bookmarks =' >> $HGRCPATH
+  $ hg up -r0
+  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  $ echo C > afile
+  $ hg ci -m "A->C"
+  created new head
 
-hg init hgrepo1
-cd hgrepo1
-echo A > afile
-hg add afile
-hg ci -m "origin"
-
-echo B > afile
-hg ci -m "A->B"
-
-hg up -r0
-echo C > afile
-hg ci -m "A->C"
+  $ hg merge -r1 2>&1 | sed 's/-C ./-C/' | egrep -v '^merging afile$' | sed 's/incomplete.*/failed!/'
+  warning: conflicts during merge.
+  merging afile failed!
+  0 files updated, 0 files merged, 0 files removed, 1 files unresolved
+  use 'hg resolve' to retry unresolved file merges or 'hg update -C' to abandon
+resolve using first parent
+  $ echo C > afile
+  $ hg resolve -m afile
+  $ hg ci -m "merge to C"
 
-hg merge -r1 2>&1 | sed 's/-C ./-C/' | egrep -v '^merging afile$' | sed 's/incomplete.*/failed!/'
-# resolve using first parent
-echo C > afile
-hg resolve -m afile
-hg ci -m "merge to C"
+  $ hg log --graph --style compact | sed 's/\[.*\]//g'
+  @    3:2,1   6c53bc0f062f   1970-01-01 00:00 +0000   test
+  |\     merge to C
+  | |
+  | o  2:0   ea82b67264a1   1970-01-01 00:00 +0000   test
+  | |    A->C
+  | |
+  o |  1   7205e83b5a3f   1970-01-01 00:00 +0000   test
+  |/     A->B
+  |
+  o  0   5d1a6b64f9d0   1970-01-01 00:00 +0000   test
+       origin
+  
 
-hg log --graph --style compact | sed 's/\[.*\]//g'
-
-cd ..
+  $ cd ..
 
-mkdir gitrepo
-cd gitrepo
-git init --bare | python -c "import sys; print sys.stdin.read().replace('$(dirname $(pwd))/', '')"
+  $ git init --bare gitrepo
+  Initialized empty Git repository in $TESTTMP/gitrepo/
 
-# dulwich does not presently support local git repos, workaround
-cd ..
-git daemon --base-path="$(pwd)"\
- --listen=localhost\
- --export-all\
- --pid-file="$DAEMON_PIDS" \
- --detach --reuseaddr \
- --enable=receive-pack
+  $ cd hgrepo1
+  $ hg bookmark -r tip master
+  $ hg push -r master ../gitrepo
+  pushing to ../gitrepo
+  searching for changes
+  $ cd ..
 
-cd hgrepo1
-hg bookmark -r tip master
-hg push -r master git://localhost/gitrepo
-cd ..
-
-hg clone git://localhost/gitrepo hgrepo2 | grep -v '^updating'
-cd hgrepo2
-echo % expect the same revision ids as above
-hg log --graph --style compact | sed 's/\[.*\]//g'
-
-cd ..
+  $ hg clone gitrepo hgrepo2 | grep -v '^updating'
+  importing git objects into hg
+  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+expect the same revision ids as above
+  $ hg -R hgrepo2 log --graph --style compact | sed 's/\[.*\]//g'
+  @    3:1,2   6c53bc0f062f   1970-01-01 00:00 +0000   test
+  |\     merge to C
+  | |
+  | o  2:0   7205e83b5a3f   1970-01-01 00:00 +0000   test
+  | |    A->B
+  | |
+  o |  1   ea82b67264a1   1970-01-01 00:00 +0000   test
+  |/     A->C
+  |
+  o  0   5d1a6b64f9d0   1970-01-01 00:00 +0000   test
+       origin
+  
deleted file mode 100644
--- a/tests/test-conflict-2.out
+++ /dev/null
@@ -1,38 +0,0 @@
-1 files updated, 0 files merged, 0 files removed, 0 files unresolved
-created new head
-warning: conflicts during merge.
-merging afile failed!
-0 files updated, 0 files merged, 0 files removed, 1 files unresolved
-use 'hg resolve' to retry unresolved file merges or 'hg update -C' to abandon
-@    3:2,1   120385945d08   1970-01-01 00:00 +0000   test
-|\     merge to B
-| |
-| o  2:0   ea82b67264a1   1970-01-01 00:00 +0000   test
-| |    A->C
-| |
-o |  1   7205e83b5a3f   1970-01-01 00:00 +0000   test
-|/     A->B
-|
-o  0   5d1a6b64f9d0   1970-01-01 00:00 +0000   test
-     origin
-
-Initialized empty Git repository in gitrepo/
-
-pushing to git://localhost/gitrepo
-exporting hg objects to git
-creating and sending data
-importing git objects into hg
-1 files updated, 0 files merged, 0 files removed, 0 files unresolved
-% expect the same revision ids as above
-@    3:1,2   120385945d08   1970-01-01 00:00 +0000   test
-|\     merge to B
-| |
-| o  2:0   7205e83b5a3f   1970-01-01 00:00 +0000   test
-| |    A->B
-| |
-o |  1   ea82b67264a1   1970-01-01 00:00 +0000   test
-|/     A->C
-|
-o  0   5d1a6b64f9d0   1970-01-01 00:00 +0000   test
-     origin
-
old mode 100755
new mode 100644
rename from tests/test-conflict-2
rename to tests/test-conflict-2.t
--- a/tests/test-conflict-2
+++ b/tests/test-conflict-2.t
@@ -1,63 +1,71 @@
-#!/bin/sh
-
-# Fails for some reason, need to investigate
-# "$TESTDIR/hghave" git || exit 80
+Load commonly used test logic
+  $ . "$TESTDIR/testutil"
 
-# bail if the user does not have dulwich
-python -c 'import dulwich, dulwich.repo' || exit 80
+  $ hg init hgrepo1
+  $ cd hgrepo1
+  $ echo A > afile
+  $ hg add afile
+  $ hg ci -m "origin"
 
-# bail early if the user is already running git-daemon
-echo hi | nc localhost 9418 2>/dev/null && exit 80
+  $ echo B > afile
+  $ hg ci -m "A->B"
 
-echo "[extensions]" >> $HGRCPATH
-echo "hggit=$(echo $(dirname $(dirname $0)))/hggit" >> $HGRCPATH
-echo 'hgext.graphlog =' >> $HGRCPATH
-echo 'hgext.bookmarks =' >> $HGRCPATH
+  $ hg up -r0
+  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  $ echo C > afile
+  $ hg ci -m "A->C"
+  created new head
 
-hg init hgrepo1
-cd hgrepo1
-echo A > afile
-hg add afile
-hg ci -m "origin"
-
-echo B > afile
-hg ci -m "A->B"
-
-hg up -r0
-echo C > afile
-hg ci -m "A->C"
+  $ hg merge -r1 2>&1 | sed 's/-C ./-C/' | egrep -v '^merging afile$' | sed 's/incomplete.*/failed!/'
+  warning: conflicts during merge.
+  merging afile failed!
+  0 files updated, 0 files merged, 0 files removed, 1 files unresolved
+  use 'hg resolve' to retry unresolved file merges or 'hg update -C' to abandon
+resolve using second parent
+  $ echo B > afile
+  $ hg resolve -m afile
+  $ hg ci -m "merge to B"
 
-hg merge -r1 2>&1 | sed 's/-C ./-C/' | egrep -v '^merging afile$' | sed 's/incomplete.*/failed!/'
-# resolve using second parent
-echo B > afile
-hg resolve -m afile
-hg ci -m "merge to B"
+  $ hg log --graph --style compact | sed 's/\[.*\]//g'
+  @    3:2,1   120385945d08   1970-01-01 00:00 +0000   test
+  |\     merge to B
+  | |
+  | o  2:0   ea82b67264a1   1970-01-01 00:00 +0000   test
+  | |    A->C
+  | |
+  o |  1   7205e83b5a3f   1970-01-01 00:00 +0000   test
+  |/     A->B
+  |
+  o  0   5d1a6b64f9d0   1970-01-01 00:00 +0000   test
+       origin
+  
 
-hg log --graph --style compact | sed 's/\[.*\]//g'
-
-cd ..
+  $ cd ..
 
-mkdir gitrepo
-cd gitrepo
-git init --bare | python -c "import sys; print sys.stdin.read().replace('$(dirname $(pwd))/', '')"
+  $ git init --bare gitrepo
+  Initialized empty Git repository in $TESTTMP/gitrepo/
 
-# dulwich does not presently support local git repos, workaround
-cd ..
-git daemon --base-path="$(pwd)"\
- --listen=localhost\
- --export-all\
- --pid-file="$DAEMON_PIDS" \
- --detach --reuseaddr \
- --enable=receive-pack
+  $ cd hgrepo1
+  $ hg bookmark -r tip master
+  $ hg push -r master ../gitrepo
+  pushing to ../gitrepo
+  searching for changes
+  $ cd ..
 
-cd hgrepo1
-hg bookmark -r tip master
-hg push -r master git://localhost/gitrepo
-cd ..
-
-hg clone git://localhost/gitrepo hgrepo2 | grep -v '^updating'
-cd hgrepo2
-echo % expect the same revision ids as above
-hg log --graph --style compact | sed 's/\[.*\]//g'
-
-cd ..
+  $ hg clone gitrepo hgrepo2 | grep -v '^updating'
+  importing git objects into hg
+  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+expect the same revision ids as above
+  $ hg -R hgrepo2 log --graph --style compact | sed 's/\[.*\]//g'
+  @    3:1,2   120385945d08   1970-01-01 00:00 +0000   test
+  |\     merge to B
+  | |
+  | o  2:0   7205e83b5a3f   1970-01-01 00:00 +0000   test
+  | |    A->B
+  | |
+  o |  1   ea82b67264a1   1970-01-01 00:00 +0000   test
+  |/     A->C
+  |
+  o  0   5d1a6b64f9d0   1970-01-01 00:00 +0000   test
+       origin
+  
deleted file mode 100644
--- a/tests/test-convergedmerge.out
+++ /dev/null
@@ -1,42 +0,0 @@
-1 files updated, 0 files merged, 0 files removed, 0 files unresolved
-created new head
-1 files updated, 0 files merged, 0 files removed, 0 files unresolved
-(branch merge, don't forget to commit)
-@    4:3,2   eaa21d002113   1970-01-01 00:00 +0000   test
-|\     merge
-| |
-| o  3:0   ea82b67264a1   1970-01-01 00:00 +0000   test
-| |    A->C
-| |
-o |  2   0dbe4ac1a758   1970-01-01 00:00 +0000   test
-| |    B->C
-| |
-o |  1   7205e83b5a3f   1970-01-01 00:00 +0000   test
-|/     A->B
-|
-o  0   5d1a6b64f9d0   1970-01-01 00:00 +0000   test
-     origin
-
-Initialized empty Git repository in gitrepo/
-
-pushing to git://localhost/gitrepo
-exporting hg objects to git
-creating and sending data
-importing git objects into hg
-1 files updated, 0 files merged, 0 files removed, 0 files unresolved
-% expect the same revision ids as above
-@    4:1,3   eaa21d002113   1970-01-01 00:00 +0000   test
-|\     merge
-| |
-| o  3   0dbe4ac1a758   1970-01-01 00:00 +0000   test
-| |    B->C
-| |
-| o  2:0   7205e83b5a3f   1970-01-01 00:00 +0000   test
-| |    A->B
-| |
-o |  1   ea82b67264a1   1970-01-01 00:00 +0000   test
-|/     A->C
-|
-o  0   5d1a6b64f9d0   1970-01-01 00:00 +0000   test
-     origin
-
old mode 100755
new mode 100644
rename from tests/test-convergedmerge
rename to tests/test-convergedmerge.t
--- a/tests/test-convergedmerge
+++ b/tests/test-convergedmerge.t
@@ -1,63 +1,75 @@
-#!/bin/sh
-
-# Fails for some reason, need to investigate
-# "$TESTDIR/hghave" git || exit 80
-
-# bail if the user does not have dulwich
-python -c 'import dulwich, dulwich.repo' || exit 80
+Load commonly used test logic
+  $ . "$TESTDIR/testutil"
 
-# bail early if the user is already running git-daemon
-echo hi | nc localhost 9418 2>/dev/null && exit 80
+  $ hg init hgrepo1
+  $ cd hgrepo1
+  $ echo A > afile
+  $ hg add afile 
+  $ hg ci -m "origin"
 
-echo "[extensions]" >> $HGRCPATH
-echo "hggit=$(echo $(dirname $(dirname $0)))/hggit" >> $HGRCPATH
-echo 'hgext.graphlog =' >> $HGRCPATH
-echo 'hgext.bookmarks =' >> $HGRCPATH
+  $ echo B > afile
+  $ hg ci -m "A->B"
 
-hg init hgrepo1
-cd hgrepo1
-echo A > afile
-hg add afile 
-hg ci -m "origin"
+  $ echo C > afile
+  $ hg ci -m "B->C"
 
-echo B > afile
-hg ci -m "A->B"
+  $ hg up -r0
+  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  $ echo C > afile
+  $ hg ci -m "A->C"
+  created new head
 
-echo C > afile
-hg ci -m "B->C"
-
-hg up -r0
-echo C > afile
-hg ci -m "A->C"
+  $ hg merge -r2
+  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  (branch merge, don't forget to commit)
+  $ hg ci -m "merge"
 
-hg merge -r2
-hg ci -m "merge"
-
-hg log --graph --style compact | sed 's/\[.*\]//g'
+  $ hg log --graph --style compact | sed 's/\[.*\]//g'
+  @    4:3,2   eaa21d002113   1970-01-01 00:00 +0000   test
+  |\     merge
+  | |
+  | o  3:0   ea82b67264a1   1970-01-01 00:00 +0000   test
+  | |    A->C
+  | |
+  o |  2   0dbe4ac1a758   1970-01-01 00:00 +0000   test
+  | |    B->C
+  | |
+  o |  1   7205e83b5a3f   1970-01-01 00:00 +0000   test
+  |/     A->B
+  |
+  o  0   5d1a6b64f9d0   1970-01-01 00:00 +0000   test
+       origin
+  
 
-cd ..
+  $ cd ..
 
-mkdir gitrepo
-cd gitrepo
-git init --bare | python -c "import sys; print sys.stdin.read().replace('$(dirname $(pwd))/', '')"
+  $ git init --bare gitrepo
+  Initialized empty Git repository in $TESTTMP/gitrepo/
 
-# dulwich does not presently support local git repos, workaround
-cd ..
-git daemon --base-path="$(pwd)"\
- --listen=localhost\
- --export-all\
- --pid-file="$DAEMON_PIDS" \
- --detach --reuseaddr \
- --enable=receive-pack
+  $ cd hgrepo1
+  $ hg bookmark -r4 master
+  $ hg push -r master ../gitrepo
+  pushing to ../gitrepo
+  searching for changes
+  $ cd ..
 
-cd hgrepo1
-hg bookmark -r4 master
-hg push -r master git://localhost/gitrepo
-cd ..
-
-hg clone git://localhost/gitrepo hgrepo2 | grep -v '^updating'
-cd hgrepo2
-echo % expect the same revision ids as above
-hg log --graph --style compact | sed 's/\[.*\]//g'
-
-cd ..
+  $ hg clone gitrepo hgrepo2 | grep -v '^updating'
+  importing git objects into hg
+  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+expect the same revision ids as above
+  $ hg -R hgrepo2 log --graph --style compact | sed 's/\[.*\]//g'
+  @    4:1,3   eaa21d002113   1970-01-01 00:00 +0000   test
+  |\     merge
+  | |
+  | o  3   0dbe4ac1a758   1970-01-01 00:00 +0000   test
+  | |    B->C
+  | |
+  | o  2:0   7205e83b5a3f   1970-01-01 00:00 +0000   test
+  | |    A->B
+  | |
+  o |  1   ea82b67264a1   1970-01-01 00:00 +0000   test
+  |/     A->C
+  |
+  o  0   5d1a6b64f9d0   1970-01-01 00:00 +0000   test
+       origin
+  
deleted file mode 100644
--- a/tests/test-empty-working-tree.out
+++ /dev/null
@@ -1,16 +0,0 @@
-Initialized empty Git repository in gitrepo/.git/
-
-Initialized empty Git repository in gitrepo2/
-
-importing git objects into hg
-0 files updated, 0 files merged, 0 files removed, 0 files unresolved
-files: 
-clearing out the git cache data
-pushing to git://localhost/gitrepo2
-exporting hg objects to git
-creating and sending data
-commit 678256865a8c85ae925bf834369264193c88f8de
-Author: test <test@example.org>
-Date:   Mon Jan 1 00:00:00 2007 +0000
-
-    empty
old mode 100755
new mode 100644
rename from tests/test-empty-working-tree
rename to tests/test-empty-working-tree.t
--- a/tests/test-empty-working-tree
+++ b/tests/test-empty-working-tree.t
@@ -1,59 +1,31 @@
-#!/bin/sh
-
-# Fails for some reason, need to investigate
-# "$TESTDIR/hghave" git || exit 80
-
-# bail if the user does not have dulwich
-python -c 'import dulwich, dulwich.repo' || exit 80
-
-# bail early if the user is already running git-daemon
-echo hi | nc localhost 9418 2> /dev/null && exit 80
+Load commonly used test logic
+  $ . "$TESTDIR/testutil"
 
-echo "[extensions]" >> $HGRCPATH
-echo "hggit=$(echo $(dirname $(dirname $0)))/hggit" >> $HGRCPATH
-echo 'hgext.bookmarks =' >> $HGRCPATH
-
-cat >> $HGRCPATH <<EOF
+  $ git init gitrepo
+  Initialized empty Git repository in $TESTTMP/gitrepo/.git/
+  $ cd gitrepo
+  $ git commit --allow-empty -m empty >/dev/null 2>/dev/null || echo "git commit error"
 
-[bookmarks]
-track.current = True
-EOF
-
-GIT_AUTHOR_NAME='test'; export GIT_AUTHOR_NAME
-GIT_AUTHOR_EMAIL='test@example.org'; export GIT_AUTHOR_EMAIL
-GIT_AUTHOR_DATE="2007-01-01 00:00:00 +0000"; export GIT_AUTHOR_DATE
-GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME"; export GIT_COMMITTER_NAME
-GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"; export GIT_COMMITTER_EMAIL
-GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"; export GIT_COMMITTER_DATE
+  $ cd ..
+  $ git init --bare gitrepo2
+  Initialized empty Git repository in $TESTTMP/gitrepo2/
 
-mkdir gitrepo
-cd gitrepo
-git init | python -c "import sys; print sys.stdin.read().replace('$(dirname $(pwd))/', '')"
-
-git commit --allow-empty -m empty >/dev/null 2>/dev/null || echo "git commit error"
-
-cd ..
-mkdir gitrepo2
-cd gitrepo2
-git init --bare | python -c "import sys; print sys.stdin.read().replace('$(dirname $(pwd))/', '')"
+  $ hg clone gitrepo hgrepo | grep -v '^updating'
+  importing git objects into hg
+  0 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  $ cd hgrepo
+  $ hg log -r tip --template 'files: {files}\n'
+  files: 
 
-# dulwich does not presently support local git repos, workaround
-cd ..
-git daemon --base-path="$(pwd)"\
- --listen=localhost\
- --export-all\
- --pid-file="$DAEMON_PIDS" \
- --detach --reuseaddr \
- --enable=receive-pack
-
-hg clone git://localhost/gitrepo hgrepo | grep -v '^updating'
-cd hgrepo
-hg log -r tip --template 'files: {files}\n'
-
-hg gclear
-hg push git://localhost/gitrepo2
-
-cd ../gitrepo2
-git log --pretty=medium
-
-cd ..
+  $ hg gclear
+  clearing out the git cache data
+  $ hg push ../gitrepo2
+  pushing to ../gitrepo2
+  searching for changes
+  $ cd ..
+  $ git --git-dir=gitrepo2 log --pretty=medium
+  commit 678256865a8c85ae925bf834369264193c88f8de
+  Author: test <test@example.org>
+  Date:   Mon Jan 1 00:00:00 2007 +0000
+  
+      empty
deleted file mode 100644
--- a/tests/test-encoding.out
+++ /dev/null
@@ -1,98 +0,0 @@
-Initialized empty Git repository in gitrepo/.git/
-
-Warning: commit message does not conform to UTF-8.
-You may want to amend it after fixing the message, or set the config
-variable i18n.commitencoding to the encoding your project uses.
-Warning: commit message does not conform to UTF-8.
-You may want to amend it after fixing the message, or set the config
-variable i18n.commitencoding to the encoding your project uses.
-Initialized empty Git repository in gitrepo2/
-
-importing git objects into hg
-4 files updated, 0 files merged, 0 files removed, 0 files unresolved
-@  changeset:   3:8549ee7fe0801b2dafc06047ca6f66d36da709f5
-|  tag:         default/master
-|  tag:         tip
-|  parent:      2:0422fbb4ec39fb69e87b94a3874ac890333de11a
-|  parent:      -1:0000000000000000000000000000000000000000
-|  manifest:    3:ea49f93388380ead5601c8fcbfa187516e7c2ed8
-|  user:        tést èncödîng <test@example.org>
-|  date:        Mon Jan 01 00:00:13 2007 +0000
-|  files+:      delta
-|  extra:       author=$ \x90\x01\x01\xe9\x91\x03\x03\x01\xe8\x91\x08\x02\x01\xf6\x91\x0c\x01\x01\xee\x91\x0f\x15
-|  extra:       branch=default
-|  extra:       committer=test <test@example.org> 1167609613 0
-|  extra:       encoding=latin-1
-|  extra:       message=\x0c\n\x90\x05\x01\xe9\x91\x07\x02\x01\xe0\x91\x0b\x01
-|  description:
-|  add déltà
-|
-|
-o  changeset:   2:0422fbb4ec39fb69e87b94a3874ac890333de11a
-|  parent:      1:9f6268bfc9eb3956c5ab8752d7b983b0ffe57115
-|  parent:      -1:0000000000000000000000000000000000000000
-|  manifest:    2:f580e7da3673c137370da2b931a1dee83590d7b4
-|  user:        tést èncödîng <test@example.org>
-|  date:        Mon Jan 01 00:00:12 2007 +0000
-|  files+:      gamma
-|  extra:       author=$ \x90\x01\x01\xe9\x91\x03\x03\x01\xe8\x91\x08\x02\x01\xf6\x91\x0c\x01\x01\xee\x91\x0f\x15
-|  extra:       branch=default
-|  extra:       committer=test <test@example.org> 1167609612 0
-|  extra:       message=\x0c\n\x90\x05\x01\xe4\x91\x07\x02\x01\xe2\x91\x0b\x01
-|  description:
-|  add gämmâ
-|
-|
-o  changeset:   1:9f6268bfc9eb3956c5ab8752d7b983b0ffe57115
-|  parent:      0:bb7d36568d6188ce0de2392246c43f6f213df954
-|  parent:      -1:0000000000000000000000000000000000000000
-|  manifest:    1:f0bd6fbafbaebe4bb59c35108428f6fce152431d
-|  user:        tést èncödîng <test@example.org>
-|  date:        Mon Jan 01 00:00:11 2007 +0000
-|  files+:      beta
-|  extra:       author=$ \x90\x01\x01\xe9\x91\x03\x03\x01\xe8\x91\x08\x02\x01\xf6\x91\x0c\x01\x01\xee\x91\x0f\x15
-|  extra:       branch=default
-|  extra:       committer=test <test@example.org> 1167609611 0
-|  description:
-|  add beta
-|
-|
-o  changeset:   0:bb7d36568d6188ce0de2392246c43f6f213df954
-   parent:      -1:0000000000000000000000000000000000000000
-   parent:      -1:0000000000000000000000000000000000000000
-   manifest:    0:8b8a0e87dfd7a0706c0524afa8ba67e20544cbf0
-   user:        test <test@example.org>
-   date:        Mon Jan 01 00:00:10 2007 +0000
-   files+:      alpha
-   extra:       branch=default
-   description:
-   add älphà
-
-
-clearing out the git cache data
-pushing to git://localhost/gitrepo2
-exporting hg objects to git
-creating and sending data
-commit da0edb01d4f3d1abf08b1be298379b0b2960e680
-Author: tést èncödîng <test@example.org>
-Date:   Mon Jan 1 00:00:13 2007 +0000
-
-    add déltà
-
-commit 2372b6c8f1b91f2db8ae5eb0f9e0427c318b449c
-Author: tést èncödîng <test@example.org>
-Date:   Mon Jan 1 00:00:12 2007 +0000
-
-    add gämmâ
-
-commit 9ef7f6dcffe643b89ba63f3323621b9a923e4802
-Author: tést èncödîng <test@example.org>
-Date:   Mon Jan 1 00:00:11 2007 +0000
-
-    add beta
-
-commit 0530b75d8c203e10dc934292a6a4032c6e958a83
-Author: test <test@example.org>
-Date:   Mon Jan 1 00:00:10 2007 +0000
-
-    add älphà
old mode 100755
new mode 100644
rename from tests/test-encoding
rename to tests/test-encoding.t
--- a/tests/test-encoding
+++ b/tests/test-encoding.t
@@ -1,71 +1,124 @@
-#!/bin/sh
-
 # -*- coding: utf-8 -*-
 
-# Fails for some reason, need to investigate
-# "$TESTDIR/hghave" git || exit 80
-
-# bail if the user does not have dulwich
-python -c 'import dulwich, dulwich.repo' || exit 80
+Load commonly used test logic
+  $ . "$TESTDIR/testutil"
 
-# bail early if the user is already running git-daemon
-echo hi | nc localhost 9418 2>/dev/null && exit 80
+  $ git init gitrepo
+  Initialized empty Git repository in $TESTTMP/gitrepo/.git/
+  $ cd gitrepo
 
-echo "[extensions]" >> $HGRCPATH
-echo "hggit=$(echo $(dirname $(dirname $0)))/hggit" >> $HGRCPATH
-echo 'hgext.graphlog =' >> $HGRCPATH
-echo 'hgext.bookmarks =' >> $HGRCPATH
+utf-8 encoded commit message
+  $ echo alpha > alpha
+  $ git add alpha
+  $ fn_git_commit -m 'add älphà'
 
-GIT_AUTHOR_NAME='test'; export GIT_AUTHOR_NAME
-GIT_AUTHOR_EMAIL='test@example.org'; export GIT_AUTHOR_EMAIL
-GIT_AUTHOR_DATE="2007-01-01 00:00:00 +0000"; export GIT_AUTHOR_DATE
-GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME"; export GIT_COMMITTER_NAME
-GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"; export GIT_COMMITTER_EMAIL
-GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"; export GIT_COMMITTER_DATE
+Create some commits using latin1 encoding
+The warning message changed in Git 1.8.0
+  $ . $TESTDIR/latin-1-encoding
+  Warning: commit message (did|does) not conform to UTF-8. (re)
+  You may want to amend it after fixing the message, or set the config
+  variable i18n.commitencoding to the encoding your project uses.
+  Warning: commit message (did|does) not conform to UTF-8. (re)
+  You may want to amend it after fixing the message, or set the config
+  variable i18n.commitencoding to the encoding your project uses.
 
-count=10
-commit()
-{
-    GIT_AUTHOR_DATE="2007-01-01 00:00:$count +0000"
-    GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"
-    git commit "$@" >/dev/null || echo "git commit error"
-    count=`expr $count + 1`
-}
+  $ cd ..
+  $ git init --bare gitrepo2
+  Initialized empty Git repository in $TESTTMP/gitrepo2/
 
-mkdir gitrepo
-cd gitrepo
-git init | python -c "import sys; print sys.stdin.read().replace('$(dirname $(pwd))/', '')"
+  $ hg clone gitrepo hgrepo | grep -v '^updating'
+  importing git objects into hg
+  4 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  $ cd hgrepo
 
-# utf-8 encoded commit message
-echo alpha > alpha
-git add alpha
-commit -m 'add älphà'
-
-. $TESTDIR/latin-1-encoding
-
-cd ..
-mkdir gitrepo2
-cd gitrepo2
-git init --bare | python -c "import sys; print sys.stdin.read().replace('$(dirname $(pwd))/', '')"
+Latin1 commit messages started being automatically converted to UTF-8 in
+Git 1.8.0, so we accept the output of either version.
+  $ HGENCODING=utf-8 hg log --graph --debug | grep -v ': *master' | grep -v 'phase:' | grep -v ': *author=' | grep -v ': *message='
+  @  changeset:   3:(8549ee7fe0801b2dafc06047ca6f66d36da709f5|c3d3e39fc04f7e2e8cdb95f090415ec1ddc1be70) (re)
+  |  tag:         default/master
+  |  tag:         tip
+  |  parent:      2:(0422fbb4ec39fb69e87b94a3874ac890333de11a|f8aa41895a3a771a72520ca205a4685b76649fdd) (re)
+  |  parent:      -1:0000000000000000000000000000000000000000
+  |  manifest:    3:ea49f93388380ead5601c8fcbfa187516e7c2ed8
+  |  user:        tést èncödîng <test@example.org>
+  |  date:        Mon Jan 01 00:00:13 2007 +0000
+  |  files+:      delta
+  |  extra:       branch=default
+  |  extra:       committer=test <test@example.org> 1167609613 0
+  |  extra:       encoding=latin-1
+  |  description:
+  |  add déltà
+  |
+  |
+  o  changeset:   2:(0422fbb4ec39fb69e87b94a3874ac890333de11a|f8aa41895a3a771a72520ca205a4685b76649fdd) (re)
+  |  parent:      1:(9f6268bfc9eb3956c5ab8752d7b983b0ffe57115|955b24cf6f8f293741d3f39110c6fe554c292533) (re)
+  |  parent:      -1:0000000000000000000000000000000000000000
+  |  manifest:    2:f580e7da3673c137370da2b931a1dee83590d7b4
+  |  user:        tést èncödîng <test@example.org>
+  |  date:        Mon Jan 01 00:00:12 2007 +0000
+  |  files+:      gamma
+  |  extra:       branch=default
+  |  extra:       committer=test <test@example.org> 1167609612 0
+  |  description:
+  |  add gämmâ
+  |
+  |
+  o  changeset:   1:(9f6268bfc9eb3956c5ab8752d7b983b0ffe57115|955b24cf6f8f293741d3f39110c6fe554c292533) (re)
+  |  parent:      0:bb7d36568d6188ce0de2392246c43f6f213df954
+  |  parent:      -1:0000000000000000000000000000000000000000
+  |  manifest:    1:f0bd6fbafbaebe4bb59c35108428f6fce152431d
+  |  user:        tést èncödîng <test@example.org>
+  |  date:        Mon Jan 01 00:00:11 2007 +0000
+  |  files+:      beta
+  |  extra:       branch=default
+  |  extra:       committer=test <test@example.org> 1167609611 0
+  |  description:
+  |  add beta
+  |
+  |
+  o  changeset:   0:bb7d36568d6188ce0de2392246c43f6f213df954
+     parent:      -1:0000000000000000000000000000000000000000
+     parent:      -1:0000000000000000000000000000000000000000
+     manifest:    0:8b8a0e87dfd7a0706c0524afa8ba67e20544cbf0
+     user:        test <test@example.org>
+     date:        Mon Jan 01 00:00:10 2007 +0000
+     files+:      alpha
+     extra:       branch=default
+     description:
+     add älphà
+  
+  
 
-# dulwich does not presently support local git repos, workaround
-cd ..
-git daemon --base-path="$(pwd)"\
- --listen=localhost\
- --export-all\
- --pid-file="$DAEMON_PIDS" \
- --detach --reuseaddr \
- --enable=receive-pack
+  $ hg gclear
+  clearing out the git cache data
+  $ hg push ../gitrepo2
+  pushing to ../gitrepo2
+  searching for changes
 
-hg clone git://localhost/gitrepo hgrepo | grep -v '^updating'
-cd hgrepo
-
-HGENCODING=utf-8 hg log --graph --debug | grep -v ': *master' | grep -v phase:
-
-hg gclear
-hg push git://localhost/gitrepo2
-
-cd ../gitrepo2
-git log --pretty=medium
-
-cd ..
+  $ cd ..
+Latin1 commit messages started being automatically converted to UTF-8 in
+Git 1.8.0, so we accept the output of either version.
+  $ git --git-dir=gitrepo2 log --pretty=medium
+  commit (da0edb01d4f3d1abf08b1be298379b0b2960e680|51c509c1c7eeb8f0a5b20aa3e894e8823f39171f) (re)
+  Author: t\xe9st \xe8nc\xf6d\xeeng <test@example.org> (esc)
+  Date:   Mon Jan 1 00:00:13 2007 +0000
+  
+      add d\xe9lt\xe0 (esc)
+  
+  commit (2372b6c8f1b91f2db8ae5eb0f9e0427c318b449c|bd576458238cbda49ffcfbafef5242e103f1bc24) (re)
+  Author: * <test@example.org> (glob)
+  Date:   Mon Jan 1 00:00:12 2007 +0000
+  
+      add g*mm* (glob)
+  
+  commit (9ef7f6dcffe643b89ba63f3323621b9a923e4802|7a7e86fc1b24db03109c9fe5da28b352de59ce90) (re)
+  Author: * <test@example.org> (glob)
+  Date:   Mon Jan 1 00:00:11 2007 +0000
+  
+      add beta
+  
+  commit 0530b75d8c203e10dc934292a6a4032c6e958a83
+  Author: test <test@example.org>
+  Date:   Mon Jan 1 00:00:10 2007 +0000
+  
+      add älphà
deleted file mode 100644
--- a/tests/test-file-removal.out
+++ /dev/null
@@ -1,77 +0,0 @@
-Initialized empty Git repository in gitrepo/.git/
-
-rm 'alpha'
-rm 'foo/bar'
-% final manifest in git is just beta
-beta
-Initialized empty Git repository in gitrepo2/
-
-importing git objects into hg
-1 files updated, 0 files merged, 0 files removed, 0 files unresolved
-@  changeset:   4:ea41a3f0ed10
-|  tag:         default/master
-|  tag:         tip
-|  user:        test <test@example.org>
-|  date:        Mon Jan 01 00:00:14 2007 +0000
-|  summary:     remove foo/bar
-|
-o  changeset:   3:c84537f94bcc
-|  user:        test <test@example.org>
-|  date:        Mon Jan 01 00:00:13 2007 +0000
-|  summary:     remove alpha
-|
-o  changeset:   2:e25450e1354f
-|  user:        test <test@example.org>
-|  date:        Mon Jan 01 00:00:12 2007 +0000
-|  summary:     add foo
-|
-o  changeset:   1:7bcd915dc873
-|  user:        test <test@example.org>
-|  date:        Mon Jan 01 00:00:11 2007 +0000
-|  summary:     add beta
-|
-o  changeset:   0:3442585be8a6
-   user:        test <test@example.org>
-   date:        Mon Jan 01 00:00:10 2007 +0000
-   summary:     add alpha
-
-
-% make sure alpha is not in this manifest
-beta
-foo/bar
-
-% make sure that only beta is in the manifest
-beta
-clearing out the git cache data
-pushing to git://localhost/gitrepo2
-exporting hg objects to git
-creating and sending data
-commit b991de8952c482a7cd51162674ffff8474862218
-Author: test <test@example.org>
-Date:   Mon Jan 1 00:00:14 2007 +0000
-
-    remove foo/bar
-
-commit b0edaf0adac19392cf2867498b983bc5192b41dd
-Author: test <test@example.org>
-Date:   Mon Jan 1 00:00:13 2007 +0000
-
-    remove alpha
-
-commit f2d0d5bfa905e12dee728b509b96cf265bb6ee43
-Author: test <test@example.org>
-Date:   Mon Jan 1 00:00:12 2007 +0000
-
-    add foo
-
-commit 9497a4ee62e16ee641860d7677cdb2589ea15554
-Author: test <test@example.org>
-Date:   Mon Jan 1 00:00:11 2007 +0000
-
-    add beta
-
-commit 7eeab2ea75ec1ac0ff3d500b5b6f8a3447dd7c03
-Author: test <test@example.org>
-Date:   Mon Jan 1 00:00:10 2007 +0000
-
-    add alpha
old mode 100755
new mode 100644
rename from tests/test-file-removal
rename to tests/test-file-removal.t
--- a/tests/test-file-removal
+++ b/tests/test-file-removal.t
@@ -1,85 +1,109 @@
-#!/bin/sh
-
-# Fails for some reason, need to investigate
-# "$TESTDIR/hghave" git || exit 80
-
-# bail if the user does not have dulwich
-python -c 'import dulwich, dulwich.repo' || exit 80
-
-# bail early if the user is already running git-daemon
-echo hi | nc localhost 9418 2>/dev/null && exit 80
-
-echo "[extensions]" >> $HGRCPATH
-echo "hggit=$(echo $(dirname $(dirname $0)))/hggit" >> $HGRCPATH
-echo 'hgext.graphlog =' >> $HGRCPATH
-echo 'hgext.bookmarks =' >> $HGRCPATH
+Load commonly used test logic
+  $ . "$TESTDIR/testutil"
 
-GIT_AUTHOR_NAME='test'; export GIT_AUTHOR_NAME
-GIT_AUTHOR_EMAIL='test@example.org'; export GIT_AUTHOR_EMAIL
-GIT_AUTHOR_DATE="2007-01-01 00:00:00 +0000"; export GIT_AUTHOR_DATE
-GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME"; export GIT_COMMITTER_NAME
-GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"; export GIT_COMMITTER_EMAIL
-GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"; export GIT_COMMITTER_DATE
+  $ git init gitrepo
+  Initialized empty Git repository in $TESTTMP/gitrepo/.git/
+  $ cd gitrepo
+  $ echo alpha > alpha
+  $ git add alpha
+  $ fn_git_commit -m 'add alpha'
+  $ echo beta > beta
+  $ git add beta
+  $ fn_git_commit -m 'add beta'
+  $ mkdir foo
+  $ echo blah > foo/bar
+  $ git add foo
+  $ fn_git_commit -m 'add foo'
+  $ git rm alpha
+  rm 'alpha'
+  $ fn_git_commit -m 'remove alpha'
+  $ git rm foo/bar
+  rm 'foo/bar'
+  $ fn_git_commit -m 'remove foo/bar'
+final manifest in git is just beta
+  $ git ls-files
+  beta
 
-count=10
-commit()
-{
-    GIT_AUTHOR_DATE="2007-01-01 00:00:$count +0000"
-    GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"
-    git commit "$@" >/dev/null 2>/dev/null || echo "git commit error"
-    count=`expr $count + 1`
-}
+  $ cd ..
+  $ git init --bare gitrepo2
+  Initialized empty Git repository in $TESTTMP/gitrepo2/
 
-mkdir gitrepo
-cd gitrepo
-git init | python -c "import sys; print sys.stdin.read().replace('$(dirname $(pwd))/', '')"
-echo alpha > alpha
-git add alpha
-commit -m 'add alpha'
-echo beta > beta
-git add beta
-commit -m 'add beta'
-mkdir foo
-echo blah > foo/bar
-git add foo
-commit -m 'add foo'
-git rm alpha
-commit -m 'remove alpha'
-git rm foo/bar
-commit -m 'remove foo/bar'
-echo % final manifest in git is just beta
-git ls-files
+  $ hg clone gitrepo hgrepo | grep -v '^updating'
+  importing git objects into hg
+  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  $ cd hgrepo
+  $ hg log --graph | grep -v ': *master'
+  @  changeset:   4:ea41a3f0ed10
+  |  tag:         default/master
+  |  tag:         tip
+  |  user:        test <test@example.org>
+  |  date:        Mon Jan 01 00:00:14 2007 +0000
+  |  summary:     remove foo/bar
+  |
+  o  changeset:   3:c84537f94bcc
+  |  user:        test <test@example.org>
+  |  date:        Mon Jan 01 00:00:13 2007 +0000
+  |  summary:     remove alpha
+  |
+  o  changeset:   2:e25450e1354f
+  |  user:        test <test@example.org>
+  |  date:        Mon Jan 01 00:00:12 2007 +0000
+  |  summary:     add foo
+  |
+  o  changeset:   1:7bcd915dc873
+  |  user:        test <test@example.org>
+  |  date:        Mon Jan 01 00:00:11 2007 +0000
+  |  summary:     add beta
+  |
+  o  changeset:   0:3442585be8a6
+     user:        test <test@example.org>
+     date:        Mon Jan 01 00:00:10 2007 +0000
+     summary:     add alpha
+  
 
-cd ..
-mkdir gitrepo2
-cd gitrepo2
-git init --bare | python -c "import sys; print sys.stdin.read().replace('$(dirname $(pwd))/', '')"
+make sure alpha is not in this manifest
+  $ hg manifest -r 3
+  beta
+  foo/bar
 
-# dulwich does not presently support local git repos, workaround
-cd ..
-git daemon --base-path="$(pwd)"\
- --listen=localhost\
- --export-all\
- --pid-file="$DAEMON_PIDS" \
- --detach --reuseaddr \
- --enable=receive-pack
+make sure that only beta is in the manifest
+  $ hg manifest
+  beta
 
-hg clone git://localhost/gitrepo hgrepo | grep -v '^updating'
-cd hgrepo
-hg log --graph | grep -v ': *master'
+  $ hg gclear
+  clearing out the git cache data
+  $ hg push ../gitrepo2
+  pushing to ../gitrepo2
+  searching for changes
 
-echo
-echo % make sure alpha is not in this manifest
-hg manifest -r 3
-
-echo
-echo % make sure that only beta is in the manifest
-hg manifest
-
-hg gclear
-hg push git://localhost/gitrepo2
-
-cd ../gitrepo2
-git log --pretty=medium
-
-cd ..
+  $ cd ..
+  $ git --git-dir=gitrepo2 log --pretty=medium
+  commit b991de8952c482a7cd51162674ffff8474862218
+  Author: test <test@example.org>
+  Date:   Mon Jan 1 00:00:14 2007 +0000
+  
+      remove foo/bar
+  
+  commit b0edaf0adac19392cf2867498b983bc5192b41dd
+  Author: test <test@example.org>
+  Date:   Mon Jan 1 00:00:13 2007 +0000
+  
+      remove alpha
+  
+  commit f2d0d5bfa905e12dee728b509b96cf265bb6ee43
+  Author: test <test@example.org>
+  Date:   Mon Jan 1 00:00:12 2007 +0000
+  
+      add foo
+  
+  commit 9497a4ee62e16ee641860d7677cdb2589ea15554
+  Author: test <test@example.org>
+  Date:   Mon Jan 1 00:00:11 2007 +0000
+  
+      add beta
+  
+  commit 7eeab2ea75ec1ac0ff3d500b5b6f8a3447dd7c03
+  Author: test <test@example.org>
+  Date:   Mon Jan 1 00:00:10 2007 +0000
+  
+      add alpha
deleted file mode 100644
--- a/tests/test-git-clone.out
+++ /dev/null
@@ -1,18 +0,0 @@
-Initialized empty Git repository in gitrepo/.git/
-
-importing git objects into hg
-2 files updated, 0 files merged, 0 files removed, 0 files unresolved
-@  changeset:   1:7bcd915dc873
-|  tag:         default/master
-|  tag:         tip
-|  user:        test <test@example.org>
-|  date:        Mon Jan 01 00:00:11 2007 +0000
-|  summary:     add beta
-|
-o  changeset:   0:3442585be8a6
-   user:        test <test@example.org>
-   date:        Mon Jan 01 00:00:10 2007 +0000
-   summary:     add alpha
-
-% we should have some bookmarks
- * master                    1:7bcd915dc873
rename from tests/test-git-clone
rename to tests/test-git-clone.t
--- a/tests/test-git-clone
+++ b/tests/test-git-clone.t
@@ -1,50 +1,35 @@
-#!/bin/sh
-
-# Fails for some reason, need to investigate
-# "$TESTDIR/hghave" git || exit 80
-
-# bail if the user does not have dulwich
-python -c 'import dulwich, dulwich.repo' || exit 80
-
-# bail early if the user is already running git-daemon
-echo hi | nc localhost 9418 2>/dev/null && exit 80
+Load commonly used test logic
+  $ . "$TESTDIR/testutil"
 
-echo "[extensions]" >> $HGRCPATH
-echo "hggit=$(echo $(dirname $(dirname $0)))/hggit" >> $HGRCPATH
-echo 'hgext.graphlog =' >> $HGRCPATH
-echo 'hgext.bookmarks =' >> $HGRCPATH
+  $ git init gitrepo
+  Initialized empty Git repository in $TESTTMP/gitrepo/.git/
+  $ cd gitrepo
+  $ echo alpha > alpha
+  $ git add alpha
+  $ fn_git_commit -m 'add alpha'
+  $ echo beta > beta
+  $ git add beta
+  $ fn_git_commit -m 'add beta'
 
-GIT_AUTHOR_NAME='test'; export GIT_AUTHOR_NAME
-GIT_AUTHOR_EMAIL='test@example.org'; export GIT_AUTHOR_EMAIL
-GIT_AUTHOR_DATE="2007-01-01 00:00:00 +0000"; export GIT_AUTHOR_DATE
-GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME"; export GIT_COMMITTER_NAME
-GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"; export GIT_COMMITTER_EMAIL
-GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"; export GIT_COMMITTER_DATE
+  $ cd ..
 
-count=10
-commit()
-{
-    GIT_AUTHOR_DATE="2007-01-01 00:00:$count +0000"
-    GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"
-    git commit "$@" >/dev/null 2>/dev/null || echo "git commit error"
-    count=`expr $count + 1`
-}
+  $ hg clone gitrepo hgrepo | grep -v '^updating'
+  importing git objects into hg
+  2 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  $ hg -R hgrepo log --graph  | grep -v ': *master'
+  @  changeset:   1:7bcd915dc873
+  |  tag:         default/master
+  |  tag:         tip
+  |  user:        test <test@example.org>
+  |  date:        Mon Jan 01 00:00:11 2007 +0000
+  |  summary:     add beta
+  |
+  o  changeset:   0:3442585be8a6
+     user:        test <test@example.org>
+     date:        Mon Jan 01 00:00:10 2007 +0000
+     summary:     add alpha
+  
 
-mkdir gitrepo
-cd gitrepo
-git init | python -c "import sys; print sys.stdin.read().replace('$(dirname $(pwd))/', '')"
-echo alpha > alpha
-git add alpha
-commit -m 'add alpha'
-echo beta > beta
-git add beta
-commit -m 'add beta'
-
-cd ..
-
-hg clone gitrepo hgrepo | grep -v '^updating'
-cd hgrepo
-hg log --graph  | grep -v ': *master'
-
-echo % we should have some bookmarks
-hg book
+we should have some bookmarks
+  $ hg -R hgrepo book
+   * master                    1:7bcd915dc873
deleted file mode 100644
--- a/tests/test-git-submodules.out
+++ /dev/null
@@ -1,39 +0,0 @@
-Initialized empty Git repository in gitrepo1/.git/
-
-Initialized empty Git repository in gitsubrepo/.git/
-
-Initialized empty Git repository in ...
-
-Initialized empty Git repository in ...
-
-[master e42b08b] add subrepo
- 2 files changed, 4 insertions(+)
- create mode 100644 .gitmodules
- create mode 160000 subrepo
-rm 'subrepo'
-rm '.gitmodules'
-[master 7e4c934] rm subrepo
- 2 files changed, 4 deletions(-)
- delete mode 100644 .gitmodules
- delete mode 160000 subrepo
-importing git objects into hg
-1 files updated, 0 files merged, 0 files removed, 0 files unresolved
-@  changeset:   2:954cdf1c8c82
-|  tag:         default/master
-|  tag:         tip
-|  user:        test <test@example.org>
-|  date:        Mon Jan 01 00:00:11 2007 +0000
-|  summary:     rm subrepo
-|
-o  changeset:   1:145121c71064
-|  user:        test <test@example.org>
-|  date:        Mon Jan 01 00:00:11 2007 +0000
-|  summary:     add subrepo
-|
-o  changeset:   0:3442585be8a6
-   user:        test <test@example.org>
-   date:        Mon Jan 01 00:00:10 2007 +0000
-   summary:     add alpha
-
-% we should have some bookmarks
- * master                    2:954cdf1c8c82
old mode 100755
new mode 100644
rename from tests/test-git-submodules
rename to tests/test-git-submodules.t
--- a/tests/test-git-submodules
+++ b/tests/test-git-submodules.t
@@ -1,72 +1,76 @@
-#!/bin/sh
-
-# Fails for some reason, need to investigate
-# "$TESTDIR/hghave" git || exit 80
-
-# bail if the user does not have dulwich
-python -c 'import dulwich, dulwich.repo' || exit 80
+Load commonly used test logic
+  $ . "$TESTDIR/testutil"
 
-# bail early if the user is already running git-daemon
-echo hi | nc localhost 9418 2>/dev/null && exit 80
-
-echo "[extensions]" >> $HGRCPATH
-echo "hggit=$(echo $(dirname $(dirname $0)))/hggit" >> $HGRCPATH
-echo 'hgext.graphlog =' >> $HGRCPATH
-echo 'hgext.bookmarks =' >> $HGRCPATH
+  $ git init gitrepo1
+  Initialized empty Git repository in $TESTTMP/gitrepo1/.git/
+  $ cd gitrepo1
+  $ echo alpha > alpha
+  $ git add alpha
+  $ fn_git_commit -m 'add alpha'
+  $ cd ..
 
-GIT_AUTHOR_NAME='test'; export GIT_AUTHOR_NAME
-GIT_AUTHOR_EMAIL='test@example.org'; export GIT_AUTHOR_EMAIL
-GIT_AUTHOR_DATE="2007-01-01 00:00:00 +0000"; export GIT_AUTHOR_DATE
-GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME"; export GIT_COMMITTER_NAME
-GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"; export GIT_COMMITTER_EMAIL
-GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"; export GIT_COMMITTER_DATE
+  $ git init gitsubrepo
+  Initialized empty Git repository in $TESTTMP/gitsubrepo/.git/
+  $ cd gitsubrepo
+  $ echo beta > beta
+  $ git add beta
+  $ fn_git_commit -m 'add beta'
+  $ cd ..
 
-count=10
-commit()
-{
-    GIT_AUTHOR_DATE="2007-01-01 00:00:$count +0000"
-    GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"
-    git commit "$@" >/dev/null 2>/dev/null || echo "git commit error" | sed 's/, 0 deletions(-)//'
-    count=`expr $count + 1`
-}
+  $ mkdir gitrepo2
+  $ cd gitrepo2
+
+  $ rmpwd="import sys; print sys.stdin.read().replace('$(dirname $(pwd))/', '')"
+different versions of git spell the dir differently. Older versions
+use the full path to the directory all the time, whereas newer
+version spell it sanely as it was given (eg . in a newer version,
+while older git will use the full normalized path for .)
+  $ clonefilt='s/Cloning into/Initialized empty Git repository in/;s/in .*/in .../'
 
-mkdir gitrepo1
-cd gitrepo1
-git init | python -c "import sys; print sys.stdin.read().replace('$(dirname $(pwd))/', '')"
-echo alpha > alpha
-git add alpha
-commit -m 'add alpha'
-cd ..
-
-mkdir gitsubrepo
-cd gitsubrepo
-git init | python -c "import sys; print sys.stdin.read().replace('$(dirname $(pwd))/', '')"
-echo beta > beta
-git add beta
-commit -m 'add beta'
-cd ..
-
-mkdir gitrepo2
-cd gitrepo2
+  $ git clone ../gitrepo1 . | python -c "$rmpwd" | sed "$clonefilt" | egrep -v '^done\.$'
+  Initialized empty Git repository in ...
+  
+  $ git submodule add ../gitsubrepo subrepo | python -c "$rmpwd" | sed "$clonefilt" | egrep -v '^done\.$'
+  Initialized empty Git repository in ...
+  
+  $ git commit -m 'add subrepo' | sed 's/, 0 deletions(-)//'
+  [master e42b08b] add subrepo
+   2 files changed, 4 insertions(+)
+   create mode 100644 .gitmodules
+   create mode 160000 subrepo
+  $ git rm --cached subrepo
+  rm 'subrepo'
+  $ git rm .gitmodules
+  rm '.gitmodules'
+  $ git commit -m 'rm subrepo' | sed 's/, 0 deletions(-)//' | sed 's/, 0 insertions(+)//'
+  [master 7e4c934] rm subrepo
+   2 files changed, 4 deletions(-)
+   delete mode 100644 .gitmodules
+   delete mode 160000 subrepo
+  $ cd ..
 
-rmpwd="import sys; print sys.stdin.read().replace('$(dirname $(pwd))/', '')"
-# different versions of git spell the dir differently. Older versions
-# use the full path to the directory all the time, whereas newer
-# version spell it sanely as it was given (eg . in a newer version,
-# while older git will use the full normalized path for .)
-clonefilt='s/Cloning into/Initialized empty Git repository in/;s/in .*/in .../'
+  $ hg clone gitrepo2 hgrepo | grep -v '^updating'
+  importing git objects into hg
+  2 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  $ hg -R hgrepo log --graph  | grep -v ': *master'
+  @  changeset:   2:76fda365fbbb
+  |  tag:         default/master
+  |  tag:         tip
+  |  user:        test <test@example.org>
+  |  date:        Mon Jan 01 00:00:11 2007 +0000
+  |  summary:     rm subrepo
+  |
+  o  changeset:   1:2f69b1b8a6f8
+  |  user:        test <test@example.org>
+  |  date:        Mon Jan 01 00:00:11 2007 +0000
+  |  summary:     add subrepo
+  |
+  o  changeset:   0:3442585be8a6
+     user:        test <test@example.org>
+     date:        Mon Jan 01 00:00:10 2007 +0000
+     summary:     add alpha
+  
 
-git clone ../gitrepo1 . | python -c "$rmpwd" | sed "$clonefilt" | egrep -v '^done\.$'
-git submodule add ../gitsubrepo subrepo | python -c "$rmpwd" | sed "$clonefilt" | egrep -v '^done\.$'
-git commit -m 'add subrepo' | sed 's/, 0 deletions(-)//'
-git rm --cached subrepo
-git rm .gitmodules
-git commit -m 'rm subrepo' | sed 's/, 0 deletions(-)//' | sed 's/, 0 insertions(+)//'
-cd ..
-
-hg clone gitrepo2 hgrepo | grep -v '^updating'
-cd hgrepo
-hg log --graph  | grep -v ': *master'
-
-echo % we should have some bookmarks
-hg book
+we should have some bookmarks
+  $ hg -R hgrepo book
+   * master                    2:76fda365fbbb
deleted file mode 100644
--- a/tests/test-git-tags.out
+++ /dev/null
@@ -1,22 +0,0 @@
-Initialized empty Git repository in gitrepo/.git/
-
-importing git objects into hg
-2 files updated, 0 files merged, 0 files removed, 0 files unresolved
-@  changeset:   1:99dcc15b7b07
-|  tag:         beta
-|  tag:         default/master
-|  tag:         tip
-|  user:        test <test@example.org>
-|  date:        Mon Jan 01 00:00:12 2007 +0000
-|  summary:     add beta
-|
-o  changeset:   0:3442585be8a6
-   tag:         alpha
-   user:        test <test@example.org>
-   date:        Mon Jan 01 00:00:10 2007 +0000
-   summary:     add alpha
-
-pushing to git://localhost/gitrepo
-exporting hg objects to git
-creating and sending data
-    default::refs/heads/master => GIT:3b7fd1b3
old mode 100755
new mode 100644
rename from tests/test-git-tags
rename to tests/test-git-tags.t
--- a/tests/test-git-tags
+++ b/tests/test-git-tags.t
@@ -1,71 +1,45 @@
-#!/bin/sh
-
-# Fails for some reason, need to investigate
-# "$TESTDIR/hghave" git || exit 80
-
-# bail if the user does not have dulwich
-python -c 'import dulwich, dulwich.repo' || exit 80
-
-# bail early if the user is already running git-daemon
-echo hi | nc localhost 9418 2>/dev/null && exit 80
+Load commonly used test logic
+  $ . "$TESTDIR/testutil"
 
-echo "[extensions]" >> $HGRCPATH
-echo "hggit=$(echo $(dirname $(dirname $0)))/hggit" >> $HGRCPATH
-echo 'hgext.graphlog =' >> $HGRCPATH
-echo 'hgext.bookmarks =' >> $HGRCPATH
+  $ git init gitrepo
+  Initialized empty Git repository in $TESTTMP/gitrepo/.git/
+  $ cd gitrepo
+  $ git config receive.denyCurrentBranch ignore
+  $ echo alpha > alpha
+  $ git add alpha
+  $ fn_git_commit -m 'add alpha'
+  $ fn_git_tag alpha
 
-GIT_AUTHOR_NAME='test'; export GIT_AUTHOR_NAME
-GIT_AUTHOR_EMAIL='test@example.org'; export GIT_AUTHOR_EMAIL
-GIT_AUTHOR_DATE="2007-01-01 00:00:00 +0000"; export GIT_AUTHOR_DATE
-GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME"; export GIT_COMMITTER_NAME
-GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"; export GIT_COMMITTER_EMAIL
-GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"; export GIT_COMMITTER_DATE
+  $ echo beta > beta
+  $ git add beta
+  $ fn_git_commit -m 'add beta'
+  $ fn_git_tag -a -m 'added tag beta' beta
+
+  $ cd ..
+  $ hg clone gitrepo hgrepo | grep -v '^updating'
+  importing git objects into hg
+  2 files updated, 0 files merged, 0 files removed, 0 files unresolved
 
-count=10
-commit()
-{
-    GIT_AUTHOR_DATE="2007-01-01 00:00:$count +0000"
-    GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"
-    git commit "$@" >/dev/null 2>/dev/null || echo "git commit error"
-    count=`expr $count + 1`
-}
-tag()
-{
-    GIT_AUTHOR_DATE="2007-01-01 00:00:$count +0000"
-    GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"
-    git tag "$@" >/dev/null 2>/dev/null || echo "git commit error"
-    count=`expr $count + 1`
-}
+  $ cd hgrepo
+  $ hg log --graph  | grep -v ': *master'
+  @  changeset:   1:99dcc15b7b07
+  |  tag:         beta
+  |  tag:         default/master
+  |  tag:         tip
+  |  user:        test <test@example.org>
+  |  date:        Mon Jan 01 00:00:12 2007 +0000
+  |  summary:     add beta
+  |
+  o  changeset:   0:3442585be8a6
+     tag:         alpha
+     user:        test <test@example.org>
+     date:        Mon Jan 01 00:00:10 2007 +0000
+     summary:     add alpha
+  
+  $ echo beta-fix >> beta
+  $ hg commit -m 'fix for beta'
+  $ hg push
+  pushing to $TESTTMP/gitrepo
+  searching for changes
 
-mkdir gitrepo
-cd gitrepo
-git init | python -c "import sys; print sys.stdin.read().replace('$(dirname $(pwd))/', '')"
-git config receive.denyCurrentBranch ignore
-echo alpha > alpha
-git add alpha
-commit -m 'add alpha'
-tag alpha
-
-echo beta > beta
-git add beta
-commit -m 'add beta'
-tag -a -m 'added tag beta' beta
-
-# dulwich does not presently support local git repos, workaround
-cd ..
-git daemon --base-path="$(pwd)"\
- --listen=localhost\
- --export-all\
- --pid-file="$DAEMON_PIDS" \
- --detach --reuseaddr \
- --enable=receive-pack
-
-hg clone git://localhost/gitrepo hgrepo | grep -v '^updating'
-
-cd hgrepo
-hg log --graph  | grep -v ': *master'
-echo beta-fix >> beta
-hg commit -m 'fix for beta'
-hg push
-
-cd ..
+  $ cd ..
deleted file mode 100644
--- a/tests/test-git-workflow.out
+++ /dev/null
@@ -1,49 +0,0 @@
-@  changeset:   0:0221c246a56712c6aa64e5ee382244d8a471b1e2
-   tag:         tip
-   parent:      -1:0000000000000000000000000000000000000000
-   parent:      -1:0000000000000000000000000000000000000000
-   manifest:    0:8b8a0e87dfd7a0706c0524afa8ba67e20544cbf0
-   user:        test
-   date:        Mon Jan 01 00:00:10 2007 +0000
-   files+:      alpha
-   extra:       branch=default
-   description:
-   add alpha
-
-
-% configure for use from git
-updating to branch default
-1 files updated, 0 files merged, 0 files removed, 0 files unresolved
-0 files updated, 0 files merged, 1 files removed, 0 files unresolved
-exporting hg objects to git
-% do some work
-Already on "master"
-% get things back to hg
-importing git objects into hg
-o  changeset:   1:7108ae7bd184226a29b8203619a8253d314643bf
-|  tag:         tip
-|  parent:      0:0221c246a56712c6aa64e5ee382244d8a471b1e2
-|  parent:      -1:0000000000000000000000000000000000000000
-|  manifest:    1:f0bd6fbafbaebe4bb59c35108428f6fce152431d
-|  user:        test <test@example.org>
-|  date:        Mon Jan 01 00:00:11 2007 +0000
-|  files+:      beta
-|  extra:       branch=default
-|  description:
-|  add beta
-|
-|
-o  changeset:   0:0221c246a56712c6aa64e5ee382244d8a471b1e2
-   parent:      -1:0000000000000000000000000000000000000000
-   parent:      -1:0000000000000000000000000000000000000000
-   manifest:    0:8b8a0e87dfd7a0706c0524afa8ba67e20544cbf0
-   user:        test
-   date:        Mon Jan 01 00:00:10 2007 +0000
-   files+:      alpha
-   extra:       branch=default
-   description:
-   add alpha
-
-
-% gimport should have updated the bookmarks as well
-   master                    1:7108ae7bd184
rename from tests/test-git-workflow
rename to tests/test-git-workflow.t
--- a/tests/test-git-workflow
+++ b/tests/test-git-workflow.t
@@ -1,70 +1,77 @@
-#!/bin/sh
-
-# Fails for some reason, need to investigate
-# "$TESTDIR/hghave" git || exit 80
-
-# bail if the user does not have dulwich
-python -c 'import dulwich, dulwich.repo' || exit 80
-
-# bail early if the user is already running git-daemon
-echo hi | nc localhost 9418 2>/dev/null && exit 80
+Load commonly used test logic
+  $ . "$TESTDIR/testutil"
 
-echo "[extensions]" >> $HGRCPATH
-echo "hggit=$(echo $(dirname $(dirname $0)))/hggit" >> $HGRCPATH
-echo 'hgext.graphlog =' >> $HGRCPATH
-echo 'hgext.bookmarks =' >> $HGRCPATH
+  $ hg init hgrepo
+  $ cd hgrepo
+  $ echo alpha > alpha
+  $ hg add alpha
+  $ fn_hg_commit -m "add alpha"
+  $ hg log --graph --debug | grep -v phase:
+  @  changeset:   0:0221c246a56712c6aa64e5ee382244d8a471b1e2
+     tag:         tip
+     parent:      -1:0000000000000000000000000000000000000000
+     parent:      -1:0000000000000000000000000000000000000000
+     manifest:    0:8b8a0e87dfd7a0706c0524afa8ba67e20544cbf0
+     user:        test
+     date:        Mon Jan 01 00:00:10 2007 +0000
+     files+:      alpha
+     extra:       branch=default
+     description:
+     add alpha
+  
+  
 
-GIT_AUTHOR_NAME='test'; export GIT_AUTHOR_NAME
-GIT_AUTHOR_EMAIL='test@example.org'; export GIT_AUTHOR_EMAIL
-GIT_AUTHOR_DATE="2007-01-01 00:00:00 +0000"; export GIT_AUTHOR_DATE
-GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME"; export GIT_COMMITTER_NAME
-GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"; export GIT_COMMITTER_EMAIL
-GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"; export GIT_COMMITTER_DATE
+  $ cd ..
+
+configure for use from git
+  $ hg clone hgrepo gitrepo
+  updating to branch default
+  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  $ cd gitrepo
+  $ hg book master
+  $ hg up null
+  0 files updated, 0 files merged, 1 files removed, 0 files unresolved
+  $ echo "[git]" >> .hg/hgrc
+  $ echo "intree = True" >> .hg/hgrc
+  $ hg gexport
 
-count=10
-commit()
-{
-    GIT_AUTHOR_DATE="2007-01-01 00:00:$count +0000"
-    GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"
-    git commit "$@" >/dev/null 2>/dev/null || echo "git commit error"
-    count=`expr $count + 1`
-}
-hgcommit()
-{
-    HGDATE="2007-01-01 00:00:$count +0000"
-    hg commit -d "$HGDATE" "$@" >/dev/null 2>/dev/null || echo "hg commit error"
-    count=`expr $count + 1`
-}
-
-mkdir hgrepo
-cd hgrepo
-hg init
-
-echo alpha > alpha
-hg add alpha
-hgcommit -m "add alpha"
-hg log --graph --debug | grep -v phase:
+do some work
+  $ git config core.bare false
+  $ git checkout master 2>&1 | sed s/\'/\"/g
+  Already on "master"
+  $ echo beta > beta
+  $ git add beta
+  $ fn_git_commit -m 'add beta'
 
-cd ..
-
-echo % configure for use from git
-hg clone hgrepo gitrepo
-cd gitrepo
-hg book master
-hg up null
-echo "[git]" >> .hg/hgrc
-echo "intree = True" >> .hg/hgrc
-hg gexport
-
-echo % do some work
-git config core.bare false
-git checkout master 2>&1 | sed s/\'/\"/g
-echo beta > beta
-git add beta
-commit -m 'add beta'
-
-echo % get things back to hg
-hg gimport
-hg log --graph --debug | grep -v ': *master' | grep -v phase:
-echo % gimport should have updated the bookmarks as well
-hg bookmarks
+get things back to hg
+  $ hg gimport
+  importing git objects into hg
+  $ hg log --graph --debug | grep -v ': *master' | grep -v phase:
+  o  changeset:   1:7108ae7bd184226a29b8203619a8253d314643bf
+  |  tag:         tip
+  |  parent:      0:0221c246a56712c6aa64e5ee382244d8a471b1e2
+  |  parent:      -1:0000000000000000000000000000000000000000
+  |  manifest:    1:f0bd6fbafbaebe4bb59c35108428f6fce152431d
+  |  user:        test <test@example.org>
+  |  date:        Mon Jan 01 00:00:11 2007 +0000
+  |  files+:      beta
+  |  extra:       branch=default
+  |  description:
+  |  add beta
+  |
+  |
+  o  changeset:   0:0221c246a56712c6aa64e5ee382244d8a471b1e2
+     parent:      -1:0000000000000000000000000000000000000000
+     parent:      -1:0000000000000000000000000000000000000000
+     manifest:    0:8b8a0e87dfd7a0706c0524afa8ba67e20544cbf0
+     user:        test
+     date:        Mon Jan 01 00:00:10 2007 +0000
+     files+:      alpha
+     extra:       branch=default
+     description:
+     add alpha
+  
+  
+gimport should have updated the bookmarks as well
+  $ hg bookmarks
+     master                    1:7108ae7bd184
deleted file mode 100644
--- a/tests/test-help.out
+++ /dev/null
@@ -1,4 +0,0 @@
- hggit push and pull from a Git server
- git Working with Git Repositories
-For more information and instructions, see "hg help git"
-Working with Git Repositories
rename from tests/test-help
rename to tests/test-help.t
--- a/tests/test-help
+++ b/tests/test-help.t
@@ -1,10 +1,12 @@
-#!/bin/sh
+Tests that the various help files are properly registered
 
-# Tests that the various help files are properly registered
+Load commonly used test logic
+  $ . "$TESTDIR/testutil"
 
-echo "[extensions]" >> $HGRCPATH
-echo "hggit=$(echo $(dirname $(dirname $0)))/hggit" >> $HGRCPATH
-
-hg help | grep 'git' | sed 's/  */ /g'
-hg help hggit | grep 'help git' | sed 's/:hg:`help git`/"hg help git"/g'
-hg help git | grep 'Working with Git Repositories'
+  $ hg help | grep 'git' | sed 's/  */ /g'
+   hggit push and pull from a Git server
+   git Working with Git Repositories
+  $ hg help hggit | grep 'help git' | sed 's/:hg:`help git`/"hg help git"/g'
+  For more information and instructions, see "hg help git"
+  $ hg help git | grep 'Working with Git Repositories'
+  Working with Git Repositories
deleted file mode 100644
--- a/tests/test-hg-author.out
+++ /dev/null
@@ -1,189 +0,0 @@
-Initialized empty Git repository in gitrepo/.git/
-
-Switched to a new branch 'not-master'
-importing git objects into hg
-1 files updated, 0 files merged, 0 files removed, 0 files unresolved
-0 files updated, 0 files merged, 0 files removed, 0 files unresolved
-pushing to git://localhost/gitrepo
-exporting hg objects to git
-creating and sending data
-    default::refs/heads/master => GIT:cffa0e8d
-pushing to git://localhost/gitrepo
-exporting hg objects to git
-creating and sending data
-    default::refs/heads/master => GIT:2b9ec6a4
-pushing to git://localhost/gitrepo
-exporting hg objects to git
-creating and sending data
-    default::refs/heads/master => GIT:fee30180
-pushing to git://localhost/gitrepo
-exporting hg objects to git
-creating and sending data
-    default::refs/heads/master => GIT:d1659250
-pushing to git://localhost/gitrepo
-exporting hg objects to git
-creating and sending data
-    default::refs/heads/master => GIT:ee985f12
-pushing to git://localhost/gitrepo
-exporting hg objects to git
-creating and sending data
-    default::refs/heads/master => GIT:d21e26b4
-pushing to git://localhost/gitrepo
-exporting hg objects to git
-creating and sending data
-    default::refs/heads/master => GIT:8c878c97
-pushing to git://localhost/gitrepo
-exporting hg objects to git
-creating and sending data
-    default::refs/heads/master => GIT:1e03e913
-@  changeset:   8:d3c51ce68cfd
-|  tag:         default/master
-|  tag:         tip
-|  user:        test >test@example.com>
-|  date:        Mon Jan 01 00:00:18 2007 +0000
-|  summary:     add theta
-|
-o  changeset:   7:b90e988091a2
-|  user:        test < test@example.com >
-|  date:        Mon Jan 01 00:00:17 2007 +0000
-|  summary:     add eta
-|
-o  changeset:   6:7ede2f971cae
-|  user:        test
-|  date:        Mon Jan 01 00:00:16 2007 +0000
-|  summary:     add zeta
-|
-o  changeset:   5:1454a94056ec
-|  user:        name <test@example.com
-|  date:        Mon Jan 01 00:00:15 2007 +0000
-|  summary:     add epsilon
-|
-o  changeset:   4:a045fd599678
-|  user:        name<test@example.com>
-|  date:        Mon Jan 01 00:00:14 2007 +0000
-|  summary:     add delta
-|
-o  changeset:   3:8da3ab8b31d0
-|  user:        <test@example.com>
-|  date:        Mon Jan 01 00:00:13 2007 +0000
-|  summary:     add gamma
-|
-o  changeset:   2:92d33c0dd6e1
-|  user:        test <test@example.com> (comment)
-|  date:        Mon Jan 01 00:00:12 2007 +0000
-|  summary:     modify beta
-|
-o  changeset:   1:0564f526fb0f
-|  user:        test
-|  date:        Mon Jan 01 00:00:11 2007 +0000
-|  summary:     add beta
-|
-o  changeset:   0:3442585be8a6
-   tag:         default/not-master
-   user:        test <test@example.org>
-   date:        Mon Jan 01 00:00:10 2007 +0000
-   summary:     add alpha
-
-importing git objects into hg
-8 files updated, 0 files merged, 0 files removed, 0 files unresolved
-@  changeset:   8:efec0270e295
-|  tag:         default/master
-|  tag:         tip
-|  user:        test ?test@example.com <test ?test@example.com>
-|  date:        Mon Jan 01 00:00:18 2007 +0000
-|  summary:     add theta
-|
-o  changeset:   7:8ab87d5066e4
-|  user:        test <test@example.com>
-|  date:        Mon Jan 01 00:00:17 2007 +0000
-|  summary:     add eta
-|
-o  changeset:   6:ff226cc916bd
-|  user:        test
-|  date:        Mon Jan 01 00:00:16 2007 +0000
-|  summary:     add zeta
-|
-o  changeset:   5:5f1557c62c53
-|  user:        name <test@example.com>
-|  date:        Mon Jan 01 00:00:15 2007 +0000
-|  summary:     add epsilon
-|
-o  changeset:   4:fc51727b28fe
-|  user:        name <test@example.com>
-|  date:        Mon Jan 01 00:00:14 2007 +0000
-|  summary:     add delta
-|
-o  changeset:   3:8da3ab8b31d0
-|  user:        <test@example.com>
-|  date:        Mon Jan 01 00:00:13 2007 +0000
-|  summary:     add gamma
-|
-o  changeset:   2:92d33c0dd6e1
-|  user:        test <test@example.com> (comment)
-|  date:        Mon Jan 01 00:00:12 2007 +0000
-|  summary:     modify beta
-|
-o  changeset:   1:0564f526fb0f
-|  user:        test
-|  date:        Mon Jan 01 00:00:11 2007 +0000
-|  summary:     add beta
-|
-o  changeset:   0:3442585be8a6
-   tag:         default/not-master
-   user:        test <test@example.org>
-   date:        Mon Jan 01 00:00:10 2007 +0000
-   summary:     add alpha
-
-commit 1e03e913eca571b86ee06d3c1ddd795dde9ca917
-Author: test ?test@example.com <test ?test@example.com>
-Date:   Mon Jan 1 00:00:18 2007 +0000
-
-    add theta
-
-commit 8c878c9764e96e67ed9f62b3f317d156bf71bc52
-Author: test <test@example.com>
-Date:   Mon Jan 1 00:00:17 2007 +0000
-
-    add eta
-
-commit d21e26b48c6136340dd1212bb45ba0e9debb130c
-Author: test <none@none>
-Date:   Mon Jan 1 00:00:16 2007 +0000
-
-    add zeta
-
-commit ee985f124d2f13ee8ad2a346a6d1b0ada8b0d491
-Author: name <test@example.com>
-Date:   Mon Jan 1 00:00:15 2007 +0000
-
-    add epsilon
-
-commit d16592507ac83a6a633b90ca255f65e5d024f0bc
-Author: name <test@example.com>
-Date:   Mon Jan 1 00:00:14 2007 +0000
-
-    add delta
-
-commit fee30180efc4943fb916de04fcf6a64b638d9325
-Author:  <test@example.com>
-Date:   Mon Jan 1 00:00:13 2007 +0000
-
-    add gamma
-
-commit 2b9ec6a47b93191986a79eeb771e461c4508c7c4
-Author: test ext:(%20%28comment%29) <test@example.com>
-Date:   Mon Jan 1 00:00:12 2007 +0000
-
-    modify beta
-
-commit cffa0e8d8ad5f284c69c898c0f3c1e32d078af8a
-Author: test <none@none>
-Date:   Mon Jan 1 00:00:11 2007 +0000
-
-    add beta
-
-commit 7eeab2ea75ec1ac0ff3d500b5b6f8a3447dd7c03
-Author: test <test@example.org>
-Date:   Mon Jan 1 00:00:10 2007 +0000
-
-    add alpha
old mode 100755
new mode 100644
rename from tests/test-hg-author
rename to tests/test-hg-author.t
--- a/tests/test-hg-author
+++ b/tests/test-hg-author.t
@@ -1,118 +1,232 @@
-#!/bin/sh
-
-# Fails for some reason, need to investigate
-# "$TESTDIR/hghave" git || exit 80
+Load commonly used test logic
+  $ . "$TESTDIR/testutil"
 
-# bail if the user does not have dulwich
-python -c 'import dulwich, dulwich.repo' || exit 80
-
-# bail early if the user is already running git-daemon
-echo hi | nc localhost 9418 2>/dev/null && exit 80
+  $ git init gitrepo
+  Initialized empty Git repository in $TESTTMP/gitrepo/.git/
+  $ cd gitrepo
+  $ echo alpha > alpha
+  $ git add alpha
+  $ fn_git_commit -m "add alpha"
+  $ git checkout -b not-master
+  Switched to a new branch 'not-master'
 
-echo "[extensions]" >> $HGRCPATH
-echo "hggit=$(echo $(dirname $(dirname $0)))/hggit" >> $HGRCPATH
-echo 'hgext.graphlog =' >> $HGRCPATH
-echo 'hgext.bookmarks =' >> $HGRCPATH
+  $ cd ..
+  $ hg clone gitrepo hgrepo | grep -v '^updating'
+  importing git objects into hg
+  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
 
-cat >> $HGRCPATH <<EOF
+  $ cd hgrepo
+  $ hg co master
+  0 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  $ echo beta > beta
+  $ hg add beta
+  $ fn_hg_commit -u "test" -m 'add beta'
+  $ hg push
+  pushing to $TESTTMP/gitrepo
+  searching for changes
 
-[bookmarks]
-track.current = True
-EOF
-
+  $ echo gamma >> beta
+  $ fn_hg_commit -u "test <test@example.com> (comment)" -m 'modify beta'
+  $ hg push
+  pushing to $TESTTMP/gitrepo
+  searching for changes
 
-GIT_AUTHOR_NAME='test'; export GIT_AUTHOR_NAME
-GIT_AUTHOR_EMAIL='test@example.org'; export GIT_AUTHOR_EMAIL
-GIT_AUTHOR_DATE="2007-01-01 00:00:00 +0000"; export GIT_AUTHOR_DATE
-GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME"; export GIT_COMMITTER_NAME
-GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"; export GIT_COMMITTER_EMAIL
-GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"; export GIT_COMMITTER_DATE
+  $ echo gamma > gamma
+  $ hg add gamma
+  $ fn_hg_commit -u "<test@example.com>" -m 'add gamma'
+  $ hg push
+  pushing to $TESTTMP/gitrepo
+  searching for changes
+
+  $ echo delta > delta
+  $ hg add delta
+  $ fn_hg_commit -u "name<test@example.com>" -m 'add delta'
+  $ hg push
+  pushing to $TESTTMP/gitrepo
+  searching for changes
+
+  $ echo epsilon > epsilon
+  $ hg add epsilon
+  $ fn_hg_commit -u "name <test@example.com" -m 'add epsilon'
+  $ hg push
+  pushing to $TESTTMP/gitrepo
+  searching for changes
 
-count=10
-commit()
-{
-    GIT_AUTHOR_DATE="2007-01-01 00:00:$count +0000"
-    GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"
-    git commit "$@" >/dev/null 2>/dev/null || echo "git commit error"
-    count=`expr $count + 1`
-}
-hgcommit()
-{
-    HGDATE="2007-01-01 00:00:$count +0000"
-    hg commit -d "$HGDATE" "$@" >/dev/null 2>/dev/null || echo "hg commit error"
-    count=`expr $count + 1`
-}
+  $ echo zeta > zeta
+  $ hg add zeta
+  $ fn_hg_commit -u " test " -m 'add zeta'
+  $ hg push
+  pushing to $TESTTMP/gitrepo
+  searching for changes
 
-mkdir gitrepo
-cd gitrepo
-git init | python -c "import sys; print sys.stdin.read().replace('$(dirname $(pwd))/', '')"
+  $ echo eta > eta
+  $ hg add eta
+  $ fn_hg_commit -u "test < test@example.com >" -m 'add eta'
+  $ hg push
+  pushing to $TESTTMP/gitrepo
+  searching for changes
 
-echo alpha > alpha
-git add alpha
-commit -m "add alpha"
-git checkout -b not-master
+  $ echo theta > theta
+  $ hg add theta
+  $ fn_hg_commit -u "test >test@example.com>" -m 'add theta'
+  $ hg push
+  pushing to $TESTTMP/gitrepo
+  searching for changes
 
-# dulwich does not presently support local git repos, workaround
-cd ..
-git daemon --base-path="$(pwd)"\
- --listen=localhost\
- --export-all\
- --pid-file="$DAEMON_PIDS" \
- --detach --reuseaddr \
- --enable=receive-pack
-
-hg clone git://localhost/gitrepo hgrepo | grep -v '^updating'
-
-cd hgrepo
-hg co master
-echo beta > beta
-hg add beta
-hgcommit -u "test" -m 'add beta'
-hg push
-
-echo gamma >> beta
-hgcommit -u "test <test@example.com> (comment)" -m 'modify beta'
-hg push
-
-echo gamma > gamma
-hg add gamma
-hgcommit -u "<test@example.com>" -m 'add gamma'
-hg push
-
-echo delta > delta
-hg add delta
-hgcommit -u "name<test@example.com>" -m 'add delta'
-hg push
+  $ hg log --graph | egrep -v ': *(not-master|master)'
+  @  changeset:   8:d3c51ce68cfd
+  |  tag:         default/master
+  |  tag:         tip
+  |  user:        test >test@example.com>
+  |  date:        Mon Jan 01 00:00:18 2007 +0000
+  |  summary:     add theta
+  |
+  o  changeset:   7:b90e988091a2
+  |  user:        test < test@example.com >
+  |  date:        Mon Jan 01 00:00:17 2007 +0000
+  |  summary:     add eta
+  |
+  o  changeset:   6:7ede2f971cae
+  |  user:        test
+  |  date:        Mon Jan 01 00:00:16 2007 +0000
+  |  summary:     add zeta
+  |
+  o  changeset:   5:1454a94056ec
+  |  user:        name <test@example.com
+  |  date:        Mon Jan 01 00:00:15 2007 +0000
+  |  summary:     add epsilon
+  |
+  o  changeset:   4:a045fd599678
+  |  user:        name<test@example.com>
+  |  date:        Mon Jan 01 00:00:14 2007 +0000
+  |  summary:     add delta
+  |
+  o  changeset:   3:8da3ab8b31d0
+  |  user:        <test@example.com>
+  |  date:        Mon Jan 01 00:00:13 2007 +0000
+  |  summary:     add gamma
+  |
+  o  changeset:   2:92d33c0dd6e1
+  |  user:        test <test@example.com> (comment)
+  |  date:        Mon Jan 01 00:00:12 2007 +0000
+  |  summary:     modify beta
+  |
+  o  changeset:   1:0564f526fb0f
+  |  user:        test
+  |  date:        Mon Jan 01 00:00:11 2007 +0000
+  |  summary:     add beta
+  |
+  o  changeset:   0:3442585be8a6
+     tag:         default/not-master
+     user:        test <test@example.org>
+     date:        Mon Jan 01 00:00:10 2007 +0000
+     summary:     add alpha
+  
 
-echo epsilon > epsilon
-hg add epsilon
-hgcommit -u "name <test@example.com" -m 'add epsilon'
-hg push
-
-echo zeta > zeta
-hg add zeta
-hgcommit -u " test " -m 'add zeta'
-hg push
-
-echo eta > eta
-hg add eta
-hgcommit -u "test < test@example.com >" -m 'add eta'
-hg push
-
-echo theta > theta
-hg add theta
-hgcommit -u "test >test@example.com>" -m 'add theta'
-hg push
-
-hg log --graph | egrep -v ': *(not-master|master)'
-
-cd ..
-hg clone git://localhost/gitrepo hgrepo2 | grep -v '^updating'
-cd hgrepo2
-hg log --graph | egrep -v ': *(not-master|master)'
-
-cd ..
-cd gitrepo
-git log --pretty=medium master
-
-cd ..
+  $ cd ..
+  $ hg clone gitrepo hgrepo2 | grep -v '^updating'
+  importing git objects into hg
+  8 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  $ hg -R hgrepo2 log --graph | egrep -v ': *(not-master|master)'
+  @  changeset:   8:efec0270e295
+  |  tag:         default/master
+  |  tag:         tip
+  |  user:        test ?test@example.com <test ?test@example.com>
+  |  date:        Mon Jan 01 00:00:18 2007 +0000
+  |  summary:     add theta
+  |
+  o  changeset:   7:8ab87d5066e4
+  |  user:        test <test@example.com>
+  |  date:        Mon Jan 01 00:00:17 2007 +0000
+  |  summary:     add eta
+  |
+  o  changeset:   6:ff226cc916bd
+  |  user:        test
+  |  date:        Mon Jan 01 00:00:16 2007 +0000
+  |  summary:     add zeta
+  |
+  o  changeset:   5:5f1557c62c53
+  |  user:        name <test@example.com>
+  |  date:        Mon Jan 01 00:00:15 2007 +0000
+  |  summary:     add epsilon
+  |
+  o  changeset:   4:fc51727b28fe
+  |  user:        name <test@example.com>
+  |  date:        Mon Jan 01 00:00:14 2007 +0000
+  |  summary:     add delta
+  |
+  o  changeset:   3:8da3ab8b31d0
+  |  user:        <test@example.com>
+  |  date:        Mon Jan 01 00:00:13 2007 +0000
+  |  summary:     add gamma
+  |
+  o  changeset:   2:92d33c0dd6e1
+  |  user:        test <test@example.com> (comment)
+  |  date:        Mon Jan 01 00:00:12 2007 +0000
+  |  summary:     modify beta
+  |
+  o  changeset:   1:0564f526fb0f
+  |  user:        test
+  |  date:        Mon Jan 01 00:00:11 2007 +0000
+  |  summary:     add beta
+  |
+  o  changeset:   0:3442585be8a6
+     tag:         default/not-master
+     user:        test <test@example.org>
+     date:        Mon Jan 01 00:00:10 2007 +0000
+     summary:     add alpha
+  
+  $ git --git-dir=gitrepo/.git log --pretty=medium master
+  commit 1e03e913eca571b86ee06d3c1ddd795dde9ca917
+  Author: test ?test@example.com <test ?test@example.com>
+  Date:   Mon Jan 1 00:00:18 2007 +0000
+  
+      add theta
+  
+  commit 8c878c9764e96e67ed9f62b3f317d156bf71bc52
+  Author: test <test@example.com>
+  Date:   Mon Jan 1 00:00:17 2007 +0000
+  
+      add eta
+  
+  commit d21e26b48c6136340dd1212bb45ba0e9debb130c
+  Author: test <none@none>
+  Date:   Mon Jan 1 00:00:16 2007 +0000
+  
+      add zeta
+  
+  commit ee985f124d2f13ee8ad2a346a6d1b0ada8b0d491
+  Author: name <test@example.com>
+  Date:   Mon Jan 1 00:00:15 2007 +0000
+  
+      add epsilon
+  
+  commit d16592507ac83a6a633b90ca255f65e5d024f0bc
+  Author: name <test@example.com>
+  Date:   Mon Jan 1 00:00:14 2007 +0000
+  
+      add delta
+  
+  commit fee30180efc4943fb916de04fcf6a64b638d9325
+  Author:  <test@example.com>
+  Date:   Mon Jan 1 00:00:13 2007 +0000
+  
+      add gamma
+  
+  commit 2b9ec6a47b93191986a79eeb771e461c4508c7c4
+  Author: test ext:(%20%28comment%29) <test@example.com>
+  Date:   Mon Jan 1 00:00:12 2007 +0000
+  
+      modify beta
+  
+  commit cffa0e8d8ad5f284c69c898c0f3c1e32d078af8a
+  Author: test <none@none>
+  Date:   Mon Jan 1 00:00:11 2007 +0000
+  
+      add beta
+  
+  commit 7eeab2ea75ec1ac0ff3d500b5b6f8a3447dd7c03
+  Author: test <test@example.org>
+  Date:   Mon Jan 1 00:00:10 2007 +0000
+  
+      add alpha
deleted file mode 100644
--- a/tests/test-hg-branch.out
+++ /dev/null
@@ -1,55 +0,0 @@
-Initialized empty Git repository in gitrepo/.git/
-
-Switched to a new branch 'not-master'
-importing git objects into hg
-1 files updated, 0 files merged, 0 files removed, 0 files unresolved
-0 files updated, 0 files merged, 0 files removed, 0 files unresolved
-pushing to git://localhost/gitrepo
-exporting hg objects to git
-creating and sending data
-    default::refs/heads/master => GIT:05c2bcbe
-marked working directory as branch gamma
-pushing to git://localhost/gitrepo
-exporting hg objects to git
-creating and sending data
-    default::refs/heads/master => GIT:296802ef
-@  changeset:   2:05aed681ccb3
-|  branch:      gamma
-|  tag:         default/master
-|  tag:         tip
-|  user:        test
-|  date:        Mon Jan 01 00:00:12 2007 +0000
-|  summary:     started branch gamma
-|
-o  changeset:   1:a31e374801c9
-|  user:        test
-|  date:        Mon Jan 01 00:00:11 2007 +0000
-|  summary:     rename alpha to beta
-|
-o  changeset:   0:3442585be8a6
-   tag:         default/not-master
-   user:        test <test@example.org>
-   date:        Mon Jan 01 00:00:10 2007 +0000
-   summary:     add alpha
-
-importing git objects into hg
-1 files updated, 0 files merged, 0 files removed, 0 files unresolved
-o  changeset:   2:05aed681ccb3
-|  branch:      gamma
-|  tag:         default/master
-|  tag:         tip
-|  user:        test
-|  date:        Mon Jan 01 00:00:12 2007 +0000
-|  summary:     started branch gamma
-|
-@  changeset:   1:a31e374801c9
-|  user:        test
-|  date:        Mon Jan 01 00:00:11 2007 +0000
-|  summary:     rename alpha to beta
-|
-o  changeset:   0:3442585be8a6
-   tag:         default/not-master
-   user:        test <test@example.org>
-   date:        Mon Jan 01 00:00:10 2007 +0000
-   summary:     add alpha
-
old mode 100755
new mode 100644
rename from tests/test-hg-branch
rename to tests/test-hg-branch.t
--- a/tests/test-hg-branch
+++ b/tests/test-hg-branch.t
@@ -1,85 +1,78 @@
-#!/bin/sh
-
-# Fails for some reason, need to investigate
-# "$TESTDIR/hghave" git || exit 80
+Load commonly used test logic
+  $ . "$TESTDIR/testutil"
 
-# bail if the user does not have dulwich
-python -c 'import dulwich, dulwich.repo' || exit 80
-
-# bail early if the user is already running git-daemon
-echo hi | nc localhost 9418 2>/dev/null && exit 80
+  $ git init gitrepo
+  Initialized empty Git repository in $TESTTMP/gitrepo/.git/
+  $ cd gitrepo
+  $ echo alpha > alpha
+  $ git add alpha
+  $ fn_git_commit -m "add alpha"
+  $ git checkout -b not-master
+  Switched to a new branch 'not-master'
 
-echo "[extensions]" >> $HGRCPATH
-echo "hggit=$(echo $(dirname $(dirname $0)))/hggit" >> $HGRCPATH
-echo 'hgext.graphlog =' >> $HGRCPATH
-echo 'hgext.bookmarks =' >> $HGRCPATH
-cat >> $HGRCPATH <<EOF
-
-[bookmarks]
-track.current = True
-EOF
+  $ cd ..
+  $ hg clone gitrepo hgrepo | grep -v '^updating'
+  importing git objects into hg
+  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
 
-GIT_AUTHOR_NAME='test'; export GIT_AUTHOR_NAME
-GIT_AUTHOR_EMAIL='test@example.org'; export GIT_AUTHOR_EMAIL
-GIT_AUTHOR_DATE="2007-01-01 00:00:00 +0000"; export GIT_AUTHOR_DATE
-GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME"; export GIT_COMMITTER_NAME
-GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"; export GIT_COMMITTER_EMAIL
-GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"; export GIT_COMMITTER_DATE
+  $ cd hgrepo
+  $ hg co master
+  0 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  $ hg mv alpha beta
+  $ fn_hg_commit -m 'rename alpha to beta'
+  $ hg push
+  pushing to $TESTTMP/gitrepo
+  searching for changes
 
-# TODO stop using this when we're 1.5 only
-filterhash="sed s/71414c4e3c6f/a31e374801c9/;s/698615204564/d93a72262a83/"
-filterhash="$filterhash;s/d93a72262a83/05aed681ccb3/"
+  $ hg branch gamma | grep -v 'permanent and global'
+  marked working directory as branch gamma
+  $ fn_hg_commit -m 'started branch gamma'
+  $ hg push
+  pushing to $TESTTMP/gitrepo
+  searching for changes
 
-count=10
-commit()
-{
-    GIT_AUTHOR_DATE="2007-01-01 00:00:$count +0000"
-    GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"
-    git commit "$@" >/dev/null 2>/dev/null || echo "git commit error"
-    count=`expr $count + 1`
-}
-hgcommit()
-{
-    HGDATE="2007-01-01 00:00:$count +0000"
-    hg commit -d "$HGDATE" "$@" >/dev/null 2>/dev/null || echo "hg commit error"
-    count=`expr $count + 1`
-}
-
-mkdir gitrepo
-cd gitrepo
-git init | python -c "import sys; print sys.stdin.read().replace('$(dirname $(pwd))/', '')"
-
-echo alpha > alpha
-git add alpha
-commit -m "add alpha"
-git checkout -b not-master
+  $ hg log --graph | egrep -v ': *(not-master|master)'
+  @  changeset:   2:05aed681ccb3
+  |  branch:      gamma
+  |  tag:         default/master
+  |  tag:         tip
+  |  user:        test
+  |  date:        Mon Jan 01 00:00:12 2007 +0000
+  |  summary:     started branch gamma
+  |
+  o  changeset:   1:a31e374801c9
+  |  user:        test
+  |  date:        Mon Jan 01 00:00:11 2007 +0000
+  |  summary:     rename alpha to beta
+  |
+  o  changeset:   0:3442585be8a6
+     tag:         default/not-master
+     user:        test <test@example.org>
+     date:        Mon Jan 01 00:00:10 2007 +0000
+     summary:     add alpha
+  
 
-# dulwich does not presently support local git repos, workaround
-cd ..
-git daemon --base-path="$(pwd)"\
- --listen=localhost\
- --export-all\
- --pid-file="$DAEMON_PIDS" \
- --detach --reuseaddr \
- --enable=receive-pack
-
-hg clone git://localhost/gitrepo hgrepo | grep -v '^updating'
-
-cd hgrepo
-hg co master
-hg mv alpha beta
-hgcommit -m 'rename alpha to beta'
-hg push
-
-hg branch gamma | grep -v 'permanent and global'
-hgcommit -m 'started branch gamma'
-hg push
-
-hg log --graph | $filterhash | egrep -v ': *(not-master|master)'
-
-cd ..
-hg clone git://localhost/gitrepo hgrepo2 | grep -v '^updating'
-cd hgrepo2
-hg log --graph | $filterhash | egrep -v ': *(not-master|master)'
-
-cd ..
+  $ cd ..
+  $ hg clone gitrepo hgrepo2 | grep -v '^updating'
+  importing git objects into hg
+  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  $ hg -R hgrepo2 log --graph | egrep -v ': *(not-master|master)'
+  o  changeset:   2:05aed681ccb3
+  |  branch:      gamma
+  |  tag:         default/master
+  |  tag:         tip
+  |  user:        test
+  |  date:        Mon Jan 01 00:00:12 2007 +0000
+  |  summary:     started branch gamma
+  |
+  @  changeset:   1:a31e374801c9
+  |  user:        test
+  |  date:        Mon Jan 01 00:00:11 2007 +0000
+  |  summary:     rename alpha to beta
+  |
+  o  changeset:   0:3442585be8a6
+     tag:         default/not-master
+     user:        test <test@example.org>
+     date:        Mon Jan 01 00:00:10 2007 +0000
+     summary:     add alpha
+  
deleted file mode 100644
--- a/tests/test-hg-tags.out
+++ /dev/null
@@ -1,45 +0,0 @@
-Initialized empty Git repository in gitrepo/.git/
-
-Switched to a new branch 'not-master'
-importing git objects into hg
-1 files updated, 0 files merged, 0 files removed, 0 files unresolved
-0 files updated, 0 files merged, 0 files removed, 0 files unresolved
-pushing to git://localhost/gitrepo
-exporting hg objects to git
-creating and sending data
-    default::refs/tags/alpha => GIT:7eeab2ea
-    default::refs/heads/master => GIT:9a2616b9
-@  changeset:   1:d529e9229f6d
-|  tag:         default/master
-|  tag:         tip
-|  user:        test
-|  date:        Mon Jan 01 00:00:11 2007 +0000
-|  summary:     Added tag alpha for changeset 3442585be8a6
-|
-o  changeset:   0:3442585be8a6
-   tag:         alpha
-   tag:         default/not-master
-   user:        test <test@example.org>
-   date:        Mon Jan 01 00:00:10 2007 +0000
-   summary:     add alpha
-
-% git should have the tag alpha
-alpha
-importing git objects into hg
-2 files updated, 0 files merged, 0 files removed, 0 files unresolved
-@  changeset:   1:d529e9229f6d
-|  tag:         default/master
-|  tag:         tip
-|  user:        test
-|  date:        Mon Jan 01 00:00:11 2007 +0000
-|  summary:     Added tag alpha for changeset 3442585be8a6
-|
-o  changeset:   0:3442585be8a6
-   tag:         alpha
-   tag:         default/not-master
-   user:        test <test@example.org>
-   date:        Mon Jan 01 00:00:10 2007 +0000
-   summary:     add alpha
-
-% the tag should be in .hgtags
-3442585be8a60c6cd476bbc4e45755339f2a23ef alpha
old mode 100755
new mode 100644
rename from tests/test-hg-tags
rename to tests/test-hg-tags.t
--- a/tests/test-hg-tags
+++ b/tests/test-hg-tags.t
@@ -1,85 +1,70 @@
-#!/bin/sh
-
-# Fails for some reason, need to investigate
-# "$TESTDIR/hghave" git || exit 80
+Load commonly used test logic
+  $ . "$TESTDIR/testutil"
 
-# bail if the user does not have dulwich
-python -c 'import dulwich, dulwich.repo' || exit 80
-
-# bail early if the user is already running git-daemon
-echo hi | nc localhost 9418 2>/dev/null && exit 80
+  $ git init gitrepo
+  Initialized empty Git repository in $TESTTMP/gitrepo/.git/
+  $ cd gitrepo
+  $ echo alpha > alpha
+  $ git add alpha
+  $ fn_git_commit -m "add alpha"
+  $ git checkout -b not-master
+  Switched to a new branch 'not-master'
 
-echo "[extensions]" >> $HGRCPATH
-echo "hggit=$(echo $(dirname $(dirname $0)))/hggit" >> $HGRCPATH
-echo 'hgext.graphlog =' >> $HGRCPATH
-echo 'hgext.bookmarks =' >> $HGRCPATH
-
-cat >> $HGRCPATH <<EOF
+  $ cd ..
+  $ hg clone gitrepo hgrepo | grep -v '^updating'
+  importing git objects into hg
+  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
 
-[bookmarks]
-track.current = True
-EOF
-
-GIT_AUTHOR_NAME='test'; export GIT_AUTHOR_NAME
-GIT_AUTHOR_EMAIL='test@example.org'; export GIT_AUTHOR_EMAIL
-GIT_AUTHOR_DATE="2007-01-01 00:00:00 +0000"; export GIT_AUTHOR_DATE
-GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME"; export GIT_COMMITTER_NAME
-GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"; export GIT_COMMITTER_EMAIL
-GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"; export GIT_COMMITTER_DATE
+  $ cd hgrepo
+  $ hg co master
+  0 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  $ fn_hg_tag alpha
+  $ hg push
+  pushing to $TESTTMP/gitrepo
+  searching for changes
 
-count=10
-commit()
-{
-    GIT_AUTHOR_DATE="2007-01-01 00:00:$count +0000"
-    GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"
-    git commit "$@" >/dev/null 2>/dev/null || echo "git commit error"
-    count=`expr $count + 1`
-}
-hgtag()
-{
-    HGDATE="2007-01-01 00:00:$count +0000"
-    hg tag -d "$HGDATE" "$@" >/dev/null 2>/dev/null || echo "hg commit error"
-    count=`expr $count + 1`
-}
+  $ hg log --graph | egrep -v ': *(not-master|master)'
+  @  changeset:   1:d529e9229f6d
+  |  tag:         default/master
+  |  tag:         tip
+  |  user:        test
+  |  date:        Mon Jan 01 00:00:11 2007 +0000
+  |  summary:     Added tag alpha for changeset 3442585be8a6
+  |
+  o  changeset:   0:3442585be8a6
+     tag:         alpha
+     tag:         default/not-master
+     user:        test <test@example.org>
+     date:        Mon Jan 01 00:00:10 2007 +0000
+     summary:     add alpha
+  
 
-mkdir gitrepo
-cd gitrepo
-git init | python -c "import sys; print sys.stdin.read().replace('$(dirname $(pwd))/', '')"
-
-echo alpha > alpha
-git add alpha
-commit -m "add alpha"
-git checkout -b not-master
+  $ cd ..
+  $ cd gitrepo
+git should have the tag alpha
+  $ git tag -l
+  alpha
 
-# dulwich does not presently support local git repos, workaround
-cd ..
-git daemon --base-path="$(pwd)"\
- --listen=localhost\
- --export-all\
- --pid-file="$DAEMON_PIDS" \
- --detach --reuseaddr \
- --enable=receive-pack
-
-hg clone git://localhost/gitrepo hgrepo | grep -v '^updating'
-
-cd hgrepo
-hg co master
-hgtag alpha
-hg push
+  $ cd ..
+  $ hg clone gitrepo hgrepo2 | grep -v '^updating'
+  importing git objects into hg
+  2 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  $ hg -R hgrepo2 log --graph | egrep -v ': *(not-master|master)'
+  @  changeset:   1:d529e9229f6d
+  |  tag:         default/master
+  |  tag:         tip
+  |  user:        test
+  |  date:        Mon Jan 01 00:00:11 2007 +0000
+  |  summary:     Added tag alpha for changeset 3442585be8a6
+  |
+  o  changeset:   0:3442585be8a6
+     tag:         alpha
+     tag:         default/not-master
+     user:        test <test@example.org>
+     date:        Mon Jan 01 00:00:10 2007 +0000
+     summary:     add alpha
+  
 
-hg log --graph | egrep -v ': *(not-master|master)'
-
-cd ..
-cd gitrepo
-echo % git should have the tag alpha
-git tag -l
-
-cd ..
-hg clone git://localhost/gitrepo hgrepo2 | grep -v '^updating'
-cd hgrepo2
-hg log --graph | egrep -v ': *(not-master|master)'
-
-echo % the tag should be in .hgtags
-cat .hgtags
-
-cd ..
+the tag should be in .hgtags
+  $ cat hgrepo2/.hgtags
+  3442585be8a60c6cd476bbc4e45755339f2a23ef alpha
deleted file mode 100644
--- a/tests/test-incoming.out
+++ /dev/null
@@ -1,81 +0,0 @@
-Initialized empty Git repository in gitrepo/.git/
-
-importing git objects into hg
-1 files updated, 0 files merged, 0 files removed, 0 files unresolved
-comparing with git://localhost/gitrepo
-comparing with git://localhost/gitrepo
-changeset:   1:9497a4ee62e1
-user:        test <test@example.org>
-date:        Mon Jan 01 00:00:11 2007 +0000
-summary:     add beta
-
-Switched to a new branch 'b1'
-comparing with git://localhost/gitrepo
-changeset:   1:9497a4ee62e1
-user:        test <test@example.org>
-date:        Mon Jan 01 00:00:11 2007 +0000
-summary:     add beta
-
-diff -r 3442585be8a6 -r 9497a4ee62e1 beta
---- /dev/null	Thu Jan 01 00:00:00 1970 +0000
-+++ b/beta	Mon Jan 01 00:00:11 2007 +0000
-@@ -0,0 +1,1 @@
-+beta
-
-changeset:   2:9865e289be73
-tag:         t1
-parent:      0:3442585be8a6
-user:        test <test@example.org>
-date:        Mon Jan 01 00:00:12 2007 +0000
-summary:     add d/gamma
-
-diff -r 3442585be8a6 -r 9865e289be73 d/gamma
---- /dev/null	Thu Jan 01 00:00:00 1970 +0000
-+++ b/d/gamma	Mon Jan 01 00:00:12 2007 +0000
-@@ -0,0 +1,1 @@
-+gamma
-
-changeset:   3:5202f48c20c9
-user:        test <test@example.org>
-date:        Mon Jan 01 00:00:13 2007 +0000
-summary:     add d/gamma line 2
-
-diff -r 9865e289be73 -r 5202f48c20c9 d/gamma
---- a/d/gamma	Mon Jan 01 00:00:12 2007 +0000
-+++ b/d/gamma	Mon Jan 01 00:00:13 2007 +0000
-@@ -1,1 +1,2 @@
- gamma
-+gamma 2
-
-% incoming -r
-comparing with git://localhost/gitrepo
-changeset:   1:9497a4ee62e1
-user:        test <test@example.org>
-date:        Mon Jan 01 00:00:11 2007 +0000
-summary:     add beta
-
-comparing with git://localhost/gitrepo
-changeset:   1:9865e289be73
-tag:         t1
-user:        test <test@example.org>
-date:        Mon Jan 01 00:00:12 2007 +0000
-summary:     add d/gamma
-
-changeset:   2:5202f48c20c9
-user:        test <test@example.org>
-date:        Mon Jan 01 00:00:13 2007 +0000
-summary:     add d/gamma line 2
-
-comparing with git://localhost/gitrepo
-changeset:   1:9865e289be73
-tag:         t1
-user:        test <test@example.org>
-date:        Mon Jan 01 00:00:12 2007 +0000
-summary:     add d/gamma
-
-% nothing incoming after pull
-pulling from git://localhost/gitrepo
-importing git objects into hg
-(run 'hg heads' to see heads, 'hg merge' to merge)
-comparing with git://localhost/gitrepo
-done
rename from tests/test-incoming
rename to tests/test-incoming.t
--- a/tests/test-incoming
+++ b/tests/test-incoming.t
@@ -1,97 +1,122 @@
-#!/bin/sh
-
-# Fails for some reason, need to investigate
-# "$TESTDIR/hghave" git || exit 80
-
-# bail if the user does not have dulwich
-python -c 'import dulwich, dulwich.repo' || exit 80
+Load commonly used test logic
+  $ . "$TESTDIR/testutil"
 
-# This test only works on hg 1.7 and later
-python -c 'from mercurial import util ; assert \
- util.version() != "unknown" and util.version() > "1.7"' || exit 80
+  $ git init gitrepo
+  Initialized empty Git repository in $TESTTMP/gitrepo/.git/
+  $ cd gitrepo
+  $ echo alpha > alpha
+  $ git add alpha
+  $ fn_git_commit -m "add alpha"
 
-# bail early if the user is already running git-daemon
-echo hi | nc localhost 9418 2>/dev/null && exit 80
+  $ cd ..
+  $ hg clone gitrepo hgrepo | grep -v '^updating'
+  importing git objects into hg
+  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
 
-echo "[extensions]" >> $HGRCPATH
-echo "hggit=$(echo $(dirname $(dirname $0)))/hggit" >> $HGRCPATH
-echo 'hgext.graphlog =' >> $HGRCPATH
-echo 'hgext.bookmarks =' >> $HGRCPATH
+  $ hg -R hgrepo incoming | grep -v 'no changes found' | grep -v 'bookmark:'
+  comparing with $TESTTMP/gitrepo
 
-GIT_AUTHOR_NAME='test'; export GIT_AUTHOR_NAME
-GIT_AUTHOR_EMAIL='test@example.org'; export GIT_AUTHOR_EMAIL
-GIT_AUTHOR_DATE="2007-01-01 00:00:00 +0000"; export GIT_AUTHOR_DATE
-GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME"; export GIT_COMMITTER_NAME
-GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"; export GIT_COMMITTER_EMAIL
-GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"; export GIT_COMMITTER_DATE
+  $ cd gitrepo
+  $ echo beta > beta
+  $ git add beta
+  $ fn_git_commit -m 'add beta'
+  $ cd ..
 
-count=10
-commit()
-{
-    GIT_AUTHOR_DATE="2007-01-01 00:00:$count +0000"
-    GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"
-    git commit "$@" >/dev/null 2>/dev/null || echo "git commit error"
-    count=`expr $count + 1`
-}
-hgcommit()
-{
-    HGDATE="2007-01-01 00:00:$count +0000"
-    hg commit -d "$HGDATE" "$@" >/dev/null 2>/dev/null || echo "hg commit error"
-    count=`expr $count + 1`
-}
+  $ hg -R hgrepo incoming | grep -v 'no changes found' | grep -v 'bookmark:'
+  comparing with $TESTTMP/gitrepo
+  changeset:   1:9497a4ee62e1
+  user:        test <test@example.org>
+  date:        Mon Jan 01 00:00:11 2007 +0000
+  summary:     add beta
+  
 
-mkdir gitrepo
-cd gitrepo
-git init | python -c "import sys; print sys.stdin.read().replace('$(dirname $(pwd))/', '')"
+  $ cd gitrepo
+  $ git checkout -b b1 HEAD^
+  Switched to a new branch 'b1'
+  $ mkdir d
+  $ echo gamma > d/gamma
+  $ git add d/gamma
+  $ fn_git_commit -m'add d/gamma'
+  $ git tag t1
 
-echo alpha > alpha
-git add alpha
-commit -m "add alpha"
-
-# dulwich does not presently support local git repos, workaround
-cd ..
-git daemon --base-path="$(pwd)"\
- --listen=localhost\
- --export-all\
- --pid-file="$DAEMON_PIDS" \
- --detach --reuseaddr \
- --enable=receive-pack
-
-hg clone git://localhost/gitrepo hgrepo | grep -v '^updating'
-
-cd hgrepo
-hg incoming | grep -v 'no changes found' | grep -v 'bookmark:'
-
-cd ../gitrepo
-echo beta > beta
-git add beta
-commit -m 'add beta'
-
-cd ../hgrepo
-hg incoming | grep -v 'no changes found' | grep -v 'bookmark:'
+  $ echo gamma 2 >> d/gamma
+  $ git add d/gamma
+  $ fn_git_commit -m'add d/gamma line 2'
+  $ cd ../hgrepo
+  $ hg incoming -p | grep -v 'no changes found' | grep -v 'bookmark:'
+  comparing with $TESTTMP/gitrepo
+  changeset:   1:9497a4ee62e1
+  user:        test <test@example.org>
+  date:        Mon Jan 01 00:00:11 2007 +0000
+  summary:     add beta
+  
+  diff -r 3442585be8a6 -r 9497a4ee62e1 beta
+  --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+  +++ b/beta	Mon Jan 01 00:00:11 2007 +0000
+  @@ -0,0 +1,1 @@
+  +beta
+  
+  changeset:   2:9865e289be73
+  tag:         t1
+  parent:      0:3442585be8a6
+  user:        test <test@example.org>
+  date:        Mon Jan 01 00:00:12 2007 +0000
+  summary:     add d/gamma
+  
+  diff -r 3442585be8a6 -r 9865e289be73 d/gamma
+  --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+  +++ b/d/gamma	Mon Jan 01 00:00:12 2007 +0000
+  @@ -0,0 +1,1 @@
+  +gamma
+  
+  changeset:   3:5202f48c20c9
+  user:        test <test@example.org>
+  date:        Mon Jan 01 00:00:13 2007 +0000
+  summary:     add d/gamma line 2
+  
+  diff -r 9865e289be73 -r 5202f48c20c9 d/gamma
+  --- a/d/gamma	Mon Jan 01 00:00:12 2007 +0000
+  +++ b/d/gamma	Mon Jan 01 00:00:13 2007 +0000
+  @@ -1,1 +1,2 @@
+   gamma
+  +gamma 2
+  
 
-cd ../gitrepo
-git checkout -b b1 HEAD^
-mkdir d
-echo gamma > d/gamma
-git add d/gamma
-commit -m'add d/gamma'
-git tag t1
-
-echo gamma 2 >> d/gamma
-git add d/gamma
-commit -m'add d/gamma line 2'
+incoming -r
+  $ hg incoming -r master | grep -v 'no changes found' | grep -v 'bookmark:'
+  comparing with $TESTTMP/gitrepo
+  changeset:   1:9497a4ee62e1
+  user:        test <test@example.org>
+  date:        Mon Jan 01 00:00:11 2007 +0000
+  summary:     add beta
+  
+  $ hg incoming -r b1 | grep -v 'no changes found' | grep -v 'bookmark:'
+  comparing with $TESTTMP/gitrepo
+  changeset:   1:9865e289be73
+  tag:         t1
+  user:        test <test@example.org>
+  date:        Mon Jan 01 00:00:12 2007 +0000
+  summary:     add d/gamma
+  
+  changeset:   2:5202f48c20c9
+  user:        test <test@example.org>
+  date:        Mon Jan 01 00:00:13 2007 +0000
+  summary:     add d/gamma line 2
+  
+  $ hg incoming -r t1 | grep -v 'no changes found' | grep -v 'bookmark:'
+  comparing with $TESTTMP/gitrepo
+  changeset:   1:9865e289be73
+  tag:         t1
+  user:        test <test@example.org>
+  date:        Mon Jan 01 00:00:12 2007 +0000
+  summary:     add d/gamma
+  
 
-cd ../hgrepo
-hg incoming -p | grep -v 'no changes found' | grep -v 'bookmark:'
-
-echo % incoming -r
-hg incoming -r master | grep -v 'no changes found' | grep -v 'bookmark:'
-hg incoming -r b1 | grep -v 'no changes found' | grep -v 'bookmark:'
-hg incoming -r t1 | grep -v 'no changes found' | grep -v 'bookmark:'
-
-echo % nothing incoming after pull
-hg pull
-hg incoming | grep -v 'no changes found' | grep -v 'bookmark:'
-
-echo 'done'
+nothing incoming after pull
+"adding remote bookmark" message was added in Mercurial 2.3
+  $ hg pull | grep -v "adding remote bookmark"
+  pulling from $TESTTMP/gitrepo
+  importing git objects into hg
+  (run 'hg heads' to see heads, 'hg merge' to merge)
+  $ hg incoming | grep -v 'no changes found' | grep -v 'bookmark:'
+  comparing with $TESTTMP/gitrepo
deleted file mode 100644
--- a/tests/test-keywords.out
+++ /dev/null
@@ -1,11 +0,0 @@
-Initialized empty Git repository in gitrepo/.git/
-
-importing git objects into hg
-2 files updated, 0 files merged, 0 files removed, 0 files unresolved
-2 a9da0c7c9bb7574b0f3139ab65cabac7468d6b8d a9da0c7c9bb7  
-1 7bcd915dc873c654b822f01b0a39269b2739e86d 7bcd915dc873 9497a4ee62e16ee641860d7677cdb2589ea15554 9497a4ee62e1
-0 3442585be8a60c6cd476bbc4e45755339f2a23ef 3442585be8a6 7eeab2ea75ec1ac0ff3d500b5b6f8a3447dd7c03 7eeab2ea75ec
-fromgit 0
-fromgit 1
-gitnode_existsA 1
-gitnode_existsB 0
rename from tests/test-keywords
rename to tests/test-keywords.t
--- a/tests/test-keywords
+++ b/tests/test-keywords.t
@@ -1,54 +1,35 @@
-#!/bin/sh
-
-# Fails for some reason, need to investigate
-# "$TESTDIR/hghave" git || exit 80
-
-# bail if the user does not have dulwich
-python -c 'import dulwich, dulwich.repo' || exit 80
-
-# bail early if the user is already running git-daemon
-echo hi | nc localhost 9418 2>/dev/null && exit 80
+Load commonly used test logic
+  $ . "$TESTDIR/testutil"
 
-echo "[extensions]" >> $HGRCPATH
-echo "hggit=$(echo $(dirname $(dirname $0)))/hggit" >> $HGRCPATH
-echo 'hgext.bookmarks =' >> $HGRCPATH
+  $ git init gitrepo
+  Initialized empty Git repository in $TESTTMP/gitrepo/.git/
+  $ cd gitrepo
+  $ echo alpha > alpha
+  $ git add alpha
+  $ fn_git_commit -m 'add alpha'
+  $ echo beta > beta
+  $ git add beta
+  $ fn_git_commit -m 'add beta'
 
-GIT_AUTHOR_NAME='test'; export GIT_AUTHOR_NAME
-GIT_AUTHOR_EMAIL='test@example.org'; export GIT_AUTHOR_EMAIL
-GIT_AUTHOR_DATE="2007-01-01 00:00:00 +0000"; export GIT_AUTHOR_DATE
-GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME"; export GIT_COMMITTER_NAME
-GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"; export GIT_COMMITTER_EMAIL
-GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"; export GIT_COMMITTER_DATE
+  $ cd ..
 
-count=10
-commit()
-{
-    GIT_AUTHOR_DATE="2007-01-01 00:00:$count +0000"
-    GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"
-    git commit "$@" >/dev/null 2>/dev/null || echo "git commit error"
-    count=`expr $count + 1`
-}
+  $ hg clone gitrepo hgrepo | grep -v '^updating'
+  importing git objects into hg
+  2 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  $ cd hgrepo
+  $ echo gamma > gamma
+  $ hg add gamma
+  $ hg commit -m 'add gamma'
 
-mkdir gitrepo
-cd gitrepo
-git init | python -c "import sys; print sys.stdin.read().replace('$(dirname $(pwd))/', '')"
-echo alpha > alpha
-git add alpha
-commit -m 'add alpha'
-echo beta > beta
-git add beta
-commit -m 'add beta'
-
-cd ..
-
-hg clone gitrepo hgrepo | grep -v '^updating'
-cd hgrepo
-echo gamma > gamma
-hg add gamma
-hg commit -m 'add gamma'
-
-hg log --template "{rev} {node} {node|short} {gitnode} {gitnode|short}\n"
-hg log --template "fromgit {rev}\n" --rev "fromgit()"
-hg log --template "gitnode_existsA {rev}\n" --rev "gitnode(9497a4ee62e16ee641860d7677cdb2589ea15554)"
-hg log --template "gitnode_existsB {rev}\n" --rev "gitnode(7eeab2ea75ec)"
-hg log --template "gitnode_notexists {rev}\n" --rev "gitnode(1234567890ab)"
+  $ hg log --template "{rev} {node} {node|short} {gitnode} {gitnode|short}\n"
+  2 a9da0c7c9bb7574b0f3139ab65cabac7468d6b8d a9da0c7c9bb7  
+  1 7bcd915dc873c654b822f01b0a39269b2739e86d 7bcd915dc873 9497a4ee62e16ee641860d7677cdb2589ea15554 9497a4ee62e1
+  0 3442585be8a60c6cd476bbc4e45755339f2a23ef 3442585be8a6 7eeab2ea75ec1ac0ff3d500b5b6f8a3447dd7c03 7eeab2ea75ec
+  $ hg log --template "fromgit {rev}\n" --rev "fromgit()"
+  fromgit 0
+  fromgit 1
+  $ hg log --template "gitnode_existsA {rev}\n" --rev "gitnode(9497a4ee62e16ee641860d7677cdb2589ea15554)"
+  gitnode_existsA 1
+  $ hg log --template "gitnode_existsB {rev}\n" --rev "gitnode(7eeab2ea75ec)"
+  gitnode_existsB 0
+  $ hg log --template "gitnode_notexists {rev}\n" --rev "gitnode(1234567890ab)"
deleted file mode 100644
--- a/tests/test-merge.out
+++ /dev/null
@@ -1,53 +0,0 @@
-Initialized empty Git repository in gitrepo/.git/
-
-Switched to a new branch "beta"
-Switched to branch "master"
-Merge successful
- beta | 1 +
- 1 file changed, 1 insertion(+)
- create mode 100644 beta
-Initialized empty Git repository in gitrepo2/
-
-importing git objects into hg
-3 files updated, 0 files merged, 0 files removed, 0 files unresolved
-% clear the cache to be sure it is regenerated correctly
-clearing out the git cache data
-pushing to git://localhost/gitrepo2
-exporting hg objects to git
-creating and sending data
-% git log in repo pushed from hg
-commit 5806851511aaf3bfe813ae3a86c5027165fa9b96
-Merge: e5023f9 9497a4e
-Author: test <test@example.org>
-Date:   Mon Jan 1 00:00:12 2007 +0000
-
-    Merge branch 'beta'
-
-commit e5023f9e5cb24fdcec7b6c127cec45d8888e35a9
-Author: test <test@example.org>
-Date:   Mon Jan 1 00:00:12 2007 +0000
-
-    add gamma
-
-commit 9497a4ee62e16ee641860d7677cdb2589ea15554
-Author: test <test@example.org>
-Date:   Mon Jan 1 00:00:11 2007 +0000
-
-    add beta
-
-commit 7eeab2ea75ec1ac0ff3d500b5b6f8a3447dd7c03
-Author: test <test@example.org>
-Date:   Mon Jan 1 00:00:10 2007 +0000
-
-    add alpha
-commit 9497a4ee62e16ee641860d7677cdb2589ea15554
-Author: test <test@example.org>
-Date:   Mon Jan 1 00:00:11 2007 +0000
-
-    add beta
-
-commit 7eeab2ea75ec1ac0ff3d500b5b6f8a3447dd7c03
-Author: test <test@example.org>
-Date:   Mon Jan 1 00:00:10 2007 +0000
-
-    add alpha
old mode 100755
new mode 100644
rename from tests/test-merge
rename to tests/test-merge.t
--- a/tests/test-merge
+++ b/tests/test-merge.t
@@ -1,80 +1,84 @@
-#!/bin/sh
-
-# Fails for some reason, need to investigate
-# "$TESTDIR/hghave" git || exit 80
-
-# bail if the user does not have dulwich
-python -c 'import dulwich, dulwich.repo' || exit 80
+Load commonly used test logic
+  $ . "$TESTDIR/testutil"
 
-# bail early if the user is already running git-daemon
-echo hi | nc localhost 9418 2>/dev/null && exit 80
+  $ git init gitrepo
+  Initialized empty Git repository in $TESTTMP/gitrepo/.git/
+  $ cd gitrepo
+  $ echo alpha > alpha
+  $ git add alpha
+  $ fn_git_commit -m 'add alpha'
 
-echo "[extensions]" >> $HGRCPATH
-echo "hggit=$(echo $(dirname $(dirname $0)))/hggit" >> $HGRCPATH
-echo 'hgext.graphlog =' >> $HGRCPATH
-echo 'hgext.bookmarks =' >> $HGRCPATH
+  $ git checkout -b beta 2>&1 | sed s/\'/\"/g
+  Switched to a new branch "beta"
+  $ echo beta > beta
+  $ git add beta
+  $ fn_git_commit -m 'add beta'
 
-GIT_AUTHOR_NAME='test'; export GIT_AUTHOR_NAME
-GIT_AUTHOR_EMAIL='test@example.org'; export GIT_AUTHOR_EMAIL
-GIT_AUTHOR_DATE="2007-01-01 00:00:00 +0000"; export GIT_AUTHOR_DATE
-GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME"; export GIT_COMMITTER_NAME
-GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"; export GIT_COMMITTER_EMAIL
-GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"; export GIT_COMMITTER_DATE
+  $ git checkout master 2>&1 | sed s/\'/\"/g
+  Switched to branch "master"
+  $ echo gamma > gamma
+  $ git add gamma
+  $ fn_git_commit -m 'add gamma'
 
-count=10
-commit()
-{
-    GIT_AUTHOR_DATE="2007-01-01 00:00:$count +0000"
-    GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"
-    git commit "$@" >/dev/null 2>/dev/null || echo "git commit error" | sed 's/, 0 deletions(-)//'
-    count=`expr $count + 1`
-}
+clean merge
+  $ git merge beta | sed "s/the '//;s/' strategy//" | sed 's/^Merge.*recursive.*$/Merge successful/' | sed 's/files/file/;s/insertions/insertion/;s/, 0 deletions.*//' | sed 's/|  */| /'
+  Merge successful
+   beta | 1 +
+   1 file changed, 1 insertion(+)
+   create mode 100644 beta
 
-mkdir gitrepo
-cd gitrepo
-git init | python -c "import sys; print sys.stdin.read().replace('$(dirname $(pwd))/', '')"
-echo alpha > alpha
-git add alpha
-commit -m 'add alpha'
+  $ cd ..
+  $ git init --bare gitrepo2
+  Initialized empty Git repository in $TESTTMP/gitrepo2/
+
+  $ hg clone gitrepo hgrepo | grep -v '^updating'
+  importing git objects into hg
+  3 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  $ cd hgrepo
 
-git checkout -b beta 2>&1 | sed s/\'/\"/g
-echo beta > beta
-git add beta
-commit -m 'add beta'
-
-git checkout master 2>&1 | sed s/\'/\"/g
-echo gamma > gamma
-git add gamma
-commit -m 'add gamma'
-
-# clean merge
-git merge beta | sed "s/the '//;s/' strategy//" | sed 's/^Merge.*recursive.*$/Merge successful/' | sed 's/files/file/;s/insertions/insertion/;s/, 0 deletions.*//' | sed 's/|  */| /'
-
-cd ..
-mkdir gitrepo2
-cd gitrepo2
-git init --bare | python -c "import sys; print sys.stdin.read().replace('$(dirname $(pwd))/', '')"
+clear the cache to be sure it is regenerated correctly
+  $ hg gclear
+  clearing out the git cache data
+  $ hg push ../gitrepo2
+  pushing to ../gitrepo2
+  searching for changes
 
-# dulwich does not presently support local git repos, workaround
-cd ..
-git daemon --base-path="$(pwd)"\
- --listen=localhost\
- --export-all \
- --pid-file="$DAEMON_PIDS" \
- --detach --reuseaddr \
- --enable=receive-pack
-
-hg clone git://localhost/gitrepo hgrepo | grep -v '^updating'
-cd hgrepo
-
-echo % clear the cache to be sure it is regenerated correctly
-hg gclear
-hg push git://localhost/gitrepo2
-
-cd ..
-cd gitrepo2
-echo % git log in repo pushed from hg
-git log --pretty=medium master | sed 's/\.\.\.//g'
-git log --pretty=medium beta | sed 's/\.\.\.//g'
-
-cd ..
+  $ cd ..
+git log in repo pushed from hg
+  $ git --git-dir=gitrepo2 log --pretty=medium master | sed 's/\.\.\.//g'
+  commit 5806851511aaf3bfe813ae3a86c5027165fa9b96
+  Merge: e5023f9 9497a4e
+  Author: test <test@example.org>
+  Date:   Mon Jan 1 00:00:12 2007 +0000
+  
+      Merge branch 'beta'
+  
+  commit e5023f9e5cb24fdcec7b6c127cec45d8888e35a9
+  Author: test <test@example.org>
+  Date:   Mon Jan 1 00:00:12 2007 +0000
+  
+      add gamma
+  
+  commit 9497a4ee62e16ee641860d7677cdb2589ea15554
+  Author: test <test@example.org>
+  Date:   Mon Jan 1 00:00:11 2007 +0000
+  
+      add beta
+  
+  commit 7eeab2ea75ec1ac0ff3d500b5b6f8a3447dd7c03
+  Author: test <test@example.org>
+  Date:   Mon Jan 1 00:00:10 2007 +0000
+  
+      add alpha
+  $ git --git-dir=gitrepo2 log --pretty=medium beta | sed 's/\.\.\.//g'
+  commit 9497a4ee62e16ee641860d7677cdb2589ea15554
+  Author: test <test@example.org>
+  Date:   Mon Jan 1 00:00:11 2007 +0000
+  
+      add beta
+  
+  commit 7eeab2ea75ec1ac0ff3d500b5b6f8a3447dd7c03
+  Author: test <test@example.org>
+  Date:   Mon Jan 1 00:00:10 2007 +0000
+  
+      add alpha
deleted file mode 100644
--- a/tests/test-octopus.out
+++ /dev/null
@@ -1,69 +0,0 @@
-Initialized empty Git repository in gitrepo/.git/
-
-Switched to a new branch "branch1"
-Switched to a new branch "branch2"
-Switched to branch "master"
-Trying simple merge with branch1
-Trying simple merge with branch2
-Merge successful
- beta  | 1 +
- gamma | 1 +
- 2 files changed, 2 insertions(+)
- create mode 100644 beta
- create mode 100644 gamma
-Initialized empty Git repository in gitrepo2/
-
-importing git objects into hg
-4 files updated, 0 files merged, 0 files removed, 0 files unresolved
-@    5:3,4   6523aa9f4775   2007-01-01 00:00 +0000   test
-|\     Merge branches 'branch1' and 'branch2'
-| |
-| o    4:1,2   7f6c791a169f   2007-01-01 00:00 +0000   test
-| |\     Merge branches 'branch1' and 'branch2'
-| | |
-o | |  3:0   1436150b86c2   2007-01-01 00:00 +0000   test
-| | |    add delta
-| | |
-+---o  2:0   37c124f2d0a0   2007-01-01 00:00 +0000   test
-| |      add gamma
-| |
-| o  1   7bcd915dc873   2007-01-01 00:00 +0000   test
-|/     add beta
-|
-o  0   3442585be8a6   2007-01-01 00:00 +0000   test
-     add alpha
-
-clearing out the git cache data
-pushing to git://localhost/gitrepo2
-exporting hg objects to git
-creating and sending data
-commit f0c7ec180419a130636d0c333fc34c1462cab4b5
-Merge: d8e22dd 9497a4e e5023f9
-Author: test <test@example.org>
-Date:   Mon Jan 1 00:00:13 2007 +0000
-
-    Merge branches 'branch1' and 'branch2'
-
-commit d8e22ddb015d06460ccbb4508d2184c12c8a7c4c
-Author: test <test@example.org>
-Date:   Mon Jan 1 00:00:13 2007 +0000
-
-    add delta
-
-commit e5023f9e5cb24fdcec7b6c127cec45d8888e35a9
-Author: test <test@example.org>
-Date:   Mon Jan 1 00:00:12 2007 +0000
-
-    add gamma
-
-commit 9497a4ee62e16ee641860d7677cdb2589ea15554
-Author: test <test@example.org>
-Date:   Mon Jan 1 00:00:11 2007 +0000
-
-    add beta
-
-commit 7eeab2ea75ec1ac0ff3d500b5b6f8a3447dd7c03
-Author: test <test@example.org>
-Date:   Mon Jan 1 00:00:10 2007 +0000
-
-    add alpha
old mode 100755
new mode 100644
rename from tests/test-octopus
rename to tests/test-octopus.t
--- a/tests/test-octopus
+++ b/tests/test-octopus.t
@@ -1,82 +1,104 @@
-#!/bin/sh
-
-# Fails for some reason, need to investigate
-# "$TESTDIR/hghave" git || exit 80
-
-# bail if the user does not have dulwich
-python -c 'import dulwich, dulwich.repo' || exit 80
+Load commonly used test logic
+  $ . "$TESTDIR/testutil"
 
-# bail early if the user is already running git-daemon
-echo hi | nc localhost 9418 2>/dev/null && exit 80
+  $ git init gitrepo
+  Initialized empty Git repository in $TESTTMP/gitrepo/.git/
+  $ cd gitrepo
+  $ echo alpha > alpha
+  $ git add alpha
+  $ fn_git_commit -m 'add alpha'
 
-echo "[extensions]" >> $HGRCPATH
-echo "hggit=$(echo $(dirname $(dirname $0)))/hggit" >> $HGRCPATH
-echo 'hgext.graphlog =' >> $HGRCPATH
-echo 'hgext.bookmarks =' >> $HGRCPATH
+  $ git checkout -b branch1 2>&1 | sed s/\'/\"/g
+  Switched to a new branch "branch1"
+  $ echo beta > beta
+  $ git add beta
+  $ fn_git_commit -m 'add beta'
 
-GIT_AUTHOR_NAME='test'; export GIT_AUTHOR_NAME
-GIT_AUTHOR_EMAIL='test@example.org'; export GIT_AUTHOR_EMAIL
-GIT_AUTHOR_DATE="2007-01-01 00:00:00 +0000"; export GIT_AUTHOR_DATE
-GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME"; export GIT_COMMITTER_NAME
-GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"; export GIT_COMMITTER_EMAIL
-GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"; export GIT_COMMITTER_DATE
+  $ git checkout -b branch2 master 2>&1 | sed s/\'/\"/g
+  Switched to a new branch "branch2"
+  $ echo gamma > gamma
+  $ git add gamma
+  $ fn_git_commit -m 'add gamma'
+
+  $ git checkout master 2>&1 | sed s/\'/\"/g
+  Switched to branch "master"
+  $ echo delta > delta
+  $ git add delta
+  $ fn_git_commit -m 'add delta'
 
-count=10
-commit()
-{
-    GIT_AUTHOR_DATE="2007-01-01 00:00:$count +0000"
-    GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"
-    git commit "$@" >/dev/null 2>/dev/null || echo "git commit error" | sed 's/0 deletions(-)//'
-    count=`expr $count + 1`
-}
+  $ git merge branch1 branch2 | sed "s/the '//;s/' strategy//" | sed 's/^Merge.*octopus.*$/Merge successful/;s/, 0 deletions.*//'  | sed 's/|  */| /'
+  Trying simple merge with branch1
+  Trying simple merge with branch2
+  Merge successful
+   beta  | 1 +
+   gamma | 1 +
+   2 files changed, 2 insertions(+)
+   create mode 100644 beta
+   create mode 100644 gamma
 
-mkdir gitrepo
-cd gitrepo
-git init | python -c "import sys; print sys.stdin.read().replace('$(dirname $(pwd))/', '')"
-
-echo alpha > alpha
-git add alpha
-commit -m 'add alpha'
+  $ cd ..
+  $ git init --bare gitrepo2
+  Initialized empty Git repository in $TESTTMP/gitrepo2/
 
-git checkout -b branch1 2>&1 | sed s/\'/\"/g
-echo beta > beta
-git add beta
-commit -m 'add beta'
+  $ hg clone gitrepo hgrepo | grep -v '^updating'
+  importing git objects into hg
+  4 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  $ cd hgrepo
+  $ hg log --graph --style compact | sed 's/\[.*\]//g'
+  @    5:3,4   6523aa9f4775   2007-01-01 00:00 +0000   test
+  |\     Merge branches 'branch1' and 'branch2'
+  | |
+  | o    4:1,2   7f6c791a169f   2007-01-01 00:00 +0000   test
+  | |\     Merge branches 'branch1' and 'branch2'
+  | | |
+  o | |  3:0   1436150b86c2   2007-01-01 00:00 +0000   test
+  | | |    add delta
+  | | |
+  +---o  2:0   37c124f2d0a0   2007-01-01 00:00 +0000   test
+  | |      add gamma
+  | |
+  | o  1   7bcd915dc873   2007-01-01 00:00 +0000   test
+  |/     add beta
+  |
+  o  0   3442585be8a6   2007-01-01 00:00 +0000   test
+       add alpha
+  
 
-git checkout -b branch2 master 2>&1 | sed s/\'/\"/g
-echo gamma > gamma
-git add gamma
-commit -m 'add gamma'
-
-git checkout master 2>&1 | sed s/\'/\"/g
-echo delta > delta
-git add delta
-commit -m 'add delta'
-
-git merge branch1 branch2 | sed "s/the '//;s/' strategy//" | sed 's/^Merge.*octopus.*$/Merge successful/;s/, 0 deletions.*//'  | sed 's/|  */| /'
+  $ hg gclear
+  clearing out the git cache data
+  $ hg push ../gitrepo2
+  pushing to ../gitrepo2
+  searching for changes
+  $ cd ..
 
-cd ..
-mkdir gitrepo2
-cd gitrepo2
-git init --bare | python -c "import sys; print sys.stdin.read().replace('$(dirname $(pwd))/', '')"
-
-# dulwich does not presently support local git repos, workaround
-cd ..
-git daemon --base-path="$(pwd)"\
- --listen=localhost\
- --export-all\
- --pid-file="$DAEMON_PIDS" \
- --detach --reuseaddr \
- --enable=receive-pack
-
-hg clone git://localhost/gitrepo hgrepo | grep -v '^updating'
-cd hgrepo
-hg log --graph --style compact | sed 's/\[.*\]//g'
-
-hg gclear
-hg push git://localhost/gitrepo2
-
-cd ../gitrepo2
-git log --pretty=medium | sed s/\\.\\.\\.//g
-
-cd ..
+  $ git --git-dir=gitrepo2 log --pretty=medium | sed s/\\.\\.\\.//g
+  commit f0c7ec180419a130636d0c333fc34c1462cab4b5
+  Merge: d8e22dd 9497a4e e5023f9
+  Author: test <test@example.org>
+  Date:   Mon Jan 1 00:00:13 2007 +0000
+  
+      Merge branches 'branch1' and 'branch2'
+  
+  commit d8e22ddb015d06460ccbb4508d2184c12c8a7c4c
+  Author: test <test@example.org>
+  Date:   Mon Jan 1 00:00:13 2007 +0000
+  
+      add delta
+  
+  commit e5023f9e5cb24fdcec7b6c127cec45d8888e35a9
+  Author: test <test@example.org>
+  Date:   Mon Jan 1 00:00:12 2007 +0000
+  
+      add gamma
+  
+  commit 9497a4ee62e16ee641860d7677cdb2589ea15554
+  Author: test <test@example.org>
+  Date:   Mon Jan 1 00:00:11 2007 +0000
+  
+      add beta
+  
+  commit 7eeab2ea75ec1ac0ff3d500b5b6f8a3447dd7c03
+  Author: test <test@example.org>
+  Date:   Mon Jan 1 00:00:10 2007 +0000
+  
+      add alpha
deleted file mode 100644
--- a/tests/test-outgoing.out
+++ /dev/null
@@ -1,82 +0,0 @@
-Initialized empty Git repository in gitrepo/.git/
-
-importing git objects into hg
-1 files updated, 0 files merged, 0 files removed, 0 files unresolved
-comparing with git://localhost/gitrepo
-exporting hg objects to git
-changeset:   1:0564f526fb0f
-tag:         beta
-user:        test
-date:        Mon Jan 01 00:00:11 2007 +0000
-summary:     add beta
-
-changeset:   2:72f56395749d
-tag:         master
-tag:         tip
-user:        test
-date:        Mon Jan 01 00:00:12 2007 +0000
-summary:     add gamma
-
-comparing with git://localhost/gitrepo
-changeset:   1:0564f526fb0f
-tag:         beta
-user:        test
-date:        Mon Jan 01 00:00:11 2007 +0000
-summary:     add beta
-
-comparing with git://localhost/gitrepo
-changeset:   1:0564f526fb0f
-tag:         beta
-user:        test
-date:        Mon Jan 01 00:00:11 2007 +0000
-summary:     add beta
-
-changeset:   2:72f56395749d
-tag:         master
-tag:         tip
-user:        test
-date:        Mon Jan 01 00:00:12 2007 +0000
-summary:     add gamma
-
-% some more work on master from git
-Already on "master"
-% this will fail
-comparing with git://localhost/gitrepo
-abort: refs/heads/master changed on the server, please pull and merge before pushing
-% let's pull and try again
-pulling from git://localhost/gitrepo
-importing git objects into hg
-(run 'hg update' to get a working copy)
-comparing with git://localhost/gitrepo
-changeset:   1:0564f526fb0f
-tag:         beta
-user:        test
-date:        Mon Jan 01 00:00:11 2007 +0000
-summary:     add beta
-
-changeset:   2:72f56395749d
-tag:         master
-user:        test
-date:        Mon Jan 01 00:00:12 2007 +0000
-summary:     add gamma
-
-comparing with git://localhost/gitrepo
-changeset:   1:0564f526fb0f
-tag:         beta
-user:        test
-date:        Mon Jan 01 00:00:11 2007 +0000
-summary:     add beta
-
-comparing with git://localhost/gitrepo
-changeset:   1:0564f526fb0f
-tag:         beta
-user:        test
-date:        Mon Jan 01 00:00:11 2007 +0000
-summary:     add beta
-
-changeset:   2:72f56395749d
-tag:         master
-user:        test
-date:        Mon Jan 01 00:00:12 2007 +0000
-summary:     add gamma
-
rename from tests/test-outgoing
rename to tests/test-outgoing.t
--- a/tests/test-outgoing
+++ b/tests/test-outgoing.t
@@ -1,103 +1,139 @@
-#!/bin/sh
-
-# This feature is currently completely broken due to changes in
-# dulwich, but since it was already broken on hg 1.9 and later, it's
-# not a blocker.
-exit 80
-
-# Fails for some reason, need to investigate
-# "$TESTDIR/hghave" git || exit 80
-python -c 'from mercurial import util ; assert \
- util.version() == "unknown" or util.version() < "1.8"' || exit 80
-
-# bail if the user does not have dulwich
-python -c 'import dulwich, dulwich.repo' || exit 80
-
-# bail early if the user is already running git-daemon
-echo hi | nc localhost 9418 2>/dev/null && exit 80
-
-echo "[extensions]" >> $HGRCPATH
-echo "hggit=$(echo $(dirname $(dirname $0)))/hggit" >> $HGRCPATH
-echo 'hgext.graphlog =' >> $HGRCPATH
-echo 'hgext.bookmarks =' >> $HGRCPATH
-
-GIT_AUTHOR_NAME='test'; export GIT_AUTHOR_NAME
-GIT_AUTHOR_EMAIL='test@example.org'; export GIT_AUTHOR_EMAIL
-GIT_AUTHOR_DATE="2007-01-01 00:00:00 +0000"; export GIT_AUTHOR_DATE
-GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME"; export GIT_COMMITTER_NAME
-GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"; export GIT_COMMITTER_EMAIL
-GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"; export GIT_COMMITTER_DATE
+Load commonly used test logic
+  $ . "$TESTDIR/testutil"
 
-count=10
-commit()
-{
-    GIT_AUTHOR_DATE="2007-01-01 00:00:$count +0000"
-    GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"
-    git commit "$@" >/dev/null 2>/dev/null || echo "git commit error"
-    count=`expr $count + 1`
-}
-hgcommit()
-{
-    HGDATE="2007-01-01 00:00:$count +0000"
-    hg commit -d "$HGDATE" "$@" >/dev/null 2>/dev/null || echo "hg commit error"
-    count=`expr $count + 1`
-}
-
-mkdir gitrepo
-cd gitrepo
-git init | python -c "import sys; print sys.stdin.read().replace('$(dirname $(pwd))/', '')"
+  $ git init gitrepo
+  Initialized empty Git repository in $TESTTMP/gitrepo/.git/
+  $ cd gitrepo
+  $ echo alpha > alpha
+  $ git add alpha
+  $ fn_git_commit -m "add alpha"
+  $ git branch alpha
+  $ git show-ref
+  7eeab2ea75ec1ac0ff3d500b5b6f8a3447dd7c03 refs/heads/alpha
+  7eeab2ea75ec1ac0ff3d500b5b6f8a3447dd7c03 refs/heads/master
 
-echo alpha > alpha
-git add alpha
-commit -m "add alpha"
+  $ cd ..
+  $ hg clone gitrepo hgrepo | grep -v '^updating'
+  importing git objects into hg
+  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
 
-# dulwich does not presently support local git repos, workaround
-cd ..
-git daemon --base-path="$(pwd)"\
- --listen=localhost\
- --export-all\
- --pid-file="$DAEMON_PIDS" \
- --detach --reuseaddr \
- --enable=receive-pack
-
-hg clone git://localhost/gitrepo hgrepo | grep -v '^updating'
-
-cd hgrepo
-echo beta > beta
-hg add beta
-hgcommit -m 'add beta'
+  $ cd hgrepo
+  $ hg update -q master
+  $ echo beta > beta
+  $ hg add beta
+  $ fn_hg_commit -m 'add beta'
 
 
-echo gamma > gamma
-hg add gamma
-hgcommit -m 'add gamma'
+  $ echo gamma > gamma
+  $ hg add gamma
+  $ fn_hg_commit -m 'add gamma'
 
-hg book -r 1 beta
+  $ hg book -r 1 beta
 
-hg outgoing | sed 's/bookmark:    /tag:         /' | grep -v 'searching for changes'
-hg outgoing -r beta | sed 's/bookmark:    /tag:         /' | grep -v 'searching for changes'
-hg outgoing -r master | sed 's/bookmark:    /tag:         /' | grep -v 'searching for changes'
+  $ hg outgoing | sed 's/bookmark:    /tag:         /' | grep -v 'searching for changes'
+  comparing with */gitrepo (glob)
+  changeset:   1:0564f526fb0f
+  tag:         beta
+  user:        test
+  date:        Mon Jan 01 00:00:11 2007 +0000
+  summary:     add beta
+  
+  changeset:   2:72f56395749d
+  tag:         master
+  tag:         tip
+  user:        test
+  date:        Mon Jan 01 00:00:12 2007 +0000
+  summary:     add gamma
+  
+  $ hg outgoing -r beta | sed 's/bookmark:    /tag:         /' | grep -v 'searching for changes'
+  comparing with */gitrepo (glob)
+  changeset:   1:0564f526fb0f
+  tag:         beta
+  user:        test
+  date:        Mon Jan 01 00:00:11 2007 +0000
+  summary:     add beta
+  
+  $ hg outgoing -r master | sed 's/bookmark:    /tag:         /' | grep -v 'searching for changes'
+  comparing with */gitrepo (glob)
+  changeset:   1:0564f526fb0f
+  tag:         beta
+  user:        test
+  date:        Mon Jan 01 00:00:11 2007 +0000
+  summary:     add beta
+  
+  changeset:   2:72f56395749d
+  tag:         master
+  tag:         tip
+  user:        test
+  date:        Mon Jan 01 00:00:12 2007 +0000
+  summary:     add gamma
+  
 
-cd ..
+  $ cd ..
+
+some more work on master from git
+  $ cd gitrepo
 
-echo % some more work on master from git
-cd gitrepo
+Check state of refs after outgoing
+  $ git show-ref
+  7eeab2ea75ec1ac0ff3d500b5b6f8a3447dd7c03 refs/heads/alpha
+  7eeab2ea75ec1ac0ff3d500b5b6f8a3447dd7c03 refs/heads/master
 
-git checkout master 2>&1 | sed s/\'/\"/g
-echo delta > delta
-git add delta
-commit -m "add delta"
+  $ git checkout master 2>&1 | sed s/\'/\"/g
+  Already on "master"
+  $ echo delta > delta
+  $ git add delta
+  $ fn_git_commit -m "add delta"
 
-cd ..
+  $ cd ..
 
-cd hgrepo
-echo % this will fail # maybe we should try to make it work
-hg outgoing
-echo % let\'s pull and try again
-hg pull
-hg outgoing | sed 's/bookmark:    /tag:         /' | grep -v 'searching for changes'
-hg outgoing -r beta | sed 's/bookmark:    /tag:         /' | grep -v 'searching for changes'
-hg outgoing -r master | sed 's/bookmark:    /tag:         /' | grep -v 'searching for changes'
+  $ cd hgrepo
+this will fail # maybe we should try to make it work
+  $ hg outgoing
+  comparing with */gitrepo (glob)
+  abort: refs/heads/master changed on the server, please pull and merge before pushing
+  [255]
+let's pull and try again
+  $ hg pull 2>&1 | grep -v 'divergent bookmark'
+  pulling from */gitrepo (glob)
+  importing git objects into hg
+  (run 'hg update' to get a working copy)
+  $ hg outgoing | sed 's/bookmark:    /tag:         /' | grep -v 'searching for changes'
+  comparing with */gitrepo (glob)
+  changeset:   1:0564f526fb0f
+  tag:         beta
+  user:        test
+  date:        Mon Jan 01 00:00:11 2007 +0000
+  summary:     add beta
+  
+  changeset:   2:72f56395749d
+  tag:         master
+  user:        test
+  date:        Mon Jan 01 00:00:12 2007 +0000
+  summary:     add gamma
+  
+  $ hg outgoing -r beta | sed 's/bookmark:    /tag:         /' | grep -v 'searching for changes'
+  comparing with */gitrepo (glob)
+  changeset:   1:0564f526fb0f
+  tag:         beta
+  user:        test
+  date:        Mon Jan 01 00:00:11 2007 +0000
+  summary:     add beta
+  
+  $ hg outgoing -r master | sed 's/bookmark:    /tag:         /' | grep -v 'searching for changes'
+  comparing with */gitrepo (glob)
+  changeset:   1:0564f526fb0f
+  tag:         beta
+  user:        test
+  date:        Mon Jan 01 00:00:11 2007 +0000
+  summary:     add beta
+  
+  changeset:   2:72f56395749d
+  tag:         master
+  user:        test
+  date:        Mon Jan 01 00:00:12 2007 +0000
+  summary:     add gamma
+  
 
 
-cd ..
+  $ cd ..
deleted file mode 100644
--- a/tests/test-pull-after-strip.out
+++ /dev/null
@@ -1,59 +0,0 @@
-Initialized empty Git repository in gitrepo/.git/
-
-Switched to a new branch "beta"
-% clone a tag
-importing git objects into hg
-1 files updated, 0 files merged, 0 files removed, 0 files unresolved
-@  changeset:   0:3442585be8a6
-   tag:         alpha
-   tag:         default/master
-   tag:         tip
-   user:        test <test@example.org>
-   date:        Mon Jan 01 00:00:10 2007 +0000
-   summary:     add alpha
-
-% clone a branch
-importing git objects into hg
-2 files updated, 0 files merged, 0 files removed, 0 files unresolved
-@  changeset:   1:7bcd915dc873
-|  tag:         default/beta
-|  tag:         tip
-|  user:        test <test@example.org>
-|  date:        Mon Jan 01 00:00:11 2007 +0000
-|  summary:     add beta
-|
-o  changeset:   0:3442585be8a6
-   tag:         alpha
-   tag:         default/master
-   user:        test <test@example.org>
-   date:        Mon Jan 01 00:00:10 2007 +0000
-   summary:     add alpha
-
-0 files updated, 0 files merged, 1 files removed, 0 files unresolved
-pulling from git://localhost/gitrepo
-importing git objects into hg
-abort: you appear to have run strip - please run hg git-cleanup
-git commit map cleaned
-% pull works after 'hg git-cleanup'
-pulling from git://localhost/gitrepo
-importing git objects into hg
-(run 'hg update' to get a working copy)
-o  changeset:   2:611948b1ec6a
-|  tag:         default/beta
-|  tag:         tip
-|  user:        test <test@example.org>
-|  date:        Mon Jan 01 00:00:12 2007 +0000
-|  summary:     add to beta
-|
-o  changeset:   1:7bcd915dc873
-|  user:        test <test@example.org>
-|  date:        Mon Jan 01 00:00:11 2007 +0000
-|  summary:     add beta
-|
-@  changeset:   0:3442585be8a6
-   tag:         alpha
-   tag:         default/master
-   user:        test <test@example.org>
-   date:        Mon Jan 01 00:00:10 2007 +0000
-   summary:     add alpha
-
rename from tests/test-pull-after-strip
rename to tests/test-pull-after-strip.t
--- a/tests/test-pull-after-strip
+++ b/tests/test-pull-after-strip.t
@@ -1,96 +1,96 @@
-#!/bin/sh
-
-# Fails for some reason, need to investigate
-# "$TESTDIR/hghave" git || exit 80
+Load commonly used test logic
+  $ . "$TESTDIR/testutil"
 
-# this test is busted on hg < 1.5. I'm not sure how to fix it.
-cat > tmp.py <<EOF
-import sys
-v = sys.stdin.read().strip()[:-1]
-if v[1] == '.' and ((int(v[0]) == 1 and int(v[2]) > 4) or int(v[0]) > 1):
-  sys.exit(0)
-sys.exit(1)
-EOF
+  $ git init gitrepo
+  Initialized empty Git repository in $TESTTMP/gitrepo/.git/
+  $ cd gitrepo
+  $ echo alpha > alpha
+  $ git add alpha
+  $ fn_git_commit -m 'add alpha'
 
-hg version | grep version | sed 's/.*(version //' | python tmp.py || exit 80
+  $ git tag alpha
 
-# bail if the user does not have dulwich
-python -c 'import dulwich, dulwich.repo' || exit 80
-
-# bail early if the user is already running git-daemon
-echo hi | nc localhost 9418 2>/dev/null && exit 80
+  $ git checkout -b beta 2>&1 | sed s/\'/\"/g
+  Switched to a new branch "beta"
+  $ echo beta > beta
+  $ git add beta
+  $ fn_git_commit -m 'add beta'
 
 
-cat >> $HGRCPATH <<EOF
-[extensions]
-graphlog=
-bookmarks=
-mq=
-EOF
-echo "hggit=$(echo $(dirname $(dirname $0)))/hggit" >> $HGRCPATH
-
-GIT_AUTHOR_NAME='test'; export GIT_AUTHOR_NAME
-GIT_AUTHOR_EMAIL='test@example.org'; export GIT_AUTHOR_EMAIL
-GIT_AUTHOR_DATE="2007-01-01 00:00:00 +0000"; export GIT_AUTHOR_DATE
-GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME"; export GIT_COMMITTER_NAME
-GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"; export GIT_COMMITTER_EMAIL
-GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"; export GIT_COMMITTER_DATE
-
-count=10
-commit()
-{
-    GIT_AUTHOR_DATE="2007-01-01 00:00:$count +0000"
-    GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"
-    git commit "$@" >/dev/null 2>/dev/null || echo "git commit error"
-    count=`expr $count + 1`
-}
-
-mkdir gitrepo
-cd gitrepo
-git init | python -c "import sys; print sys.stdin.read().replace('$(dirname $(pwd))/', '')"
-echo alpha > alpha
-git add alpha
-commit -m 'add alpha'
-
-git tag alpha
+  $ cd ..
+clone a tag
+  $ hg clone -r alpha gitrepo hgrepo-a | grep -v '^updating'
+  importing git objects into hg
+  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  $ hg -R hgrepo-a log --graph | egrep -v ': *(beta|master)'
+  @  changeset:   0:3442585be8a6
+     tag:         alpha
+     tag:         default/master
+     tag:         tip
+     user:        test <test@example.org>
+     date:        Mon Jan 01 00:00:10 2007 +0000
+     summary:     add alpha
+  
+clone a branch
+  $ hg clone -r beta gitrepo hgrepo-b | grep -v '^updating'
+  importing git objects into hg
+  2 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  $ hg -R hgrepo-b log --graph | egrep -v ': *(beta|master)'
+  @  changeset:   1:7bcd915dc873
+  |  tag:         default/beta
+  |  tag:         tip
+  |  user:        test <test@example.org>
+  |  date:        Mon Jan 01 00:00:11 2007 +0000
+  |  summary:     add beta
+  |
+  o  changeset:   0:3442585be8a6
+     tag:         alpha
+     tag:         default/master
+     user:        test <test@example.org>
+     date:        Mon Jan 01 00:00:10 2007 +0000
+     summary:     add alpha
+  
+  $ cd gitrepo
+  $ echo beta line 2 >> beta
+  $ git add beta
+  $ fn_git_commit -m 'add to beta'
 
-git checkout -b beta 2>&1 | sed s/\'/\"/g
-echo beta > beta
-git add beta
-commit -m 'add beta'
-
-
-cd ..
-git daemon --base-path="$(pwd)"\
- --listen=localhost\
- --export-all\
- --pid-file="$DAEMON_PIDS" \
- --detach --reuseaddr
-
-echo % clone a tag
-hg clone -r alpha git://localhost/gitrepo hgrepo-a | grep -v '^updating'
-cd hgrepo-a
-hg log --graph | egrep -v ': *(beta|master)'
+  $ cd ..
+  $ cd hgrepo-b
+  $ hg strip tip 2>&1 | grep -v saving | grep -v backup
+  0 files updated, 0 files merged, 1 files removed, 0 files unresolved
+  $ hg pull -r beta
+  pulling from $TESTTMP/gitrepo
+  importing git objects into hg
+  abort: you appear to have run strip - please run hg git-cleanup
+  [255]
+  $ hg git-cleanup
+  git commit map cleaned
+pull works after 'hg git-cleanup'
+"adding remote bookmark" message was added in Mercurial 2.3
+  $ hg pull -r beta | grep -v "adding remote bookmark"
+  pulling from $TESTTMP/gitrepo
+  importing git objects into hg
+  (run 'hg update' to get a working copy)
+  $ hg log --graph | egrep -v 'bookmark: *(alpha|beta|master)'
+  o  changeset:   2:611948b1ec6a
+  |  tag:         default/beta
+  |  tag:         tip
+  |  user:        test <test@example.org>
+  |  date:        Mon Jan 01 00:00:12 2007 +0000
+  |  summary:     add to beta
+  |
+  o  changeset:   1:7bcd915dc873
+  |  user:        test <test@example.org>
+  |  date:        Mon Jan 01 00:00:11 2007 +0000
+  |  summary:     add beta
+  |
+  @  changeset:   0:3442585be8a6
+     tag:         alpha
+     tag:         default/master
+     user:        test <test@example.org>
+     date:        Mon Jan 01 00:00:10 2007 +0000
+     summary:     add alpha
+  
 
-cd ..
-echo % clone a branch
-hg clone -r beta git://localhost/gitrepo hgrepo-b | grep -v '^updating'
-cd hgrepo-b
-hg log --graph | egrep -v ': *(beta|master)'
-cd ..
-
-cd gitrepo
-echo beta line 2 >> beta
-git add beta
-commit -m 'add to beta'
-
-cd ..
-cd hgrepo-b
-hg strip tip 2>&1 | grep -v saving | grep -v backup
-hg pull -r beta
-hg git-cleanup
-echo % pull works after \'hg git-cleanup\'
-hg pull -r beta
-hg log --graph | egrep -v ': *(beta|master)'
-
-cd ..
+  $ cd ..
deleted file mode 100644
--- a/tests/test-pull.out
+++ /dev/null
@@ -1,31 +0,0 @@
-Initialized empty Git repository in gitrepo/.git/
-
-Switched to a new branch "beta"
-% clone a tag
-importing git objects into hg
-1 files updated, 0 files merged, 0 files removed, 0 files unresolved
-@  changeset:   0:3442585be8a6
-   tag:         alpha
-   tag:         default/master
-   tag:         tip
-   user:        test <test@example.org>
-   date:        Mon Jan 01 00:00:10 2007 +0000
-   summary:     add alpha
-
-% clone a branch
-importing git objects into hg
-2 files updated, 0 files merged, 0 files removed, 0 files unresolved
-@  changeset:   1:7bcd915dc873
-|  tag:         default/beta
-|  tag:         tip
-|  user:        test <test@example.org>
-|  date:        Mon Jan 01 00:00:11 2007 +0000
-|  summary:     add beta
-|
-o  changeset:   0:3442585be8a6
-   tag:         alpha
-   tag:         default/master
-   user:        test <test@example.org>
-   date:        Mon Jan 01 00:00:10 2007 +0000
-   summary:     add alpha
-
new file mode 100644
--- /dev/null
+++ b/tests/test-pull.t
@@ -0,0 +1,140 @@
+Load commonly used test logic
+  $ . "$TESTDIR/testutil"
+
+set up a git repo with some commits, branches and a tag
+  $ git init -q gitrepo
+  $ cd gitrepo
+  $ echo alpha > alpha
+  $ git add alpha
+  $ fn_git_commit -m 'add alpha'
+  $ git tag t_alpha
+  $ git checkout -qb beta
+  $ echo beta > beta
+  $ git add beta
+  $ fn_git_commit -m 'add beta'
+  $ cd ..
+
+clone a tag (ideally we'd want to pull it, but that seems broken for now)
+#  $ hg init hgrepo
+#  $ echo "[paths]" >> hgrepo/.hg/hgrc
+#  $ echo "default=$TESTTMP/gitrepo" >> hgrepo/.hg/hgrc
+#  $ hg -R hgrepo pull -r t_alpha
+  $ hg clone -r t_alpha gitrepo hgrepo
+  importing git objects into hg
+  updating to branch default
+  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  $ hg -R hgrepo log --graph
+  @  changeset:   0:3442585be8a6
+     bookmark:    master
+     tag:         default/master
+     tag:         t_alpha
+     tag:         tip
+     user:        test <test@example.org>
+     date:        Mon Jan 01 00:00:10 2007 +0000
+     summary:     add alpha
+  
+pull a branch
+  $ hg -R hgrepo pull -r beta
+  pulling from $TESTTMP/gitrepo
+  importing git objects into hg
+  (run 'hg update' to get a working copy)
+  $ hg -R hgrepo log --graph
+  o  changeset:   1:7bcd915dc873
+  |  bookmark:    beta
+  |  tag:         default/beta
+  |  tag:         tip
+  |  user:        test <test@example.org>
+  |  date:        Mon Jan 01 00:00:11 2007 +0000
+  |  summary:     add beta
+  |
+  @  changeset:   0:3442585be8a6
+     bookmark:    master
+     tag:         default/master
+     tag:         t_alpha
+     user:        test <test@example.org>
+     date:        Mon Jan 01 00:00:10 2007 +0000
+     summary:     add alpha
+  
+add another commit and tag to the git repo
+  $ cd gitrepo
+  $ git tag t_beta
+  $ git checkout -q master
+  $ echo gamma > gamma
+  $ git add gamma
+  $ fn_git_commit -m 'add gamma'
+  $ cd ..
+
+pull everything else
+  $ hg -R hgrepo pull
+  pulling from $TESTTMP/gitrepo
+  importing git objects into hg
+  (run 'hg update' to get a working copy)
+  $ hg -R hgrepo log --graph
+  o  changeset:   2:37c124f2d0a0
+  |  bookmark:    master
+  |  tag:         default/master
+  |  tag:         tip
+  |  parent:      0:3442585be8a6
+  |  user:        test <test@example.org>
+  |  date:        Mon Jan 01 00:00:12 2007 +0000
+  |  summary:     add gamma
+  |
+  | o  changeset:   1:7bcd915dc873
+  |/   bookmark:    beta
+  |    tag:         default/beta
+  |    tag:         t_beta
+  |    user:        test <test@example.org>
+  |    date:        Mon Jan 01 00:00:11 2007 +0000
+  |    summary:     add beta
+  |
+  @  changeset:   0:3442585be8a6
+     tag:         t_alpha
+     user:        test <test@example.org>
+     date:        Mon Jan 01 00:00:10 2007 +0000
+     summary:     add alpha
+  
+add a merge to the git repo
+  $ cd gitrepo
+  $ git merge beta | sed 's/|  */| /'
+  Merge made by the 'recursive' strategy.
+   beta | 1 +
+   1 file changed, 1 insertion(+)
+   create mode 100644 beta
+  $ cd ..
+
+pull the merge
+  $ hg -R hgrepo pull
+  pulling from $TESTTMP/gitrepo
+  importing git objects into hg
+  (run 'hg update' to get a working copy)
+  $ hg -R hgrepo log --graph
+  o    changeset:   3:b8668fddf56c
+  |\   bookmark:    master
+  | |  tag:         default/master
+  | |  tag:         tip
+  | |  parent:      2:37c124f2d0a0
+  | |  parent:      1:7bcd915dc873
+  | |  user:        test <test@example.org>
+  | |  date:        Mon Jan 01 00:00:12 2007 +0000
+  | |  summary:     Merge branch 'beta'
+  | |
+  | o  changeset:   2:37c124f2d0a0
+  | |  parent:      0:3442585be8a6
+  | |  user:        test <test@example.org>
+  | |  date:        Mon Jan 01 00:00:12 2007 +0000
+  | |  summary:     add gamma
+  | |
+  o |  changeset:   1:7bcd915dc873
+  |/   bookmark:    beta
+  |    tag:         default/beta
+  |    tag:         t_beta
+  |    user:        test <test@example.org>
+  |    date:        Mon Jan 01 00:00:11 2007 +0000
+  |    summary:     add beta
+  |
+  @  changeset:   0:3442585be8a6
+     tag:         t_alpha
+     user:        test <test@example.org>
+     date:        Mon Jan 01 00:00:10 2007 +0000
+     summary:     add alpha
+  
deleted file mode 100644
--- a/tests/test-push-r.out
+++ /dev/null
@@ -1,114 +0,0 @@
-1 files updated, 0 files merged, 0 files removed, 0 files unresolved
-created new head
-1 files updated, 0 files merged, 2 files removed, 0 files unresolved
-pushing to test-0
-searching for changes
-adding changesets
-adding manifests
-adding file changes
-added 1 changesets with 1 changes to 1 files
-checking changesets
-checking manifests
-crosschecking files in changesets and manifests
-checking files
-1 files, 1 changesets, 1 total revisions
-pushing to test-1
-searching for changes
-adding changesets
-adding manifests
-adding file changes
-added 2 changesets with 2 changes to 1 files
-checking changesets
-checking manifests
-crosschecking files in changesets and manifests
-checking files
-1 files, 2 changesets, 2 total revisions
-pushing to test-2
-searching for changes
-adding changesets
-adding manifests
-adding file changes
-added 3 changesets with 3 changes to 1 files
-checking changesets
-checking manifests
-crosschecking files in changesets and manifests
-checking files
-1 files, 3 changesets, 3 total revisions
-pushing to test-3
-searching for changes
-adding changesets
-adding manifests
-adding file changes
-added 4 changesets with 4 changes to 1 files
-checking changesets
-checking manifests
-crosschecking files in changesets and manifests
-checking files
-1 files, 4 changesets, 4 total revisions
-pushing to test-4
-searching for changes
-adding changesets
-adding manifests
-adding file changes
-added 2 changesets with 2 changes to 1 files
-checking changesets
-checking manifests
-crosschecking files in changesets and manifests
-checking files
-1 files, 2 changesets, 2 total revisions
-pushing to test-5
-searching for changes
-adding changesets
-adding manifests
-adding file changes
-added 3 changesets with 3 changes to 1 files
-checking changesets
-checking manifests
-crosschecking files in changesets and manifests
-checking files
-1 files, 3 changesets, 3 total revisions
-pushing to test-6
-searching for changes
-adding changesets
-adding manifests
-adding file changes
-added 4 changesets with 5 changes to 2 files
-checking changesets
-checking manifests
-crosschecking files in changesets and manifests
-checking files
-2 files, 4 changesets, 5 total revisions
-pushing to test-7
-searching for changes
-adding changesets
-adding manifests
-adding file changes
-added 5 changesets with 6 changes to 3 files
-checking changesets
-checking manifests
-crosschecking files in changesets and manifests
-checking files
-3 files, 5 changesets, 6 total revisions
-pushing to test-8
-searching for changes
-adding changesets
-adding manifests
-adding file changes
-added 5 changesets with 5 changes to 2 files
-checking changesets
-checking manifests
-crosschecking files in changesets and manifests
-checking files
-2 files, 5 changesets, 5 total revisions
-pulling from ../test-7
-searching for changes
-adding changesets
-adding manifests
-adding file changes
-added 4 changesets with 2 changes to 3 files (+1 heads)
-(run 'hg heads' to see heads, 'hg merge' to merge)
-checking changesets
-checking manifests
-crosschecking files in changesets and manifests
-checking files
-4 files, 9 changesets, 7 total revisions
rename from tests/test-push-r
rename to tests/test-push-r.t
--- a/tests/test-push-r
+++ b/tests/test-push-r.t
@@ -1,63 +1,170 @@
-#!/bin/sh
-
-# bail if the user does not have dulwich
-python -c 'import dulwich, dulwich.repo' || exit 80
-
-echo "[extensions]" >> $HGRCPATH
-echo "hggit=$(echo $(dirname $(dirname $0)))/hggit" >> $HGRCPATH
-echo 'hgext.graphlog =' >> $HGRCPATH
-echo 'hgext.bookmarks =' >> $HGRCPATH
+Load commonly used test logic
+  $ . "$TESTDIR/testutil"
 
-hg init test
-cd test
-cat >>afile <<EOF
-0
-EOF
-hg add afile
-hg commit -m "0.0"
-cat >>afile <<EOF
-1
-EOF
-hg commit -m "0.1"
-cat >>afile <<EOF
-2
-EOF
-hg commit -m "0.2"
-cat >>afile <<EOF
-3
-EOF
-hg commit -m "0.3"
-hg update -C 0
-cat >>afile <<EOF
-1
-EOF
-hg commit -m "1.1"
-cat >>afile <<EOF
-2
-EOF
-hg commit -m "1.2"
-cat >fred <<EOF
-a line
-EOF
-cat >>afile <<EOF
-3
-EOF
-hg add fred
-hg commit -m "1.3"
-hg mv afile adifferentfile
-hg commit -m "1.3m"
-hg update -C 3
-hg mv afile anotherfile
-hg commit -m "0.3m"
-cd ..
-for i in 0 1 2 3 4 5 6 7 8; do
-   mkdir test-"$i"
-   hg --cwd test-"$i" init
-   hg -R test push -r "$i" test-"$i"
-   cd test-"$i"
-   hg verify
-   cd ..
-done
-cd test-8
-hg pull ../test-7
-hg verify
+  $ hg init test
+  $ cd test
+  $ cat >>afile <<EOF
+  > 0
+  > EOF
+  $ hg add afile
+  $ hg commit -m "0.0"
+  $ cat >>afile <<EOF
+  > 1
+  > EOF
+  $ hg commit -m "0.1"
+  $ cat >>afile <<EOF
+  > 2
+  > EOF
+  $ hg commit -m "0.2"
+  $ cat >>afile <<EOF
+  > 3
+  > EOF
+  $ hg commit -m "0.3"
+  $ hg update -C 0
+  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  $ cat >>afile <<EOF
+  > 1
+  > EOF
+  $ hg commit -m "1.1"
+  created new head
+  $ cat >>afile <<EOF
+  > 2
+  > EOF
+  $ hg commit -m "1.2"
+  $ cat >fred <<EOF
+  > a line
+  > EOF
+  $ cat >>afile <<EOF
+  > 3
+  > EOF
+  $ hg add fred
+  $ hg commit -m "1.3"
+  $ hg mv afile adifferentfile
+  $ hg commit -m "1.3m"
+  $ hg update -C 3
+  1 files updated, 0 files merged, 2 files removed, 0 files unresolved
+  $ hg mv afile anotherfile
+  $ hg commit -m "0.3m"
+  $ cd ..
+  $ for i in 0 1 2 3 4 5 6 7 8; do
+  >    mkdir test-"$i"
+  >    hg --cwd test-"$i" init
+  >    hg -R test push -r "$i" test-"$i"
+  >    cd test-"$i"
+  >    hg verify
+  >    cd ..
+  > done
+  pushing to test-0
+  searching for changes
+  adding changesets
+  adding manifests
+  adding file changes
+  added 1 changesets with 1 changes to 1 files
+  checking changesets
+  checking manifests
+  crosschecking files in changesets and manifests
+  checking files
+  1 files, 1 changesets, 1 total revisions
+  pushing to test-1
+  searching for changes
+  adding changesets
+  adding manifests
+  adding file changes
+  added 2 changesets with 2 changes to 1 files
+  checking changesets
+  checking manifests
+  crosschecking files in changesets and manifests
+  checking files
+  1 files, 2 changesets, 2 total revisions
+  pushing to test-2
+  searching for changes
+  adding changesets
+  adding manifests
+  adding file changes
+  added 3 changesets with 3 changes to 1 files
+  checking changesets
+  checking manifests
+  crosschecking files in changesets and manifests
+  checking files
+  1 files, 3 changesets, 3 total revisions
+  pushing to test-3
+  searching for changes
+  adding changesets
+  adding manifests
+  adding file changes
+  added 4 changesets with 4 changes to 1 files
+  checking changesets
+  checking manifests
+  crosschecking files in changesets and manifests
+  checking files
+  1 files, 4 changesets, 4 total revisions
+  pushing to test-4
+  searching for changes
+  adding changesets
+  adding manifests
+  adding file changes
+  added 2 changesets with 2 changes to 1 files
+  checking changesets
+  checking manifests
+  crosschecking files in changesets and manifests
+  checking files
+  1 files, 2 changesets, 2 total revisions
+  pushing to test-5
+  searching for changes
+  adding changesets
+  adding manifests
+  adding file changes
+  added 3 changesets with 3 changes to 1 files
+  checking changesets
+  checking manifests
+  crosschecking files in changesets and manifests
+  checking files
+  1 files, 3 changesets, 3 total revisions
+  pushing to test-6
+  searching for changes
+  adding changesets
+  adding manifests
+  adding file changes
+  added 4 changesets with 5 changes to 2 files
+  checking changesets
+  checking manifests
+  crosschecking files in changesets and manifests
+  checking files
+  2 files, 4 changesets, 5 total revisions
+  pushing to test-7
+  searching for changes
+  adding changesets
+  adding manifests
+  adding file changes
+  added 5 changesets with 6 changes to 3 files
+  checking changesets
+  checking manifests
+  crosschecking files in changesets and manifests
+  checking files
+  3 files, 5 changesets, 6 total revisions
+  pushing to test-8
+  searching for changes
+  adding changesets
+  adding manifests
+  adding file changes
+  added 5 changesets with 5 changes to 2 files
+  checking changesets
+  checking manifests
+  crosschecking files in changesets and manifests
+  checking files
+  2 files, 5 changesets, 5 total revisions
+  $ cd test-8
+  $ hg pull ../test-7
+  pulling from ../test-7
+  searching for changes
+  adding changesets
+  adding manifests
+  adding file changes
+  added 4 changesets with 2 changes to 3 files (+1 heads)
+  (run 'hg heads' to see heads, 'hg merge' to merge)
+  $ hg verify
+  checking changesets
+  checking manifests
+  crosschecking files in changesets and manifests
+  checking files
+  4 files, 9 changesets, 7 total revisions
deleted file mode 100644
--- a/tests/test-push.out
+++ /dev/null
@@ -1,59 +0,0 @@
-Initialized empty Git repository in gitrepo/.git/
-
-Switched to a new branch "not-master"
-importing git objects into hg
-1 files updated, 0 files merged, 0 files removed, 0 files unresolved
-pushing to git://localhost/gitrepo
-exporting hg objects to git
-creating and sending data
-    default::refs/heads/beta => GIT:cffa0e8d
-[0]
-% should have two different branches
-  beta       cffa0e8 add beta
-  master     7eeab2e add alpha
-* not-master 7eeab2e add alpha
-% some more work on master from git
-Switched to branch "master"
-Switched to branch "not-master"
-% this should fail
-pushing to git://localhost/gitrepo
-creating and sending data
-abort: refs/heads/master changed on the server, please pull and merge before pushing
-[255]
-% ... even with -f
-pushing to git://localhost/gitrepo
-creating and sending data
-abort: refs/heads/master changed on the server, please pull and merge before pushing
-[255]
-pulling from git://localhost/gitrepo
-importing git objects into hg
-(run 'hg update' to get a working copy)
-% master and default/master should be diferent
-changeset:   2:72f56395749d
-user:        test
-date:        Mon Jan 01 00:00:12 2007 +0000
-summary:     add gamma
-
-changeset:   3:1436150b86c2
-tag:         default/master
-tag:         tip
-parent:      0:3442585be8a6
-user:        test <test@example.org>
-date:        Mon Jan 01 00:00:13 2007 +0000
-summary:     add delta
-
-% this should also fail
-pushing to git://localhost/gitrepo
-creating and sending data
-abort: pushing refs/heads/master overwrites 72f56395749d
-[255]
-% ... but succeed with -f
-pushing to git://localhost/gitrepo
-creating and sending data
-    default::refs/heads/master => GIT:cc119202
-[0]
-% this should fail, no changes to push
-pushing to git://localhost/gitrepo
-creating and sending data
-no changes found
-[1]
old mode 100755
new mode 100644
rename from tests/test-push
rename to tests/test-push.t
--- a/tests/test-push
+++ b/tests/test-push.t
@@ -1,120 +1,125 @@
-#!/bin/sh
-
-# Fails for some reason, need to investigate
-# "$TESTDIR/hghave" git || exit 80
-
-# bail if the user does not have dulwich
-python -c 'import dulwich, dulwich.repo' || exit 80
+Load commonly used test logic
+  $ . "$TESTDIR/testutil"
 
-# bail early if the user is already running git-daemon
-echo hi | nc localhost 9418 2>/dev/null && exit 80
+  $ git init gitrepo
+  Initialized empty Git repository in $TESTTMP/gitrepo/.git/
+  $ cd gitrepo
+  $ echo alpha > alpha
+  $ git add alpha
+  $ fn_git_commit -m "add alpha"
+  $ git checkout -b not-master 2>&1 | sed s/\'/\"/g
+  Switched to a new branch "not-master"
 
-echo "[extensions]" >> $HGRCPATH
-echo "hggit=$(echo $(dirname $(dirname $0)))/hggit" >> $HGRCPATH
-echo 'hgext.graphlog =' >> $HGRCPATH
-echo 'hgext.bookmarks =' >> $HGRCPATH
+  $ cd ..
+  $ hg clone gitrepo hgrepo | grep -v '^updating'
+  importing git objects into hg
+  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+
+  $ cd hgrepo
+  $ echo beta > beta
+  $ hg add beta
+  $ fn_hg_commit -m 'add beta'
 
 
-GIT_AUTHOR_NAME='test'; export GIT_AUTHOR_NAME
-GIT_AUTHOR_EMAIL='test@example.org'; export GIT_AUTHOR_EMAIL
-GIT_AUTHOR_DATE="2007-01-01 00:00:00 +0000"; export GIT_AUTHOR_DATE
-GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME"; export GIT_COMMITTER_NAME
-GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"; export GIT_COMMITTER_EMAIL
-GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"; export GIT_COMMITTER_DATE
+  $ echo gamma > gamma
+  $ hg add gamma
+  $ fn_hg_commit -m 'add gamma'
+
+  $ hg book -r 1 beta
+  $ hg push -r beta
+  pushing to $TESTTMP/gitrepo
+  searching for changes
 
-count=10
-commit()
-{
-    GIT_AUTHOR_DATE="2007-01-01 00:00:$count +0000"
-    GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"
-    git commit "$@" >/dev/null 2>/dev/null || echo "git commit error"
-    count=`expr $count + 1`
-}
-hgcommit()
-{
-    HGDATE="2007-01-01 00:00:$count +0000"
-    hg commit -d "$HGDATE" "$@" >/dev/null 2>/dev/null || echo "hg commit error"
-    count=`expr $count + 1`
-}
+  $ cd ..
 
-mkdir gitrepo
-cd gitrepo
-git init | python -c "import sys; print sys.stdin.read().replace('$(dirname $(pwd))/', '')"
+should have two different branches
+  $ cd gitrepo
+  $ git branch -v
+    beta       cffa0e8 add beta
+    master     7eeab2e add alpha
+  * not-master 7eeab2e add alpha
 
-echo alpha > alpha
-git add alpha
-commit -m "add alpha"
-git checkout -b not-master 2>&1 | sed s/\'/\"/g
+some more work on master from git
+  $ git checkout master 2>&1 | sed s/\'/\"/g
+  Switched to branch "master"
+  $ echo delta > delta
+  $ git add delta
+  $ fn_git_commit -m "add delta"
+  $ git checkout not-master 2>&1 | sed s/\'/\"/g
+  Switched to branch "not-master"
+
+  $ cd ..
 
-# dulwich does not presently support local git repos, workaround
-cd ..
-git daemon --base-path="$(pwd)"\
- --listen=localhost\
- --export-all\
- --pid-file="$DAEMON_PIDS" \
- --detach --reuseaddr \
- --enable=receive-pack
+  $ cd hgrepo
+this should fail
+  $ hg push -r master
+  pushing to $TESTTMP/gitrepo
+  searching for changes
+  abort: refs/heads/master changed on the server, please pull and merge before pushing
+  [255]
 
-hg clone git://localhost/gitrepo hgrepo | grep -v '^updating'
-
-cd hgrepo
-echo beta > beta
-hg add beta
-hgcommit -m 'add beta'
-
-
-echo gamma > gamma
-hg add gamma
-hgcommit -m 'add gamma'
+... even with -f
+  $ hg push -fr master
+  pushing to $TESTTMP/gitrepo
+  searching for changes
+  abort: refs/heads/master changed on the server, please pull and merge before pushing
+  [255]
 
-hg book -r 1 beta
-hg push -r beta
-echo [$?]
-
-cd ..
-
-echo % should have two different branches
-cd gitrepo
-git branch -v
-
-echo % some more work on master from git
-git checkout master 2>&1 | sed s/\'/\"/g
-echo delta > delta
-git add delta
-commit -m "add delta"
-git checkout not-master 2>&1 | sed s/\'/\"/g
-
-cd ..
-
-cd hgrepo
-echo % this should fail
-hg push -r master
-echo [$?]
+  $ hg pull 2>&1 | grep -v 'divergent bookmark'
+  pulling from $TESTTMP/gitrepo
+  importing git objects into hg
+  (run 'hg update' to get a working copy)
+TODO shouldn't need to do this since we're (in theory) pushing master explicitly,
+which should not implicitly also push the not-master ref.
+  $ hg book not-master -r default/not-master --force
+master and default/master should be diferent
+  $ hg log -r master | grep -v ': *master'
+  changeset:   2:72f56395749d
+  user:        test
+  date:        Mon Jan 01 00:00:12 2007 +0000
+  summary:     add gamma
+  
+  $ hg log -r default/master | grep -v 'master@default'
+  changeset:   3:1436150b86c2
+  tag:         default/master
+  tag:         tip
+  parent:      0:3442585be8a6
+  user:        test <test@example.org>
+  date:        Mon Jan 01 00:00:13 2007 +0000
+  summary:     add delta
+  
 
-echo % ... even with -f
-hg push -fr master
-echo [$?]
+this should also fail
+  $ hg push -r master
+  pushing to $TESTTMP/gitrepo
+  searching for changes
+  abort: pushing refs/heads/master overwrites 72f56395749d
+  [255]
 
-hg pull
-# TODO shouldn't need to do this since we're (in theory) pushing master explicitly,
-# which should not implicitly also push the not-master ref.
-hg book not-master -r default/not-master --force
-echo % master and default/master should be diferent
-hg log -r master | grep -v ': *master'
-hg log -r default/master
+... but succeed with -f
+  $ hg push -fr master
+  pushing to $TESTTMP/gitrepo
+  searching for changes
 
-echo % this should also fail
-hg push -r master
-echo [$?]
+this should fail, no changes to push
+The exit code for this was broken in Mercurial (incorrectly returning 0) until
+issue3228 was fixed in 2.1
+  $ hg push -r master && false
+  pushing to $TESTTMP/gitrepo
+  searching for changes
+  no changes found
+  [1]
 
-echo % ... but succeed with -f
-hg push -fr master
-echo [$?]
+  $ cd ..
 
-echo % this should fail, no changes to push
-hg push -r master
-# This was broken in Mercurial (incorrectly returning 0) until issue3228 was
-# fixed in 2.1
-echo [$?] | sed s/0/1/
-
-cd ..
+Push empty Hg repo to empty Git repo (issue #58)
+Since there aren't any changes, exit code 1 is expected in modern Mercurial.
+However, since it varies between supported Mercurial versions, we need to
+force it to consistency for now. (see issue3228, fixed in Mercurial 2.1)
+  $ hg init hgrepo2
+  $ git init -q --bare gitrepo2
+  $ hg -R hgrepo2 push gitrepo2 && false
+  pushing to gitrepo2
+  searching for changes
+  no changes found
+  [1]
deleted file mode 100755
--- a/tests/test-sane-without-bookmarks
+++ /dev/null
@@ -1,57 +0,0 @@
-#!/bin/sh
-
-# Fails for some reason, need to investigate
-# "$TESTDIR/hghave" git || exit 80
-
-# bail if the user does not have dulwich
-python -c 'import dulwich, dulwich.repo' || exit 80
-
-# bail if hgext.bookmarks does not exist, which means hg >= 1.8
-python -c 'import hgext.bookmarks' || exit 80
-
-# bail early if the user is already running git-daemon
-echo hi | nc localhost 9418 2>/dev/null && exit 80
-
-echo "[extensions]" >> $HGRCPATH
-echo "hggit=$(echo $(dirname $(dirname $0)))/hggit" >> $HGRCPATH
-echo 'hgext.graphlog =' >> $HGRCPATH
-
-GIT_AUTHOR_NAME='test'; export GIT_AUTHOR_NAME
-GIT_AUTHOR_EMAIL='test@example.org'; export GIT_AUTHOR_EMAIL
-GIT_AUTHOR_DATE="2007-01-01 00:00:00 +0000"; export GIT_AUTHOR_DATE
-GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME"; export GIT_COMMITTER_NAME
-GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"; export GIT_COMMITTER_EMAIL
-GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"; export GIT_COMMITTER_DATE
-
-count=10
-commit()
-{
-    GIT_AUTHOR_DATE="2007-01-01 00:00:$count +0000"
-    GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"
-    git commit "$@" >/dev/null 2>/dev/null || echo "git commit error"
-    count=`expr $count + 1`
-}
-
-mkdir gitrepo
-cd gitrepo
-git init | python -c "import sys; print sys.stdin.read().replace('$(dirname $(pwd))/', '')"
-echo alpha > alpha
-git add alpha
-commit -m 'add alpha'
-echo beta > beta
-git add beta
-commit -m 'add beta'
-
-# dulwich does not presently support local git repos, workaround
-cd ..
-git daemon --base-path="$(pwd)"\
- --listen=localhost\
- --export-all\
-  --pid-file="$DAEMON_PIDS" \
- --detach --reuseaddr
-
-hg clone git://localhost/gitrepo hgrepo | grep -v '^updating'
-cd hgrepo
-hg log --graph | grep -v ': *master'
-
-cd ..
deleted file mode 100644
--- a/tests/test-sane-without-bookmarks.out
+++ /dev/null
@@ -1,17 +0,0 @@
-Initialized empty Git repository in gitrepo/.git/
-
-creating bookmarks failed, do you have bookmarks enabled?
-importing git objects into hg
-2 files updated, 0 files merged, 0 files removed, 0 files unresolved
-@  changeset:   1:7bcd915dc873
-|  tag:         default/master
-|  tag:         tip
-|  user:        test <test@example.org>
-|  date:        Mon Jan 01 00:00:11 2007 +0000
-|  summary:     add beta
-|
-o  changeset:   0:3442585be8a6
-   user:        test <test@example.org>
-   date:        Mon Jan 01 00:00:10 2007 +0000
-   summary:     add alpha
-
new file mode 100644
--- /dev/null
+++ b/tests/test-subrepos.t
@@ -0,0 +1,115 @@
+Load commonly used test logic
+  $ . "$TESTDIR/testutil"
+
+  $ git init gitsubrepo
+  Initialized empty Git repository in $TESTTMP/gitsubrepo/.git/
+  $ cd gitsubrepo
+  $ echo beta > beta
+  $ git add beta
+  $ fn_git_commit -m 'add beta'
+  $ cd ..
+
+  $ git init gitrepo1
+  Initialized empty Git repository in $TESTTMP/gitrepo1/.git/
+  $ cd gitrepo1
+  $ echo alpha > alpha
+  $ git add alpha
+  $ fn_git_commit -m 'add alpha'
+  $ git submodule add ../gitsubrepo subrepo1
+  Cloning into 'subrepo1'...
+  done.
+  $ fn_git_commit -m 'add subrepo1'
+  $ git submodule add ../gitsubrepo xyz/subrepo2
+  Cloning into 'xyz/subrepo2'...
+  done.
+  $ fn_git_commit -m 'add subrepo2'
+we are going to push to this repo from our hg clone,
+allow commits despite working copy presense
+  $ git config receive.denyCurrentBranch ignore
+  $ cd ..
+Ensure gitlinks are transformed to .hgsubstate on hg pull from git
+  $ hg clone gitrepo1 hgrepo
+  importing git objects into hg
+  updating to branch default
+  cloning subrepo subrepo1 from $TESTTMP/gitsubrepo
+  cloning subrepo xyz/subrepo2 from $TESTTMP/gitsubrepo
+  4 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  $ cd hgrepo
+  $ hg bookmarks -f -r default master
+1. Ensure gitlinks are transformed to .hgsubstate on hg <- git pull
+.hgsub shall list two [git] subrepos
+  $ cat .hgsub
+  subrepo1 = [git]../gitsubrepo
+  xyz/subrepo2 = [git]../gitsubrepo
+.hgsubstate shall list two idenitcal revisions
+  $ cat .hgsubstate
+  56f0304c5250308f14cfbafdc27bd12d40154d17 subrepo1
+  56f0304c5250308f14cfbafdc27bd12d40154d17 xyz/subrepo2
+hg status shall NOT report .hgsub and .hgsubstate as untracked - either ignored or unmodified
+  $ hg status --unknown .hgsub .hgsubstate
+  $ hg status --modified .hgsub .hgsubstate
+  $ cd ..
+
+2. Check gitmodules are preserved during hg -> git push
+  $ cd gitsubrepo
+  $ echo gamma > gamma
+  $ git add gamma
+  $ fn_git_commit -m 'add gamma'
+  $ cd ..
+  $ cd hgrepo
+  $ cd xyz/subrepo2
+  $ git pull | sed 's/files/file/;s/insertions/insertion/;s/, 0 deletions.*//' | sed 's/|  */| /'
+  From $TESTTMP/gitsubrepo
+     56f0304..aabf7cd  master     -> origin/master
+  Updating 56f0304..aabf7cd
+  Fast-forward
+   gamma | 1 +
+   1 file changed, 1 insertion(+)
+   create mode 100644 gamma
+  $ cd ../..
+  $ echo xxx >> alpha
+  $ hg commit -m 'Update subrepo2 from hg' | grep -v "committing subrepository" || true
+  $ hg push
+  pushing to $TESTTMP/gitrepo1
+  searching for changes
+  $ cd ..
+  $ cd gitrepo1
+there shall be two gitlink entries, with values matching that in .hgsubstate
+  $ git ls-tree -r HEAD^{tree} | grep 'commit'
+  160000 commit 56f0304c5250308f14cfbafdc27bd12d40154d17	subrepo1
+  160000 commit aabf7cd015089aff0b84596e69aa37b24a3d090a	xyz/subrepo2
+bring working copy to HEAD state (it's not bare repo)
+  $ git reset --hard
+  HEAD is now at 4663c49 Update subrepo2 from hg
+  $ cd ..
+
+3. Check .hgsub and .hgsubstate from git repository are merged, not overwritten
+  $ hg init hgsub
+  $ cd hgsub
+  $ echo delta > delta
+  $ hg add delta
+  $ fn_hg_commit -m "add delta"
+  $ echo "`hg tip --template '{node}'` hgsub" > ../gitrepo1/.hgsubstate
+  $ echo "hgsub = $(pwd)" > ../gitrepo1/.hgsub
+  $ cd ../gitrepo1
+  $ git add .hgsubstate .hgsub
+  $ fn_git_commit -m "Test3. Prepare .hgsub and .hgsubstate sources"
+  $ cd ../hgrepo
+  $ hg pull
+  pulling from $TESTTMP/gitrepo1
+  importing git objects into hg
+  (run 'hg update' to get a working copy)
+  $ hg checkout -C
+  cloning subrepo hgsub from $TESTTMP/hgsub
+  2 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  $ cd ..
+pull shall bring .hgsub entry which was added to the git repo
+  $ cat hgrepo/.hgsub
+  hgsub = $TESTTMP/hgsub
+  subrepo1 = [git]../gitsubrepo
+  xyz/subrepo2 = [git]../gitsubrepo
+.hgsubstate shall list revision of the subrepo added through git repo
+  $ cat hgrepo/.hgsubstate
+  481ec30d580f333ae3a77f94c973ce37b69d5bda hgsub
+  56f0304c5250308f14cfbafdc27bd12d40154d17 subrepo1
+  aabf7cd015089aff0b84596e69aa37b24a3d090a xyz/subrepo2
deleted file mode 100644
--- a/tests/test-tree-decomposition.out
+++ /dev/null
@@ -1,33 +0,0 @@
-Initialized empty Git repository in gitrepo/.git/
-
-Initialized empty Git repository in gitrepo2/
-
-importing git objects into hg
-2 files updated, 0 files merged, 0 files removed, 0 files unresolved
-adds: d1
-dels: d1/f1
-adds: d2/f2
-dels: d1/f2
-adds: d1/f1 d1/f2
-dels: 
-clearing out the git cache data
-pushing to git://localhost/gitrepo2
-exporting hg objects to git
-creating and sending data
-commit 6e0dbd8cd92ed4823c69cb48d8a2b81f904e6e69
-Author: test <test@example.org>
-Date:   Mon Jan 1 00:00:12 2007 +0000
-
-    replace a dir with a file
-
-commit a1874d5cd0b1549ed729e36f0da4a93ed36259ee
-Author: test <test@example.org>
-Date:   Mon Jan 1 00:00:11 2007 +0000
-
-    rename
-
-commit 102c17a5deda49db3f10ec5573f9378867098b7c
-Author: test <test@example.org>
-Date:   Mon Jan 1 00:00:10 2007 +0000
-
-    initial
old mode 100755
new mode 100644
rename from tests/test-tree-decomposition
rename to tests/test-tree-decomposition.t
--- a/tests/test-tree-decomposition
+++ b/tests/test-tree-decomposition.t
@@ -1,76 +1,63 @@
-#!/bin/sh
-
-# Fails for some reason, need to investigate
-# "$TESTDIR/hghave" git || exit 80
-
-# bail if the user does not have dulwich
-python -c 'import dulwich, dulwich.repo' || exit 80
-
-# bail early if the user is already running git-daemon
-echo hi | nc localhost 9418 2> /dev/null && exit 80
-
-echo "[extensions]" >> $HGRCPATH
-echo "hggit=$(echo $(dirname $(dirname $0)))/hggit" >> $HGRCPATH
-echo 'hgext.bookmarks =' >> $HGRCPATH
-
-GIT_AUTHOR_NAME='test'; export GIT_AUTHOR_NAME
-GIT_AUTHOR_EMAIL='test@example.org'; export GIT_AUTHOR_EMAIL
-GIT_AUTHOR_DATE="2007-01-01 00:00:00 +0000"; export GIT_AUTHOR_DATE
-GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME"; export GIT_COMMITTER_NAME
-GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"; export GIT_COMMITTER_EMAIL
-GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"; export GIT_COMMITTER_DATE
+Load commonly used test logic
+  $ . "$TESTDIR/testutil"
 
-count=10
-commit()
-{
-    GIT_AUTHOR_DATE="2007-01-01 00:00:$count +0000"
-    GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"
-    git commit "$@" >/dev/null 2>/dev/null || echo "git commit error"
-    count=`expr $count + 1`
-}
-
-mkdir gitrepo
-cd gitrepo
-git init | python -c "import sys; print sys.stdin.read().replace('$(dirname $(pwd))/', '')"
+  $ git init gitrepo
+  Initialized empty Git repository in $TESTTMP/gitrepo/.git/
+  $ cd gitrepo
+  $ mkdir d1
+  $ echo a > d1/f1
+  $ echo b > d1/f2
+  $ git add d1/f1 d1/f2
+  $ fn_git_commit -m initial
 
-mkdir d1
-echo a > d1/f1
-echo b > d1/f2
-git add d1/f1 d1/f2
-commit -m initial
+  $ mkdir d2
+  $ git mv d1/f2 d2/f2
+  $ fn_git_commit -m 'rename'
 
-mkdir d2
-git mv d1/f2 d2/f2
-commit -m 'rename'
-
-rm -r d1
-echo c > d1
-git add d1
-commit -m 'replace a dir with a file'
+  $ rm -r d1
+  $ echo c > d1
+  $ git add d1
+  $ fn_git_commit -m 'replace a dir with a file'
 
 
-cd ..
-mkdir gitrepo2
-cd gitrepo2
-git init --bare | python -c "import sys; print sys.stdin.read().replace('$(dirname $(pwd))/', '')"
+  $ cd ..
+  $ git init --bare gitrepo2
+  Initialized empty Git repository in $TESTTMP/gitrepo2/
+
+  $ hg clone gitrepo hgrepo | grep -v '^updating'
+  importing git objects into hg
+  2 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  $ cd hgrepo
+  $ hg log --template 'adds: {file_adds}\ndels: {file_dels}\n'
+  adds: d1
+  dels: d1/f1
+  adds: d2/f2
+  dels: d1/f2
+  adds: d1/f1 d1/f2
+  dels: 
 
-# dulwich does not presently support local git repos, workaround
-cd ..
-git daemon --base-path="$(pwd)"\
- --listen=localhost\
- --export-all\
- --pid-file="$DAEMON_PIDS" \
- --detach --reuseaddr \
- --enable=receive-pack
+  $ hg gclear
+  clearing out the git cache data
+  $ hg push ../gitrepo2
+  pushing to ../gitrepo2
+  searching for changes
+  $ cd ..
 
-hg clone git://localhost/gitrepo hgrepo | grep -v '^updating'
-cd hgrepo
-hg log --template 'adds: {file_adds}\ndels: {file_dels}\n'
-
-hg gclear
-hg push git://localhost/gitrepo2
-
-cd ../gitrepo2
-git log --pretty=medium
-
-cd ..
+  $ git --git-dir=gitrepo2 log --pretty=medium
+  commit 6e0dbd8cd92ed4823c69cb48d8a2b81f904e6e69
+  Author: test <test@example.org>
+  Date:   Mon Jan 1 00:00:12 2007 +0000
+  
+      replace a dir with a file
+  
+  commit a1874d5cd0b1549ed729e36f0da4a93ed36259ee
+  Author: test <test@example.org>
+  Date:   Mon Jan 1 00:00:11 2007 +0000
+  
+      rename
+  
+  commit 102c17a5deda49db3f10ec5573f9378867098b7c
+  Author: test <test@example.org>
+  Date:   Mon Jan 1 00:00:10 2007 +0000
+  
+      initial
--- a/tests/test-url-parsing.py
+++ b/tests/test-url-parsing.py
@@ -1,4 +1,12 @@
-import os, sys, tempfile, unittest, shutil
+import sys
+
+try:
+    import dulwich
+except ImportError:
+    print "skipped: missing feature: dulwich"
+    sys.exit(80)
+
+import os, tempfile, unittest, shutil
 from mercurial import ui, hg, commands
 
 sys.path.append(os.path.join(os.path.dirname(__file__), os.path.pardir))
new file mode 100755
--- /dev/null
+++ b/tests/testutil
@@ -0,0 +1,57 @@
+#!/bin/sh
+
+# This file holds logic that is used in many tests.
+# It can be called in a test like this:
+#  $ . "$TESTDIR/testutil"
+
+# Activate extensions
+echo "[extensions]" >> $HGRCPATH
+echo "hggit=$(echo $(dirname $TESTDIR))/hggit" >> $HGRCPATH
+# Not needed in Mercurial 2.3+, as graphlog was integrated into core
+echo 'graphlog=' >> $HGRCPATH
+echo 'mq=' >> $HGRCPATH
+
+# Standard checks for external dependencies
+# We use the git command-line client and dulwich in pretty much all the tests.
+# Thus, to avoid repetitively declaring that requirement in almost every test,
+# we just call the checks in all tests that include this library.
+python -c 'import dulwich' || {
+    echo "skipped: missing feature: dulwich" && exit 80
+}
+"$TESTDIR/hghave" git || exit 80
+
+GIT_AUTHOR_NAME='test'; export GIT_AUTHOR_NAME
+GIT_AUTHOR_EMAIL='test@example.org'; export GIT_AUTHOR_EMAIL
+GIT_AUTHOR_DATE="2007-01-01 00:00:00 +0000"; export GIT_AUTHOR_DATE
+GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME"; export GIT_COMMITTER_NAME
+GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"; export GIT_COMMITTER_EMAIL
+GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"; export GIT_COMMITTER_DATE
+
+# Functions to commit and tag in Mercurial and Git in a predictable manner
+count=10
+
+fn_git_commit() {
+    GIT_AUTHOR_DATE="2007-01-01 00:00:$count +0000"
+    GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"
+    git commit "$@" >/dev/null || echo "git commit error"
+    count=`expr $count + 1`
+}
+
+fn_hg_commit() {
+    HGDATE="2007-01-01 00:00:$count +0000"
+    hg commit -d "$HGDATE" "$@" >/dev/null || echo "hg commit error"
+    count=`expr $count + 1`
+}
+
+fn_git_tag() {
+    GIT_AUTHOR_DATE="2007-01-01 00:00:$count +0000"
+    GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"
+    git tag "$@" >/dev/null || echo "git tag error"
+    count=`expr $count + 1`
+}
+
+fn_hg_tag() {
+    HGDATE="2007-01-01 00:00:$count +0000"
+    hg tag -d "$HGDATE" "$@" >/dev/null || echo "hg tag error"
+    count=`expr $count + 1`
+}