[PATCH/WIP v3 00/31] Make git-am a builtin

STALE3737d

Revision v3 of 8 in this series.

45 messages, 3 authors, 2016-06-15 · open the first message on its own page

[PATCH/WIP v3 00/31] Make git-am a builtin

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:22

This patch series depends on pt/pull-builtin for OPT_PASSTHRU_ARGV() and
argv_array_pushv().

This is a re-roll of [WIP v3]. Thanks Junio and Stefan for the reviews last
round.

The biggest addition this round would be the support for git-rebase. Here's
a small unscientific benchmark that rebases 50 patches:

	git init &&
	echo initial >file &&
	git add file &&
	git commit -m initial &&
	git tag initial &&
	for x in $(seq 50)
	do
	    echo $x >>file &&
	    git commit -a -m $x
	done &&
	git checkout -b onto-rebase initial &&
	git commit --allow-empty -mempty &&
	time git rebase -q --onto onto-rebase initial master

With master:

1.53s, 1.55s, 1.17s, 1.52s, 1.22s. Avg: ~1.40s

With master + this patch series:

0.22s, 0.22s, 0.18s, 0.21s, 0.18s. Avg: ~0.20s

So this is around a 6-7x speedup.

Previous versions:

[WIP v1] http://thread.gmane.org/gmane.comp.version-control.git/270048
[WIP v2] http://thread.gmane.org/gmane.comp.version-control.git/271381

git-am is a commonly used command for applying a series of patches from a
mailbox to the current branch. Currently, it is implemented by the shell script
git-am.sh. However, compared to C, shell scripts have certain deficiencies:
they need to spawn a lot of processes, introduce a lot of dependencies and
cannot take advantage of git's internal caches.

This WIP patch series rewrites git-am.sh into optimized C builtin/am.c, and is
part of my GSoC project to rewrite git-pull and git-am into C builtins[1].

[1] https://gist.github.com/pyokagan/1b7b0d1f4dab6ba3cef1


Paul Tan (31):
  wrapper: implement xopen()
  wrapper: implement xfopen()
  am: implement skeletal builtin am
  am: implement patch queue mechanism
  am: split out mbox/maildir patches with git-mailsplit
  am: detect mbox patches
  am: extract patch, message and authorship with git-mailinfo
  am: apply patch with git-apply
  am: commit applied patch
  am: refresh the index at start
  am: refuse to apply patches if index is dirty
  am: implement --resolved/--continue
  am: implement --skip
  am: implement --abort
  am: don't accept patches when there's a session in progress
  am: implement quiet option
  am: exit with user friendly message on patch failure
  am: implement am --signoff
  cache-tree: introduce write_index_as_tree()
  am: implement 3-way merge
  am: --rebasing
  am: don't use git-mailinfo if --rebasing
  am: handle stray state directory
  am: implement -k/--keep, --keep-non-patch
  am: implement --[no-]message-id, am.messageid
  am: support --keep-cr, am.keepcr
  am: implement --[no-]scissors
  am: pass git-apply's options to git-apply
  am: implement --ignore-date
  am: implement --committer-date-is-author-date
  am: implement -S/--gpg-sign, commit.gpgsign

 Makefile          |    1 +
 builtin.h         |    1 +
 builtin/am.c      | 1650 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 cache-tree.c      |   29 +-
 cache-tree.h      |    1 +
 git-compat-util.h |    2 +
 git.c             |    1 +
 wrapper.c         |   43 ++
 8 files changed, 1716 insertions(+), 12 deletions(-)
 create mode 100644 builtin/am.c

-- 
2.1.4

[PATCH/WIP v3 01/31] wrapper: implement xopen()

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:22

A common usage pattern of open() is to check if it was successful, and
die() if it was not:

	int fd = open(path, O_WRONLY | O_CREAT, 0777);
	if (fd < 0)
		die_errno(_("Could not open '%s' for writing."), path);

Implement a wrapper function xopen() that does the above so that we can
save a few lines of code, and make the die() messages consistent.

Helped-by: Torsten Bögershausen [off-list ref]
Helped-by: Jeff King [off-list ref]
Signed-off-by: Paul Tan <redacted>
---
 git-compat-util.h |  1 +
 wrapper.c         | 25 +++++++++++++++++++++++++
 2 files changed, 26 insertions(+)
diff --git a/git-compat-util.h b/git-compat-util.h
index 0cc7ae8..bc77d77 100644
--- a/git-compat-util.h
+++ b/git-compat-util.h
@@ -719,6 +719,7 @@ extern void *xrealloc(void *ptr, size_t size);
 extern void *xcalloc(size_t nmemb, size_t size);
 extern void *xmmap(void *start, size_t length, int prot, int flags, int fd, off_t offset);
 extern void *xmmap_gently(void *start, size_t length, int prot, int flags, int fd, off_t offset);
+extern int xopen(const char *path, int flags, ...);
 extern ssize_t xread(int fd, void *buf, size_t len);
 extern ssize_t xwrite(int fd, const void *buf, size_t len);
 extern ssize_t xpread(int fd, void *buf, size_t len, off_t offset);
diff --git a/wrapper.c b/wrapper.c
index c1a663f..82658b3 100644
--- a/wrapper.c
+++ b/wrapper.c
@@ -189,6 +189,31 @@ void *xcalloc(size_t nmemb, size_t size)
 # endif
 #endif
 
+/**
+ * xopen() is the same as open(), but it die()s if the open() fails.
+ */
+int xopen(const char *path, int oflag, ...)
+{
+	mode_t mode = 0;
+	va_list ap;
+
+	va_start(ap, oflag);
+	if (oflag & O_CREAT)
+		mode = va_arg(ap, mode_t);
+	va_end(ap);
+
+	assert(path);
+
+	for (;;) {
+		int fd = open(path, oflag, mode);
+		if (fd >= 0)
+			return fd;
+		if (errno == EINTR)
+			continue;
+		die_errno(_("could not open '%s'"), path);
+	}
+}
+
 /*
  * xread() is the same a read(), but it automatically restarts read()
  * operations with a recoverable error (EAGAIN and EINTR). xread()
-- 
2.1.4

[PATCH/WIP v3 02/31] wrapper: implement xfopen()

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:22

A common usage pattern of fopen() is to check if it succeeded, and die()
if it failed:

	FILE *fp = fopen(path, "w");
	if (!fp)
		die_errno(_("could not open '%s' for writing"), path);

Implement a wrapper function xfopen() for the above, so that we can save
a few lines of code and make the die() messages consistent.

Signed-off-by: Paul Tan <redacted>
---
 git-compat-util.h |  1 +
 wrapper.c         | 18 ++++++++++++++++++
 2 files changed, 19 insertions(+)
diff --git a/git-compat-util.h b/git-compat-util.h
index bc77d77..4e69110 100644
--- a/git-compat-util.h
+++ b/git-compat-util.h
@@ -724,6 +724,7 @@ extern ssize_t xread(int fd, void *buf, size_t len);
 extern ssize_t xwrite(int fd, const void *buf, size_t len);
 extern ssize_t xpread(int fd, void *buf, size_t len, off_t offset);
 extern int xdup(int fd);
+extern FILE *xfopen(const char *path, const char *mode);
 extern FILE *xfdopen(int fd, const char *mode);
 extern int xmkstemp(char *template);
 extern int xmkstemp_mode(char *template, int mode);
diff --git a/wrapper.c b/wrapper.c
index 82658b3..9692460 100644
--- a/wrapper.c
+++ b/wrapper.c
@@ -336,6 +336,24 @@ int xdup(int fd)
 	return ret;
 }
 
+/**
+ * xfopen() is the same as fopen(), but it die()s if the fopen() fails.
+ */
+FILE *xfopen(const char *path, const char *mode)
+{
+	assert(path);
+	assert(mode);
+
+	for (;;) {
+		FILE *fp = fopen(path, mode);
+		if (fp)
+			return fp;
+		if (errno == EINTR)
+			continue;
+		die_errno(_("could not open '%s'"), path);
+	}
+}
+
 FILE *xfdopen(int fd, const char *mode)
 {
 	FILE *stream = fdopen(fd, mode);
-- 
2.1.4

[PATCH/WIP v3 05/31] am: split out mbox/maildir patches with git-mailsplit

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:22

git-am.sh supports mbox, stgit and mercurial patches. Re-implement
support for splitting out mbox/maildirs using git-mailsplit, while also
implementing the framework required to support other patch formats in
the future.

Re-implement support for the --patch-format option (since a5a6755
(git-am foreign patch support: introduce patch_format, 2009-05-27)) to
allow the user to choose between the different patch formats.

Signed-off-by: Paul Tan <redacted>
---

Notes:
    v3
    
    * Moved the TODO comment to the previous patch

 builtin/am.c | 104 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 101 insertions(+), 3 deletions(-)
diff --git a/builtin/am.c b/builtin/am.c
index af68c51..e9a3687 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -8,6 +8,12 @@
 #include "exec_cmd.h"
 #include "parse-options.h"
 #include "dir.h"
+#include "run-command.h"
+
+enum patch_format {
+	PATCH_FORMAT_UNKNOWN = 0,
+	PATCH_FORMAT_MBOX
+};
 
 struct am_state {
 	/* state directory path */
@@ -16,6 +22,9 @@ struct am_state {
 	/* current and last patch numbers, 1-indexed */
 	int cur;
 	int last;
+
+	/* number of digits in patch filename */
+	int prec;
 };
 
 /**
@@ -26,6 +35,8 @@ static void am_state_init(struct am_state *state)
 	memset(state, 0, sizeof(*state));
 
 	strbuf_init(&state->dir, 0);
+
+	state->prec = 4;
 }
 
 /**
@@ -111,13 +122,69 @@ static void am_destroy(const struct am_state *state)
 }
 
 /**
+ * Splits out individual patches from `paths`, where each path is either a mbox
+ * file or a Maildir. Return 0 on success, -1 on failure.
+ */
+static int split_patches_mbox(struct am_state *state, struct string_list *paths)
+{
+	struct child_process cp = CHILD_PROCESS_INIT;
+	struct string_list_item *item;
+	struct strbuf last = STRBUF_INIT;
+
+	cp.git_cmd = 1;
+	argv_array_push(&cp.args, "mailsplit");
+	argv_array_pushf(&cp.args, "-d%d", state->prec);
+	argv_array_pushf(&cp.args, "-o%s", state->dir.buf);
+	argv_array_push(&cp.args, "-b");
+	argv_array_push(&cp.args, "--");
+
+	for_each_string_list_item(item, paths)
+		argv_array_push(&cp.args, item->string);
+
+	if (capture_command(&cp, &last, 8))
+		return -1;
+
+	state->cur = 1;
+	state->last = strtol(last.buf, NULL, 10);
+
+	return 0;
+}
+
+/**
+ * Splits out individual patches, of patch_format, contained within paths.
+ * These patches will be stored in the state directory, with each patch's
+ * filename being its index, padded to state->prec digits. state->cur will be
+ * set to the index of the first patch, and state->last will be set to the
+ * index of the last patch.
+ *
+ * Returns 0 on success, -1 on failure.
+ */
+static int split_patches(struct am_state *state, enum patch_format patch_format,
+		struct string_list *paths)
+{
+	switch (patch_format) {
+	case PATCH_FORMAT_MBOX:
+		return split_patches_mbox(state, paths);
+	default:
+		die("BUG: invalid patch_format");
+	}
+	return -1;
+}
+
+/**
  * Setup a new am session for applying patches
  */
-static void am_setup(struct am_state *state)
+static void am_setup(struct am_state *state, enum patch_format patch_format,
+		struct string_list *paths)
 {
 	if (mkdir(state->dir.buf, 0777) < 0 && errno != EEXIST)
 		die_errno(_("failed to create directory '%s'"), state->dir.buf);
 
+	if (split_patches(state, patch_format, paths) < 0) {
+		am_destroy(state);
+		die(_("Failed to split patches."));
+	}
+
 	write_file(am_path(state, "next"), 1, "%d", state->cur);
 
 	write_file(am_path(state, "last"), 1, "%d", state->last);
@@ -148,7 +215,23 @@ static void am_run(struct am_state *state)
 	am_destroy(state);
 }
 
+/**
+ * parse_options() callback that validates and sets opt->value to the
+ * PATCH_FORMAT_* enum value corresponding to `arg`.
+ */
+static int parse_opt_patchformat(const struct option *opt, const char *arg, int unset)
+{
+	int *opt_value = opt->value;
+
+	if (!strcmp(arg, "mbox"))
+		*opt_value = PATCH_FORMAT_MBOX;
+	else
+		return -1;
+	return 0;
+}
+
 static struct am_state state;
+static int opt_patch_format;
 
 static const char * const am_usage[] = {
 	N_("git am [options] [(<mbox>|<Maildir>)...]"),
@@ -156,6 +239,8 @@ static const char * const am_usage[] = {
 };
 
 static struct option am_options[] = {
+	OPT_CALLBACK(0, "patch-format", &opt_patch_format, N_("format"),
+		N_("format the patch(es) are in"), parse_opt_patchformat),
 	OPT_END()
 };
 
@@ -185,8 +270,21 @@ int cmd_am(int argc, const char **argv, const char *prefix)
 
 	if (am_in_progress(&state))
 		am_load(&state);
-	else
-		am_setup(&state);
+	else {
+		struct string_list paths = STRING_LIST_INIT_DUP;
+		int i;
+
+		for (i = 0; i < argc; i++) {
+			if (is_absolute_path(argv[i]) || !prefix)
+				string_list_append(&paths, argv[i]);
+			else
+				string_list_append(&paths, mkpath("%s/%s", prefix, argv[i]));
+		}
+
+		am_setup(&state, opt_patch_format, &paths);
+
+		string_list_clear(&paths, 0);
+	}
 
 	am_run(&state);
 
-- 
2.1.4

[PATCH/WIP v3 03/31] am: implement skeletal builtin am

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:22

For the purpose of rewriting git-am.sh into a C builtin, implement a
skeletal builtin/am.c that redirects to $GIT_EXEC_PATH/git-am if the
environment variable _GIT_USE_BUILTIN_AM is not defined. Since in the
Makefile git-am.sh takes precedence over builtin/am.c,
$GIT_EXEC_PATH/git-am will contain the shell script git-am.sh, and thus
this allows us to fall back on the functional git-am.sh when running the
test suite for tests that depend on a working git-am implementation.

Since git-am.sh cannot handle any environment modifications by
setup_git_directory(), "am" has to be declared as NO_SETUP in git.c. On
the other hand, to re-implement git-am.sh in builtin/am.c, we do need to
run all the git dir and work tree setup logic that git.c does for us. As
such, we work around this temporarily by copying the logic in git.c's
run_builtin(), which amounts to:

	prefix = setup_git_directory();
	trace_repo_setup(prefix);
	setup_work_tree();

This redirection should be removed when all the features of git-am.sh
have been re-implemented in builtin/am.c.

Helped-by: Junio C Hamano [off-list ref]
Signed-off-by: Paul Tan <redacted>
---

Notes:
    v3
    
    * Style fixes
    
    * git-am.sh cannot handle the chdir() and GIT_DIR envionment variable
      that setup_git_directory() sets, so we work around it by copying the
      logic of git.c's run_builtin(), and running it only when we are using
      the builtin am.

 Makefile     |  1 +
 builtin.h    |  1 +
 builtin/am.c | 28 ++++++++++++++++++++++++++++
 git.c        |  1 +
 4 files changed, 31 insertions(+)
 create mode 100644 builtin/am.c
diff --git a/Makefile b/Makefile
index 93e4fa2..ff9bdc0 100644
--- a/Makefile
+++ b/Makefile
@@ -811,6 +811,7 @@ LIB_OBJS += xdiff-interface.o
 LIB_OBJS += zlib.o
 
 BUILTIN_OBJS += builtin/add.o
+BUILTIN_OBJS += builtin/am.o
 BUILTIN_OBJS += builtin/annotate.o
 BUILTIN_OBJS += builtin/apply.o
 BUILTIN_OBJS += builtin/archive.o
diff --git a/builtin.h b/builtin.h
index ea3c834..f30cf00 100644
--- a/builtin.h
+++ b/builtin.h
@@ -30,6 +30,7 @@ extern int textconv_object(const char *path, unsigned mode, const unsigned char
 extern int is_builtin(const char *s);
 
 extern int cmd_add(int argc, const char **argv, const char *prefix);
+extern int cmd_am(int argc, const char **argv, const char *prefix);
 extern int cmd_annotate(int argc, const char **argv, const char *prefix);
 extern int cmd_apply(int argc, const char **argv, const char *prefix);
 extern int cmd_archive(int argc, const char **argv, const char *prefix);
diff --git a/builtin/am.c b/builtin/am.c
new file mode 100644
index 0000000..dbc8836
--- /dev/null
+++ b/builtin/am.c
@@ -0,0 +1,28 @@
+/*
+ * Builtin "git am"
+ *
+ * Based on git-am.sh by Junio C Hamano.
+ */
+#include "cache.h"
+#include "builtin.h"
+#include "exec_cmd.h"
+
+int cmd_am(int argc, const char **argv, const char *prefix)
+{
+	/*
+	 * FIXME: Once all the features of git-am.sh have been re-implemented
+	 * in builtin/am.c, this preamble can be removed.
+	 */
+	if (!getenv("_GIT_USE_BUILTIN_AM")) {
+		const char *path = mkpath("%s/git-am", git_exec_path());
+
+		if (sane_execvp(path, (char **)argv) < 0)
+			die_errno("could not exec %s", path);
+	} else {
+		prefix = setup_git_directory();
+		trace_repo_setup(prefix);
+		setup_work_tree();
+	}
+
+	return 0;
+}
diff --git a/git.c b/git.c
index e7a7713..a671535 100644
--- a/git.c
+++ b/git.c
@@ -370,6 +370,7 @@ static int run_builtin(struct cmd_struct *p, int argc, const char **argv)
 
 static struct cmd_struct commands[] = {
 	{ "add", cmd_add, RUN_SETUP | NEED_WORK_TREE },
+	{ "am", cmd_am, NO_SETUP },
 	{ "annotate", cmd_annotate, RUN_SETUP },
 	{ "apply", cmd_apply, RUN_SETUP_GENTLY },
 	{ "archive", cmd_archive },
-- 
2.1.4

[PATCH/WIP v3 06/31] am: detect mbox patches

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:22

Since 15ced75 (git-am foreign patch support: autodetect some patch
formats, 2009-05-27), git-am.sh is able to autodetect mbox, stgit and
mercurial patches through heuristics.

Re-implement support for autodetecting mbox/maildir files.

Helped-by: Eric Sunshine [off-list ref]
Signed-off-by: Paul Tan <redacted>
---
 builtin/am.c | 98 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 98 insertions(+)
diff --git a/builtin/am.c b/builtin/am.c
index e9a3687..7b97ea8 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -121,6 +121,96 @@ static void am_destroy(const struct am_state *state)
 	strbuf_release(&sb);
 }
 
+/*
+ * Returns 1 if the file looks like a piece of email a-la RFC2822, 0 otherwise.
+ * We check this by grabbing all the non-indented lines and seeing if they look
+ * like they begin with valid header field names.
+ */
+static int is_email(const char *filename)
+{
+	struct strbuf sb = STRBUF_INIT;
+	FILE *fp = xfopen(filename, "r");
+	int ret = 1;
+
+	while (!strbuf_getline(&sb, fp, '\n')) {
+		const char *x;
+
+		strbuf_rtrim(&sb);
+
+		if (!sb.len)
+			break; /* End of header */
+
+		/* Ignore indented folded lines */
+		if (*sb.buf == '\t' || *sb.buf == ' ')
+			continue;
+
+		/* It's a header if it matches the regexp "^[!-9;-~]+:" */
+		for (x = sb.buf; *x; x++) {
+			if (('!' <= *x && *x <= '9') || (';' <= *x && *x <= '~'))
+				continue;
+			if (*x == ':' && x != sb.buf)
+				break;
+			ret = 0;
+			goto done;
+		}
+	}
+
+done:
+	fclose(fp);
+	strbuf_release(&sb);
+	return ret;
+}
+
+/**
+ * Attempts to detect the patch_format of the patches contained in `paths`,
+ * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
+ * detection fails.
+ */
+static int detect_patch_format(struct string_list *paths)
+{
+	enum patch_format ret = PATCH_FORMAT_UNKNOWN;
+	struct strbuf l1 = STRBUF_INIT;
+	struct strbuf l2 = STRBUF_INIT;
+	struct strbuf l3 = STRBUF_INIT;
+	FILE *fp;
+
+	/*
+	 * We default to mbox format if input is from stdin and for directories
+	 */
+	if (!paths->nr || !strcmp(paths->items->string, "-") ||
+	    is_directory(paths->items->string)) {
+		ret = PATCH_FORMAT_MBOX;
+		goto done;
+	}
+
+	/*
+	 * Otherwise, check the first 3 lines of the first patch, starting
+	 * from the first non-blank line, to try to detect its format.
+	 */
+	fp = xfopen(paths->items->string, "r");
+	while (!strbuf_getline(&l1, fp, '\n')) {
+		strbuf_trim(&l1);
+		if (l1.len)
+			break;
+	}
+	strbuf_getline(&l2, fp, '\n');
+	strbuf_trim(&l2);
+	strbuf_getline(&l3, fp, '\n');
+	strbuf_trim(&l3);
+	fclose(fp);
+
+	if (starts_with(l1.buf, "From ") || starts_with(l1.buf, "From: "))
+		ret = PATCH_FORMAT_MBOX;
+	else if (l1.len && l2.len && l3.len && is_email(paths->items->string))
+		ret = PATCH_FORMAT_MBOX;
+
+done:
+	strbuf_release(&l1);
+	strbuf_release(&l2);
+	strbuf_release(&l3);
+	return ret;
+}
+
 /**
  * Splits out individual patches from `paths`, where each path is either a mbox
  * file or a Maildir. Return 0 on success, -1 on failure.
@@ -177,6 +267,14 @@ static int split_patches(struct am_state *state, enum patch_format patch_format,
 static void am_setup(struct am_state *state, enum patch_format patch_format,
 		struct string_list *paths)
 {
+	if (!patch_format)
+		patch_format = detect_patch_format(paths);
+
+	if (!patch_format) {
+		fprintf_ln(stderr, _("Patch format detection failed."));
+		exit(128);
+	}
+
 	if (mkdir(state->dir.buf, 0777) < 0 && errno != EEXIST)
 		die_errno(_("failed to create directory '%s'"), state->dir.buf);
 
-- 
2.1.4

[PATCH/WIP v3 08/31] am: apply patch with git-apply

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:22

Implement applying the patch to the index using git-apply.

Signed-off-by: Paul Tan <redacted>
---
 builtin/am.c | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 56 insertions(+), 1 deletion(-)
diff --git a/builtin/am.c b/builtin/am.c
index d6434e4..296a5fc 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -27,6 +27,18 @@ static int is_empty_file(const char *filename)
 	return !st.st_size;
 }
 
+/**
+ * Returns the first line of msg
+ */
+static const char *firstline(const char *msg)
+{
+	static struct strbuf sb = STRBUF_INIT;
+
+	strbuf_reset(&sb);
+	strbuf_add(&sb, msg, strchrnul(msg, '\n') - msg);
+	return sb.buf;
+}
+
 enum patch_format {
 	PATCH_FORMAT_UNKNOWN = 0,
 	PATCH_FORMAT_MBOX
@@ -519,6 +531,31 @@ static int parse_patch(struct am_state *state, const char *patch)
 	return 0;
 }
 
+/*
+ * Applies current patch with git-apply. Returns 0 on success, -1 otherwise.
+ */
+static int run_apply(const struct am_state *state)
+{
+	struct child_process cp = CHILD_PROCESS_INIT;
+
+	cp.git_cmd = 1;
+
+	argv_array_push(&cp.args, "apply");
+
+	argv_array_push(&cp.args, "--index");
+
+	argv_array_push(&cp.args, am_path(state, "patch"));
+
+	if (run_command(&cp))
+		return -1;
+
+	/* Reload index as git-apply will have modified it. */
+	discard_cache();
+	read_cache();
+
+	return 0;
+}
+
 /**
  * Applies all queued patches.
  */
@@ -536,7 +573,25 @@ static void am_run(struct am_state *state)
 		write_author_script(state);
 		write_file(am_path(state, "final-commit"), 1, "%s", state->msg.buf);
 
-		/* TODO: Patch application not implemented yet */
+		printf_ln(_("Applying: %s"), firstline(state->msg.buf));
+
+		if (run_apply(state) < 0) {
+			int value;
+
+			printf_ln(_("Patch failed at %s %s"), msgnum(state),
+					firstline(state->msg.buf));
+
+			if (!git_config_get_bool("advice.amworkdir", &value) && !value)
+				printf_ln(_("The copy of the patch that failed is found in: %s"),
+						am_path(state, "patch"));
+
+			exit(128);
+		}
+
+		/*
+		 * TODO: After the patch has been applied to the index with
+		 * git-apply, we need to make commit as well.
+		 */
 
 next:
 		am_next(state);
-- 
2.1.4

[PATCH/WIP v3 04/31] am: implement patch queue mechanism

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:22

git-am applies a series of patches. If the process terminates
abnormally, we want to be able to resume applying the series of patches.
This requires the session state to be saved in a persistent location.

Implement the mechanism of a "patch queue", represented by 2 integers --
the index of the current patch we are applying and the index of the last
patch, as well as its lifecycle through the following functions:

* am_setup(), which will set up the state directory
  $GIT_DIR/rebase-apply. As such, even if the process exits abnormally,
  the last-known state will still persist.

* am_load(), which is called if there is an am session in
  progress, to load the last known state from the state directory so we
  can resume applying patches.

* am_run(), which will do the actual patch application. After applying a
  patch, it calls am_next() to increment the current patch index. The
  logic for applying and committing a patch is not implemented yet.

* am_destroy(), which is finally called when we successfully applied all
  the patches in the queue, to clean up by removing the state directory
  and its contents.

Signed-off-by: Paul Tan <redacted>
---
 builtin/am.c | 168 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 168 insertions(+)
diff --git a/builtin/am.c b/builtin/am.c
index dbc8836..af68c51 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -6,6 +6,158 @@
 #include "cache.h"
 #include "builtin.h"
 #include "exec_cmd.h"
+#include "parse-options.h"
+#include "dir.h"
+
+struct am_state {
+	/* state directory path */
+	struct strbuf dir;
+
+	/* current and last patch numbers, 1-indexed */
+	int cur;
+	int last;
+};
+
+/**
+ * Initializes am_state with the default values.
+ */
+static void am_state_init(struct am_state *state)
+{
+	memset(state, 0, sizeof(*state));
+
+	strbuf_init(&state->dir, 0);
+}
+
+/**
+ * Release memory allocated by an am_state.
+ */
+static void am_state_release(struct am_state *state)
+{
+	strbuf_release(&state->dir);
+}
+
+/**
+ * Returns path relative to the am_state directory.
+ */
+static inline const char *am_path(const struct am_state *state, const char *path)
+{
+	return mkpath("%s/%s", state->dir.buf, path);
+}
+
+/**
+ * Returns 1 if there is an am session in progress, 0 otherwise.
+ */
+static int am_in_progress(const struct am_state *state)
+{
+	struct stat st;
+
+	if (lstat(state->dir.buf, &st) < 0 || !S_ISDIR(st.st_mode))
+		return 0;
+	if (lstat(am_path(state, "last"), &st) || !S_ISREG(st.st_mode))
+		return 0;
+	if (lstat(am_path(state, "next"), &st) || !S_ISREG(st.st_mode))
+		return 0;
+	return 1;
+}
+
+/**
+ * Reads the contents of `file`. The third argument can be used to give a hint
+ * about the file size, to avoid reallocs. Returns number of bytes read on
+ * success, -1 if the file does not exist. If trim is set, trailing whitespace
+ * will be removed from the file contents.
+ */
+static int read_state_file(struct strbuf *sb, const char *file, size_t hint, int trim)
+{
+	strbuf_reset(sb);
+	if (strbuf_read_file(sb, file, hint) >= 0) {
+		if (trim)
+			strbuf_trim(sb);
+
+		return sb->len;
+	}
+
+	if (errno == ENOENT)
+		return -1;
+
+	die_errno(_("could not read '%s'"), file);
+}
+
+/**
+ * Loads state from disk.
+ */
+static void am_load(struct am_state *state)
+{
+	struct strbuf sb = STRBUF_INIT;
+
+	read_state_file(&sb, am_path(state, "next"), 8, 1);
+	state->cur = strtol(sb.buf, NULL, 10);
+
+	read_state_file(&sb, am_path(state, "last"), 8, 1);
+	state->last = strtol(sb.buf, NULL, 10);
+
+	strbuf_release(&sb);
+}
+
+/**
+ * Remove the am_state directory.
+ */
+static void am_destroy(const struct am_state *state)
+{
+	struct strbuf sb = STRBUF_INIT;
+
+	strbuf_addstr(&sb, state->dir.buf);
+	remove_dir_recursively(&sb, 0);
+	strbuf_release(&sb);
+}
+
+/**
+ * Setup a new am session for applying patches
+ */
+static void am_setup(struct am_state *state)
+{
+	if (mkdir(state->dir.buf, 0777) < 0 && errno != EEXIST)
+		die_errno(_("failed to create directory '%s'"), state->dir.buf);
+
+	write_file(am_path(state, "next"), 1, "%d", state->cur);
+
+	write_file(am_path(state, "last"), 1, "%d", state->last);
+}
+
+/**
+ * Increments the patch pointer, and cleans am_state for the application of the
+ * next patch.
+ */
+static void am_next(struct am_state *state)
+{
+	state->cur++;
+	write_file(am_path(state, "next"), 1, "%d", state->cur);
+}
+
+/**
+ * Applies all queued patches.
+ */
+static void am_run(struct am_state *state)
+{
+	while (state->cur <= state->last) {
+
+		/* TODO: Patch application not implemented yet */
+
+		am_next(state);
+	}
+
+	am_destroy(state);
+}
+
+static struct am_state state;
+
+static const char * const am_usage[] = {
+	N_("git am [options] [(<mbox>|<Maildir>)...]"),
+	NULL
+};
+
+static struct option am_options[] = {
+	OPT_END()
+};
 
 int cmd_am(int argc, const char **argv, const char *prefix)
 {
@@ -24,5 +176,21 @@ int cmd_am(int argc, const char **argv, const char *prefix)
 		setup_work_tree();
 	}
 
+	git_config(git_default_config, NULL);
+
+	am_state_init(&state);
+	strbuf_addstr(&state.dir, git_path("rebase-apply"));
+
+	argc = parse_options(argc, argv, prefix, am_options, am_usage, 0);
+
+	if (am_in_progress(&state))
+		am_load(&state);
+	else
+		am_setup(&state);
+
+	am_run(&state);
+
+	am_state_release(&state);
+
 	return 0;
 }
-- 
2.1.4

[PATCH/WIP v3 07/31] am: extract patch, message and authorship with git-mailinfo

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:22

For the purpose of applying the patch and committing the results,
implement extracting the patch data, commit message and authorship from
an e-mail message using git-mailinfo.

git-mailinfo is run as a separate process, but ideally in the future,
we should be be able to access its functionality directly without
spawning a new process.

Helped-by: Junio C Hamano [off-list ref]
Helped-by: Jeff King [off-list ref]
Signed-off-by: Paul Tan <redacted>
---
Notes:
    v3
    
    * Style fixes

 builtin/am.c | 232 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 232 insertions(+)
diff --git a/builtin/am.c b/builtin/am.c
index 7b97ea8..d6434e4 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -9,6 +9,23 @@
 #include "parse-options.h"
 #include "dir.h"
 #include "run-command.h"
+#include "quote.h"
+
+/**
+ * Returns 1 if the file is empty or does not exist, 0 otherwise.
+ */
+static int is_empty_file(const char *filename)
+{
+	struct stat st;
+
+	if (stat(filename, &st) < 0) {
+		if (errno == ENOENT)
+			return 1;
+		die_errno(_("could not stat %s"), filename);
+	}
+
+	return !st.st_size;
+}
 
 enum patch_format {
 	PATCH_FORMAT_UNKNOWN = 0,
@@ -23,6 +40,12 @@ struct am_state {
 	int cur;
 	int last;
 
+	/* commit message and metadata */
+	struct strbuf author_name;
+	struct strbuf author_email;
+	struct strbuf author_date;
+	struct strbuf msg;
+
 	/* number of digits in patch filename */
 	int prec;
 };
@@ -36,6 +59,11 @@ static void am_state_init(struct am_state *state)
 
 	strbuf_init(&state->dir, 0);
 
+	strbuf_init(&state->author_name, 0);
+	strbuf_init(&state->author_email, 0);
+	strbuf_init(&state->author_date, 0);
+	strbuf_init(&state->msg, 0);
+
 	state->prec = 4;
 }
 
@@ -45,6 +73,10 @@ static void am_state_init(struct am_state *state)
 static void am_state_release(struct am_state *state)
 {
 	strbuf_release(&state->dir);
+	strbuf_release(&state->author_name);
+	strbuf_release(&state->author_email);
+	strbuf_release(&state->author_date);
+	strbuf_release(&state->msg);
 }
 
 /**
@@ -94,6 +126,105 @@ static int read_state_file(struct strbuf *sb, const char *file, size_t hint, int
 }
 
 /**
+ * Reads a KEY=VALUE shell variable assignment from fp, and returns the VALUE
+ * in `value`. VALUE must be a quoted string, and the KEY must match `key`.
+ * Returns 0 on success, -1 on failure.
+ *
+ * This is used by read_author_script() to read the GIT_AUTHOR_* variables from
+ * the author-script.
+ */
+static int read_shell_var(struct strbuf *value, FILE *fp, const char *key)
+{
+	struct strbuf sb = STRBUF_INIT;
+	char *str;
+
+	if (strbuf_getline(&sb, fp, '\n'))
+		return -1;
+
+	if (!skip_prefix(sb.buf, key, (const char **)&str))
+		return -1;
+
+	if (!skip_prefix(str, "=", (const char **)&str))
+		return -1;
+
+	str = sq_dequote(str);
+	if (!str)
+		return -1;
+
+	strbuf_reset(value);
+	strbuf_addstr(value, str);
+
+	strbuf_release(&sb);
+
+	return 0;
+}
+
+/**
+ * Parses the "author script" `filename`, and sets state->author_name,
+ * state->author_email and state->author_date accordingly. We are strict with
+ * our parsing, as the author script is supposed to be eval'd, and loosely
+ * parsing it may not give the results the user expects.
+ *
+ * The author script is of the format:
+ *
+ *	GIT_AUTHOR_NAME='$author_name'
+ *	GIT_AUTHOR_EMAIL='$author_email'
+ *	GIT_AUTHOR_DATE='$author_date'
+ *
+ * where $author_name, $author_email and $author_date are quoted.
+ */
+static int read_author_script(struct am_state *state)
+{
+	const char *filename = am_path(state, "author-script");
+	FILE *fp = fopen(filename, "r");
+	if (!fp) {
+		if (errno == ENOENT)
+			return 0;
+		die_errno(_("could not open '%s' for reading"), filename);
+	}
+
+	if (read_shell_var(&state->author_name, fp, "GIT_AUTHOR_NAME"))
+		return -1;
+
+	if (read_shell_var(&state->author_email, fp, "GIT_AUTHOR_EMAIL"))
+		return -1;
+
+	if (read_shell_var(&state->author_date, fp, "GIT_AUTHOR_DATE"))
+		return -1;
+
+	if (fgetc(fp) != EOF)
+		return -1;
+
+	fclose(fp);
+	return 0;
+}
+
+/**
+ * Saves state->author_name, state->author_email and state->author_date in
+ * `filename` as an "author script", which is the format used by git-am.sh.
+ */
+static void write_author_script(const struct am_state *state)
+{
+	static const char fmt[] = "GIT_AUTHOR_NAME=%s\n"
+		"GIT_AUTHOR_EMAIL=%s\n"
+		"GIT_AUTHOR_DATE=%s\n";
+	struct strbuf author_name = STRBUF_INIT;
+	struct strbuf author_email = STRBUF_INIT;
+	struct strbuf author_date = STRBUF_INIT;
+
+	sq_quote_buf(&author_name, state->author_name.buf);
+	sq_quote_buf(&author_email, state->author_email.buf);
+	sq_quote_buf(&author_date, state->author_date.buf);
+
+	write_file(am_path(state, "author-script"), 1, fmt,
+			author_name.buf, author_email.buf, author_date.buf);
+
+	strbuf_release(&author_name);
+	strbuf_release(&author_email);
+	strbuf_release(&author_date);
+}
+
+/**
  * Loads state from disk.
  */
 static void am_load(struct am_state *state)
@@ -106,6 +237,11 @@ static void am_load(struct am_state *state)
 	read_state_file(&sb, am_path(state, "last"), 8, 1);
 	state->last = strtol(sb.buf, NULL, 10);
 
+	if (read_author_script(state) < 0)
+		die(_("could not parse author script"));
+
+	read_state_file(&state->msg, am_path(state, "final-commit"), 0, 0);
+
 	strbuf_release(&sb);
 }
 
@@ -296,6 +432,91 @@ static void am_next(struct am_state *state)
 {
 	state->cur++;
 	write_file(am_path(state, "next"), 1, "%d", state->cur);
+
+	strbuf_reset(&state->author_name);
+	strbuf_reset(&state->author_email);
+	strbuf_reset(&state->author_date);
+	unlink(am_path(state, "author-script"));
+
+	strbuf_reset(&state->msg);
+	unlink(am_path(state, "final-commit"));
+}
+
+/**
+ * Returns the filename of the current patch.
+ */
+static const char *msgnum(const struct am_state *state)
+{
+	static struct strbuf sb = STRBUF_INIT;
+
+	strbuf_reset(&sb);
+	strbuf_addf(&sb, "%0*d", state->prec, state->cur);
+
+	return sb.buf;
+}
+
+/**
+ * Parses `patch` using git-mailinfo. state->msg will be set to the patch
+ * message. state->author_name, state->author_email, state->author_date will be
+ * set to the patch author's name, email and date respectively. The patch's
+ * body will be written to "$state_dir/patch", where $state_dir is the state
+ * directory.
+ *
+ * Returns 1 if the patch should be skipped, 0 otherwise.
+ */
+static int parse_patch(struct am_state *state, const char *patch)
+{
+	FILE *fp;
+	struct child_process cp = CHILD_PROCESS_INIT;
+	struct strbuf sb = STRBUF_INIT;
+
+	cp.git_cmd = 1;
+	cp.in = xopen(patch, O_RDONLY, 0);
+	cp.out = xopen(am_path(state, "info"), O_WRONLY | O_CREAT, 0777);
+
+	argv_array_push(&cp.args, "mailinfo");
+	argv_array_push(&cp.args, am_path(state, "msg"));
+	argv_array_push(&cp.args, am_path(state, "patch"));
+
+	if (run_command(&cp) < 0)
+		die("could not parse patch");
+
+	close(cp.in);
+	close(cp.out);
+
+	/* Extract message and author information */
+	fp = xfopen(am_path(state, "info"), "r");
+	while (!strbuf_getline(&sb, fp, '\n')) {
+		const char *x;
+
+		if (skip_prefix(sb.buf, "Subject: ", &x)) {
+			if (state->msg.len)
+				strbuf_addch(&state->msg, '\n');
+			strbuf_addstr(&state->msg, x);
+		} else if (skip_prefix(sb.buf, "Author: ", &x))
+			strbuf_addstr(&state->author_name, x);
+		else if (skip_prefix(sb.buf, "Email: ", &x))
+			strbuf_addstr(&state->author_email, x);
+		else if (skip_prefix(sb.buf, "Date: ", &x))
+			strbuf_addstr(&state->author_date, x);
+	}
+	fclose(fp);
+
+	/* Skip pine's internal folder data */
+	if (!strcmp(state->author_name.buf, "Mail System Internal Data"))
+		return 1;
+
+	if (is_empty_file(am_path(state, "patch")))
+		die(_("Patch is empty. Was it split wrong?\n"
+		"If you would prefer to skip this patch, instead run \"git am --skip\".\n"
+		"To restore the original branch and stop patching run \"git am --abort\"."));
+
+	strbuf_addstr(&state->msg, "\n\n");
+	if (strbuf_read_file(&state->msg, am_path(state, "msg"), 0) < 0)
+		die_errno(_("could not read '%s'"), am_path(state, "msg"));
+	stripspace(&state->msg, 0);
+
+	return 0;
 }
 
 /**
@@ -304,9 +525,20 @@ static void am_next(struct am_state *state)
 static void am_run(struct am_state *state)
 {
 	while (state->cur <= state->last) {
+		const char *patch = am_path(state, msgnum(state));
+
+		if (!file_exists(patch))
+			goto next;
+
+		if (parse_patch(state, patch))
+			goto next; /* patch should be skipped */
+
+		write_author_script(state);
+		write_file(am_path(state, "final-commit"), 1, "%s", state->msg.buf);
 
 		/* TODO: Patch application not implemented yet */
 
+next:
 		am_next(state);
 	}
 
-- 
2.1.4

[PATCH/WIP v3 09/31] am: commit applied patch

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:22

Implement do_commit(), which commits the index which contains the
results of applying the patch, along with the extracted commit message
and authorship information.

Signed-off-by: Paul Tan <redacted>
---
 builtin/am.c | 51 +++++++++++++++++++++++++++++++++++++++++++++++----
 1 file changed, 47 insertions(+), 4 deletions(-)
diff --git a/builtin/am.c b/builtin/am.c
index 296a5fc..dfb6f7e 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -10,6 +10,9 @@
 #include "dir.h"
 #include "run-command.h"
 #include "quote.h"
+#include "cache-tree.h"
+#include "refs.h"
+#include "commit.h"
 
 /**
  * Returns 1 if the file is empty or does not exist, 0 otherwise.
@@ -557,6 +560,49 @@ static int run_apply(const struct am_state *state)
 }
 
 /**
+ * Commits the current index with state->msg as the commit message and
+ * state->author_name, state->author_email and state->author_date as the author
+ * information.
+ */
+static void do_commit(const struct am_state *state)
+{
+	unsigned char tree[GIT_SHA1_RAWSZ], parent[GIT_SHA1_RAWSZ],
+		      commit[GIT_SHA1_RAWSZ];
+	unsigned char *ptr;
+	struct commit_list *parents = NULL;
+	const char *reflog_msg, *author;
+	struct strbuf sb = STRBUF_INIT;
+
+	if (write_cache_as_tree(tree, 0, NULL))
+		die(_("git write-tree failed to write a tree"));
+
+	if (!get_sha1_commit("HEAD", parent)) {
+		ptr = parent;
+		commit_list_insert(lookup_commit(parent), &parents);
+	} else {
+		ptr = NULL;
+		fprintf_ln(stderr, _("applying to an empty history"));
+	}
+
+	author = fmt_ident(state->author_name.buf, state->author_email.buf,
+			state->author_date.buf, IDENT_STRICT);
+
+	if (commit_tree(state->msg.buf, state->msg.len, tree, parents, commit,
+				author, NULL))
+		die(_("failed to write commit object"));
+
+	reflog_msg = getenv("GIT_REFLOG_ACTION");
+	if (!reflog_msg)
+		reflog_msg = "am";
+
+	strbuf_addf(&sb, "%s: %s", reflog_msg, firstline(state->msg.buf));
+
+	update_ref(sb.buf, "HEAD", commit, ptr, 0, UPDATE_REFS_DIE_ON_ERR);
+
+	strbuf_release(&sb);
+}
+
+/**
  * Applies all queued patches.
  */
 static void am_run(struct am_state *state)
@@ -588,10 +634,7 @@ static void am_run(struct am_state *state)
 			exit(128);
 		}
 
-		/*
-		 * TODO: After the patch has been applied to the index with
-		 * git-apply, we need to make commit as well.
-		 */
+		do_commit(state);
 
 next:
 		am_next(state);
-- 
2.1.4

[PATCH/WIP v3 10/31] am: refresh the index at start

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:22

If a file is unchanged but stat-dirty, git-apply may erroneously fail to
apply patches, thinking that they conflict with a dirty working tree.

As such, since 2a6f08a (am: refresh the index at start and --resolved,
2011-08-15), git-am will refresh the index before applying patches.
Re-implement this behavior.

Signed-off-by: Paul Tan <redacted>
---
 builtin/am.c | 20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)
diff --git a/builtin/am.c b/builtin/am.c
index dfb6f7e..a7efe85 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -13,6 +13,7 @@
 #include "cache-tree.h"
 #include "refs.h"
 #include "commit.h"
+#include "lockfile.h"
 
 /**
  * Returns 1 if the file is empty or does not exist, 0 otherwise.
@@ -471,6 +472,20 @@ static const char *msgnum(const struct am_state *state)
 }
 
 /**
+ * Refresh and write index.
+ */
+static void refresh_and_write_cache(void)
+{
+	static struct lock_file lock_file;
+
+	hold_locked_index(&lock_file, 1);
+	refresh_cache(REFRESH_QUIET);
+	if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
+		die(_("unable to write index file"));
+	rollback_lock_file(&lock_file);
+}
+
+/**
  * Parses `patch` using git-mailinfo. state->msg will be set to the patch
  * message. state->author_name, state->author_email, state->author_date will be
  * set to the patch author's name, email and date respectively. The patch's
@@ -607,6 +622,8 @@ static void do_commit(const struct am_state *state)
  */
 static void am_run(struct am_state *state)
 {
+	refresh_and_write_cache();
+
 	while (state->cur <= state->last) {
 		const char *patch = am_path(state, msgnum(state));
 
@@ -696,6 +713,9 @@ int cmd_am(int argc, const char **argv, const char *prefix)
 
 	argc = parse_options(argc, argv, prefix, am_options, am_usage, 0);
 
+	if (read_index_preload(&the_index, NULL) < 0)
+		die(_("failed to read the index"));
+
 	if (am_in_progress(&state))
 		am_load(&state);
 	else {
-- 
2.1.4

[PATCH/WIP v3 13/31] am: implement --skip

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:22

Since d1c5f2a (Add git-am, applymbox replacement., 2005-10-07), git-am
supported resuming from a failed patch application by skipping the
current patch. Re-implement this feature by introducing am_skip().

Signed-off-by: Paul Tan <redacted>
---
 builtin/am.c | 121 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 119 insertions(+), 2 deletions(-)
diff --git a/builtin/am.c b/builtin/am.c
index 4381164..0d7af19 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -16,6 +16,8 @@
 #include "lockfile.h"
 #include "diff.h"
 #include "diffcore.h"
+#include "unpack-trees.h"
+#include "branch.h"
 
 /**
  * Returns 1 if the file is empty or does not exist, 0 otherwise.
@@ -735,6 +737,114 @@ static void am_resolve(struct am_state *state)
 }
 
 /**
+ * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
+ * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
+ * failure.
+ */
+static int fast_forward_to(struct tree *head, struct tree *remote, int reset)
+{
+	struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
+	struct unpack_trees_options opts;
+	struct tree_desc t[2];
+
+	if (parse_tree(head) || parse_tree(remote))
+		return -1;
+
+	hold_locked_index(lock_file, 1);
+
+	refresh_cache(REFRESH_QUIET);
+
+	memset(&opts, 0, sizeof(opts));
+	opts.head_idx = 1;
+	opts.src_index = &the_index;
+	opts.dst_index = &the_index;
+	opts.update = 1;
+	opts.merge = 1;
+	opts.reset = reset;
+	opts.fn = twoway_merge;
+	init_tree_desc(&t[0], head->buffer, head->size);
+	init_tree_desc(&t[1], remote->buffer, remote->size);
+
+	if (unpack_trees(2, t, &opts)) {
+		rollback_lock_file(lock_file);
+		return -1;
+	}
+
+	if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
+		die(_("unable to write new index file"));
+
+	return 0;
+}
+
+/**
+ * Clean the index without touching entries that are not modified between
+ * `head` and `remote`.
+ */
+static int clean_index(const unsigned char *head, const unsigned char *remote)
+{
+	struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
+	struct tree *head_tree, *remote_tree, *index_tree;
+	unsigned char index[GIT_SHA1_RAWSZ];
+	struct pathspec pathspec;
+
+	head_tree = parse_tree_indirect(head);
+	if (!head_tree)
+		return error(_("Could not parse object '%s'."), sha1_to_hex(head));
+
+	remote_tree = parse_tree_indirect(remote);
+	if (!remote_tree)
+		return error(_("Could not parse object '%s'."), sha1_to_hex(remote));
+
+	read_cache_unmerged();
+
+	if (fast_forward_to(head_tree, head_tree, 1))
+		return -1;
+
+	if (write_cache_as_tree(index, 0, NULL))
+		return -1;
+
+	index_tree = parse_tree_indirect(index);
+	if (!index_tree)
+		return error(_("Could not parse object '%s'."), sha1_to_hex(index));
+
+	if (fast_forward_to(index_tree, remote_tree, 0))
+		return -1;
+
+	memset(&pathspec, 0, sizeof(pathspec));
+
+	hold_locked_index(lock_file, 1);
+
+	if (read_tree(remote_tree, 0, &pathspec)) {
+		rollback_lock_file(lock_file);
+		return -1;
+	}
+
+	if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
+		die(_("unable to write new index file"));
+
+	remove_branch_state();
+
+	return 0;
+}
+
+/**
+ * Resume the current am session by skipping the current patch.
+ */
+static void am_skip(struct am_state *state)
+{
+	unsigned char head[GIT_SHA1_RAWSZ];
+
+	if (get_sha1("HEAD", head))
+		hashcpy(head, EMPTY_TREE_SHA1_BIN);
+
+	if (clean_index(head, head))
+		die(_("failed to clean index"));
+
+	am_next(state);
+	am_run(state);
+}
+
+/**
  * parse_options() callback that validates and sets opt->value to the
  * PATCH_FORMAT_* enum value corresponding to `arg`.
  */
@@ -751,7 +861,8 @@ static int parse_opt_patchformat(const struct option *opt, const char *arg, int
 
 enum resume_mode {
 	RESUME_FALSE = 0,
-	RESUME_RESOLVED
+	RESUME_RESOLVED,
+	RESUME_SKIP
 };
 
 static struct am_state state;
@@ -760,7 +871,7 @@ static enum resume_mode opt_resume;
 
 static const char * const am_usage[] = {
 	N_("git am [options] [(<mbox>|<Maildir>)...]"),
-	N_("git am [options] --continue"),
+	N_("git am [options] (--continue | --skip)"),
 	NULL
 };
 
@@ -773,6 +884,9 @@ static struct option am_options[] = {
 	OPT_CMDMODE('r', "resolved", &opt_resume,
 		N_("synonyms for --continue"),
 		RESUME_RESOLVED),
+	OPT_CMDMODE(0, "skip", &opt_resume,
+		N_("skip the current patch"),
+		RESUME_SKIP),
 	OPT_END()
 };
 
@@ -831,6 +945,9 @@ int cmd_am(int argc, const char **argv, const char *prefix)
 	case RESUME_RESOLVED:
 		am_resolve(&state);
 		break;
+	case RESUME_SKIP:
+		am_skip(&state);
+		break;
 	default:
 		die("BUG: invalid resume value");
 	}
-- 
2.1.4

[PATCH/WIP v3 12/31] am: implement --resolved/--continue

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:22

Since 0c15cc9 (git-am: --resolved., 2005-11-16), git-am supported
resuming from a failed patch application. The user will manually apply
the patch, and the run git am --resolved which will then commit the
resulting index. Re-implement this feature by introducing am_resolve().

Since it makes no sense for the user to run am --resolved when there is
no session in progress, we error out in this case.

Signed-off-by: Paul Tan <redacted>
---
 builtin/am.c | 55 ++++++++++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 54 insertions(+), 1 deletion(-)
diff --git a/builtin/am.c b/builtin/am.c
index 9d6ab2a..4381164 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -707,6 +707,34 @@ next:
 }
 
 /**
+ * Resume the current am session after patch application failure. The user did
+ * all the hard work, and we do not have to do any patch application. Just
+ * trust and commit what the user has in the index and working tree.
+ */
+static void am_resolve(struct am_state *state)
+{
+	printf_ln(_("Applying: %s"), firstline(state->msg.buf));
+
+	if (!index_has_changes(NULL)) {
+		printf_ln(_("No changes - did you forget to use 'git add'?\n"
+			"If there is nothing left to stage, chances are that something else\n"
+			"already introduced the same changes; you might want to skip this patch."));
+		exit(128);
+	}
+
+	if (unmerged_cache()) {
+		printf_ln(_("You still have unmerged paths in your index.\n"
+			"Did you forget to use 'git add'?"));
+		exit(128);
+	}
+
+	do_commit(state);
+
+	am_next(state);
+	am_run(state);
+}
+
+/**
  * parse_options() callback that validates and sets opt->value to the
  * PATCH_FORMAT_* enum value corresponding to `arg`.
  */
@@ -721,17 +749,30 @@ static int parse_opt_patchformat(const struct option *opt, const char *arg, int
 	return 0;
 }
 
+enum resume_mode {
+	RESUME_FALSE = 0,
+	RESUME_RESOLVED
+};
+
 static struct am_state state;
 static int opt_patch_format;
+static enum resume_mode opt_resume;
 
 static const char * const am_usage[] = {
 	N_("git am [options] [(<mbox>|<Maildir>)...]"),
+	N_("git am [options] --continue"),
 	NULL
 };
 
 static struct option am_options[] = {
 	OPT_CALLBACK(0, "patch-format", &opt_patch_format, N_("format"),
 		N_("format the patch(es) are in"), parse_opt_patchformat),
+	OPT_CMDMODE(0, "continue", &opt_resume,
+		N_("continue applying patches after resolving a conflict"),
+		RESUME_RESOLVED),
+	OPT_CMDMODE('r', "resolved", &opt_resume,
+		N_("synonyms for --continue"),
+		RESUME_RESOLVED),
 	OPT_END()
 };
 
@@ -768,6 +809,9 @@ int cmd_am(int argc, const char **argv, const char *prefix)
 		struct string_list paths = STRING_LIST_INIT_DUP;
 		int i;
 
+		if (opt_resume)
+			die(_("Resolve operation not in progress, we are not resuming."));
+
 		for (i = 0; i < argc; i++) {
 			if (is_absolute_path(argv[i]) || !prefix)
 				string_list_append(&paths, argv[i]);
@@ -780,7 +824,16 @@ int cmd_am(int argc, const char **argv, const char *prefix)
 		string_list_clear(&paths, 0);
 	}
 
-	am_run(&state);
+	switch (opt_resume) {
+	case RESUME_FALSE:
+		am_run(&state);
+		break;
+	case RESUME_RESOLVED:
+		am_resolve(&state);
+		break;
+	default:
+		die("BUG: invalid resume value");
+	}
 
 	am_state_release(&state);
 
-- 
2.1.4

[PATCH/WIP v3 14/31] am: implement --abort

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:22

Since 3e5057a (git am --abort, 2008-07-16), git-am supported the --abort
option that will rewind HEAD back to the original commit. Re-implement
this feature through am_abort().

Since 7b3b7e3 (am --abort: keep unrelated commits since the last failure
and warn, 2010-12-21), to prevent commits made since the last failure
from being lost, git-am will not rewind HEAD back to the original
commit if HEAD moved since the last failure. Re-implement this through
safe_to_abort().

Signed-off-by: Paul Tan <redacted>
---
 builtin/am.c | 95 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 92 insertions(+), 3 deletions(-)
diff --git a/builtin/am.c b/builtin/am.c
index 0d7af19..7053b8f 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -423,6 +423,8 @@ static int split_patches(struct am_state *state, enum patch_format patch_format,
 static void am_setup(struct am_state *state, enum patch_format patch_format,
 		struct string_list *paths)
 {
+	unsigned char curr_head[GIT_SHA1_RAWSZ];
+
 	if (!patch_format)
 		patch_format = detect_patch_format(paths);
 
@@ -442,6 +444,14 @@ static void am_setup(struct am_state *state, enum patch_format patch_format,
 	write_file(am_path(state, "next"), 1, "%d", state->cur);
 
 	write_file(am_path(state, "last"), 1, "%d", state->last);
+
+	if (!get_sha1("HEAD", curr_head)) {
+		write_file(am_path(state, "abort-safety"), 1, "%s", sha1_to_hex(curr_head));
+		update_ref("am", "ORIG_HEAD", curr_head, NULL, 0, UPDATE_REFS_DIE_ON_ERR);
+	} else {
+		write_file(am_path(state, "abort-safety"), 1, "%s", "");
+		delete_ref("ORIG_HEAD", NULL, 0);
+	}
 }
 
 /**
@@ -450,6 +460,8 @@ static void am_setup(struct am_state *state, enum patch_format patch_format,
  */
 static void am_next(struct am_state *state)
 {
+	unsigned char head[GIT_SHA1_RAWSZ];
+
 	state->cur++;
 	write_file(am_path(state, "next"), 1, "%d", state->cur);
 
@@ -460,6 +472,11 @@ static void am_next(struct am_state *state)
 
 	strbuf_reset(&state->msg);
 	unlink(am_path(state, "final-commit"));
+
+	if (!get_sha1("HEAD", head))
+		write_file(am_path(state, "abort-safety"), 1, "%s", sha1_to_hex(head));
+	else
+		write_file(am_path(state, "abort-safety"), 1, "%s", "");
 }
 
 /**
@@ -665,10 +682,14 @@ static void am_run(struct am_state *state)
 {
 	struct strbuf sb = STRBUF_INIT;
 
+	unlink(am_path(state, "dirtyindex"));
+
 	refresh_and_write_cache();
 
-	if (index_has_changes(&sb))
+	if (index_has_changes(&sb)) {
+		write_file(am_path(state, "dirtyindex"), 1, "t");
 		die(_("Dirty index: cannot apply patches (dirty: %s)"), sb.buf);
+	}
 
 	strbuf_release(&sb);
 
@@ -844,6 +865,67 @@ static void am_skip(struct am_state *state)
 	am_run(state);
 }
 
+static int safe_to_abort(const struct am_state *state)
+{
+	struct strbuf sb = STRBUF_INIT;
+	unsigned char abort_safety[GIT_SHA1_RAWSZ], head[GIT_SHA1_RAWSZ];
+
+	if (file_exists(am_path(state, "dirtyindex")))
+		return 0;
+
+	if (read_state_file(&sb, am_path(state, "abort-safety"), 40, 1) > 0) {
+		if (get_sha1_hex(sb.buf, abort_safety))
+			die(_("could not parse %s"), am_path(state, "abort_safety"));
+	} else
+		hashclr(abort_safety);
+
+	if (get_sha1("HEAD", head))
+		hashclr(head);
+
+	if (!hashcmp(head, abort_safety))
+		return 1;
+
+	error(_("You seem to have moved HEAD since the last 'am' failure.\n"
+		"Not rewinding to ORIG_HEAD"));
+
+	return 0;
+}
+
+/**
+ * Aborts the current am session if it is safe to do so.
+ */
+static void am_abort(struct am_state *state)
+{
+	unsigned char curr_head[GIT_SHA1_RAWSZ], orig_head[GIT_SHA1_RAWSZ];
+	int has_curr_head, has_orig_head;
+	const char *curr_branch;
+
+	if (!safe_to_abort(state)) {
+		am_destroy(state);
+		return;
+	}
+
+	curr_branch = resolve_refdup("HEAD", 0, curr_head, NULL);
+	has_curr_head = !is_null_sha1(curr_head);
+	if (!has_curr_head)
+		hashcpy(curr_head, EMPTY_TREE_SHA1_BIN);
+
+	has_orig_head = !get_sha1("ORIG_HEAD", orig_head);
+	if (!has_orig_head)
+		hashcpy(orig_head, EMPTY_TREE_SHA1_BIN);
+
+	clean_index(curr_head, orig_head);
+
+	if (has_orig_head)
+		update_ref("am --abort", "HEAD", orig_head,
+				has_curr_head ? curr_head : NULL, 0,
+				UPDATE_REFS_DIE_ON_ERR);
+	else if (curr_branch)
+		delete_ref(curr_branch, NULL, REF_NODEREF);
+
+	am_destroy(state);
+}
+
 /**
  * parse_options() callback that validates and sets opt->value to the
  * PATCH_FORMAT_* enum value corresponding to `arg`.
@@ -862,7 +944,8 @@ static int parse_opt_patchformat(const struct option *opt, const char *arg, int
 enum resume_mode {
 	RESUME_FALSE = 0,
 	RESUME_RESOLVED,
-	RESUME_SKIP
+	RESUME_SKIP,
+	RESUME_ABORT
 };
 
 static struct am_state state;
@@ -871,7 +954,7 @@ static enum resume_mode opt_resume;
 
 static const char * const am_usage[] = {
 	N_("git am [options] [(<mbox>|<Maildir>)...]"),
-	N_("git am [options] (--continue | --skip)"),
+	N_("git am [options] (--continue | --skip | --abort)"),
 	NULL
 };
 
@@ -887,6 +970,9 @@ static struct option am_options[] = {
 	OPT_CMDMODE(0, "skip", &opt_resume,
 		N_("skip the current patch"),
 		RESUME_SKIP),
+	OPT_CMDMODE(0, "abort", &opt_resume,
+		N_("restore the original branch and abort the patching operation."),
+		RESUME_ABORT),
 	OPT_END()
 };
 
@@ -948,6 +1034,9 @@ int cmd_am(int argc, const char **argv, const char *prefix)
 	case RESUME_SKIP:
 		am_skip(&state);
 		break;
+	case RESUME_ABORT:
+		am_abort(&state);
+		break;
 	default:
 		die("BUG: invalid resume value");
 	}
-- 
2.1.4

[PATCH/WIP v3 15/31] am: don't accept patches when there's a session in progress

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:22

Since d1c5f2a (Add git-am, applymbox replacement., 2005-10-07), git-am
would error out if the user gave it mbox(s) on the command-line, but
there was a session in progress.

Since c95b138 (Fix git-am safety checks, 2006-09-15), git-am would
detect if the user attempted to feed it a mbox via stdin, by checking if
stdin is not a tty and there is no resume command given.

Re-implement the above two safety checks.

Signed-off-by: Paul Tan <redacted>
---

Notes:
    NOTE: there's no test for this

 builtin/am.c | 19 +++++++++++++++++--
 1 file changed, 17 insertions(+), 2 deletions(-)
diff --git a/builtin/am.c b/builtin/am.c
index 7053b8f..4adc487 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -1003,9 +1003,24 @@ int cmd_am(int argc, const char **argv, const char *prefix)
 	if (read_index_preload(&the_index, NULL) < 0)
 		die(_("failed to read the index"));
 
-	if (am_in_progress(&state))
+	if (am_in_progress(&state)) {
+		/*
+		 * Catch user error to feed us patches when there is a session
+		 * in progress:
+		 *
+		 * 1. mbox path(s) are provided on the command-line.
+		 * 2. stdin is not a tty: the user is trying to feed us a patch
+		 *    from standard input. This is somewhat unreliable -- stdin
+		 *    could be /dev/null for example and the caller did not
+		 *    intend to feed us a patch but wanted to continue
+		 *    unattended.
+		 */
+		if (argc || (!opt_resume && !isatty(0)))
+			die(_("previous rebase directory %s still exists but mbox given."),
+				state.dir.buf);
+
 		am_load(&state);
-	else {
+	} else {
 		struct string_list paths = STRING_LIST_INIT_DUP;
 		int i;
 
-- 
2.1.4

[PATCH/WIP v3 17/31] am: exit with user friendly message on patch failure

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:22

Since ced9456 (Give the user a hint for how to continue in the case that
git-am fails because it requires user intervention, 2006-05-02), git-am
prints additional information on how the user can re-invoke git-am to
resume patch application after resolving the failure. Re-implement this
through the die_user_resolve() function.

Since cc12005 (Make git rebase interactive help match documentation.,
2006-05-13), git-am supports the --resolvemsg option which is used by
git-rebase to override the message printed out when git-am fails.
Re-implement this option.

Signed-off-by: Paul Tan <redacted>
---
 builtin/am.c | 26 +++++++++++++++++++++++---
 1 file changed, 23 insertions(+), 3 deletions(-)
diff --git a/builtin/am.c b/builtin/am.c
index 5f38264..1807d12 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -70,6 +70,9 @@ struct am_state {
 	int prec;
 
 	int quiet;
+
+	/* override error message when patch failure occurs */
+	const char *resolvemsg;
 };
 
 /**
@@ -636,6 +639,21 @@ static int parse_patch(struct am_state *state, const char *patch)
 	return 0;
 }
 
+/**
+ * Dies with a user-friendly message on how to proceed after resolving the
+ * problem. This message can be overridden with state->resolvemsg.
+ */
+static void NORETURN die_user_resolve(const struct am_state *state)
+{
+	if (state->resolvemsg)
+		printf_ln("%s", state->resolvemsg);
+	else
+		printf_ln(_("When you have resolved this problem, run \"git am --continue\".\n"
+			"If you prefer to skip this patch, run \"git am --skip\" instead.\n"
+			"To restore the original branch and stop patching, run \"git am --abort\"."));
+	exit(128);
+}
+
 /*
  * Applies current patch with git-apply. Returns 0 on success, -1 otherwise.
  */
@@ -746,7 +764,7 @@ static void am_run(struct am_state *state)
 				printf_ln(_("The copy of the patch that failed is found in: %s"),
 						am_path(state, "patch"));
 
-			exit(128);
+			die_user_resolve(state);
 		}
 
 		do_commit(state);
@@ -771,13 +789,13 @@ static void am_resolve(struct am_state *state)
 		printf_ln(_("No changes - did you forget to use 'git add'?\n"
 			"If there is nothing left to stage, chances are that something else\n"
 			"already introduced the same changes; you might want to skip this patch."));
-		exit(128);
+		die_user_resolve(state);
 	}
 
 	if (unmerged_cache()) {
 		printf_ln(_("You still have unmerged paths in your index.\n"
 			"Did you forget to use 'git add'?"));
-		exit(128);
+		die_user_resolve(state);
 	}
 
 	do_commit(state);
@@ -991,6 +1009,8 @@ static struct option am_options[] = {
 	OPT__QUIET(&state.quiet, N_("be quiet")),
 	OPT_CALLBACK(0, "patch-format", &opt_patch_format, N_("format"),
 		N_("format the patch(es) are in"), parse_opt_patchformat),
+	OPT_STRING(0, "resolvemsg", &state.resolvemsg, NULL,
+		N_("override error message when patch failure occurs")),
 	OPT_CMDMODE(0, "continue", &opt_resume,
 		N_("continue applying patches after resolving a conflict"),
 		RESUME_RESOLVED),
-- 
2.1.4

[PATCH/WIP v3 16/31] am: implement quiet option

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:22

Since 0e987a1 (am, rebase: teach quiet option, 2009-06-16), git-am
supported the --quiet option and GIT_QUIET environment variable, and
when told to be quiet, would only speak on failure. Re-implement this by
introducing the say() function, which works like fprintf_ln(), but would
only write to the stream when state->quiet is false.

Signed-off-by: Paul Tan <redacted>
---
 builtin/am.c | 36 +++++++++++++++++++++++++++++++++---
 1 file changed, 33 insertions(+), 3 deletions(-)
diff --git a/builtin/am.c b/builtin/am.c
index 4adc487..5f38264 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -68,6 +68,8 @@ struct am_state {
 
 	/* number of digits in patch filename */
 	int prec;
+
+	int quiet;
 };
 
 /**
@@ -75,6 +77,8 @@ struct am_state {
  */
 static void am_state_init(struct am_state *state)
 {
+	const char *quiet;
+
 	memset(state, 0, sizeof(*state));
 
 	strbuf_init(&state->dir, 0);
@@ -85,6 +89,10 @@ static void am_state_init(struct am_state *state)
 	strbuf_init(&state->msg, 0);
 
 	state->prec = 4;
+
+	quiet = getenv("GIT_QUIET");
+	if (quiet && *quiet)
+		state->quiet = 1;
 }
 
 /**
@@ -108,6 +116,22 @@ static inline const char *am_path(const struct am_state *state, const char *path
 }
 
 /**
+ * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
+ * at the end.
+ */
+static void say(const struct am_state *state, FILE *fp, const char *fmt, ...)
+{
+	va_list ap;
+
+	va_start(ap, fmt);
+	if (!state->quiet) {
+		vfprintf(fp, fmt, ap);
+		putc('\n', fp);
+	}
+	va_end(ap);
+}
+
+/**
  * Returns 1 if there is an am session in progress, 0 otherwise.
  */
 static int am_in_progress(const struct am_state *state)
@@ -262,6 +286,9 @@ static void am_load(struct am_state *state)
 
 	read_state_file(&state->msg, am_path(state, "final-commit"), 0, 0);
 
+	read_state_file(&sb, am_path(state, "quiet"), 2, 1);
+	state->quiet = !strcmp(sb.buf, "t");
+
 	strbuf_release(&sb);
 }
 
@@ -445,6 +472,8 @@ static void am_setup(struct am_state *state, enum patch_format patch_format,
 
 	write_file(am_path(state, "last"), 1, "%d", state->last);
 
+	write_file(am_path(state, "quiet"), 1, state->quiet ? "t" : "f");
+
 	if (!get_sha1("HEAD", curr_head)) {
 		write_file(am_path(state, "abort-safety"), 1, "%s", sha1_to_hex(curr_head));
 		update_ref("am", "ORIG_HEAD", curr_head, NULL, 0, UPDATE_REFS_DIE_ON_ERR);
@@ -654,7 +683,7 @@ static void do_commit(const struct am_state *state)
 		commit_list_insert(lookup_commit(parent), &parents);
 	} else {
 		ptr = NULL;
-		fprintf_ln(stderr, _("applying to an empty history"));
+		say(state, stderr, _("applying to an empty history"));
 	}
 
 	author = fmt_ident(state->author_name.buf, state->author_email.buf,
@@ -705,7 +734,7 @@ static void am_run(struct am_state *state)
 		write_author_script(state);
 		write_file(am_path(state, "final-commit"), 1, "%s", state->msg.buf);
 
-		printf_ln(_("Applying: %s"), firstline(state->msg.buf));
+		say(state, stdout, _("Applying: %s"), firstline(state->msg.buf));
 
 		if (run_apply(state) < 0) {
 			int value;
@@ -736,7 +765,7 @@ next:
  */
 static void am_resolve(struct am_state *state)
 {
-	printf_ln(_("Applying: %s"), firstline(state->msg.buf));
+	say(state, stdout, _("Applying: %s"), firstline(state->msg.buf));
 
 	if (!index_has_changes(NULL)) {
 		printf_ln(_("No changes - did you forget to use 'git add'?\n"
@@ -959,6 +988,7 @@ static const char * const am_usage[] = {
 };
 
 static struct option am_options[] = {
+	OPT__QUIET(&state.quiet, N_("be quiet")),
 	OPT_CALLBACK(0, "patch-format", &opt_patch_format, N_("format"),
 		N_("format the patch(es) are in"), parse_opt_patchformat),
 	OPT_CMDMODE(0, "continue", &opt_resume,
-- 
2.1.4

[PATCH/WIP v3 19/31] cache-tree: introduce write_index_as_tree()

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:22

A caller may wish to write a temporary index as a tree. However,
write_cache_as_tree() assumes that the index was read from, and will
write to, the default index file path. Introduce write_index_as_tree()
which removes this limitation by allowing the caller to specify its own
index_state and index file path.

Signed-off-by: Paul Tan <redacted>
---
 cache-tree.c | 29 +++++++++++++++++------------
 cache-tree.h |  1 +
 2 files changed, 18 insertions(+), 12 deletions(-)
diff --git a/cache-tree.c b/cache-tree.c
index 32772b9..feace8b 100644
--- a/cache-tree.c
+++ b/cache-tree.c
@@ -592,7 +592,7 @@ static struct cache_tree *cache_tree_find(struct cache_tree *it, const char *pat
 	return it;
 }
 
-int write_cache_as_tree(unsigned char *sha1, int flags, const char *prefix)
+int write_index_as_tree(unsigned char *sha1, struct index_state *index_state, const char *index_path, int flags, const char *prefix)
 {
 	int entries, was_valid, newfd;
 	struct lock_file *lock_file;
@@ -603,23 +603,23 @@ int write_cache_as_tree(unsigned char *sha1, int flags, const char *prefix)
 	 */
 	lock_file = xcalloc(1, sizeof(struct lock_file));
 
-	newfd = hold_locked_index(lock_file, 1);
+	newfd = hold_lock_file_for_update(lock_file, index_path, LOCK_DIE_ON_ERROR);
 
-	entries = read_cache();
+	entries = read_index_from(index_state, index_path);
 	if (entries < 0)
 		return WRITE_TREE_UNREADABLE_INDEX;
 	if (flags & WRITE_TREE_IGNORE_CACHE_TREE)
-		cache_tree_free(&(active_cache_tree));
+		cache_tree_free(&index_state->cache_tree);
 
-	if (!active_cache_tree)
-		active_cache_tree = cache_tree();
+	if (!index_state->cache_tree)
+		index_state->cache_tree = cache_tree();
 
-	was_valid = cache_tree_fully_valid(active_cache_tree);
+	was_valid = cache_tree_fully_valid(index_state->cache_tree);
 	if (!was_valid) {
-		if (cache_tree_update(&the_index, flags) < 0)
+		if (cache_tree_update(index_state, flags) < 0)
 			return WRITE_TREE_UNMERGED_INDEX;
 		if (0 <= newfd) {
-			if (!write_locked_index(&the_index, lock_file, COMMIT_LOCK))
+			if (!write_locked_index(index_state, lock_file, COMMIT_LOCK))
 				newfd = -1;
 		}
 		/* Not being able to write is fine -- we are only interested
@@ -631,14 +631,14 @@ int write_cache_as_tree(unsigned char *sha1, int flags, const char *prefix)
 	}
 
 	if (prefix) {
-		struct cache_tree *subtree =
-			cache_tree_find(active_cache_tree, prefix);
+		struct cache_tree *subtree;
+		subtree = cache_tree_find(index_state->cache_tree, prefix);
 		if (!subtree)
 			return WRITE_TREE_PREFIX_ERROR;
 		hashcpy(sha1, subtree->sha1);
 	}
 	else
-		hashcpy(sha1, active_cache_tree->sha1);
+		hashcpy(sha1, index_state->cache_tree->sha1);
 
 	if (0 <= newfd)
 		rollback_lock_file(lock_file);
@@ -646,6 +646,11 @@ int write_cache_as_tree(unsigned char *sha1, int flags, const char *prefix)
 	return 0;
 }
 
+int write_cache_as_tree(unsigned char *sha1, int flags, const char *prefix)
+{
+	return write_index_as_tree(sha1, &the_index, get_index_file(), flags, prefix);
+}
+
 static void prime_cache_tree_rec(struct cache_tree *it, struct tree *tree)
 {
 	struct tree_desc desc;
diff --git a/cache-tree.h b/cache-tree.h
index aa7b3e4..41c5746 100644
--- a/cache-tree.h
+++ b/cache-tree.h
@@ -46,6 +46,7 @@ int update_main_cache_tree(int);
 #define WRITE_TREE_UNMERGED_INDEX (-2)
 #define WRITE_TREE_PREFIX_ERROR (-3)
 
+int write_index_as_tree(unsigned char *sha1, struct index_state *index_state, const char *index_path, int flags, const char *prefix);
 int write_cache_as_tree(unsigned char *sha1, int flags, const char *prefix);
 void prime_cache_tree(struct index_state *, struct tree *);
 
-- 
2.1.4

[PATCH/WIP v3 11/31] am: refuse to apply patches if index is dirty

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:22

Since d1c5f2a (Add git-am, applymbox replacement., 2005-10-07), git-am
will refuse to apply patches if the index is dirty. Re-implement this
behavior.

Signed-off-by: Paul Tan <redacted>
---

Notes:
    Note: no tests for this

 builtin/am.c | 46 ++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 46 insertions(+)
diff --git a/builtin/am.c b/builtin/am.c
index a7efe85..9d6ab2a 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -14,6 +14,8 @@
 #include "refs.h"
 #include "commit.h"
 #include "lockfile.h"
+#include "diff.h"
+#include "diffcore.h"
 
 /**
  * Returns 1 if the file is empty or does not exist, 0 otherwise.
@@ -486,6 +488,43 @@ static void refresh_and_write_cache(void)
 }
 
 /**
+ * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn
+ * branch, returns 1 if there are entries in the index, 0 otherwise. If an
+ * strbuf is provided, the space-separated list of files that differ will be
+ * appended to it.
+ */
+static int index_has_changes(struct strbuf *sb)
+{
+	unsigned char head[GIT_SHA1_RAWSZ];
+	int i;
+
+	if (!get_sha1_tree("HEAD", head)) {
+		struct diff_options opt;
+
+		diff_setup(&opt);
+		DIFF_OPT_SET(&opt, EXIT_WITH_STATUS);
+		if (!sb)
+			DIFF_OPT_SET(&opt, QUICK);
+		do_diff_cache(head, &opt);
+		diffcore_std(&opt);
+		for (i = 0; sb && i < diff_queued_diff.nr; i++) {
+			if (i)
+				strbuf_addch(sb, ' ');
+			strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);
+		}
+		diff_flush(&opt);
+		return DIFF_OPT_TST(&opt, HAS_CHANGES) != 0;
+	} else {
+		for (i = 0; sb && i < active_nr; i++) {
+			if (i)
+				strbuf_addch(sb, ' ');
+			strbuf_addstr(sb, active_cache[i]->name);
+		}
+		return !!active_nr;
+	}
+}
+
+/**
  * Parses `patch` using git-mailinfo. state->msg will be set to the patch
  * message. state->author_name, state->author_email, state->author_date will be
  * set to the patch author's name, email and date respectively. The patch's
@@ -622,8 +661,15 @@ static void do_commit(const struct am_state *state)
  */
 static void am_run(struct am_state *state)
 {
+	struct strbuf sb = STRBUF_INIT;
+
 	refresh_and_write_cache();
 
+	if (index_has_changes(&sb))
+		die(_("Dirty index: cannot apply patches (dirty: %s)"), sb.buf);
+
+	strbuf_release(&sb);
+
 	while (state->cur <= state->last) {
 		const char *patch = am_path(state, msgnum(state));
 
-- 
2.1.4

[PATCH/WIP v3 18/31] am: implement am --signoff

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:22

Since d1c5f2a (Add git-am, applymbox replacement., 2005-10-07), git-am
supported the --signoff option which will append a signoff at the end of
the commit messsage. Re-implement this feature by calling
append_signoff() if the option is set.

Signed-off-by: Paul Tan <redacted>
---
 builtin/am.c | 13 +++++++++++++
 1 file changed, 13 insertions(+)
diff --git a/builtin/am.c b/builtin/am.c
index 1807d12..d45dd41 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -18,6 +18,7 @@
 #include "diffcore.h"
 #include "unpack-trees.h"
 #include "branch.h"
+#include "sequencer.h"
 
 /**
  * Returns 1 if the file is empty or does not exist, 0 otherwise.
@@ -71,6 +72,8 @@ struct am_state {
 
 	int quiet;
 
+	int sign;
+
 	/* override error message when patch failure occurs */
 	const char *resolvemsg;
 };
@@ -292,6 +295,9 @@ static void am_load(struct am_state *state)
 	read_state_file(&sb, am_path(state, "quiet"), 2, 1);
 	state->quiet = !strcmp(sb.buf, "t");
 
+	read_state_file(&sb, am_path(state, "sign"), 2, 1);
+	state->sign = !strcmp(sb.buf, "t");
+
 	strbuf_release(&sb);
 }
 
@@ -477,6 +483,8 @@ static void am_setup(struct am_state *state, enum patch_format patch_format,
 
 	write_file(am_path(state, "quiet"), 1, state->quiet ? "t" : "f");
 
+	write_file(am_path(state, "sign"), 1, state->sign ? "t" : "f");
+
 	if (!get_sha1("HEAD", curr_head)) {
 		write_file(am_path(state, "abort-safety"), 1, "%s", sha1_to_hex(curr_head));
 		update_ref("am", "ORIG_HEAD", curr_head, NULL, 0, UPDATE_REFS_DIE_ON_ERR);
@@ -636,6 +644,9 @@ static int parse_patch(struct am_state *state, const char *patch)
 		die_errno(_("could not read '%s'"), am_path(state, "msg"));
 	stripspace(&state->msg, 0);
 
+	if (state->sign)
+		append_signoff(&state->msg, 0, 0);
+
 	return 0;
 }
 
@@ -1007,6 +1018,8 @@ static const char * const am_usage[] = {
 
 static struct option am_options[] = {
 	OPT__QUIET(&state.quiet, N_("be quiet")),
+	OPT_BOOL('s', "signoff", &state.sign,
+		N_("add a Signed-off-by line to the commit message")),
 	OPT_CALLBACK(0, "patch-format", &opt_patch_format, N_("format"),
 		N_("format the patch(es) are in"), parse_opt_patchformat),
 	OPT_STRING(0, "resolvemsg", &state.resolvemsg, NULL,
-- 
2.1.4

[PATCH/WIP v3 20/31] am: implement 3-way merge

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:22

Since d1c5f2a (Add git-am, applymbox replacement., 2005-10-07),
git-am.sh supported the --3way option, and if set, would attempt to do a
3-way merge if the initial patch application fails.

Since 5d86861 (am -3: list the paths that needed 3-way fallback,
2012-03-28), in a 3-way merge git-am.sh would list the paths that needed
3-way fallback, so that the user can review them more carefully to spot
mismerges.

Re-implement the above in builtin/am.c.

Signed-off-by: Paul Tan <redacted>
---
 builtin/am.c | 147 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 143 insertions(+), 4 deletions(-)
diff --git a/builtin/am.c b/builtin/am.c
index d45dd41..e154c87 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -19,6 +19,8 @@
 #include "unpack-trees.h"
 #include "branch.h"
 #include "sequencer.h"
+#include "revision.h"
+#include "merge-recursive.h"
 
 /**
  * Returns 1 if the file is empty or does not exist, 0 otherwise.
@@ -70,6 +72,8 @@ struct am_state {
 	/* number of digits in patch filename */
 	int prec;
 
+	int threeway;
+
 	int quiet;
 
 	int sign;
@@ -292,6 +296,9 @@ static void am_load(struct am_state *state)
 
 	read_state_file(&state->msg, am_path(state, "final-commit"), 0, 0);
 
+	read_state_file(&sb, am_path(state, "threeway"), 2, 1);
+	state->threeway = !strcmp(sb.buf, "t");
+
 	read_state_file(&sb, am_path(state, "quiet"), 2, 1);
 	state->quiet = !strcmp(sb.buf, "t");
 
@@ -481,6 +488,8 @@ static void am_setup(struct am_state *state, enum patch_format patch_format,
 
 	write_file(am_path(state, "last"), 1, "%d", state->last);
 
+	write_file(am_path(state, "threeway"), 1, state->threeway ? "t" : "f");
+
 	write_file(am_path(state, "quiet"), 1, state->quiet ? "t" : "f");
 
 	write_file(am_path(state, "sign"), 1, state->sign ? "t" : "f");
@@ -666,17 +675,33 @@ static void NORETURN die_user_resolve(const struct am_state *state)
 }
 
 /*
- * Applies current patch with git-apply. Returns 0 on success, -1 otherwise.
+ * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
+ * index_file is not NULL, the patch will be applied to that index.
  */
-static int run_apply(const struct am_state *state)
+static int run_apply(const struct am_state *state, const char *index_file)
 {
 	struct child_process cp = CHILD_PROCESS_INIT;
 
 	cp.git_cmd = 1;
 
+	if (index_file)
+		argv_array_pushf(&cp.env_array, "GIT_INDEX_FILE=%s", index_file);
+
+	/*
+	 * If we are allowed to fall back on 3-way merge, don't give false
+	 * errors during the initial attempt.
+	 */
+	if (state->threeway && !index_file) {
+		cp.no_stdout = 1;
+		cp.no_stderr = 1;
+	}
+
 	argv_array_push(&cp.args, "apply");
 
-	argv_array_push(&cp.args, "--index");
+	if (index_file)
+		argv_array_push(&cp.args, "--cached");
+	else
+		argv_array_push(&cp.args, "--index");
 
 	argv_array_push(&cp.args, am_path(state, "patch"));
 
@@ -685,8 +710,100 @@ static int run_apply(const struct am_state *state)
 
 	/* Reload index as git-apply will have modified it. */
 	discard_cache();
+	read_cache_from(index_file ? index_file : get_index_file());
+
+	return 0;
+}
+
+/**
+ * Builds a index that contains just the blobs needed for a 3way merge.
+ */
+static int build_fake_ancestor(const struct am_state *state, const char *index_file)
+{
+	struct child_process cp = CHILD_PROCESS_INIT;
+
+	cp.git_cmd = 1;
+	argv_array_push(&cp.args, "apply");
+	argv_array_pushf(&cp.args, "--build-fake-ancestor=%s", index_file);
+	argv_array_push(&cp.args, am_path(state, "patch"));
+
+	if (run_command(&cp))
+		return -1;
+
+	return 0;
+}
+
+/**
+ * Attempt a threeway merge, using index_path as the temporary index.
+ */
+static int fall_back_threeway(const struct am_state *state, const char *index_path)
+{
+	unsigned char orig_tree[GIT_SHA1_RAWSZ], his_tree[GIT_SHA1_RAWSZ],
+		      our_tree[GIT_SHA1_RAWSZ];
+	const unsigned char *bases[1] = {orig_tree};
+	struct merge_options o;
+	struct commit *result;
+
+	if (get_sha1("HEAD", our_tree) < 0)
+		hashcpy(our_tree, EMPTY_TREE_SHA1_BIN);
+
+	if (build_fake_ancestor(state, index_path))
+		return error("could not build fake ancestor");
+
+	discard_cache();
+	read_cache_from(index_path);
+
+	if (write_index_as_tree(orig_tree, &the_index, index_path, 0, NULL))
+		return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));
+
+	say(state, stdout, _("Using index info to reconstruct a base tree..."));
+
+	if (!state->quiet) {
+		/*
+		 * List paths that needed 3-way fallback, so that the user can
+		 * review them with extra care to spot mismerges.
+		 */
+		struct rev_info rev_info;
+		const char *diff_filter_str = "--diff-filter=AM";
+
+		init_revisions(&rev_info, NULL);
+		rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;
+		diff_opt_parse(&rev_info.diffopt, &diff_filter_str, 1);
+		add_pending_sha1(&rev_info, "HEAD", our_tree, 0);
+		diff_setup_done(&rev_info.diffopt);
+		run_diff_index(&rev_info, 1);
+	}
+
+	if (run_apply(state, index_path))
+		return error(_("Did you hand edit your patch?\n"
+				"It does not apply to blobs recorded in its index."));
+
+	if (write_index_as_tree(his_tree, &the_index, index_path, 0, NULL))
+		return error("could not write tree");
+
+	say(state, stdout, _("Falling back to patching base and 3-way merge..."));
+
+	discard_cache();
 	read_cache();
 
+	/*
+	 * This is not so wrong. Depending on which base we picked, orig_tree
+	 * may be wildly different from ours, but his_tree has the same set of
+	 * wildly different changes in parts the patch did not touch, so
+	 * recursive ends up canceling them, saying that we reverted all those
+	 * changes.
+	 */
+
+	init_merge_options(&o);
+
+	o.branch1 = "HEAD";
+	o.branch2 = firstline(state->msg.buf);
+	if (state->quiet)
+		o.verbosity = 0;
+
+	if (merge_recursive_generic(&o, our_tree, his_tree, 1, bases, &result))
+		return error(_("Failed to merge in the changes."));
+
 	return 0;
 }
 
@@ -753,6 +870,7 @@ static void am_run(struct am_state *state)
 
 	while (state->cur <= state->last) {
 		const char *patch = am_path(state, msgnum(state));
+		int apply_status;
 
 		if (!file_exists(patch))
 			goto next;
@@ -765,7 +883,26 @@ static void am_run(struct am_state *state)
 
 		say(state, stdout, _("Applying: %s"), firstline(state->msg.buf));
 
-		if (run_apply(state) < 0) {
+		apply_status = run_apply(state, NULL);
+
+		if (apply_status && state->threeway) {
+			struct strbuf sb = STRBUF_INIT;
+
+			strbuf_addstr(&sb, am_path(state, "patch-merge-index"));
+			apply_status = fall_back_threeway(state, sb.buf);
+			strbuf_release(&sb);
+
+			/*
+			 * Applying the patch to an earlier tree and merging
+			 * the result may have produced the same tree as ours.
+			 */
+			if (!apply_status && !index_has_changes(NULL)) {
+				say(state, stdout, _("No changes -- Patch already applied."));
+				goto next;
+			}
+		}
+
+		if (apply_status) {
 			int value;
 
 			printf_ln(_("Patch failed at %s %s"), msgnum(state),
@@ -1017,6 +1154,8 @@ static const char * const am_usage[] = {
 };
 
 static struct option am_options[] = {
+	OPT_BOOL('3', "3way", &state.threeway,
+		N_("allow fall back on 3way merging if needed")),
 	OPT__QUIET(&state.quiet, N_("be quiet")),
 	OPT_BOOL('s', "signoff", &state.sign,
 		N_("add a Signed-off-by line to the commit message")),
-- 
2.1.4

[PATCH/WIP v3 24/31] am: implement -k/--keep, --keep-non-patch

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:22

Since d1c5f2a (Add git-am, applymbox replacement., 2005-10-07),
git-am.sh supported the -k/--keep option to pass the -k option to
git-mailsplit.

Since f7e5ea1 (am: learn passing -b to mailinfo, 2012-01-16), git-am.sh
supported the --keep-non-patch option to pass the -b option to
git-mailsplit.

Re-implement these two options in builtin/am.c.

Signed-off-by: Paul Tan <redacted>
---
 builtin/am.c | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 51 insertions(+)
diff --git a/builtin/am.c b/builtin/am.c
index bbef91f..b73549f 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -81,6 +81,12 @@ enum patch_format {
 	PATCH_FORMAT_MBOX
 };
 
+enum keep_type {
+	KEEP_FALSE = 0,
+	KEEP_TRUE,      /* pass -k flag to git-mailinfo */
+	KEEP_NON_PATCH  /* pass -b flag to git-mailinfo */
+};
+
 struct am_state {
 	/* state directory path */
 	struct strbuf dir;
@@ -104,6 +110,9 @@ struct am_state {
 
 	int sign;
 
+	/* one of the enum keep_type values */
+	int keep;
+
 	/* override error message when patch failure occurs */
 	const char *resolvemsg;
 
@@ -333,6 +342,14 @@ static void am_load(struct am_state *state)
 	read_state_file(&sb, am_path(state, "sign"), 2, 1);
 	state->sign = !strcmp(sb.buf, "t");
 
+	read_state_file(&sb, am_path(state, "keep"), 2, 1);
+	if (!strcmp(sb.buf, "t"))
+		state->keep = KEEP_TRUE;
+	else if (!strcmp(sb.buf, "b"))
+		state->keep = KEEP_NON_PATCH;
+	else
+		state->keep = KEEP_FALSE;
+
 	state->rebasing = !!file_exists(am_path(state, "rebasing"));
 
 	strbuf_release(&sb);
@@ -497,6 +514,7 @@ static void am_setup(struct am_state *state, enum patch_format patch_format,
 		struct string_list *paths)
 {
 	unsigned char curr_head[GIT_SHA1_RAWSZ];
+	const char *str;
 
 	if (!patch_format)
 		patch_format = detect_patch_format(paths);
@@ -527,6 +545,21 @@ static void am_setup(struct am_state *state, enum patch_format patch_format,
 
 	write_file(am_path(state, "sign"), 1, state->sign ? "t" : "f");
 
+	switch (state->keep) {
+	case KEEP_FALSE:
+		str = "f";
+		break;
+	case KEEP_TRUE:
+		str = "t";
+		break;
+	case KEEP_NON_PATCH:
+		str = "b";
+		break;
+	default:
+		die("BUG: invalid value for state->keep");
+	}
+	write_file(am_path(state, "keep"), 1, "%s", str);
+
 	if (state->rebasing)
 		write_file(am_path(state, "rebasing"), 1, "%s", "");
 	else
@@ -653,6 +686,20 @@ static int parse_patch(struct am_state *state, const char *patch)
 	cp.out = xopen(am_path(state, "info"), O_WRONLY | O_CREAT, 0777);
 
 	argv_array_push(&cp.args, "mailinfo");
+
+	switch (state->keep) {
+	case KEEP_FALSE:
+		break;
+	case KEEP_TRUE:
+		argv_array_push(&cp.args, "-k");
+		break;
+	case KEEP_NON_PATCH:
+		argv_array_push(&cp.args, "-b");
+		break;
+	default:
+		die("BUG: invalid value for state->keep");
+	}
+
 	argv_array_push(&cp.args, am_path(state, "msg"));
 	argv_array_push(&cp.args, am_path(state, "patch"));
 
@@ -1326,6 +1373,10 @@ static struct option am_options[] = {
 	OPT__QUIET(&state.quiet, N_("be quiet")),
 	OPT_BOOL('s', "signoff", &state.sign,
 		N_("add a Signed-off-by line to the commit message")),
+	OPT_SET_INT('k', "keep", &state.keep,
+		N_("pass -k flag to git-mailinfo"), KEEP_TRUE),
+	OPT_SET_INT(0, "keep-non-patch", &state.keep,
+		N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH),
 	OPT_CALLBACK(0, "patch-format", &opt_patch_format, N_("format"),
 		N_("format the patch(es) are in"), parse_opt_patchformat),
 	OPT_STRING(0, "resolvemsg", &state.resolvemsg, NULL,
-- 
2.1.4

[PATCH/WIP v3 23/31] am: handle stray state directory

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:22

Should git-am terminate unexpectedly between the point where the state
directory is created, but the "next" and "last" files are not written
yet, a stray state directory will be left behind.

As such, since b141f3c (am: handle stray $dotest directory, 2013-06-15),
git-am.sh explicitly recognizes such a stray directory, and allows the
user to remove it with am --abort.

Re-implement this feature in builtin/am.c.

Signed-off-by: Paul Tan <redacted>
---
 builtin/am.c | 15 +++++++++++++++
 1 file changed, 15 insertions(+)
diff --git a/builtin/am.c b/builtin/am.c
index 0d7e37c..bbef91f 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -1395,6 +1395,21 @@ int cmd_am(int argc, const char **argv, const char *prefix)
 		struct string_list paths = STRING_LIST_INIT_DUP;
 		int i;
 
+		/*
+		 * Possible stray dotest directory in the independent-run case.
+		 */
+		if (file_exists(state.dir.buf) && !state.rebasing) {
+			if (opt_resume == RESUME_ABORT) {
+				am_destroy(&state);
+				am_state_release(&state);
+				return 0;
+			}
+
+			die(_("Stray %s directory found.\n"
+				"Use \"git am --abort\" to remove it."),
+				state.dir.buf);
+		}
+
 		if (opt_resume)
 			die(_("Resolve operation not in progress, we are not resuming."));
 
-- 
2.1.4

[PATCH/WIP v3 21/31] am: --rebasing

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:22

Since 3041c32 (am: --rebasing, 2008-03-04), git-am.sh supported the
--rebasing option, which is used internally by git-rebase to tell git-am
that it is being used for its purpose. It would create the empty file
$state_dir/rebasing to help "completion" scripts tell if the ongoing
operation is am or rebase.

As of 0fbb95d (am: don't call mailinfo if $rebasing, 2012-06-26),
--rebasing also implies --3way as well.

Since a1549e1 (am: return control to caller, for housekeeping,
2013-05-12), git-am.sh would only clean up the state directory when it
is not --rebasing, instead deferring cleanup to git-rebase.sh.

Re-implement the above in builtin/am.c.

Signed-off-by: Paul Tan <redacted>
---
 builtin/am.c | 24 +++++++++++++++++++++---
 1 file changed, 21 insertions(+), 3 deletions(-)
diff --git a/builtin/am.c b/builtin/am.c
index e154c87..9afa3bb 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -80,6 +80,8 @@ struct am_state {
 
 	/* override error message when patch failure occurs */
 	const char *resolvemsg;
+
+	int rebasing;
 };
 
 /**
@@ -305,6 +307,8 @@ static void am_load(struct am_state *state)
 	read_state_file(&sb, am_path(state, "sign"), 2, 1);
 	state->sign = !strcmp(sb.buf, "t");
 
+	state->rebasing = !!file_exists(am_path(state, "rebasing"));
+
 	strbuf_release(&sb);
 }
 
@@ -484,6 +488,9 @@ static void am_setup(struct am_state *state, enum patch_format patch_format,
 		die(_("Failed to split patches."));
 	}
 
+	if (state->rebasing)
+		state->threeway = 1;
+
 	write_file(am_path(state, "next"), 1, "%d", state->cur);
 
 	write_file(am_path(state, "last"), 1, "%d", state->last);
@@ -494,12 +501,20 @@ static void am_setup(struct am_state *state, enum patch_format patch_format,
 
 	write_file(am_path(state, "sign"), 1, state->sign ? "t" : "f");
 
+	if (state->rebasing)
+		write_file(am_path(state, "rebasing"), 1, "%s", "");
+	else
+		write_file(am_path(state, "applying"), 1, "%s", "");
+
 	if (!get_sha1("HEAD", curr_head)) {
 		write_file(am_path(state, "abort-safety"), 1, "%s", sha1_to_hex(curr_head));
-		update_ref("am", "ORIG_HEAD", curr_head, NULL, 0, UPDATE_REFS_DIE_ON_ERR);
+		if (!state->rebasing)
+			update_ref("am", "ORIG_HEAD", curr_head, NULL, 0,
+					UPDATE_REFS_DIE_ON_ERR);
 	} else {
 		write_file(am_path(state, "abort-safety"), 1, "%s", "");
-		delete_ref("ORIG_HEAD", NULL, 0);
+		if (!state->rebasing)
+			delete_ref("ORIG_HEAD", NULL, 0);
 	}
 }
 
@@ -921,7 +936,8 @@ next:
 		am_next(state);
 	}
 
-	am_destroy(state);
+	if (!state->rebasing)
+		am_destroy(state);
 }
 
 /**
@@ -1175,6 +1191,8 @@ static struct option am_options[] = {
 	OPT_CMDMODE(0, "abort", &opt_resume,
 		N_("restore the original branch and abort the patching operation."),
 		RESUME_ABORT),
+	OPT_HIDDEN_BOOL(0, "rebasing", &state.rebasing,
+		N_("(internal use for git-rebase)")),
 	OPT_END()
 };
 
-- 
2.1.4

[PATCH/WIP v3 26/31] am: support --keep-cr, am.keepcr

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:22

Since ad2c928 (git-am: Add command line parameter `--keep-cr` passing it
to git-mailsplit, 2010-02-27), git-am.sh supported the --keep-cr option
and would pass it to git-mailsplit.

Since e80d4cb (git-am: Add am.keepcr and --no-keep-cr to override it,
2010-02-27), git-am.sh supported the am.keepcr config setting, which
controls whether --keep-cr is on by default.

Re-implement the above in builtin/am.c.

Signed-off-by: Paul Tan <redacted>
---
 builtin/am.c | 30 ++++++++++++++++++++++++------
 1 file changed, 24 insertions(+), 6 deletions(-)
diff --git a/builtin/am.c b/builtin/am.c
index 4cec380..1991f36 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -469,7 +469,8 @@ done:
  * Splits out individual patches from `paths`, where each path is either a mbox
  * file or a Maildir. Return 0 on success, -1 on failure.
  */
-static int split_patches_mbox(struct am_state *state, struct string_list *paths)
+static int split_patches_mbox(struct am_state *state, struct string_list *paths,
+		int keep_cr)
 {
 	struct child_process cp = CHILD_PROCESS_INIT;
 	struct string_list_item *item;
@@ -480,6 +481,8 @@ static int split_patches_mbox(struct am_state *state, struct string_list *paths)
 	argv_array_pushf(&cp.args, "-d%d", state->prec);
 	argv_array_pushf(&cp.args, "-o%s", state->dir.buf);
 	argv_array_push(&cp.args, "-b");
+	if (keep_cr)
+		argv_array_push(&cp.args, "--keep-cr");
 	argv_array_push(&cp.args, "--");
 
 	for_each_string_list_item(item, paths)
@@ -501,14 +504,22 @@ static int split_patches_mbox(struct am_state *state, struct string_list *paths)
  * set to the index of the first patch, and state->last will be set to the
  * index of the last patch.
  *
+ * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1
+ * to disable this behavior, -1 to use the default configured setting.
+ *
  * Returns 0 on success, -1 on failure.
  */
 static int split_patches(struct am_state *state, enum patch_format patch_format,
-		struct string_list *paths)
+		struct string_list *paths, int keep_cr)
 {
+	if (keep_cr < 0) {
+		keep_cr = 0;
+		git_config_get_bool("am.keepcr", &keep_cr);
+	}
+
 	switch (patch_format) {
 	case PATCH_FORMAT_MBOX:
-		return split_patches_mbox(state, paths);
+		return split_patches_mbox(state, paths, keep_cr);
 	default:
 		die("BUG: invalid patch_format");
 	}
@@ -519,7 +530,7 @@ static int split_patches(struct am_state *state, enum patch_format patch_format,
  * Setup a new am session for applying patches
  */
 static void am_setup(struct am_state *state, enum patch_format patch_format,
-		struct string_list *paths)
+		struct string_list *paths, int keep_cr)
 {
 	unsigned char curr_head[GIT_SHA1_RAWSZ];
 	const char *str;
@@ -535,7 +546,7 @@ static void am_setup(struct am_state *state, enum patch_format patch_format,
 	if (mkdir(state->dir.buf, 0777) < 0 && errno != EEXIST)
 		die_errno(_("failed to create directory '%s'"), state->dir.buf);
 
-	if (split_patches(state, patch_format, paths) < 0) {
+	if (split_patches(state, patch_format, paths, keep_cr) < 0) {
 		am_destroy(state);
 		die(_("Failed to split patches."));
 	}
@@ -1371,6 +1382,7 @@ enum resume_mode {
 };
 
 static struct am_state state;
+static int opt_keep_cr = -1;
 static int opt_patch_format;
 static enum resume_mode opt_resume;
 
@@ -1392,6 +1404,12 @@ static struct option am_options[] = {
 		N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH),
 	OPT_BOOL('m', "message-id", &state.message_id,
 		N_("pass -m flag to git-mailinfo")),
+	{ OPTION_SET_INT, 0, "keep-cr", &opt_keep_cr, NULL,
+	  N_("pass --keep-cr flag to git-mailsplit for mbox format"),
+	  PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1},
+	{ OPTION_SET_INT, 0, "no-keep-cr", &opt_keep_cr, NULL,
+	  N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),
+	  PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 0},
 	OPT_CALLBACK(0, "patch-format", &opt_patch_format, N_("format"),
 		N_("format the patch(es) are in"), parse_opt_patchformat),
 	OPT_STRING(0, "resolvemsg", &state.resolvemsg, NULL,
@@ -1486,7 +1504,7 @@ int cmd_am(int argc, const char **argv, const char *prefix)
 				string_list_append(&paths, mkpath("%s/%s", prefix, argv[i]));
 		}
 
-		am_setup(&state, opt_patch_format, &paths);
+		am_setup(&state, opt_patch_format, &paths, opt_keep_cr);
 
 		string_list_clear(&paths, 0);
 	}
-- 
2.1.4

[PATCH/WIP v3 22/31] am: don't use git-mailinfo if --rebasing

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:22

Since 5e835ca (rebase: do not munge commit log message, 2008-04-16),
git am --rebasing no longer gets the commit log message from the patch,
but reads it directly from the commit identified by the "From " header
line.

Since 43c2325 (am: use get_author_ident_from_commit instead of mailinfo
when rebasing, 2010-06-16), git am --rebasing also gets the author name,
email and date directly from the commit.

Since 0fbb95d (am: don't call mailinfo if $rebasing, 2012-06-26), git am
--rebasing does not use git-mailinfo to get the patch body, but rather
generates it directly from the commit itself.

The above 3 commits introduced a separate parse_patch() code path in
git-am.sh's --rebasing mode that bypasses git-mailinfo. Re-implement
this code path in builtin/am.c as parse_patch_rebase().

Signed-off-by: Paul Tan <redacted>
---
 builtin/am.c | 155 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 153 insertions(+), 2 deletions(-)
diff --git a/builtin/am.c b/builtin/am.c
index 9afa3bb..0d7e37c 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -21,6 +21,8 @@
 #include "sequencer.h"
 #include "revision.h"
 #include "merge-recursive.h"
+#include "revision.h"
+#include "log-tree.h"
 
 /**
  * Returns 1 if the file is empty or does not exist, 0 otherwise.
@@ -50,6 +52,30 @@ static const char *firstline(const char *msg)
 	return sb.buf;
 }
 
+/**
+ * Iterate over lines, each terminated by c, in a string, without modifying the
+ * string itself. begin will be set to the beginning of the line, while end
+ * will be set to the line termination or null character at the end of the line
+ * or string. On the first call, begin and end must be initialized to the
+ * string to be iterated over. E.g.:
+ *
+ *	const char *begin, *end, *str = "1\n2\n3";
+ *	begin = end = str;
+ *	while (!getbufline(&begin, &end, '\n'))
+ *		...
+ */
+static int getbufline(const char **begin, const char **end, int c)
+{
+	if (!**end)
+		return EOF;
+	else if (**end == c)
+		*begin = *end + 1;
+	else
+		*begin = *end;
+	*end = strchrnul(*begin, c);
+	return 0;
+}
+
 enum patch_format {
 	PATCH_FORMAT_UNKNOWN = 0,
 	PATCH_FORMAT_MBOX
@@ -675,6 +701,126 @@ static int parse_patch(struct am_state *state, const char *patch)
 }
 
 /**
+ * Sets commit_id to the commit hash where the patch was generated from.
+ * Returns 0 on success, -1 on failure.
+ */
+static int get_patch_commit_sha1(unsigned char *commit_id, const char *patch)
+{
+	struct strbuf sb = STRBUF_INIT;
+	FILE *fp = xfopen(patch, "r");
+	const char *x;
+
+	if (strbuf_getline(&sb, fp, '\n'))
+		return -1;
+
+	if (!skip_prefix(sb.buf, "From ", &x))
+		return -1;
+
+	if (get_sha1_hex(x, commit_id) < 0)
+		return -1;
+
+	strbuf_release(&sb);
+	fclose(fp);
+	return 0;
+}
+
+/**
+ * Sets state->msg, state->author_name, state->author_email, state->author_date
+ * to the commit's respective info.
+ */
+static void get_commit_info(struct am_state *state, struct commit *commit)
+{
+	const char *buf, *begin, *end;
+
+	buf = logmsg_reencode(commit, NULL, get_commit_output_encoding());
+	begin = end = buf;
+
+	while (!getbufline(&begin, &end, '\n')) {
+		const char *x;
+
+		if (skip_prefix(begin, "author ", &x)) {
+			struct ident_split split;
+			const char *date;
+
+			if (split_ident_line(&split, x, end - x) < 0) {
+				struct strbuf sb = STRBUF_INIT;
+
+				strbuf_add(&sb, x, end - x);
+				die(_("invalid ident line: %s"), sb.buf);
+			}
+
+			if (split.name_begin)
+				strbuf_add(&state->author_name,
+					split.name_begin,
+					split.name_end - split.name_begin);
+
+			if (split.mail_begin)
+				strbuf_add(&state->author_email,
+					split.mail_begin,
+					split.mail_end - split.mail_begin);
+
+			date = show_ident_date(&split, DATE_NORMAL);
+			strbuf_addstr(&state->author_date, date);
+		} else if (begin == end) {
+			end++;
+			break;
+		}
+	}
+
+	strbuf_addstr(&state->msg, end);
+}
+
+/**
+ * Writes commit as a patch to $state_dir/patch.
+ */
+static void write_commit_patch(const struct am_state *state, struct commit *commit)
+{
+	struct rev_info rev_info;
+	FILE *fp;
+
+	fp = xfopen(am_path(state, "patch"), "w");
+	init_revisions(&rev_info, NULL);
+	rev_info.diff = 1;
+	rev_info.abbrev = 0;
+	rev_info.disable_stdin = 1;
+	rev_info.show_root_diff = 1;
+	rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
+	rev_info.no_commit_id = 1;
+	DIFF_OPT_SET(&rev_info.diffopt, BINARY);
+	DIFF_OPT_SET(&rev_info.diffopt, FULL_INDEX);
+	rev_info.diffopt.use_color = 0;
+	rev_info.diffopt.file = fp;
+	rev_info.diffopt.close_file = 1;
+	add_pending_object(&rev_info, &commit->object, "");
+	diff_setup_done(&rev_info.diffopt);
+	log_tree_commit(&rev_info, commit);
+}
+
+/**
+ * Like parse_patch(), but parses the patch by looking up its commit ID
+ * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
+ * of patches.
+ *
+ * Will always return 0 as the patch should never be skipped.
+ */
+static int parse_patch_rebase(struct am_state *state, const char *patch)
+{
+	struct commit *commit;
+	unsigned char commit_sha1[GIT_SHA1_RAWSZ];
+
+	if (get_patch_commit_sha1(commit_sha1, patch) < 0)
+		die(_("could not parse %s"), patch);
+
+	commit = lookup_commit_or_die(commit_sha1, patch);
+
+	get_commit_info(state, commit);
+
+	write_commit_patch(state, commit);
+
+	return 0;
+}
+
+/**
  * Dies with a user-friendly message on how to proceed after resolving the
  * problem. This message can be overridden with state->resolvemsg.
  */
@@ -885,12 +1031,17 @@ static void am_run(struct am_state *state)
 
 	while (state->cur <= state->last) {
 		const char *patch = am_path(state, msgnum(state));
-		int apply_status;
+		int apply_status, skip;
 
 		if (!file_exists(patch))
 			goto next;
 
-		if (parse_patch(state, patch))
+		if (state->rebasing)
+			skip = parse_patch_rebase(state, patch);
+		else
+			skip = parse_patch(state, patch);
+
+		if (skip)
 			goto next; /* patch should be skipped */
 
 		write_author_script(state);
-- 
2.1.4

[PATCH/WIP v3 25/31] am: implement --[no-]message-id, am.messageid

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:22

Since a078f73 (git-am: add --message-id/--no-message-id, 2014-11-25),
git-am.sh supported the --[no-]message-id options, and the
"am.messageid" setting which specifies the default option.

--[no-]message-id tells git-am whether or not the -m option should be
passed to git-mailinfo.

Re-implement this option in builtin/am.c.

Signed-off-by: Paul Tan <redacted>
---

Notes:
    No test for am.messageid

 builtin/am.c | 15 +++++++++++++++
 1 file changed, 15 insertions(+)
diff --git a/builtin/am.c b/builtin/am.c
index b73549f..4cec380 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -113,6 +113,9 @@ struct am_state {
 	/* one of the enum keep_type values */
 	int keep;
 
+	/* pass -m flag to git-mailinfo */
+	int message_id;
+
 	/* override error message when patch failure occurs */
 	const char *resolvemsg;
 
@@ -140,6 +143,8 @@ static void am_state_init(struct am_state *state)
 	quiet = getenv("GIT_QUIET");
 	if (quiet && *quiet)
 		state->quiet = 1;
+
+	git_config_get_bool("am.messageid", &state->message_id);
 }
 
 /**
@@ -350,6 +355,9 @@ static void am_load(struct am_state *state)
 	else
 		state->keep = KEEP_FALSE;
 
+	read_state_file(&sb, am_path(state, "messageid"), 2, 1);
+	state->message_id = !strcmp(sb.buf, "t");
+
 	state->rebasing = !!file_exists(am_path(state, "rebasing"));
 
 	strbuf_release(&sb);
@@ -560,6 +568,8 @@ static void am_setup(struct am_state *state, enum patch_format patch_format,
 	}
 	write_file(am_path(state, "keep"), 1, "%s", str);
 
+	write_file(am_path(state, "messageid"), 1, state->message_id ? "t" : "f");
+
 	if (state->rebasing)
 		write_file(am_path(state, "rebasing"), 1, "%s", "");
 	else
@@ -700,6 +710,9 @@ static int parse_patch(struct am_state *state, const char *patch)
 		die("BUG: invalid value for state->keep");
 	}
 
+	if (state->message_id)
+		argv_array_push(&cp.args, "-m");
+
 	argv_array_push(&cp.args, am_path(state, "msg"));
 	argv_array_push(&cp.args, am_path(state, "patch"));
 
@@ -1377,6 +1390,8 @@ static struct option am_options[] = {
 		N_("pass -k flag to git-mailinfo"), KEEP_TRUE),
 	OPT_SET_INT(0, "keep-non-patch", &state.keep,
 		N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH),
+	OPT_BOOL('m', "message-id", &state.message_id,
+		N_("pass -m flag to git-mailinfo")),
 	OPT_CALLBACK(0, "patch-format", &opt_patch_format, N_("format"),
 		N_("format the patch(es) are in"), parse_opt_patchformat),
 	OPT_STRING(0, "resolvemsg", &state.resolvemsg, NULL,
-- 
2.1.4

[PATCH/WIP v3 27/31] am: implement --[no-]scissors

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:22

Since 017678b (am/mailinfo: Disable scissors processing by default,
2009-08-26), git-am supported the --[no-]scissors option, passing it to
git-mailinfo.

Re-implement support for this option.

Signed-off-by: Paul Tan <redacted>
---

Notes:
    There are tests for mailinfo --scissors, but not am --scissors, or
    mailinfo.scissors.

 builtin/am.c | 49 +++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 49 insertions(+)
diff --git a/builtin/am.c b/builtin/am.c
index 1991f36..42efce1 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -87,6 +87,12 @@ enum keep_type {
 	KEEP_NON_PATCH  /* pass -b flag to git-mailinfo */
 };
 
+enum scissors_type {
+	SCISSORS_UNSET = -1,
+	SCISSORS_TRUE,  /* pass --scissors to git-mailinfo */
+	SCISSORS_FALSE  /* pass --no-scissors to git-mailinfo */
+};
+
 struct am_state {
 	/* state directory path */
 	struct strbuf dir;
@@ -116,6 +122,9 @@ struct am_state {
 	/* pass -m flag to git-mailinfo */
 	int message_id;
 
+	/* one of the enum scissors_type values */
+	int scissors;
+
 	/* override error message when patch failure occurs */
 	const char *resolvemsg;
 
@@ -145,6 +154,8 @@ static void am_state_init(struct am_state *state)
 		state->quiet = 1;
 
 	git_config_get_bool("am.messageid", &state->message_id);
+
+	state->scissors = SCISSORS_UNSET;
 }
 
 /**
@@ -358,6 +369,14 @@ static void am_load(struct am_state *state)
 	read_state_file(&sb, am_path(state, "messageid"), 2, 1);
 	state->message_id = !strcmp(sb.buf, "t");
 
+	read_state_file(&sb, am_path(state, "scissors"), 2, 1);
+	if (!strcmp(sb.buf, "t"))
+		state->scissors = SCISSORS_TRUE;
+	else if (!strcmp(sb.buf, "f"))
+		state->scissors = SCISSORS_FALSE;
+	else
+		state->scissors = SCISSORS_UNSET;
+
 	state->rebasing = !!file_exists(am_path(state, "rebasing"));
 
 	strbuf_release(&sb);
@@ -581,6 +600,21 @@ static void am_setup(struct am_state *state, enum patch_format patch_format,
 
 	write_file(am_path(state, "messageid"), 1, state->message_id ? "t" : "f");
 
+	switch (state->scissors) {
+	case SCISSORS_UNSET:
+		str = "";
+		break;
+	case SCISSORS_FALSE:
+		str = "f";
+		break;
+	case SCISSORS_TRUE:
+		str = "t";
+		break;
+	default:
+		die("BUG: invalid value for state->scissors");
+	}
+	write_file(am_path(state, "scissors"), 1, "%s", str);
+
 	if (state->rebasing)
 		write_file(am_path(state, "rebasing"), 1, "%s", "");
 	else
@@ -724,6 +758,19 @@ static int parse_patch(struct am_state *state, const char *patch)
 	if (state->message_id)
 		argv_array_push(&cp.args, "-m");
 
+	switch (state->scissors) {
+	case SCISSORS_UNSET:
+		break;
+	case SCISSORS_FALSE:
+		argv_array_push(&cp.args, "--no-scissors");
+		break;
+	case SCISSORS_TRUE:
+		argv_array_push(&cp.args, "--scissors");
+		break;
+	default:
+		die("BUG: invalid value for state->scissors");
+	}
+
 	argv_array_push(&cp.args, am_path(state, "msg"));
 	argv_array_push(&cp.args, am_path(state, "patch"));
 
@@ -1410,6 +1457,8 @@ static struct option am_options[] = {
 	{ OPTION_SET_INT, 0, "no-keep-cr", &opt_keep_cr, NULL,
 	  N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),
 	  PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 0},
+	OPT_BOOL('c', "scissors", &state.scissors,
+		N_("strip everything before a scissors line")),
 	OPT_CALLBACK(0, "patch-format", &opt_patch_format, N_("format"),
 		N_("format the patch(es) are in"), parse_opt_patchformat),
 	OPT_STRING(0, "resolvemsg", &state.resolvemsg, NULL,
-- 
2.1.4

[PATCH/WIP v3 29/31] am: implement --ignore-date

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:22

Since a79ec62 (git-am: Add --ignore-date option, 2009-01-24), git-am.sh
supported the --ignore-date option, and would use the current timestamp
instead of the one provided in the patch if the option was set.

Re-implement this option in builtin/am.c.

Signed-off-by: Paul Tan <redacted>
---
 builtin/am.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
diff --git a/builtin/am.c b/builtin/am.c
index 3556765..6623b49 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -130,6 +130,8 @@ struct am_state {
 	/* override error message when patch failure occurs */
 	const char *resolvemsg;
 
+	int ignore_date;
+
 	int rebasing;
 };
 
@@ -1131,7 +1133,8 @@ static void do_commit(const struct am_state *state)
 	}
 
 	author = fmt_ident(state->author_name.buf, state->author_email.buf,
-			state->author_date.buf, IDENT_STRICT);
+			state->ignore_date ? NULL : state->author_date.buf,
+			IDENT_STRICT);
 
 	if (commit_tree(state->msg.buf, state->msg.len, tree, parents, commit,
 				author, NULL))
@@ -1521,6 +1524,8 @@ static struct option am_options[] = {
 	OPT_CMDMODE(0, "abort", &opt_resume,
 		N_("restore the original branch and abort the patching operation."),
 		RESUME_ABORT),
+	OPT_BOOL(0, "ignore-date", &state.ignore_date,
+		N_("use current timestamp for author date")),
 	OPT_HIDDEN_BOOL(0, "rebasing", &state.rebasing,
 		N_("(internal use for git-rebase)")),
 	OPT_END()
-- 
2.1.4

[PATCH/WIP v3 31/31] am: implement -S/--gpg-sign, commit.gpgsign

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:22

Since 3b4e395 (am: add the --gpg-sign option, 2014-02-01), git-am.sh
supported the --gpg-sign option, and would pass it to git-commit-tree,
thus GPG-signing the commit object.

Re-implement this option in builtin/am.c.

git-commit-tree would also sign the commit by default if the
commit.gpgsign setting is true. Since we do not run commit-tree, we
re-implement this behavior by handling the commit.gpgsign setting
ourselves.

Signed-off-by: Paul Tan <redacted>
---
 builtin/am.c | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)
diff --git a/builtin/am.c b/builtin/am.c
index 608a2da..91dae92 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -134,6 +134,8 @@ struct am_state {
 
 	int ignore_date;
 
+	const char *sign_commit;
+
 	int rebasing;
 };
 
@@ -143,6 +145,7 @@ struct am_state {
 static void am_state_init(struct am_state *state)
 {
 	const char *quiet;
+	int sign_commit;
 
 	memset(state, 0, sizeof(*state));
 
@@ -164,6 +167,9 @@ static void am_state_init(struct am_state *state)
 	state->scissors = SCISSORS_UNSET;
 
 	argv_array_init(&state->git_apply_opts);
+
+	if (!git_config_get_bool("commit.gpgsign", &sign_commit))
+		state->sign_commit = sign_commit ? "" : NULL;
 }
 
 /**
@@ -1143,7 +1149,7 @@ static void do_commit(const struct am_state *state)
 			state->ignore_date ? "" : state->author_date.buf, 1);
 
 	if (commit_tree(state->msg.buf, state->msg.len, tree, parents, commit,
-				author, NULL))
+				author, state->sign_commit))
 		die(_("failed to write commit object"));
 
 	reflog_msg = getenv("GIT_REFLOG_ACTION");
@@ -1535,6 +1541,9 @@ static struct option am_options[] = {
 		N_("lie about committer date")),
 	OPT_BOOL(0, "ignore-date", &state.ignore_date,
 		N_("use current timestamp for author date")),
+	{ OPTION_STRING, 'S', "gpg-sign", &state.sign_commit, N_("key-id"),
+	  N_("GPG-sign commits"),
+	  PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
 	OPT_HIDDEN_BOOL(0, "rebasing", &state.rebasing,
 		N_("(internal use for git-rebase)")),
 	OPT_END()
-- 
2.1.4

[PATCH/WIP v3 28/31] am: pass git-apply's options to git-apply

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:22

git-am.sh recognizes some of git-apply's options, and would pass them to
git-apply:

* --whitespace, since 8c31cb8 (git-am: --whitespace=x option.,
  2006-02-28)

* -C, since 67dad68 (add -C[NUM] to git-am, 2007-02-08)

* -p, since 2092a1f (Teach git-am to pass -p option down to git-apply,
  2007-02-11)

* --directory, since b47dfe9 (git-am: add --directory=<dir> option,
  2009-01-11)

* --reject, since b80da42 (git-am: implement --reject option passed to
  git-apply, 2009-01-23)

* --ignore-space-change, --ignore-whitespace, since 86c91f9 (git apply:
  option to ignore whitespace differences, 2009-08-04)

* --exclude, since 77e9e49 (am: pass exclude down to apply, 2011-08-03)

* --include, since 58725ef (am: support --include option, 2012-03-28)

Re-implement support for these options in builtin/am.c.

Signed-off-by: Paul Tan <redacted>
---
 builtin/am.c | 46 ++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 46 insertions(+)
diff --git a/builtin/am.c b/builtin/am.c
index 42efce1..3556765 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -125,6 +125,8 @@ struct am_state {
 	/* one of the enum scissors_type values */
 	int scissors;
 
+	struct argv_array git_apply_opts;
+
 	/* override error message when patch failure occurs */
 	const char *resolvemsg;
 
@@ -156,6 +158,8 @@ static void am_state_init(struct am_state *state)
 	git_config_get_bool("am.messageid", &state->message_id);
 
 	state->scissors = SCISSORS_UNSET;
+
+	argv_array_init(&state->git_apply_opts);
 }
 
 /**
@@ -168,6 +172,8 @@ static void am_state_release(struct am_state *state)
 	strbuf_release(&state->author_email);
 	strbuf_release(&state->author_date);
 	strbuf_release(&state->msg);
+
+	argv_array_clear(&state->git_apply_opts);
 }
 
 /**
@@ -377,6 +383,11 @@ static void am_load(struct am_state *state)
 	else
 		state->scissors = SCISSORS_UNSET;
 
+	read_state_file(&sb, am_path(state, "apply-opt"), 128, 1);
+	argv_array_clear(&state->git_apply_opts);
+	if (sq_dequote_to_argv_array(sb.buf, &state->git_apply_opts) < 0)
+		die(_("could not parse %s"), am_path(state, "apply-opt"));
+
 	state->rebasing = !!file_exists(am_path(state, "rebasing"));
 
 	strbuf_release(&sb);
@@ -553,6 +564,7 @@ static void am_setup(struct am_state *state, enum patch_format patch_format,
 {
 	unsigned char curr_head[GIT_SHA1_RAWSZ];
 	const char *str;
+	struct strbuf sb = STRBUF_INIT;
 
 	if (!patch_format)
 		patch_format = detect_patch_format(paths);
@@ -615,6 +627,10 @@ static void am_setup(struct am_state *state, enum patch_format patch_format,
 	}
 	write_file(am_path(state, "scissors"), 1, "%s", str);
 
+	sq_quote_argv(&sb, state->git_apply_opts.argv, 0);
+	write_file(am_path(state, "apply-opt"), 1, "%s", sb.buf);
+	strbuf_release(&sb);
+
 	if (state->rebasing)
 		write_file(am_path(state, "rebasing"), 1, "%s", "");
 	else
@@ -977,6 +993,8 @@ static int run_apply(const struct am_state *state, const char *index_file)
 
 	argv_array_push(&cp.args, "apply");
 
+	argv_array_pushv(&cp.args, state->git_apply_opts.argv);
+
 	if (index_file)
 		argv_array_push(&cp.args, "--cached");
 	else
@@ -1003,6 +1021,7 @@ static int build_fake_ancestor(const struct am_state *state, const char *index_f
 
 	cp.git_cmd = 1;
 	argv_array_push(&cp.args, "apply");
+	argv_array_pushv(&cp.args, state->git_apply_opts.argv);
 	argv_array_pushf(&cp.args, "--build-fake-ancestor=%s", index_file);
 	argv_array_push(&cp.args, am_path(state, "patch"));
 
@@ -1459,8 +1478,35 @@ static struct option am_options[] = {
 	  PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 0},
 	OPT_BOOL('c', "scissors", &state.scissors,
 		N_("strip everything before a scissors line")),
+	OPT_PASSTHRU_ARGV(0, "whitespace", &state.git_apply_opts, N_("action"),
+		N_("pass it through git-apply"),
+		0),
+	OPT_PASSTHRU_ARGV(0, "ignore-space-change", &state.git_apply_opts, NULL,
+		N_("pass it through git-apply"),
+		PARSE_OPT_NOARG),
+	OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &state.git_apply_opts, NULL,
+		N_("pass it through git-apply"),
+		PARSE_OPT_NOARG),
+	OPT_PASSTHRU_ARGV(0, "directory", &state.git_apply_opts, N_("root"),
+		N_("pass it through git-apply"),
+		0),
+	OPT_PASSTHRU_ARGV(0, "exclude", &state.git_apply_opts, N_("path"),
+		N_("pass it through git-apply"),
+		0),
+	OPT_PASSTHRU_ARGV(0, "include", &state.git_apply_opts, N_("path"),
+		N_("pass it through git-apply"),
+		0),
+	OPT_PASSTHRU_ARGV('C', NULL, &state.git_apply_opts, N_("n"),
+		N_("pass it through git-apply"),
+		0),
+	OPT_PASSTHRU_ARGV('p', NULL, &state.git_apply_opts, N_("num"),
+		N_("pass it through git-apply"),
+		0),
 	OPT_CALLBACK(0, "patch-format", &opt_patch_format, N_("format"),
 		N_("format the patch(es) are in"), parse_opt_patchformat),
+	OPT_PASSTHRU_ARGV(0, "reject", &state.git_apply_opts, NULL,
+		N_("pass it through git-apply"),
+		PARSE_OPT_NOARG),
 	OPT_STRING(0, "resolvemsg", &state.resolvemsg, NULL,
 		N_("override error message when patch failure occurs")),
 	OPT_CMDMODE(0, "continue", &opt_resume,
-- 
2.1.4

[PATCH/WIP v3 30/31] am: implement --committer-date-is-author-date

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:22

Since 3f01ad6 (am: Add --committer-date-is-author-date option,
2009-01-22), git-am.sh implemented the --committer-date-is-author-date
option, which tells git-am to use the timestamp recorded in the email
message as both author and committer date.

Re-implement this option in builtin/am.c.

Signed-off-by: Paul Tan <redacted>
---
 builtin/am.c | 9 +++++++++
 1 file changed, 9 insertions(+)
diff --git a/builtin/am.c b/builtin/am.c
index 6623b49..608a2da 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -130,6 +130,8 @@ struct am_state {
 	/* override error message when patch failure occurs */
 	const char *resolvemsg;
 
+	int committer_date_is_author_date;
+
 	int ignore_date;
 
 	int rebasing;
@@ -1136,6 +1138,10 @@ static void do_commit(const struct am_state *state)
 			state->ignore_date ? NULL : state->author_date.buf,
 			IDENT_STRICT);
 
+	if (state->committer_date_is_author_date)
+		setenv("GIT_COMMITTER_DATE",
+			state->ignore_date ? "" : state->author_date.buf, 1);
+
 	if (commit_tree(state->msg.buf, state->msg.len, tree, parents, commit,
 				author, NULL))
 		die(_("failed to write commit object"));
@@ -1524,6 +1530,9 @@ static struct option am_options[] = {
 	OPT_CMDMODE(0, "abort", &opt_resume,
 		N_("restore the original branch and abort the patching operation."),
 		RESUME_ABORT),
+	OPT_BOOL(0, "committer-date-is-author-date",
+		&state.committer_date_is_author_date,
+		N_("lie about committer date")),
 	OPT_BOOL(0, "ignore-date", &state.ignore_date,
 		N_("use current timestamp for author date")),
 	OPT_HIDDEN_BOOL(0, "rebasing", &state.rebasing,
-- 
2.1.4

Re: [PATCH/WIP v3 04/31] am: implement patch queue mechanism

From: Stefan Beller <hidden>
Date: 2016-06-15 23:05:22

On Thu, Jun 18, 2015 at 4:25 AM, Paul Tan [off-list ref] wrote:
+/**
+ * Reads the contents of `file`. The third argument can be used to give a hint
I would avoid `third` here. (I needed to count twice to be sure which
argument you
were referring to, as I was confused.) Also how do you abstain from
giving a hint?
(0 or negative or MAX_INT?)

So maybe

    /**
     * Reads the contents of `file`. Returns number of bytes read on success,
     * -1 if the file does not exist. If trim is set, trailing
whitespace will be removed
     * from the file contents. If `hint` is non-zero, it is used as a
hint for initial
     * allocation to avoid reallocs.
     */
quoted hunk
+ * about the file size, to avoid reallocs. Returns number of bytes read on
+ * success, -1 if the file does not exist. If trim is set, trailing whitespace
+ * will be removed from the file contents.
+ */
+static int read_state_file(struct strbuf *sb, const char *file, size_t hint, int trim)
+{
+       strbuf_reset(sb);
+       if (strbuf_read_file(sb, file, hint) >= 0) {
+               if (trim)
+                       strbuf_trim(sb);
+
+               return sb->len;
+       }
+
+       if (errno == ENOENT)
+               return -1;
+
+       die_errno(_("could not read '%s'"), file);
+}
+
+/**
+ * Loads state from disk.
+ */
+static void am_load(struct am_state *state)
+{
+       struct strbuf sb = STRBUF_INIT;
+
+       read_state_file(&sb, am_path(state, "next"), 8, 1);
+       state->cur = strtol(sb.buf, NULL, 10);
+
+       read_state_file(&sb, am_path(state, "last"), 8, 1);
+       state->last = strtol(sb.buf, NULL, 10);
+
+       strbuf_release(&sb);
+}
+
+/**
+ * Remove the am_state directory.
+ */
+static void am_destroy(const struct am_state *state)
+{
+       struct strbuf sb = STRBUF_INIT;
+
+       strbuf_addstr(&sb, state->dir.buf);
+       remove_dir_recursively(&sb, 0);
+       strbuf_release(&sb);
+}
+
+/**
+ * Setup a new am session for applying patches
+ */
+static void am_setup(struct am_state *state)
+{
+       if (mkdir(state->dir.buf, 0777) < 0 && errno != EEXIST)
+               die_errno(_("failed to create directory '%s'"), state->dir.buf);
+
+       write_file(am_path(state, "next"), 1, "%d", state->cur);
+
+       write_file(am_path(state, "last"), 1, "%d", state->last);
+}
+
+/**
+ * Increments the patch pointer, and cleans am_state for the application of the
+ * next patch.
+ */
+static void am_next(struct am_state *state)
+{
+       state->cur++;
+       write_file(am_path(state, "next"), 1, "%d", state->cur);
+}
+
+/**
+ * Applies all queued patches.
+ */
+static void am_run(struct am_state *state)
+{
+       while (state->cur <= state->last) {
+
+               /* TODO: Patch application not implemented yet */
+
+               am_next(state);
+       }
+
+       am_destroy(state);
+}
+
+static struct am_state state;
+
+static const char * const am_usage[] = {
+       N_("git am [options] [(<mbox>|<Maildir>)...]"),
+       NULL
+};
+
+static struct option am_options[] = {
+       OPT_END()
+};

 int cmd_am(int argc, const char **argv, const char *prefix)
 {
@@ -24,5 +176,21 @@ int cmd_am(int argc, const char **argv, const char *prefix)
                setup_work_tree();
        }

+       git_config(git_default_config, NULL);
+
+       am_state_init(&state);
+       strbuf_addstr(&state.dir, git_path("rebase-apply"));
+
+       argc = parse_options(argc, argv, prefix, am_options, am_usage, 0);
+
+       if (am_in_progress(&state))
+               am_load(&state);
+       else
+               am_setup(&state);
+
+       am_run(&state);
+
+       am_state_release(&state);
+
        return 0;
 }
--
2.1.4

Re: [PATCH/WIP v3 04/31] am: implement patch queue mechanism

From: Johannes Schindelin <hidden>
Date: 2016-06-15 23:05:29

Hi Paul,

On 2015-06-18 13:25, Paul Tan wrote:
quoted hunk
diff --git a/builtin/am.c b/builtin/am.c
index dbc8836..af68c51 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -6,6 +6,158 @@
 #include "cache.h"
 #include "builtin.h"
 #include "exec_cmd.h"
+#include "parse-options.h"
+#include "dir.h"
+
+struct am_state {
+	/* state directory path */
+	struct strbuf dir;
+
+	/* current and last patch numbers, 1-indexed */
+	int cur;
+	int last;
+};
+
+/**
+ * Initializes am_state with the default values.
+ */
+static void am_state_init(struct am_state *state)
+{
+	memset(state, 0, sizeof(*state));
+
+	strbuf_init(&state->dir, 0);
+}
With strbufs, we use the initializer STRBUF_INIT. How about using

#define AM_STATE_INIT { STRBUF_INIT, 0, 0 }

here?
+/**
+ * Reads the contents of `file`. The third argument can be used to give a hint
+ * about the file size, to avoid reallocs. Returns number of bytes read on
+ * success, -1 if the file does not exist. If trim is set, trailing whitespace
+ * will be removed from the file contents.
+ */
+static int read_state_file(struct strbuf *sb, const char *file,
size_t hint, int trim)
+{
+	strbuf_reset(sb);
+	if (strbuf_read_file(sb, file, hint) >= 0) {
+		if (trim)
+			strbuf_trim(sb);
+
+		return sb->len;
+	}
+
+	if (errno == ENOENT)
+		return -1;
+
+	die_errno(_("could not read '%s'"), file);
+}
A couple of thoughts:

- why not reuse the strbuf by making it a part of the am_state()? That way, you can allocate, say, 1024 bytes (should be plenty enough for most of our operations) and just reuse them in all of the functions. We will not make any of this multi-threaded anyway, I don't think.

- Given that we only read short files all the time, why not skip the hint parameter? Especially if we reuse the strbuf, it should be good enough to allocate a reasonable buffer first and then just assume that we do not have to reallocate it all that often anyway.

- Since we only read files from the state directory, why not pass the basename as parameter? That way we can avoid calling `am_path()` explicitly over and over again (and yours truly cannot forget to call `am_path()` in future patches).

- If you agree with these suggestions, the signature would become something like

static void read_state_file(struct am_state *state, const char *basename, int trim);
+/**
+ * Remove the am_state directory.
+ */
+static void am_destroy(const struct am_state *state)
+{
+	struct strbuf sb = STRBUF_INIT;
+
+	strbuf_addstr(&sb, state->dir.buf);
+	remove_dir_recursively(&sb, 0);
+	strbuf_release(&sb);
+}
Given that `remove_dir_recursively()` has to reset the strbuf with the directory's path to the original value before it returns (because it recurses into itself, therefore the value *has* to be reset when returning), we can just call

    remove_dir_recursively(&state->dir, 0);

and do not need another temporary strbuf.
+/**
+ * Increments the patch pointer, and cleans am_state for the application of the
+ * next patch.
+ */
+static void am_next(struct am_state *state)
+{
+	state->cur++;
+	write_file(am_path(state, "next"), 1, "%d", state->cur);
+}
Locking and re-checking the contents of "next" before writing the incremented value would probably be a little too paranoid...

(Just saying it out loud, the current code is fine by me.)

Ciao,
Dscho

Re: [PATCH/WIP v3 06/31] am: detect mbox patches

From: Johannes Schindelin <hidden>
Date: 2016-06-15 23:05:29

Hi Paul,

On 2015-06-18 13:25, Paul Tan wrote:
quoted hunk
diff --git a/builtin/am.c b/builtin/am.c
index e9a3687..7b97ea8 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -121,6 +121,96 @@ static void am_destroy(const struct am_state *state)
 	strbuf_release(&sb);
 }
 
+/*
+ * Returns 1 if the file looks like a piece of email a-la RFC2822, 0 otherwise.
+ * We check this by grabbing all the non-indented lines and seeing if they look
+ * like they begin with valid header field names.
+ */
+static int is_email(const char *filename)
+{
+	struct strbuf sb = STRBUF_INIT;
+	FILE *fp = xfopen(filename, "r");
+	int ret = 1;
+
+	while (!strbuf_getline(&sb, fp, '\n')) {
+		const char *x;
+
+		strbuf_rtrim(&sb);
+
+		if (!sb.len)
+			break; /* End of header */
+
+		/* Ignore indented folded lines */
+		if (*sb.buf == '\t' || *sb.buf == ' ')
+			continue;
+
+		/* It's a header if it matches the regexp "^[!-9;-~]+:" */
Why not just compile a regex and use it here? We use regexes elsewhere anyway...
+/**
+ * Attempts to detect the patch_format of the patches contained in `paths`,
+ * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
+ * detection fails.
+ */
+static int detect_patch_format(struct string_list *paths)
+{
+	enum patch_format ret = PATCH_FORMAT_UNKNOWN;
+	struct strbuf l1 = STRBUF_INIT;
+	struct strbuf l2 = STRBUF_INIT;
+	struct strbuf l3 = STRBUF_INIT;
+	FILE *fp;
+
+	/*
+	 * We default to mbox format if input is from stdin and for directories
+	 */
+	if (!paths->nr || !strcmp(paths->items->string, "-") ||
+	    is_directory(paths->items->string)) {
+		ret = PATCH_FORMAT_MBOX;
+		goto done;
+	}
+
+	/*
+	 * Otherwise, check the first 3 lines of the first patch, starting
+	 * from the first non-blank line, to try to detect its format.
+	 */
+	fp = xfopen(paths->items->string, "r");
+	while (!strbuf_getline(&l1, fp, '\n')) {
+		strbuf_trim(&l1);
+		if (l1.len)
+			break;
+	}
+	strbuf_getline(&l2, fp, '\n');
We should test the return value of `strbuf_getline()`; if EOF was reached already, `strbuf_getwholeline()` does not touch the strbuf. I know, the strbuf is still initialized empty here, but it is too easy to forget when changing this code.
+	strbuf_trim(&l2);
+	strbuf_getline(&l3, fp, '\n');
+	strbuf_trim(&l3);
+	fclose(fp);
+
+	if (starts_with(l1.buf, "From ") || starts_with(l1.buf, "From: "))
+		ret = PATCH_FORMAT_MBOX;
Hmm. We can test that earlier and return without reading from the file any further, I think.
+	else if (l1.len && l2.len && l3.len && is_email(paths->items->string))
+		ret = PATCH_FORMAT_MBOX;
Maybe we can do better than this by folding the `is_email() function into this here function, reusing the same strbuf to read the lines and keeping track of the email header lines we saw... I would really like to avoid opening the same file twice just to figure out whether it is in email format.

The rest looks very nice!
Dscho

Re: [PATCH/WIP v3 01/31] wrapper: implement xopen()

From: Johannes Schindelin <hidden>
Date: 2016-06-15 23:05:29

Hi Paul,

On 2015-06-18 13:25, Paul Tan wrote:
quoted hunk
diff --git a/git-compat-util.h b/git-compat-util.h
index 0cc7ae8..bc77d77 100644
--- a/git-compat-util.h
+++ b/git-compat-util.h
@@ -719,6 +719,7 @@ extern void *xrealloc(void *ptr, size_t size);
 extern void *xcalloc(size_t nmemb, size_t size);
 extern void *xmmap(void *start, size_t length, int prot, int flags,
int fd, off_t offset);
 extern void *xmmap_gently(void *start, size_t length, int prot, int
flags, int fd, off_t offset);
+extern int xopen(const char *path, int flags, ...);
I wonder whether it is worth it to make this a varargs function. It is not too much to ask callers to specify a specific mode everytime they call `xopen()`, no?
quoted hunk
diff --git a/wrapper.c b/wrapper.c
index c1a663f..82658b3 100644
--- a/wrapper.c
+++ b/wrapper.c
@@ -189,6 +189,31 @@ void *xcalloc(size_t nmemb, size_t size)
 # endif
 #endif
 
+/**
+ * xopen() is the same as open(), but it die()s if the open() fails.
+ */
+int xopen(const char *path, int oflag, ...)
+{
+	mode_t mode = 0;
+	va_list ap;
+
+	va_start(ap, oflag);
+	if (oflag & O_CREAT)
+		mode = va_arg(ap, mode_t);
+	va_end(ap);
+
+	assert(path);
+
+	for (;;) {
+		int fd = open(path, oflag, mode);
+		if (fd >= 0)
+			return fd;
+		if (errno == EINTR)
+			continue;
+		die_errno(_("could not open '%s'"), path);
It is often helpful to know whether a path was opened for reading or writing, so maybe we should have something like

if (oflag & O_WRITE)
    die_errno(_("could not open '%s' for writing"), path);
else if (oflag & O_READ)
    die_errno(_("could not open '%s' for reading"), path);
else
    die_errno(_("could not open '%s'"), path);

? I know it is a bit of duplication, but I fear we cannot get around that without breaking i18n support.

Ciao,
Dscho

Re: [PATCH/WIP v3 07/31] am: extract patch, message and authorship with git-mailinfo

From: Johannes Schindelin <hidden>
Date: 2016-06-15 23:05:29

Hi Paul,

On 2015-06-18 13:25, Paul Tan wrote:
quoted hunk
diff --git a/builtin/am.c b/builtin/am.c
index 7b97ea8..d6434e4 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -94,6 +126,105 @@ static int read_state_file(struct strbuf *sb,
const char *file, size_t hint, int
 }
 
 /**
+ * Reads a KEY=VALUE shell variable assignment from fp, and returns the VALUE
+ * in `value`. VALUE must be a quoted string, and the KEY must match `key`.
+ * Returns 0 on success, -1 on failure.
+ *
+ * This is used by read_author_script() to read the GIT_AUTHOR_* variables from
+ * the author-script.
+ */
+static int read_shell_var(struct strbuf *value, FILE *fp, const char *key)
+{
+	struct strbuf sb = STRBUF_INIT;
+	char *str;
+
+	if (strbuf_getline(&sb, fp, '\n'))
+		return -1;
+
+	if (!skip_prefix(sb.buf, key, (const char **)&str))
+		return -1;
+
+	if (!skip_prefix(str, "=", (const char **)&str))
+		return -1;
+
+	str = sq_dequote(str);
+	if (!str)
+		return -1;
+
+	strbuf_reset(value);
+	strbuf_addstr(value, str);
+
+	strbuf_release(&sb);
+
+	return 0;
+}
How about using `strbuf_remove()` and keeping `str` as `const char *`? I also think we can fold it into the `read_author_script()` function and make it more resilient with regards to the order of the variables. Something like this:

static int read_author_script(struct am_state *state)
{
	struct strbuf sb = STRBUF_INIT;
	const char *filename = am_path(state, "author-script");
	FILE *fp = fopen(filename, "r");
	if (!fp) {
		if (errno == ENOENT)
			return 0;
		die_errno(_("could not open '%s' for reading"), filename);
	}

	while (!strbuf_getline(&sb, fp, '\n')) {
		char *equal = strchr(sb.buf, '='), **var;

		if (!equal) {
error:
			fclose(fp);
			return -1;
		}
		*equal = '\0';
		if (!strcmp(sb.buf, "GIT_AUTHOR_NAME"))
			var = &state->author_name;
		else if (!strcmp(sb.buf, "GIT_AUTHOR_EMAIL"))
			var = &state->author_email;
		else if (!strcmp(sb.buf, "GIT_AUTHOR_DATE"))
			var = &state->author_date;
		else
			goto error;
		*var = xstrdup(sq_dequote(equal + 1));
	}

	fclose(fp);
	return -1;
}

If you follow my earlier suggestion to keep a strbuf inside the am_state, you could reuse that here, too.
+/**
+ * Saves state->author_name, state->author_email and state->author_date in
+ * `filename` as an "author script", which is the format used by git-am.sh.
+ */
+static void write_author_script(const struct am_state *state)
+{
+	static const char fmt[] = "GIT_AUTHOR_NAME=%s\n"
+		"GIT_AUTHOR_EMAIL=%s\n"
+		"GIT_AUTHOR_DATE=%s\n";
+	struct strbuf author_name = STRBUF_INIT;
+	struct strbuf author_email = STRBUF_INIT;
+	struct strbuf author_date = STRBUF_INIT;
+
+	sq_quote_buf(&author_name, state->author_name.buf);
+	sq_quote_buf(&author_email, state->author_email.buf);
+	sq_quote_buf(&author_date, state->author_date.buf);
The `sq_quote_buf()` function does not call `strbuf_reset()`. Therefore you could just use a single strbuf to construct the entire three lines and then write that out. Again, if you follow my suggestion to keep a "scratch pad" strbuf in am_state, you could reuse that.

That scratch pad could come in handy in a couple of other places in the rest of this patch.

Ciao,
Dscho

Re: [PATCH/WIP v3 01/31] wrapper: implement xopen()

From: Stefan Beller <hidden>
Date: 2016-06-15 23:05:29

On Wed, Jun 24, 2015 at 9:28 AM, Johannes Schindelin
[off-list ref] wrote:
Hi Paul,

On 2015-06-18 13:25, Paul Tan wrote:
quoted
diff --git a/git-compat-util.h b/git-compat-util.h
index 0cc7ae8..bc77d77 100644
--- a/git-compat-util.h
+++ b/git-compat-util.h
@@ -719,6 +719,7 @@ extern void *xrealloc(void *ptr, size_t size);
 extern void *xcalloc(size_t nmemb, size_t size);
 extern void *xmmap(void *start, size_t length, int prot, int flags,
int fd, off_t offset);
 extern void *xmmap_gently(void *start, size_t length, int prot, int
flags, int fd, off_t offset);
+extern int xopen(const char *path, int flags, ...);
I wonder whether it is worth it to make this a varargs function. It is not too much to ask callers to specify a specific mode everytime they call `xopen()`, no?
quoted
diff --git a/wrapper.c b/wrapper.c
index c1a663f..82658b3 100644
--- a/wrapper.c
+++ b/wrapper.c
@@ -189,6 +189,31 @@ void *xcalloc(size_t nmemb, size_t size)
 # endif
 #endif

+/**
+ * xopen() is the same as open(), but it die()s if the open() fails.
+ */
+int xopen(const char *path, int oflag, ...)
+{
+     mode_t mode = 0;
+     va_list ap;
+
+     va_start(ap, oflag);
+     if (oflag & O_CREAT)
+             mode = va_arg(ap, mode_t);
+     va_end(ap);
+
+     assert(path);
+
+     for (;;) {
+             int fd = open(path, oflag, mode);
+             if (fd >= 0)
+                     return fd;
+             if (errno == EINTR)
+                     continue;
+             die_errno(_("could not open '%s'"), path);
It is often helpful to know whether a path was opened for reading or writing, so maybe we should have something like

if (oflag & O_WRITE)
    die_errno(_("could not open '%s' for writing"), path);
else if (oflag & O_READ)
    die_errno(_("could not open '%s' for reading"), path);
else
    die_errno(_("could not open '%s'"), path);

? I know it is a bit of duplication, but I fear we cannot get around that without breaking i18n support.
This distinction was part of earlier series, but Torsten Boegershausen
suggested to leave
it out. [compare
http://thread.gmane.org/gmane.comp.version-control.git/270048/focus=270049]
Ciao,
Dscho

Re: [PATCH/WIP v3 01/31] wrapper: implement xopen()

From: Johannes Schindelin <hidden>
Date: 2016-06-15 23:05:29

Hi Stefan,

On 2015-06-24 18:59, Stefan Beller wrote:
On Wed, Jun 24, 2015 at 9:28 AM, Johannes Schindelin
[off-list ref] wrote:
quoted
On 2015-06-18 13:25, Paul Tan wrote:
quoted
+             int fd = open(path, oflag, mode);
+             if (fd >= 0)
+                     return fd;
+             if (errno == EINTR)
+                     continue;
+             die_errno(_("could not open '%s'"), path);
It is often helpful to know whether a path was opened for reading or writing, so maybe we should have something like

if (oflag & O_WRITE)
    die_errno(_("could not open '%s' for writing"), path);
else if (oflag & O_READ)
    die_errno(_("could not open '%s' for reading"), path);
else
    die_errno(_("could not open '%s'"), path);

? I know it is a bit of duplication, but I fear we cannot get around that without breaking i18n support.
This distinction was part of earlier series, but Torsten Boegershausen
suggested to leave
it out. [compare
http://thread.gmane.org/gmane.comp.version-control.git/270048/focus=270049]
So sorry that I missed that (it is still somewhere in my ever-growing inbox). I would have politely disagreed with Torsten if I had not missed it, though.

IMO the varargs make the code more cumbersome to read (and even fragile, because you can easily call `xopen(path, O_WRITE | O_CREATE)` and would not even get so much as a compiler warning!) and the error message does carry value: it helps you resolve the issue (it is completely unnecessary to check write permissions of the directory when a file could not be opened for reading, for example, yet if the error message does not say that and you suspect that the file could not be opened for *writing* that is exactly what you would waste your time checking).

Ciao,
Dscho

Re: [PATCH/WIP v3 06/31] am: detect mbox patches

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:31

On Wed, Jun 24, 2015 at 11:10 PM, Johannes Schindelin
[off-list ref] wrote:
Hi Paul,

On 2015-06-18 13:25, Paul Tan wrote:
quoted
diff --git a/builtin/am.c b/builtin/am.c
index e9a3687..7b97ea8 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -121,6 +121,96 @@ static void am_destroy(const struct am_state *state)
      strbuf_release(&sb);
 }

+/*
+ * Returns 1 if the file looks like a piece of email a-la RFC2822, 0 otherwise.
+ * We check this by grabbing all the non-indented lines and seeing if they look
+ * like they begin with valid header field names.
+ */
+static int is_email(const char *filename)
+{
+     struct strbuf sb = STRBUF_INIT;
+     FILE *fp = xfopen(filename, "r");
+     int ret = 1;
+
+     while (!strbuf_getline(&sb, fp, '\n')) {
+             const char *x;
+
+             strbuf_rtrim(&sb);
+
+             if (!sb.len)
+                     break; /* End of header */
+
+             /* Ignore indented folded lines */
+             if (*sb.buf == '\t' || *sb.buf == ' ')
+                     continue;
+
+             /* It's a header if it matches the regexp "^[!-9;-~]+:" */
Why not just compile a regex and use it here? We use regexes elsewhere anyway...
Ah, you're right. A regular expression would definitely be clearer.
I've fixed it on my end.
quoted
+/**
+ * Attempts to detect the patch_format of the patches contained in `paths`,
+ * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
+ * detection fails.
+ */
+static int detect_patch_format(struct string_list *paths)
+{
+     enum patch_format ret = PATCH_FORMAT_UNKNOWN;
+     struct strbuf l1 = STRBUF_INIT;
+     struct strbuf l2 = STRBUF_INIT;
+     struct strbuf l3 = STRBUF_INIT;
+     FILE *fp;
+
+     /*
+      * We default to mbox format if input is from stdin and for directories
+      */
+     if (!paths->nr || !strcmp(paths->items->string, "-") ||
+         is_directory(paths->items->string)) {
+             ret = PATCH_FORMAT_MBOX;
+             goto done;
+     }
+
+     /*
+      * Otherwise, check the first 3 lines of the first patch, starting
+      * from the first non-blank line, to try to detect its format.
+      */
+     fp = xfopen(paths->items->string, "r");
+     while (!strbuf_getline(&l1, fp, '\n')) {
+             strbuf_trim(&l1);
+             if (l1.len)
+                     break;
+     }
+     strbuf_getline(&l2, fp, '\n');
We should test the return value of `strbuf_getline()`; if EOF was reached already, `strbuf_getwholeline()` does not touch the strbuf. I know, the strbuf is still initialized empty here, but it is too easy to forget when changing this code.
Ah OK. I'll vote for doing a strbuf_reset() just before the
strbuf_getline() though.
quoted
+     strbuf_trim(&l2);
+     strbuf_getline(&l3, fp, '\n');
+     strbuf_trim(&l3);
+     fclose(fp);
+
+     if (starts_with(l1.buf, "From ") || starts_with(l1.buf, "From: "))
+             ret = PATCH_FORMAT_MBOX;
Hmm. We can test that earlier and return without reading from the file any further, I think.
The "reading 3 lines at the beginning" logic is meant to support a
later patch where support for StGit and mercurial patches is added.
That said, it's true that we don't need to read 3 lines in this patch,
so I think I will remove it in this patch.
quoted
+     else if (l1.len && l2.len && l3.len && is_email(paths->items->string))
+             ret = PATCH_FORMAT_MBOX;
Maybe we can do better than this by folding the `is_email() function into this here function, reusing the same strbuf to read the lines and keeping track of the email header lines we saw... I would really like to avoid opening the same file twice just to figure out whether it is in email format.
Okay, how about every time we call a strbuf_getline(), we save the
line to a string_list as well? Like string_list_getline_crlf() below:

/**
 * Like strbuf_getline(), but supports both '\n' and "\r\n" as line
 * terminators.
 */
static int strbuf_getline_crlf(struct strbuf *sb, FILE *fp)
{
    if (strbuf_getwholeline(sb, fp, '\n'))
        return EOF;
    if (sb->buf[sb->len - 1] == '\n') {
        strbuf_setlen(sb, sb->len - 1);
        if (sb->len > 0 && sb->buf[sb->len - 1] == '\r')
            strbuf_setlen(sb, sb->len - 1);
    }
    return 0;
}

/**
 * Like strbuf_getline_crlf(), but appends the line to a string_list and
 * returns it as a string. Returns NULL on EOF.
 */
static const char *string_list_getline_crlf(struct string_list *list, FILE *fp)
{
    struct strbuf sb = STRBUF_INIT;
    struct string_list_item *item;

    if (strbuf_getline_crlf(&sb, fp))
        return NULL;
    item = string_list_append_nodup(list, strbuf_detach(&sb, NULL));
    return item->string;
}

So now, is_email() can have access to previously-read lines, and if it
needs some more, it can read more as well:

static int is_email(struct string_list *lines, FILE *fp)
{
    const char *header_regex = "^[!-9;-~]+:";
    regex_t regex;
    int ret = 1;
    size_t i;

    if (regcomp(&regex, header_regex, REG_NOSUB | REG_EXTENDED))
        die("Invalid search pattern: %s", header_regex);

    for (i = 0; i < lines->nr || string_list_getline_crlf(lines, fp); i++) {
        const char *line = lines->items[i].string;

        if (!*line)
            break; /* End of header */

        /* Ignore indented folded lines */
        if (*line == '\t' || *line == ' ')
            continue;

        /* It's a header if it matches header_regex */
        if (regexec(&regex, line, 0, NULL, 0)) {
            ret = 0;
            goto done;
        }
    }

done:
    regfree(&regex);
    return ret;
}

Which solves the problem of opening the file 2 times. What do you think?

Regards,
Paul

Re: [PATCH/WIP v3 04/31] am: implement patch queue mechanism

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:31

On Wed, Jun 24, 2015 at 10:59 PM, Johannes Schindelin
[off-list ref] wrote:
quoted
diff --git a/builtin/am.c b/builtin/am.c
index dbc8836..af68c51 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -6,6 +6,158 @@
 #include "cache.h"
 #include "builtin.h"
 #include "exec_cmd.h"
+#include "parse-options.h"
+#include "dir.h"
+
+struct am_state {
+     /* state directory path */
+     struct strbuf dir;
+
+     /* current and last patch numbers, 1-indexed */
+     int cur;
+     int last;
+};
+
+/**
+ * Initializes am_state with the default values.
+ */
+static void am_state_init(struct am_state *state)
+{
+     memset(state, 0, sizeof(*state));
+
+     strbuf_init(&state->dir, 0);
+}
With strbufs, we use the initializer STRBUF_INIT. How about using

#define AM_STATE_INIT { STRBUF_INIT, 0, 0 }

here?
Later in the patch series am_state_init() will also take into account
config settings when filling up the default values. e.g. see patches
25/31[1] or 31/31[2]. I think that is reasonable: the purpose of
am_state_init() is to initialize the am_state struct with the default
values, and the default values can be set by the user through the
config settings.

This means, though, that we can't use initializers without introducing
global variables.

[1] http://thread.gmane.org/gmane.comp.version-control.git/271967/focus=271972
[2] http://thread.gmane.org/gmane.comp.version-control.git/271967/focus=271972
quoted
+/**
+ * Reads the contents of `file`. The third argument can be used to give a hint
+ * about the file size, to avoid reallocs. Returns number of bytes read on
+ * success, -1 if the file does not exist. If trim is set, trailing whitespace
+ * will be removed from the file contents.
+ */
+static int read_state_file(struct strbuf *sb, const char *file,
size_t hint, int trim)
+{
+     strbuf_reset(sb);
+     if (strbuf_read_file(sb, file, hint) >= 0) {
+             if (trim)
+                     strbuf_trim(sb);
+
+             return sb->len;
+     }
+
+     if (errno == ENOENT)
+             return -1;
+
+     die_errno(_("could not read '%s'"), file);
+}
A couple of thoughts:

- why not reuse the strbuf by making it a part of the am_state()? That way, you can allocate, say, 1024 bytes (should be plenty enough for most of our operations) and just reuse them in all of the functions. We will not make any of this multi-threaded anyway, I don't think.
But too much usage of this temporary strbuf may lead to a situation
where one function calls another, and both functions write to the
strbuf and clobber its contents.

Besides, if we are talking about read_state_file(), it takes an
external strbuf, so it gives the caller the freedom to choose which
strbuf it uses (e.g. if it is stack allocated or in the am_state
struct). I think it's more flexible this way.
- Given that we only read short files all the time, why not skip the hint parameter? Especially if we reuse the strbuf, it should be good enough to allocate a reasonable buffer first and then just assume that we do not have to reallocate it all that often anyway.
Doh! Right, the hint parameter is quite useless, since in am_load() we
use the same strbuf anyway. (And strbuf_init() can set a hint as well)
I've removed it on my side.
- Since we only read files from the state directory, why not pass the basename as parameter? That way we can avoid calling `am_path()` explicitly over and over again (and yours truly cannot forget to call `am_path()` in future patches).
Makes sense. After all, this function is called read_STATE_file() ;-)
- If you agree with these suggestions, the signature would become something like

static void read_state_file(struct am_state *state, const char *basename, int trim);
So for now, my function signature is

static void read_state_file(struct strbuf *sb, const struct am_state
*state, const char *basename, int trim);
quoted
+/**
+ * Remove the am_state directory.
+ */
+static void am_destroy(const struct am_state *state)
+{
+     struct strbuf sb = STRBUF_INIT;
+
+     strbuf_addstr(&sb, state->dir.buf);
+     remove_dir_recursively(&sb, 0);
+     strbuf_release(&sb);
+}
Given that `remove_dir_recursively()` has to reset the strbuf with the directory's path to the original value before it returns (because it recurses into itself, therefore the value *has* to be reset when returning), we can just call

    remove_dir_recursively(&state->dir, 0);

and do not need another temporary strbuf.
Ah right. Although, state->dir is not an strbuf anymore on my side. As
Junio[3] rightfully noted, state->dir is not modified by the am_*()
API, so it's been changed to a char*. Which means an strbuf is
required to be passed to remove_dir_recursively();
quoted
+/**
+ * Increments the patch pointer, and cleans am_state for the application of the
+ * next patch.
+ */
+static void am_next(struct am_state *state)
+{
+     state->cur++;
+     write_file(am_path(state, "next"), 1, "%d", state->cur);
+}
Locking and re-checking the contents of "next" before writing the incremented value would probably be a little too paranoid...
Yeah, Junio did bring something like that[3]. I'm still thinking about
it, though I don't think I would like this issue to block the patch
series since it's a delicate issue, and git-am.sh does not do anything
special either.

For now though, I've moved all the write_file()s into a central
am_save() function, so if we want to do any locking or syncing it
would be easy to modify am_save(), and then all the callers will
benefit.

[3] http://thread.gmane.org/gmane.comp.version-control.git/271967/focus=271972

Re: [PATCH/WIP v3 06/31] am: detect mbox patches

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:32

On Thu, Jun 25, 2015 at 9:40 PM, Paul Tan [off-list ref] wrote:
On Wed, Jun 24, 2015 at 11:10 PM, Johannes Schindelin
[off-list ref] wrote:
quoted
quoted
+     else if (l1.len && l2.len && l3.len && is_email(paths->items->string))
+             ret = PATCH_FORMAT_MBOX;
Maybe we can do better than this by folding the `is_email() function into this here function, reusing the same strbuf to read the lines and keeping track of the email header lines we saw... I would really like to avoid opening the same file twice just to figure out whether it is in email format.
Okay, how about every time we call a strbuf_getline(), we save the
line to a string_list as well? Like string_list_getline_crlf() below:
[...]
Hmm, on second thought, I don't think it's worth the code complexity.
While I agree it's desirable to not open the file twice, I don't think
detecting the patch format is so IO intensive that it needs to be
optimized to that extent.

Instead, we should probably just modify is_email() to take a FILE*,
and then fseek(fp, 0L, SEEK_SET) to the beginning.

I think the logic of is_email() is complex and so it should not be
folded into the detect_patch_format() function, especially since we
may add detection of other patch formats in the future, and may need
more complex heuristics.

Regards,
Paul

Re: [PATCH/WIP v3 07/31] am: extract patch, message and authorship with git-mailinfo

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:32

On Thu, Jun 25, 2015 at 12:36 AM, Johannes Schindelin
[off-list ref] wrote:
On 2015-06-18 13:25, Paul Tan wrote:
quoted
diff --git a/builtin/am.c b/builtin/am.c
index 7b97ea8..d6434e4 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -94,6 +126,105 @@ static int read_state_file(struct strbuf *sb,
const char *file, size_t hint, int
 }

 /**
+ * Reads a KEY=VALUE shell variable assignment from fp, and returns the VALUE
+ * in `value`. VALUE must be a quoted string, and the KEY must match `key`.
+ * Returns 0 on success, -1 on failure.
+ *
+ * This is used by read_author_script() to read the GIT_AUTHOR_* variables from
+ * the author-script.
+ */
+static int read_shell_var(struct strbuf *value, FILE *fp, const char *key)
+{
+     struct strbuf sb = STRBUF_INIT;
+     char *str;
+
+     if (strbuf_getline(&sb, fp, '\n'))
+             return -1;
+
+     if (!skip_prefix(sb.buf, key, (const char **)&str))
+             return -1;
+
+     if (!skip_prefix(str, "=", (const char **)&str))
+             return -1;
+
+     str = sq_dequote(str);
+     if (!str)
+             return -1;
+
+     strbuf_reset(value);
+     strbuf_addstr(value, str);
+
+     strbuf_release(&sb);
+
+     return 0;
+}
How about using `strbuf_remove()` and keeping `str` as `const char *`?
OK, I'll try that out. Looks like this now:

static char *read_shell_var(FILE *fp, const char *key)
{
    struct strbuf sb = STRBUF_INIT;
    const char *str;

    if (strbuf_getline(&sb, fp, '\n'))
        return NULL;

    if (!skip_prefix(sb.buf, key, &str))
        return NULL;

    if (!skip_prefix(str, "=", &str))
        return NULL;

    strbuf_remove(&sb, 0, str - sb.buf);

    str = sq_dequote(sb.buf);
    if (!str)
        return NULL;

    return strbuf_detach(&sb, NULL);
}
I also think we can fold it into the `read_author_script()` function and make it more resilient with regards to the order of the variables. Something like this:
[...]
Hmm, I think we should be very strict about parsing the author-script
file though. As explained in read_author_script(), git-am.sh evals the
author-script, which we can't in C. I would much rather we barf at the
first sign that the author-script is not what we expect, rather than
attempt to parse it as much as possible, but end up with the wrong
results as compared to git-am.sh.

Besides, currently git-am.sh will always write the author-script with
the order of GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL and GIT_AUTHOR_DATE. If
the order is wrong, I would think it means that something is messing
with the author-script, and it would be better if we bail out
immediately, instead of potentially doing something wrong.
quoted
+/**
+ * Saves state->author_name, state->author_email and state->author_date in
+ * `filename` as an "author script", which is the format used by git-am.sh.
+ */
+static void write_author_script(const struct am_state *state)
+{
+     static const char fmt[] = "GIT_AUTHOR_NAME=%s\n"
+             "GIT_AUTHOR_EMAIL=%s\n"
+             "GIT_AUTHOR_DATE=%s\n";
+     struct strbuf author_name = STRBUF_INIT;
+     struct strbuf author_email = STRBUF_INIT;
+     struct strbuf author_date = STRBUF_INIT;
+
+     sq_quote_buf(&author_name, state->author_name.buf);
+     sq_quote_buf(&author_email, state->author_email.buf);
+     sq_quote_buf(&author_date, state->author_date.buf);
The `sq_quote_buf()` function does not call `strbuf_reset()`. Therefore you could just use a single strbuf to construct the entire three lines and then write that out. Again, if you follow my suggestion to keep a "scratch pad" strbuf in am_state, you could reuse that.
Right, makes sense. I've implemented it on my end.

Thanks,
Paul

Re: [PATCH/WIP v3 01/31] wrapper: implement xopen()

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:36

On Thu, Jun 25, 2015 at 2:39 AM, Johannes Schindelin
[off-list ref] wrote:
IMO the varargs make the code more cumbersome to read (and even fragile, because you can easily call `xopen(path, O_WRITE | O_CREATE)` and would not even get so much as a compiler warning!)
I think that since xopen() is a wrapper around open(), it is best to
follow its interface (as defined by the POSIX spec) as much as
possible. It's important to note that the POSIX spec explicitly
defines that open() takes a variable number of arguments, and that the
`mode` argument is only used if O_CREAT is set. This means that if we
cement xopen() to take 3 arguments, and the third is a mode_t (or an
int), then we may not be able to keep up with changes in the POSIX
spec which e.g. in the future may specify that open() takes 4
arguments if certain flags are set.
and the error message does carry value: it helps you resolve the issue (it is completely unnecessary to check write permissions of the directory when a file could not be opened for reading, for example, yet if the error message does not say that and you suspect that the file could not be opened for *writing* that is exactly what you would waste your time checking).
Good point, I agree with this. I'll look into putting the error messages back.

Thanks,
Paul

Re: [PATCH/WIP v3 01/31] wrapper: implement xopen()

From: Paul Tan <hidden>
Date: 2016-06-15 23:05:36

On Wed, Jul 1, 2015 at 5:41 PM, Paul Tan [off-list ref] wrote:
Good point, I agree with this. I'll look into putting the error messages back.
This should work I think. It should take into account that O_RDONLY,
O_WRONLY, O_RDWR is defines as 0, 1, 2 on glibc, while the POSIX spec
also defines that O_RDONLY | O_WRONLY == O_RDWR.
diff --git a/wrapper.c b/wrapper.c
index c867ca9..e451463 100644
--- a/wrapper.c
+++ b/wrapper.c
@@ -214,7 +214,13 @@ int xopen(const char *path, int oflag, ...)
             return fd;
         if (errno == EINTR)
             continue;
-        die_errno(_("could not open '%s'"), path);
+
+        if ((oflag & O_RDWR) == O_RDWR)
+            die_errno(_("could not open '%s' for reading and writing"), path);
+        else if ((oflag & O_WRONLY) == O_WRONLY)
+            die_errno(_("could not open '%s' for writing"), path);
+        else
+            die_errno(_("could not open '%s' for reading"), path);
     }
 }
@@ -351,7 +357,13 @@ FILE *xfopen(const char *path, const char *mode)
             return fp;
         if (errno == EINTR)
             continue;
-        die_errno(_("could not open '%s'"), path);
+
+        if (*mode && mode[1] == '+')
+            die_errno(_("could not open '%s' for reading and writing"), path);
+        else if (*mode == 'w' || *mode == 'a')
+            die_errno(_("could not open '%s' for writing"), path);
+        else
+            die_errno(_("could not open '%s' for reading"), path);
     }
 }
Keyboard shortcuts
hback out one level
jnext message in thread
kprevious message in thread
ldrill in
Escclose help / fold thread tree
?toggle this help