changeset 28218:41dcd7545266

merge with stable
author Matt Mackall <mpm@selenic.com>
date Wed, 24 Feb 2016 15:55:44 -0600
parents d2ac8b57a75d (diff) cb6a952efbf4 (current diff)
children 97fe88806f6f
files mercurial/cmdutil.py mercurial/help/config.txt mercurial/ui.py tests/test-paths.t
diffstat 166 files changed, 5155 insertions(+), 1241 deletions(-) [+]
line wrap: on
line diff
--- a/.hgignore	Tue Feb 23 11:41:47 2016 +0100
+++ b/.hgignore	Wed Feb 24 15:55:44 2016 -0600
@@ -25,6 +25,7 @@
 tests/*.err
 tests/htmlcov
 build
+contrib/chg/chg
 contrib/hgsh/hgsh
 contrib/vagrant/.vagrant
 dist
--- a/contrib/check-code.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/contrib/check-code.py	Wed Feb 24 15:55:44 2016 -0600
@@ -90,7 +90,7 @@
     (r'pushd|popd', "don't use 'pushd' or 'popd', use 'cd'"),
     (r'\W\$?\(\([^\)\n]*\)\)', "don't use (()) or $(()), use 'expr'"),
     (r'grep.*-q', "don't use 'grep -q', redirect to /dev/null"),
-    (r'(?<!hg )grep.*-a', "don't use 'grep -a', use in-line python"),
+    (r'(?<!hg )grep.* -a', "don't use 'grep -a', use in-line python"),
     (r'sed.*-i', "don't use 'sed -i', use a temporary file"),
     (r'\becho\b.*\\n', "don't use 'echo \\n', use printf"),
     (r'echo -n', "don't use 'echo -n', use printf"),
@@ -176,6 +176,19 @@
      'write "file:/*/$TESTTMP" + (glob) to match on windows too'),
     (r'^  (cat|find): .*: No such file or directory',
      'use test -f to test for file existence'),
+    (r'^  diff -[^ -]*p',
+     "don't use (external) diff with -p for portability"),
+    (r'^  [-+][-+][-+] .* [-+]0000 \(glob\)',
+     "glob timezone field in diff output for portability"),
+    (r'^  @@ -[0-9]+ [+][0-9]+,[0-9]+ @@',
+     "use '@@ -N* +N,n @@ (glob)' style chunk header for portability"),
+    (r'^  @@ -[0-9]+,[0-9]+ [+][0-9]+ @@',
+     "use '@@ -N,n +N* @@ (glob)' style chunk header for portability"),
+    (r'^  @@ -[0-9]+ [+][0-9]+ @@',
+     "use '@@ -N* +N* @@ (glob)' style chunk header for portability"),
+    (uprefix + r'hg( +-[^ ]+( +[^ ]+)?)* +extdiff'
+     r'( +(-[^ po-]+|--(?!program|option)[^ ]+|[^-][^ ]*))*$',
+     "use $RUNTESTDIR/pdiff via extdiff (or -o/-p for false-positives)"),
   ],
   # warnings
   [
@@ -475,7 +488,7 @@
         if debug:
             print name, f
         fc = 0
-        if not (re.match(match, f) or (magic and re.search(magic, f))):
+        if not (re.match(match, f) or (magic and re.search(magic, pre))):
             if debug:
                 print "Skipping %s for %s it doesn't match %s" % (
                        name, match, f)
--- a/contrib/check-commit	Tue Feb 23 11:41:47 2016 +0100
+++ b/contrib/check-commit	Wed Feb 24 15:55:44 2016 -0600
@@ -23,7 +23,8 @@
 
 errors = [
     (beforepatch + r".*[(]bc[)]", "(BC) needs to be uppercase"),
-    (beforepatch + r".*[(]issue \d\d\d", "no space allowed between issue and number"),
+    (beforepatch + r".*[(]issue \d\d\d",
+     "no space allowed between issue and number"),
     (beforepatch + r".*[(]bug(\d|\s)", "use (issueDDDD) instead of bug"),
     (commitheader + r"# User [^@\n]+\n", "username is not an email address"),
     (commitheader + r"(?!merge with )[^#]\S+[^:] ",
@@ -34,7 +35,7 @@
      "summary keyword should be most user-relevant one-word command or topic"),
     (afterheader + r".*\.\s*\n", "don't add trailing period on summary line"),
     (afterheader + r".{79,}", "summary line too long (limit is 78)"),
-    (r"\n\+\n \n", "adds double empty line"),
+    (r"\n\+\n( |\+)\n", "adds double empty line"),
     (r"\n \n\+\n", "adds double empty line"),
     (r"\n\+[ \t]+def [a-z]+_[a-z]", "adds a function with foo_bar naming"),
 ]
@@ -45,13 +46,12 @@
         return first
     return second
 
-def checkcommit(commit, node = None):
+def checkcommit(commit, node=None):
     exitcode = 0
     printed = node is None
     hits = []
     for exp, msg in errors:
-        m = re.search(exp, commit)
-        if m:
+        for m in re.finditer(exp, commit):
             end = m.end()
             trailing = re.search(r'(\\n)+$', exp)
             if trailing:
--- a/contrib/check-config.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/contrib/check-config.py	Wed Feb 24 15:55:44 2016 -0600
@@ -105,4 +105,7 @@
                 print "undocumented: %s (%s)%s" % (name, ctype, default)
 
 if __name__ == "__main__":
-    sys.exit(main(sys.argv[1:]))
+    if len(sys.argv) > 1:
+        sys.exit(main(sys.argv[1:]))
+    else:
+        sys.exit(main([l.rstrip() for l in sys.stdin]))
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contrib/chg/Makefile	Wed Feb 24 15:55:44 2016 -0600
@@ -0,0 +1,50 @@
+HG = $(CURDIR)/../../hg
+
+TARGET = chg
+SRCS = chg.c hgclient.c util.c
+OBJS = $(SRCS:.c=.o)
+
+CFLAGS ?= -O2 -Wall -Wextra -pedantic -g
+CPPFLAGS ?= -D_FORTIFY_SOURCE=2
+override CFLAGS += -std=gnu99
+
+DESTDIR =
+PREFIX = /usr/local
+MANDIR = $(PREFIX)/share/man/man1
+
+CHGSOCKDIR = /tmp/chg$(shell id -u)
+CHGSOCKNAME = $(CHGSOCKDIR)/server
+
+.PHONY: all
+all: $(TARGET)
+
+$(TARGET): $(OBJS)
+	$(CC) $(LDFLAGS) -o $@ $(OBJS)
+
+chg.o: hgclient.h util.h
+hgclient.o: hgclient.h util.h
+util.o: util.h
+
+.PHONY: install
+install: $(TARGET)
+	install -d $(DESTDIR)$(PREFIX)/bin
+	install -m 755 $(TARGET) $(DESTDIR)$(PREFIX)/bin
+	install -d $(DESTDIR)$(MANDIR)
+	install -m 644 chg.1 $(DESTDIR)$(MANDIR)
+
+.PHONY: serve
+serve:
+	[ -d $(CHGSOCKDIR) ] || ( umask 077; mkdir $(CHGSOCKDIR) )
+	$(HG) serve --cwd / --cmdserver chgunix \
+		--address $(CHGSOCKNAME) \
+		--config extensions.chgserver= \
+		--config progress.assume-tty=1 \
+		--config cmdserver.log=/dev/stderr
+
+.PHONY: clean
+clean:
+	$(RM) $(OBJS)
+
+.PHONY: distclean
+distclean:
+	$(RM) $(OBJS) $(TARGET)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contrib/chg/README	Wed Feb 24 15:55:44 2016 -0600
@@ -0,0 +1,32 @@
+cHg
+===
+
+A fast client for Mercurial command server running on Unix.
+
+Install:
+
+ $ make
+ $ make install
+
+Usage:
+
+ $ chg help                 # show help of Mercurial
+ $ alias hg=chg             # replace hg command
+ $ chg --kill-chg-daemon    # terminate background server
+ $ chg --reload-chg-daemon  # reload configuration files
+
+Environment variables:
+
+Although cHg tries to update environment variables, some of them cannot be
+changed after spawning the server. The following variables are specially
+handled:
+
+ * configuration files are reloaded if HGPLAIN or HGPLAINEXCEPT changed, but
+   some behaviors won't change correctly.
+ * CHGHG or HG specifies the path to the hg executable spawned as the
+   background command server.
+
+The following variables are available for testing:
+
+ * CHGDEBUG enables debug messages.
+ * CHGSOCKNAME specifies the socket path of the background cmdserver.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contrib/chg/chg.1	Wed Feb 24 15:55:44 2016 -0600
@@ -0,0 +1,44 @@
+.\"                                      Hey, EMACS: -*- nroff -*-
+.\" First parameter, NAME, should be all caps
+.\" Second parameter, SECTION, should be 1-8, maybe w/ subsection
+.\" other parameters are allowed: see man(7), man(1)
+.TH CHG 1 "March 3, 2013"
+.\" Please adjust this date whenever revising the manpage.
+.\"
+.\" Some roff macros, for reference:
+.\" .nh        disable hyphenation
+.\" .hy        enable hyphenation
+.\" .ad l      left justify
+.\" .ad b      justify to both left and right margins
+.\" .nf        disable filling
+.\" .fi        enable filling
+.\" .br        insert line break
+.\" .sp <n>    insert n+1 empty lines
+.\" for manpage-specific macros, see man(7)
+.SH NAME
+chg \- a fast client for Mercurial command server
+.SH SYNOPSIS
+.B chg
+.IR command " [" options "] [" arguments "]..."
+.br
+.SH DESCRIPTION
+The
+.B chg
+command is the wrapper for
+.B hg
+command.
+It uses the Mercurial command server to reduce start-up overhead.
+.SH OPTIONS
+This program accepts the same command line syntax as the
+.B hg
+command. Additionally it accepts the following options.
+.TP
+.B \-\-kill\-chg\-daemon
+Terminate the background command servers.
+.TP
+.B \-\-reload\-chg\-daemon
+Reload configuration files.
+.SH SEE ALSO
+.BR hg (1),
+.SH AUTHOR
+Written by Yuya Nishihara <yuya@tcha.org>.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contrib/chg/chg.c	Wed Feb 24 15:55:44 2016 -0600
@@ -0,0 +1,475 @@
+/*
+ * A fast client for Mercurial command server
+ *
+ * Copyright (c) 2011 Yuya Nishihara <yuya@tcha.org>
+ *
+ * This software may be used and distributed according to the terms of the
+ * GNU General Public License version 2 or any later version.
+ */
+
+#include <assert.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/file.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <sys/un.h>
+#include <sys/wait.h>
+#include <time.h>
+#include <unistd.h>
+
+#include "hgclient.h"
+#include "util.h"
+
+#ifndef UNIX_PATH_MAX
+#define UNIX_PATH_MAX (sizeof(((struct sockaddr_un *)NULL)->sun_path))
+#endif
+
+struct cmdserveropts {
+	char sockname[UNIX_PATH_MAX];
+	char lockfile[UNIX_PATH_MAX];
+	char pidfile[UNIX_PATH_MAX];
+	size_t argsize;
+	const char **args;
+	int lockfd;
+};
+
+static void initcmdserveropts(struct cmdserveropts *opts) {
+	memset(opts, 0, sizeof(struct cmdserveropts));
+	opts->lockfd = -1;
+}
+
+static void freecmdserveropts(struct cmdserveropts *opts) {
+	free(opts->args);
+	opts->args = NULL;
+	opts->argsize = 0;
+}
+
+/*
+ * Test if an argument is a sensitive flag that should be passed to the server.
+ * Return 0 if not, otherwise the number of arguments starting from the current
+ * one that should be passed to the server.
+ */
+static size_t testsensitiveflag(const char *arg)
+{
+	static const struct {
+		const char *name;
+		size_t narg;
+	} flags[] = {
+		{"--config", 1},
+		{"--cwd", 1},
+		{"--repo", 1},
+		{"--repository", 1},
+		{"--traceback", 0},
+		{"-R", 1},
+	};
+	size_t i;
+	for (i = 0; i < sizeof(flags) / sizeof(flags[0]); ++i) {
+		size_t len = strlen(flags[i].name);
+		size_t narg = flags[i].narg;
+		if (memcmp(arg, flags[i].name, len) == 0) {
+			if (arg[len] == '\0') {  /* --flag (value) */
+				return narg + 1;
+			} else if (arg[len] == '=' && narg > 0) {  /* --flag=value */
+				return 1;
+			} else if (flags[i].name[1] != '-') {  /* short flag */
+				return 1;
+			}
+		}
+	}
+	return 0;
+}
+
+/*
+ * Parse argv[] and put sensitive flags to opts->args
+ */
+static void setcmdserverargs(struct cmdserveropts *opts,
+			     int argc, const char *argv[])
+{
+	size_t i, step;
+	opts->argsize = 0;
+	for (i = 0, step = 1; i < (size_t)argc; i += step, step = 1) {
+		if (!argv[i])
+			continue;  /* pass clang-analyse */
+		if (strcmp(argv[i], "--") == 0)
+			break;
+		size_t n = testsensitiveflag(argv[i]);
+		if (n == 0 || i + n > (size_t)argc)
+			continue;
+		opts->args = reallocx(opts->args,
+				      (n + opts->argsize) * sizeof(char *));
+		memcpy(opts->args + opts->argsize, argv + i,
+		       sizeof(char *) * n);
+		opts->argsize += n;
+		step = n;
+	}
+}
+
+static void preparesockdir(const char *sockdir)
+{
+	int r;
+	r = mkdir(sockdir, 0700);
+	if (r < 0 && errno != EEXIST)
+		abortmsg("cannot create sockdir %s (errno = %d)",
+			 sockdir, errno);
+
+	struct stat st;
+	r = lstat(sockdir, &st);
+	if (r < 0)
+		abortmsg("cannot stat %s (errno = %d)", sockdir, errno);
+	if (!S_ISDIR(st.st_mode))
+		abortmsg("cannot create sockdir %s (file exists)", sockdir);
+	if (st.st_uid != geteuid() || st.st_mode & 0077)
+		abortmsg("insecure sockdir %s", sockdir);
+}
+
+static void setcmdserveropts(struct cmdserveropts *opts)
+{
+	int r;
+	char sockdir[UNIX_PATH_MAX];
+	const char *envsockname = getenv("CHGSOCKNAME");
+	if (!envsockname) {
+		/* by default, put socket file in secure directory
+		 * (permission of socket file may be ignored on some Unices) */
+		const char *tmpdir = getenv("TMPDIR");
+		if (!tmpdir)
+			tmpdir = "/tmp";
+		r = snprintf(sockdir, sizeof(sockdir), "%s/chg%d",
+			     tmpdir, geteuid());
+		if (r < 0 || (size_t)r >= sizeof(sockdir))
+			abortmsg("too long TMPDIR (r = %d)", r);
+		preparesockdir(sockdir);
+	}
+
+	const char *basename = (envsockname) ? envsockname : sockdir;
+	const char *sockfmt = (envsockname) ? "%s" : "%s/server";
+	const char *lockfmt = (envsockname) ? "%s.lock" : "%s/lock";
+	const char *pidfmt = (envsockname) ? "%s.pid" : "%s/pid";
+	r = snprintf(opts->sockname, sizeof(opts->sockname), sockfmt, basename);
+	if (r < 0 || (size_t)r >= sizeof(opts->sockname))
+		abortmsg("too long TMPDIR or CHGSOCKNAME (r = %d)", r);
+	r = snprintf(opts->lockfile, sizeof(opts->lockfile), lockfmt, basename);
+	if (r < 0 || (size_t)r >= sizeof(opts->lockfile))
+		abortmsg("too long TMPDIR or CHGSOCKNAME (r = %d)", r);
+	r = snprintf(opts->pidfile, sizeof(opts->pidfile), pidfmt, basename);
+	if (r < 0 || (size_t)r >= sizeof(opts->pidfile))
+		abortmsg("too long TMPDIR or CHGSOCKNAME (r = %d)", r);
+}
+
+/*
+ * Acquire a file lock that indicates a client is trying to start and connect
+ * to a server, before executing a command. The lock is released upon exit or
+ * explicit unlock. Will block if the lock is held by another process.
+ */
+static void lockcmdserver(struct cmdserveropts *opts)
+{
+	if (opts->lockfd == -1) {
+		opts->lockfd = open(opts->lockfile, O_RDWR | O_CREAT | O_NOFOLLOW, 0600);
+		if (opts->lockfd == -1)
+			abortmsg("cannot create lock file %s", opts->lockfile);
+	}
+	int r = flock(opts->lockfd, LOCK_EX);
+	if (r == -1)
+		abortmsg("cannot acquire lock");
+}
+
+/*
+ * Release the file lock held by calling lockcmdserver. Will do nothing if
+ * lockcmdserver is not called.
+ */
+static void unlockcmdserver(struct cmdserveropts *opts)
+{
+	if (opts->lockfd == -1)
+		return;
+	flock(opts->lockfd, LOCK_UN);
+	close(opts->lockfd);
+	opts->lockfd = -1;
+}
+
+static void execcmdserver(const struct cmdserveropts *opts)
+{
+	const char *hgcmd = getenv("CHGHG");
+	if (!hgcmd || hgcmd[0] == '\0')
+		hgcmd = getenv("HG");
+	if (!hgcmd || hgcmd[0] == '\0')
+		hgcmd = "hg";
+
+	const char *baseargv[] = {
+		hgcmd,
+		"serve",
+		"--cwd", "/",
+		"--cmdserver", "chgunix",
+		"--address", opts->sockname,
+		"--daemon-postexec", "none",
+		"--pid-file", opts->pidfile,
+		"--config", "extensions.chgserver=",
+		/* wrap root ui so that it can be disabled/enabled by config */
+		"--config", "progress.assume-tty=1",
+	};
+	size_t baseargvsize = sizeof(baseargv) / sizeof(baseargv[0]);
+	size_t argsize = baseargvsize + opts->argsize + 1;
+
+	const char **argv = mallocx(sizeof(char *) * argsize);
+	memcpy(argv, baseargv, sizeof(baseargv));
+	memcpy(argv + baseargvsize, opts->args, sizeof(char *) * opts->argsize);
+	argv[argsize - 1] = NULL;
+
+	if (execvp(hgcmd, (char **)argv) < 0)
+		abortmsg("failed to exec cmdserver (errno = %d)", errno);
+	free(argv);
+}
+
+/* Retry until we can connect to the server. Give up after some time. */
+static hgclient_t *retryconnectcmdserver(struct cmdserveropts *opts, pid_t pid)
+{
+	static const struct timespec sleepreq = {0, 10 * 1000000};
+	int pst = 0;
+
+	for (unsigned int i = 0; i < 10 * 100; i++) {
+		hgclient_t *hgc = hgc_open(opts->sockname);
+		if (hgc)
+			return hgc;
+
+		if (pid > 0) {
+			/* collect zombie if child process fails to start */
+			int r = waitpid(pid, &pst, WNOHANG);
+			if (r != 0)
+				goto cleanup;
+		}
+
+		nanosleep(&sleepreq, NULL);
+	}
+
+	abortmsg("timed out waiting for cmdserver %s", opts->sockname);
+	return NULL;
+
+cleanup:
+	if (WIFEXITED(pst)) {
+		abortmsg("cmdserver exited with status %d", WEXITSTATUS(pst));
+	} else if (WIFSIGNALED(pst)) {
+		abortmsg("cmdserver killed by signal %d", WTERMSIG(pst));
+	} else {
+		abortmsg("error white waiting cmdserver");
+	}
+	return NULL;
+}
+
+/* Connect to a cmdserver. Will start a new server on demand. */
+static hgclient_t *connectcmdserver(struct cmdserveropts *opts)
+{
+	hgclient_t *hgc = hgc_open(opts->sockname);
+	if (hgc)
+		return hgc;
+
+	lockcmdserver(opts);
+	hgc = hgc_open(opts->sockname);
+	if (hgc) {
+		unlockcmdserver(opts);
+		debugmsg("cmdserver is started by another process");
+		return hgc;
+	}
+
+	debugmsg("start cmdserver at %s", opts->sockname);
+
+	pid_t pid = fork();
+	if (pid < 0)
+		abortmsg("failed to fork cmdserver process");
+	if (pid == 0) {
+		/* do not leak lockfd to hg */
+		close(opts->lockfd);
+		/* bypass uisetup() of pager extension */
+		int nullfd = open("/dev/null", O_WRONLY);
+		if (nullfd >= 0) {
+			dup2(nullfd, fileno(stdout));
+			close(nullfd);
+		}
+		execcmdserver(opts);
+	} else {
+		hgc = retryconnectcmdserver(opts, pid);
+	}
+
+	unlockcmdserver(opts);
+	return hgc;
+}
+
+static void killcmdserver(const struct cmdserveropts *opts, int sig)
+{
+	FILE *fp = fopen(opts->pidfile, "r");
+	if (!fp)
+		abortmsg("cannot open %s (errno = %d)", opts->pidfile, errno);
+	int pid = 0;
+	int n = fscanf(fp, "%d", &pid);
+	fclose(fp);
+	if (n != 1 || pid <= 0)
+		abortmsg("cannot read pid from %s", opts->pidfile);
+
+	if (kill((pid_t)pid, sig) < 0) {
+		if (errno == ESRCH)
+			return;
+		abortmsg("cannot kill %d (errno = %d)", pid, errno);
+	}
+}
+
+static pid_t peerpid = 0;
+
+static void forwardsignal(int sig)
+{
+	assert(peerpid > 0);
+	if (kill(peerpid, sig) < 0)
+		abortmsg("cannot kill %d (errno = %d)", peerpid, errno);
+	debugmsg("forward signal %d", sig);
+}
+
+static void handlestopsignal(int sig)
+{
+	sigset_t unblockset, oldset;
+	struct sigaction sa, oldsa;
+	if (sigemptyset(&unblockset) < 0)
+		goto error;
+	if (sigaddset(&unblockset, sig) < 0)
+		goto error;
+	memset(&sa, 0, sizeof(sa));
+	sa.sa_handler = SIG_DFL;
+	sa.sa_flags = SA_RESTART;
+	if (sigemptyset(&sa.sa_mask) < 0)
+		goto error;
+
+	forwardsignal(sig);
+	if (raise(sig) < 0)  /* resend to self */
+		goto error;
+	if (sigaction(sig, &sa, &oldsa) < 0)
+		goto error;
+	if (sigprocmask(SIG_UNBLOCK, &unblockset, &oldset) < 0)
+		goto error;
+	/* resent signal will be handled before sigprocmask() returns */
+	if (sigprocmask(SIG_SETMASK, &oldset, NULL) < 0)
+		goto error;
+	if (sigaction(sig, &oldsa, NULL) < 0)
+		goto error;
+	return;
+
+error:
+	abortmsg("failed to handle stop signal (errno = %d)", errno);
+}
+
+static void setupsignalhandler(pid_t pid)
+{
+	if (pid <= 0)
+		return;
+	peerpid = pid;
+
+	struct sigaction sa;
+	memset(&sa, 0, sizeof(sa));
+	sa.sa_handler = forwardsignal;
+	sa.sa_flags = SA_RESTART;
+	if (sigemptyset(&sa.sa_mask) < 0)
+		goto error;
+
+	if (sigaction(SIGHUP, &sa, NULL) < 0)
+		goto error;
+	if (sigaction(SIGINT, &sa, NULL) < 0)
+		goto error;
+
+	/* terminate frontend by double SIGTERM in case of server freeze */
+	sa.sa_flags |= SA_RESETHAND;
+	if (sigaction(SIGTERM, &sa, NULL) < 0)
+		goto error;
+
+	/* propagate job control requests to worker */
+	sa.sa_handler = forwardsignal;
+	sa.sa_flags = SA_RESTART;
+	if (sigaction(SIGCONT, &sa, NULL) < 0)
+		goto error;
+	sa.sa_handler = handlestopsignal;
+	sa.sa_flags = SA_RESTART;
+	if (sigaction(SIGTSTP, &sa, NULL) < 0)
+		goto error;
+
+	return;
+
+error:
+	abortmsg("failed to set up signal handlers (errno = %d)", errno);
+}
+
+/* This implementation is based on hgext/pager.py (pre 369741ef7253) */
+static void setuppager(hgclient_t *hgc, const char *const args[],
+		       size_t argsize)
+{
+	const char *pagercmd = hgc_getpager(hgc, args, argsize);
+	if (!pagercmd)
+		return;
+
+	int pipefds[2];
+	if (pipe(pipefds) < 0)
+		return;
+	pid_t pid = fork();
+	if (pid < 0)
+		goto error;
+	if (pid == 0) {
+		close(pipefds[0]);
+		if (dup2(pipefds[1], fileno(stdout)) < 0)
+			goto error;
+		if (isatty(fileno(stderr))) {
+			if (dup2(pipefds[1], fileno(stderr)) < 0)
+				goto error;
+		}
+		close(pipefds[1]);
+		hgc_attachio(hgc);  /* reattach to pager */
+		return;
+	} else {
+		dup2(pipefds[0], fileno(stdin));
+		close(pipefds[0]);
+		close(pipefds[1]);
+
+		int r = execlp("/bin/sh", "/bin/sh", "-c", pagercmd, NULL);
+		if (r < 0) {
+			abortmsg("cannot start pager '%s' (errno = %d)",
+				 pagercmd, errno);
+		}
+		return;
+	}
+
+error:
+	close(pipefds[0]);
+	close(pipefds[1]);
+	abortmsg("failed to prepare pager (errno = %d)", errno);
+}
+
+int main(int argc, const char *argv[], const char *envp[])
+{
+	if (getenv("CHGDEBUG"))
+		enabledebugmsg();
+
+	struct cmdserveropts opts;
+	initcmdserveropts(&opts);
+	setcmdserveropts(&opts);
+	setcmdserverargs(&opts, argc, argv);
+
+	if (argc == 2) {
+		int sig = 0;
+		if (strcmp(argv[1], "--kill-chg-daemon") == 0)
+			sig = SIGTERM;
+		if (strcmp(argv[1], "--reload-chg-daemon") == 0)
+			sig = SIGHUP;
+		if (sig > 0) {
+			killcmdserver(&opts, sig);
+			return 0;
+		}
+	}
+
+	hgclient_t *hgc = connectcmdserver(&opts);
+	if (!hgc)
+		abortmsg("cannot open hg client");
+
+	setupsignalhandler(hgc_peerpid(hgc));
+	hgc_setenv(hgc, envp);
+	setuppager(hgc, argv + 1, argc - 1);
+	int exitcode = hgc_runcommand(hgc, argv + 1, argc - 1);
+	hgc_close(hgc);
+	freecmdserveropts(&opts);
+	return exitcode;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contrib/chg/hgclient.c	Wed Feb 24 15:55:44 2016 -0600
@@ -0,0 +1,535 @@
+/*
+ * A command server client that uses Unix domain socket
+ *
+ * Copyright (c) 2011 Yuya Nishihara <yuya@tcha.org>
+ *
+ * This software may be used and distributed according to the terms of the
+ * GNU General Public License version 2 or any later version.
+ */
+
+#include <arpa/inet.h>  /* for ntohl(), htonl() */
+#include <assert.h>
+#include <ctype.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <signal.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/un.h>
+#include <unistd.h>
+
+#include "hgclient.h"
+#include "util.h"
+
+enum {
+	CAP_GETENCODING = 0x0001,
+	CAP_RUNCOMMAND = 0x0002,
+	/* cHg extension: */
+	CAP_ATTACHIO = 0x0100,
+	CAP_CHDIR = 0x0200,
+	CAP_GETPAGER = 0x0400,
+	CAP_SETENV = 0x0800,
+	CAP_SETUMASK = 0x1000,
+};
+
+typedef struct {
+	const char *name;
+	unsigned int flag;
+} cappair_t;
+
+static const cappair_t captable[] = {
+	{"getencoding", CAP_GETENCODING},
+	{"runcommand", CAP_RUNCOMMAND},
+	{"attachio", CAP_ATTACHIO},
+	{"chdir", CAP_CHDIR},
+	{"getpager", CAP_GETPAGER},
+	{"setenv", CAP_SETENV},
+	{"setumask", CAP_SETUMASK},
+	{NULL, 0},  /* terminator */
+};
+
+typedef struct {
+	char ch;
+	char *data;
+	size_t maxdatasize;
+	size_t datasize;
+} context_t;
+
+struct hgclient_tag_ {
+	int sockfd;
+	pid_t pid;
+	context_t ctx;
+	unsigned int capflags;
+};
+
+static const size_t defaultdatasize = 4096;
+
+static void initcontext(context_t *ctx)
+{
+	ctx->ch = '\0';
+	ctx->data = malloc(defaultdatasize);
+	ctx->maxdatasize = (ctx->data) ? defaultdatasize : 0;
+	ctx->datasize = 0;
+	debugmsg("initialize context buffer with size %zu", ctx->maxdatasize);
+}
+
+static void enlargecontext(context_t *ctx, size_t newsize)
+{
+	if (newsize <= ctx->maxdatasize)
+		return;
+
+	newsize = defaultdatasize
+		* ((newsize + defaultdatasize - 1) / defaultdatasize);
+	ctx->data = reallocx(ctx->data, newsize);
+	ctx->maxdatasize = newsize;
+	debugmsg("enlarge context buffer to %zu", ctx->maxdatasize);
+}
+
+static void freecontext(context_t *ctx)
+{
+	debugmsg("free context buffer");
+	free(ctx->data);
+	ctx->data = NULL;
+	ctx->maxdatasize = 0;
+	ctx->datasize = 0;
+}
+
+/* Read channeled response from cmdserver */
+static void readchannel(hgclient_t *hgc)
+{
+	assert(hgc);
+
+	ssize_t rsize = recv(hgc->sockfd, &hgc->ctx.ch, sizeof(hgc->ctx.ch), 0);
+	if (rsize != sizeof(hgc->ctx.ch))
+		abortmsg("failed to read channel");
+
+	uint32_t datasize_n;
+	rsize = recv(hgc->sockfd, &datasize_n, sizeof(datasize_n), 0);
+	if (rsize != sizeof(datasize_n))
+		abortmsg("failed to read data size");
+
+	/* datasize denotes the maximum size to write if input request */
+	hgc->ctx.datasize = ntohl(datasize_n);
+	enlargecontext(&hgc->ctx, hgc->ctx.datasize);
+
+	if (isupper(hgc->ctx.ch) && hgc->ctx.ch != 'S')
+		return;  /* assumes input request */
+
+	size_t cursize = 0;
+	while (cursize < hgc->ctx.datasize) {
+		rsize = recv(hgc->sockfd, hgc->ctx.data + cursize,
+			     hgc->ctx.datasize - cursize, 0);
+		if (rsize < 0)
+			abortmsg("failed to read data block");
+		cursize += rsize;
+	}
+}
+
+static void sendall(int sockfd, const void *data, size_t datasize)
+{
+	const char *p = data;
+	const char *const endp = p + datasize;
+	while (p < endp) {
+		ssize_t r = send(sockfd, p, endp - p, 0);
+		if (r < 0)
+			abortmsg("cannot communicate (errno = %d)", errno);
+		p += r;
+	}
+}
+
+/* Write lengh-data block to cmdserver */
+static void writeblock(const hgclient_t *hgc)
+{
+	assert(hgc);
+
+	const uint32_t datasize_n = htonl(hgc->ctx.datasize);
+	sendall(hgc->sockfd, &datasize_n, sizeof(datasize_n));
+
+	sendall(hgc->sockfd, hgc->ctx.data, hgc->ctx.datasize);
+}
+
+static void writeblockrequest(const hgclient_t *hgc, const char *chcmd)
+{
+	debugmsg("request %s, block size %zu", chcmd, hgc->ctx.datasize);
+
+	char buf[strlen(chcmd) + 1];
+	memcpy(buf, chcmd, sizeof(buf) - 1);
+	buf[sizeof(buf) - 1] = '\n';
+	sendall(hgc->sockfd, buf, sizeof(buf));
+
+	writeblock(hgc);
+}
+
+/* Build '\0'-separated list of args. argsize < 0 denotes that args are
+ * terminated by NULL. */
+static void packcmdargs(context_t *ctx, const char *const args[],
+			ssize_t argsize)
+{
+	ctx->datasize = 0;
+	const char *const *const end = (argsize >= 0) ? args + argsize : NULL;
+	for (const char *const *it = args; it != end && *it; ++it) {
+		const size_t n = strlen(*it) + 1;  /* include '\0' */
+		enlargecontext(ctx, ctx->datasize + n);
+		memcpy(ctx->data + ctx->datasize, *it, n);
+		ctx->datasize += n;
+	}
+
+	if (ctx->datasize > 0)
+		--ctx->datasize;  /* strip last '\0' */
+}
+
+/* Extract '\0'-separated list of args to new buffer, terminated by NULL */
+static const char **unpackcmdargsnul(const context_t *ctx)
+{
+	const char **args = NULL;
+	size_t nargs = 0, maxnargs = 0;
+	const char *s = ctx->data;
+	const char *e = ctx->data + ctx->datasize;
+	for (;;) {
+		if (nargs + 1 >= maxnargs) {  /* including last NULL */
+			maxnargs += 256;
+			args = reallocx(args, maxnargs * sizeof(args[0]));
+		}
+		args[nargs] = s;
+		nargs++;
+		s = memchr(s, '\0', e - s);
+		if (!s)
+			break;
+		s++;
+	}
+	args[nargs] = NULL;
+	return args;
+}
+
+static void handlereadrequest(hgclient_t *hgc)
+{
+	context_t *ctx = &hgc->ctx;
+	size_t r = fread(ctx->data, sizeof(ctx->data[0]), ctx->datasize, stdin);
+	ctx->datasize = r;
+	writeblock(hgc);
+}
+
+/* Read single-line */
+static void handlereadlinerequest(hgclient_t *hgc)
+{
+	context_t *ctx = &hgc->ctx;
+	if (!fgets(ctx->data, ctx->datasize, stdin))
+		ctx->data[0] = '\0';
+	ctx->datasize = strlen(ctx->data);
+	writeblock(hgc);
+}
+
+/* Execute the requested command and write exit code */
+static void handlesystemrequest(hgclient_t *hgc)
+{
+	context_t *ctx = &hgc->ctx;
+	enlargecontext(ctx, ctx->datasize + 1);
+	ctx->data[ctx->datasize] = '\0';  /* terminate last string */
+
+	const char **args = unpackcmdargsnul(ctx);
+	if (!args[0] || !args[1])
+		abortmsg("missing command or cwd in system request");
+	debugmsg("run '%s' at '%s'", args[0], args[1]);
+	int32_t r = runshellcmd(args[0], args + 2, args[1]);
+	free(args);
+
+	uint32_t r_n = htonl(r);
+	memcpy(ctx->data, &r_n, sizeof(r_n));
+	ctx->datasize = sizeof(r_n);
+	writeblock(hgc);
+}
+
+/* Read response of command execution until receiving 'r'-esult */
+static void handleresponse(hgclient_t *hgc)
+{
+	for (;;) {
+		readchannel(hgc);
+		context_t *ctx = &hgc->ctx;
+		debugmsg("response read from channel %c, size %zu",
+			 ctx->ch, ctx->datasize);
+		switch (ctx->ch) {
+		case 'o':
+			fwrite(ctx->data, sizeof(ctx->data[0]), ctx->datasize,
+			       stdout);
+			break;
+		case 'e':
+			fwrite(ctx->data, sizeof(ctx->data[0]), ctx->datasize,
+			       stderr);
+			break;
+		case 'd':
+			/* assumes last char is '\n' */
+			ctx->data[ctx->datasize - 1] = '\0';
+			debugmsg("server: %s", ctx->data);
+			break;
+		case 'r':
+			return;
+		case 'I':
+			handlereadrequest(hgc);
+			break;
+		case 'L':
+			handlereadlinerequest(hgc);
+			break;
+		case 'S':
+			handlesystemrequest(hgc);
+			break;
+		default:
+			if (isupper(ctx->ch))
+				abortmsg("cannot handle response (ch = %c)",
+					 ctx->ch);
+		}
+	}
+}
+
+static unsigned int parsecapabilities(const char *s, const char *e)
+{
+	unsigned int flags = 0;
+	while (s < e) {
+		const char *t = strchr(s, ' ');
+		if (!t || t > e)
+			t = e;
+		const cappair_t *cap;
+		for (cap = captable; cap->flag; ++cap) {
+			size_t n = t - s;
+			if (strncmp(s, cap->name, n) == 0 &&
+			    strlen(cap->name) == n) {
+				flags |= cap->flag;
+				break;
+			}
+		}
+		s = t + 1;
+	}
+	return flags;
+}
+
+static void readhello(hgclient_t *hgc)
+{
+	readchannel(hgc);
+	context_t *ctx = &hgc->ctx;
+	if (ctx->ch != 'o')
+		abortmsg("unexpected channel of hello message (ch = %c)",
+			 ctx->ch);
+	enlargecontext(ctx, ctx->datasize + 1);
+	ctx->data[ctx->datasize] = '\0';
+	debugmsg("hello received: %s (size = %zu)", ctx->data, ctx->datasize);
+
+	const char *s = ctx->data;
+	const char *const dataend = ctx->data + ctx->datasize;
+	while (s < dataend) {
+		const char *t = strchr(s, ':');
+		if (!t || t[1] != ' ')
+			break;
+		const char *u = strchr(t + 2, '\n');
+		if (!u)
+			u = dataend;
+		if (strncmp(s, "capabilities:", t - s + 1) == 0) {
+			hgc->capflags = parsecapabilities(t + 2, u);
+		} else if (strncmp(s, "pid:", t - s + 1) == 0) {
+			hgc->pid = strtol(t + 2, NULL, 10);
+		}
+		s = u + 1;
+	}
+	debugmsg("capflags=0x%04x, pid=%d", hgc->capflags, hgc->pid);
+}
+
+static void attachio(hgclient_t *hgc)
+{
+	debugmsg("request attachio");
+	static const char chcmd[] = "attachio\n";
+	sendall(hgc->sockfd, chcmd, sizeof(chcmd) - 1);
+	readchannel(hgc);
+	context_t *ctx = &hgc->ctx;
+	if (ctx->ch != 'I')
+		abortmsg("unexpected response for attachio (ch = %c)", ctx->ch);
+
+	static const int fds[3] = {STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO};
+	struct msghdr msgh;
+	memset(&msgh, 0, sizeof(msgh));
+	struct iovec iov = {ctx->data, ctx->datasize};  /* dummy payload */
+	msgh.msg_iov = &iov;
+	msgh.msg_iovlen = 1;
+	char fdbuf[CMSG_SPACE(sizeof(fds))];
+	msgh.msg_control = fdbuf;
+	msgh.msg_controllen = sizeof(fdbuf);
+	struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msgh);
+	cmsg->cmsg_level = SOL_SOCKET;
+	cmsg->cmsg_type = SCM_RIGHTS;
+	cmsg->cmsg_len = CMSG_LEN(sizeof(fds));
+	memcpy(CMSG_DATA(cmsg), fds, sizeof(fds));
+	msgh.msg_controllen = cmsg->cmsg_len;
+	ssize_t r = sendmsg(hgc->sockfd, &msgh, 0);
+	if (r < 0)
+		abortmsg("sendmsg failed (errno = %d)", errno);
+
+	handleresponse(hgc);
+	int32_t n;
+	if (ctx->datasize != sizeof(n))
+		abortmsg("unexpected size of attachio result");
+	memcpy(&n, ctx->data, sizeof(n));
+	n = ntohl(n);
+	if (n != sizeof(fds) / sizeof(fds[0]))
+		abortmsg("failed to send fds (n = %d)", n);
+}
+
+static void chdirtocwd(hgclient_t *hgc)
+{
+	if (!getcwd(hgc->ctx.data, hgc->ctx.maxdatasize))
+		abortmsg("failed to getcwd (errno = %d)", errno);
+	hgc->ctx.datasize = strlen(hgc->ctx.data);
+	writeblockrequest(hgc, "chdir");
+}
+
+static void forwardumask(hgclient_t *hgc)
+{
+	mode_t mask = umask(0);
+	umask(mask);
+
+	static const char command[] = "setumask\n";
+	sendall(hgc->sockfd, command, sizeof(command) - 1);
+	uint32_t data = htonl(mask);
+	sendall(hgc->sockfd, &data, sizeof(data));
+}
+
+/*!
+ * Open connection to per-user cmdserver
+ *
+ * If no background server running, returns NULL.
+ */
+hgclient_t *hgc_open(const char *sockname)
+{
+	int fd = socket(AF_UNIX, SOCK_STREAM, 0);
+	if (fd < 0)
+		abortmsg("cannot create socket (errno = %d)", errno);
+
+	/* don't keep fd on fork(), so that it can be closed when the parent
+	 * process get terminated. */
+	int flags = fcntl(fd, F_GETFD);
+	if (flags < 0)
+		abortmsg("cannot get flags of socket (errno = %d)", errno);
+	if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) < 0)
+		abortmsg("cannot set flags of socket (errno = %d)", errno);
+
+	struct sockaddr_un addr;
+	addr.sun_family = AF_UNIX;
+	strncpy(addr.sun_path, sockname, sizeof(addr.sun_path));
+	addr.sun_path[sizeof(addr.sun_path) - 1] = '\0';
+
+	debugmsg("connect to %s", addr.sun_path);
+	int r = connect(fd, (struct sockaddr *)&addr, sizeof(addr));
+	if (r < 0) {
+		close(fd);
+		if (errno == ENOENT || errno == ECONNREFUSED)
+			return NULL;
+		abortmsg("cannot connect to %s (errno = %d)",
+			 addr.sun_path, errno);
+	}
+
+	hgclient_t *hgc = mallocx(sizeof(hgclient_t));
+	memset(hgc, 0, sizeof(*hgc));
+	hgc->sockfd = fd;
+	initcontext(&hgc->ctx);
+
+	readhello(hgc);
+	if (!(hgc->capflags & CAP_RUNCOMMAND))
+		abortmsg("insufficient capability: runcommand");
+	if (hgc->capflags & CAP_ATTACHIO)
+		attachio(hgc);
+	if (hgc->capflags & CAP_CHDIR)
+		chdirtocwd(hgc);
+	if (hgc->capflags & CAP_SETUMASK)
+		forwardumask(hgc);
+
+	return hgc;
+}
+
+/*!
+ * Close connection and free allocated memory
+ */
+void hgc_close(hgclient_t *hgc)
+{
+	assert(hgc);
+	freecontext(&hgc->ctx);
+	close(hgc->sockfd);
+	free(hgc);
+}
+
+pid_t hgc_peerpid(const hgclient_t *hgc)
+{
+	assert(hgc);
+	return hgc->pid;
+}
+
+/*!
+ * Execute the specified Mercurial command
+ *
+ * @return result code
+ */
+int hgc_runcommand(hgclient_t *hgc, const char *const args[], size_t argsize)
+{
+	assert(hgc);
+
+	packcmdargs(&hgc->ctx, args, argsize);
+	writeblockrequest(hgc, "runcommand");
+	handleresponse(hgc);
+
+	int32_t exitcode_n;
+	if (hgc->ctx.datasize != sizeof(exitcode_n)) {
+		abortmsg("unexpected size of exitcode");
+	}
+	memcpy(&exitcode_n, hgc->ctx.data, sizeof(exitcode_n));
+	return ntohl(exitcode_n);
+}
+
+/*!
+ * (Re-)send client's stdio channels so that the server can access to tty
+ */
+void hgc_attachio(hgclient_t *hgc)
+{
+	assert(hgc);
+	if (!(hgc->capflags & CAP_ATTACHIO))
+		return;
+	attachio(hgc);
+}
+
+/*!
+ * Get pager command for the given Mercurial command args
+ *
+ * If no pager enabled, returns NULL. The return value becomes invalid
+ * once you run another request to hgc.
+ */
+const char *hgc_getpager(hgclient_t *hgc, const char *const args[],
+			 size_t argsize)
+{
+	assert(hgc);
+
+	if (!(hgc->capflags & CAP_GETPAGER))
+		return NULL;
+
+	packcmdargs(&hgc->ctx, args, argsize);
+	writeblockrequest(hgc, "getpager");
+	handleresponse(hgc);
+
+	if (hgc->ctx.datasize < 1 || hgc->ctx.data[0] == '\0')
+		return NULL;
+	enlargecontext(&hgc->ctx, hgc->ctx.datasize + 1);
+	hgc->ctx.data[hgc->ctx.datasize] = '\0';
+	return hgc->ctx.data;
+}
+
+/*!
+ * Update server's environment variables
+ *
+ * @param envp  list of environment variables in "NAME=VALUE" format,
+ *              terminated by NULL.
+ */
+void hgc_setenv(hgclient_t *hgc, const char *const envp[])
+{
+	assert(hgc && envp);
+	if (!(hgc->capflags & CAP_SETENV))
+		return;
+	packcmdargs(&hgc->ctx, envp, /*argsize*/ -1);
+	writeblockrequest(hgc, "setenv");
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contrib/chg/hgclient.h	Wed Feb 24 15:55:44 2016 -0600
@@ -0,0 +1,29 @@
+/*
+ * A command server client that uses Unix domain socket
+ *
+ * Copyright (c) 2011 Yuya Nishihara <yuya@tcha.org>
+ *
+ * This software may be used and distributed according to the terms of the
+ * GNU General Public License version 2 or any later version.
+ */
+
+#ifndef HGCLIENT_H_
+#define HGCLIENT_H_
+
+#include <sys/types.h>
+
+struct hgclient_tag_;
+typedef struct hgclient_tag_ hgclient_t;
+
+hgclient_t *hgc_open(const char *sockname);
+void hgc_close(hgclient_t *hgc);
+
+pid_t hgc_peerpid(const hgclient_t *hgc);
+
+int hgc_runcommand(hgclient_t *hgc, const char *const args[], size_t argsize);
+void hgc_attachio(hgclient_t *hgc);
+const char *hgc_getpager(hgclient_t *hgc, const char *const args[],
+			 size_t argsize);
+void hgc_setenv(hgclient_t *hgc, const char *const envp[]);
+
+#endif  /* HGCLIENT_H_ */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contrib/chg/util.c	Wed Feb 24 15:55:44 2016 -0600
@@ -0,0 +1,139 @@
+/*
+ * Utility functions
+ *
+ * Copyright (c) 2011 Yuya Nishihara <yuya@tcha.org>
+ *
+ * This software may be used and distributed according to the terms of the
+ * GNU General Public License version 2 or any later version.
+ */
+
+#include <signal.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+#include "util.h"
+
+void abortmsg(const char *fmt, ...)
+{
+	va_list args;
+	va_start(args, fmt);
+	fputs("\033[1;31mchg: abort: ", stderr);
+	vfprintf(stderr, fmt, args);
+	fputs("\033[m\n", stderr);
+	va_end(args);
+
+	exit(255);
+}
+
+static int debugmsgenabled = 0;
+
+void enabledebugmsg(void)
+{
+	debugmsgenabled = 1;
+}
+
+void debugmsg(const char *fmt, ...)
+{
+	if (!debugmsgenabled)
+		return;
+
+	va_list args;
+	va_start(args, fmt);
+	fputs("\033[1;30mchg: debug: ", stderr);
+	vfprintf(stderr, fmt, args);
+	fputs("\033[m\n", stderr);
+	va_end(args);
+}
+
+void *mallocx(size_t size)
+{
+	void *result = malloc(size);
+	if (!result)
+		abortmsg("failed to malloc");
+	return result;
+}
+
+void *reallocx(void *ptr, size_t size)
+{
+	void *result = realloc(ptr, size);
+	if (!result)
+		abortmsg("failed to realloc");
+	return result;
+}
+
+/*
+ * Execute a shell command in mostly the same manner as system(), with the
+ * give environment variables, after chdir to the given cwd. Returns a status
+ * code compatible with the Python subprocess module.
+ */
+int runshellcmd(const char *cmd, const char *envp[], const char *cwd)
+{
+	enum { F_SIGINT = 1, F_SIGQUIT = 2, F_SIGMASK = 4, F_WAITPID = 8 };
+	unsigned int doneflags = 0;
+	int status = 0;
+	struct sigaction newsa, oldsaint, oldsaquit;
+	sigset_t oldmask;
+
+	/* block or mask signals just as system() does */
+	memset(&newsa, 0, sizeof(newsa));
+	newsa.sa_handler = SIG_IGN;
+	newsa.sa_flags = 0;
+	if (sigemptyset(&newsa.sa_mask) < 0)
+		goto done;
+	if (sigaction(SIGINT, &newsa, &oldsaint) < 0)
+		goto done;
+	doneflags |= F_SIGINT;
+	if (sigaction(SIGQUIT, &newsa, &oldsaquit) < 0)
+		goto done;
+	doneflags |= F_SIGQUIT;
+
+	if (sigaddset(&newsa.sa_mask, SIGCHLD) < 0)
+		goto done;
+	if (sigprocmask(SIG_BLOCK, &newsa.sa_mask, &oldmask) < 0)
+		goto done;
+	doneflags |= F_SIGMASK;
+
+	pid_t pid = fork();
+	if (pid < 0)
+		goto done;
+	if (pid == 0) {
+		sigaction(SIGINT, &oldsaint, NULL);
+		sigaction(SIGQUIT, &oldsaquit, NULL);
+		sigprocmask(SIG_SETMASK, &oldmask, NULL);
+		if (cwd && chdir(cwd) < 0)
+			_exit(127);
+		const char *argv[] = {"sh", "-c", cmd, NULL};
+		if (envp) {
+			execve("/bin/sh", (char **)argv, (char **)envp);
+		} else {
+			execv("/bin/sh", (char **)argv);
+		}
+		_exit(127);
+	} else {
+		if (waitpid(pid, &status, 0) < 0)
+			goto done;
+		doneflags |= F_WAITPID;
+	}
+
+done:
+	if (doneflags & F_SIGINT)
+		sigaction(SIGINT, &oldsaint, NULL);
+	if (doneflags & F_SIGQUIT)
+		sigaction(SIGQUIT, &oldsaquit, NULL);
+	if (doneflags & F_SIGMASK)
+		sigprocmask(SIG_SETMASK, &oldmask, NULL);
+
+	/* no way to report other errors, use 127 (= shell termination) */
+	if (!(doneflags & F_WAITPID))
+		return 127;
+	if (WIFEXITED(status))
+		return WEXITSTATUS(status);
+	if (WIFSIGNALED(status))
+		return -WTERMSIG(status);
+	return 127;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/contrib/chg/util.h	Wed Feb 24 15:55:44 2016 -0600
@@ -0,0 +1,27 @@
+/*
+ * Utility functions
+ *
+ * Copyright (c) 2011 Yuya Nishihara <yuya@tcha.org>
+ *
+ * This software may be used and distributed according to the terms of the
+ * GNU General Public License version 2 or any later version.
+ */
+
+#ifndef UTIL_H_
+#define UTIL_H_
+
+#ifdef __GNUC__
+#define PRINTF_FORMAT_ __attribute__((format(printf, 1, 2)))
+#endif
+
+void abortmsg(const char *fmt, ...) PRINTF_FORMAT_;
+
+void enabledebugmsg(void);
+void debugmsg(const char *fmt, ...) PRINTF_FORMAT_;
+
+void *mallocx(size_t size);
+void *reallocx(void *ptr, size_t size);
+
+int runshellcmd(const char *cmd, const char *envp[], const char *cwd);
+
+#endif  /* UTIL_H_ */
--- a/contrib/hg-ssh	Tue Feb 23 11:41:47 2016 +0100
+++ b/contrib/hg-ssh	Wed Feb 24 15:55:44 2016 -0600
@@ -52,7 +52,7 @@
     orig_cmd = os.getenv('SSH_ORIGINAL_COMMAND', '?')
     try:
         cmdargv = shlex.split(orig_cmd)
-    except ValueError, e:
+    except ValueError as e:
         sys.stderr.write('Illegal command "%s": %s\n' % (orig_cmd, e))
         sys.exit(255)
 
@@ -77,7 +77,7 @@
         sys.exit(255)
 
 def rejectpush(ui, **kwargs):
-    ui.warn("Permission denied\n")
+    ui.warn(("Permission denied\n"))
     # mercurial hooks use unix process conventions for hook return values
     # so a truthy return means failure
     return True
--- a/contrib/revsetbenchmarks.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/contrib/revsetbenchmarks.py	Wed Feb 24 15:55:44 2016 -0600
@@ -63,7 +63,7 @@
         return parseoutput(output)
     except CalledProcessError as exc:
         print >> sys.stderr, 'abort: cannot run revset benchmark: %s' % exc.cmd
-        if exc.output is None:
+        if getattr(exc, 'output', None) is None: # no output before 2.7
             print >> sys.stderr, '(no output)'
         else:
             print >> sys.stderr, exc.output
--- a/contrib/simplemerge	Tue Feb 23 11:41:47 2016 +0100
+++ b/contrib/simplemerge	Wed Feb 24 15:55:44 2016 -0600
@@ -47,7 +47,7 @@
     opts = {}
     try:
         args = fancyopts.fancyopts(sys.argv[1:], options, opts)
-    except fancyopts.getopt.GetoptError, e:
+    except fancyopts.getopt.GetoptError as e:
         raise ParseError(e)
     if opts['help']:
         showhelp()
@@ -55,11 +55,11 @@
     if len(args) != 3:
             raise ParseError(_('wrong number of arguments'))
     sys.exit(simplemerge.simplemerge(ui.ui(), *args, **opts))
-except ParseError, e:
+except ParseError as e:
     sys.stdout.write("%s: %s\n" % (sys.argv[0], e))
     showhelp()
     sys.exit(1)
-except error.Abort, e:
+except error.Abort as e:
     sys.stderr.write("abort: %s\n" % e)
     sys.exit(255)
 except KeyboardInterrupt:
--- a/contrib/win32/hgwebdir_wsgi.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/contrib/win32/hgwebdir_wsgi.py	Wed Feb 24 15:55:44 2016 -0600
@@ -1,43 +1,86 @@
 # An example WSGI script for IIS/isapi-wsgi to export multiple hgweb repos
-# Copyright 2010 Sune Foldager <cryo@cyanite.org>
+# Copyright 2010-2016 Sune Foldager <cyano@me.com>
 #
 # This software may be used and distributed according to the terms of the
 # GNU General Public License version 2 or any later version.
 #
 # Requirements:
-# - Python 2.6
-# - PyWin32 build 214 or newer
-# - Mercurial installed from source (python setup.py install)
-# - IIS 7
-#
-# Earlier versions will in general work as well, but the PyWin32 version is
-# necessary for win32traceutil to work correctly.
+# - Python 2.7, preferably 64 bit
+# - PyWin32 for Python 2.7 (32 or 64 bit)
+# - Mercurial installed from source (python setup.py install) or download the
+#   python module installer from https://www.mercurial-scm.org/wiki/Download
+# - IIS 7 or newer
 #
 #
 # Installation and use:
 #
-# - Download the isapi-wsgi source and run python setup.py install:
-#   http://code.google.com/p/isapi-wsgi/
+# - Download or clone the isapi-wsgi source and run python setup.py install.
+#   https://github.com/hexdump42/isapi-wsgi
+#
+# - Create a directory to hold the shim dll, config files etc. This can reside
+#   inside the standard IIS directory, C:\inetpub, or anywhere else. Copy this
+#   script there.
 #
 # - Run this script (i.e. python hgwebdir_wsgi.py) to get a shim dll. The
 #   shim is identical for all scripts, so you can just copy and rename one
-#   from an earlier run, if you wish.
+#   from an earlier run, if you wish. The shim needs to reside in the same
+#   directory as this script.
+#
+# - Start IIS manager and create a new app pool:
+#   .NET CLR Version: No Managed Code
+#   Advanced Settings: Enable 32 Bit Applications, if using 32 bit Python.
+#   You can adjust the identity and maximum worker processes if you wish. This
+#   setup works fine with multiple worker processes.
 #
-# - Setup an IIS application where your hgwebdir is to be served from.
-#   On 64-bit systems, make sure it's assigned a 32-bit app pool.
+# - Create an IIS application where your hgwebdir is to be served from.
+#   Assign it the app pool you just created and point its physical path to the
+#   directory you created.
+#
+# - In the application, remove all handler mappings and setup a wildcard script
+#   handler mapping of type IsapiModule with the shim dll as its executable.
+#   This file MUST reside in the same directory as the shim. The easiest way
+#   to do all this is to close IIS manager, place a web.config file in your
+#   directory and start IIS manager again. The file should contain:
 #
-# - In the application, setup a wildcard script handler mapping of type
-#   IsapiModule with the shim dll as its executable. This file MUST reside
-#   in the same directory as the shim. Remove all other handlers, if you wish.
+#   <?xml version="1.0" encoding="UTF-8"?>
+#   <configuration>
+#       <system.webServer>
+#           <handlers accessPolicy="Read, Script">
+#               <clear />
+#               <add name="hgwebdir" path="*" verb="*" modules="IsapiModule"
+#                    scriptProcessor="C:\your\directory\_hgwebdir_wsgi.dll"
+#                    resourceType="Unspecified" requireAccess="None"
+#                    preCondition="bitness64" />
+#           </handlers>
+#       </system.webServer>
+#   </configuration>
+#
+#   Where "bitness64" should be replaced with "bitness32" for 32 bit Python.
+#
+# - Edit ISAPI And CGI Restrictions on the web server (global setting). Add a
+#   restriction pointing to your shim dll and allow it to run.
 #
-# - Make sure the ISAPI and CGI restrictions (configured globally on the
-#   web server) includes the shim dll, to allow it to run.
+# - Create a configuration file in your directory and adjust the configuration
+#   variables below to match your needs. Example configuration:
+#
+#   [web]
+#   style = gitweb
+#   push_ssl = false
+#   allow_push = *
+#   encoding = utf8
 #
-# - Adjust the configuration variables below to match your needs.
+#   [server]
+#   validate = true
+#
+#   [paths]
+#   repo1 = c:\your\directory\repo1
+#   repo2 = c:\your\directory\repo2
+#
+# - Restart the web server and see if things are running.
 #
 
 # Configuration file location
-hgweb_config = r'c:\src\iis\hg\hgweb.config'
+hgweb_config = r'c:\your\directory\wsgi.config'
 
 # Global settings for IIS path translation
 path_strip = 0   # Strip this many path elements off (when using url rewrite)
@@ -47,20 +90,14 @@
 import sys
 
 # Adjust python path if this is not a system-wide install
-#sys.path.insert(0, r'c:\path\to\python\lib')
+#sys.path.insert(0, r'C:\your\custom\hg\build\lib.win32-2.7')
 
 # Enable tracing. Run 'python -m win32traceutil' to debug
 if getattr(sys, 'isapidllhandle', None) is not None:
     import win32traceutil
     win32traceutil.SetupForPrint # silence unused import warning
 
-# To serve pages in local charset instead of UTF-8, remove the two lines below
-import os
-os.environ['HGENCODING'] = 'UTF-8'
-
-
 import isapi_wsgi
-from mercurial import demandimport; demandimport.enable()
 from mercurial.hgweb.hgwebdir_mod import hgwebdir
 
 # Example tweak: Replace isapi_wsgi's handler to provide better error message
--- a/doc/docchecker	Tue Feb 23 11:41:47 2016 +0100
+++ b/doc/docchecker	Wed Feb 24 15:55:44 2016 -0600
@@ -14,41 +14,41 @@
 hg_cramped = re.compile(r'\w:hg:`')
 
 def check(line):
-  if hg_backtick.search(line):
-    print(line)
-    print("""warning: please avoid nesting ' in :hg:`...`""")
-  if hg_cramped.search(line):
-    print(line)
-    print('warning: please have a space before :hg:')
+    if hg_backtick.search(line):
+        print(line)
+        print("""warning: please avoid nesting ' in :hg:`...`""")
+    if hg_cramped.search(line):
+        print(line)
+        print('warning: please have a space before :hg:')
 
 def work(file):
-  (llead, lline) = ('', '')
+    (llead, lline) = ('', '')
 
-  for line in file:
-    # this section unwraps lines
-    match = leadingline.match(line)
-    if not match:
-      check(lline)
-      (llead, lline) = ('', '')
-      continue
+    for line in file:
+        # this section unwraps lines
+        match = leadingline.match(line)
+        if not match:
+            check(lline)
+            (llead, lline) = ('', '')
+            continue
 
-    lead, line = match.group(1), match.group(2)
-    if (lead == llead):
-      if (lline != ''):
-        lline += ' ' + line
-      else:
-        lline = line
-    else:
-      check(lline)
-      (llead, lline) = (lead, line)
-  check(lline)
+        lead, line = match.group(1), match.group(2)
+        if (lead == llead):
+            if (lline != ''):
+                lline += ' ' + line
+            else:
+                lline = line
+        else:
+            check(lline)
+            (llead, lline) = (lead, line)
+    check(lline)
 
 def main():
-  for f in sys.argv[1:]:
-    try:
-      with open(f) as file:
-        work(file)
-    except:
-      print("failed to process %s" % f)
+    for f in sys.argv[1:]:
+        try:
+            with open(f) as file:
+                work(file)
+        except BaseException as e:
+            print("failed to process %s: %s" % (f, e))
 
 main()
--- a/doc/runrst	Tue Feb 23 11:41:47 2016 +0100
+++ b/doc/runrst	Wed Feb 24 15:55:44 2016 -0600
@@ -30,10 +30,22 @@
     linktext = nodes.literal(rawtext, text)
     parts = text.split()
     cmd, args = parts[1], parts[2:]
+    refuri = "hg.1.html#%s" % cmd
     if cmd == 'help' and args:
-        cmd = args[0] # link to 'dates' for 'hg help dates'
+        if args[0] == 'config':
+            # :hg:`help config`
+            refuri = "hgrc.5.html"
+        elif args[0].startswith('config.'):
+            # :hg:`help config.SECTION...`
+            refuri = "hgrc.5.html#%s" % args[0].split('.', 2)[1]
+        elif len(args) >= 2 and args[0] == '-c':
+            # :hg:`help -c COMMAND ...` is equivalent to :hg:`COMMAND`
+            # (mainly for :hg:`help -c config`)
+            refuri = "hg.1.html#%s" % args[1]
+        else:
+            refuri = "hg.1.html#%s" % args[0]
     node = nodes.reference(rawtext, '', linktext,
-                           refuri="hg.1.html#%s" % cmd)
+                           refuri=refuri)
     return [node], []
 
 roles.register_local_role("hg", role_hg)
--- a/hgext/acl.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/hgext/acl.py	Wed Feb 24 15:55:44 2016 -0600
@@ -191,9 +191,17 @@
 
 '''
 
+from __future__ import absolute_import
+
+import getpass
+import urllib
+
 from mercurial.i18n import _
-from mercurial import util, match, error
-import getpass, urllib
+from mercurial import (
+    error,
+    match,
+    util,
+)
 
 # Note for extension authors: ONLY specify testedwith = 'internal' for
 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hgext/automv.py	Wed Feb 24 15:55:44 2016 -0600
@@ -0,0 +1,100 @@
+# automv.py
+#
+# Copyright 2013-2016 Facebook, Inc.
+#
+# This software may be used and distributed according to the terms of the
+# GNU General Public License version 2 or any later version.
+"""Check for unrecorded moves at commit time (EXPERIMENTAL)
+
+This extension checks at commit/amend time if any of the committed files
+comes from an unrecorded mv.
+
+The threshold at which a file is considered a move can be set with the
+``automv.similarity`` config option. This option takes a percentage between 0
+(disabled) and 100 (files must be identical), the default is 95.
+
+"""
+
+# Using 95 as a default similarity is based on an analysis of the mercurial
+# repositories of the cpython, mozilla-central & mercurial repositories, as
+# well as 2 very large facebook repositories. At 95 50% of all potential
+# missed moves would be caught, as well as correspond with 87% of all
+# explicitly marked moves.  Together, 80% of moved files are 95% similar or
+# more.
+#
+# See http://markmail.org/thread/5pxnljesvufvom57 for context.
+
+from __future__ import absolute_import
+
+from mercurial import (
+    commands,
+    copies,
+    error,
+    extensions,
+    scmutil,
+    similar
+)
+from mercurial.i18n import _
+
+def extsetup(ui):
+    entry = extensions.wrapcommand(
+        commands.table, 'commit', mvcheck)
+    entry[1].append(
+        ('', 'no-automv', None,
+         _('disable automatic file move detection')))
+
+def mvcheck(orig, ui, repo, *pats, **opts):
+    """Hook to check for moves at commit time"""
+    renames = None
+    disabled = opts.pop('no_automv', False)
+    if not disabled:
+        threshold = ui.configint('automv', 'similarity', 95)
+        if not 0 <= threshold <= 100:
+            raise error.Abort(_('automv.similarity must be between 0 and 100'))
+        if threshold > 0:
+            match = scmutil.match(repo[None], pats, opts)
+            added, removed = _interestingfiles(repo, match)
+            renames = _findrenames(repo, match, added, removed,
+                                   threshold / 100.0)
+
+    with repo.wlock():
+        if renames is not None:
+            scmutil._markchanges(repo, (), (), renames)
+        return orig(ui, repo, *pats, **opts)
+
+def _interestingfiles(repo, matcher):
+    """Find what files were added or removed in this commit.
+
+    Returns a tuple of two lists: (added, removed). Only files not *already*
+    marked as moved are included in the added list.
+
+    """
+    stat = repo.status(match=matcher)
+    added = stat[1]
+    removed = stat[2]
+
+    copy = copies._forwardcopies(repo['.'], repo[None], matcher)
+    # remove the copy files for which we already have copy info
+    added = [f for f in added if f not in copy]
+
+    return added, removed
+
+def _findrenames(repo, matcher, added, removed, similarity):
+    """Find what files in added are really moved files.
+
+    Any file named in removed that is at least similarity% similar to a file
+    in added is seen as a rename.
+
+    """
+    renames = {}
+    if similarity > 0:
+        for src, dst, score in similar.findrenames(
+                repo, added, removed, similarity):
+            if repo.ui.verbose:
+                repo.ui.status(
+                    _('detected move of %s as %s (%d%% similar)\n') % (
+                        matcher.rel(src), matcher.rel(dst), score * 100))
+            renames[dst] = src
+    if renames:
+        repo.ui.status(_('detected move of %d files\n') % len(renames))
+    return renames
--- a/hgext/blackbox.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/hgext/blackbox.py	Wed Feb 24 15:55:44 2016 -0600
@@ -29,9 +29,16 @@
 
 """
 
-from mercurial import util, cmdutil
+from __future__ import absolute_import
+
+import errno
+import re
+
 from mercurial.i18n import _
-import errno, os, re
+from mercurial import (
+    cmdutil,
+    util,
+)
 
 cmdtable = {}
 command = cmdutil.command(cmdtable)
@@ -51,23 +58,23 @@
         def _openlogfile(self):
             def rotate(oldpath, newpath):
                 try:
-                    os.unlink(newpath)
+                    self._bbvfs.unlink(newpath)
                 except OSError as err:
                     if err.errno != errno.ENOENT:
                         self.debug("warning: cannot remove '%s': %s\n" %
                                    (newpath, err.strerror))
                 try:
                     if newpath:
-                        os.rename(oldpath, newpath)
+                        self._bbvfs.rename(oldpath, newpath)
                 except OSError as err:
                     if err.errno != errno.ENOENT:
                         self.debug("warning: cannot rename '%s' to '%s': %s\n" %
                                    (newpath, oldpath, err.strerror))
 
-            fp = self._bbopener('blackbox.log', 'a')
+            fp = self._bbvfs('blackbox.log', 'a')
             maxsize = self.configbytes('blackbox', 'maxsize', 1048576)
             if maxsize > 0:
-                st = os.fstat(fp.fileno())
+                st = self._bbvfs.fstat(fp)
                 if st.st_size >= maxsize:
                     path = fp.name
                     fp.close()
@@ -77,7 +84,7 @@
                                newpath='%s.%d' % (path, i))
                     rotate(oldpath=path,
                            newpath=maxfiles > 0 and path + '.1')
-                    fp = self._bbopener('blackbox.log', 'a')
+                    fp = self._bbvfs('blackbox.log', 'a')
             return fp
 
         def log(self, event, *msg, **opts):
@@ -89,13 +96,13 @@
 
             if util.safehasattr(self, '_blackbox'):
                 blackbox = self._blackbox
-            elif util.safehasattr(self, '_bbopener'):
+            elif util.safehasattr(self, '_bbvfs'):
                 try:
                     self._blackbox = self._openlogfile()
                 except (IOError, OSError) as err:
                     self.debug('warning: cannot write to blackbox.log: %s\n' %
                                err.strerror)
-                    del self._bbopener
+                    del self._bbvfs
                     self._blackbox = None
                 blackbox = self._blackbox
             else:
@@ -107,18 +114,19 @@
             if blackbox:
                 date = util.datestr(None, '%Y/%m/%d %H:%M:%S')
                 user = util.getuser()
-                pid = str(os.getpid())
+                pid = str(util.getpid())
                 formattedmsg = msg[0] % msg[1:]
                 try:
                     blackbox.write('%s %s (%s)> %s' %
                                    (date, user, pid, formattedmsg))
+                    blackbox.flush()
                 except IOError as err:
                     self.debug('warning: cannot write to blackbox.log: %s\n' %
                                err.strerror)
                 lastblackbox = blackbox
 
         def setrepo(self, repo):
-            self._bbopener = repo.vfs
+            self._bbvfs = repo.vfs
 
     ui.__class__ = blackboxui
 
@@ -143,7 +151,7 @@
     '''view the recent repository events
     '''
 
-    if not os.path.exists(repo.join('blackbox.log')):
+    if not repo.vfs.exists('blackbox.log'):
         return
 
     limit = opts.get('limit')
--- a/hgext/bugzilla.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/hgext/bugzilla.py	Wed Feb 24 15:55:44 2016 -0600
@@ -277,10 +277,21 @@
     Changeset commit comment. Bug 1234.
 '''
 
+from __future__ import absolute_import
+
+import re
+import time
+import urlparse
+import xmlrpclib
+
 from mercurial.i18n import _
 from mercurial.node import short
-from mercurial import cmdutil, mail, util, error
-import re, time, urlparse, xmlrpclib
+from mercurial import (
+    cmdutil,
+    error,
+    mail,
+    util,
+)
 
 # Note for extension authors: ONLY specify testedwith = 'internal' for
 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
--- a/hgext/censor.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/hgext/censor.py	Wed Feb 24 15:55:44 2016 -0600
@@ -25,10 +25,20 @@
 revisions if they are allowed by the "censor.policy=ignore" config option.
 """
 
+from __future__ import absolute_import
+
+from mercurial.i18n import _
 from mercurial.node import short
-from mercurial import cmdutil, error, filelog, revlog, scmutil, util
-from mercurial.i18n import _
-from mercurial import lock as lockmod
+
+from mercurial import (
+    cmdutil,
+    error,
+    filelog,
+    lock as lockmod,
+    revlog,
+    scmutil,
+    util,
+)
 
 cmdtable = {}
 command = cmdutil.command(cmdtable)
--- a/hgext/chgserver.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/hgext/chgserver.py	Wed Feb 24 15:55:44 2016 -0600
@@ -283,24 +283,25 @@
         Note that the behavior of --cwd option is bit different from this.
         It does not affect --config parameter.
         """
-        length = struct.unpack('>I', self._read(4))[0]
-        if not length:
+        path = self._readstr()
+        if not path:
             return
-        path = self._read(length)
         _log('chdir to %r\n' % path)
         os.chdir(path)
 
+    def setumask(self):
+        """Change umask"""
+        mask = struct.unpack('>I', self._read(4))[0]
+        _log('setumask %r\n' % mask)
+        os.umask(mask)
+
     def getpager(self):
         """Read cmdargs and write pager command to r-channel if enabled
 
         If pager isn't enabled, this writes '\0' because channeledoutput
         does not allow to write empty data.
         """
-        length = struct.unpack('>I', self._read(4))[0]
-        if not length:
-            args = []
-        else:
-            args = self._read(length).split('\0')
+        args = self._readlist()
         try:
             cmd, _func, args, options, _cmdoptions = dispatch._parse(self.ui,
                                                                      args)
@@ -323,12 +324,9 @@
 
         Note that not all variables can make an effect on the running process.
         """
-        length = struct.unpack('>I', self._read(4))[0]
-        if not length:
-            return
-        s = self._read(length)
+        l = self._readlist()
         try:
-            newenv = dict(l.split('=', 1) for l in s.split('\0'))
+            newenv = dict(s.split('=', 1) for s in l)
         except ValueError:
             raise ValueError('unexpected value in setenv request')
 
@@ -349,11 +347,16 @@
     capabilities.update({'attachio': attachio,
                          'chdir': chdir,
                          'getpager': getpager,
-                         'setenv': setenv})
+                         'setenv': setenv,
+                         'setumask': setumask})
 
 # copied from mercurial/commandserver.py
 class _requesthandler(SocketServer.StreamRequestHandler):
     def handle(self):
+        # use a different process group from the master process, making this
+        # process pass kernel "is_current_pgrp_orphaned" check so signals like
+        # SIGTSTP, SIGTTIN, SIGTTOU are not ignored.
+        os.setpgid(0, 0)
         ui = self.server.ui
         repo = self.server.repo
         sv = chgcmdserver(ui, repo, self.rfile, self.wfile, self.connection)
--- a/hgext/children.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/hgext/children.py	Wed Feb 24 15:55:44 2016 -0600
@@ -14,9 +14,15 @@
 "children(REV)"` instead.
 '''
 
-from mercurial import cmdutil
-from mercurial.commands import templateopts
+from __future__ import absolute_import
+
 from mercurial.i18n import _
+from mercurial import (
+    cmdutil,
+    commands,
+)
+
+templateopts = commands.templateopts
 
 cmdtable = {}
 command = cmdutil.command(cmdtable)
--- a/hgext/churn.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/hgext/churn.py	Wed Feb 24 15:55:44 2016 -0600
@@ -8,11 +8,22 @@
 
 '''command to display statistics about repository history'''
 
+from __future__ import absolute_import
+
+import datetime
+import os
+import time
+
 from mercurial.i18n import _
-from mercurial import patch, cmdutil, scmutil, util, commands, error
-from mercurial import encoding
-import os
-import time, datetime
+from mercurial import (
+    cmdutil,
+    commands,
+    encoding,
+    error,
+    patch,
+    scmutil,
+    util,
+)
 
 cmdtable = {}
 command = cmdutil.command(cmdtable)
--- a/hgext/clonebundles.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/hgext/clonebundles.py	Wed Feb 24 15:55:44 2016 -0600
@@ -162,6 +162,8 @@
 Mercurial server when the bundle hosting service fails.
 """
 
+from __future__ import absolute_import
+
 from mercurial import (
     extensions,
     wireproto,
--- a/hgext/histedit.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/hgext/histedit.py	Wed Feb 24 15:55:44 2016 -0600
@@ -279,7 +279,7 @@
         except IOError as err:
             if err.errno != errno.ENOENT:
                 raise
-            raise error.Abort(_('no histedit in progress'))
+            cmdutil.wrongtooltocontinue(self.repo, _('histedit'))
 
         if state.startswith('v1\n'):
             data = self._load()
@@ -447,13 +447,18 @@
         parentctx, but does not commit them."""
         repo = self.repo
         rulectx = repo[self.node]
+        repo.ui.pushbuffer(error=True, labeled=True)
         hg.update(repo, self.state.parentctxnode, quietempty=True)
         stats = applychanges(repo.ui, repo, rulectx, {})
         if stats and stats[3] > 0:
+            buf = repo.ui.popbuffer()
+            repo.ui.write(*buf)
             raise error.InterventionRequired(
                 _('Fix up the change (%s %s)') %
                 (self.verb, node.short(self.node)),
                 hint=_('hg histedit --continue to resume'))
+        else:
+            repo.ui.popbuffer()
 
     def continuedirty(self):
         """Continues the action when changes have been applied to the working
@@ -733,7 +738,9 @@
 
     def finishfold(self, ui, repo, ctx, oldctx, newnode, internalchanges):
         parent = ctx.parents()[0].node()
+        repo.ui.pushbuffer()
         hg.update(repo, parent)
+        repo.ui.popbuffer()
         ### prepare new commit data
         commitopts = {}
         commitopts['user'] = ctx.user()
@@ -764,7 +771,9 @@
             repo.ui.restoreconfig(phasebackup)
         if n is None:
             return ctx, []
+        repo.ui.pushbuffer()
         hg.update(repo, n)
+        repo.ui.popbuffer()
         replacements = [(oldctx.node(), (newnode,)),
                         (ctx.node(), (n,)),
                         (newnode, (n,)),
@@ -892,7 +901,7 @@
     - Specify ANCESTOR directly
 
     - Use --outgoing -- it will be the first linear changeset not
-      included in destination. (See :hg:`help config.default-push`)
+      included in destination. (See :hg:`help config.paths.default-push`)
 
     - Otherwise, the value from the "histedit.defaultrev" config option
       is used as a revset to select the base revision when ANCESTOR is not
@@ -973,7 +982,21 @@
     finally:
         release(state.lock, state.wlock)
 
-def _histedit(ui, repo, state, *freeargs, **opts):
+goalcontinue = 'continue'
+goalabort = 'abort'
+goaleditplan = 'edit-plan'
+goalnew = 'new'
+
+def _getgoal(opts):
+    if opts.get('continue'):
+        return goalcontinue
+    if opts.get('abort'):
+        return goalabort
+    if opts.get('edit_plan'):
+        return goaleditplan
+    return goalnew
+
+def _validateargs(ui, repo, state, freeargs, opts, goal, rules, revs):
     # TODO only abort if we try to histedit mq patches, not just
     # blanket if mq patches are applied somewhere
     mq = getattr(repo, 'mq', None)
@@ -982,28 +1005,21 @@
 
     # basic argument incompatibility processing
     outg = opts.get('outgoing')
-    cont = opts.get('continue')
     editplan = opts.get('edit_plan')
     abort = opts.get('abort')
     force = opts.get('force')
-    rules = opts.get('commands', '')
-    revs = opts.get('rev', [])
-    goal = 'new' # This invocation goal, in new, continue, abort
     if force and not outg:
         raise error.Abort(_('--force only allowed with --outgoing'))
-    if cont:
+    if goal == 'continue':
         if any((outg, abort, revs, freeargs, rules, editplan)):
             raise error.Abort(_('no arguments allowed with --continue'))
-        goal = 'continue'
-    elif abort:
+    elif goal == 'abort':
         if any((outg, revs, freeargs, rules, editplan)):
             raise error.Abort(_('no arguments allowed with --abort'))
-        goal = 'abort'
-    elif editplan:
+    elif goal == 'edit-plan':
         if any((outg, revs, freeargs)):
             raise error.Abort(_('only --commands argument allowed with '
                                '--edit-plan'))
-        goal = 'edit-plan'
     else:
         if os.path.exists(os.path.join(repo.path, 'histedit-state')):
             raise error.Abort(_('history edit already in progress, try '
@@ -1025,124 +1041,36 @@
                 raise error.Abort(
                     _('histedit requires exactly one ancestor revision'))
 
+def _histedit(ui, repo, state, *freeargs, **opts):
+    goal = _getgoal(opts)
+    revs = opts.get('rev', [])
+    rules = opts.get('commands', '')
+    state.keep = opts.get('keep', False)
 
-    replacements = []
-    state.keep = opts.get('keep', False)
-    supportsmarkers = obsolete.isenabled(repo, obsolete.createmarkersopt)
+    _validateargs(ui, repo, state, freeargs, opts, goal, rules, revs)
 
     # rebuild state
-    if goal == 'continue':
+    if goal == goalcontinue:
         state.read()
         state = bootstrapcontinue(ui, state, opts)
-    elif goal == 'edit-plan':
-        state.read()
-        if not rules:
-            comment = geteditcomment(node.short(state.parentctxnode),
-                                     node.short(state.topmost))
-            rules = ruleeditor(repo, ui, state.actions, comment)
-        else:
-            if rules == '-':
-                f = sys.stdin
-            else:
-                f = open(rules)
-            rules = f.read()
-            f.close()
-        actions = parserules(rules, state)
-        ctxs = [repo[act.nodetoverify()] \
-                for act in state.actions if act.nodetoverify()]
-        warnverifyactions(ui, repo, actions, state, ctxs)
-        state.actions = actions
-        state.write()
+    elif goal == goaleditplan:
+        _edithisteditplan(ui, repo, state, rules)
         return
-    elif goal == 'abort':
-        try:
-            state.read()
-            tmpnodes, leafs = newnodestoabort(state)
-            ui.debug('restore wc to old parent %s\n'
-                    % node.short(state.topmost))
-
-            # Recover our old commits if necessary
-            if not state.topmost in repo and state.backupfile:
-                backupfile = repo.join(state.backupfile)
-                f = hg.openpath(ui, backupfile)
-                gen = exchange.readbundle(ui, f, backupfile)
-                with repo.transaction('histedit.abort') as tr:
-                    if not isinstance(gen, bundle2.unbundle20):
-                        gen.apply(repo, 'histedit', 'bundle:' + backupfile)
-                    if isinstance(gen, bundle2.unbundle20):
-                        bundle2.applybundle(repo, gen, tr,
-                                            source='histedit',
-                                            url='bundle:' + backupfile)
-
-                os.remove(backupfile)
-
-            # check whether we should update away
-            if repo.unfiltered().revs('parents() and (%n  or %ln::)',
-                                    state.parentctxnode, leafs | tmpnodes):
-                hg.clean(repo, state.topmost, show_stats=True, quietempty=True)
-            cleanupnode(ui, repo, 'created', tmpnodes)
-            cleanupnode(ui, repo, 'temp', leafs)
-        except Exception:
-            if state.inprogress():
-                ui.warn(_('warning: encountered an exception during histedit '
-                    '--abort; the repository may not have been completely '
-                    'cleaned up\n'))
-            raise
-        finally:
-                state.clear()
+    elif goal == goalabort:
+        _aborthistedit(ui, repo, state)
         return
     else:
-        cmdutil.checkunfinished(repo)
-        cmdutil.bailifchanged(repo)
+        # goal == goalnew
+        _newhistedit(ui, repo, state, revs, freeargs, opts)
 
-        topmost, empty = repo.dirstate.parents()
-        if outg:
-            if freeargs:
-                remote = freeargs[0]
-            else:
-                remote = None
-            root = findoutgoing(ui, repo, remote, force, opts)
-        else:
-            rr = list(repo.set('roots(%ld)', scmutil.revrange(repo, revs)))
-            if len(rr) != 1:
-                raise error.Abort(_('The specified revisions must have '
-                    'exactly one common root'))
-            root = rr[0].node()
-
-        revs = between(repo, root, topmost, state.keep)
-        if not revs:
-            raise error.Abort(_('%s is not an ancestor of working directory') %
-                             node.short(root))
+    _continuehistedit(ui, repo, state)
+    _finishhistedit(ui, repo, state)
 
-        ctxs = [repo[r] for r in revs]
-        if not rules:
-            comment = geteditcomment(node.short(root), node.short(topmost))
-            actions = [pick(state, r) for r in revs]
-            rules = ruleeditor(repo, ui, actions, comment)
-        else:
-            if rules == '-':
-                f = sys.stdin
-            else:
-                f = open(rules)
-            rules = f.read()
-            f.close()
-        actions = parserules(rules, state)
-        warnverifyactions(ui, repo, actions, state, ctxs)
-
-        parentctxnode = repo[root].parents()[0].node()
-
-        state.parentctxnode = parentctxnode
-        state.actions = actions
-        state.topmost = topmost
-        state.replacements = replacements
-
-        # Create a backup so we can always abort completely.
-        backupfile = None
-        if not obsolete.isenabled(repo, obsolete.createmarkersopt):
-            backupfile = repair._bundle(repo, [parentctxnode], [topmost], root,
-                                        'histedit')
-        state.backupfile = backupfile
-
+def _continuehistedit(ui, repo, state):
+    """This function runs after either:
+    - bootstrapcontinue (if the goal is 'continue')
+    - _newhistedit (if the goal is 'new')
+    """
     # preprocess rules so that we can hide inner folds from the user
     # and only show one editor
     actions = state.actions[:]
@@ -1167,7 +1095,11 @@
     state.write()
     ui.progress(_("editing"), None)
 
+def _finishhistedit(ui, repo, state):
+    """This action runs when histedit is finishing its session"""
+    repo.ui.pushbuffer()
     hg.update(repo, state.parentctxnode, quietempty=True)
+    repo.ui.popbuffer()
 
     mapping, tmpnodes, created, ntm = processreplacement(state)
     if mapping:
@@ -1182,6 +1114,7 @@
                     for n in succs[1:]:
                         ui.debug(m % node.short(n))
 
+    supportsmarkers = obsolete.isenabled(repo, obsolete.createmarkersopt)
     if supportsmarkers:
         # Only create markers if the temp nodes weren't already removed.
         obsolete.createmarkers(repo, ((repo[t],()) for t in sorted(tmpnodes)
@@ -1211,6 +1144,119 @@
     if repo.vfs.exists('histedit-last-edit.txt'):
         repo.vfs.unlink('histedit-last-edit.txt')
 
+def _aborthistedit(ui, repo, state):
+    try:
+        state.read()
+        __, leafs, tmpnodes, __ = processreplacement(state)
+        ui.debug('restore wc to old parent %s\n'
+                % node.short(state.topmost))
+
+        # Recover our old commits if necessary
+        if not state.topmost in repo and state.backupfile:
+            backupfile = repo.join(state.backupfile)
+            f = hg.openpath(ui, backupfile)
+            gen = exchange.readbundle(ui, f, backupfile)
+            with repo.transaction('histedit.abort') as tr:
+                if not isinstance(gen, bundle2.unbundle20):
+                    gen.apply(repo, 'histedit', 'bundle:' + backupfile)
+                if isinstance(gen, bundle2.unbundle20):
+                    bundle2.applybundle(repo, gen, tr,
+                                        source='histedit',
+                                        url='bundle:' + backupfile)
+
+            os.remove(backupfile)
+
+        # check whether we should update away
+        if repo.unfiltered().revs('parents() and (%n  or %ln::)',
+                                state.parentctxnode, leafs | tmpnodes):
+            hg.clean(repo, state.topmost, show_stats=True, quietempty=True)
+        cleanupnode(ui, repo, 'created', tmpnodes)
+        cleanupnode(ui, repo, 'temp', leafs)
+    except Exception:
+        if state.inprogress():
+            ui.warn(_('warning: encountered an exception during histedit '
+                '--abort; the repository may not have been completely '
+                'cleaned up\n'))
+        raise
+    finally:
+            state.clear()
+
+def _edithisteditplan(ui, repo, state, rules):
+    state.read()
+    if not rules:
+        comment = geteditcomment(node.short(state.parentctxnode),
+                                 node.short(state.topmost))
+        rules = ruleeditor(repo, ui, state.actions, comment)
+    else:
+        if rules == '-':
+            f = sys.stdin
+        else:
+            f = open(rules)
+        rules = f.read()
+        f.close()
+    actions = parserules(rules, state)
+    ctxs = [repo[act.nodetoverify()] \
+            for act in state.actions if act.nodetoverify()]
+    warnverifyactions(ui, repo, actions, state, ctxs)
+    state.actions = actions
+    state.write()
+
+def _newhistedit(ui, repo, state, revs, freeargs, opts):
+    outg = opts.get('outgoing')
+    rules = opts.get('commands', '')
+    force = opts.get('force')
+
+    cmdutil.checkunfinished(repo)
+    cmdutil.bailifchanged(repo)
+
+    topmost, empty = repo.dirstate.parents()
+    if outg:
+        if freeargs:
+            remote = freeargs[0]
+        else:
+            remote = None
+        root = findoutgoing(ui, repo, remote, force, opts)
+    else:
+        rr = list(repo.set('roots(%ld)', scmutil.revrange(repo, revs)))
+        if len(rr) != 1:
+            raise error.Abort(_('The specified revisions must have '
+                'exactly one common root'))
+        root = rr[0].node()
+
+    revs = between(repo, root, topmost, state.keep)
+    if not revs:
+        raise error.Abort(_('%s is not an ancestor of working directory') %
+                         node.short(root))
+
+    ctxs = [repo[r] for r in revs]
+    if not rules:
+        comment = geteditcomment(node.short(root), node.short(topmost))
+        actions = [pick(state, r) for r in revs]
+        rules = ruleeditor(repo, ui, actions, comment)
+    else:
+        if rules == '-':
+            f = sys.stdin
+        else:
+            f = open(rules)
+        rules = f.read()
+        f.close()
+    actions = parserules(rules, state)
+    warnverifyactions(ui, repo, actions, state, ctxs)
+
+    parentctxnode = repo[root].parents()[0].node()
+
+    state.parentctxnode = parentctxnode
+    state.actions = actions
+    state.topmost = topmost
+    state.replacements = []
+
+    # Create a backup so we can always abort completely.
+    backupfile = None
+    if not obsolete.isenabled(repo, obsolete.createmarkersopt):
+        backupfile = repair._bundle(repo, [parentctxnode], [topmost], root,
+                                    'histedit')
+    state.backupfile = backupfile
+
 def bootstrapcontinue(ui, state, opts):
     repo = state.repo
     if state.actions:
@@ -1340,24 +1386,40 @@
                 hint=_('use "drop %s" to discard, see also: '
                        '"hg help -e histedit.config"') % missing[0][:12])
 
-def newnodestoabort(state):
-    """process the list of replacements to return
+def adjustreplacementsfrommarkers(repo, oldreplacements):
+    """Adjust replacements from obsolescense markers
 
-    1) the list of final node
-    2) the list of temporary node
+    Replacements structure is originally generated based on
+    histedit's state and does not account for changes that are
+    not recorded there. This function fixes that by adding
+    data read from obsolescense markers"""
+    if not obsolete.isenabled(repo, obsolete.createmarkersopt):
+        return oldreplacements
 
-    This is meant to be used on abort as less data are required in this case.
-    """
-    replacements = state.replacements
-    allsuccs = set()
-    replaced = set()
-    for rep in replacements:
-        allsuccs.update(rep[1])
-        replaced.add(rep[0])
-    newnodes = allsuccs - replaced
-    tmpnodes = allsuccs & replaced
-    return newnodes, tmpnodes
+    unfi = repo.unfiltered()
+    newreplacements = list(oldreplacements)
+    oldsuccs = [r[1] for r in oldreplacements]
+    # successors that have already been added to succstocheck once
+    seensuccs = set().union(*oldsuccs) # create a set from an iterable of tuples
+    succstocheck = list(seensuccs)
+    while succstocheck:
+        n = succstocheck.pop()
+        try:
+            ctx = unfi[n]
+        except error.RepoError:
+            # XXX node unknown locally, we should properly follow marker
+            newreplacements.append((n, ()))
+            continue
 
+        for marker in obsolete.successormarkers(ctx):
+            nsuccs = marker.succnodes()
+            newreplacements.append((n, nsuccs))
+            for nsucc in nsuccs:
+                if nsucc not in seensuccs:
+                    seensuccs.add(nsucc)
+                    succstocheck.append(nsucc)
+
+    return newreplacements
 
 def processreplacement(state):
     """process the list of replacements to return
@@ -1365,7 +1427,7 @@
     1) the final mapping between original and created nodes
     2) the list of temporary node created by histedit
     3) the list of new commit created by histedit"""
-    replacements = state.replacements
+    replacements = adjustreplacementsfrommarkers(state.repo, state.replacements)
     allsuccs = set()
     replaced = set()
     fullmapping = {}
--- a/hgext/largefiles/overrides.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/hgext/largefiles/overrides.py	Wed Feb 24 15:55:44 2016 -0600
@@ -452,11 +452,10 @@
 # writing the files into the working copy and lfcommands.updatelfiles
 # will update the largefiles.
 def overridecalculateupdates(origfn, repo, p1, p2, pas, branchmerge, force,
-                             acceptremote, followcopies, matcher=None):
+                             acceptremote, *args, **kwargs):
     overwrite = force and not branchmerge
     actions, diverge, renamedelete = origfn(
-        repo, p1, p2, pas, branchmerge, force, acceptremote,
-        followcopies, matcher=matcher)
+        repo, p1, p2, pas, branchmerge, force, acceptremote, *args, **kwargs)
 
     if overwrite:
         return actions, diverge, renamedelete
@@ -963,7 +962,7 @@
     if subrepos:
         for subpath in sorted(ctx.substate):
             sub = ctx.workingsub(subpath)
-            submatch = match_.narrowmatcher(subpath, matchfn)
+            submatch = match_.subdirmatcher(subpath, matchfn)
             sub._repo.lfstatus = True
             sub.archive(archiver, prefix, submatch)
 
@@ -1011,7 +1010,7 @@
 
     for subpath in sorted(ctx.substate):
         sub = ctx.workingsub(subpath)
-        submatch = match_.narrowmatcher(subpath, match)
+        submatch = match_.subdirmatcher(subpath, match)
         sub._repo.lfstatus = True
         sub.archive(archiver, prefix + repo._path + '/', submatch)
 
--- a/hgext/rebase.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/hgext/rebase.py	Wed Feb 24 15:55:44 2016 -0600
@@ -16,7 +16,7 @@
 
 from mercurial import hg, util, repair, merge, cmdutil, commands, bookmarks
 from mercurial import extensions, patch, scmutil, phases, obsolete, error
-from mercurial import copies, repoview, revset
+from mercurial import copies, destutil, repoview, revset
 from mercurial.commands import templateopts
 from mercurial.node import nullrev, nullid, hex, short
 from mercurial.lock import release
@@ -69,11 +69,12 @@
             c(ctx, extra)
     return extrafn
 
-def _destrebase(repo):
-    # Destination defaults to the latest revision in the
-    # current branch
-    branch = repo[None].branch()
-    return repo[branch].rev()
+def _destrebase(repo, sourceset):
+    """small wrapper around destmerge to pass the right extra args
+
+    Please wrap destutil.destmerge instead."""
+    return destutil.destmerge(repo, action='rebase', sourceset=sourceset,
+                              onheadcheck=False)
 
 revsetpredicate = revset.extpredicate()
 
@@ -83,12 +84,12 @@
 
     # default destination for rebase.
     # # XXX: Currently private because I expect the signature to change.
-    # # XXX: - taking rev as arguments,
     # # XXX: - bailing out in case of ambiguity vs returning all data.
-    # # XXX: - probably merging with the merge destination.
     # i18n: "_rebasedefaultdest" is a keyword
-    revset.getargs(x, 0, 0, _("_rebasedefaultdest takes no arguments"))
-    return subset & revset.baseset([_destrebase(repo)])
+    sourceset = None
+    if x is not None:
+        sourceset = revset.getset(repo, revset.fullreposet(repo), x)
+    return subset & revset.baseset([_destrebase(repo, sourceset)])
 
 @command('rebase',
     [('s', 'source', '',
@@ -127,10 +128,13 @@
     Published commits cannot be rebased (see :hg:`help phases`).
     To copy commits, see :hg:`help graft`.
 
-    If you don't specify a destination changeset (``-d/--dest``),
-    rebase uses the current branch tip as the destination. (The
-    destination changeset is not modified by rebasing, but new
-    changesets are added as its descendants.)
+    If you don't specify a destination changeset (``-d/--dest``), rebase
+    will use the same logic as :hg:`merge` to pick a destination.  if
+    the current branch contains exactly one other head, the other head
+    is merged with by default.  Otherwise, an explicit revision with
+    which to merge with must be provided.  (destination changeset is not
+    modified by rebasing, but new changesets are added as its
+    descendants.)
 
     Here are the ways to select changesets:
 
@@ -155,6 +159,11 @@
     a named branch with two heads. You will need to explicitly specify source
     and/or destination.
 
+    If you need to use a tool to automate merge/conflict decisions, you
+    can specify one with ``--tool``, see :hg:`help merge-tools`.
+    As a caveat: the tool will not be used to mediate when a file was
+    deleted, there is no hook presently available for this.
+
     If a rebase is interrupted to manually resolve a conflict, it can be
     continued with --continue/-c or aborted with --abort/-a.
 
@@ -258,9 +267,11 @@
             try:
                 (originalwd, target, state, skipped, collapsef, keepf,
                  keepbranchesf, external, activebookmark) = restorestatus(repo)
+                collapsemsg = restorecollapsemsg(repo)
             except error.RepoLookupError:
                 if abortf:
                     clearstatus(repo)
+                    clearcollapsemsg(repo)
                     repo.ui.warn(_('rebase aborted (no revision is removed,'
                                    ' only broken state is cleared)\n'))
                     return 0
@@ -272,78 +283,9 @@
                 return abort(repo, originalwd, target, state,
                              activebookmark=activebookmark)
         else:
-            if srcf and basef:
-                raise error.Abort(_('cannot specify both a '
-                                   'source and a base'))
-            if revf and basef:
-                raise error.Abort(_('cannot specify both a '
-                                   'revision and a base'))
-            if revf and srcf:
-                raise error.Abort(_('cannot specify both a '
-                                   'revision and a source'))
-
-            cmdutil.checkunfinished(repo)
-            cmdutil.bailifchanged(repo)
-
-            if destf:
-                dest = scmutil.revsingle(repo, destf)
-            else:
-                dest = repo[_destrebase(repo)]
-                destf = str(dest)
-
-            if revf:
-                rebaseset = scmutil.revrange(repo, revf)
-                if not rebaseset:
-                    ui.status(_('empty "rev" revision set - '
-                                'nothing to rebase\n'))
-                    return _nothingtorebase()
-            elif srcf:
-                src = scmutil.revrange(repo, [srcf])
-                if not src:
-                    ui.status(_('empty "source" revision set - '
-                                'nothing to rebase\n'))
-                    return _nothingtorebase()
-                rebaseset = repo.revs('(%ld)::', src)
-                assert rebaseset
-            else:
-                base = scmutil.revrange(repo, [basef or '.'])
-                if not base:
-                    ui.status(_('empty "base" revision set - '
-                                "can't compute rebase set\n"))
-                    return _nothingtorebase()
-                commonanc = repo.revs('ancestor(%ld, %d)', base, dest).first()
-                if commonanc is not None:
-                    rebaseset = repo.revs('(%d::(%ld) - %d)::',
-                                          commonanc, base, commonanc)
-                else:
-                    rebaseset = []
-
-                if not rebaseset:
-                    # transform to list because smartsets are not comparable to
-                    # lists. This should be improved to honor laziness of
-                    # smartset.
-                    if list(base) == [dest.rev()]:
-                        if basef:
-                            ui.status(_('nothing to rebase - %s is both "base"'
-                                        ' and destination\n') % dest)
-                        else:
-                            ui.status(_('nothing to rebase - working directory '
-                                        'parent is also destination\n'))
-                    elif not repo.revs('%ld - ::%d', base, dest):
-                        if basef:
-                            ui.status(_('nothing to rebase - "base" %s is '
-                                        'already an ancestor of destination '
-                                        '%s\n') %
-                                      ('+'.join(str(repo[r]) for r in base),
-                                       dest))
-                        else:
-                            ui.status(_('nothing to rebase - working '
-                                        'directory parent is already an '
-                                        'ancestor of destination %s\n') % dest)
-                    else: # can it happen?
-                        ui.status(_('nothing to rebase from %s to %s\n') %
-                                  ('+'.join(str(repo[r]) for r in base), dest))
-                    return _nothingtorebase()
+            dest, rebaseset = _definesets(ui, repo, destf, srcf, basef, revf)
+            if dest is None:
+                return _nothingtorebase()
 
             allowunstable = obsolete.isenabled(repo, obsolete.allowunstableopt)
             if (not (keepf or allowunstable)
@@ -369,10 +311,13 @@
                 divergencebasecandidates = rebaseobsrevs - rebaseobsskipped
 
                 if divergencebasecandidates and not divergenceok:
-                    msg = _("this rebase will cause divergence")
+                    divhashes = (str(repo[r])
+                                 for r in divergencebasecandidates)
+                    msg = _("this rebase will cause "
+                            "divergences from: %s")
                     h = _("to force the rebase please set "
                           "rebase.allowdivergence=True")
-                    raise error.Abort(msg, hint=h)
+                    raise error.Abort(msg % (",".join(divhashes),), hint=h)
 
                 # - plain prune (no successor) changesets are rebased
                 # - split changesets are not rebased if at least one of the
@@ -452,6 +397,7 @@
                                              targetancestors)
                 storestatus(repo, originalwd, target, state, collapsef, keepf,
                             keepbranchesf, external, activebookmark)
+                storecollapsemsg(repo, collapsemsg)
                 if len(repo[None].parents()) == 2:
                     repo.ui.debug('resuming interrupted rebase\n')
                 else:
@@ -573,6 +519,7 @@
                     # active bookmark was divergent one and has been deleted
                     activebookmark = None
         clearstatus(repo)
+        clearcollapsemsg(repo)
 
         ui.note(_("rebase completed\n"))
         util.unlinkpath(repo.sjoin('undo'), ignoremissing=True)
@@ -586,6 +533,84 @@
     finally:
         release(lock, wlock)
 
+def _definesets(ui, repo, destf=None, srcf=None, basef=None, revf=[]):
+    """use revisions argument to define destination and rebase set
+    """
+    if srcf and basef:
+        raise error.Abort(_('cannot specify both a source and a base'))
+    if revf and basef:
+        raise error.Abort(_('cannot specify both a revision and a base'))
+    if revf and srcf:
+        raise error.Abort(_('cannot specify both a revision and a source'))
+
+    cmdutil.checkunfinished(repo)
+    cmdutil.bailifchanged(repo)
+
+    if destf:
+        dest = scmutil.revsingle(repo, destf)
+
+    if revf:
+        rebaseset = scmutil.revrange(repo, revf)
+        if not rebaseset:
+            ui.status(_('empty "rev" revision set - nothing to rebase\n'))
+            return None, None
+    elif srcf:
+        src = scmutil.revrange(repo, [srcf])
+        if not src:
+            ui.status(_('empty "source" revision set - nothing to rebase\n'))
+            return None, None
+        rebaseset = repo.revs('(%ld)::', src)
+        assert rebaseset
+    else:
+        base = scmutil.revrange(repo, [basef or '.'])
+        if not base:
+            ui.status(_('empty "base" revision set - '
+                        "can't compute rebase set\n"))
+            return None, None
+        if not destf:
+            dest = repo[_destrebase(repo, base)]
+            destf = str(dest)
+
+        commonanc = repo.revs('ancestor(%ld, %d)', base, dest).first()
+        if commonanc is not None:
+            rebaseset = repo.revs('(%d::(%ld) - %d)::',
+                                  commonanc, base, commonanc)
+        else:
+            rebaseset = []
+
+        if not rebaseset:
+            # transform to list because smartsets are not comparable to
+            # lists. This should be improved to honor laziness of
+            # smartset.
+            if list(base) == [dest.rev()]:
+                if basef:
+                    ui.status(_('nothing to rebase - %s is both "base"'
+                                ' and destination\n') % dest)
+                else:
+                    ui.status(_('nothing to rebase - working directory '
+                                'parent is also destination\n'))
+            elif not repo.revs('%ld - ::%d', base, dest):
+                if basef:
+                    ui.status(_('nothing to rebase - "base" %s is '
+                                'already an ancestor of destination '
+                                '%s\n') %
+                              ('+'.join(str(repo[r]) for r in base),
+                               dest))
+                else:
+                    ui.status(_('nothing to rebase - working '
+                                'directory parent is already an '
+                                'ancestor of destination %s\n') % dest)
+            else: # can it happen?
+                ui.status(_('nothing to rebase from %s to %s\n') %
+                          ('+'.join(str(repo[r]) for r in base), dest))
+            return None, None
+
+    if not destf:
+        dest = repo[_destrebase(repo, rebaseset)]
+        destf = str(dest)
+
+    return dest, rebaseset
+
 def externalparent(repo, state, targetancestors):
     """Return the revision that should be used as the second parent
     when the revisions in state is collapsed on top of targetancestors.
@@ -838,6 +863,29 @@
             bookmarks.deletedivergent(repo, [targetnode], k)
     marks.recordchange(tr)
 
+def storecollapsemsg(repo, collapsemsg):
+    'Store the collapse message to allow recovery'
+    collapsemsg = collapsemsg or ''
+    f = repo.vfs("last-message.txt", "w")
+    f.write("%s\n" % collapsemsg)
+    f.close()
+
+def clearcollapsemsg(repo):
+    'Remove collapse message file'
+    util.unlinkpath(repo.join("last-message.txt"), ignoremissing=True)
+
+def restorecollapsemsg(repo):
+    'Restore previously stored collapse message'
+    try:
+        f = repo.vfs("last-message.txt")
+        collapsemsg = f.readline().strip()
+        f.close()
+    except IOError as err:
+        if err.errno != errno.ENOENT:
+            raise
+        raise error.Abort(_('no rebase in progress'))
+    return collapsemsg
+
 def storestatus(repo, originalwd, target, state, collapse, keep, keepbranches,
                 external, activebookmark):
     'Store the current status to allow recovery'
@@ -910,7 +958,7 @@
     except IOError as err:
         if err.errno != errno.ENOENT:
             raise
-        raise error.Abort(_('no rebase in progress'))
+        cmdutil.wrongtooltocontinue(repo, _('rebase'))
 
     if keepbranches is None:
         raise error.Abort(_('.hg/rebasestate is incomplete'))
@@ -997,6 +1045,7 @@
 
     finally:
         clearstatus(repo)
+        clearcollapsemsg(repo)
         repo.ui.warn(_('rebase aborted\n'))
     return 0
 
@@ -1140,7 +1189,6 @@
                 ui.debug('--update and --rebase are not compatible, ignoring '
                          'the update flag\n')
 
-            movemarkfrom = repo['.'].node()
             revsprepull = len(repo)
             origpostincoming = commands.postincoming
             def _dummy(*args, **kwargs):
@@ -1160,15 +1208,18 @@
                 # --source.
                 if 'source' in opts:
                     del opts['source']
-                rebase(ui, repo, **opts)
-                branch = repo[None].branch()
-                dest = repo[branch].rev()
-                if dest != repo['.'].rev():
-                    # there was nothing to rebase we force an update
-                    hg.update(repo, dest)
-                    if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
-                        ui.status(_("updating bookmark %s\n")
-                                  % repo._activebookmark)
+                try:
+                    rebase(ui, repo, **opts)
+                except error.NoMergeDestAbort:
+                    # we can maybe update instead
+                    rev, _a, _b = destutil.destupdate(repo)
+                    if rev == repo['.'].rev():
+                        ui.status(_('nothing to rebase\n'))
+                    else:
+                        ui.status(_('nothing to rebase - updating instead\n'))
+                        # not passing argument to get the bare update behavior
+                        # with warning and trumpets
+                        commands.update(ui, repo)
         finally:
             release(lock, wlock)
     else:
--- a/hgext/schemes.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/hgext/schemes.py	Wed Feb 24 15:55:44 2016 -0600
@@ -41,9 +41,11 @@
 """
 
 import os, re
-from mercurial import extensions, hg, templater, util, error
+from mercurial import extensions, hg, templater, util, error, cmdutil
 from mercurial.i18n import _
 
+cmdtable = {}
+command = cmdutil.command(cmdtable)
 # Note for extension authors: ONLY specify testedwith = 'internal' for
 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
 # be specifying the version(s) of Mercurial they are tested with, or
@@ -65,6 +67,10 @@
         return '<ShortRepository: %s>' % self.scheme
 
     def instance(self, ui, url, create):
+        url = self.resolve(url)
+        return hg._peerlookup(url).instance(ui, url, create)
+
+    def resolve(self, url):
         # Should this use the util.url class, or is manual parsing better?
         try:
             url = url.split('://', 1)[1]
@@ -77,8 +83,7 @@
         else:
             tail = ''
         context = dict((str(i + 1), v) for i, v in enumerate(parts))
-        url = ''.join(self.templater.process(self.url, context)) + tail
-        return hg._peerlookup(url).instance(ui, url, create)
+        return ''.join(self.templater.process(self.url, context)) + tail
 
 def hasdriveletter(orig, path):
     if path:
@@ -106,3 +111,12 @@
         hg.schemes[scheme] = ShortRepository(url, scheme, t)
 
     extensions.wrapfunction(util, 'hasdriveletter', hasdriveletter)
+
+@command('debugexpandscheme', norepo=True)
+def expandscheme(ui, url, **opts):
+    """given a repo path, provide the scheme-expanded path
+    """
+    repo = hg._peerlookup(url)
+    if isinstance(repo, ShortRepository):
+        url = repo.resolve(url)
+    ui.write(url + '\n')
--- a/hgext/shelve.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/hgext/shelve.py	Wed Feb 24 15:55:44 2016 -0600
@@ -628,7 +628,7 @@
         except IOError as err:
             if err.errno != errno.ENOENT:
                 raise
-            raise error.Abort(_('no unshelve operation underway'))
+            cmdutil.wrongtooltocontinue(repo, _('unshelve'))
 
         if abortf:
             return unshelveabort(ui, repo, state, opts)
--- a/i18n/posplit	Tue Feb 23 11:41:47 2016 +0100
+++ b/i18n/posplit	Wed Feb 24 15:55:44 2016 -0600
@@ -57,11 +57,13 @@
                 if mdirective:
                     if not msgid[mdirective.end():].rstrip():
                         # only directive, nothing to translate here
+                        delta += 2
                         continue
                     directive = mdirective.group(1)
                     if directive in ('container', 'include'):
                         if msgid.rstrip('\n').count('\n') == 0:
                             # only rst syntax, nothing to translate
+                            delta += 2
                             continue
                         else:
                             # lines following directly, unexpected
--- a/mercurial/archival.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/archival.py	Wed Feb 24 15:55:44 2016 -0600
@@ -331,7 +331,7 @@
     if subrepos:
         for subpath in sorted(ctx.substate):
             sub = ctx.workingsub(subpath)
-            submatch = matchmod.narrowmatcher(subpath, matchfn)
+            submatch = matchmod.subdirmatcher(subpath, matchfn)
             total += sub.archive(archiver, prefix, submatch)
 
     if total == 0:
--- a/mercurial/bookmarks.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/bookmarks.py	Wed Feb 24 15:55:44 2016 -0600
@@ -182,6 +182,11 @@
             fp.write("%s %s\n" % (hex(node), encoding.fromlocal(name)))
         self._clean = True
 
+    def expandname(self, bname):
+        if bname == '.':
+            return self.active
+        return bname
+
 def _readactive(repo, marks):
     """
     Get the active bookmark. We can have an active bookmark that updates
--- a/mercurial/bundlerepo.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/bundlerepo.py	Wed Feb 24 15:55:44 2016 -0600
@@ -362,7 +362,8 @@
 
         if f in self.bundlefilespos:
             self.bundle.seek(self.bundlefilespos[f])
-            return bundlefilelog(self.svfs, f, self.bundle, self.changelog.rev)
+            linkmapper = self.unfiltered().changelog.rev
+            return bundlefilelog(self.svfs, f, self.bundle, linkmapper)
         else:
             return filelog.filelog(self.svfs, f)
 
--- a/mercurial/cmdutil.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/cmdutil.py	Wed Feb 24 15:55:44 2016 -0600
@@ -758,14 +758,14 @@
             fp.write(str(pid) + '\n')
             fp.close()
 
-    if opts['daemon'] and not opts['daemon_pipefds']:
+    if opts['daemon'] and not opts['daemon_postexec']:
         # Signal child process startup with file removal
         lockfd, lockpath = tempfile.mkstemp(prefix='hg-service-')
         os.close(lockfd)
         try:
             if not runargs:
                 runargs = util.hgcmd() + sys.argv[1:]
-            runargs.append('--daemon-pipefds=%s' % lockpath)
+            runargs.append('--daemon-postexec=unlink:%s' % lockpath)
             # Don't pass --cwd to the child process, because we've already
             # changed directory.
             for i in xrange(1, len(runargs)):
@@ -796,15 +796,19 @@
         initfn()
 
     if not opts['daemon']:
-        writepid(os.getpid())
-
-    if opts['daemon_pipefds']:
-        lockpath = opts['daemon_pipefds']
+        writepid(util.getpid())
+
+    if opts['daemon_postexec']:
+        inst = opts['daemon_postexec']
         try:
             os.setsid()
         except AttributeError:
             pass
-        os.unlink(lockpath)
+        if inst.startswith('unlink:'):
+            lockpath = inst[7:]
+            os.unlink(lockpath)
+        elif inst != 'none':
+            raise error.Abort(_('invalid value for --daemon-postexec'))
         util.hidewindow()
         sys.stdout.flush()
         sys.stderr.flush()
@@ -1142,7 +1146,7 @@
                 # node2 (inclusive). Thus, ctx2's substate won't contain that
                 # subpath. The best we can do is to ignore it.
                 tempnode2 = None
-            submatch = matchmod.narrowmatcher(subpath, match)
+            submatch = matchmod.subdirmatcher(subpath, match)
             sub.diff(ui, diffopts, tempnode2, submatch, changes=changes,
                      stat=stat, fp=fp, prefix=prefix)
 
@@ -2254,7 +2258,7 @@
     for subpath in sorted(wctx.substate):
         sub = wctx.sub(subpath)
         try:
-            submatch = matchmod.narrowmatcher(subpath, match)
+            submatch = matchmod.subdirmatcher(subpath, match)
             if opts.get('subrepos'):
                 bad.extend(sub.add(ui, submatch, prefix, False, **opts))
             else:
@@ -2283,7 +2287,7 @@
     for subpath in sorted(wctx.substate):
         sub = wctx.sub(subpath)
         try:
-            submatch = matchmod.narrowmatcher(subpath, match)
+            submatch = matchmod.subdirmatcher(subpath, match)
             subbad, subforgot = sub.forget(submatch, prefix)
             bad.extend([subpath + '/' + f for f in subbad])
             forgot.extend([subpath + '/' + f for f in subforgot])
@@ -2340,7 +2344,7 @@
         if subrepos or matchessubrepo(subpath):
             sub = ctx.sub(subpath)
             try:
-                submatch = matchmod.narrowmatcher(subpath, m)
+                submatch = matchmod.subdirmatcher(subpath, m)
                 if sub.printfiles(ui, submatch, fm, fmt, subrepos) == 0:
                     ret = 0
             except error.LookupError:
@@ -2369,7 +2373,7 @@
         if subrepos or matchessubrepo(m, subpath):
             sub = wctx.sub(subpath)
             try:
-                submatch = matchmod.narrowmatcher(subpath, m)
+                submatch = matchmod.subdirmatcher(subpath, m)
                 if sub.removefiles(submatch, prefix, after, force, subrepos):
                     ret = 1
             except error.LookupError:
@@ -2467,7 +2471,7 @@
     for subpath in sorted(ctx.substate):
         sub = ctx.sub(subpath)
         try:
-            submatch = matchmod.narrowmatcher(subpath, matcher)
+            submatch = matchmod.subdirmatcher(subpath, matcher)
 
             if not sub.cat(submatch, os.path.join(prefix, sub._path),
                            **opts):
@@ -3122,13 +3126,26 @@
     """
     parent, p2 = parents
     node = ctx.node()
+    excluded_files = []
+    matcher_opts = {"exclude": excluded_files}
+
     def checkout(f):
         fc = ctx[f]
         repo.wwrite(f, fc.data(), fc.flags())
 
     audit_path = pathutil.pathauditor(repo.root)
     for f in actions['forget'][0]:
-        repo.dirstate.drop(f)
+        if interactive:
+            choice = \
+                repo.ui.promptchoice(
+                    _("forget added file %s (yn)?$$ &Yes $$ &No")
+                    % f)
+            if choice == 0:
+                repo.dirstate.drop(f)
+            else:
+                excluded_files.append(repo.wjoin(f))
+        else:
+            repo.dirstate.drop(f)
     for f in actions['remove'][0]:
         audit_path(f)
         try:
@@ -3154,7 +3171,7 @@
     if interactive:
         # Prompt the user for changes to revert
         torevert = [repo.wjoin(f) for f in actions['revert'][0]]
-        m = scmutil.match(ctx, torevert, {})
+        m = scmutil.match(ctx, torevert, matcher_opts)
         diffopts = patch.difffeatureopts(repo.ui, whitespace=True)
         diffopts.nodates = True
         diffopts.git = True
@@ -3326,13 +3343,56 @@
      _('hg graft --continue')),
     ]
 
-def checkafterresolved(repo):
-    contmsg = _("continue: %s\n")
+def howtocontinue(repo):
+    '''Check for an unfinished operation and return the command to finish
+    it.
+
+    afterresolvedstates tupples define a .hg/{file} and the corresponding
+    command needed to finish it.
+
+    Returns a (msg, warning) tuple. 'msg' is a string and 'warning' is
+    a boolean.
+    '''
+    contmsg = _("continue: %s")
     for f, msg in afterresolvedstates:
         if repo.vfs.exists(f):
-            repo.ui.warn(contmsg % msg)
-            return
-    repo.ui.note(contmsg % _("hg commit"))
+            return contmsg % msg, True
+    workingctx = repo[None]
+    dirty = any(repo.status()) or any(workingctx.sub(s).dirty()
+                                         for s in workingctx.substate)
+    if dirty:
+        return contmsg % _("hg commit"), False
+    return None, None
+
+def checkafterresolved(repo):
+    '''Inform the user about the next action after completing hg resolve
+
+    If there's a matching afterresolvedstates, howtocontinue will yield
+    repo.ui.warn as the reporter.
+
+    Otherwise, it will yield repo.ui.note.
+    '''
+    msg, warning = howtocontinue(repo)
+    if msg is not None:
+        if warning:
+            repo.ui.warn("%s\n" % msg)
+        else:
+            repo.ui.note("%s\n" % msg)
+
+def wrongtooltocontinue(repo, task):
+    '''Raise an abort suggesting how to properly continue if there is an
+    active task.
+
+    Uses howtocontinue() to find the active task.
+
+    If there's no task (repo.ui.note for 'hg commit'), it does not offer
+    a hint.
+    '''
+    after = howtocontinue(repo)
+    hint = None
+    if after[1]:
+        hint = after[0]
+    raise error.Abort(_('no %s in progress') % task, hint=hint)
 
 class dirstateguard(object):
     '''Restore dirstate at unexpected failure.
--- a/mercurial/commands.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/commands.py	Wed Feb 24 15:55:44 2016 -0600
@@ -2457,20 +2457,21 @@
             raise error.Abort(_("no ignore patterns found"))
     else:
         for f in files:
+            nf = util.normpath(f)
             ignored = None
             ignoredata = None
-            if f != '.':
-                if ignore(f):
-                    ignored = f
-                    ignoredata = repo.dirstate._ignorefileandline(f)
+            if nf != '.':
+                if ignore(nf):
+                    ignored = nf
+                    ignoredata = repo.dirstate._ignorefileandline(nf)
                 else:
-                    for p in util.finddirs(f):
+                    for p in util.finddirs(nf):
                         if ignore(p):
                             ignored = p
                             ignoredata = repo.dirstate._ignorefileandline(p)
                             break
             if ignored:
-                if ignored == f:
+                if ignored == nf:
                     ui.write("%s is ignored\n" % f)
                 else:
                     ui.write("%s is ignored because of containing folder %s\n"
@@ -2813,6 +2814,17 @@
                          % (afile, _hashornull(anode)))
                 ui.write(('  other path: %s (node %s)\n')
                          % (ofile, _hashornull(onode)))
+            elif rtype == 'f':
+                filename, rawextras = record.split('\0', 1)
+                extras = rawextras.split('\0')
+                i = 0
+                extrastrings = []
+                while i < len(extras):
+                    extrastrings.append('%s = %s' % (extras[i], extras[i + 1]))
+                    i += 2
+
+                ui.write(('file extras: %s (%s)\n')
+                         % (filename, ', '.join(extrastrings)))
             else:
                 ui.write(('unrecognized entry: %s\t%s\n')
                          % (rtype, record.replace('\0', '\t')))
@@ -3204,12 +3216,16 @@
             ts = ts + rs
             heads -= set(r.parentrevs(rev))
             heads.add(rev)
+            try:
+                compression = ts / r.end(rev)
+            except ZeroDivisionError:
+                compression = 0
             ui.write("%5d %5d %5d %5d %5d %10d %4d %4d %4d %7d %9d "
                      "%11d %5d %8d\n" %
                      (rev, p1, p2, r.start(rev), r.end(rev),
                       r.start(dbase), r.start(cbase),
                       r.start(p1), r.start(p2),
-                      rs, ts, ts / r.end(rev), len(heads), clen))
+                      rs, ts, compression, len(heads), clen))
         return 0
 
     v = r.version
@@ -3917,7 +3933,7 @@
         except IOError as inst:
             if inst.errno != errno.ENOENT:
                 raise
-            raise error.Abort(_("no graft state found, can't continue"))
+            cmdutil.wrongtooltocontinue(repo, _('graft'))
     else:
         cmdutil.checkunfinished(repo)
         cmdutil.bailifchanged(repo)
@@ -5231,7 +5247,8 @@
     try:
         # ui.forcemerge is an internal variable, do not document
         repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''), 'merge')
-        return hg.merge(repo, node, force=opts.get('force'))
+        force = opts.get('force')
+        return hg.merge(repo, node, force=force, mergeforce=force)
     finally:
         ui.setconfig('ui', 'forcemerge', '', 'merge')
 
@@ -5530,13 +5547,17 @@
     if modheads == 0:
         return
     if optupdate:
+        warndest = False
         try:
             brev = checkout
             movemarkfrom = None
             if not checkout:
+                warndest = True
                 updata = destutil.destupdate(repo)
                 checkout, movemarkfrom, brev = updata
             ret = hg.update(repo, checkout)
+            if warndest:
+                destutil.statusotherdests(ui, repo)
         except error.UpdateAbort as inst:
             msg = _("not updating: %s") % str(inst)
             hint = inst.hint
@@ -5687,7 +5708,8 @@
 
     If -B/--bookmark is used, the specified bookmarked revision, its
     ancestors, and the bookmark will be pushed to the remote
-    repository.
+    repository. Specifying ``.`` is equivalent to specifying the active
+    bookmark's name.
 
     Please see :hg:`help urls` for important details about ``ssh://``
     URLs. If DESTINATION is omitted, a default path will be used.
@@ -5699,6 +5721,7 @@
         ui.setconfig('bookmarks', 'pushing', opts['bookmark'], 'push')
         for b in opts['bookmark']:
             # translate -B options to -r so changesets get pushed
+            b = repo._bookmarks.expandname(b)
             if b in repo._bookmarks:
                 opts.setdefault('rev', []).append(b)
             else:
@@ -6185,7 +6208,7 @@
     [('A', 'accesslog', '', _('name of access log file to write to'),
      _('FILE')),
     ('d', 'daemon', None, _('run server in background')),
-    ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('FILE')),
+    ('', 'daemon-postexec', '', _('used internally by daemon mode')),
     ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
     # use string type, then we can check if something was passed
     ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
@@ -6943,27 +6966,30 @@
     if rev is None or rev == '':
         rev = node
 
+    if date and rev is not None:
+        raise error.Abort(_("you can't specify a revision and a date"))
+
+    if check and clean:
+        raise error.Abort(_("cannot specify both -c/--check and -C/--clean"))
+
+    warndest = False
+
     with repo.wlock():
         cmdutil.clearunfinished(repo)
 
         if date:
-            if rev is not None:
-                raise error.Abort(_("you can't specify a revision and a date"))
             rev = cmdutil.finddate(ui, repo, date)
 
         # if we defined a bookmark, we have to remember the original name
         brev = rev
         rev = scmutil.revsingle(repo, rev, rev).rev()
 
-        if check and clean:
-            raise error.Abort(_("cannot specify both -c/--check and -C/--clean")
-                             )
-
         if check:
             cmdutil.bailifchanged(repo, merge=False)
         if rev is None:
             updata = destutil.destupdate(repo, clean=clean, check=check)
             rev, movemarkfrom, brev = updata
+            warndest = True
 
         repo.ui.setconfig('ui', 'forcemerge', tool, 'update')
 
@@ -6990,7 +7016,8 @@
                 ui.status(_("(leaving bookmark %s)\n") %
                           repo._activebookmark)
             bookmarks.deactivate(repo)
-
+        if warndest:
+            destutil.statusotherdests(ui, repo)
     return ret
 
 @command('verify', [])
@@ -7030,10 +7057,16 @@
         # format names and versions into columns
         names = []
         vers = []
+        place = []
         for name, module in extensions.extensions():
             names.append(name)
             vers.append(extensions.moduleversion(module))
+            if extensions.ismoduleinternal(module):
+                place.append(_("internal"))
+            else:
+                place.append(_("external"))
         if names:
             maxnamelen = max(len(n) for n in names)
             for i, name in enumerate(names):
-                ui.write("  %-*s  %s\n" % (maxnamelen, name, vers[i]))
+                ui.write("  %-*s  %s  %s\n" %
+                         (maxnamelen, name, place[i], vers[i]))
--- a/mercurial/commandserver.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/commandserver.py	Wed Feb 24 15:55:44 2016 -0600
@@ -190,16 +190,31 @@
 
         return data
 
+    def _readstr(self):
+        """read a string from the channel
+
+        format:
+        data length (uint32), data
+        """
+        length = struct.unpack('>I', self._read(4))[0]
+        if not length:
+            return ''
+        return self._read(length)
+
+    def _readlist(self):
+        """read a list of NULL separated strings from the channel"""
+        s = self._readstr()
+        if s:
+            return s.split('\0')
+        else:
+            return []
+
     def runcommand(self):
         """ reads a list of \0 terminated arguments, executes
         and writes the return code to the result channel """
         from . import dispatch  # avoid cycle
 
-        length = struct.unpack('>I', self._read(4))[0]
-        if not length:
-            args = []
-        else:
-            args = self._read(length).split('\0')
+        args = self._readlist()
 
         # copy the uis so changes (e.g. --config or --verbose) don't
         # persist between requests
@@ -262,7 +277,7 @@
         hellomsg += '\n'
         hellomsg += 'encoding: ' + encoding.encoding
         hellomsg += '\n'
-        hellomsg += 'pid: %d' % os.getpid()
+        hellomsg += 'pid: %d' % util.getpid()
 
         # write the hello msg in -one- chunk
         self.cout.write(hellomsg)
--- a/mercurial/context.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/context.py	Wed Feb 24 15:55:44 2016 -0600
@@ -365,7 +365,7 @@
                     # node1 and node2 (inclusive). Thus, ctx2's substate
                     # won't contain that subpath. The best we can do ignore it.
                     rev2 = None
-                submatch = matchmod.narrowmatcher(subpath, match)
+                submatch = matchmod.subdirmatcher(subpath, match)
                 s = sub.status(rev2, match=submatch, ignored=listignored,
                                clean=listclean, unknown=listunknown,
                                listsubrepos=True)
@@ -789,7 +789,7 @@
         if fctx._customcmp:
             return fctx.cmp(self)
 
-        if (fctx._filerev is None
+        if (fctx._filenode is None
             and (self._repo._encodefilterpats
                  # if file data starts with '\1\n', empty metadata block is
                  # prepended, which adds 4 bytes to filelog.size().
@@ -1892,9 +1892,9 @@
             p2node = nullid
             p = pctx[f].parents() # if file isn't in pctx, check p2?
             if len(p) > 0:
-                p1node = p[0].node()
+                p1node = p[0].filenode()
                 if len(p) > 1:
-                    p2node = p[1].node()
+                    p2node = p[1].filenode()
             man[f] = revlog.hash(self[f].data(), p1node, p2node)
 
         for f in self._status.added:
--- a/mercurial/copies.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/copies.py	Wed Feb 24 15:55:44 2016 -0600
@@ -10,7 +10,9 @@
 import heapq
 
 from . import (
+    node,
     pathutil,
+    scmutil,
     util,
 )
 
@@ -175,7 +177,18 @@
     # we currently don't try to find where old files went, too expensive
     # this means we can miss a case like 'hg rm b; hg cp a b'
     cm = {}
-    missing = _computeforwardmissing(a, b, match=match)
+
+    # Computing the forward missing is quite expensive on large manifests, since
+    # it compares the entire manifests. We can optimize it in the common use
+    # case of computing what copies are in a commit versus its parent (like
+    # during a rebase or histedit). Note, we exclude merge commits from this
+    # optimization, since the ctx.files() for a merge commit is not correct for
+    # this comparison.
+    forwardmissingmatch = match
+    if not match and b.p1() == a and b.p2().node() == node.nullid:
+        forwardmissingmatch = scmutil.matchfiles(a._repo, b.files())
+    missing = _computeforwardmissing(a, b, match=forwardmissingmatch)
+
     ancestrycontext = a._repo.changelog.ancestors([b.rev()], inclusive=True)
     for f in missing:
         fctx = b[f]
--- a/mercurial/demandimport.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/demandimport.py	Wed Feb 24 15:55:44 2016 -0600
@@ -174,7 +174,12 @@
             """
             symbol = getattr(mod, attr, nothing)
             if symbol is nothing:
-                symbol = _demandmod(attr, mod.__dict__, locals, level=1)
+                mn = '%s.%s' % (mod.__name__, attr)
+                if mn in ignore:
+                    importfunc = _origimport
+                else:
+                    importfunc = _demandmod
+                symbol = importfunc(attr, mod.__dict__, locals, level=1)
                 setattr(mod, attr, symbol)
 
             # Record the importing module references this symbol so we can
@@ -250,6 +255,7 @@
     '_sre', # issue4920
     'rfc822',
     'mimetools',
+    'sqlalchemy.events', # has import-time side effects (issue5085)
     # setuptools 8 expects this module to explode early when not on windows
     'distutils.msvc9compiler'
     ]
--- a/mercurial/destutil.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/destutil.py	Wed Feb 24 15:55:44 2016 -0600
@@ -92,7 +92,8 @@
     wc = repo[None]
     movemark = node = None
     try:
-        node = repo.branchtip(wc.branch())
+        node = repo.revs('max(.::(head() and branch(%s)))'
+                         , wc.branch()).first()
         if bookmarks.isactivewdirparent(repo):
             movemark = repo['.'].node()
     except error.RepoLookupError:
@@ -133,7 +134,102 @@
 
     return rev, movemark, activemark
 
-def _destmergebook(repo):
+msgdestmerge = {
+    # too many matching divergent bookmark
+    'toomanybookmarks':
+        {'merge':
+            (_("multiple matching bookmarks to merge -"
+               " please merge with an explicit rev or bookmark"),
+             _("run 'hg heads' to see all heads")),
+         'rebase':
+            (_("multiple matching bookmarks to rebase -"
+               " please rebase to an explicit rev or bookmark"),
+             _("run 'hg heads' to see all heads")),
+        },
+    # no other matching divergent bookmark
+    'nootherbookmarks':
+        {'merge':
+            (_("no matching bookmark to merge - "
+               "please merge with an explicit rev or bookmark"),
+             _("run 'hg heads' to see all heads")),
+         'rebase':
+            (_("no matching bookmark to rebase - "
+               "please rebase to an explicit rev or bookmark"),
+             _("run 'hg heads' to see all heads")),
+        },
+    # branch have too many unbookmarked heads, no obvious destination
+    'toomanyheads':
+        {'merge':
+            (_("branch '%s' has %d heads - please merge with an explicit rev"),
+             _("run 'hg heads .' to see heads")),
+         'rebase':
+            (_("branch '%s' has %d heads - please rebase to an explicit rev"),
+             _("run 'hg heads .' to see heads")),
+        },
+    # branch have no other unbookmarked heads
+    'bookmarkedheads':
+        {'merge':
+            (_("heads are bookmarked - please merge with an explicit rev"),
+             _("run 'hg heads' to see all heads")),
+         'rebase':
+            (_("heads are bookmarked - please rebase to an explicit rev"),
+             _("run 'hg heads' to see all heads")),
+        },
+    # branch have just a single heads, but there is other branches
+    'nootherbranchheads':
+        {'merge':
+            (_("branch '%s' has one head - please merge with an explicit rev"),
+             _("run 'hg heads' to see all heads")),
+         'rebase':
+            (_("branch '%s' has one head - please rebase to an explicit rev"),
+             _("run 'hg heads' to see all heads")),
+        },
+    # repository have a single head
+    'nootherheads':
+        {'merge':
+            (_('nothing to merge'),
+            None),
+         'rebase':
+            (_('nothing to rebase'),
+            None),
+        },
+    # repository have a single head and we are not on it
+    'nootherheadsbehind':
+        {'merge':
+            (_('nothing to merge'),
+             _("use 'hg update' instead")),
+         'rebase':
+            (_('nothing to rebase'),
+             _("use 'hg update' instead")),
+        },
+    # We are not on a head
+    'notatheads':
+        {'merge':
+            (_('working directory not at a head revision'),
+             _("use 'hg update' or merge with an explicit revision")),
+         'rebase':
+            (_('working directory not at a head revision'),
+             _("use 'hg update' or rebase to an explicit revision"))
+        },
+    'emptysourceset':
+        {'merge':
+            (_('source set is empty'),
+             None),
+         'rebase':
+            (_('source set is empty'),
+             None),
+        },
+    'multiplebranchessourceset':
+        {'merge':
+            (_('source set is rooted in multiple branches'),
+             None),
+         'rebase':
+            (_('rebaseset is rooted in multiple named branches'),
+             _('specify an explicit destination with --dest')),
+        },
+    }
+
+def _destmergebook(repo, action='merge', sourceset=None):
     """find merge destination in the active bookmark case"""
     node = None
     bmheads = repo.bookmarkheads(repo._activebookmark)
@@ -144,61 +240,90 @@
         else:
             node = bmheads[0]
     elif len(bmheads) > 2:
-        raise error.Abort(_("multiple matching bookmarks to merge - "
-            "please merge with an explicit rev or bookmark"),
-            hint=_("run 'hg heads' to see all heads"))
+        msg, hint = msgdestmerge['toomanybookmarks'][action]
+        raise error.ManyMergeDestAbort(msg, hint=hint)
     elif len(bmheads) <= 1:
-        raise error.Abort(_("no matching bookmark to merge - "
-            "please merge with an explicit rev or bookmark"),
-            hint=_("run 'hg heads' to see all heads"))
+        msg, hint = msgdestmerge['nootherbookmarks'][action]
+        raise error.NoMergeDestAbort(msg, hint=hint)
     assert node is not None
     return node
 
-def _destmergebranch(repo):
+def _destmergebranch(repo, action='merge', sourceset=None, onheadcheck=True):
     """find merge destination based on branch heads"""
     node = None
-    branch = repo[None].branch()
-    bheads = repo.branchheads(branch)
-    nbhs = [bh for bh in bheads if not repo[bh].bookmarks()]
 
-    if len(nbhs) > 2:
-        raise error.Abort(_("branch '%s' has %d heads - "
-                           "please merge with an explicit rev")
-                         % (branch, len(bheads)),
-                         hint=_("run 'hg heads .' to see heads"))
+    if sourceset is None:
+        sourceset = [repo[repo.dirstate.p1()].rev()]
+        branch = repo.dirstate.branch()
+    elif not sourceset:
+        msg, hint = msgdestmerge['emptysourceset'][action]
+        raise error.NoMergeDestAbort(msg, hint=hint)
+    else:
+        branch = None
+        for ctx in repo.set('roots(%ld::%ld)', sourceset, sourceset):
+            if branch is not None and ctx.branch() != branch:
+                msg, hint = msgdestmerge['multiplebranchessourceset'][action]
+                raise error.ManyMergeDestAbort(msg, hint=hint)
+            branch = ctx.branch()
 
-    parent = repo.dirstate.p1()
-    if len(nbhs) <= 1:
-        if len(bheads) > 1:
-            raise error.Abort(_("heads are bookmarked - "
-                               "please merge with an explicit rev"),
-                             hint=_("run 'hg heads' to see all heads"))
-        if len(repo.heads()) > 1:
-            raise error.Abort(_("branch '%s' has one head - "
-                               "please merge with an explicit rev")
-                             % branch,
-                             hint=_("run 'hg heads' to see all heads"))
-        msg, hint = _('nothing to merge'), None
-        if parent != repo.lookup(branch):
-            hint = _("use 'hg update' instead")
+    bheads = repo.branchheads(branch)
+    onhead = repo.revs('%ld and %ln', sourceset, bheads)
+    if onheadcheck and not onhead:
+        # Case A: working copy if not on a head. (merge only)
+        #
+        # This is probably a user mistake We bailout pointing at 'hg update'
+        if len(repo.heads()) <= 1:
+            msg, hint = msgdestmerge['nootherheadsbehind'][action]
+        else:
+            msg, hint = msgdestmerge['notatheads'][action]
         raise error.Abort(msg, hint=hint)
-
-    if parent not in bheads:
-        raise error.Abort(_('working directory not at a head revision'),
-                         hint=_("use 'hg update' or merge with an "
-                                "explicit revision"))
-    if parent == nbhs[0]:
-        node = nbhs[-1]
+    # remove heads descendants of source from the set
+    bheads = list(repo.revs('%ln - (%ld::)', bheads, sourceset))
+    # filters out bookmarked heads
+    nbhs = list(repo.revs('%ld - bookmark()', bheads))
+    if len(nbhs) > 1:
+        # Case B: There is more than 1 other anonymous heads
+        #
+        # This means that there will be more than 1 candidate. This is
+        # ambiguous. We abort asking the user to pick as explicit destination
+        # instead.
+        msg, hint = msgdestmerge['toomanyheads'][action]
+        msg %= (branch, len(bheads) + 1)
+        raise error.ManyMergeDestAbort(msg, hint=hint)
+    elif not nbhs:
+        # Case B: There is no other anonymous heads
+        #
+        # This means that there is no natural candidate to merge with.
+        # We abort, with various messages for various cases.
+        if bheads:
+            msg, hint = msgdestmerge['bookmarkedheads'][action]
+        elif len(repo.heads()) > 1:
+            msg, hint = msgdestmerge['nootherbranchheads'][action]
+            msg %= branch
+        elif not onhead:
+            # if 'onheadcheck == False' (rebase case),
+            # this was not caught in Case A.
+            msg, hint = msgdestmerge['nootherheadsbehind'][action]
+        else:
+            msg, hint = msgdestmerge['nootherheads'][action]
+        raise error.NoMergeDestAbort(msg, hint=hint)
     else:
         node = nbhs[0]
     assert node is not None
     return node
 
-def destmerge(repo):
+def destmerge(repo, action='merge', sourceset=None, onheadcheck=True):
+    """return the default destination for a merge
+
+    (or raise exception about why it can't pick one)
+
+    :action: the action being performed, controls emitted error message
+    """
     if repo._activebookmark:
-        node = _destmergebook(repo)
+        node = _destmergebook(repo, action=action, sourceset=sourceset)
     else:
-        node = _destmergebranch(repo)
+        node = _destmergebranch(repo, action=action, sourceset=sourceset,
+                                onheadcheck=onheadcheck)
     return repo[node].rev()
 
 histeditdefaultrevset = 'reverse(only(.) and not public() and not ::merge())'
@@ -218,3 +343,34 @@
             return revs.first()
 
     return None
+
+def _statusotherbook(ui, repo):
+    bmheads = repo.bookmarkheads(repo._activebookmark)
+    curhead = repo[repo._activebookmark].node()
+    if repo.revs('%n and parents()', curhead):
+        # we are on the active bookmark
+        bmheads = [b for b in bmheads if curhead != b]
+        if bmheads:
+            msg = _('%i other divergent bookmarks for "%s"\n')
+            ui.status(msg % (len(bmheads), repo._activebookmark))
+
+def _statusotherbranchheads(ui, repo):
+    currentbranch = repo.dirstate.branch()
+    heads = repo.branchheads(currentbranch)
+    l = len(heads)
+    if repo.revs('%ln and parents()', heads):
+        # we are on a head
+        heads = repo.revs('%ln - parents()', heads)
+        if heads and l != len(heads):
+            ui.status(_('%i other heads for branch "%s"\n') %
+                      (len(heads), currentbranch))
+
+def statusotherdests(ui, repo):
+    """Print message about other head"""
+    # XXX we should probably include a hint:
+    # - about what to do
+    # - how to see such heads
+    if repo._activebookmark:
+        _statusotherbook(ui, repo)
+    else:
+        _statusotherbranchheads(ui, repo)
--- a/mercurial/dispatch.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/dispatch.py	Wed Feb 24 15:55:44 2016 -0600
@@ -609,7 +609,8 @@
 
     for cfg in config:
         try:
-            name, value = cfg.split('=', 1)
+            name, value = [cfgelem.strip()
+                           for cfgelem in cfg.split('=', 1)]
             section, name = name.split('.', 1)
             if not section or not name:
                 raise IndexError
--- a/mercurial/encoding.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/encoding.py	Wed Feb 24 15:55:44 2016 -0600
@@ -7,6 +7,7 @@
 
 from __future__ import absolute_import
 
+import array
 import locale
 import os
 import unicodedata
@@ -378,9 +379,23 @@
     upper = 1
     other = 0
 
-_jsonmap = {}
+_jsonmap = []
+_jsonmap.extend("\\u%04x" % x for x in xrange(32))
+_jsonmap.extend(chr(x) for x in xrange(32, 127))
+_jsonmap.append('\\u007f')
+_jsonmap[0x09] = '\\t'
+_jsonmap[0x0a] = '\\n'
+_jsonmap[0x22] = '\\"'
+_jsonmap[0x5c] = '\\\\'
+_jsonmap[0x08] = '\\b'
+_jsonmap[0x0c] = '\\f'
+_jsonmap[0x0d] = '\\r'
+_paranoidjsonmap = _jsonmap[:]
+_paranoidjsonmap[0x3c] = '\\u003c'  # '<' (e.g. escape "</script>")
+_paranoidjsonmap[0x3e] = '\\u003e'  # '>'
+_jsonmap.extend(chr(x) for x in xrange(128, 256))
 
-def jsonescape(s):
+def jsonescape(s, paranoid=False):
     '''returns a string suitable for JSON
 
     JSON is problematic for us because it doesn't support non-Unicode
@@ -405,24 +420,36 @@
     'utf-8: caf\\xc3\\xa9'
     >>> jsonescape('')
     ''
+
+    If paranoid, non-ascii and common troublesome characters are also escaped.
+    This is suitable for web output.
+
+    >>> jsonescape('escape boundary: \\x7e \\x7f \\xc2\\x80', paranoid=True)
+    'escape boundary: ~ \\\\u007f \\\\u0080'
+    >>> jsonescape('a weird byte: \\xdd', paranoid=True)
+    'a weird byte: \\\\udcdd'
+    >>> jsonescape('utf-8: caf\\xc3\\xa9', paranoid=True)
+    'utf-8: caf\\\\u00e9'
+    >>> jsonescape('non-BMP: \\xf0\\x9d\\x84\\x9e', paranoid=True)
+    'non-BMP: \\\\ud834\\\\udd1e'
+    >>> jsonescape('<foo@example.org>', paranoid=True)
+    '\\\\u003cfoo@example.org\\\\u003e'
     '''
 
-    if not _jsonmap:
-        for x in xrange(32):
-            _jsonmap[chr(x)] = "\\u%04x" % x
-        for x in xrange(32, 256):
-            c = chr(x)
-            _jsonmap[c] = c
-        _jsonmap['\x7f'] = '\\u007f'
-        _jsonmap['\t'] = '\\t'
-        _jsonmap['\n'] = '\\n'
-        _jsonmap['\"'] = '\\"'
-        _jsonmap['\\'] = '\\\\'
-        _jsonmap['\b'] = '\\b'
-        _jsonmap['\f'] = '\\f'
-        _jsonmap['\r'] = '\\r'
+    if paranoid:
+        jm = _paranoidjsonmap
+    else:
+        jm = _jsonmap
 
-    return ''.join(_jsonmap[c] for c in toutf8b(s))
+    u8chars = toutf8b(s)
+    try:
+        return ''.join(jm[x] for x in bytearray(u8chars))  # fast path
+    except IndexError:
+        pass
+    # non-BMP char is represented as UTF-16 surrogate pair
+    u16codes = array.array('H', u8chars.decode('utf-8').encode('utf-16'))
+    u16codes.pop(0)  # drop BOM
+    return ''.join(jm[x] if x < 128 else '\\u%04x' % x for x in u16codes)
 
 _utf8len = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 4]
 
--- a/mercurial/error.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/error.py	Wed Feb 24 15:55:44 2016 -0600
@@ -72,6 +72,15 @@
 class UpdateAbort(Abort):
     """Raised when an update is aborted for destination issue"""
 
+class MergeDestAbort(Abort):
+    """Raised when an update is aborted for destination issues"""
+
+class NoMergeDestAbort(MergeDestAbort):
+    """Raised when an update is aborted because there is nothing to merge"""
+
+class ManyMergeDestAbort(MergeDestAbort):
+    """Raised when an update is aborted because destination is ambigious"""
+
 class ResponseExpected(Abort):
     """Raised when an EOF is received for a prompt"""
     def __init__(self):
--- a/mercurial/exchange.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/exchange.py	Wed Feb 24 15:55:44 2016 -0600
@@ -576,7 +576,8 @@
         ancestors = repo.changelog.ancestors(revnums, inclusive=True)
     remotebookmark = remote.listkeys('bookmarks')
 
-    explicit = set(pushop.bookmarks)
+    explicit = set([repo._bookmarks.expandname(bookmark)
+                    for bookmark in pushop.bookmarks])
 
     comp = bookmod.compare(repo, repo._bookmarks, remotebookmark, srchex=hex)
     addsrc, adddst, advsrc, advdst, diverge, differ, invalid, same = comp
--- a/mercurial/extensions.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/extensions.py	Wed Feb 24 15:55:44 2016 -0600
@@ -456,6 +456,10 @@
 
     return exts
 
+def notloaded():
+    '''return short names of extensions that failed to load'''
+    return [name for name, mod in _extensions.iteritems() if mod is None]
+
 def moduleversion(module):
     '''return version information from given module as a string'''
     if (util.safehasattr(module, 'getversion')
@@ -468,3 +472,7 @@
     if isinstance(version, (list, tuple)):
         version = '.'.join(str(o) for o in version)
     return version
+
+def ismoduleinternal(module):
+    exttestedwith = getattr(module, 'testedwith', None)
+    return exttestedwith == "internal"
--- a/mercurial/help.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/help.py	Wed Feb 24 15:55:44 2016 -0600
@@ -149,6 +149,8 @@
     for name, docs in itertools.chain(
         extensions.enabled(False).iteritems(),
         extensions.disabled().iteritems()):
+        if not docs:
+            continue
         mod = extensions.load(ui, name, '')
         name = name.rpartition('.')[-1]
         if lowercontains(name) or lowercontains(docs):
--- a/mercurial/help/config.txt	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/help/config.txt	Wed Feb 24 15:55:44 2016 -0600
@@ -800,7 +800,7 @@
 ``outgoing``
   Run after sending changes from local repository to another. ID of
   first changeset sent is in ``$HG_NODE``. Source of operation is in
-  ``$HG_SOURCE``; Also see :hg:`help config.preoutgoing` hook.
+  ``$HG_SOURCE``; Also see :hg:`help config.hooks.preoutgoing` hook.
 
 ``post-<command>``
   Run after successful invocations of the associated command. The
@@ -881,11 +881,11 @@
 ``txnclose``
   Run after any repository transaction has been committed. At this
   point, the transaction can no longer be rolled back. The hook will run
-  after the lock is released. See :hg:`help config.pretxnclose` docs for
+  after the lock is released. See :hg:`help config.hooks.pretxnclose` docs for
   details about available variables.
 
 ``txnabort``
-  Run when a transaction is aborted. See :hg:`help config.pretxnclose`
+  Run when a transaction is aborted. See :hg:`help config.hooks.pretxnclose`
   docs for details about available variables.
 
 ``pretxnchangegroup``
@@ -1007,6 +1007,25 @@
     Optional. Always use the proxy, even for localhost and any entries
     in ``http_proxy.no``. (default: False)
 
+``merge``
+---------
+
+This section specifies behavior during merges and updates.
+
+``checkignored``
+   Controls behavior when an ignored file on disk has the same name as a tracked
+   file in the changeset being merged or updated to, and has different
+   contents. Options are ``abort``, ``warn`` and ``ignore``. With ``abort``,
+   abort on such files. With ``warn``, warn on such files and back them up as
+   .orig. With ``ignore``, don't print a warning and back them up as
+   .orig. (default: ``abort``)
+
+``checkunknown``
+   Controls behavior when an unknown file that isn't ignored has the same name
+   as a tracked file in the changeset being merged or updated to, and has
+   different contents. Similar to ``merge.checkignored``, except for files that
+   are not ignored. (default: ``abort``)
+
 ``merge-patterns``
 ------------------
 
--- a/mercurial/help/environment.txt	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/help/environment.txt	Wed Feb 24 15:55:44 2016 -0600
@@ -69,6 +69,8 @@
         Preserve internationalization.
     ``revsetalias``
         Don't remove revset aliases.
+    ``progress``
+        Don't hide progress output.
 
     Setting HGPLAINEXCEPT to anything (even an empty string) will
     enable plain mode.
--- a/mercurial/hg.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/hg.py	Wed Feb 24 15:55:44 2016 -0600
@@ -236,20 +236,7 @@
 
     r = repository(ui, destwvfs.base)
     postshare(srcrepo, r, bookmarks=bookmarks)
-
-    if update:
-        r.ui.status(_("updating working directory\n"))
-        if update is not True:
-            checkout = update
-        for test in (checkout, 'default', 'tip'):
-            if test is None:
-                continue
-            try:
-                uprev = r.lookup(test)
-                break
-            except error.RepoLookupError:
-                continue
-        _update(r, uprev)
+    _postshareupdate(r, update, checkout=checkout)
 
 def postshare(sourcerepo, destrepo, bookmarks=True):
     """Called after a new shared repo is created.
@@ -272,6 +259,27 @@
         fp.write('bookmarks\n')
         fp.close()
 
+def _postshareupdate(repo, update, checkout=None):
+    """Maybe perform a working directory update after a shared repo is created.
+
+    ``update`` can be a boolean or a revision to update to.
+    """
+    if not update:
+        return
+
+    repo.ui.status(_("updating working directory\n"))
+    if update is not True:
+        checkout = update
+    for test in (checkout, 'default', 'tip'):
+        if test is None:
+            continue
+        try:
+            uprev = repo.lookup(test)
+            break
+        except error.RepoLookupError:
+            continue
+    _update(repo, uprev)
+
 def copystore(ui, srcrepo, destpath):
     '''copy files from store of srcrepo in destpath
 
@@ -348,7 +356,7 @@
               rev=rev, update=False, stream=stream)
 
     sharerepo = repository(ui, path=sharepath)
-    share(ui, sharerepo, dest=dest, update=update, bookmarks=False)
+    share(ui, sharerepo, dest=dest, update=False, bookmarks=False)
 
     # We need to perform a pull against the dest repo to fetch bookmarks
     # and other non-store data that isn't shared by default. In the case of
@@ -358,6 +366,8 @@
     destrepo = repository(ui, path=dest)
     exchange.pull(destrepo, srcpeer, heads=revs)
 
+    _postshareupdate(destrepo, update)
+
     return srcpeer, peer(ui, peeropts, dest)
 
 def clone(ui, peeropts, source, dest=None, pull=False, rev=None,
@@ -671,10 +681,10 @@
         _showstats(repo, stats, quietempty)
     return stats[3] > 0
 
-def merge(repo, node, force=None, remind=True):
+def merge(repo, node, force=None, remind=True, mergeforce=False):
     """Branch merge with node, resolving changes. Return true if any
     unresolved conflicts."""
-    stats = mergemod.update(repo, node, True, force)
+    stats = mergemod.update(repo, node, True, force, mergeforce=mergeforce)
     _showstats(repo, stats)
     if stats[3]:
         repo.ui.status(_("use 'hg resolve' to retry unresolved file merges "
@@ -865,6 +875,7 @@
         assert isinstance(repo, localrepo.localrepository)
         self._repo = repo
         self._state, self.mtime = self._repostate()
+        self._filtername = repo.filtername
 
     def fetch(self):
         """Refresh (if necessary) and return a repository.
@@ -884,7 +895,11 @@
         if state == self._state:
             return self._repo, False
 
-        self._repo = repository(self._repo.baseui, self._repo.url())
+        repo = repository(self._repo.baseui, self._repo.url())
+        if self._filtername:
+            self._repo = repo.filtered(self._filtername)
+        else:
+            self._repo = repo.unfiltered()
         self._state = state
         self.mtime = mtime
 
@@ -912,6 +927,10 @@
         completely independent of the original.
         """
         repo = repository(self._repo.baseui, self._repo.origroot)
+        if self._filtername:
+            repo = repo.filtered(self._filtername)
+        else:
+            repo = repo.unfiltered()
         c = cachedlocalrepo(repo)
         c._state = self._state
         c.mtime = self.mtime
--- a/mercurial/hgweb/webcommands.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/hgweb/webcommands.py	Wed Feb 24 15:55:44 2016 -0600
@@ -1135,7 +1135,7 @@
                              max([edge[1] for edge in edges] or [0]))
         return cols
 
-    def graphdata(usetuples, **map):
+    def graphdata(usetuples, encodestr):
         data = []
 
         row = 0
@@ -1143,11 +1143,11 @@
             if type != graphmod.CHANGESET:
                 continue
             node = str(ctx)
-            age = templatefilters.age(ctx.date())
-            desc = templatefilters.firstline(ctx.description())
+            age = encodestr(templatefilters.age(ctx.date()))
+            desc = templatefilters.firstline(encodestr(ctx.description()))
             desc = cgi.escape(templatefilters.nonempty(desc))
-            user = cgi.escape(templatefilters.person(ctx.user()))
-            branch = cgi.escape(ctx.branch())
+            user = cgi.escape(templatefilters.person(encodestr(ctx.user())))
+            branch = cgi.escape(encodestr(ctx.branch()))
             try:
                 branchnode = web.repo.branchtip(branch)
             except error.RepoLookupError:
@@ -1156,8 +1156,9 @@
 
             if usetuples:
                 data.append((node, vtx, edges, desc, user, age, branch,
-                             [cgi.escape(x) for x in ctx.tags()],
-                             [cgi.escape(x) for x in ctx.bookmarks()]))
+                             [cgi.escape(encodestr(x)) for x in ctx.tags()],
+                             [cgi.escape(encodestr(x))
+                              for x in ctx.bookmarks()]))
             else:
                 edgedata = [{'col': edge[0], 'nextcol': edge[1],
                              'color': (edge[2] - 1) % 6 + 1,
@@ -1195,8 +1196,9 @@
                 canvaswidth=(cols + 1) * bg_height,
                 truecanvasheight=rows * bg_height,
                 canvasheight=canvasheight, bg_height=bg_height,
-                jsdata=lambda **x: graphdata(True, **x),
-                nodes=lambda **x: graphdata(False, **x),
+                # {jsdata} will be passed to |json, so it must be in utf-8
+                jsdata=lambda **x: graphdata(True, encoding.fromlocal),
+                nodes=lambda **x: graphdata(False, str),
                 node=ctx.hex(), changenav=changenav)
 
 def _getdoc(e):
--- a/mercurial/hook.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/hook.py	Wed Feb 24 15:55:44 2016 -0600
@@ -36,7 +36,7 @@
         d = funcname.rfind('.')
         if d == -1:
             raise error.HookLoadError(
-                _('%s hook is invalid ("%s" not in a module)')
+                _('%s hook is invalid: "%s" not in a module')
                 % (hname, funcname))
         modname = funcname[:d]
         oldpaths = sys.path
@@ -49,13 +49,13 @@
         with demandimport.deactivated():
             try:
                 obj = __import__(modname)
-            except ImportError:
-                e1 = sys.exc_type, sys.exc_value, sys.exc_traceback
+            except (ImportError, SyntaxError):
+                e1 = sys.exc_info()
                 try:
                     # extensions are loaded with hgext_ prefix
                     obj = __import__("hgext_%s" % modname)
-                except ImportError:
-                    e2 = sys.exc_type, sys.exc_value, sys.exc_traceback
+                except (ImportError, SyntaxError):
+                    e2 = sys.exc_info()
                     if ui.tracebackflag:
                         ui.warn(_('exception from first failed import '
                                   'attempt:\n'))
@@ -64,20 +64,26 @@
                         ui.warn(_('exception from second failed import '
                                   'attempt:\n'))
                     ui.traceback(e2)
+
+                    if not ui.tracebackflag:
+                        tracebackhint = _(
+                            'run with --traceback for stack trace')
+                    else:
+                        tracebackhint = None
                     raise error.HookLoadError(
-                        _('%s hook is invalid (import of "%s" failed)') %
-                        (hname, modname))
+                        _('%s hook is invalid: import of "%s" failed') %
+                        (hname, modname), hint=tracebackhint)
         sys.path = oldpaths
         try:
             for p in funcname.split('.')[1:]:
                 obj = getattr(obj, p)
         except AttributeError:
             raise error.HookLoadError(
-                _('%s hook is invalid ("%s" is not defined)')
+                _('%s hook is invalid: "%s" is not defined')
                 % (hname, funcname))
         if not callable(obj):
             raise error.HookLoadError(
-                _('%s hook is invalid ("%s" is not callable)')
+                _('%s hook is invalid: "%s" is not callable')
                 % (hname, funcname))
 
     ui.note(_("calling hook %s: %s\n") % (hname, funcname))
@@ -100,6 +106,8 @@
                            '%s\n') % (hname, exc))
         if throw:
             raise
+        if not ui.tracebackflag:
+            ui.warn(_('(run with --traceback for stack trace)\n'))
         ui.traceback()
         return True, True
     finally:
--- a/mercurial/localrepo.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/localrepo.py	Wed Feb 24 15:55:44 2016 -0600
@@ -242,9 +242,6 @@
     # only functions defined in module of enabled extensions are invoked
     featuresetupfuncs = set()
 
-    def _baserequirements(self, create):
-        return ['revlogv1']
-
     def __init__(self, baseui, path=None, create=False):
         self.requirements = set()
         self.wvfs = scmutil.vfs(path, expandpath=True, realpath=True)
@@ -282,29 +279,21 @@
 
         if not self.vfs.isdir():
             if create:
+                self.requirements = newreporequirements(self)
+
                 if not self.wvfs.exists():
                     self.wvfs.makedirs()
                 self.vfs.makedir(notindexed=True)
-                self.requirements.update(self._baserequirements(create))
-                if self.ui.configbool('format', 'usestore', True):
+
+                if 'store' in self.requirements:
                     self.vfs.mkdir("store")
-                    self.requirements.add("store")
-                    if self.ui.configbool('format', 'usefncache', True):
-                        self.requirements.add("fncache")
-                        if self.ui.configbool('format', 'dotencode', True):
-                            self.requirements.add('dotencode')
+
                     # create an invalid changelog
                     self.vfs.append(
                         "00changelog.i",
                         '\0\0\0\2' # represents revlogv2
                         ' dummy changelog to prevent using the old repo layout'
                     )
-                if scmutil.gdinitconfig(self.ui):
-                    self.requirements.add("generaldelta")
-                if self.ui.configbool('experimental', 'treemanifest', False):
-                    self.requirements.add("treemanifest")
-                if self.ui.configbool('experimental', 'manifestv2', False):
-                    self.requirements.add("manifestv2")
             else:
                 raise error.RepoError(_("repository %s not found") % path)
         elif create:
@@ -985,7 +974,7 @@
             data = self.wvfs.read(filename)
         return self._filter(self._encodefilterpats, filename, data)
 
-    def wwrite(self, filename, data, flags):
+    def wwrite(self, filename, data, flags, backgroundclose=False):
         """write ``data`` into ``filename`` in the working directory
 
         This returns length of written (maybe decoded) data.
@@ -994,7 +983,7 @@
         if 'l' in flags:
             self.wvfs.symlink(data, filename)
         else:
-            self.wvfs.write(filename, data)
+            self.wvfs.write(filename, data, backgroundclose=backgroundclose)
             if 'x' in flags:
                 self.wvfs.setflags(filename, False, True)
         return len(data)
@@ -1962,3 +1951,27 @@
 
 def islocal(path):
     return True
+
+def newreporequirements(repo):
+    """Determine the set of requirements for a new local repository.
+
+    Extensions can wrap this function to specify custom requirements for
+    new repositories.
+    """
+    ui = repo.ui
+    requirements = set(['revlogv1'])
+    if ui.configbool('format', 'usestore', True):
+        requirements.add('store')
+        if ui.configbool('format', 'usefncache', True):
+            requirements.add('fncache')
+            if ui.configbool('format', 'dotencode', True):
+                requirements.add('dotencode')
+
+    if scmutil.gdinitconfig(ui):
+        requirements.add('generaldelta')
+    if ui.configbool('experimental', 'treemanifest', False):
+        requirements.add('treemanifest')
+    if ui.configbool('experimental', 'manifestv2', False):
+        requirements.add('manifestv2')
+
+    return requirements
--- a/mercurial/lock.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/lock.py	Wed Feb 24 15:55:44 2016 -0600
@@ -9,7 +9,6 @@
 
 import contextlib
 import errno
-import os
 import socket
 import time
 import warnings
@@ -77,8 +76,8 @@
         self.release()
 
     def _getpid(self):
-        # wrapper around os.getpid() to make testing easier
-        return os.getpid()
+        # wrapper around util.getpid() to make testing easier
+        return util.getpid()
 
     def lock(self):
         timeout = self.timeout
--- a/mercurial/manifest.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/manifest.py	Wed Feb 24 15:55:44 2016 -0600
@@ -325,6 +325,9 @@
     def iteritems(self):
         return (x[:2] for x in self._lm.iterentries())
 
+    def iterentries(self):
+        return self._lm.iterentries()
+
     def text(self, usemanifestv2=False):
         if usemanifestv2:
             return _textv2(self._lm.iterentries())
@@ -517,6 +520,15 @@
         self._node = node
         self._dirty = False
 
+    def iterentries(self):
+        self._load()
+        for p, n in sorted(self._dirs.items() + self._files.items()):
+            if p in self._files:
+                yield self._subpath(p), n, self._flags.get(p, '')
+            else:
+                for x in n.iterentries():
+                    yield x
+
     def iteritems(self):
         self._load()
         for p, n in sorted(self._dirs.items() + self._files.items()):
@@ -627,7 +639,6 @@
 
     def setflag(self, f, flags):
         """Set the flags (symlink, executable) for path f."""
-        assert 't' not in flags
         self._load()
         dir, subpath = _splittopdir(f)
         if dir:
@@ -849,9 +860,7 @@
     def text(self, usemanifestv2=False):
         """Get the full data of this manifest as a bytestring."""
         self._load()
-        flags = self.flags
-        return _text(((f, self[f], flags(f)) for f in self.keys()),
-                     usemanifestv2)
+        return _text(self.iterentries(), usemanifestv2)
 
     def dirtext(self, usemanifestv2=False):
         """Get the full data of this directory as a bytestring. Make sure that
@@ -920,7 +929,8 @@
         return manifestdict(data)
 
     def dirlog(self, dir):
-        assert self._treeondisk
+        if dir:
+            assert self._treeondisk
         if dir not in self._dirlogcache:
             self._dirlogcache[dir] = manifest(self.opener, dir,
                                               self._dirlogcache)
@@ -945,6 +955,22 @@
         d = mdiff.patchtext(self.revdiff(self.deltaparent(r), r))
         return self._newmanifest(d)
 
+    def readshallowdelta(self, node):
+        '''For flat manifests, this is the same as readdelta(). For
+        treemanifests, this will read the delta for this revlog's directory,
+        without recursively reading subdirectory manifests. Instead, any
+        subdirectory entry will be reported as it appears in the manifests, i.e.
+        the subdirectory will be reported among files and distinguished only by
+        its 't' flag.'''
+        if not self._treeondisk:
+            return self.readdelta(node)
+        if self._usemanifestv2:
+            raise error.Abort(
+                "readshallowdelta() not implemented for manifestv2")
+        r = self.rev(node)
+        d = mdiff.patchtext(self.revdiff(self.deltaparent(r), r))
+        return manifestdict(d)
+
     def readfast(self, node):
         '''use the faster of readdelta or read
 
--- a/mercurial/match.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/match.py	Wed Feb 24 15:55:44 2016 -0600
@@ -334,13 +334,13 @@
     m.bad = badfn
     return m
 
-class narrowmatcher(match):
+class subdirmatcher(match):
     """Adapt a matcher to work on a subdirectory only.
 
     The paths are remapped to remove/insert the path as needed:
 
     >>> m1 = match('root', '', ['a.txt', 'sub/b.txt'])
-    >>> m2 = narrowmatcher('sub', m1)
+    >>> m2 = subdirmatcher('sub', m1)
     >>> bool(m2('a.txt'))
     False
     >>> bool(m2('b.txt'))
@@ -381,7 +381,16 @@
             self._always = any(f == path for f in matcher._files)
 
         self._anypats = matcher._anypats
+        # Some information is lost in the superclass's constructor, so we
+        # can not accurately create the matching function for the subdirectory
+        # from the inputs. Instead, we override matchfn() and visitdir() to
+        # call the original matcher with the subdirectory path prepended.
         self.matchfn = lambda fn: matcher.matchfn(self._path + "/" + fn)
+        def visitdir(dir):
+            if dir == '.':
+                return matcher.visitdir(self._path)
+            return matcher.visitdir(self._path + "/" + dir)
+        self.visitdir = visitdir
         self._fileroots = set(self._files)
 
     def abs(self, f):
--- a/mercurial/merge.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/merge.py	Wed Feb 24 15:55:44 2016 -0600
@@ -65,6 +65,7 @@
        (experimental)
     m: the external merge driver defined for this merge plus its run state
        (experimental)
+    f: a (filename, dictonary) tuple of optional values for a given file
     X: unsupported mandatory record type (used in tests)
     x: unsupported advisory record type (used in tests)
 
@@ -102,6 +103,7 @@
 
     def reset(self, node=None, other=None):
         self._state = {}
+        self._stateextras = {}
         self._local = None
         self._other = None
         for var in ('localctx', 'otherctx'):
@@ -126,6 +128,7 @@
         of on disk file.
         """
         self._state = {}
+        self._stateextras = {}
         self._local = None
         self._other = None
         for var in ('localctx', 'otherctx'):
@@ -152,6 +155,16 @@
             elif rtype in 'FDC':
                 bits = record.split('\0')
                 self._state[bits[0]] = bits[1:]
+            elif rtype == 'f':
+                filename, rawextras = record.split('\0', 1)
+                extraparts = rawextras.split('\0')
+                extras = {}
+                i = 0
+                while i < len(extraparts):
+                    extras[extraparts[i]] = extraparts[i + 1]
+                    i += 2
+
+                self._stateextras[filename] = extras
             elif not rtype.islower():
                 unsupported.add(rtype)
         self._results = {}
@@ -336,6 +349,10 @@
                 records.append(('C', '\0'.join([d] + v)))
             else:
                 records.append(('F', '\0'.join([d] + v)))
+        for filename, extras in sorted(self._stateextras.iteritems()):
+            rawextras = '\0'.join('%s\0%s' % (k, v) for k, v in
+                                  extras.iteritems())
+            records.append(('f', '%s\0%s' % (filename, rawextras)))
         return records
 
     def _writerecords(self, records):
@@ -388,6 +405,7 @@
                            fca.path(), hex(fca.filenode()),
                            fco.path(), hex(fco.filenode()),
                            fcl.flags()]
+        self._stateextras[fd] = { 'ancestorlinknode' : hex(fca.node()) }
         self._dirty = True
 
     def __contains__(self, dfile):
@@ -423,6 +441,9 @@
             if entry[0] == 'd':
                 yield f
 
+    def extras(self, filename):
+        return self._stateextras.setdefault(filename, {})
+
     def _resolve(self, preresolve, dfile, wctx, labels=None):
         """rerun merge process for file path `dfile`"""
         if self[dfile] in 'rd':
@@ -430,10 +451,16 @@
         stateentry = self._state[dfile]
         state, hash, lfile, afile, anode, ofile, onode, flags = stateentry
         octx = self._repo[self._other]
+        extras = self.extras(dfile)
+        anccommitnode = extras.get('ancestorlinknode')
+        if anccommitnode:
+            actx = self._repo[anccommitnode]
+        else:
+            actx = None
         fcd = self._filectxorabsent(hash, wctx, dfile)
         fco = self._filectxorabsent(onode, octx, ofile)
         # TODO: move this to filectxorabsent
-        fca = self._repo.filectx(afile, fileid=anode)
+        fca = self._repo.filectx(afile, fileid=anode, changeid=actx)
         # "premerge" x flags
         flo = fco.flags()
         fla = fca.flags()
@@ -462,6 +489,7 @@
         if r is None:
             # no real conflict
             del self._state[dfile]
+            self._stateextras.pop(dfile, None)
             self._dirty = True
         elif not r:
             self.mark(dfile, 'r')
@@ -570,29 +598,29 @@
 def _checkunknownfile(repo, wctx, mctx, f, f2=None):
     if f2 is None:
         f2 = f
-    return (repo.wvfs.isfileorlink(f)
-        and repo.wvfs.audit.check(f)
+    return (repo.wvfs.audit.check(f)
+        and repo.wvfs.isfileorlink(f)
         and repo.dirstate.normalize(f) not in repo.dirstate
         and mctx[f2].cmp(wctx[f]))
 
-def _checkunknownfiles(repo, wctx, mctx, force, actions):
+def _checkunknownfiles(repo, wctx, mctx, force, actions, mergeforce):
     """
     Considers any actions that care about the presence of conflicting unknown
     files. For some actions, the result is to abort; for others, it is to
     choose a different action.
     """
     conflicts = set()
+    warnconflicts = set()
+    abortconflicts = set()
+    unknownconfig = _getcheckunknownconfig(repo, 'merge', 'checkunknown')
+    ignoredconfig = _getcheckunknownconfig(repo, 'merge', 'checkignored')
     if not force:
-        abortconflicts = set()
-        warnconflicts = set()
         def collectconflicts(conflicts, config):
             if config == 'abort':
                 abortconflicts.update(conflicts)
             elif config == 'warn':
                 warnconflicts.update(conflicts)
 
-        unknownconfig = _getcheckunknownconfig(repo, 'merge', 'checkunknown')
-        ignoredconfig = _getcheckunknownconfig(repo, 'merge', 'checkignored')
         for f, (m, args, msg) in actions.iteritems():
             if m in ('c', 'dc'):
                 if _checkunknownfile(repo, wctx, mctx, f):
@@ -606,28 +634,54 @@
         unknownconflicts = conflicts - ignoredconflicts
         collectconflicts(ignoredconflicts, ignoredconfig)
         collectconflicts(unknownconflicts, unknownconfig)
-        for f in sorted(abortconflicts):
-            repo.ui.warn(_("%s: untracked file differs\n") % f)
-        if abortconflicts:
-            raise error.Abort(_("untracked files in working directory "
-                                "differ from files in requested revision"))
+    else:
+        for f, (m, args, msg) in actions.iteritems():
+            if m == 'cm':
+                fl2, anc = args
+                different = _checkunknownfile(repo, wctx, mctx, f)
+                if repo.dirstate._ignore(f):
+                    config = ignoredconfig
+                else:
+                    config = unknownconfig
 
-        for f in sorted(warnconflicts):
-            repo.ui.warn(_("%s: replacing untracked file\n") % f)
+                # The behavior when force is True is described by this table:
+                #  config  different  mergeforce  |    action    backup
+                #    *         n          *       |      get        n
+                #    *         y          y       |     merge       -
+                #   abort      y          n       |     merge       -   (1)
+                #   warn       y          n       |  warn + get     y
+                #  ignore      y          n       |      get        y
+                #
+                # (1) this is probably the wrong behavior here -- we should
+                #     probably abort, but some actions like rebases currently
+                #     don't like an abort happening in the middle of
+                #     merge.update.
+                if not different:
+                    actions[f] = ('g', (fl2, False), "remote created")
+                elif mergeforce or config == 'abort':
+                    actions[f] = ('m', (f, f, None, False, anc),
+                                  "remote differs from untracked local")
+                elif config == 'abort':
+                    abortconflicts.add(f)
+                else:
+                    if config == 'warn':
+                        warnconflicts.add(f)
+                    actions[f] = ('g', (fl2, True), "remote created")
+
+    for f in sorted(abortconflicts):
+        repo.ui.warn(_("%s: untracked file differs\n") % f)
+    if abortconflicts:
+        raise error.Abort(_("untracked files in working directory "
+                            "differ from files in requested revision"))
+
+    for f in sorted(warnconflicts):
+        repo.ui.warn(_("%s: replacing untracked file\n") % f)
 
     for f, (m, args, msg) in actions.iteritems():
         backup = f in conflicts
         if m == 'c':
             flags, = args
             actions[f] = ('g', (flags, backup), msg)
-        elif m == 'cm':
-            fl2, anc = args
-            different = _checkunknownfile(repo, wctx, mctx, f)
-            if different:
-                actions[f] = ('m', (f, f, None, False, anc),
-                              "remote differs from untracked local")
-            else:
-                actions[f] = ('g', (fl2, backup), "remote created")
 
 def _forgetremoved(wctx, mctx, branchmerge):
     """
@@ -876,13 +930,14 @@
             del actions[f] # don't get = keep local deleted
 
 def calculateupdates(repo, wctx, mctx, ancestors, branchmerge, force,
-                     acceptremote, followcopies, matcher=None):
+                     acceptremote, followcopies, matcher=None,
+                     mergeforce=False):
     "Calculate the actions needed to merge mctx into wctx using ancestors"
     if len(ancestors) == 1: # default
         actions, diverge, renamedelete = manifestmerge(
             repo, wctx, mctx, ancestors[0], branchmerge, force, matcher,
             acceptremote, followcopies)
-        _checkunknownfiles(repo, wctx, mctx, force, actions)
+        _checkunknownfiles(repo, wctx, mctx, force, actions, mergeforce)
 
     else: # only when merge.preferancestor=* - the default
         repo.ui.note(
@@ -897,7 +952,7 @@
             actions, diverge1, renamedelete1 = manifestmerge(
                 repo, wctx, mctx, ancestor, branchmerge, force, matcher,
                 acceptremote, followcopies)
-            _checkunknownfiles(repo, wctx, mctx, force, actions)
+            _checkunknownfiles(repo, wctx, mctx, force, actions, mergeforce)
 
             # Track the shortest set of warning on the theory that bid
             # merge will correctly incorporate more information
@@ -1003,29 +1058,30 @@
     wwrite = repo.wwrite
     ui = repo.ui
     i = 0
-    for f, (flags, backup), msg in actions:
-        repo.ui.debug(" %s: %s -> g\n" % (f, msg))
-        if verbose:
-            repo.ui.note(_("getting %s\n") % f)
+    with repo.wvfs.backgroundclosing(ui, expectedcount=len(actions)):
+        for f, (flags, backup), msg in actions:
+            repo.ui.debug(" %s: %s -> g\n" % (f, msg))
+            if verbose:
+                repo.ui.note(_("getting %s\n") % f)
 
-        if backup:
-            absf = repo.wjoin(f)
-            orig = scmutil.origpath(ui, repo, absf)
-            try:
-                # TODO Mercurial has always aborted if an untracked directory
-                # is replaced by a tracked file, or generally with
-                # file/directory merges. This needs to be sorted out.
-                if repo.wvfs.isfileorlink(f):
-                    util.rename(absf, orig)
-            except OSError as e:
-                if e.errno != errno.ENOENT:
-                    raise
+            if backup:
+                absf = repo.wjoin(f)
+                orig = scmutil.origpath(ui, repo, absf)
+                try:
+                    # TODO Mercurial has always aborted if an untracked
+                    # directory is replaced by a tracked file, or generally
+                    # with file/directory merges. This needs to be sorted out.
+                    if repo.wvfs.isfileorlink(f):
+                        util.rename(absf, orig)
+                except OSError as e:
+                    if e.errno != errno.ENOENT:
+                        raise
 
-        wwrite(f, fctx(f).data(), flags)
-        if i == 100:
-            yield i, f
-            i = 0
-        i += 1
+            wwrite(f, fctx(f).data(), flags, backgroundclose=True)
+            if i == 100:
+                yield i, f
+                i = 0
+            i += 1
     if i > 0:
         yield i, f
 
@@ -1315,7 +1371,7 @@
             repo.dirstate.normal(f)
 
 def update(repo, node, branchmerge, force, ancestor=None,
-           mergeancestor=False, labels=None, matcher=None):
+           mergeancestor=False, labels=None, matcher=None, mergeforce=False):
     """
     Perform a merge between the working directory and the given node
 
@@ -1328,6 +1384,9 @@
       If false, merging with an ancestor (fast-forward) is only allowed
       between different named branches. This flag is used by rebase extension
       as a temporary fix and should be avoided in general.
+    labels = labels to use for base, local and other
+    mergeforce = whether the merge was run with 'merge --force' (deprecated): if
+      this is True, then 'force' should be True as well.
 
     The table below shows all the behaviors of the update command
     given the -c and -C or no options, whether the working directory
@@ -1463,7 +1522,7 @@
         ### calculate phase
         actionbyfile, diverge, renamedelete = calculateupdates(
             repo, wc, p2, pas, branchmerge, force, mergeancestor,
-            followcopies, matcher=matcher)
+            followcopies, matcher=matcher, mergeforce=mergeforce)
 
         # Prompt and create actions. Most of this is in the resolve phase
         # already, but we can't handle .hgsubstate in filemerge or
--- a/mercurial/obsolete.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/obsolete.py	Wed Feb 24 15:55:44 2016 -0600
@@ -1225,6 +1225,7 @@
         metadata['user'] = repo.ui.username()
     tr = repo.transaction('add-obsolescence-marker')
     try:
+        markerargs = []
         for rel in relations:
             prec = rel[0]
             sucs = rel[1]
@@ -1243,6 +1244,15 @@
                 npare = tuple(p.node() for p in prec.parents())
             if nprec in nsucs:
                 raise error.Abort("changeset %s cannot obsolete itself" % prec)
+
+            # Creating the marker causes the hidden cache to become invalid,
+            # which causes recomputation when we ask for prec.parents() above.
+            # Resulting in n^2 behavior.  So let's prepare all of the args
+            # first, then create the markers.
+            markerargs.append((nprec, nsucs, npare, localmetadata))
+
+        for args in markerargs:
+            nprec, nsucs, npare, localmetadata = args
             repo.obsstore.create(tr, nprec, nsucs, flag, parents=npare,
                                  date=date, metadata=localmetadata)
             repo.filteredrevcache.clear()
--- a/mercurial/pathutil.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/pathutil.py	Wed Feb 24 15:55:44 2016 -0600
@@ -83,16 +83,17 @@
         parts.pop()
         normparts.pop()
         prefixes = []
-        while parts:
-            prefix = os.sep.join(parts)
-            normprefix = os.sep.join(normparts)
+        # It's important that we check the path parts starting from the root.
+        # This means we won't accidentaly traverse a symlink into some other
+        # filesystem (which is potentially expensive to access).
+        for i in range(len(parts)):
+            prefix = os.sep.join(parts[:i + 1])
+            normprefix = os.sep.join(normparts[:i + 1])
             if normprefix in self.auditeddir:
-                break
+                continue
             if self._realfs:
                 self._checkfs(prefix, path)
             prefixes.append(normprefix)
-            parts.pop()
-            normparts.pop()
 
         self.audited.add(normpath)
         # only add prefixes to the cache after checking everything: we don't
--- a/mercurial/phases.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/phases.py	Wed Feb 24 15:55:44 2016 -0600
@@ -435,11 +435,11 @@
             continue
         node = bin(nhex)
         phase = int(phase)
-        if phase == 0:
+        if phase == public:
             if node != nullid:
                 repo.ui.warn(_('ignoring inconsistent public root'
                                ' from remote: %s\n') % nhex)
-        elif phase == 1:
+        elif phase == draft:
             if node in nodemap:
                 draftroots.append(node)
         else:
--- a/mercurial/progress.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/progress.py	Wed Feb 24 15:55:44 2016 -0600
@@ -18,7 +18,7 @@
     return ' '.join(s for s in args if s)
 
 def shouldprint(ui):
-    return not (ui.quiet or ui.plain()) and (
+    return not (ui.quiet or ui.plain('progress')) and (
         ui._isatty(sys.stderr) or ui.configbool('progress', 'assume-tty'))
 
 def fmtremaining(seconds):
--- a/mercurial/repair.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/repair.py	Wed Feb 24 15:55:44 2016 -0600
@@ -273,6 +273,16 @@
 
         ui.progress(_('changeset'), None)
 
+        if 'treemanifest' in repo.requirements: # safe but unnecessary otherwise
+            for dir in util.dirs(seenfiles):
+                i = 'meta/%s/00manifest.i' % dir
+                d = 'meta/%s/00manifest.d' % dir
+
+                if repo.store._exists(i):
+                    newentries.add(i)
+                if repo.store._exists(d):
+                    newentries.add(d)
+
         addcount = len(newentries - oldentries)
         removecount = len(oldentries - newentries)
         for p in sorted(oldentries - newentries):
--- a/mercurial/revset.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/revset.py	Wed Feb 24 15:55:44 2016 -0600
@@ -436,6 +436,9 @@
 def andset(repo, subset, x, y):
     return getset(repo, getset(repo, subset, x), y)
 
+def differenceset(repo, subset, x, y):
+    return getset(repo, subset, x) - getset(repo, subset, y)
+
 def orset(repo, subset, *xs):
     assert xs
     if len(xs) == 1:
@@ -541,8 +544,10 @@
 @predicate('_destmerge')
 def _destmerge(repo, subset, x):
     # experimental revset for merge destination
-    getargs(x, 0, 0, _("_mergedefaultdest takes no arguments"))
-    return subset & baseset([destutil.destmerge(repo)])
+    sourceset = None
+    if x is not None:
+        sourceset = getset(repo, fullreposet(repo), x)
+    return subset & baseset([destutil.destmerge(repo, sourceset=sourceset)])
 
 @predicate('adds(pattern)', safe=True)
 def adds(repo, subset, x):
@@ -1086,13 +1091,14 @@
         matcher = matchmod.match(repo.root, repo.getcwd(), [x],
                                  ctx=repo[None], default='path')
 
+        files = c.manifest().walk(matcher)
+
         s = set()
-        for fname in c:
-            if matcher(fname):
-                fctx = c[fname]
-                s = s.union(set(c.rev() for c in fctx.ancestors(followfirst)))
-                # include the revision responsible for the most recent version
-                s.add(fctx.introrev())
+        for fname in files:
+            fctx = c[fname]
+            s = s.union(set(c.rev() for c in fctx.ancestors(followfirst)))
+            # include the revision responsible for the most recent version
+            s.add(fctx.introrev())
     else:
         s = _revancestors(repo, baseset([c.rev()]), followfirst)
 
@@ -2144,6 +2150,7 @@
     "and": andset,
     "or": orset,
     "not": notset,
+    "difference": differenceset,
     "list": listset,
     "keyvalue": keyvaluepair,
     "func": func,
@@ -2204,6 +2211,9 @@
         if isonly(tb, ta):
             return w, ('func', ('symbol', 'only'), ('list', tb[2], ta[1][2]))
 
+        if tb is not None and tb[0] == 'not':
+            return wa, ('difference', ta, tb[1])
+
         if wa > wb:
             return w, (op, tb, ta)
         return w, (op, ta, tb)
--- a/mercurial/scmutil.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/scmutil.py	Wed Feb 24 15:55:44 2016 -0600
@@ -276,8 +276,8 @@
         with self(path, mode=mode) as fp:
             return fp.readlines()
 
-    def write(self, path, data):
-        with self(path, 'wb') as fp:
+    def write(self, path, data, backgroundclose=False):
+        with self(path, 'wb', backgroundclose=backgroundclose) as fp:
             return fp.write(data)
 
     def writelines(self, path, data, mode='wb', notindexed=False):
@@ -913,7 +913,7 @@
         if opts.get('subrepos') or matchessubrepo(m, subpath):
             sub = wctx.sub(subpath)
             try:
-                submatch = matchmod.narrowmatcher(subpath, m)
+                submatch = matchmod.subdirmatcher(subpath, m)
                 if sub.addremove(submatch, prefix, opts, dry_run, similarity):
                     ret = 1
             except error.LookupError:
--- a/mercurial/simplemerge.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/simplemerge.py	Wed Feb 24 15:55:44 2016 -0600
@@ -92,7 +92,8 @@
                     mid_marker='=======',
                     end_marker='>>>>>>>',
                     base_marker=None,
-                    localorother=None):
+                    localorother=None,
+                    minimize=False):
         """Return merge in cvs-like form.
         """
         self.conflicts = False
@@ -109,6 +110,8 @@
         if name_base and base_marker:
             base_marker = base_marker + ' ' + name_base
         merge_regions = self.merge_regions()
+        if minimize:
+            merge_regions = self.minimize(merge_regions)
         for t in merge_regions:
             what = t[0]
             if what == 'unchanged':
@@ -195,6 +198,9 @@
         'a', start, end
              Non-clashing insertion from a[start:end]
 
+        'conflict', zstart, zend, astart, aend, bstart, bend
+            Conflict between a and b, with z as common ancestor
+
         Method is as follows:
 
         The two sequences align only on regions which match the base
@@ -266,6 +272,45 @@
                 ia = aend
                 ib = bend
 
+    def minimize(self, merge_regions):
+        """Trim conflict regions of lines where A and B sides match.
+
+        Lines where both A and B have made the same changes at the begining
+        or the end of each merge region are eliminated from the conflict
+        region and are instead considered the same.
+        """
+        for region in merge_regions:
+            if region[0] != "conflict":
+                yield region
+                continue
+            issue, z1, z2, a1, a2, b1, b2 = region
+            alen = a2 - a1
+            blen = b2 - b1
+
+            # find matches at the front
+            ii = 0
+            while ii < alen and ii < blen and \
+                  self.a[a1 + ii] == self.b[b1 + ii]:
+                ii += 1
+            startmatches = ii
+
+            # find matches at the end
+            ii = 0
+            while ii < alen and ii < blen and \
+                  self.a[a2 - ii - 1] == self.b[b2 - ii - 1]:
+                ii += 1
+            endmatches = ii
+
+            if startmatches > 0:
+                yield 'same', a1, a1 + startmatches
+
+            yield ('conflict', z1, z2,
+                    a1 + startmatches, a2 - endmatches,
+                    b1 + startmatches, b2 - endmatches)
+
+            if endmatches > 0:
+                yield 'same', a2 - endmatches, a2
+
     def find_sync_regions(self):
         """Return a list of sync regions, where both descendants match the base.
 
@@ -399,7 +444,10 @@
         out = sys.stdout
 
     m3 = Merge3Text(basetext, localtext, othertext)
-    extrakwargs = {"localorother": opts.get("localorother", None)}
+    extrakwargs = {
+            "localorother": opts.get("localorother", None),
+            'minimize': True,
+        }
     if mode == 'union':
         extrakwargs['start_marker'] = None
         extrakwargs['mid_marker'] = None
@@ -407,6 +455,7 @@
     elif name_base is not None:
         extrakwargs['base_marker'] = '|||||||'
         extrakwargs['name_base'] = name_base
+        extrakwargs['minimize'] = False
     for line in m3.merge_lines(name_a=name_a, name_b=name_b, **extrakwargs):
         out.write(line)
 
--- a/mercurial/store.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/store.py	Wed Feb 24 15:55:44 2016 -0600
@@ -290,7 +290,7 @@
         mode = None
     return mode
 
-_data = ('data 00manifest.d 00manifest.i 00changelog.d 00changelog.i'
+_data = ('data meta 00manifest.d 00manifest.i 00changelog.d 00changelog.i'
          ' phaseroots obsstore')
 
 class basicstore(object):
@@ -330,7 +330,7 @@
         return l
 
     def datafiles(self):
-        return self._walk('data', True)
+        return self._walk('data', True) + self._walk('meta', True)
 
     def topfiles(self):
         # yield manifest before changelog
@@ -378,7 +378,7 @@
         self.opener = self.vfs
 
     def datafiles(self):
-        for a, b, size in self._walk('data', True):
+        for a, b, size in super(encodedstore, self).datafiles():
             try:
                 a = decodefilename(a)
             except KeyError:
@@ -460,7 +460,8 @@
         self.encode = encode
 
     def __call__(self, path, mode='r', *args, **kw):
-        if mode not in ('r', 'rb') and path.startswith('data/'):
+        if mode not in ('r', 'rb') and (path.startswith('data/') or
+                                        path.startswith('meta/')):
             self.fncache.add(path)
         return self.vfs(self.encode(path), mode, *args, **kw)
 
@@ -504,7 +505,7 @@
                     raise
 
     def copylist(self):
-        d = ('data dh fncache phaseroots obsstore'
+        d = ('data meta dh fncache phaseroots obsstore'
              ' 00manifest.d 00manifest.i 00changelog.d 00changelog.i')
         return (['requires', '00changelog.i'] +
                 ['store/' + f for f in d.split()])
--- a/mercurial/subrepo.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/subrepo.py	Wed Feb 24 15:55:44 2016 -0600
@@ -774,7 +774,7 @@
         ctx = self._repo[rev]
         for subpath in ctx.substate:
             s = subrepo(ctx, subpath, True)
-            submatch = matchmod.narrowmatcher(subpath, match)
+            submatch = matchmod.subdirmatcher(subpath, match)
             total += s.archive(archiver, prefix + self._path + '/', submatch)
         return total
 
--- a/mercurial/templatefilters.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/templatefilters.py	Wed Feb 24 15:55:44 2016 -0600
@@ -197,15 +197,8 @@
         return {None: 'null', False: 'false', True: 'true'}[obj]
     elif isinstance(obj, int) or isinstance(obj, float):
         return str(obj)
-    elif isinstance(obj, encoding.localstr):
-        u = encoding.fromlocal(obj).decode('utf-8')  # can round-trip
-        return '"%s"' % jsonescape(u)
     elif isinstance(obj, str):
-        # no encoding.fromlocal() because it may abort if obj can't be decoded
-        u = unicode(obj, encoding.encoding, 'replace')
-        return '"%s"' % jsonescape(u)
-    elif isinstance(obj, unicode):
-        return '"%s"' % jsonescape(obj)
+        return '"%s"' % encoding.jsonescape(obj, paranoid=True)
     elif util.safehasattr(obj, 'keys'):
         out = []
         for k, v in sorted(obj.iteritems()):
@@ -222,23 +215,6 @@
     else:
         raise TypeError('cannot encode type %s' % obj.__class__.__name__)
 
-def _uescape(c):
-    if 0x20 <= ord(c) < 0x80:
-        return c
-    else:
-        return '\\u%04x' % ord(c)
-
-_escapes = [
-    ('\\', '\\\\'), ('"', '\\"'), ('\t', '\\t'), ('\n', '\\n'),
-    ('\r', '\\r'), ('\f', '\\f'), ('\b', '\\b'),
-    ('<', '\\u003c'), ('>', '\\u003e'), ('\0', '\\u0000')
-]
-
-def jsonescape(s):
-    for k, v in _escapes:
-        s = s.replace(k, v)
-    return ''.join(_uescape(c) for c in s)
-
 def lower(text):
     """:lower: Any text. Converts the text to lowercase."""
     return encoding.lower(text)
@@ -377,6 +353,10 @@
     """:emailuser: Any text. Returns the user portion of an email address."""
     return util.emailuser(text)
 
+def utf8(text):
+    """:utf8: Any text. Converts from the local character encoding to UTF-8."""
+    return encoding.fromlocal(text)
+
 def xmlescape(text):
     text = (text
             .replace('&', '&amp;')
@@ -402,7 +382,6 @@
     "isodate": isodate,
     "isodatesec": isodatesec,
     "json": json,
-    "jsonescape": jsonescape,
     "lower": lower,
     "nonempty": nonempty,
     "obfuscate": obfuscate,
@@ -423,6 +402,7 @@
     "urlescape": urlescape,
     "user": userfilter,
     "emailuser": emailuser,
+    "utf8": utf8,
     "xmlescape": xmlescape,
 }
 
--- a/mercurial/templatekw.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/templatekw.py	Wed Feb 24 15:55:44 2016 -0600
@@ -490,9 +490,10 @@
     """helper to generate a list of revisions in which a mapped template will
     be evaluated"""
     repo = args['ctx'].repo()
+    revs = [str(r) for r in revs]  # ifcontains() needs a list of str
     f = _showlist(name, revs, **args)
     return _hybrid(f, revs,
-                   lambda x: {name: x, 'ctx': repo[x], 'revcache': {}})
+                   lambda x: {name: x, 'ctx': repo[int(x)], 'revcache': {}})
 
 def showsubrepos(**args):
     """:subrepos: List of strings. Updated subrepositories in the changeset."""
--- a/mercurial/templater.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/templater.py	Wed Feb 24 15:55:44 2016 -0600
@@ -581,14 +581,14 @@
     if len(args) > 1:
         formatargs = list([a[0](context, mapping, a[1]) for a in args[1:]])
         revs = query(revsetmod.formatspec(raw, *formatargs))
-        revs = list([str(r) for r in revs])
+        revs = list(revs)
     else:
         revsetcache = mapping['cache'].setdefault("revsetcache", {})
         if raw in revsetcache:
             revs = revsetcache[raw]
         else:
             revs = query(raw)
-            revs = list([str(r) for r in revs])
+            revs = list(revs)
             revsetcache[raw] = revs
 
     return templatekw.showrevslist("revision", revs, **mapping)
--- a/mercurial/templates/json/map	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/templates/json/map	Wed Feb 24 15:55:44 2016 -0600
@@ -8,26 +8,26 @@
 changelistentry = '\{
   "node": {node|json},
   "date": {date|json},
-  "desc": {desc|json},
+  "desc": {desc|utf8|json},
   "bookmarks": [{join(bookmarks%changelistentryname, ", ")}],
   "tags": [{join(tags%changelistentryname, ", ")}],
-  "user": {author|json}
+  "user": {author|utf8|json}
   }'
-changelistentryname = '{name|json}'
+changelistentryname = '{name|utf8|json}'
 changeset = '\{
   "node": {node|json},
   "date": {date|json},
-  "desc": {desc|json},
+  "desc": {desc|utf8|json},
   "branch": {if(branch, branch%changesetbranch, "default"|json)},
   "bookmarks": [{join(changesetbookmark, ", ")}],
   "tags": [{join(changesettag, ", ")}],
-  "user": {author|json},
+  "user": {author|utf8|json},
   "parents": [{join(parent%changesetparent, ", ")}],
   "phase": {phase|json}
   }'
-changesetbranch = '{name|json}'
-changesetbookmark = '{bookmark|json}'
-changesettag = '{tag|json}'
+changesetbranch = '{name|utf8|json}'
+changesetbookmark = '{bookmark|utf8|json}'
+changesettag = '{tag|utf8|json}'
 changesetparent = '{node|json}'
 manifest = '\{
   "node": {node|json},
@@ -37,7 +37,7 @@
   "bookmarks": [{join(bookmarks%name, ", ")}],
   "tags": [{join(tags%name, ", ")}]
   }'
-name = '{name|json}'
+name = '{name|utf8|json}'
 direntry = '\{
   "abspath": {path|json},
   "basename": {basename|json},
@@ -55,7 +55,7 @@
   "tags": [{join(entriesnotip%tagentry, ", ")}]
   }'
 tagentry = '\{
-  "tag": {tag|json},
+  "tag": {tag|utf8|json},
   "node": {node|json},
   "date": {date|json}
   }'
@@ -64,7 +64,7 @@
   "bookmarks": [{join(entries%bookmarkentry, ", ")}]
   }'
 bookmarkentry = '\{
-  "bookmark": {bookmark|json},
+  "bookmark": {bookmark|utf8|json},
   "node": {node|json},
   "date": {date|json}
   }'
@@ -72,7 +72,7 @@
   "branches": [{join(entries%branchentry, ", ")}]
   }'
 branchentry = '\{
-  "branch": {branch|json},
+  "branch": {branch|utf8|json},
   "node": {node|json},
   "date": {date|json},
   "status": {status|json}
@@ -82,8 +82,8 @@
   "path": {file|json},
   "node": {node|json},
   "date": {date|json},
-  "desc": {desc|json},
-  "author": {author|json},
+  "desc": {desc|utf8|json},
+  "author": {author|utf8|json},
   "parents": [{join(parent%changesetparent, ", ")}],
   "children": [{join(child%changesetparent, ", ")}],
   "diff": [{join(diff%diffblock, ", ")}]
@@ -116,8 +116,8 @@
   "path": {file|json},
   "node": {node|json},
   "date": {date|json},
-  "desc": {desc|json},
-  "author": {author|json},
+  "desc": {desc|utf8|json},
+  "author": {author|utf8|json},
   "parents": [{join(parent%changesetparent, ", ")}],
   "children": [{join(child%changesetparent, ", ")}],
   "leftnode": {leftnode|json},
@@ -137,9 +137,9 @@
 fileannotate = '\{
   "abspath": {file|json},
   "node": {node|json},
-  "author": {author|json},
+  "author": {author|utf8|json},
   "date": {date|json},
-  "desc": {desc|json},
+  "desc": {desc|utf8|json},
   "parents": [{join(parent%changesetparent, ", ")}],
   "children": [{join(child%changesetparent, ", ")}],
   "permissions": {permissions|json},
@@ -147,8 +147,8 @@
   }'
 fileannotation = '\{
   "node": {node|json},
-  "author": {author|json},
-  "desc": {desc|json},
+  "author": {author|utf8|json},
+  "desc": {desc|utf8|json},
   "abspath": {file|json},
   "targetline": {targetline|json},
   "line": {line|json},
@@ -163,12 +163,12 @@
   "othercommands": [{join(othercommands%helptopicentry, ", ")}]
   }'
 helptopicentry = '\{
-  "topic": {topic|json},
-  "summary": {summary|json}
+  "topic": {topic|utf8|json},
+  "summary": {summary|utf8|json}
   }'
 help = '\{
-  "topic": {topic|json},
-  "rawdoc": {doc|json}
+  "topic": {topic|utf8|json},
+  "rawdoc": {doc|utf8|json}
   }'
 filenodelink = ''
 filenolink = ''
--- a/mercurial/ui.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/ui.py	Wed Feb 24 15:55:44 2016 -0600
@@ -42,7 +42,6 @@
 # (see "hg help extensions" for more info)
 #
 # pager =
-# progress =
 # color =""",
 
     'cloned':
@@ -86,7 +85,6 @@
 # (see "hg help extensions" for more info)
 #
 # blackbox =
-# progress =
 # color =
 # pager =""",
 }
--- a/mercurial/util.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/util.py	Wed Feb 24 15:55:44 2016 -0600
@@ -65,6 +65,7 @@
 findexe = platform.findexe
 gethgcmd = platform.gethgcmd
 getuser = platform.getuser
+getpid = os.getpid
 groupmembers = platform.groupmembers
 groupname = platform.groupname
 hidewindow = platform.hidewindow
--- a/mercurial/verify.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/verify.py	Wed Feb 24 15:55:44 2016 -0600
@@ -147,9 +147,9 @@
         mflinkrevs, filelinkrevs = self._verifychangelog()
 
         filenodes = self._verifymanifest(mflinkrevs)
+        del mflinkrevs
 
-        self._crosscheckfiles(mflinkrevs, filelinkrevs, filenodes)
-        del mflinkrevs
+        self._crosscheckfiles(filelinkrevs, filenodes)
 
         totalfiles, filerevisions = self._verifyfiles(filenodes, filelinkrevs)
 
@@ -197,60 +197,111 @@
         ui.progress(_('checking'), None)
         return mflinkrevs, filelinkrevs
 
-    def _verifymanifest(self, mflinkrevs):
+    def _verifymanifest(self, mflinkrevs, dir="", storefiles=None,
+                        progress=None):
         repo = self.repo
         ui = self.ui
-        mf = self.repo.manifest
+        mf = self.repo.manifest.dirlog(dir)
+
+        if not dir:
+            self.ui.status(_("checking manifests\n"))
 
-        ui.status(_("checking manifests\n"))
         filenodes = {}
+        subdirnodes = {}
         seen = {}
+        label = "manifest"
+        if dir:
+            label = dir
+            revlogfiles = mf.files()
+            storefiles.difference_update(revlogfiles)
+            if progress: # should be true since we're in a subdirectory
+                progress()
         if self.refersmf:
             # Do not check manifest if there are only changelog entries with
             # null manifests.
-            self.checklog(mf, "manifest", 0)
+            self.checklog(mf, label, 0)
         total = len(mf)
         for i in mf:
-            ui.progress(_('checking'), i, total=total, unit=_('manifests'))
+            if not dir:
+                ui.progress(_('checking'), i, total=total, unit=_('manifests'))
             n = mf.node(i)
-            lr = self.checkentry(mf, i, n, seen, mflinkrevs.get(n, []),
-                                 "manifest")
+            lr = self.checkentry(mf, i, n, seen, mflinkrevs.get(n, []), label)
             if n in mflinkrevs:
                 del mflinkrevs[n]
+            elif dir:
+                self.err(lr, _("%s not in parent-directory manifest") %
+                         short(n), label)
             else:
-                self.err(lr, _("%s not in changesets") % short(n), "manifest")
+                self.err(lr, _("%s not in changesets") % short(n), label)
 
             try:
-                for f, fn in mf.readdelta(n).iteritems():
+                for f, fn, fl in mf.readshallowdelta(n).iterentries():
                     if not f:
-                        self.err(lr, _("file without name in manifest"))
-                    elif f != "/dev/null": # ignore this in very old repos
-                        if _validpath(repo, f):
-                            filenodes.setdefault(
-                                _normpath(f), {}).setdefault(fn, lr)
+                        self.err(lr, _("entry without name in manifest"))
+                    elif f == "/dev/null":  # ignore this in very old repos
+                        continue
+                    fullpath = dir + _normpath(f)
+                    if not _validpath(repo, fullpath):
+                        continue
+                    if fl == 't':
+                        subdirnodes.setdefault(fullpath + '/', {}).setdefault(
+                            fn, []).append(lr)
+                    else:
+                        filenodes.setdefault(fullpath, {}).setdefault(fn, lr)
             except Exception as inst:
-                self.exc(lr, _("reading manifest delta %s") % short(n), inst)
-        ui.progress(_('checking'), None)
+                self.exc(lr, _("reading delta %s") % short(n), inst, label)
+        if not dir:
+            ui.progress(_('checking'), None)
+
+        if self.havemf:
+            for c, m in sorted([(c, m) for m in mflinkrevs
+                        for c in mflinkrevs[m]]):
+                if dir:
+                    self.err(c, _("parent-directory manifest refers to unknown "
+                                  "revision %s") % short(m), label)
+                else:
+                    self.err(c, _("changeset refers to unknown revision %s") %
+                             short(m), label)
+
+        if not dir and subdirnodes:
+            self.ui.status(_("checking directory manifests\n"))
+            storefiles = set()
+            subdirs = set()
+            revlogv1 = self.revlogv1
+            for f, f2, size in repo.store.datafiles():
+                if not f:
+                    self.err(None, _("cannot decode filename '%s'") % f2)
+                elif (size > 0 or not revlogv1) and f.startswith('meta/'):
+                    storefiles.add(_normpath(f))
+                    subdirs.add(os.path.dirname(f))
+            subdircount = len(subdirs)
+            currentsubdir = [0]
+            def progress():
+                currentsubdir[0] += 1
+                ui.progress(_('checking'), currentsubdir[0], total=subdircount,
+                            unit=_('manifests'))
+
+        for subdir, linkrevs in subdirnodes.iteritems():
+            subdirfilenodes = self._verifymanifest(linkrevs, subdir, storefiles,
+                                                   progress)
+            for f, onefilenodes in subdirfilenodes.iteritems():
+                filenodes.setdefault(f, {}).update(onefilenodes)
+
+        if not dir and subdirnodes:
+            ui.progress(_('checking'), None)
+            for f in sorted(storefiles):
+                self.warn(_("warning: orphan revlog '%s'") % f)
 
         return filenodes
 
-    def _crosscheckfiles(self, mflinkrevs, filelinkrevs, filenodes):
+    def _crosscheckfiles(self, filelinkrevs, filenodes):
         repo = self.repo
         ui = self.ui
         ui.status(_("crosschecking files in changesets and manifests\n"))
 
-        total = len(mflinkrevs) + len(filelinkrevs) + len(filenodes)
+        total = len(filelinkrevs) + len(filenodes)
         count = 0
         if self.havemf:
-            for c, m in sorted([(c, m) for m in mflinkrevs
-                                for c in mflinkrevs[m]]):
-                count += 1
-                if m == nullid:
-                    continue
-                ui.progress(_('crosschecking'), count, total=total)
-                self.err(c, _("changeset refers to unknown manifest %s") %
-                         short(m))
-
             for f in sorted(filelinkrevs):
                 count += 1
                 ui.progress(_('crosschecking'), count, total=total)
@@ -284,7 +335,7 @@
         for f, f2, size in repo.store.datafiles():
             if not f:
                 self.err(None, _("cannot decode filename '%s'") % f2)
-            elif size > 0 or not revlogv1:
+            elif (size > 0 or not revlogv1) and f.startswith('data/'):
                 storefiles.add(_normpath(f))
 
         files = sorted(set(filenodes) | set(filelinkrevs))
@@ -374,11 +425,11 @@
             if f in filenodes:
                 fns = [(lr, n) for n, lr in filenodes[f].iteritems()]
                 for lr, node in sorted(fns):
-                    self.err(lr, _("%s in manifests not found") % short(node),
-                             f)
+                    self.err(lr, _("manifest refers to unknown revision %s") %
+                             short(node), f)
         ui.progress(_('checking'), None)
 
-        for f in storefiles:
+        for f in sorted(storefiles):
             self.warn(_("warning: orphan revlog '%s'") % f)
 
         return len(files), revisions
--- a/mercurial/worker.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/mercurial/worker.py	Wed Feb 24 15:55:44 2016 -0600
@@ -152,14 +152,11 @@
     _exitstatus = _posixexitstatus
 
 def partition(lst, nslices):
-    '''partition a list into N slices of equal size'''
-    n = len(lst)
-    chunk, slop = n / nslices, n % nslices
-    end = 0
-    for i in xrange(nslices):
-        start = end
-        end = start + chunk
-        if slop:
-            end += 1
-            slop -= 1
-        yield lst[start:end]
+    '''partition a list into N slices of roughly equal size
+
+    The current strategy takes every Nth element from the input. If
+    we ever write workers that need to preserve grouping in input
+    we should consider allowing callers to specify a partition strategy.
+    '''
+    for i in range(nslices):
+        yield lst[i::nslices]
--- a/tests/dumbhttp.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/dumbhttp.py	Wed Feb 24 15:55:44 2016 -0600
@@ -38,7 +38,7 @@
     parser.add_option('-f', '--foreground', dest='foreground',
         action='store_true',
         help='do not start the HTTP server in the background')
-    parser.add_option('--daemon-pipefds')
+    parser.add_option('--daemon-postexec')
 
     (options, args) = parser.parse_args()
 
@@ -49,7 +49,7 @@
 
     opts = {'pid_file': options.pid,
             'daemon': not options.foreground,
-            'daemon_pipefds': options.daemon_pipefds}
+            'daemon_postexec': options.daemon_postexec}
     service = simplehttpservice(options.host, options.port)
     cmdutil.service(opts, initfn=service.init, runfn=service.run,
                     runargs=[sys.executable, __file__] + sys.argv[1:])
--- a/tests/f	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/f	Wed Feb 24 15:55:44 2016 -0600
@@ -64,7 +64,7 @@
             if opts.size and not isdir:
                 facts.append('size=%s' % stat.st_size)
             if opts.mode and not islink:
-                facts.append('mode=%o' % (stat.st_mode & 0777))
+                facts.append('mode=%o' % (stat.st_mode & 0o777))
             if opts.links:
                 facts.append('links=%s' % stat.st_nlink)
             if opts.newer:
@@ -106,7 +106,7 @@
                         chunk = chunk[opts.bytes:]
             if opts.hexdump:
                 for i in range(0, len(chunk), 16):
-                    s = chunk[i:i+16]
+                    s = chunk[i:i + 16]
                     outfile.write('%04x: %-47s |%s|\n' %
                                   (i, ' '.join('%02x' % ord(c) for c in s),
                                    re.sub('[^ -~]', '.', s)))
--- a/tests/hghave	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/hghave	Wed Feb 24 15:55:44 2016 -0600
@@ -20,7 +20,7 @@
         check, _ = feature
         try:
             check()
-        except Exception, e:
+        except Exception as e:
             print "feature %s failed:  %s" % (name, e)
             failed += 1
     return failed
@@ -45,7 +45,7 @@
     sys.path.insert(0, path)
     try:
         import hghaveaddon
-    except BaseException, inst:
+    except BaseException as inst:
         sys.stderr.write('failed to import hghaveaddon.py from %r: %s\n'
                          % (path, inst))
         sys.exit(2)
--- a/tests/hghave.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/hghave.py	Wed Feb 24 15:55:44 2016 -0600
@@ -335,21 +335,6 @@
     except ImportError:
         return False
 
-@check("json", "some json module available")
-def has_json():
-    try:
-        import json
-        json.dumps
-        return True
-    except ImportError:
-        try:
-            import simplejson as json
-            json.dumps
-            return True
-        except ImportError:
-            pass
-    return False
-
 @check("outer-repo", "outer repo")
 def has_outer_repo():
     # failing for other reasons than 'no repo' imply that there is a repo
--- a/tests/hypothesishelpers.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/hypothesishelpers.py	Wed Feb 24 15:55:44 2016 -0600
@@ -8,9 +8,16 @@
 import sys
 import traceback
 
-from hypothesis.settings import set_hypothesis_home_dir
+try:
+    # hypothesis 2.x
+    from hypothesis.configuration import set_hypothesis_home_dir
+    from hypothesis import settings
+except ImportError:
+    # hypothesis 1.x
+    from hypothesis.settings import set_hypothesis_home_dir
+    from hypothesis import Settings as settings
 import hypothesis.strategies as st
-from hypothesis import given, Settings
+from hypothesis import given
 
 # hypothesis store data regarding generate example and code
 set_hypothesis_home_dir(os.path.join(
@@ -26,7 +33,8 @@
         # Fixed in version 1.13 (released 2015 october 29th)
         f.__module__ = '__anon__'
         try:
-            given(*args, settings=Settings(max_examples=2000), **kwargs)(f)()
+            with settings(max_examples=2000):
+                given(*args, **kwargs)(f)()
         except Exception:
             traceback.print_exc(file=sys.stdout)
             sys.exit(1)
--- a/tests/mockblackbox.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/mockblackbox.py	Wed Feb 24 15:55:44 2016 -0600
@@ -4,8 +4,11 @@
     return 0, 0
 def getuser():
     return 'bob'
+def getpid():
+    return 5000
 
 # mock the date and user apis so the output is always the same
 def uisetup(ui):
     util.makedate = makedate
     util.getuser = getuser
+    util.getpid = getpid
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tests/pdiff	Wed Feb 24 15:55:44 2016 -0600
@@ -0,0 +1,58 @@
+#!/bin/sh
+
+# Script to get stable diff output on any platform.
+#
+# Output of this script is almost equivalent to GNU diff with "-Nru".
+#
+# Use this script as "hg pdiff" via extdiff extension with preparation
+# below in test scripts:
+#
+#   $ cat >> $HGRCPATH <<EOF
+#   > [extdiff]
+#   > pdiff = sh "$RUNTESTDIR/pdiff"
+#   > EOF
+
+filediff(){
+    # USAGE: filediff file1 file2 [header]
+
+    # compare with /dev/null if file doesn't exist (as "-N" option)
+    file1="$1"
+    if test ! -f "$file1"; then
+        file1=/dev/null
+    fi
+    file2="$2"
+    if test ! -f "$file2"; then
+        file2=/dev/null
+    fi
+
+    if cmp -s "$file1" "$file2"; then
+        # Return immediately, because comparison isn't needed. This
+        # also avoids redundant message of diff like "No differences
+        # encountered" (on Solaris)
+        return
+    fi
+
+    if test -n "$3"; then
+        # show header only in recursive case
+        echo "$3"
+    fi
+
+    # replace "/dev/null" by corresponded filename (as "-N" option)
+    diff -u "$file1" "$file2" |
+    sed "s@^--- /dev/null\(.*\)\$@--- $1\1@" |
+    sed "s@^\+\+\+ /dev/null\(.*\)\$@+++ $2\1@"
+}
+
+if test -d "$1" -o -d "$2"; then
+    # ensure comparison in dictionary order
+    (
+    if test -d "$1"; then (cd "$1" && find . -type f); fi
+    if test -d "$2"; then (cd "$2" && find . -type f); fi
+    ) |
+    sed 's@^\./@@g' | sort | uniq |
+    while read file; do
+        filediff "$1/$file" "$2/$file" "diff -Nru $1/$file $2/$file"
+    done
+else
+    filediff "$1" "$2"
+fi
--- a/tests/run-tests.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/run-tests.py	Wed Feb 24 15:55:44 2016 -0600
@@ -48,6 +48,7 @@
 from distutils import version
 import difflib
 import errno
+import json
 import optparse
 import os
 import shutil
@@ -69,15 +70,6 @@
 import unittest
 
 osenvironb = getattr(os, 'environb', os.environ)
-
-try:
-    import json
-except ImportError:
-    try:
-        import simplejson as json
-    except ImportError:
-        json = None
-
 processlock = threading.Lock()
 
 if sys.version_info > (3, 5, 0):
@@ -257,6 +249,10 @@
         metavar="HG",
         help="test using specified hg script rather than a "
              "temporary installation")
+    parser.add_option("--chg", action="store_true",
+                      help="install and use chg wrapper in place of hg")
+    parser.add_option("--with-chg", metavar="CHG",
+                      help="use specified chg wrapper in place of hg")
     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",
@@ -285,11 +281,12 @@
         options.pure = True
 
     if options.with_hg:
-        options.with_hg = os.path.expanduser(options.with_hg)
+        options.with_hg = os.path.realpath(
+            os.path.expanduser(_bytespath(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':
+        if not os.path.basename(options.with_hg) == b'hg':
             sys.stderr.write('warning: --with-hg should specify an hg script\n')
     if options.local:
         testdir = os.path.dirname(_bytespath(os.path.realpath(sys.argv[0])))
@@ -299,6 +296,20 @@
                          % hgbin)
         options.with_hg = hgbin
 
+    if (options.chg or options.with_chg) and os.name == 'nt':
+        parser.error('chg does not work on %s' % os.name)
+    if options.with_chg:
+        options.chg = False  # no installation to temporary location
+        options.with_chg = os.path.realpath(
+            os.path.expanduser(_bytespath(options.with_chg)))
+        if not (os.path.isfile(options.with_chg) and
+                os.access(options.with_chg, os.X_OK)):
+            parser.error('--with-chg must specify a chg executable')
+    if options.chg and options.with_hg:
+        # chg shares installation location with hg
+        parser.error('--chg does not work when --with-hg is specified '
+                     '(use --with-chg instead)')
+
     options.anycoverage = options.cover or options.annotate or options.htmlcov
     if options.anycoverage:
         try:
@@ -443,7 +454,7 @@
                  debug=False,
                  timeout=defaults['timeout'],
                  startport=defaults['port'], extraconfigopts=None,
-                 py3kwarnings=False, shell=None,
+                 py3kwarnings=False, shell=None, hgcommand=None,
                  slowtimeout=defaults['slowtimeout']):
         """Create a test from parameters.
 
@@ -490,6 +501,7 @@
         self._extraconfigopts = extraconfigopts or []
         self._py3kwarnings = py3kwarnings
         self._shell = _bytespath(shell)
+        self._hgcommand = hgcommand or b'hg'
 
         self._aborted = False
         self._daemonpids = []
@@ -708,6 +720,10 @@
         """Terminate execution of this test."""
         self._aborted = True
 
+    def _portmap(self, i):
+        offset = '' if i == 0 else '%s' % i
+        return (br':%d\b' % (self._startport + i), b':$HGPORT%s' % offset)
+
     def _getreplacements(self):
         """Obtain a mapping of text replacements to apply to test output.
 
@@ -716,31 +732,39 @@
         occur.
         """
         r = [
-            (br':%d\b' % self._startport, b':$HGPORT'),
-            (br':%d\b' % (self._startport + 1), b':$HGPORT1'),
-            (br':%d\b' % (self._startport + 2), b':$HGPORT2'),
+            # This list should be parallel to defineport in _getenv
+            self._portmap(0),
+            self._portmap(1),
+            self._portmap(2),
             (br'(?m)^(saved backup bundle to .*\.hg)( \(glob\))?$',
              br'\1 (glob)'),
             ]
-
-        if os.name == 'nt':
-            r.append(
-                (b''.join(c.isalpha() and b'[%s%s]' % (c.lower(), c.upper()) or
-                    c in b'/\\' and br'[/\\]' or c.isdigit() and c or b'\\' + c
-                    for c in self._testtmp), b'$TESTTMP'))
-        else:
-            r.append((re.escape(self._testtmp), b'$TESTTMP'))
+        r.append((self._escapepath(self._testtmp), b'$TESTTMP'))
 
         return r
 
+    def _escapepath(self, p):
+        if os.name == 'nt':
+            return (
+                (b''.join(c.isalpha() and b'[%s%s]' % (c.lower(), c.upper()) or
+                    c in b'/\\' and br'[/\\]' or c.isdigit() and c or b'\\' + c
+                    for c in p))
+            )
+        else:
+            return re.escape(p)
+
     def _getenv(self):
         """Obtain environment variables to use during test execution."""
+        def defineport(i):
+            offset = '' if i == 0 else '%s' % i
+            env["HGPORT%s" % offset] = '%s' % (self._startport + i)
         env = os.environ.copy()
         env['TESTTMP'] = self._testtmp
         env['HOME'] = self._testtmp
-        env["HGPORT"] = str(self._startport)
-        env["HGPORT1"] = str(self._startport + 1)
-        env["HGPORT2"] = str(self._startport + 2)
+        # This number should match portneeded in _getport
+        for port in xrange(3):
+            # This list should be parallel to _portmap in _getreplacements
+            defineport(port)
         env["HGRCPATH"] = os.path.join(self._threadtmp, b'.hgrc')
         env["DAEMON_PIDS"] = os.path.join(self._threadtmp, b'daemon.pids')
         env["HGEDITOR"] = ('"' + sys.executable + '"'
@@ -981,6 +1005,8 @@
 
         if self._debug:
             script.append(b'set -x\n')
+        if self._hgcommand != b'hg':
+            script.append(b'alias hg="%s"\n' % self._hgcommand)
         if os.getenv('MSYSTEM'):
             script.append(b'alias pwd="pwd -W"\n')
 
@@ -1347,7 +1373,6 @@
             return
 
         accepted = False
-        failed = False
         lines = []
 
         with iolock:
@@ -1388,7 +1413,7 @@
                     else:
                         rename(test.errpath, '%s.out' % test.path)
                     accepted = True
-            if not accepted and not failed:
+            if not accepted:
                 self.faildata[test.name] = b''.join(lines)
 
         return accepted
@@ -1481,7 +1506,7 @@
             def get():
                 num_tests[0] += 1
                 if getattr(test, 'should_reload', False):
-                    return self._loadtest(test.bname, num_tests[0])
+                    return self._loadtest(test.path, num_tests[0])
                 return test
             if not os.path.exists(test.path):
                 result.addSkip(test, "Doesn't exist")
@@ -1714,8 +1739,6 @@
                     xuf.write(doc.toprettyxml(indent='  ', encoding='utf-8'))
 
             if self._runner.options.json:
-                if json is None:
-                    raise ImportError("json module not installed")
                 jsonpath = os.path.join(self._runner._testdir, 'report.json')
                 with open(jsonpath, 'w') as fp:
                     timesd = {}
@@ -1809,7 +1832,9 @@
         self._pythondir = None
         self._coveragefile = None
         self._createdfiles = []
+        self._hgcommand = None
         self._hgpath = None
+        self._chgsockdir = None
         self._portoffset = 0
         self._ports = {}
 
@@ -1871,7 +1896,7 @@
                     for kw, mul in slow.items():
                         if kw in f:
                             val *= mul
-                    if f.endswith('.py'):
+                    if f.endswith(b'.py'):
                         val /= 10.0
                     perf[f] = val / 1000.0
                     return perf[f]
@@ -1915,14 +1940,9 @@
         if self.options.with_hg:
             self._installdir = None
             whg = self.options.with_hg
-            # If --with-hg is not specified, we have bytes already,
-            # but if it was specified in python3 we get a str, so we
-            # have to encode it back into a bytes.
-            if PYTHON3:
-                if not isinstance(whg, bytes):
-                    whg = _bytespath(whg)
             self._bindir = os.path.dirname(os.path.realpath(whg))
             assert isinstance(self._bindir, bytes)
+            self._hgcommand = os.path.basename(whg)
             self._tmpbindir = os.path.join(self._hgtmp, b'install', b'bin')
             os.makedirs(self._tmpbindir)
 
@@ -1934,11 +1954,24 @@
             self._pythondir = self._bindir
         else:
             self._installdir = os.path.join(self._hgtmp, b"install")
-            self._bindir = osenvironb[b"BINDIR"] = \
-                os.path.join(self._installdir, b"bin")
+            self._bindir = os.path.join(self._installdir, b"bin")
+            self._hgcommand = b'hg'
             self._tmpbindir = self._bindir
             self._pythondir = os.path.join(self._installdir, b"lib", b"python")
 
+        # set up crafted chg environment, then replace "hg" command by "chg"
+        chgbindir = self._bindir
+        if self.options.chg or self.options.with_chg:
+            self._chgsockdir = d = os.path.join(self._hgtmp, b'chgsock')
+            os.mkdir(d)
+            osenvironb[b'CHGSOCKNAME'] = os.path.join(d, b"server")
+            osenvironb[b'CHGHG'] = os.path.join(self._bindir, self._hgcommand)
+        if self.options.chg:
+            self._hgcommand = b'chg'
+        elif self.options.with_chg:
+            chgbindir = os.path.dirname(os.path.realpath(self.options.with_chg))
+            self._hgcommand = os.path.basename(self.options.with_chg)
+
         osenvironb[b"BINDIR"] = self._bindir
         osenvironb[b"PYTHON"] = PYTHON
 
@@ -1955,6 +1988,8 @@
             realfile = os.path.realpath(fileb)
             realdir = os.path.abspath(os.path.dirname(realfile))
             path.insert(2, realdir)
+        if chgbindir != self._bindir:
+            path.insert(1, chgbindir)
         if self._testdir != runtestdir:
             path = [self._testdir] + path
         if self._tmpbindir != self._bindir:
@@ -2023,6 +2058,9 @@
                 self._checkhglib("Testing")
             else:
                 self._usecorrectpython()
+            if self.options.chg:
+                assert self._installdir
+                self._installchg()
 
             if self.options.restart:
                 orig = list(tests)
@@ -2116,12 +2154,15 @@
                     startport=self._getport(count),
                     extraconfigopts=self.options.extra_config_opt,
                     py3kwarnings=self.options.py3k_warnings,
-                    shell=self.options.shell)
+                    shell=self.options.shell,
+                    hgcommand=self._hgcommand)
         t.should_reload = True
         return t
 
     def _cleanup(self):
         """Clean up state from this test invocation."""
+        if self._chgsockdir:
+            self._killchgdaemons()
 
         if self.options.keep_tmpdir:
             return
@@ -2321,6 +2362,34 @@
 
         return self._hgpath
 
+    def _installchg(self):
+        """Install chg into the test environment"""
+        vlog('# Performing temporary installation of CHG')
+        assert os.path.dirname(self._bindir) == self._installdir
+        assert self._hgroot, 'must be called after _installhg()'
+        cmd = (b'"%(make)s" clean install PREFIX="%(prefix)s"'
+               % {b'make': 'make',  # TODO: switch by option or environment?
+                  b'prefix': self._installdir})
+        cwd = os.path.join(self._hgroot, b'contrib', b'chg')
+        vlog("# Running", cmd)
+        proc = subprocess.Popen(cmd, shell=True, cwd=cwd,
+                                stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+                                stderr=subprocess.STDOUT)
+        out, _err = proc.communicate()
+        if proc.returncode != 0:
+            if PYTHON3:
+                sys.stdout.buffer.write(out)
+            else:
+                sys.stdout.write(out)
+            sys.exit(1)
+
+    def _killchgdaemons(self):
+        """Kill all background chg command servers spawned by tests"""
+        for f in os.listdir(self._chgsockdir):
+            if not f.endswith(b'.pid'):
+                continue
+            killdaemons(os.path.join(self._chgsockdir, f))
+
     def _outputcoverage(self):
         """Produce code coverage output."""
         from coverage import coverage
--- a/tests/test-add.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-add.t	Wed Feb 24 15:55:44 2016 -0600
@@ -226,7 +226,7 @@
   $ hg diff capsdir1/capsdir
   diff -r * CapsDir1/CapsDir/SubDir/Def.txt (glob)
   --- a/CapsDir1/CapsDir/SubDir/Def.txt	Thu Jan 01 00:00:00 1970 +0000
-  +++ b/CapsDir1/CapsDir/SubDir/Def.txt	* +0000 (glob)
+  +++ b/CapsDir1/CapsDir/SubDir/Def.txt	* (glob)
   @@ -1,1 +1,1 @@
   -xyz
   +def
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tests/test-automv.t	Wed Feb 24 15:55:44 2016 -0600
@@ -0,0 +1,338 @@
+Tests for the automv extension; detect moved files at commit time.
+
+  $ cat >> $HGRCPATH << EOF
+  > [extensions]
+  > automv=
+  > rebase=
+  > EOF
+
+Setup repo
+
+  $ hg init repo
+  $ cd repo
+
+Test automv command for commit
+
+  $ printf 'foo\nbar\nbaz\n' > a.txt
+  $ hg add a.txt
+  $ hg commit -m 'init repo with a'
+
+mv/rm/add
+  $ mv a.txt b.txt
+  $ hg rm a.txt
+  $ hg add b.txt
+  $ hg status -C
+  A b.txt
+  R a.txt
+  $ hg commit -m 'msg'
+  detected move of 1 files
+  $ hg status --change . -C
+  A b.txt
+    a.txt
+  R a.txt
+  $ hg up -r 0
+  1 files updated, 0 files merged, 1 files removed, 0 files unresolved
+
+mv/rm/add/modif
+  $ mv a.txt b.txt
+  $ hg rm a.txt
+  $ hg add b.txt
+  $ printf '\n' >> b.txt
+  $ hg status -C
+  A b.txt
+  R a.txt
+  $ hg commit -m 'msg'
+  detected move of 1 files
+  created new head
+  $ hg status --change . -C
+  A b.txt
+    a.txt
+  R a.txt
+  $ hg up -r 0
+  1 files updated, 0 files merged, 1 files removed, 0 files unresolved
+
+mv/rm/add/modif
+  $ mv a.txt b.txt
+  $ hg rm a.txt
+  $ hg add b.txt
+  $ printf '\nfoo\n' >> b.txt
+  $ hg status -C
+  A b.txt
+  R a.txt
+  $ hg commit -m 'msg'
+  created new head
+  $ hg status --change . -C
+  A b.txt
+  R a.txt
+  $ hg up -r 0
+  1 files updated, 0 files merged, 1 files removed, 0 files unresolved
+
+mv/rm/add/modif/changethreshold
+  $ mv a.txt b.txt
+  $ hg rm a.txt
+  $ hg add b.txt
+  $ printf '\nfoo\n' >> b.txt
+  $ hg status -C
+  A b.txt
+  R a.txt
+  $ hg commit --config automv.similarity='60' -m 'msg'
+  detected move of 1 files
+  created new head
+  $ hg status --change . -C
+  A b.txt
+    a.txt
+  R a.txt
+  $ hg up -r 0
+  1 files updated, 0 files merged, 1 files removed, 0 files unresolved
+
+mv
+  $ mv a.txt b.txt
+  $ hg status -C
+  ! a.txt
+  ? b.txt
+  $ hg commit -m 'msg'
+  nothing changed (1 missing files, see 'hg status')
+  [1]
+  $ hg status -C
+  ! a.txt
+  ? b.txt
+  $ hg revert -aqC
+  $ rm b.txt
+
+mv/rm/add/notincommitfiles
+  $ mv a.txt b.txt
+  $ hg rm a.txt
+  $ hg add b.txt
+  $ echo 'bar' > c.txt
+  $ hg add c.txt
+  $ hg status -C
+  A b.txt
+  A c.txt
+  R a.txt
+  $ hg commit c.txt -m 'msg'
+  created new head
+  $ hg status --change . -C
+  A c.txt
+  $ hg status -C
+  A b.txt
+  R a.txt
+  $ hg up -r 0
+  0 files updated, 0 files merged, 1 files removed, 0 files unresolved
+  $ hg rm a.txt
+  $ echo 'bar' > c.txt
+  $ hg add c.txt
+  $ hg commit -m 'msg'
+  detected move of 1 files
+  created new head
+  $ hg status --change . -C
+  A b.txt
+    a.txt
+  A c.txt
+  R a.txt
+  $ hg up -r 0
+  1 files updated, 0 files merged, 2 files removed, 0 files unresolved
+
+mv/rm/add/--no-automv
+  $ mv a.txt b.txt
+  $ hg rm a.txt
+  $ hg add b.txt
+  $ hg status -C
+  A b.txt
+  R a.txt
+  $ hg commit --no-automv -m 'msg'
+  created new head
+  $ hg status --change . -C
+  A b.txt
+  R a.txt
+  $ hg up -r 0
+  1 files updated, 0 files merged, 1 files removed, 0 files unresolved
+
+Test automv command for commit --amend
+
+mv/rm/add
+  $ echo 'c' > c.txt
+  $ hg add c.txt
+  $ hg commit -m 'revision to amend to'
+  created new head
+  $ mv a.txt b.txt
+  $ hg rm a.txt
+  $ hg add b.txt
+  $ hg status -C
+  A b.txt
+  R a.txt
+  $ hg commit --amend -m 'amended'
+  detected move of 1 files
+  saved backup bundle to $TESTTMP/repo/.hg/strip-backup/*-amend-backup.hg (glob)
+  $ hg status --change . -C
+  A b.txt
+    a.txt
+  A c.txt
+  R a.txt
+  $ hg up -r 0
+  1 files updated, 0 files merged, 2 files removed, 0 files unresolved
+
+mv/rm/add/modif
+  $ echo 'c' > c.txt
+  $ hg add c.txt
+  $ hg commit -m 'revision to amend to'
+  created new head
+  $ mv a.txt b.txt
+  $ hg rm a.txt
+  $ hg add b.txt
+  $ printf '\n' >> b.txt
+  $ hg status -C
+  A b.txt
+  R a.txt
+  $ hg commit --amend -m 'amended'
+  detected move of 1 files
+  saved backup bundle to $TESTTMP/repo/.hg/strip-backup/*-amend-backup.hg (glob)
+  $ hg status --change . -C
+  A b.txt
+    a.txt
+  A c.txt
+  R a.txt
+  $ hg up -r 0
+  1 files updated, 0 files merged, 2 files removed, 0 files unresolved
+
+mv/rm/add/modif
+  $ echo 'c' > c.txt
+  $ hg add c.txt
+  $ hg commit -m 'revision to amend to'
+  created new head
+  $ mv a.txt b.txt
+  $ hg rm a.txt
+  $ hg add b.txt
+  $ printf '\nfoo\n' >> b.txt
+  $ hg status -C
+  A b.txt
+  R a.txt
+  $ hg commit --amend -m 'amended'
+  saved backup bundle to $TESTTMP/repo/.hg/strip-backup/*-amend-backup.hg (glob)
+  $ hg status --change . -C
+  A b.txt
+  A c.txt
+  R a.txt
+  $ hg up -r 0
+  1 files updated, 0 files merged, 2 files removed, 0 files unresolved
+
+mv/rm/add/modif/changethreshold
+  $ echo 'c' > c.txt
+  $ hg add c.txt
+  $ hg commit -m 'revision to amend to'
+  created new head
+  $ mv a.txt b.txt
+  $ hg rm a.txt
+  $ hg add b.txt
+  $ printf '\nfoo\n' >> b.txt
+  $ hg status -C
+  A b.txt
+  R a.txt
+  $ hg commit --amend --config automv.similarity='60' -m 'amended'
+  detected move of 1 files
+  saved backup bundle to $TESTTMP/repo/.hg/strip-backup/*-amend-backup.hg (glob)
+  $ hg status --change . -C
+  A b.txt
+    a.txt
+  A c.txt
+  R a.txt
+  $ hg up -r 0
+  1 files updated, 0 files merged, 2 files removed, 0 files unresolved
+
+mv
+  $ echo 'c' > c.txt
+  $ hg add c.txt
+  $ hg commit -m 'revision to amend to'
+  created new head
+  $ mv a.txt b.txt
+  $ hg status -C
+  ! a.txt
+  ? b.txt
+  $ hg commit --amend -m 'amended'
+  saved backup bundle to $TESTTMP/repo/.hg/strip-backup/*-amend-backup.hg (glob)
+  $ hg status -C
+  ! a.txt
+  ? b.txt
+  $ hg up -Cr 0
+  1 files updated, 0 files merged, 1 files removed, 0 files unresolved
+
+mv/rm/add/notincommitfiles
+  $ echo 'c' > c.txt
+  $ hg add c.txt
+  $ hg commit -m 'revision to amend to'
+  created new head
+  $ mv a.txt b.txt
+  $ hg rm a.txt
+  $ hg add b.txt
+  $ echo 'bar' > d.txt
+  $ hg add d.txt
+  $ hg status -C
+  A b.txt
+  A d.txt
+  R a.txt
+  $ hg commit --amend -m 'amended' d.txt
+  saved backup bundle to $TESTTMP/repo/.hg/strip-backup/*-amend-backup.hg (glob)
+  $ hg status --change . -C
+  A c.txt
+  A d.txt
+  $ hg status -C
+  A b.txt
+  R a.txt
+  $ hg commit --amend -m 'amended'
+  detected move of 1 files
+  saved backup bundle to $TESTTMP/repo/.hg/strip-backup/*-amend-backup.hg (glob)
+  $ hg status --change . -C
+  A b.txt
+    a.txt
+  A c.txt
+  A d.txt
+  R a.txt
+  $ hg up -r 0
+  1 files updated, 0 files merged, 3 files removed, 0 files unresolved
+
+mv/rm/add/--no-automv
+  $ echo 'c' > c.txt
+  $ hg add c.txt
+  $ hg commit -m 'revision to amend to'
+  created new head
+  $ mv a.txt b.txt
+  $ hg rm a.txt
+  $ hg add b.txt
+  $ hg status -C
+  A b.txt
+  R a.txt
+  $ hg commit --amend -m 'amended' --no-automv
+  saved backup bundle to $TESTTMP/repo/.hg/strip-backup/*-amend-backup.hg (glob)
+  $ hg status --change . -C
+  A b.txt
+  A c.txt
+  R a.txt
+  $ hg up -r 0
+  1 files updated, 0 files merged, 2 files removed, 0 files unresolved
+
+mv/rm/commit/add/amend
+  $ echo 'c' > c.txt
+  $ hg add c.txt
+  $ hg commit -m 'revision to amend to'
+  created new head
+  $ mv a.txt b.txt
+  $ hg rm a.txt
+  $ hg status -C
+  R a.txt
+  ? b.txt
+  $ hg commit -m "removed a"
+  $ hg add b.txt
+  $ hg commit --amend -m 'amended'
+  saved backup bundle to $TESTTMP/repo/.hg/strip-backup/*-amend-backup.hg (glob)
+  $ hg status --change . -C
+  A b.txt
+  R a.txt
+
+error conditions
+
+  $ cat >> $HGRCPATH << EOF
+  > [automv]
+  > similarity=110
+  > EOF
+  $ hg commit -m 'revision to amend to'
+  abort: automv.similarity must be between 0 and 100
+  [255]
--- a/tests/test-backout.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-backout.t	Wed Feb 24 15:55:44 2016 -0600
@@ -686,6 +686,7 @@
   * version 2 records
   local: b71750c4b0fdf719734971e3ef90dbeab5919a2d
   other: a30dd8addae3ce71b8667868478542bc417439e6
+  file extras: foo (ancestorlinknode = 91360952243723bd5b1138d5f26bd8c8564cb553)
   file: foo (record type "F", state "u", hash 0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33)
     local path: foo (flags "")
     ancestor path: foo (node f89532f44c247a0e993d63e3a734dd781ab04708)
--- a/tests/test-bad-extension.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-bad-extension.t	Wed Feb 24 15:55:44 2016 -0600
@@ -1,11 +1,19 @@
   $ echo 'raise Exception("bit bucket overflow")' > badext.py
-  $ abspath=`pwd`/badext.py
+  $ abspathexc=`pwd`/badext.py
+
+  $ cat >baddocext.py <<EOF
+  > """
+  > baddocext is bad
+  > """
+  > EOF
+  $ abspathdoc=`pwd`/baddocext.py
 
   $ cat <<EOF >> $HGRCPATH
   > [extensions]
   > gpg =
   > hgext.gpg =
-  > badext = $abspath
+  > badext = $abspathexc
+  > baddocext = $abspathdoc
   > badext2 =
   > EOF
 
@@ -23,6 +31,19 @@
   Traceback (most recent call last):
   ImportError: No module named badext2
 
+names of extensions failed to load can be accessed via extensions.notloaded()
+
+  $ cat <<EOF > showbadexts.py
+  > from mercurial import cmdutil, commands, extensions
+  > cmdtable = {}
+  > command = cmdutil.command(cmdtable)
+  > @command('showbadexts', norepo=True)
+  > def showbadexts(ui, *pats, **opts):
+  >     ui.write('BADEXTS: %s' % ' '.join(sorted(extensions.notloaded())))
+  > EOF
+  $ hg --config extensions.badexts=showbadexts.py showbadexts 2>&1 | grep '^BADEXTS'
+  BADEXTS: badext badext2
+
 show traceback for ImportError of hgext.name if debug is set
 (note that --debug option isn't applied yet when loading extensions)
 
@@ -38,3 +59,12 @@
   *** failed to import extension badext2: No module named badext2
   Traceback (most recent call last):
   ImportError: No module named badext2
+
+confirm that there's no crash when an extension's documentation is bad
+
+  $ hg help --keyword baddocext
+  *** failed to import extension badext from $TESTTMP/badext.py: bit bucket overflow
+  *** failed to import extension badext2: No module named badext2
+  Topics:
+  
+   extensions Using Additional Features
--- a/tests/test-bisect2.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-bisect2.t	Wed Feb 24 15:55:44 2016 -0600
@@ -244,6 +244,7 @@
 
   $ hg up -C
   0 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  3 other heads for branch "default"
 
 complex bisect test 1  # first bad rev is 9
 
--- a/tests/test-blackbox.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-blackbox.t	Wed Feb 24 15:55:44 2016 -0600
@@ -15,6 +15,7 @@
   $ hg blackbox
   1970/01/01 00:00:00 bob (*)> add a (glob)
   1970/01/01 00:00:00 bob (*)> add a exited 0 after * seconds (glob)
+  1970/01/01 00:00:00 bob (*)> blackbox (glob)
 
 incoming change tracking
 
@@ -43,22 +44,23 @@
   adding file changes
   added 1 changesets with 1 changes to 1 files
   (run 'hg update' to get a working copy)
-  $ hg blackbox -l 5
+  $ hg blackbox -l 6
   1970/01/01 00:00:00 bob (*)> pull (glob)
-  1970/01/01 00:00:00 bob (*)> updated served branch cache in ?.???? seconds (glob)
+  1970/01/01 00:00:00 bob (*)> updated served branch cache in * seconds (glob)
   1970/01/01 00:00:00 bob (*)> wrote served branch cache with 1 labels and 2 nodes (glob)
   1970/01/01 00:00:00 bob (*)> 1 incoming changes - new heads: d02f48003e62 (glob)
   1970/01/01 00:00:00 bob (*)> pull exited 0 after * seconds (glob)
+  1970/01/01 00:00:00 bob (*)> blackbox -l 6 (glob)
 
 we must not cause a failure if we cannot write to the log
 
   $ hg rollback
   repository tip rolled back to revision 1 (undo pull)
 
-#if unix-permissions no-root
-  $ chmod 000 .hg/blackbox.log
+  $ mv .hg/blackbox.log .hg/blackbox.log-
+  $ mkdir .hg/blackbox.log
   $ hg --debug incoming
-  warning: cannot write to blackbox.log: Permission denied
+  warning: cannot write to blackbox.log: * (glob)
   comparing with $TESTTMP/blackboxtest (glob)
   query 1; heads
   searching for changes
@@ -77,7 +79,6 @@
   c
   
   
-#endif
   $ hg pull
   pulling from $TESTTMP/blackboxtest (glob)
   searching for changes
@@ -87,14 +88,14 @@
   added 1 changesets with 1 changes to 1 files
   (run 'hg update' to get a working copy)
 
-a failure reading from the log is fine
-#if unix-permissions no-root
+a failure reading from the log is fatal
+
   $ hg blackbox -l 3
-  abort: Permission denied: $TESTTMP/blackboxtest2/.hg/blackbox.log
+  abort: *$TESTTMP/blackboxtest2/.hg/blackbox.log* (glob)
   [255]
 
-  $ chmod 600 .hg/blackbox.log
-#endif
+  $ rmdir .hg/blackbox.log
+  $ mv .hg/blackbox.log- .hg/blackbox.log
 
 backup bundles get logged
 
@@ -105,12 +106,13 @@
   $ hg strip tip
   0 files updated, 0 files merged, 1 files removed, 0 files unresolved
   saved backup bundle to $TESTTMP/blackboxtest2/.hg/strip-backup/*-backup.hg (glob)
-  $ hg blackbox -l 5
+  $ hg blackbox -l 6
   1970/01/01 00:00:00 bob (*)> strip tip (glob)
-  1970/01/01 00:00:00 bob (*)> saved backup bundle to $TESTTMP/blackboxtest2/.hg/strip-backup/*-backup.hg (glob)
-  1970/01/01 00:00:00 bob (*)> updated base branch cache in ?.???? seconds (glob)
+  1970/01/01 00:00:00 bob (*)> saved backup bundle to $TESTTMP/blackboxtest2/.hg/strip-backup/73f6ee326b27-7612e004-backup.hg (glob)
+  1970/01/01 00:00:00 bob (*)> updated base branch cache in * seconds (glob)
   1970/01/01 00:00:00 bob (*)> wrote base branch cache with 1 labels and 2 nodes (glob)
   1970/01/01 00:00:00 bob (*)> strip tip exited 0 after * seconds (glob)
+  1970/01/01 00:00:00 bob (*)> blackbox -l 6 (glob)
 
 extension and python hooks - use the eol extension for a pythonhook
 
@@ -121,12 +123,14 @@
   $ hg update
   hooked
   1 files updated, 0 files merged, 0 files removed, 0 files unresolved
-  $ hg blackbox -l 5
+  1 other heads for branch "default"
+  $ hg blackbox -l 6
   1970/01/01 00:00:00 bob (*)> update (glob)
   1970/01/01 00:00:00 bob (*)> writing .hg/cache/tags2-visible with 0 tags (glob)
   1970/01/01 00:00:00 bob (*)> pythonhook-preupdate: hgext.eol.preupdate finished in * seconds (glob)
   1970/01/01 00:00:00 bob (*)> exthook-update: echo hooked finished in * seconds (glob)
   1970/01/01 00:00:00 bob (*)> update exited 0 after * seconds (glob)
+  1970/01/01 00:00:00 bob (*)> blackbox -l 6 (glob)
 
 log rotation
 
@@ -142,6 +146,41 @@
   .hg/blackbox.log
   .hg/blackbox.log.1
   .hg/blackbox.log.2
+  $ cd ..
+
+  $ hg init blackboxtest3
+  $ cd blackboxtest3
+  $ hg blackbox
+  1970/01/01 00:00:00 bob (*)> blackbox (glob)
+  $ mv .hg/blackbox.log .hg/blackbox.log-
+  $ mkdir .hg/blackbox.log
+  $ sed -e 's/\(.*test1.*\)/#\1/; s#\(.*commit2.*\)#os.rmdir(".hg/blackbox.log")\nos.rename(".hg/blackbox.log-", ".hg/blackbox.log")\n\1#' $TESTDIR/test-dispatch.py > ../test-dispatch.py
+  $ python ../test-dispatch.py
+  running: add foo
+  result: 0
+  running: commit -m commit1 -d 2000-01-01 foo
+  result: None
+  running: commit -m commit2 -d 2000-01-02 foo
+  result: None
+  running: log -r 0
+  changeset:   0:0e4634943879
+  user:        test
+  date:        Sat Jan 01 00:00:00 2000 +0000
+  summary:     commit1
+  
+  result: None
+  running: log -r tip
+  changeset:   1:45589e459b2e
+  tag:         tip
+  user:        test
+  date:        Sun Jan 02 00:00:00 2000 +0000
+  summary:     commit2
+  
+  result: None
+  $ hg blackbox
+  1970/01/01 00:00:00 bob (*)> blackbox (glob)
+  1970/01/01 00:00:00 bob (*)> blackbox exited 0 after * seconds (glob)
+  1970/01/01 00:00:00 bob (*)> blackbox (glob)
 
 cleanup
   $ cd ..
--- a/tests/test-bookmarks-pushpull.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-bookmarks-pushpull.t	Wed Feb 24 15:55:44 2016 -0600
@@ -103,6 +103,29 @@
   deleting remote bookmark W
   [1]
 
+export the active bookmark
+
+  $ hg bookmark V
+  $ hg push -B . ../a
+  pushing to ../a
+  searching for changes
+  no changes found
+  exporting bookmark V
+  [1]
+
+delete the bookmark
+
+  $ hg book -d V
+  $ hg push -B V ../a
+  pushing to ../a
+  searching for changes
+  no changes found
+  deleting remote bookmark V
+  [1]
+  $ hg up foobar
+  0 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  (activating bookmark foobar)
+
 push/pull name that doesn't exist
 
   $ hg push -B badname ../a
@@ -680,12 +703,12 @@
 
 pushing an existing but divergent bookmark with -B still requires -f
 
-  $ hg clone -q . r
+  $ hg clone -q . ../r
   $ hg up -q X
   $ echo 1 > f2
   $ hg ci -qAml
 
-  $ cd r
+  $ cd ../r
   $ hg up -q X
   $ echo 2 > f2
   $ hg ci -qAmr
@@ -696,7 +719,7 @@
   abort: push creates new remote head 54694f811df9 with bookmark 'X'!
   (pull and merge or see "hg help push" for details about pushing new heads)
   [255]
-  $ cd ..
+  $ cd ../addmarks
 
 Check summary output for incoming/outgoing bookmarks
 
--- a/tests/test-bookmarks.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-bookmarks.t	Wed Feb 24 15:55:44 2016 -0600
@@ -573,6 +573,7 @@
   $ hg bookmark -r3 Y
   moving bookmark 'Y' forward from db815d6d32e6
   $ cp -r  ../cloned-bookmarks-update ../cloned-bookmarks-manual-update
+  $ cp -r  ../cloned-bookmarks-update ../cloned-bookmarks-manual-update-with-divergence
 
 (manual version)
 
@@ -617,6 +618,34 @@
   updating to active bookmark Y
   1 files updated, 0 files merged, 0 files removed, 0 files unresolved
 
+We warn about divergent during bare update to the active bookmark
+
+  $ hg -R ../cloned-bookmarks-manual-update-with-divergence update Y
+  0 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  (activating bookmark Y)
+  $ hg -R ../cloned-bookmarks-manual-update-with-divergence bookmarks -r X2 Y@1
+  $ hg -R ../cloned-bookmarks-manual-update-with-divergence bookmarks
+     X2                        1:925d80f479bb
+   * Y                         2:db815d6d32e6
+     Y@1                       1:925d80f479bb
+     Z                         2:db815d6d32e6
+     x  y                      2:db815d6d32e6
+  $ hg -R ../cloned-bookmarks-manual-update-with-divergence pull
+  pulling from $TESTTMP
+  searching for changes
+  adding changesets
+  adding manifests
+  adding file changes
+  added 2 changesets with 2 changes to 2 files (+1 heads)
+  updating bookmark Y
+  updating bookmark Z
+  (run 'hg heads' to see heads, 'hg merge' to merge)
+  $ hg -R ../cloned-bookmarks-manual-update-with-divergence update
+  updating to active bookmark Y
+  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  (activating bookmark Y)
+  1 other divergent bookmarks for "Y"
+
 test wrongly formated bookmark
 
   $ echo '' >> .hg/bookmarks
@@ -706,34 +735,12 @@
      date:        Thu Jan 01 00:00:00 1970 +0000
      summary:     0
   
-test non-linear update not clearing active bookmark
-
-  $ hg up 1
-  1 files updated, 0 files merged, 2 files removed, 0 files unresolved
-  (leaving bookmark four)
-  $ hg book drop
-  $ hg up -C
-  1 files updated, 0 files merged, 1 files removed, 0 files unresolved
-  (leaving bookmark drop)
-  $ hg sum
-  parent: 2:db815d6d32e6 
-   2
-  branch: default
-  bookmarks: should-end-on-two
-  commit: 2 unknown (clean)
-  update: 1 new changesets, 2 branch heads (merge)
-  phases: 4 draft
-  $ hg book
-     drop                      1:925d80f479bb
-     four                      3:9ba5f110a0b3
-     should-end-on-two         2:db815d6d32e6
-  $ hg book -d drop
-  $ hg up four
-  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
-  (activating bookmark four)
 
 no-op update doesn't deactive bookmarks
 
+  $ hg up four
+  0 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  (activating bookmark four)
   $ hg up
   0 files updated, 0 files merged, 0 files removed, 0 files unresolved
   $ hg sum
--- a/tests/test-branches.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-branches.t	Wed Feb 24 15:55:44 2016 -0600
@@ -544,15 +544,15 @@
   0060: e3 d4 9c 05 80 00 00 02 e2 3b 55 05 00 00 00 02 |.........;U.....|
   0070: f8 94 c2 56 80 00 00 03                         |...V....|
 
-#if unix-permissions no-root
 no errors when revbranchcache is not writable
 
   $ echo >> .hg/cache/rbc-revs-v1
-  $ chmod a-w .hg/cache/rbc-revs-v1
+  $ mv .hg/cache/rbc-revs-v1 .hg/cache/rbc-revs-v1_
+  $ mkdir .hg/cache/rbc-revs-v1
   $ rm -f .hg/cache/branch* && hg head a -T '{rev}\n'
   5
-  $ chmod a+w .hg/cache/rbc-revs-v1
-#endif
+  $ rmdir .hg/cache/rbc-revs-v1
+  $ mv .hg/cache/rbc-revs-v1_ .hg/cache/rbc-revs-v1
 
 recovery from invalid cache revs file with trailing data
   $ echo >> .hg/cache/rbc-revs-v1
--- a/tests/test-check-config.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-check-config.t	Wed Feb 24 15:55:44 2016 -0600
@@ -5,4 +5,4 @@
 New errors are not allowed. Warnings are strongly discouraged.
 
   $ hg files "set:(**.py or **.txt) - tests/**" | sed 's|\\|/|g' |
-  >   xargs python contrib/check-config.py
+  >   python contrib/check-config.py
--- a/tests/test-check-py3-compat.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-check-py3-compat.t	Wed Feb 24 15:55:44 2016 -0600
@@ -32,13 +32,6 @@
   doc/gendoc.py not using absolute_import
   doc/hgmanpage.py not using absolute_import
   hgext/__init__.py not using absolute_import
-  hgext/acl.py not using absolute_import
-  hgext/blackbox.py not using absolute_import
-  hgext/bugzilla.py not using absolute_import
-  hgext/censor.py not using absolute_import
-  hgext/children.py not using absolute_import
-  hgext/churn.py not using absolute_import
-  hgext/clonebundles.py not using absolute_import
   hgext/color.py not using absolute_import
   hgext/convert/__init__.py not using absolute_import
   hgext/convert/bzr.py not using absolute_import
--- a/tests/test-clone.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-clone.t	Wed Feb 24 15:55:44 2016 -0600
@@ -774,11 +774,11 @@
   adding manifests
   adding file changes
   added 3 changesets with 3 changes to 1 files
-  updating working directory
-  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
   searching for changes
   no changes found
   adding remote bookmark bookA
+  updating working directory
+  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
 
 The shared repo should have been created
 
@@ -804,8 +804,6 @@
 
   $ hg --config share.pool=share clone source1b share-dest1b
   (sharing from existing pooled repository b5f04eac9d8f7a6a9fcb070243cccea7dc5ea0c1)
-  updating working directory
-  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
   searching for changes
   adding changesets
   adding manifests
@@ -813,6 +811,8 @@
   added 4 changesets with 4 changes to 1 files (+4 heads)
   adding remote bookmark head1
   adding remote bookmark head2
+  updating working directory
+  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
 
   $ ls share
   b5f04eac9d8f7a6a9fcb070243cccea7dc5ea0c1
@@ -831,6 +831,17 @@
   $ hg -R share-dest1b config paths.default
   $TESTTMP/source1a (glob)
 
+Checked out revision should be head of default branch
+
+  $ hg -R share-dest1b log -r .
+  changeset:   4:99f71071f117
+  bookmark:    head2
+  parent:      0:b5f04eac9d8f
+  user:        test
+  date:        Thu Jan 01 00:00:00 1970 +0000
+  summary:     head2
+  
+
 Clone from unrelated repo should result in new share
 
   $ hg --config share.pool=share clone source2 share-dest2
@@ -840,10 +851,10 @@
   adding manifests
   adding file changes
   added 2 changesets with 2 changes to 1 files
+  searching for changes
+  no changes found
   updating working directory
   1 files updated, 0 files merged, 0 files removed, 0 files unresolved
-  searching for changes
-  no changes found
 
   $ ls share
   22aeff664783fd44c6d9b435618173c118c3448e
@@ -858,11 +869,11 @@
   adding manifests
   adding file changes
   added 3 changesets with 3 changes to 1 files
-  updating working directory
-  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
   searching for changes
   no changes found
   adding remote bookmark bookA
+  updating working directory
+  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
 
   $ ls shareremote
   195bb1fcdb595c14a6c13e0269129ed78f6debde
@@ -874,12 +885,12 @@
   adding manifests
   adding file changes
   added 6 changesets with 6 changes to 1 files (+4 heads)
-  updating working directory
-  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
   searching for changes
   no changes found
   adding remote bookmark head1
   adding remote bookmark head2
+  updating working directory
+  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
 
   $ ls shareremote
   195bb1fcdb595c14a6c13e0269129ed78f6debde
@@ -893,10 +904,10 @@
   adding manifests
   adding file changes
   added 2 changesets with 2 changes to 1 files
+  no changes found
+  adding remote bookmark head1
   updating working directory
   1 files updated, 0 files merged, 0 files removed, 0 files unresolved
-  no changes found
-  adding remote bookmark head1
 
   $ hg -R share-1arev log -G
   @  changeset:   1:4a8dc1ab4c13
@@ -916,8 +927,6 @@
 
   $ hg --config share.pool=sharerevs clone -r 99f71071f117 source1b share-1brev
   (sharing from existing pooled repository b5f04eac9d8f7a6a9fcb070243cccea7dc5ea0c1)
-  updating working directory
-  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
   searching for changes
   adding changesets
   adding manifests
@@ -925,9 +934,11 @@
   added 1 changesets with 1 changes to 1 files (+1 heads)
   adding remote bookmark head1
   adding remote bookmark head2
+  updating working directory
+  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
 
   $ hg -R share-1brev log -G
-  o  changeset:   2:99f71071f117
+  @  changeset:   2:99f71071f117
   |  bookmark:    head2
   |  tag:         tip
   |  parent:      0:b5f04eac9d8f
@@ -935,7 +946,7 @@
   |  date:        Thu Jan 01 00:00:00 1970 +0000
   |  summary:     head2
   |
-  | @  changeset:   1:4a8dc1ab4c13
+  | o  changeset:   1:4a8dc1ab4c13
   |/   bookmark:    head1
   |    user:        test
   |    date:        Thu Jan 01 00:00:00 1970 +0000
@@ -955,9 +966,9 @@
   adding manifests
   adding file changes
   added 2 changesets with 2 changes to 1 files
+  no changes found
   updating working directory
   1 files updated, 0 files merged, 0 files removed, 0 files unresolved
-  no changes found
 
   $ hg -R share-1bbranch1 log -G
   o  changeset:   1:5f92a6c1a1b1
@@ -975,13 +986,13 @@
 
   $ hg --config share.pool=sharebranch clone -b branch2 source1b share-1bbranch2
   (sharing from existing pooled repository b5f04eac9d8f7a6a9fcb070243cccea7dc5ea0c1)
-  updating working directory
-  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
   searching for changes
   adding changesets
   adding manifests
   adding file changes
   added 1 changesets with 1 changes to 1 files (+1 heads)
+  updating working directory
+  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
 
   $ hg -R share-1bbranch2 log -G
   o  changeset:   2:6bacf4683960
--- a/tests/test-command-template.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-command-template.t	Wed Feb 24 15:55:44 2016 -0600
@@ -1018,7 +1018,7 @@
   $ hg log --style ./t
   abort: template file ./q: Permission denied
   [255]
-  $ rm q
+  $ rm -f q
 #endif
 
 Include works:
@@ -3310,6 +3310,13 @@
   0 a
   p 
 
+a revset item must be evaluated as an integer revision, not an offset from tip
+
+  $ hg log -l 1 -T '{revset("null") % "{rev}:{node|short}"}\n'
+  -1:000000000000
+  $ hg log -l 1 -T '{revset("%s", "null") % "{rev}:{node|short}"}\n'
+  -1:000000000000
+
 Test active bookmark templating
 
   $ hg book foo
@@ -3535,11 +3542,17 @@
   hg: parse error: invalid \x escape
   [255]
 
+json filter should escape HTML tags so that the output can be embedded in hgweb:
+
+  $ hg log -T "{'<foo@example.org>'|json}\n" -R a -l1
+  "\u003cfoo@example.org\u003e"
+
 Set up repository for non-ascii encoding tests:
 
   $ hg init nonascii
   $ cd nonascii
   $ python <<EOF
+  > open('latin1', 'w').write('\xe9')
   > open('utf-8', 'w').write('\xc3\xa9')
   > EOF
   $ HGENCODING=utf-8 hg branch -q `cat utf-8`
@@ -3550,10 +3563,24 @@
   $ HGENCODING=ascii hg log -T "{branch|json}\n" -r0
   "\u00e9"
 
-json filter should not abort if it can't decode bytes:
-(not sure the current behavior is right; we might want to use utf-8b encoding?)
+json filter takes input as utf-8b:
 
   $ HGENCODING=ascii hg log -T "{'`cat utf-8`'|json}\n" -l1
-  "\ufffd\ufffd"
+  "\u00e9"
+  $ HGENCODING=ascii hg log -T "{'`cat latin1`'|json}\n" -l1
+  "\udce9"
+
+utf8 filter:
+
+  $ HGENCODING=ascii hg log -T "round-trip: {branch|utf8|hex}\n" -r0
+  round-trip: c3a9
+  $ HGENCODING=latin1 hg log -T "decoded: {'`cat latin1`'|utf8|hex}\n" -l1
+  decoded: c3a9
+  $ HGENCODING=ascii hg log -T "replaced: {'`cat latin1`'|utf8|hex}\n" -l1
+  abort: decoding near * (glob)
+  [255]
+  $ hg log -T "invalid type: {rev|utf8}\n" -r0
+  abort: template filter 'utf8' is not compatible with keyword 'rev'
+  [255]
 
   $ cd ..
--- a/tests/test-completion.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-completion.t	Wed Feb 24 15:55:44 2016 -0600
@@ -158,7 +158,7 @@
   --config
   --cwd
   --daemon
-  --daemon-pipefds
+  --daemon-postexec
   --debug
   --debugger
   --encoding
@@ -218,7 +218,7 @@
   pull: update, force, rev, bookmark, branch, ssh, remotecmd, insecure
   push: force, rev, bookmark, branch, new-branch, ssh, remotecmd, insecure
   remove: after, force, subrepos, include, exclude
-  serve: accesslog, daemon, daemon-pipefds, errorlog, port, address, prefix, name, web-conf, webdir-conf, pid-file, stdio, cmdserver, templates, style, ipv6, certificate
+  serve: accesslog, daemon, daemon-postexec, errorlog, port, address, prefix, name, web-conf, webdir-conf, pid-file, stdio, cmdserver, templates, style, ipv6, certificate
   status: all, modified, added, removed, deleted, clean, unknown, ignored, no-status, copies, print0, rev, change, include, exclude, subrepos, template
   summary: remote
   update: clean, check, date, rev, tool
--- a/tests/test-conflict.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-conflict.t	Wed Feb 24 15:55:44 2016 -0600
@@ -46,16 +46,13 @@
 
   $ cat a
   Small Mathematical Series.
-  <<<<<<< local: 618808747361 - test: branch2
   1
   2
   3
+  <<<<<<< local: 618808747361 - test: branch2
   6
   8
   =======
-  1
-  2
-  3
   4
   5
   >>>>>>> other: c0c68e4fe667  - test: branch1
@@ -79,16 +76,13 @@
 
   $ cat a
   Small Mathematical Series.
-  <<<<<<< local: test 2
   1
   2
   3
+  <<<<<<< local: test 2
   6
   8
   =======
-  1
-  2
-  3
   4
   5
   >>>>>>> other: test 1
@@ -108,16 +102,13 @@
 
   $ cat a
   Small Mathematical Series.
-  <<<<<<< local: test 2
   1
   2
   3
+  <<<<<<< local: test 2
   6
   8
   =======
-  1
-  2
-  3
   4
   5
   >>>>>>> other: test 1
@@ -150,16 +141,13 @@
 
   $ cat a
   Small Mathematical Series.
-  <<<<<<< local: 123456789012345678901234567890123456789012345678901234567890\xe3\x81\x82... (esc)
   1
   2
   3
+  <<<<<<< local: 123456789012345678901234567890123456789012345678901234567890\xe3\x81\x82... (esc)
   6
   8
   =======
-  1
-  2
-  3
   4
   5
   >>>>>>> other: branch1
@@ -179,16 +167,13 @@
 
   $ cat a
   Small Mathematical Series.
-  <<<<<<< local
   1
   2
   3
+  <<<<<<< local
   6
   8
   =======
-  1
-  2
-  3
   4
   5
   >>>>>>> other
@@ -232,6 +217,7 @@
 
   $ hg up -C
   2 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  1 other heads for branch "default"
   $ printf "\n\nEnd of file\n" >> a
   $ hg ci -m "Add some stuff at the end"
   $ hg up -r 1
@@ -269,6 +255,7 @@
 
   $ hg up -C
   1 files updated, 0 files merged, 1 files removed, 0 files unresolved
+  1 other heads for branch "default"
   $ hg merge --tool :merge-local
   merging a
   2 files updated, 0 files merged, 0 files removed, 0 files unresolved
--- a/tests/test-contrib-check-commit.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-contrib-check-commit.t	Wed Feb 24 15:55:44 2016 -0600
@@ -87,6 +87,10 @@
   > @@ -599,7 +599,7 @@
   >          if opts.get('all'):
   >  
+  > 
+  > +
+  > + some = otherjunk
+  > +
   > +
   > + def blah_blah(x):
   > +     pass
@@ -102,10 +106,10 @@
    This has no topic and ends with a period.
   7: don't add trailing period on summary line
    This has no topic and ends with a period.
-  15: adds double empty line
-   +
-  16: adds a function with foo_bar naming
-   + def blah_blah(x):
   19: adds double empty line
    +
+  20: adds a function with foo_bar naming
+   + def blah_blah(x):
+  23: adds double empty line
+   +
   [1]
--- a/tests/test-contrib.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-contrib.t	Wed Feb 24 15:55:44 2016 -0600
@@ -148,11 +148,10 @@
   base
   <<<<<<< conflict-local
   not other
-  end
   =======
   other
+  >>>>>>> conflict-other
   end
-  >>>>>>> conflict-other
   [1]
 
 1 label
@@ -161,11 +160,10 @@
   base
   <<<<<<< foo
   not other
-  end
   =======
   other
+  >>>>>>> conflict-other
   end
-  >>>>>>> conflict-other
   [1]
 
 2 labels
@@ -174,11 +172,10 @@
   base
   <<<<<<< foo
   not other
-  end
   =======
   other
+  >>>>>>> bar
   end
-  >>>>>>> bar
   [1]
 
 3 labels
--- a/tests/test-devel-warnings.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-devel-warnings.t	Wed Feb 24 15:55:44 2016 -0600
@@ -70,16 +70,16 @@
   $ hg init lock-checker
   $ cd lock-checker
   $ hg buggylocking
-  devel-warn: transaction with no lock at: $TESTTMP/buggylocking.py:11 (buggylocking)
-  devel-warn: "wlock" acquired after "lock" at: $TESTTMP/buggylocking.py:13 (buggylocking)
+  devel-warn: transaction with no lock at: $TESTTMP/buggylocking.py:* (buggylocking) (glob)
+  devel-warn: "wlock" acquired after "lock" at: $TESTTMP/buggylocking.py:* (buggylocking) (glob)
   $ cat << EOF >> $HGRCPATH
   > [devel]
   > all=0
   > check-locks=1
   > EOF
   $ hg buggylocking
-  devel-warn: transaction with no lock at: $TESTTMP/buggylocking.py:11 (buggylocking)
-  devel-warn: "wlock" acquired after "lock" at: $TESTTMP/buggylocking.py:13 (buggylocking)
+  devel-warn: transaction with no lock at: $TESTTMP/buggylocking.py:* (buggylocking) (glob)
+  devel-warn: "wlock" acquired after "lock" at: $TESTTMP/buggylocking.py:* (buggylocking) (glob)
   $ hg buggylocking --traceback
   devel-warn: transaction with no lock at:
    */hg:* in * (glob)
@@ -112,7 +112,7 @@
   $ hg add a
   $ hg commit -m a
   $ hg stripintr
-  saved backup bundle to $TESTTMP/lock-checker/.hg/strip-backup/cb9a9f314b8b-cc5ccb0b-backup.hg (glob)
+  saved backup bundle to $TESTTMP/lock-checker/.hg/strip-backup/*-backup.hg (glob)
   abort: programming error: cannot strip from inside a transaction
   (contact your extension maintainer)
   [255]
@@ -122,7 +122,7 @@
   0
   $ hg oldanddeprecated
   devel-warn: foorbar is deprecated, go shopping
-  (compatibility will be dropped after Mercurial-42.1337, update your code.) at: $TESTTMP/buggylocking.py:53 (oldanddeprecated)
+  (compatibility will be dropped after Mercurial-42.1337, update your code.) at: $TESTTMP/buggylocking.py:* (oldanddeprecated) (glob)
 
   $ hg oldanddeprecated --traceback
   devel-warn: foorbar is deprecated, go shopping
--- a/tests/test-extdiff.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-extdiff.t	Wed Feb 24 15:55:44 2016 -0600
@@ -72,7 +72,7 @@
 
 Specifying an empty revision should abort.
 
-  $ hg extdiff --patch --rev 'ancestor()' --rev 1
+  $ hg extdiff -p diff --patch --rev 'ancestor()' --rev 1
   abort: empty revision on one side of range
   [255]
 
--- a/tests/test-extension.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-extension.t	Wed Feb 24 15:55:44 2016 -0600
@@ -1003,7 +1003,7 @@
   
   Enabled extensions:
   
-    throw  1.2.3
+    throw  external  1.2.3
   $ echo 'getversion = lambda: "1.twentythree"' >> throw.py
   $ rm -f throw.pyc throw.pyo
   $ hg version -v --config extensions.throw=throw.py
@@ -1016,7 +1016,7 @@
   
   Enabled extensions:
   
-    throw  1.twentythree
+    throw  external  1.twentythree
 
 Refuse to load extensions with minimum version requirements
 
--- a/tests/test-graft.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-graft.t	Wed Feb 24 15:55:44 2016 -0600
@@ -1,3 +1,9 @@
+  $ cat >> $HGRCPATH <<EOF
+  > [extdiff]
+  > # for portability:
+  > pdiff = sh "$RUNTESTDIR/pdiff"
+  > EOF
+
 Create a repo with some stuff in it:
 
   $ hg init a
@@ -40,6 +46,13 @@
   |
   o  test@0.public: 0
   
+Can't continue without starting:
+
+  $ hg rm -q e
+  $ hg graft --continue
+  abort: no graft in progress
+  [255]
+  $ hg revert -r . -q e
 
 Need to specify a rev:
 
@@ -189,10 +202,10 @@
    e: versions differ -> m (premerge)
   picked tool ':merge' for e (binary False symlink False changedelete False)
   merging e
-  my e@1905859650ec+ other e@9c233e8e184d ancestor e@68795b066622
+  my e@1905859650ec+ other e@9c233e8e184d ancestor e@4c60f11aa304
    e: versions differ -> m (merge)
   picked tool ':merge' for e (binary False symlink False changedelete False)
-  my e@1905859650ec+ other e@9c233e8e184d ancestor e@68795b066622
+  my e@1905859650ec+ other e@9c233e8e184d ancestor e@4c60f11aa304
   warning: conflicts while merging e! (edit, then use 'hg resolve --mark')
   abort: unresolved conflicts, can't continue
   (use hg resolve and hg graft --continue --log)
@@ -342,9 +355,9 @@
   skipping already grafted revision 7:ef0ef43d49e7 (was grafted from 2:5c095ad7e90f)
   [255]
 
-  $ hg extdiff --config extensions.extdiff= --patch -r 2 -r 13
-  --- */hg-5c095ad7e90f.patch	* +0000 (glob)
-  +++ */hg-7a4785234d87.patch	* +0000 (glob)
+  $ hg pdiff --config extensions.extdiff= --patch -r 2 -r 13
+  --- */hg-5c095ad7e90f.patch	* (glob)
+  +++ */hg-7a4785234d87.patch	* (glob)
   @@ -1,18 +1,18 @@
    # HG changeset patch
   -# User test
@@ -373,9 +386,9 @@
   ++a
   [1]
 
-  $ hg extdiff --config extensions.extdiff= --patch -r 2 -r 13 -X .
-  --- */hg-5c095ad7e90f.patch	* +0000 (glob)
-  +++ */hg-7a4785234d87.patch	* +0000 (glob)
+  $ hg pdiff --config extensions.extdiff= --patch -r 2 -r 13 -X .
+  --- */hg-5c095ad7e90f.patch	* (glob)
+  +++ */hg-7a4785234d87.patch	* (glob)
   @@ -1,8 +1,8 @@
    # HG changeset patch
   -# User test
--- a/tests/test-hgignore.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-hgignore.t	Wed Feb 24 15:55:44 2016 -0600
@@ -286,3 +286,16 @@
   $ hg debugignore dir1/file2
   dir1/file2 is ignored
   (ignore rule in dir2/.hgignore, line 1: 'file*2')
+
+#if windows
+
+Windows paths are accepted on input
+
+  $ rm dir1/.hgignore
+  $ echo "dir1/file*" >> .hgignore
+  $ hg debugignore "dir1\file2"
+  dir1\file2 is ignored
+  (ignore rule in $TESTTMP\ignorerepo\.hgignore, line 4: 'dir1/file*')
+  $ hg up -qC .
+
+#endif
--- a/tests/test-hgweb-json.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-hgweb-json.t	Wed Feb 24 15:55:44 2016 -0600
@@ -1,4 +1,3 @@
-#require json
 #require serve
 
   $ request() {
--- a/tests/test-highlight.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-highlight.t	Wed Feb 24 15:55:44 2016 -0600
@@ -10,6 +10,12 @@
   $ hg init test
   $ cd test
 
+  $ filterhtml () {
+  >   sed -e "s/class=\"k\"/class=\"kn\"/g" \
+  >       -e "s/class=\"mf\"/class=\"mi\"/g" \
+  >       -e "s/class=\"\([cs]\)[h12]\"/class=\"\1\"/g"
+  > }
+
 create random Python file to exercise Pygments
 
   $ cat <<EOF > primes.py
@@ -57,8 +63,7 @@
 
 hgweb filerevision, html
 
-  $ (get-with-headers.py localhost:$HGPORT 'file/tip/primes.py') \
-  >     | sed "s/class=\"k\"/class=\"kn\"/g" | sed "s/class=\"mf\"/class=\"mi\"/g"
+  $ (get-with-headers.py localhost:$HGPORT 'file/tip/primes.py') | filterhtml
   200 Script output follows
   
   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
@@ -190,8 +195,7 @@
 
 hgweb fileannotate, html
 
-  $ (get-with-headers.py localhost:$HGPORT 'annotate/tip/primes.py') \
-  >     | sed "s/class=\"k\"/class=\"kn\"/g" | sed "s/class=\"mi\"/class=\"mf\"/g"
+  $ (get-with-headers.py localhost:$HGPORT 'annotate/tip/primes.py') | filterhtml
   200 Script output follows
   
   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
@@ -408,7 +412,7 @@
   <a href="/annotate/06824edf55d0/primes.py#l18"
   title="06824edf55d0: a">test@0</a>
   </td>
-  <td class="source"><a href="#l18">    18</a>         <span class="n">ns</span> <span class="o">=</span> <span class="n">ifilter</span><span class="p">(</span><span class="kn">lambda</span> <span class="n">n</span><span class="p">:</span> <span class="n">n</span> <span class="o">%</span> <span class="n">p</span> <span class="o">!=</span> <span class="mf">0</span><span class="p">,</span> <span class="n">ns</span><span class="p">)</span></td>
+  <td class="source"><a href="#l18">    18</a>         <span class="n">ns</span> <span class="o">=</span> <span class="n">ifilter</span><span class="p">(</span><span class="kn">lambda</span> <span class="n">n</span><span class="p">:</span> <span class="n">n</span> <span class="o">%</span> <span class="n">p</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">,</span> <span class="n">ns</span><span class="p">)</span></td>
   </tr>
   <tr id="l19">
   <td class="annotate">
@@ -436,14 +440,14 @@
   <a href="/annotate/06824edf55d0/primes.py#l22"
   title="06824edf55d0: a">test@0</a>
   </td>
-  <td class="source"><a href="#l22">    22</a>     <span class="n">odds</span> <span class="o">=</span> <span class="n">ifilter</span><span class="p">(</span><span class="kn">lambda</span> <span class="n">i</span><span class="p">:</span> <span class="n">i</span> <span class="o">%</span> <span class="mf">2</span> <span class="o">==</span> <span class="mf">1</span><span class="p">,</span> <span class="n">count</span><span class="p">())</span></td>
+  <td class="source"><a href="#l22">    22</a>     <span class="n">odds</span> <span class="o">=</span> <span class="n">ifilter</span><span class="p">(</span><span class="kn">lambda</span> <span class="n">i</span><span class="p">:</span> <span class="n">i</span> <span class="o">%</span> <span class="mi">2</span> <span class="o">==</span> <span class="mi">1</span><span class="p">,</span> <span class="n">count</span><span class="p">())</span></td>
   </tr>
   <tr id="l23">
   <td class="annotate">
   <a href="/annotate/06824edf55d0/primes.py#l23"
   title="06824edf55d0: a">test@0</a>
   </td>
-  <td class="source"><a href="#l23">    23</a>     <span class="kn">return</span> <span class="n">chain</span><span class="p">([</span><span class="mf">2</span><span class="p">],</span> <span class="n">sieve</span><span class="p">(</span><span class="n">dropwhile</span><span class="p">(</span><span class="kn">lambda</span> <span class="n">n</span><span class="p">:</span> <span class="n">n</span> <span class="o">&lt;</span> <span class="mf">3</span><span class="p">,</span> <span class="n">odds</span><span class="p">)))</span></td>
+  <td class="source"><a href="#l23">    23</a>     <span class="kn">return</span> <span class="n">chain</span><span class="p">([</span><span class="mi">2</span><span class="p">],</span> <span class="n">sieve</span><span class="p">(</span><span class="n">dropwhile</span><span class="p">(</span><span class="kn">lambda</span> <span class="n">n</span><span class="p">:</span> <span class="n">n</span> <span class="o">&lt;</span> <span class="mi">3</span><span class="p">,</span> <span class="n">odds</span><span class="p">)))</span></td>
   </tr>
   <tr id="l24">
   <td class="annotate">
@@ -478,7 +482,7 @@
   <a href="/annotate/06824edf55d0/primes.py#l28"
   title="06824edf55d0: a">test@0</a>
   </td>
-  <td class="source"><a href="#l28">    28</a>         <span class="n">n</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mf">1</span><span class="p">])</span></td>
+  <td class="source"><a href="#l28">    28</a>         <span class="n">n</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span></td>
   </tr>
   <tr id="l29">
   <td class="annotate">
@@ -492,7 +496,7 @@
   <a href="/annotate/06824edf55d0/primes.py#l30"
   title="06824edf55d0: a">test@0</a>
   </td>
-  <td class="source"><a href="#l30">    30</a>         <span class="n">n</span> <span class="o">=</span> <span class="mf">10</span></td>
+  <td class="source"><a href="#l30">    30</a>         <span class="n">n</span> <span class="o">=</span> <span class="mi">10</span></td>
   </tr>
   <tr id="l31">
   <td class="annotate">
--- a/tests/test-histedit-arguments.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-histedit-arguments.t	Wed Feb 24 15:55:44 2016 -0600
@@ -133,6 +133,11 @@
   (hg histedit --continue to resume)
   [1]
 
+  $ hg graft --continue
+  abort: no graft in progress
+  (continue: hg histedit --continue)
+  [255]
+
   $ mv .hg/histedit-state .hg/histedit-state.back
   $ hg update --quiet --clean 2
   $ echo alpha >> alpha
@@ -243,9 +248,6 @@
   > p    c8e68270e35a 3 four
   > f 08d98a8350f3 4 five
   > EOF
-  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
-  reverting alpha
-  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
   four
   ***
   five
@@ -258,7 +260,6 @@
   HG: user: test
   HG: branch 'default'
   HG: changed alpha
-  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
   saved backup bundle to $TESTTMP/foo/.hg/strip-backup/*-backup.hg (glob)
   saved backup bundle to $TESTTMP/foo/.hg/strip-backup/*-backup.hg (glob)
 
--- a/tests/test-histedit-commute.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-histedit-commute.t	Wed Feb 24 15:55:44 2016 -0600
@@ -104,7 +104,6 @@
   > pick 055a42cdd887 d
   > EOF
   $ HGEDITOR="cat \"$EDITED\" > " hg histedit 177f92b77385 2>&1 | fixbundle
-  0 files updated, 0 files merged, 3 files removed, 0 files unresolved
 
 log after edit
   $ hg log --graph
@@ -148,7 +147,6 @@
   > pick d8249471110a e
   > pick 8ade9693061e f
   > EOF
-  0 files updated, 0 files merged, 3 files removed, 0 files unresolved
 
   $ hg log --graph
   @  changeset:   5:7eca9b5b1148
@@ -191,7 +189,6 @@
   > pick 915da888f2de e
   > pick 177f92b77385 c
   > EOF
-  0 files updated, 0 files merged, 4 files removed, 0 files unresolved
   $ hg log --graph
   @  changeset:   5:38b92f448761
   |  tag:         tip
@@ -232,7 +229,6 @@
   > pick 38b92f448761 c
   > pick de71b079d9ce e
   > EOF
-  0 files updated, 0 files merged, 2 files removed, 0 files unresolved
   $ hg log --graph
   @  changeset:   7:803ef1c6fcfd
   |  tag:         tip
@@ -417,11 +413,6 @@
   > EOF
 
   $ HGEDITOR="sh ./editor.sh" hg histedit 0
-  1 files updated, 0 files merged, 1 files removed, 0 files unresolved
-  adding another-dir/initial-file (glob)
-  removing initial-dir/initial-file (glob)
-  0 files updated, 0 files merged, 1 files removed, 0 files unresolved
-  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
   saved backup bundle to $TESTTMP/issue4251/.hg/strip-backup/*-backup.hg (glob)
   saved backup bundle to $TESTTMP/issue4251/.hg/strip-backup/*-backup.hg (glob)
 
--- a/tests/test-histedit-drop.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-histedit-drop.t	Wed Feb 24 15:55:44 2016 -0600
@@ -59,7 +59,6 @@
   > pick 652413bf663e f
   > pick 055a42cdd887 d
   > EOF
-  0 files updated, 0 files merged, 4 files removed, 0 files unresolved
 
 log after edit
   $ hg log --graph
@@ -124,7 +123,6 @@
   > pick a4f7421b80f7 f
   > drop f518305ce889 d
   > EOF
-  0 files updated, 0 files merged, 1 files removed, 0 files unresolved
   $ hg log --graph
   @  changeset:   3:a4f7421b80f7
   |  tag:         tip
@@ -158,7 +156,6 @@
   > pick cb9a9f314b8b a
   > pick ee283cb5f2d5 e
   > EOF
-  0 files updated, 0 files merged, 3 files removed, 0 files unresolved
   $ hg log --graph
   @  changeset:   1:e99c679bf03e
   |  tag:         tip
--- a/tests/test-histedit-edit.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-histedit-edit.t	Wed Feb 24 15:55:44 2016 -0600
@@ -286,7 +286,6 @@
   > mv tmp "\$1"
   > EOF
   $ HGEDITOR="sh ../edit.sh" hg histedit tip 2>&1 | fixbundle
-  0 files updated, 0 files merged, 1 files removed, 0 files unresolved
   $ hg status
   $ hg log --limit 1
   changeset:   6:1fd3b2fe7754
@@ -327,7 +326,6 @@
   $ HGEDITOR="sh $TESTTMP/editor.sh" hg histedit tip --commands - 2>&1 << EOF | fixbundle
   > mess 1fd3b2fe7754 f
   > EOF
-  0 files updated, 0 files merged, 1 files removed, 0 files unresolved
   abort: emulating unexpected abort
   $ test -f .hg/last-message.txt
   [1]
@@ -354,8 +352,6 @@
   $ HGEDITOR="sh $TESTTMP/editor.sh" hg histedit tip --commands - 2>&1 << EOF
   > mess 1fd3b2fe7754 f
   > EOF
-  0 files updated, 0 files merged, 1 files removed, 0 files unresolved
-  adding f
   ==== before editing
   f
   
@@ -408,7 +404,6 @@
   $ hg histedit tip --commands - 2>&1 << EOF | fixbundle
   > mess 1fd3b2fe7754 f
   > EOF
-  0 files updated, 0 files merged, 1 files removed, 0 files unresolved
   $ hg status
   $ hg log --limit 1
   changeset:   6:62feedb1200e
--- a/tests/test-histedit-fold-non-commute.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-histedit-fold-non-commute.t	Wed Feb 24 15:55:44 2016 -0600
@@ -104,7 +104,6 @@
   > print
   > EOF
   $ HGEDITOR="python cat.py" hg histedit --continue 2>&1 | fixbundle | grep -v '2 files removed'
-  2 files updated, 0 files merged, 0 files removed, 0 files unresolved
   d
   ***
   does not commute with e
@@ -121,7 +120,6 @@
   
   
   
-  2 files updated, 0 files merged, 0 files removed, 0 files unresolved
   merging e
   warning: conflicts while merging e! (edit, then use 'hg resolve --mark')
   Fix up the change (pick 7b4e2f4b7bcd)
@@ -262,8 +260,6 @@
   (no more unresolved files)
   continue: hg histedit --continue
   $ hg histedit --continue 2>&1 | fixbundle | grep -v '2 files removed'
-  2 files updated, 0 files merged, 0 files removed, 0 files unresolved
-  2 files updated, 0 files merged, 0 files removed, 0 files unresolved
   merging e
   warning: conflicts while merging e! (edit, then use 'hg resolve --mark')
   Fix up the change (pick 7b4e2f4b7bcd)
--- a/tests/test-histedit-fold.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-histedit-fold.t	Wed Feb 24 15:55:44 2016 -0600
@@ -54,9 +54,6 @@
   > fold 177f92b77385 c
   > pick 055a42cdd887 d
   > EOF
-  0 files updated, 0 files merged, 4 files removed, 0 files unresolved
-  0 files updated, 0 files merged, 2 files removed, 0 files unresolved
-  2 files updated, 0 files merged, 0 files removed, 0 files unresolved
 
 log after edit
   $ hg logt --graph
@@ -111,9 +108,6 @@
   > pick 6de59d13424a f
   > pick 9c277da72c9b d
   > EOF
-  0 files updated, 0 files merged, 4 files removed, 0 files unresolved
-  0 files updated, 0 files merged, 2 files removed, 0 files unresolved
-  2 files updated, 0 files merged, 0 files removed, 0 files unresolved
 
   $ HGEDITOR=$OLDHGEDITOR
 
@@ -177,10 +171,7 @@
   > pick 8e03a72b6f83 f
   > fold c4a9eb7989fc d
   > EOF
-  0 files updated, 0 files merged, 1 files removed, 0 files unresolved
-  adding d
   allow non-folding commit
-  0 files updated, 0 files merged, 3 files removed, 0 files unresolved
   ==== before editing
   f
   ***
@@ -242,9 +233,6 @@
   > EOF
   editing: pick e860deea161a 4 e 1/2 changes (50.00%)
   editing: fold a00ad806cb55 5 f 2/2 changes (100.00%)
-  0 files updated, 0 files merged, 1 files removed, 0 files unresolved
-  0 files updated, 0 files merged, 2 files removed, 0 files unresolved
-  2 files updated, 0 files merged, 0 files removed, 0 files unresolved
 
 tip after edit
   $ hg log --rev .
@@ -372,7 +360,6 @@
   created new head
   $ echo 6 >> file
   $ HGEDITOR=cat hg histedit --continue
-  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
   +4
   ***
   +5.2
@@ -387,7 +374,6 @@
   HG: user: test
   HG: branch 'default'
   HG: changed file
-  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
   saved backup bundle to $TESTTMP/fold-with-dropped/.hg/strip-backup/55c8d8dc79ce-4066cd98-backup.hg (glob)
   saved backup bundle to $TESTTMP/fold-with-dropped/.hg/strip-backup/617f94f13c0f-a35700fc-backup.hg (glob)
   $ hg logt -G
@@ -443,10 +429,6 @@
   > pick 1c4f440a8085 rename
   > fold e0371e0426bc b
   > EOF
-  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
-  reverting b.txt
-  1 files updated, 0 files merged, 1 files removed, 0 files unresolved
-  1 files updated, 0 files merged, 1 files removed, 0 files unresolved
 
   $ hg logt --follow b.txt
   1:cf858d235c76 rename
@@ -489,9 +471,6 @@
   > fold a1a953ffb4b0 c
   > pick 6c795aa153cb a
   > EOF
-  0 files updated, 0 files merged, 3 files removed, 0 files unresolved
-  0 files updated, 0 files merged, 2 files removed, 0 files unresolved
-  2 files updated, 0 files merged, 0 files removed, 0 files unresolved
   commit 9599899f62c05f4377548c32bf1c9f1a39634b0c
 
   $ hg logt
@@ -530,13 +509,6 @@
   > fold b7389cc4d66e 3 foo2
   > fold 21679ff7675c 4 foo3
   > EOF
-  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
-  reverting foo
-  0 files updated, 0 files merged, 1 files removed, 0 files unresolved
-  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
-  merging foo
-  0 files updated, 0 files merged, 1 files removed, 0 files unresolved
-  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
   $ hg logt
   2:e8bedbda72c1 merged foos
   1:578c7455730c a
--- a/tests/test-histedit-non-commute-abort.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-histedit-non-commute-abort.t	Wed Feb 24 15:55:44 2016 -0600
@@ -69,7 +69,6 @@
   > pick e860deea161a e
   > pick 652413bf663e f
   > EOF
-  0 files updated, 0 files merged, 2 files removed, 0 files unresolved
   merging e
   warning: conflicts while merging e! (edit, then use 'hg resolve --mark')
   Fix up the change (pick e860deea161a)
@@ -82,6 +81,7 @@
   local: 8f7551c7e4a2f2efe0bc8c741baf7f227d65d758
   other: e860deea161a2f77de56603b340ebbb4536308ae
   unrecognized entry: x	advisory record
+  file extras: e (ancestorlinknode = 0000000000000000000000000000000000000000)
   file: e (record type "F", state "u", hash 58e6b3a414a1e090dfc6029add0f3555ccba127f)
     local path: e (flags "")
     ancestor path: e (node null)
@@ -95,6 +95,7 @@
   * version 2 records
   local: 8f7551c7e4a2f2efe0bc8c741baf7f227d65d758
   other: e860deea161a2f77de56603b340ebbb4536308ae
+  file extras: e (ancestorlinknode = 0000000000000000000000000000000000000000)
   file: e (record type "F", state "u", hash 58e6b3a414a1e090dfc6029add0f3555ccba127f)
     local path: e (flags "")
     ancestor path: e (node null)
--- a/tests/test-histedit-obsolete.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-histedit-obsolete.t	Wed Feb 24 15:55:44 2016 -0600
@@ -14,6 +14,51 @@
   > rebase=
   > EOF
 
+Test that histedit learns about obsolescence not stored in histedit state
+  $ hg init boo
+  $ cd boo
+  $ echo a > a
+  $ hg ci -Am a
+  adding a
+  $ echo a > b
+  $ echo a > c
+  $ echo a > c
+  $ hg ci -Am b
+  adding b
+  adding c
+  $ echo a > d
+  $ hg ci -Am c
+  adding d
+  $ echo "pick `hg log -r 0 -T '{node|short}'`" > plan
+  $ echo "pick `hg log -r 2 -T '{node|short}'`" >> plan
+  $ echo "edit `hg log -r 1 -T '{node|short}'`" >> plan
+  $ hg histedit -r 'all()' --commands plan
+  Editing (1b2d564fad96), you may commit or record as needed now.
+  (hg histedit --continue to resume)
+  [1]
+  $ hg st
+  A b
+  A c
+  ? plan
+  $ hg commit --amend b
+  $ hg histedit --continue
+  $ hg log -G
+  @  6:46abc7c4d873 b
+  |
+  o  5:49d44ab2be1b c
+  |
+  o  0:cb9a9f314b8b a
+  
+  $ hg debugobsolete
+  e72d22b19f8ecf4150ab4f91d0973fd9955d3ddf 49d44ab2be1b67a79127568a67c9c99430633b48 0 (*) {'user': 'test'} (glob)
+  3e30a45cf2f719e96ab3922dfe039cfd047956ce 0 {e72d22b19f8ecf4150ab4f91d0973fd9955d3ddf} (*) {'user': 'test'} (glob)
+  1b2d564fad96311b45362f17c2aa855150efb35f 46abc7c4d8738e8563e577f7889e1b6db3da4199 0 (*) {'user': 'test'} (glob)
+  114f4176969ef342759a8a57e6bccefc4234829b 49d44ab2be1b67a79127568a67c9c99430633b48 0 (*) {'user': 'test'} (glob)
+  $ cd ..
+
+Base setup for the rest of the testing
+======================================
+
   $ hg init base
   $ cd base
 
@@ -108,7 +153,6 @@
   > drop 59d9f330561f 7 d
   > pick cacdfd884a93 8 f
   > EOF
-  0 files updated, 0 files merged, 3 files removed, 0 files unresolved
   $ hg log --graph
   @  11:c13eb81022ca f
   |
@@ -167,7 +211,6 @@
   > pick 40db8afa467b 10 c
   > drop b449568bf7fc 11 f
   > EOF
-  0 files updated, 0 files merged, 1 files removed, 0 files unresolved
   $ hg log -G
   @  12:40db8afa467b c
   |
@@ -187,7 +230,6 @@
   > pick 40db8afa467b 10 c
   > drop 1b3b05f35ff0 13 h
   > EOF
-  0 files updated, 0 files merged, 3 files removed, 0 files unresolved
   $ hg log -G
   @  17:ee6544123ab8 c
   |
@@ -357,7 +399,6 @@
   > pick 7395e1ff83bd 13 h
   > pick ee118ab9fa44 16 k
   > EOF
-  0 files updated, 0 files merged, 5 files removed, 0 files unresolved
   $ hg log -G
   @  23:558246857888 (secret) k
   |
@@ -399,13 +440,6 @@
   > pick b605fb7503f2 14 i
   > fold ee118ab9fa44 16 k
   > EOF
-  0 files updated, 0 files merged, 6 files removed, 0 files unresolved
-  0 files updated, 0 files merged, 2 files removed, 0 files unresolved
-  2 files updated, 0 files merged, 0 files removed, 0 files unresolved
-  0 files updated, 0 files merged, 2 files removed, 0 files unresolved
-  2 files updated, 0 files merged, 0 files removed, 0 files unresolved
-  0 files updated, 0 files merged, 2 files removed, 0 files unresolved
-  2 files updated, 0 files merged, 0 files removed, 0 files unresolved
   $ hg log -G
   @  27:f9daec13fb98 (secret) i
   |
--- a/tests/test-hook.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-hook.t	Wed Feb 24 15:55:44 2016 -0600
@@ -436,6 +436,10 @@
   >     unreachable = 1
   > EOF
 
+  $ cat > syntaxerror.py << EOF
+  > (foo
+  > EOF
+
 test python hooks
 
 #if windows
@@ -480,7 +484,7 @@
   $ hg pull ../a
   pulling from ../a
   searching for changes
-  abort: preoutgoing.uncallable hook is invalid ("hooktests.uncallable" is not callable)
+  abort: preoutgoing.uncallable hook is invalid: "hooktests.uncallable" is not callable
   [255]
 
   $ echo '[hooks]' > ../a/.hg/hgrc
@@ -488,7 +492,7 @@
   $ hg pull ../a
   pulling from ../a
   searching for changes
-  abort: preoutgoing.nohook hook is invalid ("hooktests.nohook" is not defined)
+  abort: preoutgoing.nohook hook is invalid: "hooktests.nohook" is not defined
   [255]
 
   $ echo '[hooks]' > ../a/.hg/hgrc
@@ -496,7 +500,7 @@
   $ hg pull ../a
   pulling from ../a
   searching for changes
-  abort: preoutgoing.nomodule hook is invalid ("nomodule" not in a module)
+  abort: preoutgoing.nomodule hook is invalid: "nomodule" not in a module
   [255]
 
   $ echo '[hooks]' > ../a/.hg/hgrc
@@ -504,7 +508,8 @@
   $ hg pull ../a
   pulling from ../a
   searching for changes
-  abort: preoutgoing.badmodule hook is invalid (import of "nomodule" failed)
+  abort: preoutgoing.badmodule hook is invalid: import of "nomodule" failed
+  (run with --traceback for stack trace)
   [255]
 
   $ echo '[hooks]' > ../a/.hg/hgrc
@@ -512,9 +517,34 @@
   $ hg pull ../a
   pulling from ../a
   searching for changes
-  abort: preoutgoing.unreachable hook is invalid (import of "hooktests.container" failed)
+  abort: preoutgoing.unreachable hook is invalid: import of "hooktests.container" failed
+  (run with --traceback for stack trace)
+  [255]
+
+  $ echo '[hooks]' > ../a/.hg/hgrc
+  $ echo 'preoutgoing.syntaxerror = python:syntaxerror.syntaxerror' >> ../a/.hg/hgrc
+  $ hg pull ../a
+  pulling from ../a
+  searching for changes
+  abort: preoutgoing.syntaxerror hook is invalid: import of "syntaxerror" failed
+  (run with --traceback for stack trace)
   [255]
 
+  $ hg pull ../a --traceback 2>&1 | egrep -v '^( +File|    [_a-zA-Z*(])'
+  pulling from ../a
+  searching for changes
+  exception from first failed import attempt:
+  Traceback (most recent call last):
+      
+      ^
+  SyntaxError: invalid syntax
+  exception from second failed import attempt:
+  Traceback (most recent call last):
+  ImportError: No module named hgext_syntaxerror
+  Traceback (most recent call last):
+  HookLoadError: preoutgoing.syntaxerror hook is invalid: import of "syntaxerror" failed
+  abort: preoutgoing.syntaxerror hook is invalid: import of "syntaxerror" failed
+
   $ echo '[hooks]' > ../a/.hg/hgrc
   $ echo 'preoutgoing.pass = python:hooktests.passhook' >> ../a/.hg/hgrc
   $ hg pull ../a
@@ -530,6 +560,46 @@
   adding remote bookmark quux
   (run 'hg update' to get a working copy)
 
+post- python hooks that fail to *run* don't cause an abort
+  $ rm ../a/.hg/hgrc
+  $ echo '[hooks]' > .hg/hgrc
+  $ echo 'post-pull.broken = python:hooktests.brokenhook' >> .hg/hgrc
+  $ hg pull ../a
+  pulling from ../a
+  searching for changes
+  no changes found
+  error: post-pull.broken hook raised an exception: unsupported operand type(s) for +: 'int' and 'dict'
+  (run with --traceback for stack trace)
+
+but post- python hooks that fail to *load* do
+  $ echo '[hooks]' > .hg/hgrc
+  $ echo 'post-pull.nomodule = python:nomodule' >> .hg/hgrc
+  $ hg pull ../a
+  pulling from ../a
+  searching for changes
+  no changes found
+  abort: post-pull.nomodule hook is invalid: "nomodule" not in a module
+  [255]
+
+  $ echo '[hooks]' > .hg/hgrc
+  $ echo 'post-pull.badmodule = python:nomodule.nowhere' >> .hg/hgrc
+  $ hg pull ../a
+  pulling from ../a
+  searching for changes
+  no changes found
+  abort: post-pull.badmodule hook is invalid: import of "nomodule" failed
+  (run with --traceback for stack trace)
+  [255]
+
+  $ echo '[hooks]' > .hg/hgrc
+  $ echo 'post-pull.nohook = python:hooktests.nohook' >> .hg/hgrc
+  $ hg pull ../a
+  pulling from ../a
+  searching for changes
+  no changes found
+  abort: post-pull.nohook hook is invalid: "hooktests.nohook" is not defined
+  [255]
+
 make sure --traceback works
 
   $ echo '[hooks]' > .hg/hgrc
@@ -628,8 +698,8 @@
   Traceback (most recent call last):
   ImportError: No module named hgext_importfail
   Traceback (most recent call last):
-  HookLoadError: precommit.importfail hook is invalid (import of "importfail" failed)
-  abort: precommit.importfail hook is invalid (import of "importfail" failed)
+  HookLoadError: precommit.importfail hook is invalid: import of "importfail" failed
+  abort: precommit.importfail hook is invalid: import of "importfail" failed
 
 Issue1827: Hooks Update & Commit not completely post operation
 
--- a/tests/test-issue1502.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-issue1502.t	Wed Feb 24 15:55:44 2016 -0600
@@ -12,16 +12,14 @@
 
   $ echo "bar" > foo1/a && hg -R foo1 commit -m "edit a in foo1"
   $ echo "hi" > foo/a && hg -R foo commit -m "edited a foo"
-  $ hg -R foo1 pull -u
+  $ hg -R foo1 pull
   pulling from $TESTTMP/foo (glob)
   searching for changes
   adding changesets
   adding manifests
   adding file changes
   added 1 changesets with 1 changes to 1 files (+1 heads)
-  abort: not updating: not a linear update
-  (merge or update --check to force update)
-  [255]
+  (run 'hg heads' to see heads, 'hg merge' to merge)
 
   $ hg -R foo1 book branchy
   $ hg -R foo1 book
--- a/tests/test-issue672.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-issue672.t	Wed Feb 24 15:55:44 2016 -0600
@@ -68,7 +68,7 @@
    1a: local copied/moved from 1 -> m (premerge)
   picked tool ':merge' for 1a (binary False symlink False changedelete False)
   merging 1a and 1 to 1a
-  my 1a@e327dca35ac8+ other 1@746e9549ea96 ancestor 1@81f4b099af3d
+  my 1a@e327dca35ac8+ other 1@746e9549ea96 ancestor 1@c64f439569a9
    premerge successful
   0 files updated, 1 files merged, 0 files removed, 0 files unresolved
   (branch merge, don't forget to commit)
@@ -91,7 +91,7 @@
    1a: remote moved from 1 -> m (premerge)
   picked tool ':merge' for 1a (binary False symlink False changedelete False)
   merging 1 and 1a to 1a
-  my 1a@746e9549ea96+ other 1a@e327dca35ac8 ancestor 1@81f4b099af3d
+  my 1a@746e9549ea96+ other 1a@e327dca35ac8 ancestor 1@c64f439569a9
    premerge successful
   0 files updated, 1 files merged, 0 files removed, 0 files unresolved
   (branch merge, don't forget to commit)
--- a/tests/test-largefiles-cache.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-largefiles-cache.t	Wed Feb 24 15:55:44 2016 -0600
@@ -189,7 +189,7 @@
 Inject corruption into the largefiles store and see how update handles that:
 
   $ cd src
-  $ hg up -qC
+  $ hg up -qC tip
   $ cat large
   modified
   $ rm large
@@ -202,6 +202,7 @@
   large: data corruption in $TESTTMP/src/.hg/largefiles/e2fb5f2139d086ded2cb600d5a91a196e76bf020 with hash 6a7bb2556144babe3899b25e5428123735bb1e27 (glob)
   0 largefiles updated, 0 removed
   0 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  2 other heads for branch "default"
   $ hg st
   ! large
   ? z
--- a/tests/test-largefiles-misc.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-largefiles-misc.t	Wed Feb 24 15:55:44 2016 -0600
@@ -1095,7 +1095,7 @@
   adding manifests
   adding file changes
   added 1 changesets with 1 changes to 1 files
-  nothing to rebase - working directory parent is already an ancestor of destination bf5e395ced2c
+  nothing to rebase - updating instead
   1 files updated, 0 files merged, 0 files removed, 0 files unresolved
 
   $ cd ..
--- a/tests/test-largefiles-update.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-largefiles-update.t	Wed Feb 24 15:55:44 2016 -0600
@@ -6,6 +6,9 @@
   > merge = internal:fail
   > [extensions]
   > largefiles =
+  > [extdiff]
+  > # for portability:
+  > pdiff = sh "$RUNTESTDIR/pdiff"
   > EOF
 
   $ hg init repo
@@ -20,17 +23,17 @@
   $ echo 'large1 in #1' > large1
   $ echo 'normal1 in #1' > normal1
   $ hg commit -m '#1'
-  $ hg extdiff -r '.^' --config extensions.extdiff=
-  diff -Npru repo.0d9d9b8dc9a3/.hglf/large1 repo/.hglf/large1
+  $ hg pdiff -r '.^' --config extensions.extdiff=
+  diff -Nru repo.0d9d9b8dc9a3/.hglf/large1 repo/.hglf/large1
   --- repo.0d9d9b8dc9a3/.hglf/large1	* (glob)
   +++ repo/.hglf/large1	* (glob)
-  @@ -1 +1 @@
+  @@ -1* +1* @@ (glob)
   -4669e532d5b2c093a78eca010077e708a071bb64
   +58e24f733a964da346e2407a2bee99d9001184f5
-  diff -Npru repo.0d9d9b8dc9a3/normal1 repo/normal1
+  diff -Nru repo.0d9d9b8dc9a3/normal1 repo/normal1
   --- repo.0d9d9b8dc9a3/normal1	* (glob)
   +++ repo/normal1	* (glob)
-  @@ -1 +1 @@
+  @@ -1* +1* @@ (glob)
   -normal1
   +normal1 in #1
   [1]
@@ -68,6 +71,7 @@
 
   $ hg up
   0 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  1 other heads for branch "default"
   $ hg debugdirstate --large --nodate
   n 644          7 set                 large1
   n 644         13 set                 large2
@@ -82,6 +86,7 @@
   n 644         13 set                 large2
   $ hg up
   0 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  1 other heads for branch "default"
   $ hg debugdirstate --large --nodate
   n 644          7 set                 large1
   n 644         13 set                 large2
@@ -463,6 +468,7 @@
   keep (l)ocal ba94c2efe5b7c5e0af8d189295ce00553b0612b7 or
   take (o)ther e5bb990443d6a92aaf7223813720f7566c9dd05b? l
   2 files updated, 1 files merged, 0 files removed, 0 files unresolved
+  1 other heads for branch "default"
 
   $ hg status -A large1
   M large1
@@ -496,6 +502,7 @@
   keep (l)ocal ba94c2efe5b7c5e0af8d189295ce00553b0612b7 or
   take (o)ther e5bb990443d6a92aaf7223813720f7566c9dd05b? l
   2 files updated, 1 files merged, 0 files removed, 0 files unresolved
+  1 other heads for branch "default"
 
   $ hg status -A large1
   M large1
--- a/tests/test-lock.py	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-lock.py	Wed Feb 24 15:55:44 2016 -0600
@@ -28,7 +28,7 @@
         self._pidoffset = pidoffset
         super(lockwrapper, self).__init__(*args, **kwargs)
     def _getpid(self):
-        return os.getpid() + self._pidoffset
+        return super(lockwrapper, self)._getpid() + self._pidoffset
 
 class teststate(object):
     def __init__(self, testcase, dir, pidoffset=0):
--- a/tests/test-merge-changedelete.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-merge-changedelete.t	Wed Feb 24 15:55:44 2016 -0600
@@ -77,14 +77,17 @@
   * version 2 records
   local: 13910f48cf7bdb2a0ba6e24b4900e4fdd5739dd4
   other: 10f9a0a634e82080907e62f075ab119cbc565ea6
+  file extras: file1 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file1 (record type "C", state "u", hash 60b27f004e454aca81b0480209cce5081ec52390)
     local path: file1 (flags "")
     ancestor path: file1 (node b8e02f6433738021a065f94175c7cd23db5f05be)
     other path: file1 (node null)
+  file extras: file2 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file2 (record type "C", state "u", hash null)
     local path: file2 (flags "")
     ancestor path: file2 (node 5d9299349fc01ddd25d0070d149b124d8f10411e)
     other path: file2 (node e7c1328648519852e723de86c0c0525acd779257)
+  file extras: file3 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file3 (record type "F", state "u", hash d5b0a58bc47161b1b8a831084b366f757c4f0b11)
     local path: file3 (flags "")
     ancestor path: file3 (node 2661d26c649684b482d10f91960cc3db683c38b4)
@@ -108,6 +111,7 @@
 
   $ hg co -C
   1 files updated, 0 files merged, 1 files removed, 0 files unresolved
+  1 other heads for branch "default"
 
   $ hg merge --config ui.interactive=true <<EOF
   > c
@@ -136,14 +140,17 @@
   * version 2 records
   local: 13910f48cf7bdb2a0ba6e24b4900e4fdd5739dd4
   other: 10f9a0a634e82080907e62f075ab119cbc565ea6
+  file extras: file1 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file1 (record type "C", state "r", hash 60b27f004e454aca81b0480209cce5081ec52390)
     local path: file1 (flags "")
     ancestor path: file1 (node b8e02f6433738021a065f94175c7cd23db5f05be)
     other path: file1 (node null)
+  file extras: file2 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file2 (record type "C", state "r", hash null)
     local path: file2 (flags "")
     ancestor path: file2 (node 5d9299349fc01ddd25d0070d149b124d8f10411e)
     other path: file2 (node e7c1328648519852e723de86c0c0525acd779257)
+  file extras: file3 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file3 (record type "F", state "u", hash d5b0a58bc47161b1b8a831084b366f757c4f0b11)
     local path: file3 (flags "")
     ancestor path: file3 (node 2661d26c649684b482d10f91960cc3db683c38b4)
@@ -165,6 +172,7 @@
 
   $ hg co -C
   1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  1 other heads for branch "default"
 
   $ hg merge --config ui.interactive=true <<EOF
   > foo
@@ -205,14 +213,17 @@
   * version 2 records
   local: 13910f48cf7bdb2a0ba6e24b4900e4fdd5739dd4
   other: 10f9a0a634e82080907e62f075ab119cbc565ea6
+  file extras: file1 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file1 (record type "C", state "r", hash 60b27f004e454aca81b0480209cce5081ec52390)
     local path: file1 (flags "")
     ancestor path: file1 (node b8e02f6433738021a065f94175c7cd23db5f05be)
     other path: file1 (node null)
+  file extras: file2 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file2 (record type "C", state "r", hash null)
     local path: file2 (flags "")
     ancestor path: file2 (node 5d9299349fc01ddd25d0070d149b124d8f10411e)
     other path: file2 (node e7c1328648519852e723de86c0c0525acd779257)
+  file extras: file3 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file3 (record type "F", state "u", hash d5b0a58bc47161b1b8a831084b366f757c4f0b11)
     local path: file3 (flags "")
     ancestor path: file3 (node 2661d26c649684b482d10f91960cc3db683c38b4)
@@ -234,6 +245,7 @@
 
   $ hg co -C
   2 files updated, 0 files merged, 1 files removed, 0 files unresolved
+  1 other heads for branch "default"
 
   $ hg merge --config ui.interactive=true <<EOF
   > d
@@ -261,14 +273,17 @@
   * version 2 records
   local: 13910f48cf7bdb2a0ba6e24b4900e4fdd5739dd4
   other: 10f9a0a634e82080907e62f075ab119cbc565ea6
+  file extras: file1 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file1 (record type "C", state "r", hash 60b27f004e454aca81b0480209cce5081ec52390)
     local path: file1 (flags "")
     ancestor path: file1 (node b8e02f6433738021a065f94175c7cd23db5f05be)
     other path: file1 (node null)
+  file extras: file2 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file2 (record type "C", state "u", hash null)
     local path: file2 (flags "")
     ancestor path: file2 (node 5d9299349fc01ddd25d0070d149b124d8f10411e)
     other path: file2 (node e7c1328648519852e723de86c0c0525acd779257)
+  file extras: file3 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file3 (record type "F", state "u", hash d5b0a58bc47161b1b8a831084b366f757c4f0b11)
     local path: file3 (flags "")
     ancestor path: file3 (node 2661d26c649684b482d10f91960cc3db683c38b4)
@@ -289,6 +304,7 @@
 
   $ hg co -C
   2 files updated, 0 files merged, 1 files removed, 0 files unresolved
+  1 other heads for branch "default"
 
   $ hg merge --tool :local
   0 files updated, 3 files merged, 0 files removed, 0 files unresolved
@@ -306,14 +322,17 @@
   * version 2 records
   local: 13910f48cf7bdb2a0ba6e24b4900e4fdd5739dd4
   other: 10f9a0a634e82080907e62f075ab119cbc565ea6
+  file extras: file1 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file1 (record type "C", state "r", hash 60b27f004e454aca81b0480209cce5081ec52390)
     local path: file1 (flags "")
     ancestor path: file1 (node b8e02f6433738021a065f94175c7cd23db5f05be)
     other path: file1 (node null)
+  file extras: file2 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file2 (record type "C", state "r", hash null)
     local path: file2 (flags "")
     ancestor path: file2 (node 5d9299349fc01ddd25d0070d149b124d8f10411e)
     other path: file2 (node e7c1328648519852e723de86c0c0525acd779257)
+  file extras: file3 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file3 (record type "F", state "r", hash d5b0a58bc47161b1b8a831084b366f757c4f0b11)
     local path: file3 (flags "")
     ancestor path: file3 (node 2661d26c649684b482d10f91960cc3db683c38b4)
@@ -330,6 +349,7 @@
 
   $ hg co -C
   1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  1 other heads for branch "default"
 
   $ hg merge --tool :other
   0 files updated, 2 files merged, 1 files removed, 0 files unresolved
@@ -347,14 +367,17 @@
   * version 2 records
   local: 13910f48cf7bdb2a0ba6e24b4900e4fdd5739dd4
   other: 10f9a0a634e82080907e62f075ab119cbc565ea6
+  file extras: file1 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file1 (record type "C", state "r", hash 60b27f004e454aca81b0480209cce5081ec52390)
     local path: file1 (flags "")
     ancestor path: file1 (node b8e02f6433738021a065f94175c7cd23db5f05be)
     other path: file1 (node null)
+  file extras: file2 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file2 (record type "C", state "r", hash null)
     local path: file2 (flags "")
     ancestor path: file2 (node 5d9299349fc01ddd25d0070d149b124d8f10411e)
     other path: file2 (node e7c1328648519852e723de86c0c0525acd779257)
+  file extras: file3 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file3 (record type "F", state "r", hash d5b0a58bc47161b1b8a831084b366f757c4f0b11)
     local path: file3 (flags "")
     ancestor path: file3 (node 2661d26c649684b482d10f91960cc3db683c38b4)
@@ -371,6 +394,7 @@
 
   $ hg co -C
   2 files updated, 0 files merged, 1 files removed, 0 files unresolved
+  1 other heads for branch "default"
 
   $ hg merge --tool :fail
   0 files updated, 0 files merged, 0 files removed, 3 files unresolved
@@ -389,14 +413,17 @@
   * version 2 records
   local: 13910f48cf7bdb2a0ba6e24b4900e4fdd5739dd4
   other: 10f9a0a634e82080907e62f075ab119cbc565ea6
+  file extras: file1 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file1 (record type "C", state "u", hash 60b27f004e454aca81b0480209cce5081ec52390)
     local path: file1 (flags "")
     ancestor path: file1 (node b8e02f6433738021a065f94175c7cd23db5f05be)
     other path: file1 (node null)
+  file extras: file2 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file2 (record type "C", state "u", hash null)
     local path: file2 (flags "")
     ancestor path: file2 (node 5d9299349fc01ddd25d0070d149b124d8f10411e)
     other path: file2 (node e7c1328648519852e723de86c0c0525acd779257)
+  file extras: file3 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file3 (record type "F", state "u", hash d5b0a58bc47161b1b8a831084b366f757c4f0b11)
     local path: file3 (flags "")
     ancestor path: file3 (node 2661d26c649684b482d10f91960cc3db683c38b4)
@@ -415,6 +442,7 @@
 
   $ hg co -C
   1 files updated, 0 files merged, 1 files removed, 0 files unresolved
+  1 other heads for branch "default"
 
   $ hg merge --config ui.interactive=True --tool :prompt
   local changed file1 which remote deleted
@@ -439,14 +467,17 @@
   * version 2 records
   local: 13910f48cf7bdb2a0ba6e24b4900e4fdd5739dd4
   other: 10f9a0a634e82080907e62f075ab119cbc565ea6
+  file extras: file1 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file1 (record type "C", state "u", hash 60b27f004e454aca81b0480209cce5081ec52390)
     local path: file1 (flags "")
     ancestor path: file1 (node b8e02f6433738021a065f94175c7cd23db5f05be)
     other path: file1 (node null)
+  file extras: file2 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file2 (record type "C", state "u", hash null)
     local path: file2 (flags "")
     ancestor path: file2 (node 5d9299349fc01ddd25d0070d149b124d8f10411e)
     other path: file2 (node e7c1328648519852e723de86c0c0525acd779257)
+  file extras: file3 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file3 (record type "F", state "u", hash d5b0a58bc47161b1b8a831084b366f757c4f0b11)
     local path: file3 (flags "")
     ancestor path: file3 (node 2661d26c649684b482d10f91960cc3db683c38b4)
@@ -467,6 +498,7 @@
 
   $ hg co -C
   1 files updated, 0 files merged, 1 files removed, 0 files unresolved
+  1 other heads for branch "default"
 
   $ hg merge --tool :prompt
   local changed file1 which remote deleted
@@ -491,14 +523,17 @@
   * version 2 records
   local: 13910f48cf7bdb2a0ba6e24b4900e4fdd5739dd4
   other: 10f9a0a634e82080907e62f075ab119cbc565ea6
+  file extras: file1 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file1 (record type "C", state "u", hash 60b27f004e454aca81b0480209cce5081ec52390)
     local path: file1 (flags "")
     ancestor path: file1 (node b8e02f6433738021a065f94175c7cd23db5f05be)
     other path: file1 (node null)
+  file extras: file2 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file2 (record type "C", state "u", hash null)
     local path: file2 (flags "")
     ancestor path: file2 (node 5d9299349fc01ddd25d0070d149b124d8f10411e)
     other path: file2 (node e7c1328648519852e723de86c0c0525acd779257)
+  file extras: file3 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file3 (record type "F", state "u", hash d5b0a58bc47161b1b8a831084b366f757c4f0b11)
     local path: file3 (flags "")
     ancestor path: file3 (node 2661d26c649684b482d10f91960cc3db683c38b4)
@@ -517,6 +552,7 @@
 
   $ hg co -C
   1 files updated, 0 files merged, 1 files removed, 0 files unresolved
+  1 other heads for branch "default"
 
   $ hg merge --tool :merge3
   local changed file1 which remote deleted
@@ -541,14 +577,17 @@
   * version 2 records
   local: 13910f48cf7bdb2a0ba6e24b4900e4fdd5739dd4
   other: 10f9a0a634e82080907e62f075ab119cbc565ea6
+  file extras: file1 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file1 (record type "C", state "u", hash 60b27f004e454aca81b0480209cce5081ec52390)
     local path: file1 (flags "")
     ancestor path: file1 (node b8e02f6433738021a065f94175c7cd23db5f05be)
     other path: file1 (node null)
+  file extras: file2 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file2 (record type "C", state "u", hash null)
     local path: file2 (flags "")
     ancestor path: file2 (node 5d9299349fc01ddd25d0070d149b124d8f10411e)
     other path: file2 (node e7c1328648519852e723de86c0c0525acd779257)
+  file extras: file3 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file3 (record type "F", state "u", hash d5b0a58bc47161b1b8a831084b366f757c4f0b11)
     local path: file3 (flags "")
     ancestor path: file3 (node 2661d26c649684b482d10f91960cc3db683c38b4)
@@ -697,10 +736,12 @@
   * version 2 records
   local: ab57bf49aa276a22d35a473592d4c34b5abc3eff
   other: 10f9a0a634e82080907e62f075ab119cbc565ea6
+  file extras: file1 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file1 (record type "C", state "u", hash 60b27f004e454aca81b0480209cce5081ec52390)
     local path: file1 (flags "")
     ancestor path: file1 (node b8e02f6433738021a065f94175c7cd23db5f05be)
     other path: file1 (node null)
+  file extras: file2 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file2 (record type "C", state "u", hash null)
     local path: file2 (flags "")
     ancestor path: file2 (node 5d9299349fc01ddd25d0070d149b124d8f10411e)
@@ -735,10 +776,12 @@
   * version 2 records
   local: ab57bf49aa276a22d35a473592d4c34b5abc3eff
   other: 10f9a0a634e82080907e62f075ab119cbc565ea6
+  file extras: file1 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file1 (record type "C", state "r", hash 60b27f004e454aca81b0480209cce5081ec52390)
     local path: file1 (flags "")
     ancestor path: file1 (node b8e02f6433738021a065f94175c7cd23db5f05be)
     other path: file1 (node null)
+  file extras: file2 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file2 (record type "C", state "r", hash null)
     local path: file2 (flags "")
     ancestor path: file2 (node 5d9299349fc01ddd25d0070d149b124d8f10411e)
@@ -771,10 +814,12 @@
   * version 2 records
   local: ab57bf49aa276a22d35a473592d4c34b5abc3eff
   other: 10f9a0a634e82080907e62f075ab119cbc565ea6
+  file extras: file1 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file1 (record type "C", state "r", hash 60b27f004e454aca81b0480209cce5081ec52390)
     local path: file1 (flags "")
     ancestor path: file1 (node b8e02f6433738021a065f94175c7cd23db5f05be)
     other path: file1 (node null)
+  file extras: file2 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file2 (record type "C", state "r", hash null)
     local path: file2 (flags "")
     ancestor path: file2 (node 5d9299349fc01ddd25d0070d149b124d8f10411e)
@@ -809,10 +854,12 @@
   * version 2 records
   local: ab57bf49aa276a22d35a473592d4c34b5abc3eff
   other: 10f9a0a634e82080907e62f075ab119cbc565ea6
+  file extras: file1 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file1 (record type "C", state "u", hash 60b27f004e454aca81b0480209cce5081ec52390)
     local path: file1 (flags "")
     ancestor path: file1 (node b8e02f6433738021a065f94175c7cd23db5f05be)
     other path: file1 (node null)
+  file extras: file2 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file2 (record type "C", state "u", hash null)
     local path: file2 (flags "")
     ancestor path: file2 (node 5d9299349fc01ddd25d0070d149b124d8f10411e)
@@ -853,10 +900,12 @@
   * version 2 records
   local: ab57bf49aa276a22d35a473592d4c34b5abc3eff
   other: 10f9a0a634e82080907e62f075ab119cbc565ea6
+  file extras: file1 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file1 (record type "C", state "u", hash 60b27f004e454aca81b0480209cce5081ec52390)
     local path: file1 (flags "")
     ancestor path: file1 (node b8e02f6433738021a065f94175c7cd23db5f05be)
     other path: file1 (node null)
+  file extras: file2 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file2 (record type "C", state "u", hash null)
     local path: file2 (flags "")
     ancestor path: file2 (node 5d9299349fc01ddd25d0070d149b124d8f10411e)
@@ -898,10 +947,12 @@
   * version 2 records
   local: ab57bf49aa276a22d35a473592d4c34b5abc3eff
   other: 10f9a0a634e82080907e62f075ab119cbc565ea6
+  file extras: file1 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file1 (record type "C", state "u", hash 60b27f004e454aca81b0480209cce5081ec52390)
     local path: file1 (flags "")
     ancestor path: file1 (node b8e02f6433738021a065f94175c7cd23db5f05be)
     other path: file1 (node null)
+  file extras: file2 (ancestorlinknode = ab57bf49aa276a22d35a473592d4c34b5abc3eff)
   file: file2 (record type "C", state "u", hash null)
     local path: file2 (flags "")
     ancestor path: file2 (node 5d9299349fc01ddd25d0070d149b124d8f10411e)
--- a/tests/test-merge-criss-cross.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-merge-criss-cross.t	Wed Feb 24 15:55:44 2016 -0600
@@ -85,10 +85,10 @@
    f2: versions differ -> m (premerge)
   picked tool ':dump' for f2 (binary False symlink False changedelete False)
   merging f2
-  my f2@3b08d01b0ab5+ other f2@adfe50279922 ancestor f2@40494bf2444c
+  my f2@3b08d01b0ab5+ other f2@adfe50279922 ancestor f2@0f6b37dbe527
    f2: versions differ -> m (merge)
   picked tool ':dump' for f2 (binary False symlink False changedelete False)
-  my f2@3b08d01b0ab5+ other f2@adfe50279922 ancestor f2@40494bf2444c
+  my f2@3b08d01b0ab5+ other f2@adfe50279922 ancestor f2@0f6b37dbe527
   1 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
   [1]
@@ -212,7 +212,7 @@
   1 files updated, 0 files merged, 0 files removed, 0 files unresolved
   (branch merge, don't forget to commit)
 
-  $ hg up -qC
+  $ hg up -qC tip
   $ hg merge -v
   note: merging 3b08d01b0ab5+ and adfe50279922 using bids from ancestors 0f6b37dbe527 and 40663881a6dd
   
--- a/tests/test-merge-default.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-merge-default.t	Wed Feb 24 15:55:44 2016 -0600
@@ -27,12 +27,13 @@
 Should fail because not at a head:
 
   $ hg merge
-  abort: branch 'default' has 3 heads - please merge with an explicit rev
-  (run 'hg heads .' to see heads)
+  abort: working directory not at a head revision
+  (use 'hg update' or merge with an explicit revision)
   [255]
 
   $ hg up
   1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  2 other heads for branch "default"
 
 Should fail because > 2 heads:
 
@@ -115,3 +116,36 @@
   (run 'hg heads' to see all heads)
   [255]
 
+(on a branch with a two heads)
+
+  $ hg up 5
+  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  $ echo f >> a
+  $ hg commit -mf
+  created new head
+  $ hg log -r '_destmerge()'
+  changeset:   6:e88e33f3bf62
+  parent:      5:a431fabd6039
+  parent:      3:ea9ff125ff88
+  user:        test
+  date:        Thu Jan 01 00:00:00 1970 +0000
+  summary:     m2
+  
+
+(from the other head)
+
+  $ hg log -r '_destmerge(e88e33f3bf62)'
+  changeset:   8:b613918999e2
+  tag:         tip
+  parent:      5:a431fabd6039
+  user:        test
+  date:        Thu Jan 01 00:00:00 1970 +0000
+  summary:     f
+  
+
+(from unrelated branch)
+
+  $ hg log -r '_destmerge(foobranch)'
+  abort: branch 'foobranch' has one head - please merge with an explicit rev
+  (run 'hg heads' to see all heads)
+  [255]
--- a/tests/test-merge-force.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-merge-force.t	Wed Feb 24 15:55:44 2016 -0600
@@ -141,7 +141,7 @@
 # - local and remote changed content1_content2_*_content2-untracked
 #   in the same way, so it could potentially be left alone
 
-  $ hg merge -f --tool internal:merge3 'desc("remote")'
+  $ hg merge -f --tool internal:merge3 'desc("remote")' 2>&1 | tee $TESTTMP/merge-output-1
   local changed content1_missing_content1_content4-tracked which remote deleted
   use (c)hanged version, (d)elete, or leave (u)nresolved? u
   local changed content1_missing_content3_content3-tracked which remote deleted
@@ -217,7 +217,6 @@
   warning: conflicts while merging missing_content2_missing_content4-untracked! (edit, then use 'hg resolve --mark')
   18 files updated, 3 files merged, 8 files removed, 35 files unresolved
   use 'hg resolve' to retry unresolved file merges or 'hg update -C .' to abandon
-  [1]
 
 Check which files need to be resolved (should correspond to the output above).
 This should be the files for which the base (1st filename segment), the remote
@@ -780,3 +779,17 @@
   [1]
   $ checkstatus > $TESTTMP/status2 2>&1
   $ cmp $TESTTMP/status1 $TESTTMP/status2 || diff -U8 $TESTTMP/status1 $TESTTMP/status2
+
+Set up working directory again
+
+  $ hg -q update --clean 2
+  $ hg --config extensions.purge= purge
+  $ python $TESTDIR/generate-working-copy-states.py state 3 wc
+  $ hg addremove -q --similarity 0
+  $ hg forget *_*_*_*-untracked
+  $ rm *_*_*_missing-*
+
+Merge with checkunknown = warn, see that behavior is the same as before
+  $ hg merge -f --tool internal:merge3 'desc("remote")' --config merge.checkunknown=warn > $TESTTMP/merge-output-2 2>&1
+  [1]
+  $ cmp $TESTTMP/merge-output-1 $TESTTMP/merge-output-2 || diff -U8 $TESTTMP/merge-output-1 $TESTTMP/merge-output-2
--- a/tests/test-merge-types.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-merge-types.t	Wed Feb 24 15:55:44 2016 -0600
@@ -155,6 +155,7 @@
   1 files updated, 0 files merged, 0 files removed, 0 files unresolved
   $ hg up
   1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  1 other heads for branch "default"
   $ hg st
   ? a.orig
 
@@ -175,6 +176,7 @@
   keep (l)ocal, take (o)ther, or leave (u)nresolved? u
   0 files updated, 0 files merged, 0 files removed, 1 files unresolved
   use 'hg resolve' to retry unresolved file merges
+  1 other heads for branch "default"
   [1]
   $ hg diff --git
   diff --git a/a b/a
--- a/tests/test-merge5.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-merge5.t	Wed Feb 24 15:55:44 2016 -0600
@@ -13,16 +13,12 @@
   created new head
   $ hg update 1
   1 files updated, 0 files merged, 0 files removed, 0 files unresolved
-  $ hg update
-  abort: not a linear update
-  (merge or update --check to force update)
-  [255]
   $ rm b
-  $ hg update -c
+  $ hg update -c 2
   abort: uncommitted changes
   [255]
   $ hg revert b
-  $ hg update -c
+  $ hg update -c 2
   0 files updated, 0 files merged, 1 files removed, 0 files unresolved
   $ mv a c
 
--- a/tests/test-obsolete-tag-cache.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-obsolete-tag-cache.t	Wed Feb 24 15:55:44 2016 -0600
@@ -67,11 +67,12 @@
   042eb6bfcc4909bad84a1cbf6eb1ddf0ab587d41 head2
   55482a6fb4b1881fa8f746fd52cf6f096bb21c89 test1
 
-  $ hg blackbox -l 4
+  $ hg blackbox -l 5
   1970/01/01 00:00:00 bob (*)> tags (glob)
   1970/01/01 00:00:00 bob (*)> 2/2 cache hits/lookups in * seconds (glob)
   1970/01/01 00:00:00 bob (*)> writing .hg/cache/tags2-visible with 2 tags (glob)
   1970/01/01 00:00:00 bob (*)> tags exited 0 after * seconds (glob)
+  1970/01/01 00:00:00 bob (*)> blackbox -l 5 (glob)
 
 Hiding another changeset should cause the filtered hash to change
 
@@ -86,11 +87,12 @@
   5 2942a772f72a444bef4bef13874d515f50fa27b6 2fce1eec33263d08a4d04293960fc73a555230e4
   042eb6bfcc4909bad84a1cbf6eb1ddf0ab587d41 head2
 
-  $ hg blackbox -l 4
+  $ hg blackbox -l 5
   1970/01/01 00:00:00 bob (*)> tags (glob)
   1970/01/01 00:00:00 bob (*)> 1/1 cache hits/lookups in * seconds (glob)
   1970/01/01 00:00:00 bob (*)> writing .hg/cache/tags2-visible with 1 tags (glob)
   1970/01/01 00:00:00 bob (*)> tags exited 0 after * seconds (glob)
+  1970/01/01 00:00:00 bob (*)> blackbox -l 5 (glob)
 
 Resolving tags on an unfiltered repo writes a separate tags cache
 
@@ -106,8 +108,9 @@
   55482a6fb4b1881fa8f746fd52cf6f096bb21c89 test1
   d75775ffbc6bca1794d300f5571272879bd280da test2
 
-  $ hg blackbox -l 4
+  $ hg blackbox -l 5
   1970/01/01 00:00:00 bob (*)> --hidden tags (glob)
   1970/01/01 00:00:00 bob (*)> 2/2 cache hits/lookups in * seconds (glob)
   1970/01/01 00:00:00 bob (*)> writing .hg/cache/tags2 with 3 tags (glob)
   1970/01/01 00:00:00 bob (*)> --hidden tags exited 0 after * seconds (glob)
+  1970/01/01 00:00:00 bob (*)> blackbox -l 5 (glob)
--- a/tests/test-obsolete.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-obsolete.t	Wed Feb 24 15:55:44 2016 -0600
@@ -960,6 +960,7 @@
   $ hg log -r . -T '{node}' --debug
   8fd96dfc63e51ed5a8af1bec18eb4b19dbf83812 (no-eol)
 
+#if unix-permissions
 Check that wrong hidden cache permission does not crash
 
   $ chmod 000 .hg/cache/hidden
@@ -967,6 +968,7 @@
   cannot read hidden cache
   error writing hidden changesets cache
   8fd96dfc63e51ed5a8af1bec18eb4b19dbf83812 (no-eol)
+#endif
 
 Test cache consistency for the visible filter
 1) We want to make sure that the cached filtered revs are invalidated when
@@ -1004,5 +1006,74 @@
   (use --hidden to access hidden revisions)
   [255]
 
+Test ability to pull changeset with locally applying obsolescence markers
+(issue4945)
 
+  $ cd ..
+  $ hg init issue4845
+  $ cd issue4845
 
+  $ echo foo > f0
+  $ hg add f0
+  $ hg ci -m '0'
+  $ echo foo > f1
+  $ hg add f1
+  $ hg ci -m '1'
+  $ echo foo > f2
+  $ hg add f2
+  $ hg ci -m '2'
+
+  $ echo bar > f2
+  $ hg commit --amend --config experimetnal.evolution=createmarkers
+  $ hg log -G
+  @  4:b0551702f918 (draft) [tip ] 2
+  |
+  o  1:e016b03fd86f (draft) [ ] 1
+  |
+  o  0:a78f55e5508c (draft) [ ] 0
+  
+  $ hg log -G --hidden
+  @  4:b0551702f918 (draft) [tip ] 2
+  |
+  | x  3:f27abbcc1f77 (draft) [ ] temporary amend commit for e008cf283490
+  | |
+  | x  2:e008cf283490 (draft) [ ] 2
+  |/
+  o  1:e016b03fd86f (draft) [ ] 1
+  |
+  o  0:a78f55e5508c (draft) [ ] 0
+  
+
+  $ hg strip -r 1 --config extensions.strip=
+  0 files updated, 0 files merged, 2 files removed, 0 files unresolved
+  saved backup bundle to $TESTTMP/tmpe/issue4845/.hg/strip-backup/e016b03fd86f-c41c6bcc-backup.hg (glob)
+  $ hg log -G
+  @  0:a78f55e5508c (draft) [tip ] 0
+  
+  $ hg log -G --hidden
+  @  0:a78f55e5508c (draft) [tip ] 0
+  
+
+  $ hg pull .hg/strip-backup/*
+  pulling from .hg/strip-backup/e016b03fd86f-c41c6bcc-backup.hg
+  searching for changes
+  adding changesets
+  adding manifests
+  adding file changes
+  added 2 changesets with 2 changes to 2 files
+  (run 'hg update' to get a working copy)
+  $ hg log -G
+  o  2:b0551702f918 (draft) [tip ] 2
+  |
+  o  1:e016b03fd86f (draft) [ ] 1
+  |
+  @  0:a78f55e5508c (draft) [ ] 0
+  
+  $ hg log -G --hidden
+  o  2:b0551702f918 (draft) [tip ] 2
+  |
+  o  1:e016b03fd86f (draft) [ ] 1
+  |
+  @  0:a78f55e5508c (draft) [ ] 0
+  
+
--- a/tests/test-patchbomb.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-patchbomb.t	Wed Feb 24 15:55:44 2016 -0600
@@ -28,6 +28,9 @@
   $ echo "[extensions]" >> $HGRCPATH
   $ echo "patchbomb=" >> $HGRCPATH
 
+Ensure hg email output is sent to stdout
+  $ unset PAGER
+
   $ hg init t
   $ cd t
   $ echo a > a
--- a/tests/test-paths.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-paths.t	Wed Feb 24 15:55:44 2016 -0600
@@ -59,24 +59,24 @@
 formatter output with paths:
 
   $ echo 'dupe:pushurl = https://example.com/dupe' >> .hg/hgrc
-  $ hg paths -Tjson
+  $ hg paths -Tjson | sed 's|\\\\|\\|g'
   [
    {
     "name": "dupe",
     "pushurl": "https://example.com/dupe",
-    "url": "$TESTTMP/b#tip"
+    "url": "$TESTTMP/b#tip" (glob)
    },
    {
     "name": "expand",
-    "url": "$TESTTMP/a/$SOMETHING/bar"
+    "url": "$TESTTMP/a/$SOMETHING/bar" (glob)
    }
   ]
-  $ hg paths -Tjson dupe
+  $ hg paths -Tjson dupe | sed 's|\\\\|\\|g'
   [
    {
     "name": "dupe",
     "pushurl": "https://example.com/dupe",
-    "url": "$TESTTMP/b#tip"
+    "url": "$TESTTMP/b#tip" (glob)
    }
   ]
   $ hg paths -Tjson -q unknown
--- a/tests/test-progress.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-progress.t	Wed Feb 24 15:55:44 2016 -0600
@@ -79,6 +79,12 @@
 no progress with --quiet
   $ hg -y loop 3 --quiet
 
+test plain mode exception
+  $ HGPLAINEXCEPT=progress hg -y loop 1
+  \r (no-eol) (esc)
+  loop [                                                ] 0/1\r (no-eol) (esc)
+                                                              \r (no-eol) (esc)
+
 test nested short-lived topics (which shouldn't display with nestdelay):
 
   $ hg -y loop 3 --nested
--- a/tests/test-pull-branch.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-pull-branch.t	Wed Feb 24 15:55:44 2016 -0600
@@ -133,6 +133,7 @@
   adding file changes
   added 4 changesets with 4 changes to 1 files (+1 heads)
   1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  1 other heads for branch "branchA"
 
 Make changes on new branch on tt
 
--- a/tests/test-pull-update.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-pull-update.t	Wed Feb 24 15:55:44 2016 -0600
@@ -16,7 +16,7 @@
   $ echo 1.2 > foo
   $ hg ci -Am m
 
-Should not update:
+Should not update to the other topological branch:
 
   $ hg pull -u ../tt
   pulling from ../tt
@@ -25,13 +25,12 @@
   adding manifests
   adding file changes
   added 1 changesets with 1 changes to 1 files (+1 heads)
-  abort: not updating: not a linear update
-  (merge or update --check to force update)
-  [255]
+  0 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  1 other heads for branch "default"
 
   $ cd ../tt
 
-Should not update:
+Should not update to the other branch:
 
   $ hg pull -u ../t
   pulling from ../t
@@ -40,9 +39,8 @@
   adding manifests
   adding file changes
   added 1 changesets with 1 changes to 1 files (+1 heads)
-  abort: not updating: not a linear update
-  (merge or update --check to force update)
-  [255]
+  0 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  1 other heads for branch "default"
 
   $ HGMERGE=true hg merge
   merging foo
--- a/tests/test-push-validation.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-push-validation.t	Wed Feb 24 15:55:44 2016 -0600
@@ -72,7 +72,7 @@
   checking manifests
   crosschecking files in changesets and manifests
   checking files
-   beta@1: dddc47b3ba30 in manifests not found
+   beta@1: manifest refers to unknown revision dddc47b3ba30
   2 files, 2 changesets, 2 total revisions
   1 integrity errors encountered!
   (first damaged changeset appears to be 1)
--- a/tests/test-rebase-abort.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-rebase-abort.t	Wed Feb 24 15:55:44 2016 -0600
@@ -76,6 +76,7 @@
   local: 3e046f2ecedb793b97ed32108086edd1a162f8bc
   other: 46f0b057b5c061d276b91491c22151f78698abd2
   unrecognized entry: x	advisory record
+  file extras: common (ancestorlinknode = 3163e20567cc93074fbb7a53c8b93312e59dbf2c)
   file: common (record type "F", state "u", hash 94c8c21d08740f5da9eaa38d1f175c592692f0d1)
     local path: common (flags "")
     ancestor path: common (node de0a666fdd9c1a0b0698b90d85064d8bd34f74b6)
@@ -90,6 +91,7 @@
   * version 2 records
   local: 3e046f2ecedb793b97ed32108086edd1a162f8bc
   other: 46f0b057b5c061d276b91491c22151f78698abd2
+  file extras: common (ancestorlinknode = 3163e20567cc93074fbb7a53c8b93312e59dbf2c)
   file: common (record type "F", state "u", hash 94c8c21d08740f5da9eaa38d1f175c592692f0d1)
     local path: common (flags "")
     ancestor path: common (node de0a666fdd9c1a0b0698b90d85064d8bd34f74b6)
@@ -428,6 +430,7 @@
   commit: (clean)
   update: 1 new changesets, 2 branch heads (merge)
   phases: 4 draft
+  $ cd ..
 
 test aborting a rebase succeeds after rebasing with skipped commits onto a
 public changeset (issue4896)
@@ -461,4 +464,5 @@
   [1]
   $ hg rebase --abort
   rebase aborted
+  $ cd ..
 
--- a/tests/test-rebase-bookmarks.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-rebase-bookmarks.t	Wed Feb 24 15:55:44 2016 -0600
@@ -167,7 +167,7 @@
   created new head
   $ hg up 3
   1 files updated, 0 files merged, 0 files removed, 0 files unresolved
-  $ hg rebase
+  $ hg rebase --dest 4
   rebasing 3:3d5fa227f4b5 "C" (Y Z)
   merging c
   warning: conflicts while merging c! (edit, then use 'hg resolve --mark')
--- a/tests/test-rebase-collapse.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-rebase-collapse.t	Wed Feb 24 15:55:44 2016 -0600
@@ -58,7 +58,7 @@
   > echo "===="
   > echo "edited manually" >> \$1
   > EOF
-  $ HGEDITOR="sh $TESTTMP/editor.sh" hg rebase --collapse --keepbranches -e
+  $ HGEDITOR="sh $TESTTMP/editor.sh" hg rebase --collapse --keepbranches -e --dest 7
   rebasing 1:42ccdea3bb16 "B"
   rebasing 2:5fddd98957c8 "C"
   rebasing 3:32af7686d403 "D"
@@ -115,7 +115,7 @@
   $ cd a2
 
   $ hg phase --force --secret 6
-  $ hg rebase --source 4 --collapse
+  $ hg rebase --source 4 --collapse --dest 7
   rebasing 4:9520eea781bc "E"
   rebasing 6:eea13746799a "G"
   saved backup bundle to $TESTTMP/a2/.hg/strip-backup/9520eea781bc-fcd8edd4-backup.hg (glob)
@@ -157,7 +157,7 @@
   > env | grep HGEDITFORM
   > true
   > EOF
-  $ HGEDITOR="sh $TESTTMP/checkeditform.sh" hg rebase --source 4 --collapse -m 'custom message' -e
+  $ HGEDITOR="sh $TESTTMP/checkeditform.sh" hg rebase --source 4 --collapse -m 'custom message' -e --dest 7
   rebasing 4:9520eea781bc "E"
   rebasing 6:eea13746799a "G"
   HGEDITFORM=rebase.collapse
@@ -261,13 +261,13 @@
   $ hg clone -q -u . b b1
   $ cd b1
 
-  $ hg rebase -s 2 --collapse
+  $ hg rebase -s 2 --dest 7 --collapse
   abort: unable to collapse on top of 7, there is more than one external parent: 1, 5
   [255]
 
 Rebase and collapse - E onto H:
 
-  $ hg rebase -s 4 --collapse # root (4) is not a merge
+  $ hg rebase -s 4 --dest 7 --collapse # root (4) is not a merge
   rebasing 4:8a5212ebc852 "E"
   rebasing 5:7f219660301f "F"
   rebasing 6:c772a8b2dc17 "G"
@@ -418,7 +418,7 @@
   $ hg clone -q -u . c c1
   $ cd c1
 
-  $ hg rebase -s 4 --collapse # root (4) is not a merge
+  $ hg rebase -s 4 --dest 8 --collapse # root (4) is not a merge
   rebasing 4:8a5212ebc852 "E"
   rebasing 5:dca5924bb570 "F"
   merging E
@@ -512,7 +512,7 @@
   $ hg clone -q -u . d d1
   $ cd d1
 
-  $ hg rebase -s 1 --collapse
+  $ hg rebase -s 1 --collapse --dest 5
   rebasing 1:27547f69f254 "B"
   rebasing 2:f838bfaca5c7 "C"
   rebasing 3:7bbcd6078bcc "D"
@@ -804,3 +804,52 @@
   base
 
   $ cd ..
+
+Test that rebase --collapse will remember message after
+running into merge conflict and invoking rebase --continue.
+
+  $ hg init collapse_remember_message
+  $ cd collapse_remember_message
+  $ touch a
+  $ hg add a
+  $ hg commit -m "a"
+  $ echo "a-default" > a
+  $ hg commit -m "a-default"
+  $ hg update -r 0
+  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  $ hg branch dev
+  marked working directory as branch dev
+  (branches are permanent and global, did you want a bookmark?)
+  $ echo "a-dev" > a
+  $ hg commit -m "a-dev"
+  $ hg rebase --collapse -m "a-default-dev" -d 1
+  rebasing 2:b8d8db2b242d "a-dev" (tip)
+  merging a
+  warning: conflicts while merging a! (edit, then use 'hg resolve --mark')
+  unresolved conflicts (see hg resolve, then hg rebase --continue)
+  [1]
+  $ rm a.orig
+  $ hg resolve --mark a
+  (no more unresolved files)
+  continue: hg rebase --continue
+  $ hg rebase --continue
+  rebasing 2:b8d8db2b242d "a-dev" (tip)
+  saved backup bundle to $TESTTMP/collapse_remember_message/.hg/strip-backup/b8d8db2b242d-f474c19a-backup.hg (glob)
+  $ hg log
+  changeset:   2:12bb766dceb1
+  tag:         tip
+  user:        test
+  date:        Thu Jan 01 00:00:00 1970 +0000
+  summary:     a-default-dev
+  
+  changeset:   1:3c8db56a44bc
+  user:        test
+  date:        Thu Jan 01 00:00:00 1970 +0000
+  summary:     a-default
+  
+  changeset:   0:3903775176ed
+  user:        test
+  date:        Thu Jan 01 00:00:00 1970 +0000
+  summary:     a
+  
+  $ cd ..
--- a/tests/test-rebase-conflicts.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-rebase-conflicts.t	Wed Feb 24 15:55:44 2016 -0600
@@ -305,3 +305,55 @@
   rebase completed
   updating the branch cache
   truncating cache/rbc-revs-v1 to 72
+
+Test minimization of merge conflicts
+  $ hg up -q null
+  $ echo a > a
+  $ hg add a
+  $ hg commit -q -m 'a'
+  $ echo b >> a
+  $ hg commit -q -m 'ab'
+  $ hg bookmark ab
+  $ hg up -q '.^'
+  $ echo b >> a
+  $ echo c >> a
+  $ hg commit -q -m 'abc'
+  $ hg rebase -s 7bc217434fc1 -d ab --keep
+  rebasing 13:7bc217434fc1 "abc" (tip)
+  merging a
+  warning: conflicts while merging a! (edit, then use 'hg resolve --mark')
+  unresolved conflicts (see hg resolve, then hg rebase --continue)
+  [1]
+  $ hg diff
+  diff -r 328e4ab1f7cc a
+  --- a/a	Thu Jan 01 00:00:00 1970 +0000
+  +++ b/a	* (glob)
+  @@ -1,2 +1,6 @@
+   a
+   b
+  +<<<<<<< dest:   328e4ab1f7cc  ab - test: ab
+  +=======
+  +c
+  +>>>>>>> source: 7bc217434fc1 - test: abc
+  $ hg rebase --abort
+  rebase aborted
+  $ hg up -q -C 7bc217434fc1
+  $ hg rebase -s . -d ab --keep -t internal:merge3
+  rebasing 13:7bc217434fc1 "abc" (tip)
+  merging a
+  warning: conflicts while merging a! (edit, then use 'hg resolve --mark')
+  unresolved conflicts (see hg resolve, then hg rebase --continue)
+  [1]
+  $ hg diff
+  diff -r 328e4ab1f7cc a
+  --- a/a	Thu Jan 01 00:00:00 1970 +0000
+  +++ b/a	* (glob)
+  @@ -1,2 +1,8 @@
+   a
+  +<<<<<<< dest:   328e4ab1f7cc  ab - test: ab
+   b
+  +||||||| base
+  +=======
+  +b
+  +c
+  +>>>>>>> source: 7bc217434fc1 - test: abc
--- a/tests/test-rebase-named-branches.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-rebase-named-branches.t	Wed Feb 24 15:55:44 2016 -0600
@@ -327,14 +327,13 @@
 
   $ hg up -qr 2
   $ hg rebase
-  nothing to rebase - working directory parent is also destination
-  [1]
+  rebasing 2:792845bb77ee "b2"
+  note: rebase of 2:792845bb77ee created no changes to commit
+  saved backup bundle to $TESTTMP/case1/.hg/strip-backup/792845bb77ee-627120ee-backup.hg (glob)
   $ hg tglog
-  o  3: 'c1' c
+  o  2: 'c1' c
   |
-  | @  2: 'b2' b
-  |/
-  | o  1: 'b1' b
+  | @  1: 'b1' b
   |/
   o  0: '0'
   
@@ -373,8 +372,9 @@
   o  0: '0'
   
   $ hg rebase
-  nothing to rebase - working directory parent is also destination
-  [1]
+  abort: branch 'c' has one head - please rebase to an explicit rev
+  (run 'hg heads' to see all heads)
+  [255]
   $ hg tglog
   _  4: 'c2 closed' c
   |
--- a/tests/test-rebase-obsolete.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-rebase-obsolete.t	Wed Feb 24 15:55:44 2016 -0600
@@ -771,7 +771,7 @@
   phases: 8 draft
   unstable: 1 changesets
   $ hg rebase -s 10 -d 12
-  abort: this rebase will cause divergence
+  abort: this rebase will cause divergences from: 121d9e3bc4c6
   (to force the rebase please set rebase.allowdivergence=True)
   [255]
   $ hg log -G
--- a/tests/test-rebase-parameters.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-rebase-parameters.t	Wed Feb 24 15:55:44 2016 -0600
@@ -46,11 +46,14 @@
   
   $ cd ..
 
+Version with only two heads (to allow default destination to work)
+
+  $ hg clone -q -u . a a2heads -r 3 -r 8
 
 These fail:
 
-  $ hg clone -q -u . a a1
-  $ cd a1
+  $ hg clone -q -u . a a0
+  $ cd a0
 
   $ hg rebase -s 8 -d 7
   nothing to rebase
@@ -79,33 +82,38 @@
   abort: cannot specify both a revision and a base
   [255]
 
-  $ hg rebase --rev '1 & !1'
+  $ hg rebase --base 6
+  abort: branch 'default' has 3 heads - please rebase to an explicit rev
+  (run 'hg heads .' to see heads)
+  [255]
+
+  $ hg rebase --rev '1 & !1' --dest 8
   empty "rev" revision set - nothing to rebase
   [1]
 
-  $ hg rebase --source '1 & !1'
+  $ hg rebase --source '1 & !1' --dest 8
   empty "source" revision set - nothing to rebase
   [1]
 
-  $ hg rebase --base '1 & !1'
+  $ hg rebase --base '1 & !1' --dest 8
   empty "base" revision set - can't compute rebase set
   [1]
 
-  $ hg rebase
+  $ hg rebase --dest 8
   nothing to rebase - working directory parent is also destination
   [1]
 
-  $ hg rebase -b.
+  $ hg rebase -b . --dest 8
   nothing to rebase - e7ec4e813ba6 is both "base" and destination
   [1]
 
   $ hg up -q 7
 
-  $ hg rebase --traceback
+  $ hg rebase --dest 8 --traceback
   nothing to rebase - working directory parent is already an ancestor of destination e7ec4e813ba6
   [1]
 
-  $ hg rebase -b.
+  $ hg rebase --dest 8 -b.
   nothing to rebase - "base" 02de42196ebe is already an ancestor of destination e7ec4e813ba6
   [1]
 
@@ -117,6 +125,9 @@
 
 Rebase with no arguments (from 3 onto 8):
 
+  $ cd ..
+  $ hg clone -q -u . a2heads a1
+  $ cd a1
   $ hg up -q -C 3
 
   $ hg rebase
@@ -126,22 +137,18 @@
   saved backup bundle to $TESTTMP/a1/.hg/strip-backup/42ccdea3bb16-3cb021d3-backup.hg (glob)
 
   $ hg tglog
-  @  8: 'D'
-  |
-  o  7: 'C'
+  @  6: 'D'
   |
-  o  6: 'B'
+  o  5: 'C'
   |
-  o  5: 'I'
+  o  4: 'B'
   |
-  o  4: 'H'
+  o  3: 'I'
   |
-  | o  3: 'G'
-  |/|
-  o |  2: 'F'
-  | |
-  | o  1: 'E'
-  |/
+  o  2: 'H'
+  |
+  o  1: 'F'
+  |
   o  0: 'A'
   
 Try to rollback after a rebase (fail):
@@ -154,7 +161,7 @@
 
 Rebase with base == '.' => same as no arguments (from 3 onto 8):
 
-  $ hg clone -q -u 3 a a2
+  $ hg clone -q -u 3 a2heads a2
   $ cd a2
 
   $ hg rebase --base .
@@ -164,22 +171,18 @@
   saved backup bundle to $TESTTMP/a2/.hg/strip-backup/42ccdea3bb16-3cb021d3-backup.hg (glob)
 
   $ hg tglog
-  @  8: 'D'
-  |
-  o  7: 'C'
+  @  6: 'D'
   |
-  o  6: 'B'
+  o  5: 'C'
   |
-  o  5: 'I'
+  o  4: 'B'
   |
-  o  4: 'H'
+  o  3: 'I'
   |
-  | o  3: 'G'
-  |/|
-  o |  2: 'F'
-  | |
-  | o  1: 'E'
-  |/
+  o  2: 'H'
+  |
+  o  1: 'F'
+  |
   o  0: 'A'
   
   $ cd ..
@@ -220,7 +223,7 @@
 
 Specify only source (from 2 onto 8):
 
-  $ hg clone -q -u . a a4
+  $ hg clone -q -u . a2heads a4
   $ cd a4
 
   $ hg rebase --source 'desc("C")'
@@ -229,20 +232,16 @@
   saved backup bundle to $TESTTMP/a4/.hg/strip-backup/5fddd98957c8-f9244fa1-backup.hg (glob)
 
   $ hg tglog
-  o  8: 'D'
+  o  6: 'D'
   |
-  o  7: 'C'
-  |
-  @  6: 'I'
+  o  5: 'C'
   |
-  o  5: 'H'
+  @  4: 'I'
   |
-  | o  4: 'G'
-  |/|
-  o |  3: 'F'
-  | |
-  | o  2: 'E'
-  |/
+  o  3: 'H'
+  |
+  o  2: 'F'
+  |
   | o  1: 'B'
   |/
   o  0: 'A'
@@ -285,7 +284,7 @@
 
 Specify only base (from 1 onto 8):
 
-  $ hg clone -q -u . a a6
+  $ hg clone -q -u . a2heads a6
   $ cd a6
 
   $ hg rebase --base 'desc("D")'
@@ -295,22 +294,18 @@
   saved backup bundle to $TESTTMP/a6/.hg/strip-backup/42ccdea3bb16-3cb021d3-backup.hg (glob)
 
   $ hg tglog
-  o  8: 'D'
-  |
-  o  7: 'C'
+  o  6: 'D'
   |
-  o  6: 'B'
+  o  5: 'C'
   |
-  @  5: 'I'
+  o  4: 'B'
   |
-  o  4: 'H'
+  @  3: 'I'
   |
-  | o  3: 'G'
-  |/|
-  o |  2: 'F'
-  | |
-  | o  1: 'E'
-  |/
+  o  2: 'H'
+  |
+  o  1: 'F'
+  |
   o  0: 'A'
   
   $ cd ..
@@ -383,7 +378,7 @@
 
 Specify only revs (from 2 onto 8)
 
-  $ hg clone -q -u . a a9
+  $ hg clone -q -u . a2heads a9
   $ cd a9
 
   $ hg rebase --rev 'desc("C")::'
@@ -392,20 +387,16 @@
   saved backup bundle to $TESTTMP/a9/.hg/strip-backup/5fddd98957c8-f9244fa1-backup.hg (glob)
 
   $ hg tglog
-  o  8: 'D'
+  o  6: 'D'
   |
-  o  7: 'C'
-  |
-  @  6: 'I'
+  o  5: 'C'
   |
-  o  5: 'H'
+  @  4: 'I'
   |
-  | o  4: 'G'
-  |/|
-  o |  3: 'F'
-  | |
-  | o  2: 'E'
-  |/
+  o  3: 'H'
+  |
+  o  2: 'F'
+  |
   | o  1: 'B'
   |/
   o  0: 'A'
@@ -416,7 +407,7 @@
 
   $ hg clone -q -u . a aX
   $ cd aX
-  $ hg rebase -r 3 -r 6
+  $ hg rebase -r 3 -r 6 --dest 8
   rebasing 3:32af7686d403 "D"
   rebasing 6:eea13746799a "G"
   saved backup bundle to $TESTTMP/aX/.hg/strip-backup/eea13746799a-ad273fd6-backup.hg (glob)
@@ -495,6 +486,10 @@
   $ hg resolve -m c2
   (no more unresolved files)
   continue: hg rebase --continue
+  $ hg graft --continue
+  abort: no graft in progress
+  (continue: hg rebase --continue)
+  [255]
   $ hg rebase -c --tool internal:fail
   rebasing 2:e4e3f3546619 "c2b" (tip)
   note: rebase of 2:e4e3f3546619 created no changes to commit
--- a/tests/test-rebase-pull.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-rebase-pull.t	Wed Feb 24 15:55:44 2016 -0600
@@ -85,7 +85,7 @@
   adding manifests
   adding file changes
   added 1 changesets with 1 changes to 1 files
-  nothing to rebase - working directory parent is already an ancestor of destination 77ae9631bcca
+  nothing to rebase - updating instead
   1 files updated, 0 files merged, 0 files removed, 0 files unresolved
   updating bookmark norebase
 
@@ -209,3 +209,103 @@
   |
   o  0: 'C1'
   
+
+pull --rebase only update if there is nothing to rebase
+
+  $ cd ../a
+  $ echo R5 > R5
+  $ hg ci -Am R5
+  adding R5
+  $ hg tglog
+  @  6: 'R5'
+  |
+  o  5: 'R4'
+  |
+  o  4: 'R3'
+  |
+  o  3: 'R2'
+  |
+  o  2: 'R1'
+  |
+  o  1: 'C2'
+  |
+  o  0: 'C1'
+  
+  $ cd ../c
+  $ echo L2 > L2
+  $ hg ci -Am L2
+  adding L2
+  $ hg up 'desc(L1)'
+  0 files updated, 0 files merged, 1 files removed, 0 files unresolved
+  $ hg pull --rebase
+  pulling from $TESTTMP/a (glob)
+  searching for changes
+  adding changesets
+  adding manifests
+  adding file changes
+  added 1 changesets with 1 changes to 1 files (+1 heads)
+  rebasing 6:0d0727eb7ce0 "L1"
+  rebasing 7:c1f58876e3bf "L2"
+  saved backup bundle to $TESTTMP/c/.hg/strip-backup/0d0727eb7ce0-ef61ccb2-backup.hg (glob)
+  $ hg tglog
+  o  8: 'L2'
+  |
+  @  7: 'L1'
+  |
+  o  6: 'R5'
+  |
+  o  5: 'R4'
+  |
+  o  4: 'R3'
+  |
+  o  3: 'R2'
+  |
+  o  2: 'R1'
+  |
+  o  1: 'C2'
+  |
+  o  0: 'C1'
+  
+
+pull --rebase update (no rebase) use proper update:
+
+- warn about other head.
+
+  $ cd ../a
+  $ echo R6 > R6
+  $ hg ci -Am R6
+  adding R6
+  $ cd ../c
+  $ hg up 'desc(R5)'
+  0 files updated, 0 files merged, 1 files removed, 0 files unresolved
+  $ hg pull --rebase
+  pulling from $TESTTMP/a (glob)
+  searching for changes
+  adding changesets
+  adding manifests
+  adding file changes
+  added 1 changesets with 1 changes to 1 files (+1 heads)
+  nothing to rebase - updating instead
+  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  1 other heads for branch "default"
+  $ hg tglog
+  @  9: 'R6'
+  |
+  | o  8: 'L2'
+  | |
+  | o  7: 'L1'
+  |/
+  o  6: 'R5'
+  |
+  o  5: 'R4'
+  |
+  o  4: 'R3'
+  |
+  o  3: 'R2'
+  |
+  o  2: 'R1'
+  |
+  o  1: 'C2'
+  |
+  o  0: 'C1'
+  
--- a/tests/test-rebase-scenario-global.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-rebase-scenario-global.t	Wed Feb 24 15:55:44 2016 -0600
@@ -25,7 +25,8 @@
 
 Rebasing
 D onto H - simple rebase:
-(this also tests that editor is invoked if '--edit' is specified)
+(this also tests that editor is invoked if '--edit' is specified, and that we
+can abort or warn for colliding untracked files)
 
   $ hg clone -q -u . a a1
   $ cd a1
@@ -50,8 +51,10 @@
 
   $ hg status --rev "3^1" --rev 3
   A D
-  $ HGEDITOR=cat hg rebase -s 3 -d 7 --edit
+  $ echo collide > D
+  $ HGEDITOR=cat hg rebase -s 3 -d 7 --edit --config merge.checkunknown=warn
   rebasing 3:32af7686d403 "D"
+  D: replacing untracked file
   D
   
   
@@ -62,6 +65,9 @@
   HG: branch 'default'
   HG: added D
   saved backup bundle to $TESTTMP/a1/.hg/strip-backup/32af7686d403-6f7dface-backup.hg (glob)
+  $ cat D.orig
+  collide
+  $ rm D.orig
 
   $ hg tglog
   o  7: 'D'
@@ -84,14 +90,19 @@
 
 
 D onto F - intermediate point:
-(this also tests that editor is not invoked if '--edit' is not specified)
+(this also tests that editor is not invoked if '--edit' is not specified, and
+that we can ignore for colliding untracked files)
 
   $ hg clone -q -u . a a2
   $ cd a2
+  $ echo collide > D
 
-  $ HGEDITOR=cat hg rebase -s 3 -d 5
+  $ HGEDITOR=cat hg rebase -s 3 -d 5 --config merge.checkunknown=ignore
   rebasing 3:32af7686d403 "D"
   saved backup bundle to $TESTTMP/a2/.hg/strip-backup/32af7686d403-6f7dface-backup.hg (glob)
+  $ cat D.orig
+  collide
+  $ rm D.orig
 
   $ hg tglog
   o  7: 'D'
@@ -114,15 +125,21 @@
 
 
 E onto H - skip of G:
+(this also tests that we can overwrite untracked files and don't create backups
+if they have the same contents)
 
   $ hg clone -q -u . a a3
   $ cd a3
+  $ hg cat -r 4 E | tee E
+  E
 
   $ hg rebase -s 4 -d 7
   rebasing 4:9520eea781bc "E"
   rebasing 6:eea13746799a "G"
   note: rebase of 6:eea13746799a created no changes to commit
   saved backup bundle to $TESTTMP/a3/.hg/strip-backup/9520eea781bc-fcd8edd4-backup.hg (glob)
+  $ f E.orig
+  E.orig: file not found
 
   $ hg tglog
   o  6: 'E'
@@ -745,12 +762,73 @@
   saved backup bundle to $TESTTMP/cwd-vanish/.hg/strip-backup/779a07b1b7a0-853e0073-backup.hg (glob)
 
 Test experimental revset
+========================
 
   $ cd ..
+
+Make the repo a bit more interresting
+
+  $ hg up 1
+  0 files updated, 0 files merged, 2 files removed, 0 files unresolved
+  $ echo aaa > aaa
+  $ hg add aaa
+  $ hg commit -m aaa
+  created new head
+  $ hg log -G
+  @  changeset:   4:5f7bc9025ed2
+  |  tag:         tip
+  |  parent:      1:58d79cc1cf43
+  |  user:        test
+  |  date:        Thu Jan 01 00:00:00 1970 +0000
+  |  summary:     aaa
+  |
+  | o  changeset:   3:1910d5ff34ea
+  | |  user:        test
+  | |  date:        Thu Jan 01 00:00:00 1970 +0000
+  | |  summary:     second source with subdir
+  | |
+  | o  changeset:   2:82901330b6ef
+  |/   user:        test
+  |    date:        Thu Jan 01 00:00:00 1970 +0000
+  |    summary:     first source commit
+  |
+  o  changeset:   1:58d79cc1cf43
+  |  user:        test
+  |  date:        Thu Jan 01 00:00:00 1970 +0000
+  |  summary:     dest commit
+  |
+  o  changeset:   0:e94b687f7da3
+     user:        test
+     date:        Thu Jan 01 00:00:00 1970 +0000
+     summary:     initial commit
+  
+
+Testing from lower head
+
+  $ hg up 3
+  2 files updated, 0 files merged, 1 files removed, 0 files unresolved
   $ hg log -r '_destrebase()'
+  changeset:   4:5f7bc9025ed2
+  tag:         tip
+  parent:      1:58d79cc1cf43
+  user:        test
+  date:        Thu Jan 01 00:00:00 1970 +0000
+  summary:     aaa
+  
+
+Testing from upper head
+
+  $ hg log -r '_destrebase(4)'
   changeset:   3:1910d5ff34ea
-  tag:         tip
   user:        test
   date:        Thu Jan 01 00:00:00 1970 +0000
   summary:     second source with subdir
   
+  $ hg up 4
+  1 files updated, 0 files merged, 2 files removed, 0 files unresolved
+  $ hg log -r '_destrebase()'
+  changeset:   3:1910d5ff34ea
+  user:        test
+  date:        Thu Jan 01 00:00:00 1970 +0000
+  summary:     second source with subdir
+  
--- a/tests/test-repair-strip.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-repair-strip.t	Wed Feb 24 15:55:44 2016 -0600
@@ -1,5 +1,12 @@
 #require unix-permissions no-root
 
+  $ cat > $TESTTMP/dumpjournal.py <<EOF
+  > import sys
+  > for entry in sys.stdin.read().split('\n'):
+  >     if entry:
+  >         print entry.split('\x00')[0]
+  > EOF
+
   $ echo "[extensions]" >> $HGRCPATH
   $ echo "mq=">> $HGRCPATH
 
@@ -14,7 +21,7 @@
   >   hg verify
   >   echo % journal contents
   >   if [ -f .hg/store/journal ]; then
-  >       sed -e 's/\.i[^\n]*/\.i/' .hg/store/journal
+  >       cat .hg/store/journal | python $TESTTMP/dumpjournal.py
   >   else
   >       echo "(no journal)"
   >   fi
--- a/tests/test-resolve.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-resolve.t	Wed Feb 24 15:55:44 2016 -0600
@@ -263,10 +263,12 @@
   local: 57653b9f834a4493f7240b0681efcb9ae7cab745
   other: dc77451844e37f03f5c559e3b8529b2b48d381d1
   unrecognized entry: x	advisory record
+  file extras: file1 (ancestorlinknode = 99726c03216e233810a2564cbc0adfe395007eac)
   file: file1 (record type "F", state "r", hash 60b27f004e454aca81b0480209cce5081ec52390)
     local path: file1 (flags "")
     ancestor path: file1 (node 2ed2a3912a0b24502043eae84ee4b279c18b90dd)
     other path: file1 (node 6f4310b00b9a147241b071a60c28a650827fb03d)
+  file extras: file2 (ancestorlinknode = 99726c03216e233810a2564cbc0adfe395007eac)
   file: file2 (record type "F", state "u", hash cb99b709a1978bd205ab9dfd4c5aaa1fc91c7523)
     local path: file2 (flags "")
     ancestor path: file2 (node 2ed2a3912a0b24502043eae84ee4b279c18b90dd)
@@ -282,10 +284,12 @@
   * version 2 records
   local: 57653b9f834a4493f7240b0681efcb9ae7cab745
   other: dc77451844e37f03f5c559e3b8529b2b48d381d1
+  file extras: file1 (ancestorlinknode = 99726c03216e233810a2564cbc0adfe395007eac)
   file: file1 (record type "F", state "r", hash 60b27f004e454aca81b0480209cce5081ec52390)
     local path: file1 (flags "")
     ancestor path: file1 (node 2ed2a3912a0b24502043eae84ee4b279c18b90dd)
     other path: file1 (node 6f4310b00b9a147241b071a60c28a650827fb03d)
+  file extras: file2 (ancestorlinknode = 99726c03216e233810a2564cbc0adfe395007eac)
   file: file2 (record type "F", state "u", hash cb99b709a1978bd205ab9dfd4c5aaa1fc91c7523)
     local path: file2 (flags "")
     ancestor path: file2 (node 2ed2a3912a0b24502043eae84ee4b279c18b90dd)
--- a/tests/test-revert-interactive.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-revert-interactive.t	Wed Feb 24 15:55:44 2016 -0600
@@ -15,6 +15,7 @@
   > interactive = true
   > [extensions]
   > record =
+  > purge = 
   > EOF
 
 
@@ -377,3 +378,26 @@
    5
    d
   +lastline
+
+  $ hg update -C .
+  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  $ hg purge
+  $ touch newfile
+  $ hg add newfile
+  $ hg status
+  A newfile
+  $ hg revert -i <<EOF
+  > n
+  > EOF
+  forgetting newfile
+  forget added file newfile (yn)? n
+  $ hg status
+  A newfile
+  $ hg revert -i <<EOF
+  > y
+  > EOF
+  forgetting newfile
+  forget added file newfile (yn)? y
+  $ hg status
+  ? newfile
+
--- a/tests/test-revset.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-revset.t	Wed Feb 24 15:55:44 2016 -0600
@@ -693,12 +693,11 @@
   * optimized:
   (func
     ('symbol', 'only')
-    (and
+    (difference
       (range
         ('symbol', '8')
         ('symbol', '9'))
-      (not
-        ('symbol', '8'))))
+      ('symbol', '8')))
   * set:
   <baseset+ [8, 9]>
   8
@@ -1230,7 +1229,7 @@
 test that chained `or` operations never eat up stack (issue4624)
 (uses `0:1` instead of `0` to avoid future optimization of trivial revisions)
 
-  $ hg log -T '{rev}\n' -r "`python -c "print '|'.join(['0:1'] * 500)"`"
+  $ hg log -T '{rev}\n' -r `python -c "print '+'.join(['0:1'] * 500)"`
   0
   1
 
--- a/tests/test-run-tests.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-run-tests.t	Wed Feb 24 15:55:44 2016 -0600
@@ -21,6 +21,27 @@
   >     run-tests.py --with-hg=`which hg` "$@"
   > }
 
+error paths
+
+#if symlink
+  $ ln -s `which true` hg
+  $ run-tests.py --with-hg=./hg
+  warning: --with-hg should specify an hg script
+  
+  # Ran 0 tests, 0 skipped, 0 warned, 0 failed.
+  $ rm hg
+#endif
+
+#if execbit
+  $ touch hg
+  $ run-tests.py --with-hg=./hg
+  Usage: run-tests.py [options] [tests]
+  
+  run-tests.py: error: --with-hg must specify an executable hg script
+  [2]
+  $ rm hg
+#endif
+
 a succesful test
 =======================
 
@@ -509,8 +530,6 @@
           "result": "skip"
       }
   } (no-eol)
-#if json
-
 test for --json
 ==================
 
@@ -613,8 +632,6 @@
   } (no-eol)
   $ mv backup test-failure.t
 
-#endif
-
 backslash on end of line with glob matching is handled properly
 
   $ cat > test-glob-backslash.t << EOF
@@ -701,3 +718,13 @@
   $ rt $HGTEST_RUN_TESTS_PURE --allow-slow-tests test-very-slow-test.t
   .
   # Ran 1 tests, 0 skipped, 0 warned, 0 failed.
+
+support for running a test outside the current directory
+  $ mkdir nonlocal
+  $ cat > nonlocal/test-is-not-here.t << EOF
+  >   $ echo pass
+  >   pass
+  > EOF
+  $ rt nonlocal/test-is-not-here.t
+  .
+  # Ran 1 tests, 0 skipped, 0 warned, 0 failed.
--- a/tests/test-schemes.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-schemes.t	Wed Feb 24 15:55:44 2016 -0600
@@ -52,6 +52,21 @@
   no changes found
   [1]
 
+check that debugexpandscheme outputs the canonical form
+
+  $ hg debugexpandscheme bb://user/repo
+  https://bitbucket.org/user/repo
+
+expanding an unknown scheme emits the input
+
+  $ hg debugexpandscheme foobar://this/that
+  foobar://this/that
+
+expanding a canonical URL emits the input
+
+  $ hg debugexpandscheme https://bitbucket.org/user/repo
+  https://bitbucket.org/user/repo
+
 errors
 
   $ cat errors.log
--- a/tests/test-shelve.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-shelve.t	Wed Feb 24 15:55:44 2016 -0600
@@ -373,7 +373,7 @@
 try to continue with no unshelve underway
 
   $ hg unshelve -c
-  abort: no unshelve operation underway
+  abort: no unshelve in progress
   [255]
   $ hg status
   A foo/foo
@@ -403,6 +403,10 @@
   (use 'hg unshelve --continue' or 'hg unshelve --abort')
   [255]
 
+  $ hg graft --continue
+  abort: no graft in progress
+  (continue: hg unshelve --continue)
+  [255]
   $ hg unshelve -c
   rebasing 5:32c69314e062 "changes to: [mq]: second.patch" (tip)
   unshelve of 'default' complete
--- a/tests/test-strip.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-strip.t	Wed Feb 24 15:55:44 2016 -0600
@@ -287,6 +287,7 @@
 
   $ hg up
   1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  1 other heads for branch "default"
   $ hg log -G
   @  changeset:   4:264128213d29
   |  tag:         tip
--- a/tests/test-subrepo-deep-nested-change.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-subrepo-deep-nested-change.t	Wed Feb 24 15:55:44 2016 -0600
@@ -1,3 +1,9 @@
+  $ cat >> $HGRCPATH <<EOF
+  > [extdiff]
+  > # for portability:
+  > pdiff = sh "$RUNTESTDIR/pdiff"
+  > EOF
+
 Preparing the subrepository 'sub2'
 
   $ hg init sub2
@@ -711,92 +717,92 @@
 
 Interaction with extdiff, largefiles and subrepos
 
-  $ hg --config extensions.extdiff= extdiff -S
+  $ hg --config extensions.extdiff= pdiff -S
 
-  $ hg --config extensions.extdiff= extdiff -r '.^' -S
-  diff -Npru cloned.*/.hgsub cloned/.hgsub (glob)
-  --- cloned.*/.hgsub	* +0000 (glob)
-  +++ cloned/.hgsub	* +0000 (glob)
-  @@ -1,2 +1 @@
+  $ hg --config extensions.extdiff= pdiff -r '.^' -S
+  diff -Nru cloned.*/.hgsub cloned/.hgsub (glob)
+  --- cloned.*/.hgsub	* (glob)
+  +++ cloned/.hgsub	* (glob)
+  @@ -1,2 +1* @@ (glob)
    sub1 = ../sub1
   -sub3 = sub3
-  diff -Npru cloned.*/.hgsubstate cloned/.hgsubstate (glob)
-  --- cloned.*/.hgsubstate	* +0000 (glob)
-  +++ cloned/.hgsubstate	* +0000 (glob)
-  @@ -1,2 +1 @@
+  diff -Nru cloned.*/.hgsubstate cloned/.hgsubstate (glob)
+  --- cloned.*/.hgsubstate	* (glob)
+  +++ cloned/.hgsubstate	* (glob)
+  @@ -1,2 +1* @@ (glob)
    7a36fa02b66e61f27f3d4a822809f159479b8ab2 sub1
   -b1a26de6f2a045a9f079323693614ee322f1ff7e sub3
   [1]
 
-  $ hg --config extensions.extdiff= extdiff -r 0 -r '.^' -S
-  diff -Npru cloned.*/.hglf/b.dat cloned.*/.hglf/b.dat (glob)
+  $ hg --config extensions.extdiff= pdiff -r 0 -r '.^' -S
+  diff -Nru cloned.*/.hglf/b.dat cloned.*/.hglf/b.dat (glob)
   --- cloned.*/.hglf/b.dat	* (glob)
   +++ cloned.*/.hglf/b.dat	* (glob)
-  @@ -0,0 +1 @@
+  @@ -*,0 +1* @@ (glob)
   +da39a3ee5e6b4b0d3255bfef95601890afd80709
-  diff -Npru cloned.*/.hglf/foo/bar/large.dat cloned.*/.hglf/foo/bar/large.dat (glob)
+  diff -Nru cloned.*/.hglf/foo/bar/large.dat cloned.*/.hglf/foo/bar/large.dat (glob)
   --- cloned.*/.hglf/foo/bar/large.dat	* (glob)
   +++ cloned.*/.hglf/foo/bar/large.dat	* (glob)
-  @@ -0,0 +1 @@
+  @@ -*,0 +1* @@ (glob)
   +2f6933b5ee0f5fdd823d9717d8729f3c2523811b
-  diff -Npru cloned.*/.hglf/large.bin cloned.*/.hglf/large.bin (glob)
+  diff -Nru cloned.*/.hglf/large.bin cloned.*/.hglf/large.bin (glob)
   --- cloned.*/.hglf/large.bin	* (glob)
   +++ cloned.*/.hglf/large.bin	* (glob)
-  @@ -0,0 +1 @@
+  @@ -*,0 +1* @@ (glob)
   +7f7097b041ccf68cc5561e9600da4655d21c6d18
-  diff -Npru cloned.*/.hgsub cloned.*/.hgsub (glob)
+  diff -Nru cloned.*/.hgsub cloned.*/.hgsub (glob)
   --- cloned.*/.hgsub	* (glob)
   +++ cloned.*/.hgsub	* (glob)
-  @@ -1 +1,2 @@
+  @@ -1* +1,2 @@ (glob)
    sub1 = ../sub1
   +sub3 = sub3
-  diff -Npru cloned.*/.hgsubstate cloned.*/.hgsubstate (glob)
+  diff -Nru cloned.*/.hgsubstate cloned.*/.hgsubstate (glob)
   --- cloned.*/.hgsubstate	* (glob)
   +++ cloned.*/.hgsubstate	* (glob)
-  @@ -1 +1,2 @@
+  @@ -1* +1,2 @@ (glob)
   -fc3b4ce2696f7741438c79207583768f2ce6b0dd sub1
   +7a36fa02b66e61f27f3d4a822809f159479b8ab2 sub1
   +b1a26de6f2a045a9f079323693614ee322f1ff7e sub3
-  diff -Npru cloned.*/foo/bar/def cloned.*/foo/bar/def (glob)
+  diff -Nru cloned.*/foo/bar/def cloned.*/foo/bar/def (glob)
   --- cloned.*/foo/bar/def	* (glob)
   +++ cloned.*/foo/bar/def	* (glob)
-  @@ -0,0 +1 @@
+  @@ -*,0 +1* @@ (glob)
   +changed
-  diff -Npru cloned.*/main cloned.*/main (glob)
+  diff -Nru cloned.*/main cloned.*/main (glob)
   --- cloned.*/main	* (glob)
   +++ cloned.*/main	* (glob)
-  @@ -1 +1 @@
+  @@ -1* +1* @@ (glob)
   -main
   +foo
-  diff -Npru cloned.*/sub1/.hgsubstate cloned.*/sub1/.hgsubstate (glob)
+  diff -Nru cloned.*/sub1/.hgsubstate cloned.*/sub1/.hgsubstate (glob)
   --- cloned.*/sub1/.hgsubstate	* (glob)
   +++ cloned.*/sub1/.hgsubstate	* (glob)
-  @@ -1 +1 @@
+  @@ -1* +1* @@ (glob)
   -c57a0840e3badd667ef3c3ef65471609acb2ba3c sub2
   +c77908c81ccea3794a896c79e98b0e004aee2e9e sub2
-  diff -Npru cloned.*/sub1/sub2/folder/test.txt cloned.*/sub1/sub2/folder/test.txt (glob)
+  diff -Nru cloned.*/sub1/sub2/folder/test.txt cloned.*/sub1/sub2/folder/test.txt (glob)
   --- cloned.*/sub1/sub2/folder/test.txt	* (glob)
   +++ cloned.*/sub1/sub2/folder/test.txt	* (glob)
-  @@ -0,0 +1 @@
+  @@ -*,0 +1* @@ (glob)
   +subfolder
-  diff -Npru cloned.*/sub1/sub2/sub2 cloned.*/sub1/sub2/sub2 (glob)
+  diff -Nru cloned.*/sub1/sub2/sub2 cloned.*/sub1/sub2/sub2 (glob)
   --- cloned.*/sub1/sub2/sub2	* (glob)
   +++ cloned.*/sub1/sub2/sub2	* (glob)
-  @@ -1 +1 @@
+  @@ -1* +1* @@ (glob)
   -sub2
   +modified
-  diff -Npru cloned.*/sub3/a.txt cloned.*/sub3/a.txt (glob)
+  diff -Nru cloned.*/sub3/a.txt cloned.*/sub3/a.txt (glob)
   --- cloned.*/sub3/a.txt	* (glob)
   +++ cloned.*/sub3/a.txt	* (glob)
-  @@ -0,0 +1 @@
+  @@ -*,0 +1* @@ (glob)
   +xyz
   [1]
 
   $ echo mod > sub1/sub2/sub2
-  $ hg --config extensions.extdiff= extdiff -S
+  $ hg --config extensions.extdiff= pdiff -S
   --- */cloned.*/sub1/sub2/sub2	* (glob)
   +++ */cloned/sub1/sub2/sub2	* (glob)
-  @@ -1 +1 @@
+  @@ -1* +1* @@ (glob)
   -modified
   +mod
   [1]
--- a/tests/test-subrepo-git.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-subrepo-git.t	Wed Feb 24 15:55:44 2016 -0600
@@ -785,7 +785,7 @@
   index 0000000..257cc56
   --- /dev/null
   +++ b/s/barfoo
-  @@ -0,0 +1 @@
+  @@ -0,0 +1* @@ (glob)
   +foo
   $ hg diff --subrepos s/foobar
   diff --git a/s/foobar b/s/foobar
@@ -827,7 +827,7 @@
   index 0000000..257cc56
   --- /dev/null
   +++ b/s/barfoo
-  @@ -0,0 +1 @@
+  @@ -0,0 +1* @@ (glob)
   +foo
 
 moving a file should show a removal and an add
--- a/tests/test-subrepo.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-subrepo.t	Wed Feb 24 15:55:44 2016 -0600
@@ -664,6 +664,7 @@
   $ cd ../t
   $ hg up -C # discard our earlier merge
   1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  2 other heads for branch "default"
   $ echo blah > t/t
   $ hg ci -m13
   committing subrepository t
@@ -677,6 +678,7 @@
 
   $ hg up -C # discard changes
   1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  2 other heads for branch "default"
 
 pull
 
@@ -718,6 +720,7 @@
   adding file changes
   added 1 changesets with 1 changes to 1 files
   0 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  2 other heads for branch "default"
   $ cat t/t
   blah
 
@@ -1185,6 +1188,7 @@
   ? s/c
   $ hg update -C
   1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  2 other heads for branch "default"
   $ hg status -S
   ? s/b
   ? s/c
--- a/tests/test-tags.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-tags.t	Wed Feb 24 15:55:44 2016 -0600
@@ -136,12 +136,13 @@
   $ rm -f .hg/cache/tags2-visible .hg/cache/hgtagsfnodes1
   $ hg identify
   b9154636be93 tip
-  $ hg blackbox -l 5
+  $ hg blackbox -l 6
   1970/01/01 00:00:00 bob (*)> identify (glob)
   1970/01/01 00:00:00 bob (*)> writing 48 bytes to cache/hgtagsfnodes1 (glob)
   1970/01/01 00:00:00 bob (*)> 0/1 cache hits/lookups in * seconds (glob)
   1970/01/01 00:00:00 bob (*)> writing .hg/cache/tags2-visible with 1 tags (glob)
-  1970/01/01 00:00:00 bob (*)> identify exited 0 after ?.?? seconds (glob)
+  1970/01/01 00:00:00 bob (*)> identify exited 0 after * seconds (glob)
+  1970/01/01 00:00:00 bob (*)> blackbox -l 6 (glob)
 
 Failure to acquire lock results in no write
 
@@ -149,12 +150,13 @@
   $ echo 'foo:1' > .hg/wlock
   $ hg identify
   b9154636be93 tip
-  $ hg blackbox -l 5
+  $ hg blackbox -l 6
   1970/01/01 00:00:00 bob (*)> identify (glob)
   1970/01/01 00:00:00 bob (*)> not writing .hg/cache/hgtagsfnodes1 because lock cannot be acquired (glob)
   1970/01/01 00:00:00 bob (*)> 0/1 cache hits/lookups in * seconds (glob)
   1970/01/01 00:00:00 bob (*)> writing .hg/cache/tags2-visible with 1 tags (glob)
   1970/01/01 00:00:00 bob (*)> identify exited 0 after * seconds (glob)
+  1970/01/01 00:00:00 bob (*)> blackbox -l 6 (glob)
 
   $ fnodescacheexists
   no fnodes cache
@@ -348,12 +350,13 @@
   tip                                5:8dbfe60eff30
   bar                                1:78391a272241
 
-  $ hg blackbox -l 5
+  $ hg blackbox -l 6
   1970/01/01 00:00:00 bob (*)> tags (glob)
   1970/01/01 00:00:00 bob (*)> writing 24 bytes to cache/hgtagsfnodes1 (glob)
   1970/01/01 00:00:00 bob (*)> 2/3 cache hits/lookups in * seconds (glob)
   1970/01/01 00:00:00 bob (*)> writing .hg/cache/tags2-visible with 1 tags (glob)
   1970/01/01 00:00:00 bob (*)> tags exited 0 after * seconds (glob)
+  1970/01/01 00:00:00 bob (*)> blackbox -l 6 (glob)
 
 #if unix-permissions no-root
 Errors writing to .hgtags fnodes cache are silently ignored
@@ -368,12 +371,13 @@
   tip                                6:b968051b5cf3
   bar                                1:78391a272241
 
-  $ hg blackbox -l 5
+  $ hg blackbox -l 6
   1970/01/01 00:00:00 bob (*)> tags (glob)
   1970/01/01 00:00:00 bob (*)> couldn't write cache/hgtagsfnodes1: [Errno 13] Permission denied: '$TESTTMP/t2/.hg/cache/hgtagsfnodes1' (glob)
   1970/01/01 00:00:00 bob (*)> 2/3 cache hits/lookups in * seconds (glob)
   1970/01/01 00:00:00 bob (*)> writing .hg/cache/tags2-visible with 1 tags (glob)
   1970/01/01 00:00:00 bob (*)> tags exited 0 after * seconds (glob)
+  1970/01/01 00:00:00 bob (*)> blackbox -l 6 (glob)
 
   $ chmod a+w .hg/cache/hgtagsfnodes1
 
@@ -382,12 +386,13 @@
   tip                                6:b968051b5cf3
   bar                                1:78391a272241
 
-  $ hg blackbox -l 5
+  $ hg blackbox -l 6
   1970/01/01 00:00:00 bob (*)> tags (glob)
   1970/01/01 00:00:00 bob (*)> writing 24 bytes to cache/hgtagsfnodes1 (glob)
   1970/01/01 00:00:00 bob (*)> 2/3 cache hits/lookups in * seconds (glob)
   1970/01/01 00:00:00 bob (*)> writing .hg/cache/tags2-visible with 1 tags (glob)
   1970/01/01 00:00:00 bob (*)> tags exited 0 after * seconds (glob)
+  1970/01/01 00:00:00 bob (*)> blackbox -l 6 (glob)
 
   $ f --size .hg/cache/hgtagsfnodes1
   .hg/cache/hgtagsfnodes1: size=168
@@ -410,11 +415,12 @@
   tip                                4:0c192d7d5e6b
   bar                                1:78391a272241
 
-  $ hg blackbox -l 4
+  $ hg blackbox -l 5
   1970/01/01 00:00:00 bob (*)> writing 24 bytes to cache/hgtagsfnodes1 (glob)
   1970/01/01 00:00:00 bob (*)> 2/3 cache hits/lookups in * seconds (glob)
   1970/01/01 00:00:00 bob (*)> writing .hg/cache/tags2-visible with 1 tags (glob)
   1970/01/01 00:00:00 bob (*)> tags exited 0 after * seconds (glob)
+  1970/01/01 00:00:00 bob (*)> blackbox -l 5 (glob)
 
   $ f --size .hg/cache/hgtagsfnodes1
   .hg/cache/hgtagsfnodes1: size=120
@@ -426,12 +432,13 @@
   tip                                5:035f65efb448
   bar                                1:78391a272241
 
-  $ hg blackbox -l 5
+  $ hg blackbox -l 6
   1970/01/01 00:00:00 bob (*)> tags (glob)
   1970/01/01 00:00:00 bob (*)> writing 24 bytes to cache/hgtagsfnodes1 (glob)
   1970/01/01 00:00:00 bob (*)> 2/3 cache hits/lookups in * seconds (glob)
   1970/01/01 00:00:00 bob (*)> writing .hg/cache/tags2-visible with 1 tags (glob)
   1970/01/01 00:00:00 bob (*)> tags exited 0 after * seconds (glob)
+  1970/01/01 00:00:00 bob (*)> blackbox -l 6 (glob)
   $ f --size .hg/cache/hgtagsfnodes1
   .hg/cache/hgtagsfnodes1: size=144
 
--- a/tests/test-template-engine.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-template-engine.t	Wed Feb 24 15:55:44 2016 -0600
@@ -44,17 +44,4 @@
   0 97e5f848f0936960273bbf75be6388cd0350a32b -1 0000000000000000000000000000000000000000
   -1 0000000000000000000000000000000000000000 -1 0000000000000000000000000000000000000000
 
-Fuzzing the unicode escaper to ensure it produces valid data
-
-#if hypothesis
-
-  >>> from hypothesishelpers import *
-  >>> import mercurial.templatefilters as tf
-  >>> import json
-  >>> @check(st.text().map(lambda s: s.encode('utf-8')))
-  ... def testtfescapeproducesvalidjson(text):
-  ...     json.loads('"' + tf.jsonescape(text) + '"')
-
-#endif
-
   $ cd ..
--- a/tests/test-transplant.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-transplant.t	Wed Feb 24 15:55:44 2016 -0600
@@ -409,6 +409,7 @@
 
   $ hg up -C
   1 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  1 other heads for branch "default"
   $ rm added
   $ hg transplant --continue
   abort: no transplant to continue
--- a/tests/test-treemanifest.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-treemanifest.t	Wed Feb 24 15:55:44 2016 -0600
@@ -1,3 +1,5 @@
+#require killdaemons
+
   $ cat << EOF >> $HGRCPATH
   > [format]
   > usegeneraldelta=yes
@@ -367,7 +369,7 @@
   $ hg --config experimental.treemanifest=True init deeprepo
   $ cd deeprepo
 
-  $ mkdir a
+  $ mkdir .A
   $ mkdir b
   $ mkdir b/bar
   $ mkdir b/bar/orange
@@ -376,8 +378,8 @@
   $ mkdir b/foo/apple
   $ mkdir b/foo/apple/bees
 
-  $ touch a/one.txt
-  $ touch a/two.txt
+  $ touch .A/one.txt
+  $ touch .A/two.txt
   $ touch b/bar/fruits.txt
   $ touch b/bar/orange/fly/gnat.py
   $ touch b/bar/orange/fly/housefly.txt
@@ -393,8 +395,8 @@
 Test files from the root.
 
   $ hg files -r .
-  a/one.txt (glob)
-  a/two.txt (glob)
+  .A/one.txt (glob)
+  .A/two.txt (glob)
   b/bar/fruits.txt (glob)
   b/bar/orange/fly/gnat.py (glob)
   b/bar/orange/fly/housefly.txt (glob)
@@ -408,61 +410,56 @@
   b/bar/fruits.txt (glob)
   b/bar/orange/fly/gnat.py (glob)
   b/bar/orange/fly/housefly.txt (glob)
+  $ cp -r .hg/store .hg/store-copy
 
 Test files for a subdirectory.
 
-  $ mv .hg/store/meta/a oldmf
+  $ rm -r .hg/store/meta/~2e_a
   $ hg files -r . b
   b/bar/fruits.txt (glob)
   b/bar/orange/fly/gnat.py (glob)
   b/bar/orange/fly/housefly.txt (glob)
   b/foo/apple/bees/flower.py (glob)
-  $ mv oldmf .hg/store/meta/a
+  $ cp -r .hg/store-copy/. .hg/store
 
 Test files with just includes and excludes.
 
-  $ mv .hg/store/meta/a oldmf
-  $ mv .hg/store/meta/b/bar/orange/fly oldmf2
-  $ mv .hg/store/meta/b/foo/apple/bees oldmf3
+  $ rm -r .hg/store/meta/~2e_a
+  $ rm -r .hg/store/meta/b/bar/orange/fly
+  $ rm -r .hg/store/meta/b/foo/apple/bees
   $ hg files -r . -I path:b/bar -X path:b/bar/orange/fly -I path:b/foo -X path:b/foo/apple/bees
   b/bar/fruits.txt (glob)
-  $ mv oldmf .hg/store/meta/a
-  $ mv oldmf2 .hg/store/meta/b/bar/orange/fly
-  $ mv oldmf3 .hg/store/meta/b/foo/apple/bees
+  $ cp -r .hg/store-copy/. .hg/store
 
 Test files for a subdirectory, excluding a directory within it.
 
-  $ mv .hg/store/meta/a oldmf
-  $ mv .hg/store/meta/b/foo oldmf2
+  $ rm -r .hg/store/meta/~2e_a
+  $ rm -r .hg/store/meta/b/foo
   $ hg files -r . -X path:b/foo b
   b/bar/fruits.txt (glob)
   b/bar/orange/fly/gnat.py (glob)
   b/bar/orange/fly/housefly.txt (glob)
-  $ mv oldmf .hg/store/meta/a
-  $ mv oldmf2 .hg/store/meta/b/foo
+  $ cp -r .hg/store-copy/. .hg/store
 
 Test files for a sub directory, including only a directory within it, and
 including an unrelated directory.
 
-  $ mv .hg/store/meta/a oldmf
-  $ mv .hg/store/meta/b/foo oldmf2
+  $ rm -r .hg/store/meta/~2e_a
+  $ rm -r .hg/store/meta/b/foo
   $ hg files -r . -I path:b/bar/orange -I path:a b
   b/bar/orange/fly/gnat.py (glob)
   b/bar/orange/fly/housefly.txt (glob)
-  $ mv oldmf .hg/store/meta/a
-  $ mv oldmf2 .hg/store/meta/b/foo
+  $ cp -r .hg/store-copy/. .hg/store
 
 Test files for a pattern, including a directory, and excluding a directory
 within that.
 
-  $ mv .hg/store/meta/a oldmf
-  $ mv .hg/store/meta/b/foo oldmf2
-  $ mv .hg/store/meta/b/bar/orange oldmf3
+  $ rm -r .hg/store/meta/~2e_a
+  $ rm -r .hg/store/meta/b/foo
+  $ rm -r .hg/store/meta/b/bar/orange
   $ hg files -r . glob:**.txt -I path:b/bar -X path:b/bar/orange
   b/bar/fruits.txt (glob)
-  $ mv oldmf .hg/store/meta/a
-  $ mv oldmf2 .hg/store/meta/b/foo
-  $ mv oldmf3 .hg/store/meta/b/bar/orange
+  $ cp -r .hg/store-copy/. .hg/store
 
 Add some more changes to the deep repo
   $ echo narf >> b/bar/fruits.txt
@@ -470,14 +467,108 @@
   $ echo troz >> b/bar/orange/fly/gnat.py
   $ hg ci -m troz
 
+Verify works
+  $ hg verify
+  checking changesets
+  checking manifests
+  checking directory manifests
+  crosschecking files in changesets and manifests
+  checking files
+  8 files, 3 changesets, 10 total revisions
+
+Dirlogs are included in fncache
+  $ grep meta/.A/00manifest.i .hg/store/fncache
+  meta/.A/00manifest.i
+
+Rebuilt fncache includes dirlogs
+  $ rm .hg/store/fncache
+  $ hg debugrebuildfncache
+  adding data/.A/one.txt.i
+  adding data/.A/two.txt.i
+  adding data/b/bar/fruits.txt.i
+  adding data/b/bar/orange/fly/gnat.py.i
+  adding data/b/bar/orange/fly/housefly.txt.i
+  adding data/b/foo/apple/bees/flower.py.i
+  adding data/c.txt.i
+  adding data/d.py.i
+  adding meta/.A/00manifest.i
+  adding meta/b/00manifest.i
+  adding meta/b/bar/00manifest.i
+  adding meta/b/bar/orange/00manifest.i
+  adding meta/b/bar/orange/fly/00manifest.i
+  adding meta/b/foo/00manifest.i
+  adding meta/b/foo/apple/00manifest.i
+  adding meta/b/foo/apple/bees/00manifest.i
+  16 items added, 0 removed from fncache
+
+Finish first server
+  $ killdaemons.py
+
+Back up the recently added revlogs
+  $ cp -r .hg/store .hg/store-newcopy
+
+Verify reports missing dirlog
+  $ rm .hg/store/meta/b/00manifest.*
+  $ hg verify
+  checking changesets
+  checking manifests
+  checking directory manifests
+   0: empty or missing b/
+   b/@0: parent-directory manifest refers to unknown revision 67688a370455
+   b/@1: parent-directory manifest refers to unknown revision f38e85d334c5
+   b/@2: parent-directory manifest refers to unknown revision 99c9792fd4b0
+  warning: orphan revlog 'meta/b/bar/00manifest.i'
+  warning: orphan revlog 'meta/b/bar/orange/00manifest.i'
+  warning: orphan revlog 'meta/b/bar/orange/fly/00manifest.i'
+  warning: orphan revlog 'meta/b/foo/00manifest.i'
+  warning: orphan revlog 'meta/b/foo/apple/00manifest.i'
+  warning: orphan revlog 'meta/b/foo/apple/bees/00manifest.i'
+  crosschecking files in changesets and manifests
+   b/bar/fruits.txt@0: in changeset but not in manifest
+   b/bar/orange/fly/gnat.py@0: in changeset but not in manifest
+   b/bar/orange/fly/housefly.txt@0: in changeset but not in manifest
+   b/foo/apple/bees/flower.py@0: in changeset but not in manifest
+  checking files
+  8 files, 3 changesets, 10 total revisions
+  6 warnings encountered!
+  8 integrity errors encountered!
+  (first damaged changeset appears to be 0)
+  [1]
+  $ cp -rT .hg/store-newcopy .hg/store
+
+Verify reports missing dirlog entry
+  $ mv -f .hg/store-copy/meta/b/00manifest.* .hg/store/meta/b/
+  $ hg verify
+  checking changesets
+  checking manifests
+  checking directory manifests
+   b/@1: parent-directory manifest refers to unknown revision f38e85d334c5
+   b/@2: parent-directory manifest refers to unknown revision 99c9792fd4b0
+   b/bar/@?: rev 1 points to unexpected changeset 1
+   b/bar/@?: 5e03c4ee5e4a not in parent-directory manifest
+   b/bar/@?: rev 2 points to unexpected changeset 2
+   b/bar/@?: 1b16940d66d6 not in parent-directory manifest
+   b/bar/orange/@?: rev 1 points to unexpected changeset 2
+   (expected None)
+   b/bar/orange/fly/@?: rev 1 points to unexpected changeset 2
+   (expected None)
+  crosschecking files in changesets and manifests
+  checking files
+  8 files, 3 changesets, 10 total revisions
+  2 warnings encountered!
+  8 integrity errors encountered!
+  (first damaged changeset appears to be 1)
+  [1]
+  $ cp -rT .hg/store-newcopy .hg/store
+
 Test cloning a treemanifest repo over http.
-  $ hg serve -p $HGPORT2 -d --pid-file=hg.pid --errorlog=errors.log
+  $ hg serve -p $HGPORT -d --pid-file=hg.pid --errorlog=errors.log
   $ cat hg.pid >> $DAEMON_PIDS
   $ cd ..
 We can clone even with the knob turned off and we'll get a treemanifest repo.
   $ hg clone --config experimental.treemanifest=False \
   >   --config experimental.changegroup3=True \
-  >   http://localhost:$HGPORT2 deepclone
+  >   http://localhost:$HGPORT deepclone
   requesting all changes
   adding changesets
   adding manifests
@@ -493,8 +584,6 @@
 Tree manifest revlogs exist.
   $ find deepclone/.hg/store/meta | sort
   deepclone/.hg/store/meta
-  deepclone/.hg/store/meta/a
-  deepclone/.hg/store/meta/a/00manifest.i
   deepclone/.hg/store/meta/b
   deepclone/.hg/store/meta/b/00manifest.i
   deepclone/.hg/store/meta/b/bar
@@ -509,12 +598,134 @@
   deepclone/.hg/store/meta/b/foo/apple/00manifest.i
   deepclone/.hg/store/meta/b/foo/apple/bees
   deepclone/.hg/store/meta/b/foo/apple/bees/00manifest.i
+  deepclone/.hg/store/meta/~2e_a
+  deepclone/.hg/store/meta/~2e_a/00manifest.i
 Verify passes.
   $ cd deepclone
   $ hg verify
   checking changesets
   checking manifests
+  checking directory manifests
   crosschecking files in changesets and manifests
   checking files
   8 files, 3 changesets, 10 total revisions
   $ cd ..
+
+Create clones using old repo formats to use in later tests
+  $ hg clone --config format.usestore=False \
+  >   --config experimental.changegroup3=True \
+  >   http://localhost:$HGPORT deeprepo-basicstore
+  requesting all changes
+  adding changesets
+  adding manifests
+  adding file changes
+  added 3 changesets with 10 changes to 8 files
+  updating to branch default
+  8 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  $ cd deeprepo-basicstore
+  $ grep store .hg/requires
+  [1]
+  $ hg serve -p $HGPORT1 -d --pid-file=hg.pid --errorlog=errors.log
+  $ cat hg.pid >> $DAEMON_PIDS
+  $ cd ..
+  $ hg clone --config format.usefncache=False \
+  >   --config experimental.changegroup3=True \
+  >   http://localhost:$HGPORT deeprepo-encodedstore
+  requesting all changes
+  adding changesets
+  adding manifests
+  adding file changes
+  added 3 changesets with 10 changes to 8 files
+  updating to branch default
+  8 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  $ cd deeprepo-encodedstore
+  $ grep fncache .hg/requires
+  [1]
+  $ hg serve -p $HGPORT2 -d --pid-file=hg.pid --errorlog=errors.log
+  $ cat hg.pid >> $DAEMON_PIDS
+  $ cd ..
+
+Local clone with basicstore
+  $ hg clone -U deeprepo-basicstore local-clone-basicstore
+  $ hg -R local-clone-basicstore verify
+  checking changesets
+  checking manifests
+  checking directory manifests
+  crosschecking files in changesets and manifests
+  checking files
+  8 files, 3 changesets, 10 total revisions
+
+Local clone with encodedstore
+  $ hg clone -U deeprepo-encodedstore local-clone-encodedstore
+  $ hg -R local-clone-encodedstore verify
+  checking changesets
+  checking manifests
+  checking directory manifests
+  crosschecking files in changesets and manifests
+  checking files
+  8 files, 3 changesets, 10 total revisions
+
+Local clone with fncachestore
+  $ hg clone -U deeprepo local-clone-fncachestore
+  $ hg -R local-clone-fncachestore verify
+  checking changesets
+  checking manifests
+  checking directory manifests
+  crosschecking files in changesets and manifests
+  checking files
+  8 files, 3 changesets, 10 total revisions
+
+Stream clone with basicstore
+  $ hg clone --config experimental.changegroup3=True --uncompressed -U \
+  >   http://localhost:$HGPORT1 stream-clone-basicstore
+  streaming all changes
+  18 files to transfer, * of data (glob)
+  transferred * in * seconds (*) (glob)
+  searching for changes
+  no changes found
+  $ hg -R stream-clone-basicstore verify
+  checking changesets
+  checking manifests
+  checking directory manifests
+  crosschecking files in changesets and manifests
+  checking files
+  8 files, 3 changesets, 10 total revisions
+
+Stream clone with encodedstore
+  $ hg clone --config experimental.changegroup3=True --uncompressed -U \
+  >   http://localhost:$HGPORT2 stream-clone-encodedstore
+  streaming all changes
+  18 files to transfer, * of data (glob)
+  transferred * in * seconds (*) (glob)
+  searching for changes
+  no changes found
+  $ hg -R stream-clone-encodedstore verify
+  checking changesets
+  checking manifests
+  checking directory manifests
+  crosschecking files in changesets and manifests
+  checking files
+  8 files, 3 changesets, 10 total revisions
+
+Stream clone with fncachestore
+  $ hg clone --config experimental.changegroup3=True --uncompressed -U \
+  >   http://localhost:$HGPORT stream-clone-fncachestore
+  streaming all changes
+  18 files to transfer, * of data (glob)
+  transferred * in * seconds (*) (glob)
+  searching for changes
+  no changes found
+  $ hg -R stream-clone-fncachestore verify
+  checking changesets
+  checking manifests
+  checking directory manifests
+  crosschecking files in changesets and manifests
+  checking files
+  8 files, 3 changesets, 10 total revisions
+
+Packed bundle
+  $ hg -R deeprepo debugcreatestreamclonebundle repo-packed.hg
+  writing 3349 bytes for 18 files
+  bundle requirements: generaldelta, revlogv1, treemanifest
+  $ hg debugbundle --spec repo-packed.hg
+  none-packed1;requirements%3Dgeneraldelta%2Crevlogv1%2Ctreemanifest
--- a/tests/test-ui-config.py.out	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-ui-config.py.out	Wed Feb 24 15:55:44 2016 -0600
@@ -1,5 +1,5 @@
 [('string', 'string value'), ('bool1', 'true'), ('bool2', 'false'), ('boolinvalid', 'foo'), ('int1', '42'), ('int2', '-42'), ('intinvalid', 'foo')]
-[('list1', 'foo'), ('list2', 'foo bar baz'), ('list3', 'alice, bob'), ('list4', 'foo bar baz alice, bob'), ('list5', 'abc d"ef"g "hij def"'), ('list6', '"hello world", "how are you?"'), ('list7', 'Do"Not"Separate'), ('list8', '"Do"Separate'), ('list9', '"Do\\"NotSeparate"'), ('list10', 'string "with extraneous" quotation mark"'), ('list11', 'x, y'), ('list12', '"x", "y"'), ('list13', '""" key = "x", "y" """'), ('list14', ',,,,     '), ('list15', '" just with starting quotation'), ('list16', '"longer quotation" with "no ending quotation'), ('list17', 'this is \\" "not a quotation mark"'), ('list18', '\n \n\nding\ndong')]
+[('list1', 'foo'), ('list2', 'foo bar baz'), ('list3', 'alice, bob'), ('list4', 'foo bar baz alice, bob'), ('list5', 'abc d"ef"g "hij def"'), ('list6', '"hello world", "how are you?"'), ('list7', 'Do"Not"Separate'), ('list8', '"Do"Separate'), ('list9', '"Do\\"NotSeparate"'), ('list10', 'string "with extraneous" quotation mark"'), ('list11', 'x, y'), ('list12', '"x", "y"'), ('list13', '""" key = "x", "y" """'), ('list14', ',,,,'), ('list15', '" just with starting quotation'), ('list16', '"longer quotation" with "no ending quotation'), ('list17', 'this is \\" "not a quotation mark"'), ('list18', 'ding\ndong')]
 ---
 'string value'
 'true'
--- a/tests/test-up-local-change.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-up-local-change.t	Wed Feb 24 15:55:44 2016 -0600
@@ -172,9 +172,8 @@
   summary:     2
   
   $ hg --debug up
-  abort: uncommitted changes
-  (commit and merge, or update --clean to discard changes)
-  [255]
+  0 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  1 other heads for branch "default"
 
 test conflicting untracked files
 
--- a/tests/test-update-branches.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-update-branches.t	Wed Feb 24 15:55:44 2016 -0600
@@ -93,8 +93,8 @@
   parent=5
 
   $ norevtest 'none clean same'   clean 2
-  abort: not a linear update
-  (merge or update --check to force update)
+  0 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  1 other heads for branch "default"
   parent=2
 
 
@@ -140,8 +140,8 @@
   M foo
 
   $ norevtest 'none dirty cross'  dirty 2
-  abort: uncommitted changes
-  (commit and merge, or update --clean to discard changes)
+  0 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  1 other heads for branch "default"
   parent=2
   M foo
 
@@ -166,8 +166,9 @@
   M sub/suba
 
   $ norevtest '-c clean same'   clean 2 -c
-  1 files updated, 0 files merged, 0 files removed, 0 files unresolved
-  parent=3
+  0 files updated, 0 files merged, 0 files removed, 0 files unresolved
+  1 other heads for branch "default"
+  parent=2
 
   $ revtest '-cC dirty linear'  dirty 1 2 -cC
   abort: cannot specify both -c/--check and -C/--clean
--- a/tests/test-verify.t	Tue Feb 23 11:41:47 2016 +0100
+++ b/tests/test-verify.t	Wed Feb 24 15:55:44 2016 -0600
@@ -46,13 +46,13 @@
   checking files
    warning: revlog 'data/FOO.txt.i' not in fncache!
    0: empty or missing FOO.txt
-   FOO.txt@0: f62022d3d590 in manifests not found
+   FOO.txt@0: manifest refers to unknown revision f62022d3d590
    warning: revlog 'data/QUICK.txt.i' not in fncache!
    0: empty or missing QUICK.txt
-   QUICK.txt@0: 88b857db8eba in manifests not found
+   QUICK.txt@0: manifest refers to unknown revision 88b857db8eba
    warning: revlog 'data/bar.txt.i' not in fncache!
    0: empty or missing bar.txt
-   bar.txt@0: 256559129457 in manifests not found
+   bar.txt@0: manifest refers to unknown revision 256559129457
   3 files, 1 changesets, 0 total revisions
   3 warnings encountered!
   hint: run "hg debugrebuildfncache" to recover from corrupt fncache
@@ -63,6 +63,208 @@
   $ cd ../../..
   $ cd ..
 
+Set up a repo for testing missing revlog entries
+
+  $ hg init missing-entries
+  $ cd missing-entries
+  $ echo 0 > file
+  $ hg ci -Aqm0
+  $ cp -r .hg/store .hg/store-partial
+  $ echo 1 > file
+  $ hg ci -Aqm1
+  $ cp -r .hg/store .hg/store-full
+
+Entire changelog missing
+
+  $ rm .hg/store/00changelog.*
+  $ hg verify -q
+   0: empty or missing changelog
+   manifest@0: d0b6632564d4 not in changesets
+   manifest@1: 941fc4534185 not in changesets
+  3 integrity errors encountered!
+  (first damaged changeset appears to be 0)
+  [1]
+  $ cp -r .hg/store-full/. .hg/store
+
+Entire manifest log missing
+
+  $ rm .hg/store/00manifest.*
+  $ hg verify -q
+   0: empty or missing manifest
+  1 integrity errors encountered!
+  (first damaged changeset appears to be 0)
+  [1]
+  $ cp -r .hg/store-full/. .hg/store
+
+Entire filelog missing
+
+  $ rm .hg/store/data/file.*
+  $ hg verify -q
+   warning: revlog 'data/file.i' not in fncache!
+   0: empty or missing file
+   file@0: manifest refers to unknown revision 362fef284ce2
+   file@1: manifest refers to unknown revision c10f2164107d
+  1 warnings encountered!
+  hint: run "hg debugrebuildfncache" to recover from corrupt fncache
+  3 integrity errors encountered!
+  (first damaged changeset appears to be 0)
+  [1]
+  $ cp -r .hg/store-full/. .hg/store
+
+Entire changelog and manifest log missing
+
+  $ rm .hg/store/00changelog.*
+  $ rm .hg/store/00manifest.*
+  $ hg verify -q
+  warning: orphan revlog 'data/file.i'
+  1 warnings encountered!
+  $ cp -r .hg/store-full/. .hg/store
+
+Entire changelog and filelog missing
+
+  $ rm .hg/store/00changelog.*
+  $ rm .hg/store/data/file.*
+  $ hg verify -q
+   0: empty or missing changelog
+   manifest@0: d0b6632564d4 not in changesets
+   manifest@1: 941fc4534185 not in changesets
+   warning: revlog 'data/file.i' not in fncache!
+   ?: empty or missing file
+   file@0: manifest refers to unknown revision 362fef284ce2
+   file@1: manifest refers to unknown revision c10f2164107d
+  1 warnings encountered!
+  hint: run "hg debugrebuildfncache" to recover from corrupt fncache
+  6 integrity errors encountered!
+  (first damaged changeset appears to be 0)
+  [1]
+  $ cp -r .hg/store-full/. .hg/store
+
+Entire manifest log and filelog missing
+
+  $ rm .hg/store/00manifest.*
+  $ rm .hg/store/data/file.*
+  $ hg verify -q
+   0: empty or missing manifest
+   warning: revlog 'data/file.i' not in fncache!
+   0: empty or missing file
+  1 warnings encountered!
+  hint: run "hg debugrebuildfncache" to recover from corrupt fncache
+  2 integrity errors encountered!
+  (first damaged changeset appears to be 0)
+  [1]
+  $ cp -r .hg/store-full/. .hg/store
+
+Changelog missing entry
+
+  $ cp -f .hg/store-partial/00changelog.* .hg/store
+  $ hg verify -q
+   manifest@?: rev 1 points to nonexistent changeset 1
+   manifest@?: 941fc4534185 not in changesets
+   file@?: rev 1 points to nonexistent changeset 1
+   (expected 0)
+  1 warnings encountered!
+  3 integrity errors encountered!
+  [1]
+  $ cp -r .hg/store-full/. .hg/store
+
+Manifest log missing entry
+
+  $ cp -f .hg/store-partial/00manifest.* .hg/store
+  $ hg verify -q
+   manifest@1: changeset refers to unknown revision 941fc4534185
+   file@1: c10f2164107d not in manifests
+  2 integrity errors encountered!
+  (first damaged changeset appears to be 1)
+  [1]
+  $ cp -r .hg/store-full/. .hg/store
+
+Filelog missing entry
+
+  $ cp -f .hg/store-partial/data/file.* .hg/store/data
+  $ hg verify -q
+   file@1: manifest refers to unknown revision c10f2164107d
+  1 integrity errors encountered!
+  (first damaged changeset appears to be 1)
+  [1]
+  $ cp -r .hg/store-full/. .hg/store
+
+Changelog and manifest log missing entry
+
+  $ cp -f .hg/store-partial/00changelog.* .hg/store
+  $ cp -f .hg/store-partial/00manifest.* .hg/store
+  $ hg verify -q
+   file@?: rev 1 points to nonexistent changeset 1
+   (expected 0)
+   file@?: c10f2164107d not in manifests
+  1 warnings encountered!
+  2 integrity errors encountered!
+  [1]
+  $ cp -r .hg/store-full/. .hg/store
+
+Changelog and filelog missing entry
+
+  $ cp -f .hg/store-partial/00changelog.* .hg/store
+  $ cp -f .hg/store-partial/data/file.* .hg/store/data
+  $ hg verify -q
+   manifest@?: rev 1 points to nonexistent changeset 1
+   manifest@?: 941fc4534185 not in changesets
+   file@?: manifest refers to unknown revision c10f2164107d
+  3 integrity errors encountered!
+  [1]
+  $ cp -r .hg/store-full/. .hg/store
+
+Manifest and filelog missing entry
+
+  $ cp -f .hg/store-partial/00manifest.* .hg/store
+  $ cp -f .hg/store-partial/data/file.* .hg/store/data
+  $ hg verify -q
+   manifest@1: changeset refers to unknown revision 941fc4534185
+  1 integrity errors encountered!
+  (first damaged changeset appears to be 1)
+  [1]
+  $ cp -r .hg/store-full/. .hg/store
+
+Corrupt changelog base node to cause failure to read revision
+
+  $ printf abcd | dd conv=notrunc of=.hg/store/00changelog.i bs=1 seek=16 \
+  >   2> /dev/null
+  $ hg verify -q
+   0: unpacking changeset 08b1860757c2: * (glob)
+   manifest@?: rev 0 points to unexpected changeset 0
+   manifest@?: d0b6632564d4 not in changesets
+   file@?: rev 0 points to unexpected changeset 0
+   (expected 1)
+  1 warnings encountered!
+  4 integrity errors encountered!
+  (first damaged changeset appears to be 0)
+  [1]
+  $ cp -r .hg/store-full/. .hg/store
+
+Corrupt manifest log base node to cause failure to read revision
+
+  $ printf abcd | dd conv=notrunc of=.hg/store/00manifest.i bs=1 seek=16 \
+  >   2> /dev/null
+  $ hg verify -q
+   manifest@0: reading delta d0b6632564d4: * (glob)
+   file@0: 362fef284ce2 not in manifests
+  2 integrity errors encountered!
+  (first damaged changeset appears to be 0)
+  [1]
+  $ cp -r .hg/store-full/. .hg/store
+
+Corrupt filelog base node to cause failure to read revision
+
+  $ printf abcd | dd conv=notrunc of=.hg/store/data/file.i bs=1 seek=16 \
+  >   2> /dev/null
+  $ hg verify -q
+   file@0: unpacking 362fef284ce2: * (glob)
+  1 integrity errors encountered!
+  (first damaged changeset appears to be 0)
+  [1]
+  $ cp -r .hg/store-full/. .hg/store
+
+  $ cd ..
+
 test changelog without a manifest
 
   $ hg init b