{"thread":{"id":"39799","subject":"[PATCH v5 00/44] Make git-am a builtin","startedAt":"2015-07-07T14:20:18Z","lastAt":"2015-07-18T15:22:12Z","messageCount":63,"participants":["Paul Tan","Junio C Hamano","Stefan Beller"],"isPatch":true,"patchVersion":5,"patchTotal":44},"messages":[{"id":"265687","messageId":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":null,"subject":"[PATCH v5 00/44] Make git-am a builtin","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:18Z","receivedAt":"2015-07-07T14:20:18Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"This patch series depends on pt/pull-builtin.\n\nThis is a re-roll of [v4]. Thanks Torsten, Stefan, Junio for the reviews last\nround. Interdiff below.\n\nPrevious versions:\n\n[WIP v1] http://thread.gmane.org/gmane.comp.version-control.git/270048\n[WIP v2] http://thread.gmane.org/gmane.comp.version-control.git/271381\n[WIP v3] http://thread.gmane.org/gmane.comp.version-control.git/271967\n[v4] http://thread.gmane.org/gmane.comp.version-control.git/272876\n\ngit-am is a commonly used command for applying a series of patches from a\nmailbox to the current branch. Currently, it is implemented by the shell script\ngit-am.sh. However, compared to C, shell scripts have certain deficiencies:\nthey need to spawn a lot of processes, introduce a lot of dependencies and\ncannot take advantage of git's internal caches.\n\nThis patch series rewrites git-am.sh into optimized C builtin/am.c, and is\npart of my GSoC project to rewrite git-pull and git-am into C builtins[1].\n\n[1] https://gist.github.com/pyokagan/1b7b0d1f4dab6ba3cef1\n\n\nPaul Tan (44):\n  wrapper: implement xopen()\n  wrapper: implement xfopen()\n  builtin-am: implement skeletal builtin am\n  builtin-am: implement patch queue mechanism\n  builtin-am: split out mbox/maildir patches with git-mailsplit\n  builtin-am: auto-detect mbox patches\n  builtin-am: extract patch and commit info with git-mailinfo\n  builtin-am: apply patch with git-apply\n  builtin-am: implement committing applied patch\n  builtin-am: refuse to apply patches if index is dirty\n  builtin-am: implement --resolved/--continue\n  builtin-am: implement --skip\n  builtin-am: implement --abort\n  builtin-am: reject patches when there's a session in progress\n  builtin-am: implement -q/--quiet\n  builtin-am: exit with user friendly message on failure\n  builtin-am: implement -s/--signoff\n  cache-tree: introduce write_index_as_tree()\n  builtin-am: implement --3way, am.threeWay\n  builtin-am: implement --rebasing mode\n  builtin-am: bypass git-mailinfo when --rebasing\n  builtin-am: handle stray state directory\n  builtin-am: implement -u/--utf8\n  builtin-am: implement -k/--keep, --keep-non-patch\n  builtin-am: implement --[no-]message-id, am.messageid\n  builtin-am: support --keep-cr, am.keepcr\n  builtin-am: implement --[no-]scissors\n  builtin-am: pass git-apply's options to git-apply\n  builtin-am: implement --ignore-date\n  builtin-am: implement --committer-date-is-author-date\n  builtin-am: implement -S/--gpg-sign, commit.gpgsign\n  builtin-am: invoke post-rewrite hook\n  builtin-am: support automatic notes copying\n  builtin-am: invoke applypatch-msg hook\n  builtin-am: invoke pre-applypatch hook\n  builtin-am: invoke post-applypatch hook\n  builtin-am: rerere support\n  builtin-am: support and auto-detect StGit patches\n  builtin-am: support and auto-detect StGit series files\n  builtin-am: support and auto-detect mercurial patches\n  builtin-am: implement -i/--interactive\n  builtin-am: implement legacy -b/--binary option\n  builtin-am: check for valid committer ident\n  builtin-am: remove redirection to git-am.sh\n\n Makefile                                |    2 +-\n builtin.h                               |    1 +\n builtin/am.c                            | 2331 +++++++++++++++++++++++++++++++\n cache-tree.c                            |   29 +-\n cache-tree.h                            |    1 +\n git-am.sh => contrib/examples/git-am.sh |    0\n git-compat-util.h                       |    2 +\n git.c                                   |    1 +\n wrapper.c                               |   56 +\n 9 files changed, 2410 insertions(+), 13 deletions(-)\n create mode 100644 builtin/am.c\n rename git-am.sh => contrib/examples/git-am.sh (100%)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex fb91145..c548129 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -71,8 +71,8 @@ static int linelen(const char *msg)\n  */\n static int str_isspace(const char *str)\n {\n-\twhile (*str)\n-\t\tif (!isspace(*(str)++))\n+\tfor (; *str; str++)\n+\t\tif (!isspace(*str))\n \t\t\treturn 0;\n \n \treturn 1;\n@@ -94,8 +94,8 @@ enum keep_type {\n \n enum scissors_type {\n \tSCISSORS_UNSET = -1,\n-\tSCISSORS_TRUE,  /* pass --scissors to git-mailinfo */\n-\tSCISSORS_FALSE  /* pass --no-scissors to git-mailinfo */\n+\tSCISSORS_FALSE = 0,  /* pass --no-scissors to git-mailinfo */\n+\tSCISSORS_TRUE        /* pass --scissors to git-mailinfo */\n };\n \n struct am_state {\n@@ -160,8 +160,7 @@ struct am_state {\n  */\n static void am_state_init(struct am_state *state, const char *dir)\n {\n-\tconst char *quiet;\n-\tint sign_commit;\n+\tint gpgsign;\n \n \tmemset(state, 0, sizeof(*state));\n \n@@ -172,10 +171,6 @@ static void am_state_init(struct am_state *state, const char *dir)\n \n \tgit_config_get_bool(\"am.threeway\", &state->threeway);\n \n-\tquiet = getenv(\"GIT_QUIET\");\n-\tif (quiet && *quiet)\n-\t\tstate->quiet = 1;\n-\n \tstate->utf8 = 1;\n \n \tgit_config_get_bool(\"am.messageid\", &state->message_id);\n@@ -184,8 +179,8 @@ static void am_state_init(struct am_state *state, const char *dir)\n \n \targv_array_init(&state->git_apply_opts);\n \n-\tif (!git_config_get_bool(\"commit.gpgsign\", &sign_commit))\n-\t\tstate->sign_commit = sign_commit ? \"\" : NULL;\n+\tif (!git_config_get_bool(\"commit.gpgsign\", &gpgsign))\n+\t\tstate->sign_commit = gpgsign ? \"\" : NULL;\n }\n \n /**\n@@ -918,7 +913,7 @@ static int hg_patch_to_mail(FILE *out, FILE *in, int keep_cr)\n \t\t\tfprintf(out, \"From: %s\\n\", str);\n \t\telse if (skip_prefix(sb.buf, \"# Date \", &str)) {\n \t\t\tunsigned long timestamp;\n-\t\t\tlong tz;\n+\t\t\tlong tz, tz2;\n \t\t\tchar *end;\n \n \t\t\terrno = 0;\n@@ -942,10 +937,11 @@ static int hg_patch_to_mail(FILE *out, FILE *in, int keep_cr)\n \t\t\t * however git's timezone is in hours + minutes east of\n \t\t\t * UTC. Convert it.\n \t\t\t */\n-\t\t\ttz = tz / (60 * 60) * 100 + tz % (60 * 60);\n-\t\t\ttz = -tz;\n+\t\t\ttz2 = labs(tz) / 3600 * 100 + labs(tz) % 3600 / 60;\n+\t\t\tif (tz > 0)\n+\t\t\t\ttz2 = -tz2;\n \n-\t\t\tfprintf(out, \"Date: %s\\n\", show_date(timestamp, tz, DATE_RFC2822));\n+\t\t\tfprintf(out, \"Date: %s\\n\", show_date(timestamp, tz2, DATE_RFC2822));\n \t\t} else if (starts_with(sb.buf, \"# \")) {\n \t\t\tcontinue;\n \t\t} else {\n@@ -1555,7 +1551,7 @@ static int run_apply(const struct am_state *state, const char *index_file)\n }\n \n /**\n- * Builds a index that contains just the blobs needed for a 3way merge.\n+ * Builds an index that contains just the blobs needed for a 3way merge.\n  */\n static int build_fake_ancestor(const struct am_state *state, const char *index_file)\n {\ndiff --git a/wrapper.c b/wrapper.c\nindex f127eb3..e451463 100644\n--- a/wrapper.c\n+++ b/wrapper.c\n@@ -197,20 +197,30 @@ int xopen(const char *path, int oflag, ...)\n \tmode_t mode = 0;\n \tva_list ap;\n \n+\t/*\n+\t * va_arg() will have undefined behavior if the specified type is not\n+\t * compatible with the argument type. Since integers are promoted to\n+\t * ints, we fetch the next argument as an int, and then cast it to a\n+\t * mode_t to avoid undefined behavior.\n+\t */\n \tva_start(ap, oflag);\n \tif (oflag & O_CREAT)\n-\t\tmode = va_arg(ap, mode_t);\n+\t\tmode = va_arg(ap, int);\n \tva_end(ap);\n \n-\tassert(path);\n-\n \tfor (;;) {\n \t\tint fd = open(path, oflag, mode);\n \t\tif (fd >= 0)\n \t\t\treturn fd;\n \t\tif (errno == EINTR)\n \t\t\tcontinue;\n-\t\tdie_errno(_(\"could not open '%s'\"), path);\n+\n+\t\tif ((oflag & O_RDWR) == O_RDWR)\n+\t\t\tdie_errno(_(\"could not open '%s' for reading and writing\"), path);\n+\t\telse if ((oflag & O_WRONLY) == O_WRONLY)\n+\t\t\tdie_errno(_(\"could not open '%s' for writing\"), path);\n+\t\telse\n+\t\t\tdie_errno(_(\"could not open '%s' for reading\"), path);\n \t}\n }\n \n@@ -341,16 +351,19 @@ int xdup(int fd)\n  */\n FILE *xfopen(const char *path, const char *mode)\n {\n-\tassert(path);\n-\tassert(mode);\n-\n \tfor (;;) {\n \t\tFILE *fp = fopen(path, mode);\n \t\tif (fp)\n \t\t\treturn fp;\n \t\tif (errno == EINTR)\n \t\t\tcontinue;\n-\t\tdie_errno(_(\"could not open '%s'\"), path);\n+\n+\t\tif (*mode && mode[1] == '+')\n+\t\t\tdie_errno(_(\"could not open '%s' for reading and writing\"), path);\n+\t\telse if (*mode == 'w' || *mode == 'a')\n+\t\t\tdie_errno(_(\"could not open '%s' for writing\"), path);\n+\t\telse\n+\t\t\tdie_errno(_(\"could not open '%s' for reading\"), path);\n \t}\n }\n \n\n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265688","messageId":"1436278862-2638-2-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 01/44] wrapper: implement xopen()","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:19Z","receivedAt":"2015-07-07T14:20:19Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"A common usage pattern of open() is to check if it was successful, and\ndie() if it was not:\n\n\tint fd = open(path, O_WRONLY | O_CREAT, 0777);\n\tif (fd < 0)\n\t\tdie_errno(_(\"Could not open '%s' for writing.\"), path);\n\nImplement a wrapper function xopen() that does the above so that we can\nsave a few lines of code, and make the die() messages consistent.\n\nHelped-by: Torsten Bögershausen <tboegi@web.de>\nHelped-by: Jeff King <peff@peff.net>\nHelped-by: Johannes Schindelin <johannes.schindelin@gmx.de>\nHelped-by: Junio C Hamano <gitster@pobox.com>\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n\nNotes:\n    v5\n    \n    * Remove assert()s since we do not need to over-zealously check against\n      insane code.\n    \n    * Use va_arg(va, int) instead of va_arg(va, mode_t) to guard against\n      undefined behavior if mode_t is incompatible with the promoted integer\n      argument (int).\n    \n    * The read/write error messages have returned as they can be used to\n      better diagnose permission errors. Hopefully I got the logic right\n      this time.\n\n git-compat-util.h |  1 +\n wrapper.c         | 35 +++++++++++++++++++++++++++++++++++\n 2 files changed, 36 insertions(+)\n\ndiff --git a/git-compat-util.h b/git-compat-util.h\nindex c6d391f..e168dfd 100644\n--- a/git-compat-util.h\n+++ b/git-compat-util.h\n@@ -717,6 +717,7 @@ extern void *xrealloc(void *ptr, size_t size);\n extern void *xcalloc(size_t nmemb, size_t size);\n extern void *xmmap(void *start, size_t length, int prot, int flags, int fd, off_t offset);\n extern void *xmmap_gently(void *start, size_t length, int prot, int flags, int fd, off_t offset);\n+extern int xopen(const char *path, int flags, ...);\n extern ssize_t xread(int fd, void *buf, size_t len);\n extern ssize_t xwrite(int fd, const void *buf, size_t len);\n extern ssize_t xpread(int fd, void *buf, size_t len, off_t offset);\ndiff --git a/wrapper.c b/wrapper.c\nindex ff49807..0a4502d 100644\n--- a/wrapper.c\n+++ b/wrapper.c\n@@ -189,6 +189,41 @@ void *xcalloc(size_t nmemb, size_t size)\n # endif\n #endif\n \n+/**\n+ * xopen() is the same as open(), but it die()s if the open() fails.\n+ */\n+int xopen(const char *path, int oflag, ...)\n+{\n+\tmode_t mode = 0;\n+\tva_list ap;\n+\n+\t/*\n+\t * va_arg() will have undefined behavior if the specified type is not\n+\t * compatible with the argument type. Since integers are promoted to\n+\t * ints, we fetch the next argument as an int, and then cast it to a\n+\t * mode_t to avoid undefined behavior.\n+\t */\n+\tva_start(ap, oflag);\n+\tif (oflag & O_CREAT)\n+\t\tmode = va_arg(ap, int);\n+\tva_end(ap);\n+\n+\tfor (;;) {\n+\t\tint fd = open(path, oflag, mode);\n+\t\tif (fd >= 0)\n+\t\t\treturn fd;\n+\t\tif (errno == EINTR)\n+\t\t\tcontinue;\n+\n+\t\tif ((oflag & O_RDWR) == O_RDWR)\n+\t\t\tdie_errno(_(\"could not open '%s' for reading and writing\"), path);\n+\t\telse if ((oflag & O_WRONLY) == O_WRONLY)\n+\t\t\tdie_errno(_(\"could not open '%s' for writing\"), path);\n+\t\telse\n+\t\t\tdie_errno(_(\"could not open '%s' for reading\"), path);\n+\t}\n+}\n+\n /*\n  * xread() is the same a read(), but it automatically restarts read()\n  * operations with a recoverable error (EAGAIN and EINTR). xread()\n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265690","messageId":"1436278862-2638-3-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 02/44] wrapper: implement xfopen()","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:20Z","receivedAt":"2015-07-07T14:20:20Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"A common usage pattern of fopen() is to check if it succeeded, and die()\nif it failed:\n\n\tFILE *fp = fopen(path, \"w\");\n\tif (!fp)\n\t\tdie_errno(_(\"could not open '%s' for writing\"), path);\n\nImplement a wrapper function xfopen() for the above, so that we can save\na few lines of code and make the die() messages consistent.\n\nHelped-by: Jeff King <peff@peff.net>\nHelped-by: Johannes Schindelin <johannes.schindelin@gmx.de>\nHelped-by: Junio C Hamano <gitster@pobox.com>\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n\nNotes:\n    v5\n    \n    * Removed assert()s since we do not need to over-zealously guard against\n      insane code.\n    \n    * The read/write error messages have returned as they are useful in\n      diagnosing permission errors. Hopefully I got the logic right this\n      time.\n\n git-compat-util.h |  1 +\n wrapper.c         | 21 +++++++++++++++++++++\n 2 files changed, 22 insertions(+)\n\ndiff --git a/git-compat-util.h b/git-compat-util.h\nindex e168dfd..392da79 100644\n--- a/git-compat-util.h\n+++ b/git-compat-util.h\n@@ -722,6 +722,7 @@ extern ssize_t xread(int fd, void *buf, size_t len);\n extern ssize_t xwrite(int fd, const void *buf, size_t len);\n extern ssize_t xpread(int fd, void *buf, size_t len, off_t offset);\n extern int xdup(int fd);\n+extern FILE *xfopen(const char *path, const char *mode);\n extern FILE *xfdopen(int fd, const char *mode);\n extern int xmkstemp(char *template);\n extern int xmkstemp_mode(char *template, int mode);\ndiff --git a/wrapper.c b/wrapper.c\nindex 0a4502d..e451463 100644\n--- a/wrapper.c\n+++ b/wrapper.c\n@@ -346,6 +346,27 @@ int xdup(int fd)\n \treturn ret;\n }\n \n+/**\n+ * xfopen() is the same as fopen(), but it die()s if the fopen() fails.\n+ */\n+FILE *xfopen(const char *path, const char *mode)\n+{\n+\tfor (;;) {\n+\t\tFILE *fp = fopen(path, mode);\n+\t\tif (fp)\n+\t\t\treturn fp;\n+\t\tif (errno == EINTR)\n+\t\t\tcontinue;\n+\n+\t\tif (*mode && mode[1] == '+')\n+\t\t\tdie_errno(_(\"could not open '%s' for reading and writing\"), path);\n+\t\telse if (*mode == 'w' || *mode == 'a')\n+\t\t\tdie_errno(_(\"could not open '%s' for writing\"), path);\n+\t\telse\n+\t\t\tdie_errno(_(\"could not open '%s' for reading\"), path);\n+\t}\n+}\n+\n FILE *xfdopen(int fd, const char *mode)\n {\n \tFILE *stream = fdopen(fd, mode);\n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265689","messageId":"1436278862-2638-4-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 03/44] builtin-am: implement skeletal builtin am","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:21Z","receivedAt":"2015-07-07T14:20:21Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"For the purpose of rewriting git-am.sh into a C builtin, implement a\nskeletal builtin/am.c that redirects to $GIT_EXEC_PATH/git-am if the\nenvironment variable _GIT_USE_BUILTIN_AM is not defined. Since in the\nMakefile git-am.sh takes precedence over builtin/am.c,\n$GIT_EXEC_PATH/git-am will contain the shell script git-am.sh, and thus\nthis allows us to fall back on the functional git-am.sh when running the\ntest suite for tests that depend on a working git-am implementation.\n\nSince git-am.sh cannot handle any environment modifications by\nsetup_git_directory(), \"am\" is declared with no setup flags in git.c. On\nthe other hand, to re-implement git-am.sh in builtin/am.c, we need to\nrun all the git dir and work tree setup logic that git.c typically does\nfor us. As such, we work around this temporarily by copying the logic in\ngit.c's run_builtin(), which is roughly:\n\n\tprefix = setup_git_directory();\n\ttrace_repo_setup(prefix);\n\tsetup_work_tree();\n\nThis redirection should be removed when all the features of git-am.sh\nhave been re-implemented in builtin/am.c.\n\nHelped-by: Junio C Hamano <gitster@pobox.com>\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n Makefile     |  1 +\n builtin.h    |  1 +\n builtin/am.c | 29 +++++++++++++++++++++++++++++\n git.c        |  6 ++++++\n 4 files changed, 37 insertions(+)\n create mode 100644 builtin/am.c\n\ndiff --git a/Makefile b/Makefile\nindex 93e4fa2..ff9bdc0 100644\n--- a/Makefile\n+++ b/Makefile\n@@ -811,6 +811,7 @@ LIB_OBJS += xdiff-interface.o\n LIB_OBJS += zlib.o\n \n BUILTIN_OBJS += builtin/add.o\n+BUILTIN_OBJS += builtin/am.o\n BUILTIN_OBJS += builtin/annotate.o\n BUILTIN_OBJS += builtin/apply.o\n BUILTIN_OBJS += builtin/archive.o\ndiff --git a/builtin.h b/builtin.h\nindex ea3c834..f30cf00 100644\n--- a/builtin.h\n+++ b/builtin.h\n@@ -30,6 +30,7 @@ extern int textconv_object(const char *path, unsigned mode, const unsigned char\n extern int is_builtin(const char *s);\n \n extern int cmd_add(int argc, const char **argv, const char *prefix);\n+extern int cmd_am(int argc, const char **argv, const char *prefix);\n extern int cmd_annotate(int argc, const char **argv, const char *prefix);\n extern int cmd_apply(int argc, const char **argv, const char *prefix);\n extern int cmd_archive(int argc, const char **argv, const char *prefix);\ndiff --git a/builtin/am.c b/builtin/am.c\nnew file mode 100644\nindex 0000000..fd32caf\n--- /dev/null\n+++ b/builtin/am.c\n@@ -0,0 +1,29 @@\n+/*\n+ * Builtin \"git am\"\n+ *\n+ * Based on git-am.sh by Junio C Hamano.\n+ */\n+#include \"cache.h\"\n+#include \"builtin.h\"\n+#include \"exec_cmd.h\"\n+\n+int cmd_am(int argc, const char **argv, const char *prefix)\n+{\n+\n+\t/*\n+\t * NEEDSWORK: Once all the features of git-am.sh have been\n+\t * re-implemented in builtin/am.c, this preamble can be removed.\n+\t */\n+\tif (!getenv(\"_GIT_USE_BUILTIN_AM\")) {\n+\t\tconst char *path = mkpath(\"%s/git-am\", git_exec_path());\n+\n+\t\tif (sane_execvp(path, (char **)argv) < 0)\n+\t\t\tdie_errno(\"could not exec %s\", path);\n+\t} else {\n+\t\tprefix = setup_git_directory();\n+\t\ttrace_repo_setup(prefix);\n+\t\tsetup_work_tree();\n+\t}\n+\n+\treturn 0;\n+}\ndiff --git a/git.c b/git.c\nindex e7a7713..e84e1a1 100644\n--- a/git.c\n+++ b/git.c\n@@ -370,6 +370,12 @@ static int run_builtin(struct cmd_struct *p, int argc, const char **argv)\n \n static struct cmd_struct commands[] = {\n \t{ \"add\", cmd_add, RUN_SETUP | NEED_WORK_TREE },\n+\t/*\n+\t * NEEDSWORK: Once the redirection to git-am.sh in builtin/am.c has\n+\t * been removed, this entry should be changed to\n+\t * RUN_SETUP | NEED_WORK_TREE\n+\t */\n+\t{ \"am\", cmd_am },\n \t{ \"annotate\", cmd_annotate, RUN_SETUP },\n \t{ \"apply\", cmd_apply, RUN_SETUP_GENTLY },\n \t{ \"archive\", cmd_archive },\n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265691","messageId":"1436278862-2638-5-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 04/44] builtin-am: implement patch queue mechanism","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:22Z","receivedAt":"2015-07-07T14:20:22Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"git-am applies a series of patches. If the process terminates\nabnormally, we want to be able to resume applying the series of patches.\nThis requires the session state to be saved in a persistent location.\n\nImplement the mechanism of a \"patch queue\", represented by 2 integers --\nthe index of the current patch we are applying and the index of the last\npatch, as well as its lifecycle through the following functions:\n\n* am_setup(), which will set up the state directory\n  $GIT_DIR/rebase-apply. As such, even if the process exits abnormally,\n  the last-known state will still persist.\n\n* am_load(), which is called if there is an am session in\n  progress, to load the last known state from the state directory so we\n  can resume applying patches.\n\n* am_run(), which will do the actual patch application. After applying a\n  patch, it calls am_next() to increment the current patch index. The\n  logic for applying and committing a patch is not implemented yet.\n\n* am_destroy(), which is finally called when we successfully applied all\n  the patches in the queue, to clean up by removing the state directory\n  and its contents.\n\nHelped-by: Junio C Hamano <gitster@pobox.com>\nHelped-by: Stefan Beller <sbeller@google.com>\nHelped-by: Johannes Schindelin <johannes.schindelin@gmx.de>\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n builtin/am.c | 180 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n 1 file changed, 180 insertions(+)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex fd32caf..292f793 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -6,9 +6,174 @@\n #include \"cache.h\"\n #include \"builtin.h\"\n #include \"exec_cmd.h\"\n+#include \"parse-options.h\"\n+#include \"dir.h\"\n+\n+struct am_state {\n+\t/* state directory path */\n+\tchar *dir;\n+\n+\t/* current and last patch numbers, 1-indexed */\n+\tint cur;\n+\tint last;\n+};\n+\n+/**\n+ * Initializes am_state with the default values. The state directory is set to\n+ * dir.\n+ */\n+static void am_state_init(struct am_state *state, const char *dir)\n+{\n+\tmemset(state, 0, sizeof(*state));\n+\n+\tassert(dir);\n+\tstate->dir = xstrdup(dir);\n+}\n+\n+/**\n+ * Releases memory allocated by an am_state.\n+ */\n+static void am_state_release(struct am_state *state)\n+{\n+\tif (state->dir)\n+\t\tfree(state->dir);\n+}\n+\n+/**\n+ * Returns path relative to the am_state directory.\n+ */\n+static inline const char *am_path(const struct am_state *state, const char *path)\n+{\n+\tassert(state->dir);\n+\tassert(path);\n+\treturn mkpath(\"%s/%s\", state->dir, path);\n+}\n+\n+/**\n+ * Returns 1 if there is an am session in progress, 0 otherwise.\n+ */\n+static int am_in_progress(const struct am_state *state)\n+{\n+\tstruct stat st;\n+\n+\tif (lstat(state->dir, &st) < 0 || !S_ISDIR(st.st_mode))\n+\t\treturn 0;\n+\tif (lstat(am_path(state, \"last\"), &st) || !S_ISREG(st.st_mode))\n+\t\treturn 0;\n+\tif (lstat(am_path(state, \"next\"), &st) || !S_ISREG(st.st_mode))\n+\t\treturn 0;\n+\treturn 1;\n+}\n+\n+/**\n+ * Reads the contents of `file` in the `state` directory into `sb`. Returns the\n+ * number of bytes read on success, -1 if the file does not exist. If `trim` is\n+ * set, trailing whitespace will be removed.\n+ */\n+static int read_state_file(struct strbuf *sb, const struct am_state *state,\n+\t\t\tconst char *file, int trim)\n+{\n+\tstrbuf_reset(sb);\n+\n+\tif (strbuf_read_file(sb, am_path(state, file), 0) >= 0) {\n+\t\tif (trim)\n+\t\t\tstrbuf_trim(sb);\n+\n+\t\treturn sb->len;\n+\t}\n+\n+\tif (errno == ENOENT)\n+\t\treturn -1;\n+\n+\tdie_errno(_(\"could not read '%s'\"), am_path(state, file));\n+}\n+\n+/**\n+ * Loads state from disk.\n+ */\n+static void am_load(struct am_state *state)\n+{\n+\tstruct strbuf sb = STRBUF_INIT;\n+\n+\tif (read_state_file(&sb, state, \"next\", 1) < 0)\n+\t\tdie(\"BUG: state file 'next' does not exist\");\n+\tstate->cur = strtol(sb.buf, NULL, 10);\n+\n+\tif (read_state_file(&sb, state, \"last\", 1) < 0)\n+\t\tdie(\"BUG: state file 'last' does not exist\");\n+\tstate->last = strtol(sb.buf, NULL, 10);\n+\n+\tstrbuf_release(&sb);\n+}\n+\n+/**\n+ * Removes the am_state directory, forcefully terminating the current am\n+ * session.\n+ */\n+static void am_destroy(const struct am_state *state)\n+{\n+\tstruct strbuf sb = STRBUF_INIT;\n+\n+\tstrbuf_addstr(&sb, state->dir);\n+\tremove_dir_recursively(&sb, 0);\n+\tstrbuf_release(&sb);\n+}\n+\n+/**\n+ * Setup a new am session for applying patches\n+ */\n+static void am_setup(struct am_state *state)\n+{\n+\tif (mkdir(state->dir, 0777) < 0 && errno != EEXIST)\n+\t\tdie_errno(_(\"failed to create directory '%s'\"), state->dir);\n+\n+\t/*\n+\t * NOTE: Since the \"next\" and \"last\" files determine if an am_state\n+\t * session is in progress, they should be written last.\n+\t */\n+\n+\twrite_file(am_path(state, \"next\"), 1, \"%d\", state->cur);\n+\n+\twrite_file(am_path(state, \"last\"), 1, \"%d\", state->last);\n+}\n+\n+/**\n+ * Increments the patch pointer, and cleans am_state for the application of the\n+ * next patch.\n+ */\n+static void am_next(struct am_state *state)\n+{\n+\tstate->cur++;\n+\twrite_file(am_path(state, \"next\"), 1, \"%d\", state->cur);\n+}\n+\n+/**\n+ * Applies all queued mail.\n+ */\n+static void am_run(struct am_state *state)\n+{\n+\twhile (state->cur <= state->last) {\n+\n+\t\t/* NEEDSWORK: Patch application not implemented yet */\n+\n+\t\tam_next(state);\n+\t}\n+\n+\tam_destroy(state);\n+}\n \n int cmd_am(int argc, const char **argv, const char *prefix)\n {\n+\tstruct am_state state;\n+\n+\tconst char * const usage[] = {\n+\t\tN_(\"git am [options] [(<mbox>|<Maildir>)...]\"),\n+\t\tNULL\n+\t};\n+\n+\tstruct option options[] = {\n+\t\tOPT_END()\n+\t};\n \n \t/*\n \t * NEEDSWORK: Once all the features of git-am.sh have been\n@@ -25,5 +190,20 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \t\tsetup_work_tree();\n \t}\n \n+\tgit_config(git_default_config, NULL);\n+\n+\tam_state_init(&state, git_path(\"rebase-apply\"));\n+\n+\targc = parse_options(argc, argv, prefix, options, usage, 0);\n+\n+\tif (am_in_progress(&state))\n+\t\tam_load(&state);\n+\telse\n+\t\tam_setup(&state);\n+\n+\tam_run(&state);\n+\n+\tam_state_release(&state);\n+\n \treturn 0;\n }\n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265692","messageId":"1436278862-2638-6-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 05/44] builtin-am: split out mbox/maildir patches with git-mailsplit","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:23Z","receivedAt":"2015-07-07T14:20:23Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"git-am.sh supports mbox, stgit and mercurial patches. Re-implement\nsupport for splitting out mbox/maildirs using git-mailsplit, while also\nimplementing the framework required to support other patch formats in\nthe future.\n\nRe-implement support for the --patch-format option (since a5a6755\n(git-am foreign patch support: introduce patch_format, 2009-05-27)) to\nallow the user to choose between the different patch formats.\n\nHelped-by: Junio C Hamano <gitster@pobox.com>\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n builtin/am.c | 107 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++--\n 1 file changed, 104 insertions(+), 3 deletions(-)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex 292f793..ae93e0e 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -8,6 +8,12 @@\n #include \"exec_cmd.h\"\n #include \"parse-options.h\"\n #include \"dir.h\"\n+#include \"run-command.h\"\n+\n+enum patch_format {\n+\tPATCH_FORMAT_UNKNOWN = 0,\n+\tPATCH_FORMAT_MBOX\n+};\n \n struct am_state {\n \t/* state directory path */\n@@ -16,6 +22,9 @@ struct am_state {\n \t/* current and last patch numbers, 1-indexed */\n \tint cur;\n \tint last;\n+\n+\t/* number of digits in patch filename */\n+\tint prec;\n };\n \n /**\n@@ -28,6 +37,8 @@ static void am_state_init(struct am_state *state, const char *dir)\n \n \tassert(dir);\n \tstate->dir = xstrdup(dir);\n+\n+\tstate->prec = 4;\n }\n \n /**\n@@ -120,13 +131,71 @@ static void am_destroy(const struct am_state *state)\n }\n \n /**\n+ * Splits out individual email patches from `paths`, where each path is either\n+ * a mbox file or a Maildir. Returns 0 on success, -1 on failure.\n+ */\n+static int split_mail_mbox(struct am_state *state, const char **paths)\n+{\n+\tstruct child_process cp = CHILD_PROCESS_INIT;\n+\tstruct strbuf last = STRBUF_INIT;\n+\n+\tcp.git_cmd = 1;\n+\targv_array_push(&cp.args, \"mailsplit\");\n+\targv_array_pushf(&cp.args, \"-d%d\", state->prec);\n+\targv_array_pushf(&cp.args, \"-o%s\", state->dir);\n+\targv_array_push(&cp.args, \"-b\");\n+\targv_array_push(&cp.args, \"--\");\n+\targv_array_pushv(&cp.args, paths);\n+\n+\tif (capture_command(&cp, &last, 8))\n+\t\treturn -1;\n+\n+\tstate->cur = 1;\n+\tstate->last = strtol(last.buf, NULL, 10);\n+\n+\treturn 0;\n+}\n+\n+/**\n+ * Splits a list of files/directories into individual email patches. Each path\n+ * in `paths` must be a file/directory that is formatted according to\n+ * `patch_format`.\n+ *\n+ * Once split out, the individual email patches will be stored in the state\n+ * directory, with each patch's filename being its index, padded to state->prec\n+ * digits.\n+ *\n+ * state->cur will be set to the index of the first mail, and state->last will\n+ * be set to the index of the last mail.\n+ *\n+ * Returns 0 on success, -1 on failure.\n+ */\n+static int split_mail(struct am_state *state, enum patch_format patch_format,\n+\t\t\tconst char **paths)\n+{\n+\tswitch (patch_format) {\n+\tcase PATCH_FORMAT_MBOX:\n+\t\treturn split_mail_mbox(state, paths);\n+\tdefault:\n+\t\tdie(\"BUG: invalid patch_format\");\n+\t}\n+\treturn -1;\n+}\n+\n+/**\n  * Setup a new am session for applying patches\n  */\n-static void am_setup(struct am_state *state)\n+static void am_setup(struct am_state *state, enum patch_format patch_format,\n+\t\t\tconst char **paths)\n {\n \tif (mkdir(state->dir, 0777) < 0 && errno != EEXIST)\n \t\tdie_errno(_(\"failed to create directory '%s'\"), state->dir);\n \n+\tif (split_mail(state, patch_format, paths) < 0) {\n+\t\tam_destroy(state);\n+\t\tdie(_(\"Failed to split patches.\"));\n+\t}\n+\n \t/*\n \t * NOTE: Since the \"next\" and \"last\" files determine if an am_state\n \t * session is in progress, they should be written last.\n@@ -162,9 +231,25 @@ static void am_run(struct am_state *state)\n \tam_destroy(state);\n }\n \n+/**\n+ * parse_options() callback that validates and sets opt->value to the\n+ * PATCH_FORMAT_* enum value corresponding to `arg`.\n+ */\n+static int parse_opt_patchformat(const struct option *opt, const char *arg, int unset)\n+{\n+\tint *opt_value = opt->value;\n+\n+\tif (!strcmp(arg, \"mbox\"))\n+\t\t*opt_value = PATCH_FORMAT_MBOX;\n+\telse\n+\t\treturn error(_(\"Invalid value for --patch-format: %s\"), arg);\n+\treturn 0;\n+}\n+\n int cmd_am(int argc, const char **argv, const char *prefix)\n {\n \tstruct am_state state;\n+\tint patch_format = PATCH_FORMAT_UNKNOWN;\n \n \tconst char * const usage[] = {\n \t\tN_(\"git am [options] [(<mbox>|<Maildir>)...]\"),\n@@ -172,6 +257,9 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \t};\n \n \tstruct option options[] = {\n+\t\tOPT_CALLBACK(0, \"patch-format\", &patch_format, N_(\"format\"),\n+\t\t\tN_(\"format the patch(es) are in\"),\n+\t\t\tparse_opt_patchformat),\n \t\tOPT_END()\n \t};\n \n@@ -198,8 +286,21 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \n \tif (am_in_progress(&state))\n \t\tam_load(&state);\n-\telse\n-\t\tam_setup(&state);\n+\telse {\n+\t\tstruct argv_array paths = ARGV_ARRAY_INIT;\n+\t\tint i;\n+\n+\t\tfor (i = 0; i < argc; i++) {\n+\t\t\tif (is_absolute_path(argv[i]) || !prefix)\n+\t\t\t\targv_array_push(&paths, argv[i]);\n+\t\t\telse\n+\t\t\t\targv_array_push(&paths, mkpath(\"%s/%s\", prefix, argv[i]));\n+\t\t}\n+\n+\t\tam_setup(&state, patch_format, paths.argv);\n+\n+\t\targv_array_clear(&paths);\n+\t}\n \n \tam_run(&state);\n \n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265693","messageId":"1436278862-2638-7-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 06/44] builtin-am: auto-detect mbox patches","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:24Z","receivedAt":"2015-07-07T14:20:24Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"Since 15ced75 (git-am foreign patch support: autodetect some patch\nformats, 2009-05-27), git-am.sh is able to autodetect mbox, stgit and\nmercurial patches through heuristics.\n\nRe-implement support for autodetecting mbox/maildir files in\nbuiltin/am.c.\n\nRFC 2822 requires that lines are terminated by \"\\r\\n\". To support this,\nimplement strbuf_getline_crlf(), which will remove both '\\n' and \"\\r\\n\"\nfrom the end of the line.\n\nHelped-by: Junio C Hamano <gitster@pobox.com>\nHelped-by: Eric Sunshine <sunshine@sunshineco.com>\nHelped-by: Johannes Schindelin <johannes.schindelin@gmx.de>\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n builtin/am.c | 109 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n 1 file changed, 109 insertions(+)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex ae93e0e..9422adc 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -10,6 +10,21 @@\n #include \"dir.h\"\n #include \"run-command.h\"\n \n+/**\n+ * Like strbuf_getline(), but treats both '\\n' and \"\\r\\n\" as line terminators.\n+ */\n+static int strbuf_getline_crlf(struct strbuf *sb, FILE *fp)\n+{\n+\tif (strbuf_getwholeline(sb, fp, '\\n'))\n+\t\treturn EOF;\n+\tif (sb->buf[sb->len - 1] == '\\n') {\n+\t\tstrbuf_setlen(sb, sb->len - 1);\n+\t\tif (sb->len > 0 && sb->buf[sb->len - 1] == '\\r')\n+\t\t\tstrbuf_setlen(sb, sb->len - 1);\n+\t}\n+\treturn 0;\n+}\n+\n enum patch_format {\n \tPATCH_FORMAT_UNKNOWN = 0,\n \tPATCH_FORMAT_MBOX\n@@ -131,6 +146,92 @@ static void am_destroy(const struct am_state *state)\n }\n \n /**\n+ * Determines if the file looks like a piece of RFC2822 mail by grabbing all\n+ * non-indented lines and checking if they look like they begin with valid\n+ * header field names.\n+ *\n+ * Returns 1 if the file looks like a piece of mail, 0 otherwise.\n+ */\n+static int is_mail(FILE *fp)\n+{\n+\tconst char *header_regex = \"^[!-9;-~]+:\";\n+\tstruct strbuf sb = STRBUF_INIT;\n+\tregex_t regex;\n+\tint ret = 1;\n+\n+\tif (fseek(fp, 0L, SEEK_SET))\n+\t\tdie_errno(_(\"fseek failed\"));\n+\n+\tif (regcomp(&regex, header_regex, REG_NOSUB | REG_EXTENDED))\n+\t\tdie(\"invalid pattern: %s\", header_regex);\n+\n+\twhile (!strbuf_getline_crlf(&sb, fp)) {\n+\t\tif (!sb.len)\n+\t\t\tbreak; /* End of header */\n+\n+\t\t/* Ignore indented folded lines */\n+\t\tif (*sb.buf == '\\t' || *sb.buf == ' ')\n+\t\t\tcontinue;\n+\n+\t\t/* It's a header if it matches header_regex */\n+\t\tif (regexec(&regex, sb.buf, 0, NULL, 0)) {\n+\t\t\tret = 0;\n+\t\t\tgoto done;\n+\t\t}\n+\t}\n+\n+done:\n+\tregfree(&regex);\n+\tstrbuf_release(&sb);\n+\treturn ret;\n+}\n+\n+/**\n+ * Attempts to detect the patch_format of the patches contained in `paths`,\n+ * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if\n+ * detection fails.\n+ */\n+static int detect_patch_format(const char **paths)\n+{\n+\tenum patch_format ret = PATCH_FORMAT_UNKNOWN;\n+\tstruct strbuf l1 = STRBUF_INIT;\n+\tFILE *fp;\n+\n+\t/*\n+\t * We default to mbox format if input is from stdin and for directories\n+\t */\n+\tif (!*paths || !strcmp(*paths, \"-\") || is_directory(*paths))\n+\t\treturn PATCH_FORMAT_MBOX;\n+\n+\t/*\n+\t * Otherwise, check the first few lines of the first patch, starting\n+\t * from the first non-blank line, to try to detect its format.\n+\t */\n+\n+\tfp = xfopen(*paths, \"r\");\n+\n+\twhile (!strbuf_getline_crlf(&l1, fp)) {\n+\t\tif (l1.len)\n+\t\t\tbreak;\n+\t}\n+\n+\tif (starts_with(l1.buf, \"From \") || starts_with(l1.buf, \"From: \")) {\n+\t\tret = PATCH_FORMAT_MBOX;\n+\t\tgoto done;\n+\t}\n+\n+\tif (l1.len && is_mail(fp)) {\n+\t\tret = PATCH_FORMAT_MBOX;\n+\t\tgoto done;\n+\t}\n+\n+done:\n+\tfclose(fp);\n+\tstrbuf_release(&l1);\n+\treturn ret;\n+}\n+\n+/**\n  * Splits out individual email patches from `paths`, where each path is either\n  * a mbox file or a Maildir. Returns 0 on success, -1 on failure.\n  */\n@@ -188,6 +289,14 @@ static int split_mail(struct am_state *state, enum patch_format patch_format,\n static void am_setup(struct am_state *state, enum patch_format patch_format,\n \t\t\tconst char **paths)\n {\n+\tif (!patch_format)\n+\t\tpatch_format = detect_patch_format(paths);\n+\n+\tif (!patch_format) {\n+\t\tfprintf_ln(stderr, _(\"Patch format detection failed.\"));\n+\t\texit(128);\n+\t}\n+\n \tif (mkdir(state->dir, 0777) < 0 && errno != EEXIST)\n \t\tdie_errno(_(\"failed to create directory '%s'\"), state->dir);\n \n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265697","messageId":"1436278862-2638-8-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 07/44] builtin-am: extract patch and commit info with git-mailinfo","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:25Z","receivedAt":"2015-07-07T14:20:25Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"For the purpose of applying the patch and committing the results,\nimplement extracting the patch data, commit message and authorship from\nan e-mail message using git-mailinfo.\n\ngit-mailinfo is run as a separate process, but ideally in the future,\nwe should be be able to access its functionality directly without\nspawning a new process.\n\nHelped-by: Junio C Hamano <gitster@pobox.com>\nHelped-by: Jeff King <peff@peff.net>\nHelped-by: Johannes Schindelin <johannes.schindelin@gmx.de>\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n builtin/am.c | 335 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n 1 file changed, 335 insertions(+)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex 9422adc..4897857 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -9,6 +9,23 @@\n #include \"parse-options.h\"\n #include \"dir.h\"\n #include \"run-command.h\"\n+#include \"quote.h\"\n+\n+/**\n+ * Returns 1 if the file is empty or does not exist, 0 otherwise.\n+ */\n+static int is_empty_file(const char *filename)\n+{\n+\tstruct stat st;\n+\n+\tif (stat(filename, &st) < 0) {\n+\t\tif (errno == ENOENT)\n+\t\t\treturn 1;\n+\t\tdie_errno(_(\"could not stat %s\"), filename);\n+\t}\n+\n+\treturn !st.st_size;\n+}\n \n /**\n  * Like strbuf_getline(), but treats both '\\n' and \"\\r\\n\" as line terminators.\n@@ -38,6 +55,13 @@ struct am_state {\n \tint cur;\n \tint last;\n \n+\t/* commit metadata and message */\n+\tchar *author_name;\n+\tchar *author_email;\n+\tchar *author_date;\n+\tchar *msg;\n+\tsize_t msg_len;\n+\n \t/* number of digits in patch filename */\n \tint prec;\n };\n@@ -63,6 +87,18 @@ static void am_state_release(struct am_state *state)\n {\n \tif (state->dir)\n \t\tfree(state->dir);\n+\n+\tif (state->author_name)\n+\t\tfree(state->author_name);\n+\n+\tif (state->author_email)\n+\t\tfree(state->author_email);\n+\n+\tif (state->author_date)\n+\t\tfree(state->author_date);\n+\n+\tif (state->msg)\n+\t\tfree(state->msg);\n }\n \n /**\n@@ -115,6 +151,167 @@ static int read_state_file(struct strbuf *sb, const struct am_state *state,\n }\n \n /**\n+ * Reads a KEY=VALUE shell variable assignment from `fp`, returning the VALUE\n+ * as a newly-allocated string. VALUE must be a quoted string, and the KEY must\n+ * match `key`. Returns NULL on failure.\n+ *\n+ * This is used by read_author_script() to read the GIT_AUTHOR_* variables from\n+ * the author-script.\n+ */\n+static char *read_shell_var(FILE *fp, const char *key)\n+{\n+\tstruct strbuf sb = STRBUF_INIT;\n+\tconst char *str;\n+\n+\tif (strbuf_getline(&sb, fp, '\\n'))\n+\t\tgoto fail;\n+\n+\tif (!skip_prefix(sb.buf, key, &str))\n+\t\tgoto fail;\n+\n+\tif (!skip_prefix(str, \"=\", &str))\n+\t\tgoto fail;\n+\n+\tstrbuf_remove(&sb, 0, str - sb.buf);\n+\n+\tstr = sq_dequote(sb.buf);\n+\tif (!str)\n+\t\tgoto fail;\n+\n+\treturn strbuf_detach(&sb, NULL);\n+\n+fail:\n+\tstrbuf_release(&sb);\n+\treturn NULL;\n+}\n+\n+/**\n+ * Reads and parses the state directory's \"author-script\" file, and sets\n+ * state->author_name, state->author_email and state->author_date accordingly.\n+ * Returns 0 on success, -1 if the file could not be parsed.\n+ *\n+ * The author script is of the format:\n+ *\n+ *\tGIT_AUTHOR_NAME='$author_name'\n+ *\tGIT_AUTHOR_EMAIL='$author_email'\n+ *\tGIT_AUTHOR_DATE='$author_date'\n+ *\n+ * where $author_name, $author_email and $author_date are quoted. We are strict\n+ * with our parsing, as the file was meant to be eval'd in the old git-am.sh\n+ * script, and thus if the file differs from what this function expects, it is\n+ * better to bail out than to do something that the user does not expect.\n+ */\n+static int read_author_script(struct am_state *state)\n+{\n+\tconst char *filename = am_path(state, \"author-script\");\n+\tFILE *fp;\n+\n+\tassert(!state->author_name);\n+\tassert(!state->author_email);\n+\tassert(!state->author_date);\n+\n+\tfp = fopen(filename, \"r\");\n+\tif (!fp) {\n+\t\tif (errno == ENOENT)\n+\t\t\treturn 0;\n+\t\tdie_errno(_(\"could not open '%s' for reading\"), filename);\n+\t}\n+\n+\tstate->author_name = read_shell_var(fp, \"GIT_AUTHOR_NAME\");\n+\tif (!state->author_name) {\n+\t\tfclose(fp);\n+\t\treturn -1;\n+\t}\n+\n+\tstate->author_email = read_shell_var(fp, \"GIT_AUTHOR_EMAIL\");\n+\tif (!state->author_email) {\n+\t\tfclose(fp);\n+\t\treturn -1;\n+\t}\n+\n+\tstate->author_date = read_shell_var(fp, \"GIT_AUTHOR_DATE\");\n+\tif (!state->author_date) {\n+\t\tfclose(fp);\n+\t\treturn -1;\n+\t}\n+\n+\tif (fgetc(fp) != EOF) {\n+\t\tfclose(fp);\n+\t\treturn -1;\n+\t}\n+\n+\tfclose(fp);\n+\treturn 0;\n+}\n+\n+/**\n+ * Saves state->author_name, state->author_email and state->author_date in the\n+ * state directory's \"author-script\" file.\n+ */\n+static void write_author_script(const struct am_state *state)\n+{\n+\tstruct strbuf sb = STRBUF_INIT;\n+\n+\tassert(state->author_name);\n+\tassert(state->author_email);\n+\tassert(state->author_date);\n+\n+\tstrbuf_addstr(&sb, \"GIT_AUTHOR_NAME=\");\n+\tsq_quote_buf(&sb, state->author_name);\n+\tstrbuf_addch(&sb, '\\n');\n+\n+\tstrbuf_addstr(&sb, \"GIT_AUTHOR_EMAIL=\");\n+\tsq_quote_buf(&sb, state->author_email);\n+\tstrbuf_addch(&sb, '\\n');\n+\n+\tstrbuf_addstr(&sb, \"GIT_AUTHOR_DATE=\");\n+\tsq_quote_buf(&sb, state->author_date);\n+\tstrbuf_addch(&sb, '\\n');\n+\n+\twrite_file(am_path(state, \"author-script\"), 1, \"%s\", sb.buf);\n+\n+\tstrbuf_release(&sb);\n+}\n+\n+/**\n+ * Reads the commit message from the state directory's \"final-commit\" file,\n+ * setting state->msg to its contents and state->msg_len to the length of its\n+ * contents in bytes.\n+ *\n+ * Returns 0 on success, -1 if the file does not exist.\n+ */\n+static int read_commit_msg(struct am_state *state)\n+{\n+\tstruct strbuf sb = STRBUF_INIT;\n+\n+\tassert(!state->msg);\n+\n+\tif (read_state_file(&sb, state, \"final-commit\", 0) < 0) {\n+\t\tstrbuf_release(&sb);\n+\t\treturn -1;\n+\t}\n+\n+\tstate->msg = strbuf_detach(&sb, &state->msg_len);\n+\treturn 0;\n+}\n+\n+/**\n+ * Saves state->msg in the state directory's \"final-commit\" file.\n+ */\n+static void write_commit_msg(const struct am_state *state)\n+{\n+\tint fd;\n+\tconst char *filename = am_path(state, \"final-commit\");\n+\n+\tassert(state->msg);\n+\n+\tfd = xopen(filename, O_WRONLY | O_CREAT, 0666);\n+\tif (write_in_full(fd, state->msg, state->msg_len) < 0)\n+\t\tdie_errno(_(\"could not write to %s\"), filename);\n+\tclose(fd);\n+}\n+\n+/**\n  * Loads state from disk.\n  */\n static void am_load(struct am_state *state)\n@@ -129,6 +326,11 @@ static void am_load(struct am_state *state)\n \t\tdie(\"BUG: state file 'last' does not exist\");\n \tstate->last = strtol(sb.buf, NULL, 10);\n \n+\tif (read_author_script(state) < 0)\n+\t\tdie(_(\"could not parse author script\"));\n+\n+\tread_commit_msg(state);\n+\n \tstrbuf_release(&sb);\n }\n \n@@ -321,19 +523,152 @@ static void am_setup(struct am_state *state, enum patch_format patch_format,\n  */\n static void am_next(struct am_state *state)\n {\n+\tif (state->author_name)\n+\t\tfree(state->author_name);\n+\tstate->author_name = NULL;\n+\n+\tif (state->author_email)\n+\t\tfree(state->author_email);\n+\tstate->author_email = NULL;\n+\n+\tif (state->author_date)\n+\t\tfree(state->author_date);\n+\tstate->author_date = NULL;\n+\n+\tif (state->msg)\n+\t\tfree(state->msg);\n+\tstate->msg = NULL;\n+\tstate->msg_len = 0;\n+\n+\tunlink(am_path(state, \"author-script\"));\n+\tunlink(am_path(state, \"final-commit\"));\n+\n \tstate->cur++;\n \twrite_file(am_path(state, \"next\"), 1, \"%d\", state->cur);\n }\n \n /**\n+ * Returns the filename of the current patch email.\n+ */\n+static const char *msgnum(const struct am_state *state)\n+{\n+\tstatic struct strbuf sb = STRBUF_INIT;\n+\n+\tstrbuf_reset(&sb);\n+\tstrbuf_addf(&sb, \"%0*d\", state->prec, state->cur);\n+\n+\treturn sb.buf;\n+}\n+\n+/**\n+ * Parses `mail` using git-mailinfo, extracting its patch and authorship info.\n+ * state->msg will be set to the patch message. state->author_name,\n+ * state->author_email and state->author_date will be set to the patch author's\n+ * name, email and date respectively. The patch body will be written to the\n+ * state directory's \"patch\" file.\n+ *\n+ * Returns 1 if the patch should be skipped, 0 otherwise.\n+ */\n+static int parse_mail(struct am_state *state, const char *mail)\n+{\n+\tFILE *fp;\n+\tstruct child_process cp = CHILD_PROCESS_INIT;\n+\tstruct strbuf sb = STRBUF_INIT;\n+\tstruct strbuf msg = STRBUF_INIT;\n+\tstruct strbuf author_name = STRBUF_INIT;\n+\tstruct strbuf author_date = STRBUF_INIT;\n+\tstruct strbuf author_email = STRBUF_INIT;\n+\tint ret = 0;\n+\n+\tcp.git_cmd = 1;\n+\tcp.in = xopen(mail, O_RDONLY, 0);\n+\tcp.out = xopen(am_path(state, \"info\"), O_WRONLY | O_CREAT, 0777);\n+\n+\targv_array_push(&cp.args, \"mailinfo\");\n+\targv_array_push(&cp.args, am_path(state, \"msg\"));\n+\targv_array_push(&cp.args, am_path(state, \"patch\"));\n+\n+\tif (run_command(&cp) < 0)\n+\t\tdie(\"could not parse patch\");\n+\n+\tclose(cp.in);\n+\tclose(cp.out);\n+\n+\t/* Extract message and author information */\n+\tfp = xfopen(am_path(state, \"info\"), \"r\");\n+\twhile (!strbuf_getline(&sb, fp, '\\n')) {\n+\t\tconst char *x;\n+\n+\t\tif (skip_prefix(sb.buf, \"Subject: \", &x)) {\n+\t\t\tif (msg.len)\n+\t\t\t\tstrbuf_addch(&msg, '\\n');\n+\t\t\tstrbuf_addstr(&msg, x);\n+\t\t} else if (skip_prefix(sb.buf, \"Author: \", &x))\n+\t\t\tstrbuf_addstr(&author_name, x);\n+\t\telse if (skip_prefix(sb.buf, \"Email: \", &x))\n+\t\t\tstrbuf_addstr(&author_email, x);\n+\t\telse if (skip_prefix(sb.buf, \"Date: \", &x))\n+\t\t\tstrbuf_addstr(&author_date, x);\n+\t}\n+\tfclose(fp);\n+\n+\t/* Skip pine's internal folder data */\n+\tif (!strcmp(author_name.buf, \"Mail System Internal Data\")) {\n+\t\tret = 1;\n+\t\tgoto finish;\n+\t}\n+\n+\tif (is_empty_file(am_path(state, \"patch\"))) {\n+\t\tprintf_ln(_(\"Patch is empty. Was it split wrong?\"));\n+\t\texit(128);\n+\t}\n+\n+\tstrbuf_addstr(&msg, \"\\n\\n\");\n+\tif (strbuf_read_file(&msg, am_path(state, \"msg\"), 0) < 0)\n+\t\tdie_errno(_(\"could not read '%s'\"), am_path(state, \"msg\"));\n+\tstripspace(&msg, 0);\n+\n+\tassert(!state->author_name);\n+\tstate->author_name = strbuf_detach(&author_name, NULL);\n+\n+\tassert(!state->author_email);\n+\tstate->author_email = strbuf_detach(&author_email, NULL);\n+\n+\tassert(!state->author_date);\n+\tstate->author_date = strbuf_detach(&author_date, NULL);\n+\n+\tassert(!state->msg);\n+\tstate->msg = strbuf_detach(&msg, &state->msg_len);\n+\n+finish:\n+\tstrbuf_release(&msg);\n+\tstrbuf_release(&author_date);\n+\tstrbuf_release(&author_email);\n+\tstrbuf_release(&author_name);\n+\tstrbuf_release(&sb);\n+\treturn ret;\n+}\n+\n+/**\n  * Applies all queued mail.\n  */\n static void am_run(struct am_state *state)\n {\n \twhile (state->cur <= state->last) {\n+\t\tconst char *mail = am_path(state, msgnum(state));\n+\n+\t\tif (!file_exists(mail))\n+\t\t\tgoto next;\n+\n+\t\tif (parse_mail(state, mail))\n+\t\t\tgoto next; /* mail should be skipped */\n+\n+\t\twrite_author_script(state);\n+\t\twrite_commit_msg(state);\n \n \t\t/* NEEDSWORK: Patch application not implemented yet */\n \n+next:\n \t\tam_next(state);\n \t}\n \n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265695","messageId":"1436278862-2638-9-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 08/44] builtin-am: apply patch with git-apply","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:26Z","receivedAt":"2015-07-07T14:20:26Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"Implement applying the patch to the index using git-apply.\n\nIf a file is unchanged but stat-dirty, git-apply may erroneously fail to\napply patches, thinking that they conflict with a dirty working tree.\n\nAs such, since 2a6f08a (am: refresh the index at start and --resolved,\n2011-08-15), git-am will refresh the index before applying patches.\nRe-implement this behavior.\n\nHelped-by: Junio C Hamano <gitster@pobox.com>\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n builtin/am.c | 73 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-\n 1 file changed, 72 insertions(+), 1 deletion(-)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex 4897857..9c7a6c8 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -10,6 +10,7 @@\n #include \"dir.h\"\n #include \"run-command.h\"\n #include \"quote.h\"\n+#include \"lockfile.h\"\n \n /**\n  * Returns 1 if the file is empty or does not exist, 0 otherwise.\n@@ -42,6 +43,14 @@ static int strbuf_getline_crlf(struct strbuf *sb, FILE *fp)\n \treturn 0;\n }\n \n+/**\n+ * Returns the length of the first line of msg.\n+ */\n+static int linelen(const char *msg)\n+{\n+\treturn strchrnul(msg, '\\n') - msg;\n+}\n+\n enum patch_format {\n \tPATCH_FORMAT_UNKNOWN = 0,\n \tPATCH_FORMAT_MBOX\n@@ -561,6 +570,20 @@ static const char *msgnum(const struct am_state *state)\n }\n \n /**\n+ * Refresh and write index.\n+ */\n+static void refresh_and_write_cache(void)\n+{\n+\tstatic struct lock_file lock_file;\n+\n+\thold_locked_index(&lock_file, 1);\n+\trefresh_cache(REFRESH_QUIET);\n+\tif (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))\n+\t\tdie(_(\"unable to write index file\"));\n+\trollback_lock_file(&lock_file);\n+}\n+\n+/**\n  * Parses `mail` using git-mailinfo, extracting its patch and authorship info.\n  * state->msg will be set to the patch message. state->author_name,\n  * state->author_email and state->author_date will be set to the patch author's\n@@ -650,10 +673,35 @@ finish:\n }\n \n /**\n+ * Applies current patch with git-apply. Returns 0 on success, -1 otherwise.\n+ */\n+static int run_apply(const struct am_state *state)\n+{\n+\tstruct child_process cp = CHILD_PROCESS_INIT;\n+\n+\tcp.git_cmd = 1;\n+\n+\targv_array_push(&cp.args, \"apply\");\n+\targv_array_push(&cp.args, \"--index\");\n+\targv_array_push(&cp.args, am_path(state, \"patch\"));\n+\n+\tif (run_command(&cp))\n+\t\treturn -1;\n+\n+\t/* Reload index as git-apply will have modified it. */\n+\tdiscard_cache();\n+\tread_cache();\n+\n+\treturn 0;\n+}\n+\n+/**\n  * Applies all queued mail.\n  */\n static void am_run(struct am_state *state)\n {\n+\trefresh_and_write_cache();\n+\n \twhile (state->cur <= state->last) {\n \t\tconst char *mail = am_path(state, msgnum(state));\n \n@@ -666,7 +714,27 @@ static void am_run(struct am_state *state)\n \t\twrite_author_script(state);\n \t\twrite_commit_msg(state);\n \n-\t\t/* NEEDSWORK: Patch application not implemented yet */\n+\t\tprintf_ln(_(\"Applying: %.*s\"), linelen(state->msg), state->msg);\n+\n+\t\tif (run_apply(state) < 0) {\n+\t\t\tint advice_amworkdir = 1;\n+\n+\t\t\tprintf_ln(_(\"Patch failed at %s %.*s\"), msgnum(state),\n+\t\t\t\tlinelen(state->msg), state->msg);\n+\n+\t\t\tgit_config_get_bool(\"advice.amworkdir\", &advice_amworkdir);\n+\n+\t\t\tif (advice_amworkdir)\n+\t\t\t\tprintf_ln(_(\"The copy of the patch that failed is found in: %s\"),\n+\t\t\t\t\t\tam_path(state, \"patch\"));\n+\n+\t\t\texit(128);\n+\t\t}\n+\n+\t\t/*\n+\t\t * NEEDSWORK: After the patch has been applied to the index\n+\t\t * with git-apply, we need to make commit as well.\n+\t\t */\n \n next:\n \t\tam_next(state);\n@@ -728,6 +796,9 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \n \targc = parse_options(argc, argv, prefix, options, usage, 0);\n \n+\tif (read_index_preload(&the_index, NULL) < 0)\n+\t\tdie(_(\"failed to read the index\"));\n+\n \tif (am_in_progress(&state))\n \t\tam_load(&state);\n \telse {\n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265694","messageId":"1436278862-2638-10-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 09/44] builtin-am: implement committing applied patch","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:27Z","receivedAt":"2015-07-07T14:20:27Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"Implement do_commit(), which commits the index which contains the\nresults of applying the patch, along with the extracted commit message\nand authorship information.\n\nSince 29b6754 (am: remove rebase-apply directory before gc, 2010-02-22),\ngit gc --auto is also invoked to pack the loose objects that are created\nfrom making the commits.\n\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n builtin/am.c | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++----\n 1 file changed, 51 insertions(+), 4 deletions(-)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex 9c7a6c8..bbb540c 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -11,6 +11,9 @@\n #include \"run-command.h\"\n #include \"quote.h\"\n #include \"lockfile.h\"\n+#include \"cache-tree.h\"\n+#include \"refs.h\"\n+#include \"commit.h\"\n \n /**\n  * Returns 1 if the file is empty or does not exist, 0 otherwise.\n@@ -696,10 +699,56 @@ static int run_apply(const struct am_state *state)\n }\n \n /**\n+ * Commits the current index with state->msg as the commit message and\n+ * state->author_name, state->author_email and state->author_date as the author\n+ * information.\n+ */\n+static void do_commit(const struct am_state *state)\n+{\n+\tunsigned char tree[GIT_SHA1_RAWSZ], parent[GIT_SHA1_RAWSZ],\n+\t\t      commit[GIT_SHA1_RAWSZ];\n+\tunsigned char *ptr;\n+\tstruct commit_list *parents = NULL;\n+\tconst char *reflog_msg, *author;\n+\tstruct strbuf sb = STRBUF_INIT;\n+\n+\tif (write_cache_as_tree(tree, 0, NULL))\n+\t\tdie(_(\"git write-tree failed to write a tree\"));\n+\n+\tif (!get_sha1_commit(\"HEAD\", parent)) {\n+\t\tptr = parent;\n+\t\tcommit_list_insert(lookup_commit(parent), &parents);\n+\t} else {\n+\t\tptr = NULL;\n+\t\tfprintf_ln(stderr, _(\"applying to an empty history\"));\n+\t}\n+\n+\tauthor = fmt_ident(state->author_name, state->author_email,\n+\t\t\tstate->author_date, IDENT_STRICT);\n+\n+\tif (commit_tree(state->msg, state->msg_len, tree, parents, commit,\n+\t\t\t\tauthor, NULL))\n+\t\tdie(_(\"failed to write commit object\"));\n+\n+\treflog_msg = getenv(\"GIT_REFLOG_ACTION\");\n+\tif (!reflog_msg)\n+\t\treflog_msg = \"am\";\n+\n+\tstrbuf_addf(&sb, \"%s: %.*s\", reflog_msg, linelen(state->msg),\n+\t\t\tstate->msg);\n+\n+\tupdate_ref(sb.buf, \"HEAD\", commit, ptr, 0, UPDATE_REFS_DIE_ON_ERR);\n+\n+\tstrbuf_release(&sb);\n+}\n+\n+/**\n  * Applies all queued mail.\n  */\n static void am_run(struct am_state *state)\n {\n+\tconst char *argv_gc_auto[] = {\"gc\", \"--auto\", NULL};\n+\n \trefresh_and_write_cache();\n \n \twhile (state->cur <= state->last) {\n@@ -731,16 +780,14 @@ static void am_run(struct am_state *state)\n \t\t\texit(128);\n \t\t}\n \n-\t\t/*\n-\t\t * NEEDSWORK: After the patch has been applied to the index\n-\t\t * with git-apply, we need to make commit as well.\n-\t\t */\n+\t\tdo_commit(state);\n \n next:\n \t\tam_next(state);\n \t}\n \n \tam_destroy(state);\n+\trun_command_v_opt(argv_gc_auto, RUN_GIT_CMD);\n }\n \n /**\n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265696","messageId":"1436278862-2638-11-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 10/44] builtin-am: refuse to apply patches if index is dirty","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:28Z","receivedAt":"2015-07-07T14:20:28Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"Since d1c5f2a (Add git-am, applymbox replacement., 2005-10-07), git-am\nwill refuse to apply patches if the index is dirty. Re-implement this\nbehavior in builtin/am.c.\n\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n builtin/am.c | 45 +++++++++++++++++++++++++++++++++++++++++++++\n 1 file changed, 45 insertions(+)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex bbb540c..f9a641a 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -14,6 +14,8 @@\n #include \"cache-tree.h\"\n #include \"refs.h\"\n #include \"commit.h\"\n+#include \"diff.h\"\n+#include \"diffcore.h\"\n \n /**\n  * Returns 1 if the file is empty or does not exist, 0 otherwise.\n@@ -587,6 +589,43 @@ static void refresh_and_write_cache(void)\n }\n \n /**\n+ * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn\n+ * branch, returns 1 if there are entries in the index, 0 otherwise. If an\n+ * strbuf is provided, the space-separated list of files that differ will be\n+ * appended to it.\n+ */\n+static int index_has_changes(struct strbuf *sb)\n+{\n+\tunsigned char head[GIT_SHA1_RAWSZ];\n+\tint i;\n+\n+\tif (!get_sha1_tree(\"HEAD\", head)) {\n+\t\tstruct diff_options opt;\n+\n+\t\tdiff_setup(&opt);\n+\t\tDIFF_OPT_SET(&opt, EXIT_WITH_STATUS);\n+\t\tif (!sb)\n+\t\t\tDIFF_OPT_SET(&opt, QUICK);\n+\t\tdo_diff_cache(head, &opt);\n+\t\tdiffcore_std(&opt);\n+\t\tfor (i = 0; sb && i < diff_queued_diff.nr; i++) {\n+\t\t\tif (i)\n+\t\t\t\tstrbuf_addch(sb, ' ');\n+\t\t\tstrbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);\n+\t\t}\n+\t\tdiff_flush(&opt);\n+\t\treturn DIFF_OPT_TST(&opt, HAS_CHANGES) != 0;\n+\t} else {\n+\t\tfor (i = 0; sb && i < active_nr; i++) {\n+\t\t\tif (i)\n+\t\t\t\tstrbuf_addch(sb, ' ');\n+\t\t\tstrbuf_addstr(sb, active_cache[i]->name);\n+\t\t}\n+\t\treturn !!active_nr;\n+\t}\n+}\n+\n+/**\n  * Parses `mail` using git-mailinfo, extracting its patch and authorship info.\n  * state->msg will be set to the patch message. state->author_name,\n  * state->author_email and state->author_date will be set to the patch author's\n@@ -748,9 +787,15 @@ static void do_commit(const struct am_state *state)\n static void am_run(struct am_state *state)\n {\n \tconst char *argv_gc_auto[] = {\"gc\", \"--auto\", NULL};\n+\tstruct strbuf sb = STRBUF_INIT;\n \n \trefresh_and_write_cache();\n \n+\tif (index_has_changes(&sb))\n+\t\tdie(_(\"Dirty index: cannot apply patches (dirty: %s)\"), sb.buf);\n+\n+\tstrbuf_release(&sb);\n+\n \twhile (state->cur <= state->last) {\n \t\tconst char *mail = am_path(state, msgnum(state));\n \n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265709","messageId":"1436278862-2638-12-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 11/44] builtin-am: implement --resolved/--continue","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:29Z","receivedAt":"2015-07-07T14:20:29Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"Since 0c15cc9 (git-am: --resolved., 2005-11-16), git-am supported\nresuming from a failed patch application. The user will manually apply\nthe patch, and the run git am --resolved which will then commit the\nresulting index. Re-implement this feature by introducing am_resolve().\n\nSince it makes no sense for the user to run am --resolved when there is\nno session in progress, we error out in this case.\n\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n builtin/am.c | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-\n 1 file changed, 62 insertions(+), 1 deletion(-)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex f9a641a..f21565b 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -836,6 +836,42 @@ next:\n }\n \n /**\n+ * Resume the current am session after patch application failure. The user did\n+ * all the hard work, and we do not have to do any patch application. Just\n+ * trust and commit what the user has in the index and working tree.\n+ */\n+static void am_resolve(struct am_state *state)\n+{\n+\tif (!state->msg)\n+\t\tdie(_(\"cannot resume: %s does not exist.\"),\n+\t\t\tam_path(state, \"final-commit\"));\n+\n+\tif (!state->author_name || !state->author_email || !state->author_date)\n+\t\tdie(_(\"cannot resume: %s does not exist.\"),\n+\t\t\tam_path(state, \"author-script\"));\n+\n+\tprintf_ln(_(\"Applying: %.*s\"), linelen(state->msg), state->msg);\n+\n+\tif (!index_has_changes(NULL)) {\n+\t\tprintf_ln(_(\"No changes - did you forget to use 'git add'?\\n\"\n+\t\t\t\"If there is nothing left to stage, chances are that something else\\n\"\n+\t\t\t\"already introduced the same changes; you might want to skip this patch.\"));\n+\t\texit(128);\n+\t}\n+\n+\tif (unmerged_cache()) {\n+\t\tprintf_ln(_(\"You still have unmerged paths in your index.\\n\"\n+\t\t\t\"Did you forget to use 'git add'?\"));\n+\t\texit(128);\n+\t}\n+\n+\tdo_commit(state);\n+\n+\tam_next(state);\n+\tam_run(state);\n+}\n+\n+/**\n  * parse_options() callback that validates and sets opt->value to the\n  * PATCH_FORMAT_* enum value corresponding to `arg`.\n  */\n@@ -850,13 +886,20 @@ static int parse_opt_patchformat(const struct option *opt, const char *arg, int\n \treturn 0;\n }\n \n+enum resume_mode {\n+\tRESUME_FALSE = 0,\n+\tRESUME_RESOLVED\n+};\n+\n int cmd_am(int argc, const char **argv, const char *prefix)\n {\n \tstruct am_state state;\n \tint patch_format = PATCH_FORMAT_UNKNOWN;\n+\tenum resume_mode resume = RESUME_FALSE;\n \n \tconst char * const usage[] = {\n \t\tN_(\"git am [options] [(<mbox>|<Maildir>)...]\"),\n+\t\tN_(\"git am [options] --continue\"),\n \t\tNULL\n \t};\n \n@@ -864,6 +907,12 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \t\tOPT_CALLBACK(0, \"patch-format\", &patch_format, N_(\"format\"),\n \t\t\tN_(\"format the patch(es) are in\"),\n \t\t\tparse_opt_patchformat),\n+\t\tOPT_CMDMODE(0, \"continue\", &resume,\n+\t\t\tN_(\"continue applying patches after resolving a conflict\"),\n+\t\t\tRESUME_RESOLVED),\n+\t\tOPT_CMDMODE('r', \"resolved\", &resume,\n+\t\t\tN_(\"synonyms for --continue\"),\n+\t\t\tRESUME_RESOLVED),\n \t\tOPT_END()\n \t};\n \n@@ -897,6 +946,9 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \t\tstruct argv_array paths = ARGV_ARRAY_INIT;\n \t\tint i;\n \n+\t\tif (resume)\n+\t\t\tdie(_(\"Resolve operation not in progress, we are not resuming.\"));\n+\n \t\tfor (i = 0; i < argc; i++) {\n \t\t\tif (is_absolute_path(argv[i]) || !prefix)\n \t\t\t\targv_array_push(&paths, argv[i]);\n@@ -909,7 +961,16 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \t\targv_array_clear(&paths);\n \t}\n \n-\tam_run(&state);\n+\tswitch (resume) {\n+\tcase RESUME_FALSE:\n+\t\tam_run(&state);\n+\t\tbreak;\n+\tcase RESUME_RESOLVED:\n+\t\tam_resolve(&state);\n+\t\tbreak;\n+\tdefault:\n+\t\tdie(\"BUG: invalid resume value\");\n+\t}\n \n \tam_state_release(&state);\n \n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265698","messageId":"1436278862-2638-13-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 12/44] builtin-am: implement --skip","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:30Z","receivedAt":"2015-07-07T14:20:30Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"Since d1c5f2a (Add git-am, applymbox replacement., 2005-10-07), git-am\nsupported resuming from a failed patch application by skipping the\ncurrent patch. Re-implement this feature by introducing am_skip().\n\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n builtin/am.c | 121 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-\n 1 file changed, 119 insertions(+), 2 deletions(-)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex f21565b..5087094 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -16,6 +16,8 @@\n #include \"commit.h\"\n #include \"diff.h\"\n #include \"diffcore.h\"\n+#include \"unpack-trees.h\"\n+#include \"branch.h\"\n \n /**\n  * Returns 1 if the file is empty or does not exist, 0 otherwise.\n@@ -872,6 +874,114 @@ static void am_resolve(struct am_state *state)\n }\n \n /**\n+ * Performs a checkout fast-forward from `head` to `remote`. If `reset` is\n+ * true, any unmerged entries will be discarded. Returns 0 on success, -1 on\n+ * failure.\n+ */\n+static int fast_forward_to(struct tree *head, struct tree *remote, int reset)\n+{\n+\tstruct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));\n+\tstruct unpack_trees_options opts;\n+\tstruct tree_desc t[2];\n+\n+\tif (parse_tree(head) || parse_tree(remote))\n+\t\treturn -1;\n+\n+\thold_locked_index(lock_file, 1);\n+\n+\trefresh_cache(REFRESH_QUIET);\n+\n+\tmemset(&opts, 0, sizeof(opts));\n+\topts.head_idx = 1;\n+\topts.src_index = &the_index;\n+\topts.dst_index = &the_index;\n+\topts.update = 1;\n+\topts.merge = 1;\n+\topts.reset = reset;\n+\topts.fn = twoway_merge;\n+\tinit_tree_desc(&t[0], head->buffer, head->size);\n+\tinit_tree_desc(&t[1], remote->buffer, remote->size);\n+\n+\tif (unpack_trees(2, t, &opts)) {\n+\t\trollback_lock_file(lock_file);\n+\t\treturn -1;\n+\t}\n+\n+\tif (write_locked_index(&the_index, lock_file, COMMIT_LOCK))\n+\t\tdie(_(\"unable to write new index file\"));\n+\n+\treturn 0;\n+}\n+\n+/**\n+ * Clean the index without touching entries that are not modified between\n+ * `head` and `remote`.\n+ */\n+static int clean_index(const unsigned char *head, const unsigned char *remote)\n+{\n+\tstruct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));\n+\tstruct tree *head_tree, *remote_tree, *index_tree;\n+\tunsigned char index[GIT_SHA1_RAWSZ];\n+\tstruct pathspec pathspec;\n+\n+\thead_tree = parse_tree_indirect(head);\n+\tif (!head_tree)\n+\t\treturn error(_(\"Could not parse object '%s'.\"), sha1_to_hex(head));\n+\n+\tremote_tree = parse_tree_indirect(remote);\n+\tif (!remote_tree)\n+\t\treturn error(_(\"Could not parse object '%s'.\"), sha1_to_hex(remote));\n+\n+\tread_cache_unmerged();\n+\n+\tif (fast_forward_to(head_tree, head_tree, 1))\n+\t\treturn -1;\n+\n+\tif (write_cache_as_tree(index, 0, NULL))\n+\t\treturn -1;\n+\n+\tindex_tree = parse_tree_indirect(index);\n+\tif (!index_tree)\n+\t\treturn error(_(\"Could not parse object '%s'.\"), sha1_to_hex(index));\n+\n+\tif (fast_forward_to(index_tree, remote_tree, 0))\n+\t\treturn -1;\n+\n+\tmemset(&pathspec, 0, sizeof(pathspec));\n+\n+\thold_locked_index(lock_file, 1);\n+\n+\tif (read_tree(remote_tree, 0, &pathspec)) {\n+\t\trollback_lock_file(lock_file);\n+\t\treturn -1;\n+\t}\n+\n+\tif (write_locked_index(&the_index, lock_file, COMMIT_LOCK))\n+\t\tdie(_(\"unable to write new index file\"));\n+\n+\tremove_branch_state();\n+\n+\treturn 0;\n+}\n+\n+/**\n+ * Resume the current am session by skipping the current patch.\n+ */\n+static void am_skip(struct am_state *state)\n+{\n+\tunsigned char head[GIT_SHA1_RAWSZ];\n+\n+\tif (get_sha1(\"HEAD\", head))\n+\t\thashcpy(head, EMPTY_TREE_SHA1_BIN);\n+\n+\tif (clean_index(head, head))\n+\t\tdie(_(\"failed to clean index\"));\n+\n+\tam_next(state);\n+\tam_run(state);\n+}\n+\n+/**\n  * parse_options() callback that validates and sets opt->value to the\n  * PATCH_FORMAT_* enum value corresponding to `arg`.\n  */\n@@ -888,7 +998,8 @@ static int parse_opt_patchformat(const struct option *opt, const char *arg, int\n \n enum resume_mode {\n \tRESUME_FALSE = 0,\n-\tRESUME_RESOLVED\n+\tRESUME_RESOLVED,\n+\tRESUME_SKIP\n };\n \n int cmd_am(int argc, const char **argv, const char *prefix)\n@@ -899,7 +1010,7 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \n \tconst char * const usage[] = {\n \t\tN_(\"git am [options] [(<mbox>|<Maildir>)...]\"),\n-\t\tN_(\"git am [options] --continue\"),\n+\t\tN_(\"git am [options] (--continue | --skip)\"),\n \t\tNULL\n \t};\n \n@@ -913,6 +1024,9 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \t\tOPT_CMDMODE('r', \"resolved\", &resume,\n \t\t\tN_(\"synonyms for --continue\"),\n \t\t\tRESUME_RESOLVED),\n+\t\tOPT_CMDMODE(0, \"skip\", &resume,\n+\t\t\tN_(\"skip the current patch\"),\n+\t\t\tRESUME_SKIP),\n \t\tOPT_END()\n \t};\n \n@@ -968,6 +1082,9 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \tcase RESUME_RESOLVED:\n \t\tam_resolve(&state);\n \t\tbreak;\n+\tcase RESUME_SKIP:\n+\t\tam_skip(&state);\n+\t\tbreak;\n \tdefault:\n \t\tdie(\"BUG: invalid resume value\");\n \t}\n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265701","messageId":"1436278862-2638-14-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 13/44] builtin-am: implement --abort","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:31Z","receivedAt":"2015-07-07T14:20:31Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"Since 3e5057a (git am --abort, 2008-07-16), git-am supported the --abort\noption that will rewind HEAD back to the original commit. Re-implement\nthis through am_abort().\n\nSince 7b3b7e3 (am --abort: keep unrelated commits since the last failure\nand warn, 2010-12-21), to prevent commits made since the last failure\nfrom being lost, git-am will not rewind HEAD back to the original\ncommit if HEAD moved since the last failure. Re-implement this through\nsafe_to_abort().\n\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n builtin/am.c | 102 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++--\n 1 file changed, 99 insertions(+), 3 deletions(-)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex 5087094..1db95f2 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -507,6 +507,8 @@ static int split_mail(struct am_state *state, enum patch_format patch_format,\n static void am_setup(struct am_state *state, enum patch_format patch_format,\n \t\t\tconst char **paths)\n {\n+\tunsigned char curr_head[GIT_SHA1_RAWSZ];\n+\n \tif (!patch_format)\n \t\tpatch_format = detect_patch_format(paths);\n \n@@ -523,6 +525,14 @@ static void am_setup(struct am_state *state, enum patch_format patch_format,\n \t\tdie(_(\"Failed to split patches.\"));\n \t}\n \n+\tif (!get_sha1(\"HEAD\", curr_head)) {\n+\t\twrite_file(am_path(state, \"abort-safety\"), 1, \"%s\", sha1_to_hex(curr_head));\n+\t\tupdate_ref(\"am\", \"ORIG_HEAD\", curr_head, NULL, 0, UPDATE_REFS_DIE_ON_ERR);\n+\t} else {\n+\t\twrite_file(am_path(state, \"abort-safety\"), 1, \"%s\", \"\");\n+\t\tdelete_ref(\"ORIG_HEAD\", NULL, 0);\n+\t}\n+\n \t/*\n \t * NOTE: Since the \"next\" and \"last\" files determine if an am_state\n \t * session is in progress, they should be written last.\n@@ -539,6 +549,8 @@ static void am_setup(struct am_state *state, enum patch_format patch_format,\n  */\n static void am_next(struct am_state *state)\n {\n+\tunsigned char head[GIT_SHA1_RAWSZ];\n+\n \tif (state->author_name)\n \t\tfree(state->author_name);\n \tstate->author_name = NULL;\n@@ -559,6 +571,11 @@ static void am_next(struct am_state *state)\n \tunlink(am_path(state, \"author-script\"));\n \tunlink(am_path(state, \"final-commit\"));\n \n+\tif (!get_sha1(\"HEAD\", head))\n+\t\twrite_file(am_path(state, \"abort-safety\"), 1, \"%s\", sha1_to_hex(head));\n+\telse\n+\t\twrite_file(am_path(state, \"abort-safety\"), 1, \"%s\", \"\");\n+\n \tstate->cur++;\n \twrite_file(am_path(state, \"next\"), 1, \"%d\", state->cur);\n }\n@@ -791,10 +808,14 @@ static void am_run(struct am_state *state)\n \tconst char *argv_gc_auto[] = {\"gc\", \"--auto\", NULL};\n \tstruct strbuf sb = STRBUF_INIT;\n \n+\tunlink(am_path(state, \"dirtyindex\"));\n+\n \trefresh_and_write_cache();\n \n-\tif (index_has_changes(&sb))\n+\tif (index_has_changes(&sb)) {\n+\t\twrite_file(am_path(state, \"dirtyindex\"), 1, \"t\");\n \t\tdie(_(\"Dirty index: cannot apply patches (dirty: %s)\"), sb.buf);\n+\t}\n \n \tstrbuf_release(&sb);\n \n@@ -982,6 +1003,74 @@ static void am_skip(struct am_state *state)\n }\n \n /**\n+ * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.\n+ *\n+ * It is not safe to reset HEAD when:\n+ * 1. git-am previously failed because the index was dirty.\n+ * 2. HEAD has moved since git-am previously failed.\n+ */\n+static int safe_to_abort(const struct am_state *state)\n+{\n+\tstruct strbuf sb = STRBUF_INIT;\n+\tunsigned char abort_safety[GIT_SHA1_RAWSZ], head[GIT_SHA1_RAWSZ];\n+\n+\tif (file_exists(am_path(state, \"dirtyindex\")))\n+\t\treturn 0;\n+\n+\tif (read_state_file(&sb, state, \"abort-safety\", 1) > 0) {\n+\t\tif (get_sha1_hex(sb.buf, abort_safety))\n+\t\t\tdie(_(\"could not parse %s\"), am_path(state, \"abort_safety\"));\n+\t} else\n+\t\thashclr(abort_safety);\n+\n+\tif (get_sha1(\"HEAD\", head))\n+\t\thashclr(head);\n+\n+\tif (!hashcmp(head, abort_safety))\n+\t\treturn 1;\n+\n+\terror(_(\"You seem to have moved HEAD since the last 'am' failure.\\n\"\n+\t\t\"Not rewinding to ORIG_HEAD\"));\n+\n+\treturn 0;\n+}\n+\n+/**\n+ * Aborts the current am session if it is safe to do so.\n+ */\n+static void am_abort(struct am_state *state)\n+{\n+\tunsigned char curr_head[GIT_SHA1_RAWSZ], orig_head[GIT_SHA1_RAWSZ];\n+\tint has_curr_head, has_orig_head;\n+\tconst char *curr_branch;\n+\n+\tif (!safe_to_abort(state)) {\n+\t\tam_destroy(state);\n+\t\treturn;\n+\t}\n+\n+\tcurr_branch = resolve_refdup(\"HEAD\", 0, curr_head, NULL);\n+\thas_curr_head = !is_null_sha1(curr_head);\n+\tif (!has_curr_head)\n+\t\thashcpy(curr_head, EMPTY_TREE_SHA1_BIN);\n+\n+\thas_orig_head = !get_sha1(\"ORIG_HEAD\", orig_head);\n+\tif (!has_orig_head)\n+\t\thashcpy(orig_head, EMPTY_TREE_SHA1_BIN);\n+\n+\tclean_index(curr_head, orig_head);\n+\n+\tif (has_orig_head)\n+\t\tupdate_ref(\"am --abort\", \"HEAD\", orig_head,\n+\t\t\t\thas_curr_head ? curr_head : NULL, 0,\n+\t\t\t\tUPDATE_REFS_DIE_ON_ERR);\n+\telse if (curr_branch)\n+\t\tdelete_ref(curr_branch, NULL, REF_NODEREF);\n+\n+\tam_destroy(state);\n+}\n+\n+/**\n  * parse_options() callback that validates and sets opt->value to the\n  * PATCH_FORMAT_* enum value corresponding to `arg`.\n  */\n@@ -999,7 +1088,8 @@ static int parse_opt_patchformat(const struct option *opt, const char *arg, int\n enum resume_mode {\n \tRESUME_FALSE = 0,\n \tRESUME_RESOLVED,\n-\tRESUME_SKIP\n+\tRESUME_SKIP,\n+\tRESUME_ABORT\n };\n \n int cmd_am(int argc, const char **argv, const char *prefix)\n@@ -1010,7 +1100,7 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \n \tconst char * const usage[] = {\n \t\tN_(\"git am [options] [(<mbox>|<Maildir>)...]\"),\n-\t\tN_(\"git am [options] (--continue | --skip)\"),\n+\t\tN_(\"git am [options] (--continue | --skip | --abort)\"),\n \t\tNULL\n \t};\n \n@@ -1027,6 +1117,9 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \t\tOPT_CMDMODE(0, \"skip\", &resume,\n \t\t\tN_(\"skip the current patch\"),\n \t\t\tRESUME_SKIP),\n+\t\tOPT_CMDMODE(0, \"abort\", &resume,\n+\t\t\tN_(\"restore the original branch and abort the patching operation.\"),\n+\t\t\tRESUME_ABORT),\n \t\tOPT_END()\n \t};\n \n@@ -1085,6 +1178,9 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \tcase RESUME_SKIP:\n \t\tam_skip(&state);\n \t\tbreak;\n+\tcase RESUME_ABORT:\n+\t\tam_abort(&state);\n+\t\tbreak;\n \tdefault:\n \t\tdie(\"BUG: invalid resume value\");\n \t}\n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265699","messageId":"1436278862-2638-15-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 14/44] builtin-am: reject patches when there's a session in progress","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:32Z","receivedAt":"2015-07-07T14:20:32Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"Since d1c5f2a (Add git-am, applymbox replacement., 2005-10-07), git-am\nwould error out if the user gave it mbox(s) on the command-line, but\nthere was a session in progress.\n\nSince c95b138 (Fix git-am safety checks, 2006-09-15), git-am would\ndetect if the user attempted to feed it a mbox via stdin, by checking if\nstdin is not a tty and there is no resume command given.\n\nRe-implement the above two safety checks.\n\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n builtin/am.c | 19 +++++++++++++++++--\n 1 file changed, 17 insertions(+), 2 deletions(-)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex 1db95f2..e066a97 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -1147,9 +1147,24 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \tif (read_index_preload(&the_index, NULL) < 0)\n \t\tdie(_(\"failed to read the index\"));\n \n-\tif (am_in_progress(&state))\n+\tif (am_in_progress(&state)) {\n+\t\t/*\n+\t\t * Catch user error to feed us patches when there is a session\n+\t\t * in progress:\n+\t\t *\n+\t\t * 1. mbox path(s) are provided on the command-line.\n+\t\t * 2. stdin is not a tty: the user is trying to feed us a patch\n+\t\t *    from standard input. This is somewhat unreliable -- stdin\n+\t\t *    could be /dev/null for example and the caller did not\n+\t\t *    intend to feed us a patch but wanted to continue\n+\t\t *    unattended.\n+\t\t */\n+\t\tif (argc || (resume == RESUME_FALSE && !isatty(0)))\n+\t\t\tdie(_(\"previous rebase directory %s still exists but mbox given.\"),\n+\t\t\t\tstate.dir);\n+\n \t\tam_load(&state);\n-\telse {\n+\t} else {\n \t\tstruct argv_array paths = ARGV_ARRAY_INIT;\n \t\tint i;\n \n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265700","messageId":"1436278862-2638-16-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 15/44] builtin-am: implement -q/--quiet","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:33Z","receivedAt":"2015-07-07T14:20:33Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"Since 0e987a1 (am, rebase: teach quiet option, 2009-06-16), git-am\nsupported the --quiet option, and when told to be quiet, would only\nspeak on failure. Re-implement this by introducing the say() function,\nwhich works like fprintf_ln(), but would only write to the stream when\nstate->quiet is false.\n\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n\nNotes:\n    v5\n    \n    * Removed GIT_QUIET environment variable, as it turns out\n      git-sh-setup.sh will reset it, which means the user's environment\n      cannot affect it.\n\n builtin/am.c | 30 +++++++++++++++++++++++++++---\n 1 file changed, 27 insertions(+), 3 deletions(-)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex e066a97..61c2ad3 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -80,6 +80,8 @@ struct am_state {\n \n \t/* number of digits in patch filename */\n \tint prec;\n+\n+\tint quiet;\n };\n \n /**\n@@ -128,6 +130,22 @@ static inline const char *am_path(const struct am_state *state, const char *path\n }\n \n /**\n+ * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline\n+ * at the end.\n+ */\n+static void say(const struct am_state *state, FILE *fp, const char *fmt, ...)\n+{\n+\tva_list ap;\n+\n+\tva_start(ap, fmt);\n+\tif (!state->quiet) {\n+\t\tvfprintf(fp, fmt, ap);\n+\t\tputc('\\n', fp);\n+\t}\n+\tva_end(ap);\n+}\n+\n+/**\n  * Returns 1 if there is an am session in progress, 0 otherwise.\n  */\n static int am_in_progress(const struct am_state *state)\n@@ -347,6 +365,9 @@ static void am_load(struct am_state *state)\n \n \tread_commit_msg(state);\n \n+\tread_state_file(&sb, state, \"quiet\", 1);\n+\tstate->quiet = !strcmp(sb.buf, \"t\");\n+\n \tstrbuf_release(&sb);\n }\n \n@@ -525,6 +546,8 @@ static void am_setup(struct am_state *state, enum patch_format patch_format,\n \t\tdie(_(\"Failed to split patches.\"));\n \t}\n \n+\twrite_file(am_path(state, \"quiet\"), 1, state->quiet ? \"t\" : \"f\");\n+\n \tif (!get_sha1(\"HEAD\", curr_head)) {\n \t\twrite_file(am_path(state, \"abort-safety\"), 1, \"%s\", sha1_to_hex(curr_head));\n \t\tupdate_ref(\"am\", \"ORIG_HEAD\", curr_head, NULL, 0, UPDATE_REFS_DIE_ON_ERR);\n@@ -778,7 +801,7 @@ static void do_commit(const struct am_state *state)\n \t\tcommit_list_insert(lookup_commit(parent), &parents);\n \t} else {\n \t\tptr = NULL;\n-\t\tfprintf_ln(stderr, _(\"applying to an empty history\"));\n+\t\tsay(state, stderr, _(\"applying to an empty history\"));\n \t}\n \n \tauthor = fmt_ident(state->author_name, state->author_email,\n@@ -831,7 +854,7 @@ static void am_run(struct am_state *state)\n \t\twrite_author_script(state);\n \t\twrite_commit_msg(state);\n \n-\t\tprintf_ln(_(\"Applying: %.*s\"), linelen(state->msg), state->msg);\n+\t\tsay(state, stdout, _(\"Applying: %.*s\"), linelen(state->msg), state->msg);\n \n \t\tif (run_apply(state) < 0) {\n \t\t\tint advice_amworkdir = 1;\n@@ -873,7 +896,7 @@ static void am_resolve(struct am_state *state)\n \t\tdie(_(\"cannot resume: %s does not exist.\"),\n \t\t\tam_path(state, \"author-script\"));\n \n-\tprintf_ln(_(\"Applying: %.*s\"), linelen(state->msg), state->msg);\n+\tsay(state, stdout, _(\"Applying: %.*s\"), linelen(state->msg), state->msg);\n \n \tif (!index_has_changes(NULL)) {\n \t\tprintf_ln(_(\"No changes - did you forget to use 'git add'?\\n\"\n@@ -1105,6 +1128,7 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \t};\n \n \tstruct option options[] = {\n+\t\tOPT__QUIET(&state.quiet, N_(\"be quiet\")),\n \t\tOPT_CALLBACK(0, \"patch-format\", &patch_format, N_(\"format\"),\n \t\t\tN_(\"format the patch(es) are in\"),\n \t\t\tparse_opt_patchformat),\n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265702","messageId":"1436278862-2638-17-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 16/44] builtin-am: exit with user friendly message on failure","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:34Z","receivedAt":"2015-07-07T14:20:34Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"Since ced9456 (Give the user a hint for how to continue in the case that\ngit-am fails because it requires user intervention, 2006-05-02), git-am\nprints additional information on how the user can re-invoke git-am to\nresume patch application after resolving the failure. Re-implement this\nthrough the die_user_resolve() function.\n\nSince cc12005 (Make git rebase interactive help match documentation.,\n2006-05-13), git-am supports the --resolvemsg option which is used by\ngit-rebase to override the message printed out when git-am fails.\nRe-implement this option.\n\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n builtin/am.c | 32 ++++++++++++++++++++++++++++----\n 1 file changed, 28 insertions(+), 4 deletions(-)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex 61c2ad3..7eb23b9 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -82,6 +82,9 @@ struct am_state {\n \tint prec;\n \n \tint quiet;\n+\n+\t/* override error message when patch failure occurs */\n+\tconst char *resolvemsg;\n };\n \n /**\n@@ -668,6 +671,25 @@ static int index_has_changes(struct strbuf *sb)\n }\n \n /**\n+ * Dies with a user-friendly message on how to proceed after resolving the\n+ * problem. This message can be overridden with state->resolvemsg.\n+ */\n+static void NORETURN die_user_resolve(const struct am_state *state)\n+{\n+\tif (state->resolvemsg) {\n+\t\tprintf_ln(\"%s\", state->resolvemsg);\n+\t} else {\n+\t\tconst char *cmdline = \"git am\";\n+\n+\t\tprintf_ln(_(\"When you have resolved this problem, run \\\"%s --continue\\\".\"), cmdline);\n+\t\tprintf_ln(_(\"If you prefer to skip this patch, run \\\"%s --skip\\\" instead.\"), cmdline);\n+\t\tprintf_ln(_(\"To restore the original branch and stop patching, run \\\"%s --abort\\\".\"), cmdline);\n+\t}\n+\n+\texit(128);\n+}\n+\n+/**\n  * Parses `mail` using git-mailinfo, extracting its patch and authorship info.\n  * state->msg will be set to the patch message. state->author_name,\n  * state->author_email and state->author_date will be set to the patch author's\n@@ -727,7 +749,7 @@ static int parse_mail(struct am_state *state, const char *mail)\n \n \tif (is_empty_file(am_path(state, \"patch\"))) {\n \t\tprintf_ln(_(\"Patch is empty. Was it split wrong?\"));\n-\t\texit(128);\n+\t\tdie_user_resolve(state);\n \t}\n \n \tstrbuf_addstr(&msg, \"\\n\\n\");\n@@ -868,7 +890,7 @@ static void am_run(struct am_state *state)\n \t\t\t\tprintf_ln(_(\"The copy of the patch that failed is found in: %s\"),\n \t\t\t\t\t\tam_path(state, \"patch\"));\n \n-\t\t\texit(128);\n+\t\t\tdie_user_resolve(state);\n \t\t}\n \n \t\tdo_commit(state);\n@@ -902,13 +924,13 @@ static void am_resolve(struct am_state *state)\n \t\tprintf_ln(_(\"No changes - did you forget to use 'git add'?\\n\"\n \t\t\t\"If there is nothing left to stage, chances are that something else\\n\"\n \t\t\t\"already introduced the same changes; you might want to skip this patch.\"));\n-\t\texit(128);\n+\t\tdie_user_resolve(state);\n \t}\n \n \tif (unmerged_cache()) {\n \t\tprintf_ln(_(\"You still have unmerged paths in your index.\\n\"\n \t\t\t\"Did you forget to use 'git add'?\"));\n-\t\texit(128);\n+\t\tdie_user_resolve(state);\n \t}\n \n \tdo_commit(state);\n@@ -1132,6 +1154,8 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \t\tOPT_CALLBACK(0, \"patch-format\", &patch_format, N_(\"format\"),\n \t\t\tN_(\"format the patch(es) are in\"),\n \t\t\tparse_opt_patchformat),\n+\t\tOPT_STRING(0, \"resolvemsg\", &state.resolvemsg, NULL,\n+\t\t\tN_(\"override error message when patch failure occurs\")),\n \t\tOPT_CMDMODE(0, \"continue\", &resume,\n \t\t\tN_(\"continue applying patches after resolving a conflict\"),\n \t\t\tRESUME_RESOLVED),\n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265723","messageId":"1436278862-2638-18-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 17/44] builtin-am: implement -s/--signoff","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:35Z","receivedAt":"2015-07-07T14:20:35Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"Since d1c5f2a (Add git-am, applymbox replacement., 2005-10-07), git-am\nsupported the --signoff option which will append a signoff at the end of\nthe commit messsage. Re-implement this feature in parse_mail() by\ncalling append_signoff() if the option is set.\n\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n builtin/am.c | 13 +++++++++++++\n 1 file changed, 13 insertions(+)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex 7eb23b9..511e4dd 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -18,6 +18,7 @@\n #include \"diffcore.h\"\n #include \"unpack-trees.h\"\n #include \"branch.h\"\n+#include \"sequencer.h\"\n \n /**\n  * Returns 1 if the file is empty or does not exist, 0 otherwise.\n@@ -83,6 +84,8 @@ struct am_state {\n \n \tint quiet;\n \n+\tint append_signoff;\n+\n \t/* override error message when patch failure occurs */\n \tconst char *resolvemsg;\n };\n@@ -371,6 +374,9 @@ static void am_load(struct am_state *state)\n \tread_state_file(&sb, state, \"quiet\", 1);\n \tstate->quiet = !strcmp(sb.buf, \"t\");\n \n+\tread_state_file(&sb, state, \"sign\", 1);\n+\tstate->append_signoff = !strcmp(sb.buf, \"t\");\n+\n \tstrbuf_release(&sb);\n }\n \n@@ -551,6 +557,8 @@ static void am_setup(struct am_state *state, enum patch_format patch_format,\n \n \twrite_file(am_path(state, \"quiet\"), 1, state->quiet ? \"t\" : \"f\");\n \n+\twrite_file(am_path(state, \"sign\"), 1, state->append_signoff ? \"t\" : \"f\");\n+\n \tif (!get_sha1(\"HEAD\", curr_head)) {\n \t\twrite_file(am_path(state, \"abort-safety\"), 1, \"%s\", sha1_to_hex(curr_head));\n \t\tupdate_ref(\"am\", \"ORIG_HEAD\", curr_head, NULL, 0, UPDATE_REFS_DIE_ON_ERR);\n@@ -757,6 +765,9 @@ static int parse_mail(struct am_state *state, const char *mail)\n \t\tdie_errno(_(\"could not read '%s'\"), am_path(state, \"msg\"));\n \tstripspace(&msg, 0);\n \n+\tif (state->append_signoff)\n+\t\tappend_signoff(&msg, 0, 0);\n+\n \tassert(!state->author_name);\n \tstate->author_name = strbuf_detach(&author_name, NULL);\n \n@@ -1151,6 +1162,8 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \n \tstruct option options[] = {\n \t\tOPT__QUIET(&state.quiet, N_(\"be quiet\")),\n+\t\tOPT_BOOL('s', \"signoff\", &state.append_signoff,\n+\t\t\tN_(\"add a Signed-off-by line to the commit message\")),\n \t\tOPT_CALLBACK(0, \"patch-format\", &patch_format, N_(\"format\"),\n \t\t\tN_(\"format the patch(es) are in\"),\n \t\t\tparse_opt_patchformat),\n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265725","messageId":"1436278862-2638-19-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 18/44] cache-tree: introduce write_index_as_tree()","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:36Z","receivedAt":"2015-07-07T14:20:36Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"A caller may wish to write a temporary index as a tree. However,\nwrite_cache_as_tree() assumes that the index was read from, and will\nwrite to, the default index file path. Introduce write_index_as_tree()\nwhich removes this limitation by allowing the caller to specify its own\nindex_state and index file path.\n\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n cache-tree.c | 29 +++++++++++++++++------------\n cache-tree.h |  1 +\n 2 files changed, 18 insertions(+), 12 deletions(-)\n\ndiff --git a/cache-tree.c b/cache-tree.c\nindex 32772b9..feace8b 100644\n--- a/cache-tree.c\n+++ b/cache-tree.c\n@@ -592,7 +592,7 @@ static struct cache_tree *cache_tree_find(struct cache_tree *it, const char *pat\n \treturn it;\n }\n \n-int write_cache_as_tree(unsigned char *sha1, int flags, const char *prefix)\n+int write_index_as_tree(unsigned char *sha1, struct index_state *index_state, const char *index_path, int flags, const char *prefix)\n {\n \tint entries, was_valid, newfd;\n \tstruct lock_file *lock_file;\n@@ -603,23 +603,23 @@ int write_cache_as_tree(unsigned char *sha1, int flags, const char *prefix)\n \t */\n \tlock_file = xcalloc(1, sizeof(struct lock_file));\n \n-\tnewfd = hold_locked_index(lock_file, 1);\n+\tnewfd = hold_lock_file_for_update(lock_file, index_path, LOCK_DIE_ON_ERROR);\n \n-\tentries = read_cache();\n+\tentries = read_index_from(index_state, index_path);\n \tif (entries < 0)\n \t\treturn WRITE_TREE_UNREADABLE_INDEX;\n \tif (flags & WRITE_TREE_IGNORE_CACHE_TREE)\n-\t\tcache_tree_free(&(active_cache_tree));\n+\t\tcache_tree_free(&index_state->cache_tree);\n \n-\tif (!active_cache_tree)\n-\t\tactive_cache_tree = cache_tree();\n+\tif (!index_state->cache_tree)\n+\t\tindex_state->cache_tree = cache_tree();\n \n-\twas_valid = cache_tree_fully_valid(active_cache_tree);\n+\twas_valid = cache_tree_fully_valid(index_state->cache_tree);\n \tif (!was_valid) {\n-\t\tif (cache_tree_update(&the_index, flags) < 0)\n+\t\tif (cache_tree_update(index_state, flags) < 0)\n \t\t\treturn WRITE_TREE_UNMERGED_INDEX;\n \t\tif (0 <= newfd) {\n-\t\t\tif (!write_locked_index(&the_index, lock_file, COMMIT_LOCK))\n+\t\t\tif (!write_locked_index(index_state, lock_file, COMMIT_LOCK))\n \t\t\t\tnewfd = -1;\n \t\t}\n \t\t/* Not being able to write is fine -- we are only interested\n@@ -631,14 +631,14 @@ int write_cache_as_tree(unsigned char *sha1, int flags, const char *prefix)\n \t}\n \n \tif (prefix) {\n-\t\tstruct cache_tree *subtree =\n-\t\t\tcache_tree_find(active_cache_tree, prefix);\n+\t\tstruct cache_tree *subtree;\n+\t\tsubtree = cache_tree_find(index_state->cache_tree, prefix);\n \t\tif (!subtree)\n \t\t\treturn WRITE_TREE_PREFIX_ERROR;\n \t\thashcpy(sha1, subtree->sha1);\n \t}\n \telse\n-\t\thashcpy(sha1, active_cache_tree->sha1);\n+\t\thashcpy(sha1, index_state->cache_tree->sha1);\n \n \tif (0 <= newfd)\n \t\trollback_lock_file(lock_file);\n@@ -646,6 +646,11 @@ int write_cache_as_tree(unsigned char *sha1, int flags, const char *prefix)\n \treturn 0;\n }\n \n+int write_cache_as_tree(unsigned char *sha1, int flags, const char *prefix)\n+{\n+\treturn write_index_as_tree(sha1, &the_index, get_index_file(), flags, prefix);\n+}\n+\n static void prime_cache_tree_rec(struct cache_tree *it, struct tree *tree)\n {\n \tstruct tree_desc desc;\ndiff --git a/cache-tree.h b/cache-tree.h\nindex aa7b3e4..41c5746 100644\n--- a/cache-tree.h\n+++ b/cache-tree.h\n@@ -46,6 +46,7 @@ int update_main_cache_tree(int);\n #define WRITE_TREE_UNMERGED_INDEX (-2)\n #define WRITE_TREE_PREFIX_ERROR (-3)\n \n+int write_index_as_tree(unsigned char *sha1, struct index_state *index_state, const char *index_path, int flags, const char *prefix);\n int write_cache_as_tree(unsigned char *sha1, int flags, const char *prefix);\n void prime_cache_tree(struct index_state *, struct tree *);\n \n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265729","messageId":"1436278862-2638-20-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 19/44] builtin-am: implement --3way, am.threeWay","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:37Z","receivedAt":"2015-07-07T14:20:37Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"Since d1c5f2a (Add git-am, applymbox replacement., 2005-10-07),\ngit-am.sh supported the --3way option, and if set, would attempt to do a\n3-way merge if the initial patch application fails.\n\nSince d96a275 (git-am: add am.threeWay config variable, 2015-06-04), the\nsetting am.threeWay configures if the --3way option is set by default.\n\nSince 5d86861 (am -3: list the paths that needed 3-way fallback,\n2012-03-28), in a 3-way merge git-am.sh would list the paths that needed\n3-way fallback, so that the user can review them more carefully to spot\nmismerges.\n\nRe-implement the above in builtin/am.c.\n\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n\nNotes:\n    v5\n    \n    * s/a index/an index/\n\n builtin/am.c | 157 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++--\n 1 file changed, 153 insertions(+), 4 deletions(-)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex 511e4dd..af22c35 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -19,6 +19,8 @@\n #include \"unpack-trees.h\"\n #include \"branch.h\"\n #include \"sequencer.h\"\n+#include \"revision.h\"\n+#include \"merge-recursive.h\"\n \n /**\n  * Returns 1 if the file is empty or does not exist, 0 otherwise.\n@@ -82,6 +84,8 @@ struct am_state {\n \t/* number of digits in patch filename */\n \tint prec;\n \n+\tint threeway;\n+\n \tint quiet;\n \n \tint append_signoff;\n@@ -102,6 +106,8 @@ static void am_state_init(struct am_state *state, const char *dir)\n \tstate->dir = xstrdup(dir);\n \n \tstate->prec = 4;\n+\n+\tgit_config_get_bool(\"am.threeway\", &state->threeway);\n }\n \n /**\n@@ -371,6 +377,9 @@ static void am_load(struct am_state *state)\n \n \tread_commit_msg(state);\n \n+\tread_state_file(&sb, state, \"threeway\", 1);\n+\tstate->threeway = !strcmp(sb.buf, \"t\");\n+\n \tread_state_file(&sb, state, \"quiet\", 1);\n \tstate->quiet = !strcmp(sb.buf, \"t\");\n \n@@ -555,6 +564,8 @@ static void am_setup(struct am_state *state, enum patch_format patch_format,\n \t\tdie(_(\"Failed to split patches.\"));\n \t}\n \n+\twrite_file(am_path(state, \"threeway\"), 1, state->threeway ? \"t\" : \"f\");\n+\n \twrite_file(am_path(state, \"quiet\"), 1, state->quiet ? \"t\" : \"f\");\n \n \twrite_file(am_path(state, \"sign\"), 1, state->append_signoff ? \"t\" : \"f\");\n@@ -790,16 +801,34 @@ finish:\n }\n \n /**\n- * Applies current patch with git-apply. Returns 0 on success, -1 otherwise.\n+ * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If\n+ * `index_file` is not NULL, the patch will be applied to that index.\n  */\n-static int run_apply(const struct am_state *state)\n+static int run_apply(const struct am_state *state, const char *index_file)\n {\n \tstruct child_process cp = CHILD_PROCESS_INIT;\n \n \tcp.git_cmd = 1;\n \n+\tif (index_file)\n+\t\targv_array_pushf(&cp.env_array, \"GIT_INDEX_FILE=%s\", index_file);\n+\n+\t/*\n+\t * If we are allowed to fall back on 3-way merge, don't give false\n+\t * errors during the initial attempt.\n+\t */\n+\tif (state->threeway && !index_file) {\n+\t\tcp.no_stdout = 1;\n+\t\tcp.no_stderr = 1;\n+\t}\n+\n \targv_array_push(&cp.args, \"apply\");\n-\targv_array_push(&cp.args, \"--index\");\n+\n+\tif (index_file)\n+\t\targv_array_push(&cp.args, \"--cached\");\n+\telse\n+\t\targv_array_push(&cp.args, \"--index\");\n+\n \targv_array_push(&cp.args, am_path(state, \"patch\"));\n \n \tif (run_command(&cp))\n@@ -807,8 +836,106 @@ static int run_apply(const struct am_state *state)\n \n \t/* Reload index as git-apply will have modified it. */\n \tdiscard_cache();\n+\tread_cache_from(index_file ? index_file : get_index_file());\n+\n+\treturn 0;\n+}\n+\n+/**\n+ * Builds an index that contains just the blobs needed for a 3way merge.\n+ */\n+static int build_fake_ancestor(const struct am_state *state, const char *index_file)\n+{\n+\tstruct child_process cp = CHILD_PROCESS_INIT;\n+\n+\tcp.git_cmd = 1;\n+\targv_array_push(&cp.args, \"apply\");\n+\targv_array_pushf(&cp.args, \"--build-fake-ancestor=%s\", index_file);\n+\targv_array_push(&cp.args, am_path(state, \"patch\"));\n+\n+\tif (run_command(&cp))\n+\t\treturn -1;\n+\n+\treturn 0;\n+}\n+\n+/**\n+ * Attempt a threeway merge, using index_path as the temporary index.\n+ */\n+static int fall_back_threeway(const struct am_state *state, const char *index_path)\n+{\n+\tunsigned char orig_tree[GIT_SHA1_RAWSZ], his_tree[GIT_SHA1_RAWSZ],\n+\t\t      our_tree[GIT_SHA1_RAWSZ];\n+\tconst unsigned char *bases[1] = {orig_tree};\n+\tstruct merge_options o;\n+\tstruct commit *result;\n+\tchar *his_tree_name;\n+\n+\tif (get_sha1(\"HEAD\", our_tree) < 0)\n+\t\thashcpy(our_tree, EMPTY_TREE_SHA1_BIN);\n+\n+\tif (build_fake_ancestor(state, index_path))\n+\t\treturn error(\"could not build fake ancestor\");\n+\n+\tdiscard_cache();\n+\tread_cache_from(index_path);\n+\n+\tif (write_index_as_tree(orig_tree, &the_index, index_path, 0, NULL))\n+\t\treturn error(_(\"Repository lacks necessary blobs to fall back on 3-way merge.\"));\n+\n+\tsay(state, stdout, _(\"Using index info to reconstruct a base tree...\"));\n+\n+\tif (!state->quiet) {\n+\t\t/*\n+\t\t * List paths that needed 3-way fallback, so that the user can\n+\t\t * review them with extra care to spot mismerges.\n+\t\t */\n+\t\tstruct rev_info rev_info;\n+\t\tconst char *diff_filter_str = \"--diff-filter=AM\";\n+\n+\t\tinit_revisions(&rev_info, NULL);\n+\t\trev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;\n+\t\tdiff_opt_parse(&rev_info.diffopt, &diff_filter_str, 1);\n+\t\tadd_pending_sha1(&rev_info, \"HEAD\", our_tree, 0);\n+\t\tdiff_setup_done(&rev_info.diffopt);\n+\t\trun_diff_index(&rev_info, 1);\n+\t}\n+\n+\tif (run_apply(state, index_path))\n+\t\treturn error(_(\"Did you hand edit your patch?\\n\"\n+\t\t\t\t\"It does not apply to blobs recorded in its index.\"));\n+\n+\tif (write_index_as_tree(his_tree, &the_index, index_path, 0, NULL))\n+\t\treturn error(\"could not write tree\");\n+\n+\tsay(state, stdout, _(\"Falling back to patching base and 3-way merge...\"));\n+\n+\tdiscard_cache();\n \tread_cache();\n \n+\t/*\n+\t * This is not so wrong. Depending on which base we picked, orig_tree\n+\t * may be wildly different from ours, but his_tree has the same set of\n+\t * wildly different changes in parts the patch did not touch, so\n+\t * recursive ends up canceling them, saying that we reverted all those\n+\t * changes.\n+\t */\n+\n+\tinit_merge_options(&o);\n+\n+\to.branch1 = \"HEAD\";\n+\this_tree_name = xstrfmt(\"%.*s\", linelen(state->msg), state->msg);\n+\to.branch2 = his_tree_name;\n+\n+\tif (state->quiet)\n+\t\to.verbosity = 0;\n+\n+\tif (merge_recursive_generic(&o, our_tree, his_tree, 1, bases, &result)) {\n+\t\tfree(his_tree_name);\n+\t\treturn error(_(\"Failed to merge in the changes.\"));\n+\t}\n+\n+\tfree(his_tree_name);\n \treturn 0;\n }\n \n@@ -877,6 +1004,7 @@ static void am_run(struct am_state *state)\n \n \twhile (state->cur <= state->last) {\n \t\tconst char *mail = am_path(state, msgnum(state));\n+\t\tint apply_status;\n \n \t\tif (!file_exists(mail))\n \t\t\tgoto next;\n@@ -889,7 +1017,26 @@ static void am_run(struct am_state *state)\n \n \t\tsay(state, stdout, _(\"Applying: %.*s\"), linelen(state->msg), state->msg);\n \n-\t\tif (run_apply(state) < 0) {\n+\t\tapply_status = run_apply(state, NULL);\n+\n+\t\tif (apply_status && state->threeway) {\n+\t\t\tstruct strbuf sb = STRBUF_INIT;\n+\n+\t\t\tstrbuf_addstr(&sb, am_path(state, \"patch-merge-index\"));\n+\t\t\tapply_status = fall_back_threeway(state, sb.buf);\n+\t\t\tstrbuf_release(&sb);\n+\n+\t\t\t/*\n+\t\t\t * Applying the patch to an earlier tree and merging\n+\t\t\t * the result may have produced the same tree as ours.\n+\t\t\t */\n+\t\t\tif (!apply_status && !index_has_changes(NULL)) {\n+\t\t\t\tsay(state, stdout, _(\"No changes -- Patch already applied.\"));\n+\t\t\t\tgoto next;\n+\t\t\t}\n+\t\t}\n+\n+\t\tif (apply_status) {\n \t\t\tint advice_amworkdir = 1;\n \n \t\t\tprintf_ln(_(\"Patch failed at %s %.*s\"), msgnum(state),\n@@ -1161,6 +1308,8 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \t};\n \n \tstruct option options[] = {\n+\t\tOPT_BOOL('3', \"3way\", &state.threeway,\n+\t\t\tN_(\"allow fall back on 3way merging if needed\")),\n \t\tOPT__QUIET(&state.quiet, N_(\"be quiet\")),\n \t\tOPT_BOOL('s', \"signoff\", &state.append_signoff,\n \t\t\tN_(\"add a Signed-off-by line to the commit message\")),\n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265719","messageId":"1436278862-2638-21-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 20/44] builtin-am: implement --rebasing mode","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:38Z","receivedAt":"2015-07-07T14:20:38Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"Since 3041c32 (am: --rebasing, 2008-03-04), git-am.sh supported the\n--rebasing option, which is used internally by git-rebase to tell git-am\nthat it is being used for its purpose. It would create the empty file\n$state_dir/rebasing to help \"completion\" scripts tell if the ongoing\noperation is am or rebase.\n\nAs of 0fbb95d (am: don't call mailinfo if $rebasing, 2012-06-26),\n--rebasing also implies --3way as well.\n\nSince a1549e1 (am: return control to caller, for housekeeping,\n2013-05-12), git-am.sh would only clean up the state directory when it\nis not --rebasing, instead deferring cleanup to git-rebase.sh.\n\nRe-implement the above in builtin/am.c.\n\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n builtin/am.c | 31 +++++++++++++++++++++++++++----\n 1 file changed, 27 insertions(+), 4 deletions(-)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex af22c35..b68dcc5 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -92,6 +92,8 @@ struct am_state {\n \n \t/* override error message when patch failure occurs */\n \tconst char *resolvemsg;\n+\n+\tint rebasing;\n };\n \n /**\n@@ -386,6 +388,8 @@ static void am_load(struct am_state *state)\n \tread_state_file(&sb, state, \"sign\", 1);\n \tstate->append_signoff = !strcmp(sb.buf, \"t\");\n \n+\tstate->rebasing = !!file_exists(am_path(state, \"rebasing\"));\n+\n \tstrbuf_release(&sb);\n }\n \n@@ -564,18 +568,29 @@ static void am_setup(struct am_state *state, enum patch_format patch_format,\n \t\tdie(_(\"Failed to split patches.\"));\n \t}\n \n+\tif (state->rebasing)\n+\t\tstate->threeway = 1;\n+\n \twrite_file(am_path(state, \"threeway\"), 1, state->threeway ? \"t\" : \"f\");\n \n \twrite_file(am_path(state, \"quiet\"), 1, state->quiet ? \"t\" : \"f\");\n \n \twrite_file(am_path(state, \"sign\"), 1, state->append_signoff ? \"t\" : \"f\");\n \n+\tif (state->rebasing)\n+\t\twrite_file(am_path(state, \"rebasing\"), 1, \"%s\", \"\");\n+\telse\n+\t\twrite_file(am_path(state, \"applying\"), 1, \"%s\", \"\");\n+\n \tif (!get_sha1(\"HEAD\", curr_head)) {\n \t\twrite_file(am_path(state, \"abort-safety\"), 1, \"%s\", sha1_to_hex(curr_head));\n-\t\tupdate_ref(\"am\", \"ORIG_HEAD\", curr_head, NULL, 0, UPDATE_REFS_DIE_ON_ERR);\n+\t\tif (!state->rebasing)\n+\t\t\tupdate_ref(\"am\", \"ORIG_HEAD\", curr_head, NULL, 0,\n+\t\t\t\t\tUPDATE_REFS_DIE_ON_ERR);\n \t} else {\n \t\twrite_file(am_path(state, \"abort-safety\"), 1, \"%s\", \"\");\n-\t\tdelete_ref(\"ORIG_HEAD\", NULL, 0);\n+\t\tif (!state->rebasing)\n+\t\t\tdelete_ref(\"ORIG_HEAD\", NULL, 0);\n \t}\n \n \t/*\n@@ -1057,8 +1072,14 @@ next:\n \t\tam_next(state);\n \t}\n \n-\tam_destroy(state);\n-\trun_command_v_opt(argv_gc_auto, RUN_GIT_CMD);\n+\t/*\n+\t * In rebasing mode, it's up to the caller to take care of\n+\t * housekeeping.\n+\t */\n+\tif (!state->rebasing) {\n+\t\tam_destroy(state);\n+\t\trun_command_v_opt(argv_gc_auto, RUN_GIT_CMD);\n+\t}\n }\n \n /**\n@@ -1330,6 +1351,8 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \t\tOPT_CMDMODE(0, \"abort\", &resume,\n \t\t\tN_(\"restore the original branch and abort the patching operation.\"),\n \t\t\tRESUME_ABORT),\n+\t\tOPT_HIDDEN_BOOL(0, \"rebasing\", &state.rebasing,\n+\t\t\tN_(\"(internal use for git-rebase)\")),\n \t\tOPT_END()\n \t};\n \n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265707","messageId":"1436278862-2638-22-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 21/44] builtin-am: bypass git-mailinfo when --rebasing","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:39Z","receivedAt":"2015-07-07T14:20:39Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"Since 5e835ca (rebase: do not munge commit log message, 2008-04-16),\ngit am --rebasing no longer gets the commit log message from the patch,\nbut reads it directly from the commit identified by the \"From \" header\nline.\n\nSince 43c2325 (am: use get_author_ident_from_commit instead of mailinfo\nwhen rebasing, 2010-06-16), git am --rebasing also gets the author name,\nemail and date directly from the commit.\n\nSince 0fbb95d (am: don't call mailinfo if $rebasing, 2012-06-26), git am\n--rebasing does not use git-mailinfo to get the patch body, but rather\ngenerates it directly from the commit itself.\n\nThe above 3 commits introduced a separate parse_mail() code path in\ngit-am.sh's --rebasing mode that bypasses git-mailinfo. Re-implement\nthis code path in builtin/am.c as parse_mail_rebase().\n\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n builtin/am.c | 134 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-\n 1 file changed, 132 insertions(+), 2 deletions(-)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex b68dcc5..06ded5d 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -21,6 +21,8 @@\n #include \"sequencer.h\"\n #include \"revision.h\"\n #include \"merge-recursive.h\"\n+#include \"revision.h\"\n+#include \"log-tree.h\"\n \n /**\n  * Returns 1 if the file is empty or does not exist, 0 otherwise.\n@@ -816,6 +818,129 @@ finish:\n }\n \n /**\n+ * Sets commit_id to the commit hash where the mail was generated from.\n+ * Returns 0 on success, -1 on failure.\n+ */\n+static int get_mail_commit_sha1(unsigned char *commit_id, const char *mail)\n+{\n+\tstruct strbuf sb = STRBUF_INIT;\n+\tFILE *fp = xfopen(mail, \"r\");\n+\tconst char *x;\n+\n+\tif (strbuf_getline(&sb, fp, '\\n'))\n+\t\treturn -1;\n+\n+\tif (!skip_prefix(sb.buf, \"From \", &x))\n+\t\treturn -1;\n+\n+\tif (get_sha1_hex(x, commit_id) < 0)\n+\t\treturn -1;\n+\n+\tstrbuf_release(&sb);\n+\tfclose(fp);\n+\treturn 0;\n+}\n+\n+/**\n+ * Sets state->msg, state->author_name, state->author_email, state->author_date\n+ * to the commit's respective info.\n+ */\n+static void get_commit_info(struct am_state *state, struct commit *commit)\n+{\n+\tconst char *buffer, *ident_line, *author_date, *msg;\n+\tsize_t ident_len;\n+\tstruct ident_split ident_split;\n+\tstruct strbuf sb = STRBUF_INIT;\n+\n+\tbuffer = logmsg_reencode(commit, NULL, get_commit_output_encoding());\n+\n+\tident_line = find_commit_header(buffer, \"author\", &ident_len);\n+\n+\tif (split_ident_line(&ident_split, ident_line, ident_len) < 0) {\n+\t\tstrbuf_add(&sb, ident_line, ident_len);\n+\t\tdie(_(\"invalid ident line: %s\"), sb.buf);\n+\t}\n+\n+\tassert(!state->author_name);\n+\tif (ident_split.name_begin) {\n+\t\tstrbuf_add(&sb, ident_split.name_begin,\n+\t\t\tident_split.name_end - ident_split.name_begin);\n+\t\tstate->author_name = strbuf_detach(&sb, NULL);\n+\t} else\n+\t\tstate->author_name = xstrdup(\"\");\n+\n+\tassert(!state->author_email);\n+\tif (ident_split.mail_begin) {\n+\t\tstrbuf_add(&sb, ident_split.mail_begin,\n+\t\t\tident_split.mail_end - ident_split.mail_begin);\n+\t\tstate->author_email = strbuf_detach(&sb, NULL);\n+\t} else\n+\t\tstate->author_email = xstrdup(\"\");\n+\n+\tauthor_date = show_ident_date(&ident_split, DATE_NORMAL);\n+\tstrbuf_addstr(&sb, author_date);\n+\tassert(!state->author_date);\n+\tstate->author_date = strbuf_detach(&sb, NULL);\n+\n+\tassert(!state->msg);\n+\tmsg = strstr(buffer, \"\\n\\n\");\n+\tif (!msg)\n+\t\tdie(_(\"unable to parse commit %s\"), sha1_to_hex(commit->object.sha1));\n+\tstate->msg = xstrdup(msg + 2);\n+\tstate->msg_len = strlen(state->msg);\n+}\n+\n+/**\n+ * Writes `commit` as a patch to the state directory's \"patch\" file.\n+ */\n+static void write_commit_patch(const struct am_state *state, struct commit *commit)\n+{\n+\tstruct rev_info rev_info;\n+\tFILE *fp;\n+\n+\tfp = xfopen(am_path(state, \"patch\"), \"w\");\n+\tinit_revisions(&rev_info, NULL);\n+\trev_info.diff = 1;\n+\trev_info.abbrev = 0;\n+\trev_info.disable_stdin = 1;\n+\trev_info.show_root_diff = 1;\n+\trev_info.diffopt.output_format = DIFF_FORMAT_PATCH;\n+\trev_info.no_commit_id = 1;\n+\tDIFF_OPT_SET(&rev_info.diffopt, BINARY);\n+\tDIFF_OPT_SET(&rev_info.diffopt, FULL_INDEX);\n+\trev_info.diffopt.use_color = 0;\n+\trev_info.diffopt.file = fp;\n+\trev_info.diffopt.close_file = 1;\n+\tadd_pending_object(&rev_info, &commit->object, \"\");\n+\tdiff_setup_done(&rev_info.diffopt);\n+\tlog_tree_commit(&rev_info, commit);\n+}\n+\n+/**\n+ * Like parse_mail(), but parses the mail by looking up its commit ID\n+ * directly. This is used in --rebasing mode to bypass git-mailinfo's munging\n+ * of patches.\n+ *\n+ * Will always return 0 as the patch should never be skipped.\n+ */\n+static int parse_mail_rebase(struct am_state *state, const char *mail)\n+{\n+\tstruct commit *commit;\n+\tunsigned char commit_sha1[GIT_SHA1_RAWSZ];\n+\n+\tif (get_mail_commit_sha1(commit_sha1, mail) < 0)\n+\t\tdie(_(\"could not parse %s\"), mail);\n+\n+\tcommit = lookup_commit_or_die(commit_sha1, mail);\n+\n+\tget_commit_info(state, commit);\n+\n+\twrite_commit_patch(state, commit);\n+\n+\treturn 0;\n+}\n+\n+/**\n  * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If\n  * `index_file` is not NULL, the patch will be applied to that index.\n  */\n@@ -1019,12 +1144,17 @@ static void am_run(struct am_state *state)\n \n \twhile (state->cur <= state->last) {\n \t\tconst char *mail = am_path(state, msgnum(state));\n-\t\tint apply_status;\n+\t\tint apply_status, skip;\n \n \t\tif (!file_exists(mail))\n \t\t\tgoto next;\n \n-\t\tif (parse_mail(state, mail))\n+\t\tif (state->rebasing)\n+\t\t\tskip = parse_mail_rebase(state, mail);\n+\t\telse\n+\t\t\tskip = parse_mail(state, mail);\n+\n+\t\tif (skip)\n \t\t\tgoto next; /* mail should be skipped */\n \n \t\twrite_author_script(state);\n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265703","messageId":"1436278862-2638-23-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 22/44] builtin-am: handle stray state directory","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:40Z","receivedAt":"2015-07-07T14:20:40Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"Should git-am terminate unexpectedly between the point where the state\ndirectory is created, but the \"next\" and \"last\" files are not written\nyet, a stray state directory will be left behind.\n\nAs such, since b141f3c (am: handle stray $dotest directory, 2013-06-15),\ngit-am.sh explicitly recognizes such a stray directory, and allows the\nuser to remove it with am --abort.\n\nRe-implement this feature in builtin/am.c.\n\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n builtin/am.c | 17 +++++++++++++++++\n 1 file changed, 17 insertions(+)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex 06ded5d..c92bff4 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -1531,6 +1531,23 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \t\tstruct argv_array paths = ARGV_ARRAY_INIT;\n \t\tint i;\n \n+\t\t/*\n+\t\t * Handle stray state directory in the independent-run case. In\n+\t\t * the --rebasing case, it is up to the caller to take care of\n+\t\t * stray directories.\n+\t\t */\n+\t\tif (file_exists(state.dir) && !state.rebasing) {\n+\t\t\tif (resume == RESUME_ABORT) {\n+\t\t\t\tam_destroy(&state);\n+\t\t\t\tam_state_release(&state);\n+\t\t\t\treturn 0;\n+\t\t\t}\n+\n+\t\t\tdie(_(\"Stray %s directory found.\\n\"\n+\t\t\t\t\"Use \\\"git am --abort\\\" to remove it.\"),\n+\t\t\t\tstate.dir);\n+\t\t}\n+\n \t\tif (resume)\n \t\t\tdie(_(\"Resolve operation not in progress, we are not resuming.\"));\n \n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265705","messageId":"1436278862-2638-24-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 23/44] builtin-am: implement -u/--utf8","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:41Z","receivedAt":"2015-07-07T14:20:41Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"Since d1c5f2a (Add git-am, applymbox replacement., 2005-10-07),\ngit-am.sh supported the -u,--utf8 option. If set, the -u option will be\npassed to git-mailinfo to re-code the commit log message and authorship\nin the charset specified by i18n.commitencoding. If unset, the -n option\nwill be passed to git-mailinfo, which disables the re-encoding.\n\nSince d84029b (--utf8 is now default for 'git-am', 2007-01-08), --utf8\nis specified by default in git-am.sh.\n\nRe-implement the above in builtin/am.c.\n\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n builtin/am.c | 12 ++++++++++++\n 1 file changed, 12 insertions(+)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex c92bff4..0b441fb 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -92,6 +92,8 @@ struct am_state {\n \n \tint append_signoff;\n \n+\tint utf8;\n+\n \t/* override error message when patch failure occurs */\n \tconst char *resolvemsg;\n \n@@ -112,6 +114,8 @@ static void am_state_init(struct am_state *state, const char *dir)\n \tstate->prec = 4;\n \n \tgit_config_get_bool(\"am.threeway\", &state->threeway);\n+\n+\tstate->utf8 = 1;\n }\n \n /**\n@@ -390,6 +394,9 @@ static void am_load(struct am_state *state)\n \tread_state_file(&sb, state, \"sign\", 1);\n \tstate->append_signoff = !strcmp(sb.buf, \"t\");\n \n+\tread_state_file(&sb, state, \"utf8\", 1);\n+\tstate->utf8 = !strcmp(sb.buf, \"t\");\n+\n \tstate->rebasing = !!file_exists(am_path(state, \"rebasing\"));\n \n \tstrbuf_release(&sb);\n@@ -579,6 +586,8 @@ static void am_setup(struct am_state *state, enum patch_format patch_format,\n \n \twrite_file(am_path(state, \"sign\"), 1, state->append_signoff ? \"t\" : \"f\");\n \n+\twrite_file(am_path(state, \"utf8\"), 1, state->utf8 ? \"t\" : \"f\");\n+\n \tif (state->rebasing)\n \t\twrite_file(am_path(state, \"rebasing\"), 1, \"%s\", \"\");\n \telse\n@@ -750,6 +759,7 @@ static int parse_mail(struct am_state *state, const char *mail)\n \tcp.out = xopen(am_path(state, \"info\"), O_WRONLY | O_CREAT, 0777);\n \n \targv_array_push(&cp.args, \"mailinfo\");\n+\targv_array_push(&cp.args, state->utf8 ? \"-u\" : \"-n\");\n \targv_array_push(&cp.args, am_path(state, \"msg\"));\n \targv_array_push(&cp.args, am_path(state, \"patch\"));\n \n@@ -1464,6 +1474,8 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \t\tOPT__QUIET(&state.quiet, N_(\"be quiet\")),\n \t\tOPT_BOOL('s', \"signoff\", &state.append_signoff,\n \t\t\tN_(\"add a Signed-off-by line to the commit message\")),\n+\t\tOPT_BOOL('u', \"utf8\", &state.utf8,\n+\t\t\tN_(\"recode into utf8 (default)\")),\n \t\tOPT_CALLBACK(0, \"patch-format\", &patch_format, N_(\"format\"),\n \t\t\tN_(\"format the patch(es) are in\"),\n \t\t\tparse_opt_patchformat),\n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265706","messageId":"1436278862-2638-25-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 24/44] builtin-am: implement -k/--keep, --keep-non-patch","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:42Z","receivedAt":"2015-07-07T14:20:42Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"Since d1c5f2a (Add git-am, applymbox replacement., 2005-10-07),\ngit-am.sh supported the -k/--keep option to pass the -k option to\ngit-mailsplit.\n\nSince f7e5ea1 (am: learn passing -b to mailinfo, 2012-01-16), git-am.sh\nsupported the --keep-non-patch option to pass the -b option to\ngit-mailsplit.\n\nRe-implement these two options in builtin/am.c.\n\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n builtin/am.c | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++\n 1 file changed, 52 insertions(+)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex 0b441fb..4e1ee7f 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -68,6 +68,12 @@ enum patch_format {\n \tPATCH_FORMAT_MBOX\n };\n \n+enum keep_type {\n+\tKEEP_FALSE = 0,\n+\tKEEP_TRUE,      /* pass -k flag to git-mailinfo */\n+\tKEEP_NON_PATCH  /* pass -b flag to git-mailinfo */\n+};\n+\n struct am_state {\n \t/* state directory path */\n \tchar *dir;\n@@ -94,6 +100,9 @@ struct am_state {\n \n \tint utf8;\n \n+\t/* one of the enum keep_type values */\n+\tint keep;\n+\n \t/* override error message when patch failure occurs */\n \tconst char *resolvemsg;\n \n@@ -397,6 +406,14 @@ static void am_load(struct am_state *state)\n \tread_state_file(&sb, state, \"utf8\", 1);\n \tstate->utf8 = !strcmp(sb.buf, \"t\");\n \n+\tread_state_file(&sb, state, \"keep\", 1);\n+\tif (!strcmp(sb.buf, \"t\"))\n+\t\tstate->keep = KEEP_TRUE;\n+\telse if (!strcmp(sb.buf, \"b\"))\n+\t\tstate->keep = KEEP_NON_PATCH;\n+\telse\n+\t\tstate->keep = KEEP_FALSE;\n+\n \tstate->rebasing = !!file_exists(am_path(state, \"rebasing\"));\n \n \tstrbuf_release(&sb);\n@@ -560,6 +577,7 @@ static void am_setup(struct am_state *state, enum patch_format patch_format,\n \t\t\tconst char **paths)\n {\n \tunsigned char curr_head[GIT_SHA1_RAWSZ];\n+\tconst char *str;\n \n \tif (!patch_format)\n \t\tpatch_format = detect_patch_format(paths);\n@@ -588,6 +606,22 @@ static void am_setup(struct am_state *state, enum patch_format patch_format,\n \n \twrite_file(am_path(state, \"utf8\"), 1, state->utf8 ? \"t\" : \"f\");\n \n+\tswitch (state->keep) {\n+\tcase KEEP_FALSE:\n+\t\tstr = \"f\";\n+\t\tbreak;\n+\tcase KEEP_TRUE:\n+\t\tstr = \"t\";\n+\t\tbreak;\n+\tcase KEEP_NON_PATCH:\n+\t\tstr = \"b\";\n+\t\tbreak;\n+\tdefault:\n+\t\tdie(\"BUG: invalid value for state->keep\");\n+\t}\n+\n+\twrite_file(am_path(state, \"keep\"), 1, \"%s\", str);\n+\n \tif (state->rebasing)\n \t\twrite_file(am_path(state, \"rebasing\"), 1, \"%s\", \"\");\n \telse\n@@ -760,6 +794,20 @@ static int parse_mail(struct am_state *state, const char *mail)\n \n \targv_array_push(&cp.args, \"mailinfo\");\n \targv_array_push(&cp.args, state->utf8 ? \"-u\" : \"-n\");\n+\n+\tswitch (state->keep) {\n+\tcase KEEP_FALSE:\n+\t\tbreak;\n+\tcase KEEP_TRUE:\n+\t\targv_array_push(&cp.args, \"-k\");\n+\t\tbreak;\n+\tcase KEEP_NON_PATCH:\n+\t\targv_array_push(&cp.args, \"-b\");\n+\t\tbreak;\n+\tdefault:\n+\t\tdie(\"BUG: invalid value for state->keep\");\n+\t}\n+\n \targv_array_push(&cp.args, am_path(state, \"msg\"));\n \targv_array_push(&cp.args, am_path(state, \"patch\"));\n \n@@ -1476,6 +1524,10 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \t\t\tN_(\"add a Signed-off-by line to the commit message\")),\n \t\tOPT_BOOL('u', \"utf8\", &state.utf8,\n \t\t\tN_(\"recode into utf8 (default)\")),\n+\t\tOPT_SET_INT('k', \"keep\", &state.keep,\n+\t\t\tN_(\"pass -k flag to git-mailinfo\"), KEEP_TRUE),\n+\t\tOPT_SET_INT(0, \"keep-non-patch\", &state.keep,\n+\t\t\tN_(\"pass -b flag to git-mailinfo\"), KEEP_NON_PATCH),\n \t\tOPT_CALLBACK(0, \"patch-format\", &patch_format, N_(\"format\"),\n \t\t\tN_(\"format the patch(es) are in\"),\n \t\t\tparse_opt_patchformat),\n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265708","messageId":"1436278862-2638-26-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 25/44] builtin-am: implement --[no-]message-id, am.messageid","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:43Z","receivedAt":"2015-07-07T14:20:43Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"Since a078f73 (git-am: add --message-id/--no-message-id, 2014-11-25),\ngit-am.sh supported the --[no-]message-id options, and the\n\"am.messageid\" setting which specifies the default option.\n\n--[no-]message-id tells git-am whether or not the -m option should be\npassed to git-mailinfo.\n\nRe-implement this option in builtin/am.c.\n\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n builtin/am.c | 15 +++++++++++++++\n 1 file changed, 15 insertions(+)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex 4e1ee7f..099c6ed 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -103,6 +103,9 @@ struct am_state {\n \t/* one of the enum keep_type values */\n \tint keep;\n \n+\t/* pass -m flag to git-mailinfo */\n+\tint message_id;\n+\n \t/* override error message when patch failure occurs */\n \tconst char *resolvemsg;\n \n@@ -125,6 +128,8 @@ static void am_state_init(struct am_state *state, const char *dir)\n \tgit_config_get_bool(\"am.threeway\", &state->threeway);\n \n \tstate->utf8 = 1;\n+\n+\tgit_config_get_bool(\"am.messageid\", &state->message_id);\n }\n \n /**\n@@ -414,6 +419,9 @@ static void am_load(struct am_state *state)\n \telse\n \t\tstate->keep = KEEP_FALSE;\n \n+\tread_state_file(&sb, state, \"messageid\", 1);\n+\tstate->message_id = !strcmp(sb.buf, \"t\");\n+\n \tstate->rebasing = !!file_exists(am_path(state, \"rebasing\"));\n \n \tstrbuf_release(&sb);\n@@ -622,6 +630,8 @@ static void am_setup(struct am_state *state, enum patch_format patch_format,\n \n \twrite_file(am_path(state, \"keep\"), 1, \"%s\", str);\n \n+\twrite_file(am_path(state, \"messageid\"), 1, state->message_id ? \"t\" : \"f\");\n+\n \tif (state->rebasing)\n \t\twrite_file(am_path(state, \"rebasing\"), 1, \"%s\", \"\");\n \telse\n@@ -808,6 +818,9 @@ static int parse_mail(struct am_state *state, const char *mail)\n \t\tdie(\"BUG: invalid value for state->keep\");\n \t}\n \n+\tif (state->message_id)\n+\t\targv_array_push(&cp.args, \"-m\");\n+\n \targv_array_push(&cp.args, am_path(state, \"msg\"));\n \targv_array_push(&cp.args, am_path(state, \"patch\"));\n \n@@ -1528,6 +1541,8 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \t\t\tN_(\"pass -k flag to git-mailinfo\"), KEEP_TRUE),\n \t\tOPT_SET_INT(0, \"keep-non-patch\", &state.keep,\n \t\t\tN_(\"pass -b flag to git-mailinfo\"), KEEP_NON_PATCH),\n+\t\tOPT_BOOL('m', \"message-id\", &state.message_id,\n+\t\t\tN_(\"pass -m flag to git-mailinfo\")),\n \t\tOPT_CALLBACK(0, \"patch-format\", &patch_format, N_(\"format\"),\n \t\t\tN_(\"format the patch(es) are in\"),\n \t\t\tparse_opt_patchformat),\n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265711","messageId":"1436278862-2638-27-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 26/44] builtin-am: support --keep-cr, am.keepcr","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:44Z","receivedAt":"2015-07-07T14:20:44Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"Since ad2c928 (git-am: Add command line parameter `--keep-cr` passing it\nto git-mailsplit, 2010-02-27), git-am.sh supported the --keep-cr option\nand would pass it to git-mailsplit.\n\nSince e80d4cb (git-am: Add am.keepcr and --no-keep-cr to override it,\n2010-02-27), git-am.sh supported the am.keepcr config setting, which\ncontrols whether --keep-cr is on by default.\n\nRe-implement the above in builtin/am.c.\n\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n builtin/am.c | 29 +++++++++++++++++++++++------\n 1 file changed, 23 insertions(+), 6 deletions(-)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex 099c6ed..59a7a2a 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -530,7 +530,7 @@ done:\n  * Splits out individual email patches from `paths`, where each path is either\n  * a mbox file or a Maildir. Returns 0 on success, -1 on failure.\n  */\n-static int split_mail_mbox(struct am_state *state, const char **paths)\n+static int split_mail_mbox(struct am_state *state, const char **paths, int keep_cr)\n {\n \tstruct child_process cp = CHILD_PROCESS_INIT;\n \tstruct strbuf last = STRBUF_INIT;\n@@ -540,6 +540,8 @@ static int split_mail_mbox(struct am_state *state, const char **paths)\n \targv_array_pushf(&cp.args, \"-d%d\", state->prec);\n \targv_array_pushf(&cp.args, \"-o%s\", state->dir);\n \targv_array_push(&cp.args, \"-b\");\n+\tif (keep_cr)\n+\t\targv_array_push(&cp.args, \"--keep-cr\");\n \targv_array_push(&cp.args, \"--\");\n \targv_array_pushv(&cp.args, paths);\n \n@@ -564,14 +566,22 @@ static int split_mail_mbox(struct am_state *state, const char **paths)\n  * state->cur will be set to the index of the first mail, and state->last will\n  * be set to the index of the last mail.\n  *\n+ * Set keep_cr to 0 to convert all lines ending with \\r\\n to end with \\n, 1\n+ * to disable this behavior, -1 to use the default configured setting.\n+ *\n  * Returns 0 on success, -1 on failure.\n  */\n static int split_mail(struct am_state *state, enum patch_format patch_format,\n-\t\t\tconst char **paths)\n+\t\t\tconst char **paths, int keep_cr)\n {\n+\tif (keep_cr < 0) {\n+\t\tkeep_cr = 0;\n+\t\tgit_config_get_bool(\"am.keepcr\", &keep_cr);\n+\t}\n+\n \tswitch (patch_format) {\n \tcase PATCH_FORMAT_MBOX:\n-\t\treturn split_mail_mbox(state, paths);\n+\t\treturn split_mail_mbox(state, paths, keep_cr);\n \tdefault:\n \t\tdie(\"BUG: invalid patch_format\");\n \t}\n@@ -582,7 +592,7 @@ static int split_mail(struct am_state *state, enum patch_format patch_format,\n  * Setup a new am session for applying patches\n  */\n static void am_setup(struct am_state *state, enum patch_format patch_format,\n-\t\t\tconst char **paths)\n+\t\t\tconst char **paths, int keep_cr)\n {\n \tunsigned char curr_head[GIT_SHA1_RAWSZ];\n \tconst char *str;\n@@ -598,7 +608,7 @@ static void am_setup(struct am_state *state, enum patch_format patch_format,\n \tif (mkdir(state->dir, 0777) < 0 && errno != EEXIST)\n \t\tdie_errno(_(\"failed to create directory '%s'\"), state->dir);\n \n-\tif (split_mail(state, patch_format, paths) < 0) {\n+\tif (split_mail(state, patch_format, paths, keep_cr) < 0) {\n \t\tam_destroy(state);\n \t\tdie(_(\"Failed to split patches.\"));\n \t}\n@@ -1520,6 +1530,7 @@ enum resume_mode {\n int cmd_am(int argc, const char **argv, const char *prefix)\n {\n \tstruct am_state state;\n+\tint keep_cr = -1;\n \tint patch_format = PATCH_FORMAT_UNKNOWN;\n \tenum resume_mode resume = RESUME_FALSE;\n \n@@ -1543,6 +1554,12 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \t\t\tN_(\"pass -b flag to git-mailinfo\"), KEEP_NON_PATCH),\n \t\tOPT_BOOL('m', \"message-id\", &state.message_id,\n \t\t\tN_(\"pass -m flag to git-mailinfo\")),\n+\t\t{ OPTION_SET_INT, 0, \"keep-cr\", &keep_cr, NULL,\n+\t\t  N_(\"pass --keep-cr flag to git-mailsplit for mbox format\"),\n+\t\t  PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1},\n+\t\t{ OPTION_SET_INT, 0, \"no-keep-cr\", &keep_cr, NULL,\n+\t\t  N_(\"do not pass --keep-cr flag to git-mailsplit independent of am.keepcr\"),\n+\t\t  PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 0},\n \t\tOPT_CALLBACK(0, \"patch-format\", &patch_format, N_(\"format\"),\n \t\t\tN_(\"format the patch(es) are in\"),\n \t\t\tparse_opt_patchformat),\n@@ -1637,7 +1654,7 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \t\t\t\targv_array_push(&paths, mkpath(\"%s/%s\", prefix, argv[i]));\n \t\t}\n \n-\t\tam_setup(&state, patch_format, paths.argv);\n+\t\tam_setup(&state, patch_format, paths.argv, keep_cr);\n \n \t\targv_array_clear(&paths);\n \t}\n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265704","messageId":"1436278862-2638-28-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 27/44] builtin-am: implement --[no-]scissors","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:45Z","receivedAt":"2015-07-07T14:20:45Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"Since 017678b (am/mailinfo: Disable scissors processing by default,\n2009-08-26), git-am supported the --[no-]scissors option, passing it to\ngit-mailinfo.\n\nRe-implement support for this option in builtin/am.c.\n\nSince the default setting of --scissors in git-mailinfo can be\nconfigured with mailinfo.scissors (and perhaps through other settings in\nthe future), to be safe we make an explicit distinction between\nSCISSORS_UNSET, SCISSORS_TRUE and SCISSORS_FALSE.\n\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n\nNotes:\n    v5\n    \n    * Previously, SCISSORS_FALSE was 1 while SCISSORS_TRUE was 0. This\n      should be the other way around.\n\n builtin/am.c | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++\n 1 file changed, 50 insertions(+)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex 59a7a2a..2e46a06 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -74,6 +74,12 @@ enum keep_type {\n \tKEEP_NON_PATCH  /* pass -b flag to git-mailinfo */\n };\n \n+enum scissors_type {\n+\tSCISSORS_UNSET = -1,\n+\tSCISSORS_FALSE = 0,  /* pass --no-scissors to git-mailinfo */\n+\tSCISSORS_TRUE        /* pass --scissors to git-mailinfo */\n+};\n+\n struct am_state {\n \t/* state directory path */\n \tchar *dir;\n@@ -106,6 +112,9 @@ struct am_state {\n \t/* pass -m flag to git-mailinfo */\n \tint message_id;\n \n+\t/* one of the enum scissors_type values */\n+\tint scissors;\n+\n \t/* override error message when patch failure occurs */\n \tconst char *resolvemsg;\n \n@@ -130,6 +139,8 @@ static void am_state_init(struct am_state *state, const char *dir)\n \tstate->utf8 = 1;\n \n \tgit_config_get_bool(\"am.messageid\", &state->message_id);\n+\n+\tstate->scissors = SCISSORS_UNSET;\n }\n \n /**\n@@ -422,6 +433,14 @@ static void am_load(struct am_state *state)\n \tread_state_file(&sb, state, \"messageid\", 1);\n \tstate->message_id = !strcmp(sb.buf, \"t\");\n \n+\tread_state_file(&sb, state, \"scissors\", 1);\n+\tif (!strcmp(sb.buf, \"t\"))\n+\t\tstate->scissors = SCISSORS_TRUE;\n+\telse if (!strcmp(sb.buf, \"f\"))\n+\t\tstate->scissors = SCISSORS_FALSE;\n+\telse\n+\t\tstate->scissors = SCISSORS_UNSET;\n+\n \tstate->rebasing = !!file_exists(am_path(state, \"rebasing\"));\n \n \tstrbuf_release(&sb);\n@@ -642,6 +661,22 @@ static void am_setup(struct am_state *state, enum patch_format patch_format,\n \n \twrite_file(am_path(state, \"messageid\"), 1, state->message_id ? \"t\" : \"f\");\n \n+\tswitch (state->scissors) {\n+\tcase SCISSORS_UNSET:\n+\t\tstr = \"\";\n+\t\tbreak;\n+\tcase SCISSORS_FALSE:\n+\t\tstr = \"f\";\n+\t\tbreak;\n+\tcase SCISSORS_TRUE:\n+\t\tstr = \"t\";\n+\t\tbreak;\n+\tdefault:\n+\t\tdie(\"BUG: invalid value for state->scissors\");\n+\t}\n+\n+\twrite_file(am_path(state, \"scissors\"), 1, \"%s\", str);\n+\n \tif (state->rebasing)\n \t\twrite_file(am_path(state, \"rebasing\"), 1, \"%s\", \"\");\n \telse\n@@ -831,6 +866,19 @@ static int parse_mail(struct am_state *state, const char *mail)\n \tif (state->message_id)\n \t\targv_array_push(&cp.args, \"-m\");\n \n+\tswitch (state->scissors) {\n+\tcase SCISSORS_UNSET:\n+\t\tbreak;\n+\tcase SCISSORS_FALSE:\n+\t\targv_array_push(&cp.args, \"--no-scissors\");\n+\t\tbreak;\n+\tcase SCISSORS_TRUE:\n+\t\targv_array_push(&cp.args, \"--scissors\");\n+\t\tbreak;\n+\tdefault:\n+\t\tdie(\"BUG: invalid value for state->scissors\");\n+\t}\n+\n \targv_array_push(&cp.args, am_path(state, \"msg\"));\n \targv_array_push(&cp.args, am_path(state, \"patch\"));\n \n@@ -1560,6 +1608,8 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \t\t{ OPTION_SET_INT, 0, \"no-keep-cr\", &keep_cr, NULL,\n \t\t  N_(\"do not pass --keep-cr flag to git-mailsplit independent of am.keepcr\"),\n \t\t  PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 0},\n+\t\tOPT_BOOL('c', \"scissors\", &state.scissors,\n+\t\t\tN_(\"strip everything before a scissors line\")),\n \t\tOPT_CALLBACK(0, \"patch-format\", &patch_format, N_(\"format\"),\n \t\t\tN_(\"format the patch(es) are in\"),\n \t\t\tparse_opt_patchformat),\n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265712","messageId":"1436278862-2638-29-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 28/44] builtin-am: pass git-apply's options to git-apply","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:46Z","receivedAt":"2015-07-07T14:20:46Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"git-am.sh recognizes some of git-apply's options, and would pass them to\ngit-apply:\n\n* --whitespace, since 8c31cb8 (git-am: --whitespace=x option.,\n  2006-02-28)\n\n* -C, since 67dad68 (add -C[NUM] to git-am, 2007-02-08)\n\n* -p, since 2092a1f (Teach git-am to pass -p option down to git-apply,\n  2007-02-11)\n\n* --directory, since b47dfe9 (git-am: add --directory=<dir> option,\n  2009-01-11)\n\n* --reject, since b80da42 (git-am: implement --reject option passed to\n  git-apply, 2009-01-23)\n\n* --ignore-space-change, --ignore-whitespace, since 86c91f9 (git apply:\n  option to ignore whitespace differences, 2009-08-04)\n\n* --exclude, since 77e9e49 (am: pass exclude down to apply, 2011-08-03)\n\n* --include, since 58725ef (am: support --include option, 2012-03-28)\n\n* --reject, since b80da42 (git-am: implement --reject option passed to\n  git-apply, 2009-01-23)\n\nRe-implement support for these options in builtin/am.c.\n\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n builtin/am.c | 47 +++++++++++++++++++++++++++++++++++++++++++++++\n 1 file changed, 47 insertions(+)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex 2e46a06..6006010 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -115,6 +115,8 @@ struct am_state {\n \t/* one of the enum scissors_type values */\n \tint scissors;\n \n+\tstruct argv_array git_apply_opts;\n+\n \t/* override error message when patch failure occurs */\n \tconst char *resolvemsg;\n \n@@ -141,6 +143,8 @@ static void am_state_init(struct am_state *state, const char *dir)\n \tgit_config_get_bool(\"am.messageid\", &state->message_id);\n \n \tstate->scissors = SCISSORS_UNSET;\n+\n+\targv_array_init(&state->git_apply_opts);\n }\n \n /**\n@@ -162,6 +166,8 @@ static void am_state_release(struct am_state *state)\n \n \tif (state->msg)\n \t\tfree(state->msg);\n+\n+\targv_array_clear(&state->git_apply_opts);\n }\n \n /**\n@@ -441,6 +447,11 @@ static void am_load(struct am_state *state)\n \telse\n \t\tstate->scissors = SCISSORS_UNSET;\n \n+\tread_state_file(&sb, state, \"apply-opt\", 1);\n+\targv_array_clear(&state->git_apply_opts);\n+\tif (sq_dequote_to_argv_array(sb.buf, &state->git_apply_opts) < 0)\n+\t\tdie(_(\"could not parse %s\"), am_path(state, \"apply-opt\"));\n+\n \tstate->rebasing = !!file_exists(am_path(state, \"rebasing\"));\n \n \tstrbuf_release(&sb);\n@@ -615,6 +626,7 @@ static void am_setup(struct am_state *state, enum patch_format patch_format,\n {\n \tunsigned char curr_head[GIT_SHA1_RAWSZ];\n \tconst char *str;\n+\tstruct strbuf sb = STRBUF_INIT;\n \n \tif (!patch_format)\n \t\tpatch_format = detect_patch_format(paths);\n@@ -677,6 +689,9 @@ static void am_setup(struct am_state *state, enum patch_format patch_format,\n \n \twrite_file(am_path(state, \"scissors\"), 1, \"%s\", str);\n \n+\tsq_quote_argv(&sb, state->git_apply_opts.argv, 0);\n+\twrite_file(am_path(state, \"apply-opt\"), 1, \"%s\", sb.buf);\n+\n \tif (state->rebasing)\n \t\twrite_file(am_path(state, \"rebasing\"), 1, \"%s\", \"\");\n \telse\n@@ -701,6 +716,8 @@ static void am_setup(struct am_state *state, enum patch_format patch_format,\n \twrite_file(am_path(state, \"next\"), 1, \"%d\", state->cur);\n \n \twrite_file(am_path(state, \"last\"), 1, \"%d\", state->last);\n+\n+\tstrbuf_release(&sb);\n }\n \n /**\n@@ -1093,6 +1110,8 @@ static int run_apply(const struct am_state *state, const char *index_file)\n \n \targv_array_push(&cp.args, \"apply\");\n \n+\targv_array_pushv(&cp.args, state->git_apply_opts.argv);\n+\n \tif (index_file)\n \t\targv_array_push(&cp.args, \"--cached\");\n \telse\n@@ -1119,6 +1138,7 @@ static int build_fake_ancestor(const struct am_state *state, const char *index_f\n \n \tcp.git_cmd = 1;\n \targv_array_push(&cp.args, \"apply\");\n+\targv_array_pushv(&cp.args, state->git_apply_opts.argv);\n \targv_array_pushf(&cp.args, \"--build-fake-ancestor=%s\", index_file);\n \targv_array_push(&cp.args, am_path(state, \"patch\"));\n \n@@ -1610,9 +1630,36 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \t\t  PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 0},\n \t\tOPT_BOOL('c', \"scissors\", &state.scissors,\n \t\t\tN_(\"strip everything before a scissors line\")),\n+\t\tOPT_PASSTHRU_ARGV(0, \"whitespace\", &state.git_apply_opts, N_(\"action\"),\n+\t\t\tN_(\"pass it through git-apply\"),\n+\t\t\t0),\n+\t\tOPT_PASSTHRU_ARGV(0, \"ignore-space-change\", &state.git_apply_opts, NULL,\n+\t\t\tN_(\"pass it through git-apply\"),\n+\t\t\tPARSE_OPT_NOARG),\n+\t\tOPT_PASSTHRU_ARGV(0, \"ignore-whitespace\", &state.git_apply_opts, NULL,\n+\t\t\tN_(\"pass it through git-apply\"),\n+\t\t\tPARSE_OPT_NOARG),\n+\t\tOPT_PASSTHRU_ARGV(0, \"directory\", &state.git_apply_opts, N_(\"root\"),\n+\t\t\tN_(\"pass it through git-apply\"),\n+\t\t\t0),\n+\t\tOPT_PASSTHRU_ARGV(0, \"exclude\", &state.git_apply_opts, N_(\"path\"),\n+\t\t\tN_(\"pass it through git-apply\"),\n+\t\t\t0),\n+\t\tOPT_PASSTHRU_ARGV(0, \"include\", &state.git_apply_opts, N_(\"path\"),\n+\t\t\tN_(\"pass it through git-apply\"),\n+\t\t\t0),\n+\t\tOPT_PASSTHRU_ARGV('C', NULL, &state.git_apply_opts, N_(\"n\"),\n+\t\t\tN_(\"pass it through git-apply\"),\n+\t\t\t0),\n+\t\tOPT_PASSTHRU_ARGV('p', NULL, &state.git_apply_opts, N_(\"num\"),\n+\t\t\tN_(\"pass it through git-apply\"),\n+\t\t\t0),\n \t\tOPT_CALLBACK(0, \"patch-format\", &patch_format, N_(\"format\"),\n \t\t\tN_(\"format the patch(es) are in\"),\n \t\t\tparse_opt_patchformat),\n+\t\tOPT_PASSTHRU_ARGV(0, \"reject\", &state.git_apply_opts, NULL,\n+\t\t\tN_(\"pass it through git-apply\"),\n+\t\t\tPARSE_OPT_NOARG),\n \t\tOPT_STRING(0, \"resolvemsg\", &state.resolvemsg, NULL,\n \t\t\tN_(\"override error message when patch failure occurs\")),\n \t\tOPT_CMDMODE(0, \"continue\", &resume,\n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265710","messageId":"1436278862-2638-30-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 29/44] builtin-am: implement --ignore-date","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:47Z","receivedAt":"2015-07-07T14:20:47Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"Since a79ec62 (git-am: Add --ignore-date option, 2009-01-24), git-am.sh\nsupported the --ignore-date option, and would use the current timestamp\ninstead of the one provided in the patch if the option was set.\n\nRe-implement this option in builtin/am.c.\n\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n builtin/am.c | 7 ++++++-\n 1 file changed, 6 insertions(+), 1 deletion(-)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex 6006010..e9eacf0 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -120,6 +120,8 @@ struct am_state {\n \t/* override error message when patch failure occurs */\n \tconst char *resolvemsg;\n \n+\tint ignore_date;\n+\n \tint rebasing;\n };\n \n@@ -1254,7 +1256,8 @@ static void do_commit(const struct am_state *state)\n \t}\n \n \tauthor = fmt_ident(state->author_name, state->author_email,\n-\t\t\tstate->author_date, IDENT_STRICT);\n+\t\t\tstate->ignore_date ? NULL : state->author_date,\n+\t\t\tIDENT_STRICT);\n \n \tif (commit_tree(state->msg, state->msg_len, tree, parents, commit,\n \t\t\t\tauthor, NULL))\n@@ -1674,6 +1677,8 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \t\tOPT_CMDMODE(0, \"abort\", &resume,\n \t\t\tN_(\"restore the original branch and abort the patching operation.\"),\n \t\t\tRESUME_ABORT),\n+\t\tOPT_BOOL(0, \"ignore-date\", &state.ignore_date,\n+\t\t\tN_(\"use current timestamp for author date\")),\n \t\tOPT_HIDDEN_BOOL(0, \"rebasing\", &state.rebasing,\n \t\t\tN_(\"(internal use for git-rebase)\")),\n \t\tOPT_END()\n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265716","messageId":"1436278862-2638-31-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 30/44] builtin-am: implement --committer-date-is-author-date","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:48Z","receivedAt":"2015-07-07T14:20:48Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"Since 3f01ad6 (am: Add --committer-date-is-author-date option,\n2009-01-22), git-am.sh implemented the --committer-date-is-author-date\noption, which tells git-am to use the timestamp recorded in the email\nmessage as both author and committer date.\n\nRe-implement this option in builtin/am.c.\n\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n builtin/am.c | 9 +++++++++\n 1 file changed, 9 insertions(+)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex e9eacf0..d7bb159 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -120,6 +120,8 @@ struct am_state {\n \t/* override error message when patch failure occurs */\n \tconst char *resolvemsg;\n \n+\tint committer_date_is_author_date;\n+\n \tint ignore_date;\n \n \tint rebasing;\n@@ -1259,6 +1261,10 @@ static void do_commit(const struct am_state *state)\n \t\t\tstate->ignore_date ? NULL : state->author_date,\n \t\t\tIDENT_STRICT);\n \n+\tif (state->committer_date_is_author_date)\n+\t\tsetenv(\"GIT_COMMITTER_DATE\",\n+\t\t\tstate->ignore_date ? \"\" : state->author_date, 1);\n+\n \tif (commit_tree(state->msg, state->msg_len, tree, parents, commit,\n \t\t\t\tauthor, NULL))\n \t\tdie(_(\"failed to write commit object\"));\n@@ -1677,6 +1683,9 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \t\tOPT_CMDMODE(0, \"abort\", &resume,\n \t\t\tN_(\"restore the original branch and abort the patching operation.\"),\n \t\t\tRESUME_ABORT),\n+\t\tOPT_BOOL(0, \"committer-date-is-author-date\",\n+\t\t\t&state.committer_date_is_author_date,\n+\t\t\tN_(\"lie about committer date\")),\n \t\tOPT_BOOL(0, \"ignore-date\", &state.ignore_date,\n \t\t\tN_(\"use current timestamp for author date\")),\n \t\tOPT_HIDDEN_BOOL(0, \"rebasing\", &state.rebasing,\n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265713","messageId":"1436278862-2638-32-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 31/44] builtin-am: implement -S/--gpg-sign, commit.gpgsign","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:49Z","receivedAt":"2015-07-07T14:20:49Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"Since 3b4e395 (am: add the --gpg-sign option, 2014-02-01), git-am.sh\nsupported the --gpg-sign option, and would pass it to git-commit-tree,\nthus GPG-signing the commit object.\n\nRe-implement this option in builtin/am.c.\n\ngit-commit-tree would also sign the commit by default if the\ncommit.gpgsign setting is true. Since we do not run commit-tree, we\nre-implement this behavior by handling the commit.gpgsign setting\nourselves.\n\nHelped-by: Stefan Beller <sbeller@google.com>\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n\nNotes:\n    v5\n    \n    * Renamed local \"sign_commit\" variable in am_state_init() to \"gpgsign\"\n      to aid code review.\n\n builtin/am.c | 12 +++++++++++-\n 1 file changed, 11 insertions(+), 1 deletion(-)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex d7bb159..81b3e31 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -124,6 +124,8 @@ struct am_state {\n \n \tint ignore_date;\n \n+\tconst char *sign_commit;\n+\n \tint rebasing;\n };\n \n@@ -133,6 +135,8 @@ struct am_state {\n  */\n static void am_state_init(struct am_state *state, const char *dir)\n {\n+\tint gpgsign;\n+\n \tmemset(state, 0, sizeof(*state));\n \n \tassert(dir);\n@@ -149,6 +153,9 @@ static void am_state_init(struct am_state *state, const char *dir)\n \tstate->scissors = SCISSORS_UNSET;\n \n \targv_array_init(&state->git_apply_opts);\n+\n+\tif (!git_config_get_bool(\"commit.gpgsign\", &gpgsign))\n+\t\tstate->sign_commit = gpgsign ? \"\" : NULL;\n }\n \n /**\n@@ -1266,7 +1273,7 @@ static void do_commit(const struct am_state *state)\n \t\t\tstate->ignore_date ? \"\" : state->author_date, 1);\n \n \tif (commit_tree(state->msg, state->msg_len, tree, parents, commit,\n-\t\t\t\tauthor, NULL))\n+\t\t\t\tauthor, state->sign_commit))\n \t\tdie(_(\"failed to write commit object\"));\n \n \treflog_msg = getenv(\"GIT_REFLOG_ACTION\");\n@@ -1688,6 +1695,9 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \t\t\tN_(\"lie about committer date\")),\n \t\tOPT_BOOL(0, \"ignore-date\", &state.ignore_date,\n \t\t\tN_(\"use current timestamp for author date\")),\n+\t\t{ OPTION_STRING, 'S', \"gpg-sign\", &state.sign_commit, N_(\"key-id\"),\n+\t\t  N_(\"GPG-sign commits\"),\n+\t\t  PARSE_OPT_OPTARG, NULL, (intptr_t) \"\" },\n \t\tOPT_HIDDEN_BOOL(0, \"rebasing\", &state.rebasing,\n \t\t\tN_(\"(internal use for git-rebase)\")),\n \t\tOPT_END()\n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265714","messageId":"1436278862-2638-33-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 32/44] builtin-am: invoke post-rewrite hook","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:50Z","receivedAt":"2015-07-07T14:20:50Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"Since 96e1948 (rebase: invoke post-rewrite hook, 2010-03-12), git-am.sh\nwill invoke the post-rewrite hook after it successfully finishes\napplying all the queued patches.\n\nTo do this, when parsing a mail to extract its patch and metadata, in\n--rebasing mode git-am.sh will also store the original commit ID in the\n$state_dir/original-commit file. Once it applies and commits the patch,\nthe original commit ID, and the new commit ID, will be appended to the\n$state_dir/rewritten file.\n\nOnce all of the queued mail have been processed, git-am.sh will then\ninvoke the post-rewrite hook with the contents of the\n$state_dir/rewritten file.\n\nRe-implement this in builtin/am.c.\n\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n builtin/am.c | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++++++\n 1 file changed, 55 insertions(+)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex 81b3e31..c234ee9 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -95,6 +95,9 @@ struct am_state {\n \tchar *msg;\n \tsize_t msg_len;\n \n+\t/* when --rebasing, records the original commit the patch came from */\n+\tunsigned char orig_commit[GIT_SHA1_RAWSZ];\n+\n \t/* number of digits in patch filename */\n \tint prec;\n \n@@ -427,6 +430,11 @@ static void am_load(struct am_state *state)\n \n \tread_commit_msg(state);\n \n+\tif (read_state_file(&sb, state, \"original-commit\", 1) < 0)\n+\t\thashclr(state->orig_commit);\n+\telse if (get_sha1_hex(sb.buf, state->orig_commit) < 0)\n+\t\tdie(_(\"could not parse %s\"), am_path(state, \"original-commit\"));\n+\n \tread_state_file(&sb, state, \"threeway\", 1);\n \tstate->threeway = !strcmp(sb.buf, \"t\");\n \n@@ -482,6 +490,30 @@ static void am_destroy(const struct am_state *state)\n }\n \n /**\n+ * Runs post-rewrite hook. Returns it exit code.\n+ */\n+static int run_post_rewrite_hook(const struct am_state *state)\n+{\n+\tstruct child_process cp = CHILD_PROCESS_INIT;\n+\tconst char *hook = find_hook(\"post-rewrite\");\n+\tint ret;\n+\n+\tif (!hook)\n+\t\treturn 0;\n+\n+\targv_array_push(&cp.args, hook);\n+\targv_array_push(&cp.args, \"rebase\");\n+\n+\tcp.in = xopen(am_path(state, \"rewritten\"), O_RDONLY);\n+\tcp.stdout_to_stderr = 1;\n+\n+\tret = run_command(&cp);\n+\n+\tclose(cp.in);\n+\treturn ret;\n+}\n+\n+/**\n  * Determines if the file looks like a piece of RFC2822 mail by grabbing all\n  * non-indented lines and checking if they look like they begin with valid\n  * header field names.\n@@ -759,6 +791,9 @@ static void am_next(struct am_state *state)\n \tunlink(am_path(state, \"author-script\"));\n \tunlink(am_path(state, \"final-commit\"));\n \n+\thashclr(state->orig_commit);\n+\tunlink(am_path(state, \"original-commit\"));\n+\n \tif (!get_sha1(\"HEAD\", head))\n \t\twrite_file(am_path(state, \"abort-safety\"), 1, \"%s\", sha1_to_hex(head));\n \telse\n@@ -1078,6 +1113,8 @@ static void write_commit_patch(const struct am_state *state, struct commit *comm\n  * directly. This is used in --rebasing mode to bypass git-mailinfo's munging\n  * of patches.\n  *\n+ * state->orig_commit will be set to the original commit ID.\n+ *\n  * Will always return 0 as the patch should never be skipped.\n  */\n static int parse_mail_rebase(struct am_state *state, const char *mail)\n@@ -1094,6 +1131,10 @@ static int parse_mail_rebase(struct am_state *state, const char *mail)\n \n \twrite_commit_patch(state, commit);\n \n+\thashcpy(state->orig_commit, commit_sha1);\n+\twrite_file(am_path(state, \"original-commit\"), 1, \"%s\",\n+\t\t\tsha1_to_hex(commit_sha1));\n+\n \treturn 0;\n }\n \n@@ -1285,6 +1326,15 @@ static void do_commit(const struct am_state *state)\n \n \tupdate_ref(sb.buf, \"HEAD\", commit, ptr, 0, UPDATE_REFS_DIE_ON_ERR);\n \n+\tif (state->rebasing) {\n+\t\tFILE *fp = xfopen(am_path(state, \"rewritten\"), \"a\");\n+\n+\t\tassert(!is_null_sha1(state->orig_commit));\n+\t\tfprintf(fp, \"%s \", sha1_to_hex(state->orig_commit));\n+\t\tfprintf(fp, \"%s\\n\", sha1_to_hex(commit));\n+\t\tfclose(fp);\n+\t}\n+\n \tstrbuf_release(&sb);\n }\n \n@@ -1367,6 +1417,11 @@ next:\n \t\tam_next(state);\n \t}\n \n+\tif (!is_empty_file(am_path(state, \"rewritten\"))) {\n+\t\tassert(state->rebasing);\n+\t\trun_post_rewrite_hook(state);\n+\t}\n+\n \t/*\n \t * In rebasing mode, it's up to the caller to take care of\n \t * housekeeping.\n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265715","messageId":"1436278862-2638-34-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 33/44] builtin-am: support automatic notes copying","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:51Z","receivedAt":"2015-07-07T14:20:51Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"Since eb2151b (rebase: support automatic notes copying, 2010-03-12),\ngit-am.sh supported automatic notes copying in --rebasing mode by\ninvoking \"git notes copy\" once it has finished applying all the patches.\n\nRe-implement this feature in builtin/am.c.\n\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n builtin/am.c | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n 1 file changed, 60 insertions(+)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex c234ee9..2255a1e 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -23,6 +23,7 @@\n #include \"merge-recursive.h\"\n #include \"revision.h\"\n #include \"log-tree.h\"\n+#include \"notes-utils.h\"\n \n /**\n  * Returns 1 if the file is empty or does not exist, 0 otherwise.\n@@ -514,6 +515,64 @@ static int run_post_rewrite_hook(const struct am_state *state)\n }\n \n /**\n+ * Reads the state directory's \"rewritten\" file, and copies notes from the old\n+ * commits listed in the file to their rewritten commits.\n+ *\n+ * Returns 0 on success, -1 on failure.\n+ */\n+static int copy_notes_for_rebase(const struct am_state *state)\n+{\n+\tstruct notes_rewrite_cfg *c;\n+\tstruct strbuf sb = STRBUF_INIT;\n+\tconst char *invalid_line = _(\"Malformed input line: '%s'.\");\n+\tconst char *msg = \"Notes added by 'git rebase'\";\n+\tFILE *fp;\n+\tint ret = 0;\n+\n+\tassert(state->rebasing);\n+\n+\tc = init_copy_notes_for_rewrite(\"rebase\");\n+\tif (!c)\n+\t\treturn 0;\n+\n+\tfp = xfopen(am_path(state, \"rewritten\"), \"r\");\n+\n+\twhile (!strbuf_getline(&sb, fp, '\\n')) {\n+\t\tunsigned char from_obj[GIT_SHA1_RAWSZ], to_obj[GIT_SHA1_RAWSZ];\n+\n+\t\tif (sb.len != GIT_SHA1_HEXSZ * 2 + 1) {\n+\t\t\tret = error(invalid_line, sb.buf);\n+\t\t\tgoto finish;\n+\t\t}\n+\n+\t\tif (get_sha1_hex(sb.buf, from_obj)) {\n+\t\t\tret = error(invalid_line, sb.buf);\n+\t\t\tgoto finish;\n+\t\t}\n+\n+\t\tif (sb.buf[GIT_SHA1_HEXSZ] != ' ') {\n+\t\t\tret = error(invalid_line, sb.buf);\n+\t\t\tgoto finish;\n+\t\t}\n+\n+\t\tif (get_sha1_hex(sb.buf + GIT_SHA1_HEXSZ + 1, to_obj)) {\n+\t\t\tret = error(invalid_line, sb.buf);\n+\t\t\tgoto finish;\n+\t\t}\n+\n+\t\tif (copy_note_for_rewrite(c, from_obj, to_obj))\n+\t\t\tret = error(_(\"Failed to copy notes from '%s' to '%s'\"),\n+\t\t\t\t\tsha1_to_hex(from_obj), sha1_to_hex(to_obj));\n+\t}\n+\n+finish:\n+\tfinish_copy_notes_for_rewrite(c, msg);\n+\tfclose(fp);\n+\tstrbuf_release(&sb);\n+\treturn ret;\n+}\n+\n+/**\n  * Determines if the file looks like a piece of RFC2822 mail by grabbing all\n  * non-indented lines and checking if they look like they begin with valid\n  * header field names.\n@@ -1419,6 +1478,7 @@ next:\n \n \tif (!is_empty_file(am_path(state, \"rewritten\"))) {\n \t\tassert(state->rebasing);\n+\t\tcopy_notes_for_rebase(state);\n \t\trun_post_rewrite_hook(state);\n \t}\n \n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265730","messageId":"1436278862-2638-35-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 34/44] builtin-am: invoke applypatch-msg hook","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:52Z","receivedAt":"2015-07-07T14:20:52Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"Since d1c5f2a (Add git-am, applymbox replacement., 2005-10-07),\ngit-am.sh will invoke the applypatch-msg hooks just after extracting the\npatch message. If the applypatch-msg hook exits with a non-zero status,\ngit-am.sh abort before even applying the patch to the index.\n\nRe-implement this in builtin/am.c.\n\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n builtin/am.c | 24 ++++++++++++++++++++++++\n 1 file changed, 24 insertions(+)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex 2255a1e..f856d3b 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -491,6 +491,27 @@ static void am_destroy(const struct am_state *state)\n }\n \n /**\n+ * Runs applypatch-msg hook. Returns its exit code.\n+ */\n+static int run_applypatch_msg_hook(struct am_state *state)\n+{\n+\tint ret;\n+\n+\tassert(state->msg);\n+\tret = run_hook_le(NULL, \"applypatch-msg\", am_path(state, \"final-commit\"), NULL);\n+\n+\tif (!ret) {\n+\t\tfree(state->msg);\n+\t\tstate->msg = NULL;\n+\t\tif (read_commit_msg(state) < 0)\n+\t\t\tdie(_(\"'%s' was deleted by the applypatch-msg hook\"),\n+\t\t\t\tam_path(state, \"final-commit\"));\n+\t}\n+\n+\treturn ret;\n+}\n+\n+/**\n  * Runs post-rewrite hook. Returns it exit code.\n  */\n static int run_post_rewrite_hook(const struct am_state *state)\n@@ -1434,6 +1455,9 @@ static void am_run(struct am_state *state)\n \t\twrite_author_script(state);\n \t\twrite_commit_msg(state);\n \n+\t\tif (run_applypatch_msg_hook(state))\n+\t\t\texit(1);\n+\n \t\tsay(state, stdout, _(\"Applying: %.*s\"), linelen(state->msg), state->msg);\n \n \t\tapply_status = run_apply(state, NULL);\n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265717","messageId":"1436278862-2638-36-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 35/44] builtin-am: invoke pre-applypatch hook","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:53Z","receivedAt":"2015-07-07T14:20:53Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"Since d1c5f2a (Add git-am, applymbox replacement., 2005-10-07),\ngit-am.sg will invoke the pre-applypatch hook after applying the patch\nto the index, but before a commit is made. Should the hook exit with a\nnon-zero status, git am will exit.\n\nRe-implement this in builtin/am.c.\n\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n builtin/am.c | 3 +++\n 1 file changed, 3 insertions(+)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex f856d3b..407775c 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -1374,6 +1374,9 @@ static void do_commit(const struct am_state *state)\n \tconst char *reflog_msg, *author;\n \tstruct strbuf sb = STRBUF_INIT;\n \n+\tif (run_hook_le(NULL, \"pre-applypatch\", NULL))\n+\t\texit(1);\n+\n \tif (write_cache_as_tree(tree, 0, NULL))\n \t\tdie(_(\"git write-tree failed to write a tree\"));\n \n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265722","messageId":"1436278862-2638-37-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 36/44] builtin-am: invoke post-applypatch hook","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:54Z","receivedAt":"2015-07-07T14:20:54Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"Since d1c5f2a (Add git-am, applymbox replacement., 2005-10-07),\ngit-am.sh will invoke the post-applypatch hook after the patch is\napplied and a commit is made. The exit code of the hook is ignored.\n\nRe-implement this in builtin/am.c.\n\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n builtin/am.c | 2 ++\n 1 file changed, 2 insertions(+)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex 407775c..fdaf0a7 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -1418,6 +1418,8 @@ static void do_commit(const struct am_state *state)\n \t\tfclose(fp);\n \t}\n \n+\trun_hook_le(NULL, \"post-applypatch\", NULL);\n+\n \tstrbuf_release(&sb);\n }\n \n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265721","messageId":"1436278862-2638-38-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 37/44] builtin-am: rerere support","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:55Z","receivedAt":"2015-07-07T14:20:55Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"git-am.sh will call git-rerere at the following events:\n\n* \"git rerere\" when a three-way merge fails to record the conflicted\n  automerge results. Since 8389b52 (git-rerere: reuse recorded resolve.,\n  2006-01-28)\n\n  * Since cb6020b (Teach --[no-]rerere-autoupdate option to merge,\n    revert and friends, 2009-12-04), git-am.sh supports the\n    --[no-]rerere-autoupdate option as well, and would pass it to\n    git-rerere.\n\n* \"git rerere\" when --resolved, to record the hand resolution. Since\n  f131dd4 (rerere: record (or avoid misrecording) resolved, skipped or\n  aborted rebase/am, 2006-12-08)\n\n* \"git rerere clear\" when --skip-ing. Since f131dd4 (rerere: record (or\n  avoid misrecording) resolved, skipped or aborted rebase/am,\n  2006-12-08)\n\n* \"git rerere clear\" when --abort-ing. Since 3e5057a (git am --abort,\n  2008-07-16)\n\nRe-implement the above in builtin/am.c.\n\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n builtin/am.c | 26 ++++++++++++++++++++++++++\n 1 file changed, 26 insertions(+)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex fdaf0a7..6b388de 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -24,6 +24,7 @@\n #include \"revision.h\"\n #include \"log-tree.h\"\n #include \"notes-utils.h\"\n+#include \"rerere.h\"\n \n /**\n  * Returns 1 if the file is empty or does not exist, 0 otherwise.\n@@ -128,6 +129,8 @@ struct am_state {\n \n \tint ignore_date;\n \n+\tint allow_rerere_autoupdate;\n+\n \tconst char *sign_commit;\n \n \tint rebasing;\n@@ -1352,6 +1355,7 @@ static int fall_back_threeway(const struct am_state *state, const char *index_pa\n \t\to.verbosity = 0;\n \n \tif (merge_recursive_generic(&o, our_tree, his_tree, 1, bases, &result)) {\n+\t\trerere(state->allow_rerere_autoupdate);\n \t\tfree(his_tree_name);\n \t\treturn error(_(\"Failed to merge in the changes.\"));\n \t}\n@@ -1551,6 +1555,8 @@ static void am_resolve(struct am_state *state)\n \t\tdie_user_resolve(state);\n \t}\n \n+\trerere(0);\n+\n \tdo_commit(state);\n \n \tam_next(state);\n@@ -1649,12 +1655,29 @@ static int clean_index(const unsigned char *head, const unsigned char *remote)\n }\n \n /**\n+ * Resets rerere's merge resolution metadata.\n+ */\n+static void am_rerere_clear(void)\n+{\n+\tstruct string_list merge_rr = STRING_LIST_INIT_DUP;\n+\tint fd = setup_rerere(&merge_rr, 0);\n+\n+\tif (fd < 0)\n+\t\treturn;\n+\n+\trerere_clear(&merge_rr);\n+\tstring_list_clear(&merge_rr, 1);\n+}\n+\n+/**\n  * Resume the current am session by skipping the current patch.\n  */\n static void am_skip(struct am_state *state)\n {\n \tunsigned char head[GIT_SHA1_RAWSZ];\n \n+\tam_rerere_clear();\n+\n \tif (get_sha1(\"HEAD\", head))\n \t\thashcpy(head, EMPTY_TREE_SHA1_BIN);\n \n@@ -1712,6 +1735,8 @@ static void am_abort(struct am_state *state)\n \t\treturn;\n \t}\n \n+\tam_rerere_clear();\n+\n \tcurr_branch = resolve_refdup(\"HEAD\", 0, curr_head, NULL);\n \thas_curr_head = !is_null_sha1(curr_head);\n \tif (!has_curr_head)\n@@ -1839,6 +1864,7 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \t\t\tN_(\"lie about committer date\")),\n \t\tOPT_BOOL(0, \"ignore-date\", &state.ignore_date,\n \t\t\tN_(\"use current timestamp for author date\")),\n+\t\tOPT_RERERE_AUTOUPDATE(&state.allow_rerere_autoupdate),\n \t\t{ OPTION_STRING, 'S', \"gpg-sign\", &state.sign_commit, N_(\"key-id\"),\n \t\t  N_(\"GPG-sign commits\"),\n \t\t  PARSE_OPT_OPTARG, NULL, (intptr_t) \"\" },\n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265718","messageId":"1436278862-2638-39-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 38/44] builtin-am: support and auto-detect StGit patches","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:56Z","receivedAt":"2015-07-07T14:20:56Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"Since c574e68 (git-am foreign patch support: StGIT support, 2009-05-27),\ngit-am.sh supported converting StGit patches into RFC2822 mail patches\nthat can be parsed with git-mailinfo.\n\nImplement this by introducing two functions in builtin/am.c:\nstgit_patch_to_mail() and split_mail_conv().\n\nstgit_patch_to_mail() is a callback function for split_mail_conv(), and\ncontains the logic for converting an StGit patch into an RFC2822 mail\npatch.\n\nsplit_mail_conv() implements the logic to go through each file in the\n`paths` list, reading from stdin where specified, and calls the callback\nfunction to write the converted patch to the corresponding output file\nin the state directory. This interface should be generic enough to\nsupport other foreign patch formats in the future.\n\nSince 15ced75 (git-am foreign patch support: autodetect some patch\nformats, 2009-05-27), git-am.sh is able to auto-detect StGit patches.\nRe-implement this in builtin/am.c.\n\nHelped-by: Eric Sunshine <sunshine@sunshineco.com>\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n\nNotes:\n    v5\n    \n    * Rewrite of the loop in str_isspace() to be clearer.\n\n builtin/am.c | 132 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-\n 1 file changed, 131 insertions(+), 1 deletion(-)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex 6b388de..0bb1875 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -65,9 +65,22 @@ static int linelen(const char *msg)\n \treturn strchrnul(msg, '\\n') - msg;\n }\n \n+/**\n+ * Returns true if `str` consists of only whitespace, false otherwise.\n+ */\n+static int str_isspace(const char *str)\n+{\n+\tfor (; *str; str++)\n+\t\tif (!isspace(*str))\n+\t\t\treturn 0;\n+\n+\treturn 1;\n+}\n+\n enum patch_format {\n \tPATCH_FORMAT_UNKNOWN = 0,\n-\tPATCH_FORMAT_MBOX\n+\tPATCH_FORMAT_MBOX,\n+\tPATCH_FORMAT_STGIT\n };\n \n enum keep_type {\n@@ -646,6 +659,8 @@ static int detect_patch_format(const char **paths)\n {\n \tenum patch_format ret = PATCH_FORMAT_UNKNOWN;\n \tstruct strbuf l1 = STRBUF_INIT;\n+\tstruct strbuf l2 = STRBUF_INIT;\n+\tstruct strbuf l3 = STRBUF_INIT;\n \tFILE *fp;\n \n \t/*\n@@ -671,6 +686,23 @@ static int detect_patch_format(const char **paths)\n \t\tgoto done;\n \t}\n \n+\tstrbuf_reset(&l2);\n+\tstrbuf_getline_crlf(&l2, fp);\n+\tstrbuf_reset(&l3);\n+\tstrbuf_getline_crlf(&l3, fp);\n+\n+\t/*\n+\t * If the second line is empty and the third is a From, Author or Date\n+\t * entry, this is likely an StGit patch.\n+\t */\n+\tif (l1.len && !l2.len &&\n+\t\t(starts_with(l3.buf, \"From:\") ||\n+\t\t starts_with(l3.buf, \"Author:\") ||\n+\t\t starts_with(l3.buf, \"Date:\"))) {\n+\t\tret = PATCH_FORMAT_STGIT;\n+\t\tgoto done;\n+\t}\n+\n \tif (l1.len && is_mail(fp)) {\n \t\tret = PATCH_FORMAT_MBOX;\n \t\tgoto done;\n@@ -711,6 +743,100 @@ static int split_mail_mbox(struct am_state *state, const char **paths, int keep_\n }\n \n /**\n+ * Callback signature for split_mail_conv(). The foreign patch should be\n+ * read from `in`, and the converted patch (in RFC2822 mail format) should be\n+ * written to `out`. Return 0 on success, or -1 on failure.\n+ */\n+typedef int (*mail_conv_fn)(FILE *out, FILE *in, int keep_cr);\n+\n+/**\n+ * Calls `fn` for each file in `paths` to convert the foreign patch to the\n+ * RFC2822 mail format suitable for parsing with git-mailinfo.\n+ *\n+ * Returns 0 on success, -1 on failure.\n+ */\n+static int split_mail_conv(mail_conv_fn fn, struct am_state *state,\n+\t\t\tconst char **paths, int keep_cr)\n+{\n+\tstatic const char *stdin_only[] = {\"-\", NULL};\n+\tint i;\n+\n+\tif (!*paths)\n+\t\tpaths = stdin_only;\n+\n+\tfor (i = 0; *paths; paths++, i++) {\n+\t\tFILE *in, *out;\n+\t\tconst char *mail;\n+\t\tint ret;\n+\n+\t\tif (!strcmp(*paths, \"-\"))\n+\t\t\tin = stdin;\n+\t\telse\n+\t\t\tin = fopen(*paths, \"r\");\n+\n+\t\tif (!in)\n+\t\t\treturn error(_(\"could not open '%s' for reading: %s\"),\n+\t\t\t\t\t*paths, strerror(errno));\n+\n+\t\tmail = mkpath(\"%s/%0*d\", state->dir, state->prec, i + 1);\n+\n+\t\tout = fopen(mail, \"w\");\n+\t\tif (!out)\n+\t\t\treturn error(_(\"could not open '%s' for writing: %s\"),\n+\t\t\t\t\tmail, strerror(errno));\n+\n+\t\tret = fn(out, in, keep_cr);\n+\n+\t\tfclose(out);\n+\t\tfclose(in);\n+\n+\t\tif (ret)\n+\t\t\treturn error(_(\"could not parse patch '%s'\"), *paths);\n+\t}\n+\n+\tstate->cur = 1;\n+\tstate->last = i;\n+\treturn 0;\n+}\n+\n+/**\n+ * A split_mail_conv() callback that converts an StGit patch to an RFC2822\n+ * message suitable for parsing with git-mailinfo.\n+ */\n+static int stgit_patch_to_mail(FILE *out, FILE *in, int keep_cr)\n+{\n+\tstruct strbuf sb = STRBUF_INIT;\n+\tint subject_printed = 0;\n+\n+\twhile (!strbuf_getline(&sb, in, '\\n')) {\n+\t\tconst char *str;\n+\n+\t\tif (str_isspace(sb.buf))\n+\t\t\tcontinue;\n+\t\telse if (skip_prefix(sb.buf, \"Author:\", &str))\n+\t\t\tfprintf(out, \"From:%s\\n\", str);\n+\t\telse if (starts_with(sb.buf, \"From\") || starts_with(sb.buf, \"Date\"))\n+\t\t\tfprintf(out, \"%s\\n\", sb.buf);\n+\t\telse if (!subject_printed) {\n+\t\t\tfprintf(out, \"Subject: %s\\n\", sb.buf);\n+\t\t\tsubject_printed = 1;\n+\t\t} else {\n+\t\t\tfprintf(out, \"\\n%s\\n\", sb.buf);\n+\t\t\tbreak;\n+\t\t}\n+\t}\n+\n+\tstrbuf_reset(&sb);\n+\twhile (strbuf_fread(&sb, 8192, in) > 0) {\n+\t\tfwrite(sb.buf, 1, sb.len, out);\n+\t\tstrbuf_reset(&sb);\n+\t}\n+\n+\tstrbuf_release(&sb);\n+\treturn 0;\n+}\n+\n+/**\n  * Splits a list of files/directories into individual email patches. Each path\n  * in `paths` must be a file/directory that is formatted according to\n  * `patch_format`.\n@@ -738,6 +864,8 @@ static int split_mail(struct am_state *state, enum patch_format patch_format,\n \tswitch (patch_format) {\n \tcase PATCH_FORMAT_MBOX:\n \t\treturn split_mail_mbox(state, paths, keep_cr);\n+\tcase PATCH_FORMAT_STGIT:\n+\t\treturn split_mail_conv(stgit_patch_to_mail, state, paths, keep_cr);\n \tdefault:\n \t\tdie(\"BUG: invalid patch_format\");\n \t}\n@@ -1768,6 +1896,8 @@ static int parse_opt_patchformat(const struct option *opt, const char *arg, int\n \n \tif (!strcmp(arg, \"mbox\"))\n \t\t*opt_value = PATCH_FORMAT_MBOX;\n+\telse if (!strcmp(arg, \"stgit\"))\n+\t\t*opt_value = PATCH_FORMAT_STGIT;\n \telse\n \t\treturn error(_(\"Invalid value for --patch-format: %s\"), arg);\n \treturn 0;\n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265720","messageId":"1436278862-2638-40-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 39/44] builtin-am: support and auto-detect StGit series files","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:57Z","receivedAt":"2015-07-07T14:20:57Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"Since c574e68 (git-am foreign patch support: StGIT support, 2009-05-27),\ngit-am.sh is able to read a single StGit series file and, for each StGit\npatch listed in the file, convert the StGit patch into a RFC2822 mail\npatch suitable for parsing with git-mailinfo, and queue them in the\nstate directory for applying.\n\nSince 15ced75 (git-am foreign patch support: autodetect some patch\nformats, 2009-05-27), git-am.sh is able to auto-detect StGit series\nfiles by checking to see if the file starts with the string:\n\n\t# This series applies on GIT commit\n\nRe-implement the above in builtin/am.c.\n\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n builtin/am.c | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-\n 1 file changed, 58 insertions(+), 1 deletion(-)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex 0bb1875..7a56005 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -80,7 +80,8 @@ static int str_isspace(const char *str)\n enum patch_format {\n \tPATCH_FORMAT_UNKNOWN = 0,\n \tPATCH_FORMAT_MBOX,\n-\tPATCH_FORMAT_STGIT\n+\tPATCH_FORMAT_STGIT,\n+\tPATCH_FORMAT_STGIT_SERIES\n };\n \n enum keep_type {\n@@ -686,6 +687,11 @@ static int detect_patch_format(const char **paths)\n \t\tgoto done;\n \t}\n \n+\tif (starts_with(l1.buf, \"# This series applies on GIT commit\")) {\n+\t\tret = PATCH_FORMAT_STGIT_SERIES;\n+\t\tgoto done;\n+\t}\n+\n \tstrbuf_reset(&l2);\n \tstrbuf_getline_crlf(&l2, fp);\n \tstrbuf_reset(&l3);\n@@ -837,6 +843,53 @@ static int stgit_patch_to_mail(FILE *out, FILE *in, int keep_cr)\n }\n \n /**\n+ * This function only supports a single StGit series file in `paths`.\n+ *\n+ * Given an StGit series file, converts the StGit patches in the series into\n+ * RFC2822 messages suitable for parsing with git-mailinfo, and queues them in\n+ * the state directory.\n+ *\n+ * Returns 0 on success, -1 on failure.\n+ */\n+static int split_mail_stgit_series(struct am_state *state, const char **paths,\n+\t\t\t\t\tint keep_cr)\n+{\n+\tconst char *series_dir;\n+\tchar *series_dir_buf;\n+\tFILE *fp;\n+\tstruct argv_array patches = ARGV_ARRAY_INIT;\n+\tstruct strbuf sb = STRBUF_INIT;\n+\tint ret;\n+\n+\tif (!paths[0] || paths[1])\n+\t\treturn error(_(\"Only one StGIT patch series can be applied at once\"));\n+\n+\tseries_dir_buf = xstrdup(*paths);\n+\tseries_dir = dirname(series_dir_buf);\n+\n+\tfp = fopen(*paths, \"r\");\n+\tif (!fp)\n+\t\treturn error(_(\"could not open '%s' for reading: %s\"), *paths,\n+\t\t\t\tstrerror(errno));\n+\n+\twhile (!strbuf_getline(&sb, fp, '\\n')) {\n+\t\tif (*sb.buf == '#')\n+\t\t\tcontinue; /* skip comment lines */\n+\n+\t\targv_array_push(&patches, mkpath(\"%s/%s\", series_dir, sb.buf));\n+\t}\n+\n+\tfclose(fp);\n+\tstrbuf_release(&sb);\n+\tfree(series_dir_buf);\n+\n+\tret = split_mail_conv(stgit_patch_to_mail, state, patches.argv, keep_cr);\n+\n+\targv_array_clear(&patches);\n+\treturn ret;\n+}\n+\n+/**\n  * Splits a list of files/directories into individual email patches. Each path\n  * in `paths` must be a file/directory that is formatted according to\n  * `patch_format`.\n@@ -866,6 +919,8 @@ static int split_mail(struct am_state *state, enum patch_format patch_format,\n \t\treturn split_mail_mbox(state, paths, keep_cr);\n \tcase PATCH_FORMAT_STGIT:\n \t\treturn split_mail_conv(stgit_patch_to_mail, state, paths, keep_cr);\n+\tcase PATCH_FORMAT_STGIT_SERIES:\n+\t\treturn split_mail_stgit_series(state, paths, keep_cr);\n \tdefault:\n \t\tdie(\"BUG: invalid patch_format\");\n \t}\n@@ -1898,6 +1953,8 @@ static int parse_opt_patchformat(const struct option *opt, const char *arg, int\n \t\t*opt_value = PATCH_FORMAT_MBOX;\n \telse if (!strcmp(arg, \"stgit\"))\n \t\t*opt_value = PATCH_FORMAT_STGIT;\n+\telse if (!strcmp(arg, \"stgit-series\"))\n+\t\t*opt_value = PATCH_FORMAT_STGIT_SERIES;\n \telse\n \t\treturn error(_(\"Invalid value for --patch-format: %s\"), arg);\n \treturn 0;\n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265724","messageId":"1436278862-2638-41-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 40/44] builtin-am: support and auto-detect mercurial patches","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:58Z","receivedAt":"2015-07-07T14:20:58Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"Since 0cfd112 (am: preliminary support for hg patches, 2011-08-29),\ngit-am.sh could convert mercurial patches to an RFC2822 mail patch\nsuitable for parsing with git-mailinfo, and queue them in the state\ndirectory for application.\n\nSince 15ced75 (git-am foreign patch support: autodetect some patch\nformats, 2009-05-27), git-am.sh was able to auto-detect mercurial\npatches by checking if the file begins with the line:\n\n\t# HG changeset patch\n\nRe-implement the above in builtin/am.c.\n\nHelped-by: Stefan Beller <sbeller@google.com>\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n\nNotes:\n    v5\n    \n    * v4 had a math fail in the timestamp conversion. Fixed the math.\n    \n    * In C89, it is implementation defined whether integer division rounds\n      towards 0 or towards negative infinity. To be safe, we do the\n      timestamp conversion with positive integers only, and then negate the\n      result appropriately.\n\n builtin/am.c | 74 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-\n 1 file changed, 73 insertions(+), 1 deletion(-)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex 7a56005..55962c6 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -81,7 +81,8 @@ enum patch_format {\n \tPATCH_FORMAT_UNKNOWN = 0,\n \tPATCH_FORMAT_MBOX,\n \tPATCH_FORMAT_STGIT,\n-\tPATCH_FORMAT_STGIT_SERIES\n+\tPATCH_FORMAT_STGIT_SERIES,\n+\tPATCH_FORMAT_HG\n };\n \n enum keep_type {\n@@ -692,6 +693,11 @@ static int detect_patch_format(const char **paths)\n \t\tgoto done;\n \t}\n \n+\tif (!strcmp(l1.buf, \"# HG changeset patch\")) {\n+\t\tret = PATCH_FORMAT_HG;\n+\t\tgoto done;\n+\t}\n+\n \tstrbuf_reset(&l2);\n \tstrbuf_getline_crlf(&l2, fp);\n \tstrbuf_reset(&l3);\n@@ -890,6 +896,68 @@ static int split_mail_stgit_series(struct am_state *state, const char **paths,\n }\n \n /**\n+ * A split_patches_conv() callback that converts a mercurial patch to a RFC2822\n+ * message suitable for parsing with git-mailinfo.\n+ */\n+static int hg_patch_to_mail(FILE *out, FILE *in, int keep_cr)\n+{\n+\tstruct strbuf sb = STRBUF_INIT;\n+\n+\twhile (!strbuf_getline(&sb, in, '\\n')) {\n+\t\tconst char *str;\n+\n+\t\tif (skip_prefix(sb.buf, \"# User \", &str))\n+\t\t\tfprintf(out, \"From: %s\\n\", str);\n+\t\telse if (skip_prefix(sb.buf, \"# Date \", &str)) {\n+\t\t\tunsigned long timestamp;\n+\t\t\tlong tz, tz2;\n+\t\t\tchar *end;\n+\n+\t\t\terrno = 0;\n+\t\t\ttimestamp = strtoul(str, &end, 10);\n+\t\t\tif (errno)\n+\t\t\t\treturn error(_(\"invalid timestamp\"));\n+\n+\t\t\tif (!skip_prefix(end, \" \", &str))\n+\t\t\t\treturn error(_(\"invalid Date line\"));\n+\n+\t\t\terrno = 0;\n+\t\t\ttz = strtol(str, &end, 10);\n+\t\t\tif (errno)\n+\t\t\t\treturn error(_(\"invalid timezone offset\"));\n+\n+\t\t\tif (*end)\n+\t\t\t\treturn error(_(\"invalid Date line\"));\n+\n+\t\t\t/*\n+\t\t\t * mercurial's timezone is in seconds west of UTC,\n+\t\t\t * however git's timezone is in hours + minutes east of\n+\t\t\t * UTC. Convert it.\n+\t\t\t */\n+\t\t\ttz2 = labs(tz) / 3600 * 100 + labs(tz) % 3600 / 60;\n+\t\t\tif (tz > 0)\n+\t\t\t\ttz2 = -tz2;\n+\n+\t\t\tfprintf(out, \"Date: %s\\n\", show_date(timestamp, tz2, DATE_RFC2822));\n+\t\t} else if (starts_with(sb.buf, \"# \")) {\n+\t\t\tcontinue;\n+\t\t} else {\n+\t\t\tfprintf(out, \"\\n%s\\n\", sb.buf);\n+\t\t\tbreak;\n+\t\t}\n+\t}\n+\n+\tstrbuf_reset(&sb);\n+\twhile (strbuf_fread(&sb, 8192, in) > 0) {\n+\t\tfwrite(sb.buf, 1, sb.len, out);\n+\t\tstrbuf_reset(&sb);\n+\t}\n+\n+\tstrbuf_release(&sb);\n+\treturn 0;\n+}\n+\n+/**\n  * Splits a list of files/directories into individual email patches. Each path\n  * in `paths` must be a file/directory that is formatted according to\n  * `patch_format`.\n@@ -921,6 +989,8 @@ static int split_mail(struct am_state *state, enum patch_format patch_format,\n \t\treturn split_mail_conv(stgit_patch_to_mail, state, paths, keep_cr);\n \tcase PATCH_FORMAT_STGIT_SERIES:\n \t\treturn split_mail_stgit_series(state, paths, keep_cr);\n+\tcase PATCH_FORMAT_HG:\n+\t\treturn split_mail_conv(hg_patch_to_mail, state, paths, keep_cr);\n \tdefault:\n \t\tdie(\"BUG: invalid patch_format\");\n \t}\n@@ -1955,6 +2025,8 @@ static int parse_opt_patchformat(const struct option *opt, const char *arg, int\n \t\t*opt_value = PATCH_FORMAT_STGIT;\n \telse if (!strcmp(arg, \"stgit-series\"))\n \t\t*opt_value = PATCH_FORMAT_STGIT_SERIES;\n+\telse if (!strcmp(arg, \"hg\"))\n+\t\t*opt_value = PATCH_FORMAT_HG;\n \telse\n \t\treturn error(_(\"Invalid value for --patch-format: %s\"), arg);\n \treturn 0;\n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265726","messageId":"1436278862-2638-42-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 41/44] builtin-am: implement -i/--interactive","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:20:59Z","receivedAt":"2015-07-07T14:20:59Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"Since d1c5f2a (Add git-am, applymbox replacement., 2005-10-07),\ngit-am.sh supported the --interactive mode. After parsing the patch mail\nand extracting the patch, commit message and authorship info, an\ninteractive session will begin that allows the user to choose between:\n\n* applying the patch\n\n* applying the patch and all subsequent patches (by disabling\n  interactive mode in subsequent patches)\n\n* skipping the patch\n\n* editing the commit message\n\nSince f89ad67 (Add [v]iew patch in git-am interactive., 2005-10-25),\ngit-am.sh --interactive also supported viewing the patch to be applied.\n\nWhen --resolved-ing in --interactive mode, we need to take care to\nupdate the patch with the contents of the index, such that the correct\npatch will be displayed when the patch is viewed in interactive mode.\n\nRe-implement the above in builtin/am.c\n\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n\nNotes:\n    Can't be tested because even with test_terminal isatty(0) still returns\n    false.\n\n builtin/am.c | 106 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-\n 1 file changed, 105 insertions(+), 1 deletion(-)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex 55962c6..2866328 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -25,6 +25,7 @@\n #include \"log-tree.h\"\n #include \"notes-utils.h\"\n #include \"rerere.h\"\n+#include \"prompt.h\"\n \n /**\n  * Returns 1 if the file is empty or does not exist, 0 otherwise.\n@@ -118,6 +119,8 @@ struct am_state {\n \t/* number of digits in patch filename */\n \tint prec;\n \n+\tint interactive;\n+\n \tint threeway;\n \n \tint quiet;\n@@ -1212,7 +1215,7 @@ static void NORETURN die_user_resolve(const struct am_state *state)\n \tif (state->resolvemsg) {\n \t\tprintf_ln(\"%s\", state->resolvemsg);\n \t} else {\n-\t\tconst char *cmdline = \"git am\";\n+\t\tconst char *cmdline = state->interactive ? \"git am -i\" : \"git am\";\n \n \t\tprintf_ln(_(\"When you have resolved this problem, run \\\"%s --continue\\\".\"), cmdline);\n \t\tprintf_ln(_(\"If you prefer to skip this patch, run \\\"%s --skip\\\" instead.\"), cmdline);\n@@ -1445,6 +1448,36 @@ static void write_commit_patch(const struct am_state *state, struct commit *comm\n }\n \n /**\n+ * Writes the diff of the index against HEAD as a patch to the state\n+ * directory's \"patch\" file.\n+ */\n+static void write_index_patch(const struct am_state *state)\n+{\n+\tstruct tree *tree;\n+\tunsigned char head[GIT_SHA1_RAWSZ];\n+\tstruct rev_info rev_info;\n+\tFILE *fp;\n+\n+\tif (!get_sha1_tree(\"HEAD\", head))\n+\t\ttree = lookup_tree(head);\n+\telse\n+\t\ttree = lookup_tree(EMPTY_TREE_SHA1_BIN);\n+\n+\tfp = xfopen(am_path(state, \"patch\"), \"w\");\n+\tinit_revisions(&rev_info, NULL);\n+\trev_info.diff = 1;\n+\trev_info.disable_stdin = 1;\n+\trev_info.no_commit_id = 1;\n+\trev_info.diffopt.output_format = DIFF_FORMAT_PATCH;\n+\trev_info.diffopt.use_color = 0;\n+\trev_info.diffopt.file = fp;\n+\trev_info.diffopt.close_file = 1;\n+\tadd_pending_object(&rev_info, &tree->object, \"\");\n+\tdiff_setup_done(&rev_info.diffopt);\n+\trun_diff_index(&rev_info, 1);\n+}\n+\n+/**\n  * Like parse_mail(), but parses the mail by looking up its commit ID\n  * directly. This is used in --rebasing mode to bypass git-mailinfo's munging\n  * of patches.\n@@ -1681,6 +1714,65 @@ static void do_commit(const struct am_state *state)\n }\n \n /**\n+ * Interactively prompt the user on whether the current patch should be\n+ * applied.\n+ *\n+ * Returns 0 if the user chooses to apply the patch, 1 if the user chooses to\n+ * skip it.\n+ */\n+static int do_interactive(struct am_state *state)\n+{\n+\tassert(state->msg);\n+\n+\tif (!isatty(0))\n+\t\tdie(_(\"cannot be interactive without stdin connected to a terminal.\"));\n+\n+\tfor (;;) {\n+\t\tconst char *reply;\n+\n+\t\tputs(_(\"Commit Body is:\"));\n+\t\tputs(\"--------------------------\");\n+\t\tprintf(\"%s\", state->msg);\n+\t\tputs(\"--------------------------\");\n+\n+\t\t/*\n+\t\t * TRANSLATORS: Make sure to include [y], [n], [e], [v] and [a]\n+\t\t * in your translation. The program will only accept English\n+\t\t * input at this point.\n+\t\t */\n+\t\treply = git_prompt(_(\"Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all: \"), PROMPT_ECHO);\n+\n+\t\tif (!reply) {\n+\t\t\tcontinue;\n+\t\t} else if (*reply == 'y' || *reply == 'Y') {\n+\t\t\treturn 0;\n+\t\t} else if (*reply == 'a' || *reply == 'A') {\n+\t\t\tstate->interactive = 0;\n+\t\t\treturn 0;\n+\t\t} else if (*reply == 'n' || *reply == 'N') {\n+\t\t\treturn 1;\n+\t\t} else if (*reply == 'e' || *reply == 'E') {\n+\t\t\tstruct strbuf msg = STRBUF_INIT;\n+\n+\t\t\tif (!launch_editor(am_path(state, \"final-commit\"), &msg, NULL)) {\n+\t\t\t\tfree(state->msg);\n+\t\t\t\tstate->msg = strbuf_detach(&msg, &state->msg_len);\n+\t\t\t}\n+\t\t\tstrbuf_release(&msg);\n+\t\t} else if (*reply == 'v' || *reply == 'V') {\n+\t\t\tconst char *pager = git_pager(1);\n+\t\t\tstruct child_process cp = CHILD_PROCESS_INIT;\n+\n+\t\t\tif (!pager)\n+\t\t\t\tpager = \"cat\";\n+\t\t\targv_array_push(&cp.args, pager);\n+\t\t\targv_array_push(&cp.args, am_path(state, \"patch\"));\n+\t\t\trun_command(&cp);\n+\t\t}\n+\t}\n+}\n+\n+/**\n  * Applies all queued mail.\n  */\n static void am_run(struct am_state *state)\n@@ -1717,6 +1809,9 @@ static void am_run(struct am_state *state)\n \t\twrite_author_script(state);\n \t\twrite_commit_msg(state);\n \n+\t\tif (state->interactive && do_interactive(state))\n+\t\t\tgoto next;\n+\n \t\tif (run_applypatch_msg_hook(state))\n \t\t\texit(1);\n \n@@ -1808,10 +1903,17 @@ static void am_resolve(struct am_state *state)\n \t\tdie_user_resolve(state);\n \t}\n \n+\tif (state->interactive) {\n+\t\twrite_index_patch(state);\n+\t\tif (do_interactive(state))\n+\t\t\tgoto next;\n+\t}\n+\n \trerere(0);\n \n \tdo_commit(state);\n \n+next:\n \tam_next(state);\n \tam_run(state);\n }\n@@ -2053,6 +2155,8 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \t};\n \n \tstruct option options[] = {\n+\t\tOPT_BOOL('i', \"interactive\", &state.interactive,\n+\t\t\tN_(\"run interactively\")),\n \t\tOPT_BOOL('3', \"3way\", &state.threeway,\n \t\t\tN_(\"allow fall back on 3way merging if needed\")),\n \t\tOPT__QUIET(&state.quiet, N_(\"be quiet\")),\n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265727","messageId":"1436278862-2638-43-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 42/44] builtin-am: implement legacy -b/--binary option","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:21:00Z","receivedAt":"2015-07-07T14:21:00Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"The -b/--binary option was initially implemented in 087b674 (git-am:\n--binary; document --resume and --binary., 2005-11-16). The option will\npass the --binary flag to git-apply to allow it to apply binary patches.\n\nHowever, in 2b6eef9 (Make apply --binary a no-op., 2006-09-06), --binary\nwas been made a no-op in git-apply. Following that, since cb3a160\n(git-am: ignore --binary option, 2008-08-09), the --binary option in\ngit-am is ignored as well.\n\nIn 6c15a1c (am: officially deprecate -b/--binary option, 2012-03-13),\nthe --binary option was tweaked to its present behavior: when set, the\nmessage:\n\n\tThe -b/--binary option has been a no-op for long time, and it\n\twill be removed. Please do not use it anymore.\n\nwill be printed.\n\nRe-implement this in builtin/am.c.\n\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n builtin/am.c | 7 +++++++\n 1 file changed, 7 insertions(+)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex 2866328..ad07ba4 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -2144,6 +2144,7 @@ enum resume_mode {\n int cmd_am(int argc, const char **argv, const char *prefix)\n {\n \tstruct am_state state;\n+\tint binary = -1;\n \tint keep_cr = -1;\n \tint patch_format = PATCH_FORMAT_UNKNOWN;\n \tenum resume_mode resume = RESUME_FALSE;\n@@ -2157,6 +2158,8 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \tstruct option options[] = {\n \t\tOPT_BOOL('i', \"interactive\", &state.interactive,\n \t\t\tN_(\"run interactively\")),\n+\t\tOPT_HIDDEN_BOOL('b', \"binary\", &binary,\n+\t\t\tN_(\"(historical option -- no-op\")),\n \t\tOPT_BOOL('3', \"3way\", &state.threeway,\n \t\t\tN_(\"allow fall back on 3way merging if needed\")),\n \t\tOPT__QUIET(&state.quiet, N_(\"be quiet\")),\n@@ -2257,6 +2260,10 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \n \targc = parse_options(argc, argv, prefix, options, usage, 0);\n \n+\tif (binary >= 0)\n+\t\tfprintf_ln(stderr, _(\"The -b/--binary option has been a no-op for long time, and\\n\"\n+\t\t\t\t\"it will be removed. Please do not use it anymore.\"));\n+\n \tif (read_index_preload(&the_index, NULL) < 0)\n \t\tdie(_(\"failed to read the index\"));\n \n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265728","messageId":"1436278862-2638-44-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 43/44] builtin-am: check for valid committer ident","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:21:01Z","receivedAt":"2015-07-07T14:21:01Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"When commit_tree() is called, if the user does not have an explicit\ncommitter ident configured, it will attempt to construct a default\ncommitter ident based on the user's and system's info (e.g. gecos field,\nhostname etc.) However, if a default committer ident is unable to be\nconstructed, commit_tree() will die(), but at this point of git-am's\nexecution, there will already be changes made to the index and work\ntree.\n\nThis can be confusing to new users, and as such since d64e6b0 (Keep\nPorcelainish from failing by broken ident after making changes.,\n2006-02-18) git-am.sh will check to see if the committer ident has been\nconfigured, or a default one can be constructed, before even starting to\napply patches.\n\nRe-implement this in builtin/am.c.\n\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n\nNotes:\n    v5\n    \n    * modified commit message\n\n builtin/am.c | 3 +++\n 1 file changed, 3 insertions(+)\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex ad07ba4..a0982d9 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -2264,6 +2264,9 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \t\tfprintf_ln(stderr, _(\"The -b/--binary option has been a no-op for long time, and\\n\"\n \t\t\t\t\"it will be removed. Please do not use it anymore.\"));\n \n+\t/* Ensure a valid committer ident can be constructed */\n+\tgit_committer_info(IDENT_STRICT);\n+\n \tif (read_index_preload(&the_index, NULL) < 0)\n \t\tdie(_(\"failed to read the index\"));\n \n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265732","messageId":"1436278862-2638-45-git-send-email-pyokagan@gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"[PATCH v5 44/44] builtin-am: remove redirection to git-am.sh","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T14:21:02Z","receivedAt":"2015-07-07T14:21:02Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"At the beginning of the rewrite of git-am.sh to C, in order to not break\nexisting test scripts that depended on a functional git-am, a\nredirection to git-am.sh was introduced that would activate if the\nenvironment variable _GIT_USE_BUILTIN_AM was not defined.\n\nNow that all of git-am.sh's functionality has been re-implemented in\nbuiltin/am.c, remove this redirection, and retire git-am.sh into\ncontrib/examples/.\n\nSigned-off-by: Paul Tan <pyokagan@gmail.com>\n---\n Makefile                                |  1 -\n builtin/am.c                            | 15 ---------------\n git-am.sh => contrib/examples/git-am.sh |  0\n git.c                                   |  7 +------\n 4 files changed, 1 insertion(+), 22 deletions(-)\n rename git-am.sh => contrib/examples/git-am.sh (100%)\n\ndiff --git a/Makefile b/Makefile\nindex ff9bdc0..005d771 100644\n--- a/Makefile\n+++ b/Makefile\n@@ -466,7 +466,6 @@ TEST_PROGRAMS_NEED_X =\n # interactive shell sessions without exporting it.\n unexport CDPATH\n \n-SCRIPT_SH += git-am.sh\n SCRIPT_SH += git-bisect.sh\n SCRIPT_SH += git-difftool--helper.sh\n SCRIPT_SH += git-filter-branch.sh\ndiff --git a/builtin/am.c b/builtin/am.c\nindex a0982d9..c548129 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -2239,21 +2239,6 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \t\tOPT_END()\n \t};\n \n-\t/*\n-\t * NEEDSWORK: Once all the features of git-am.sh have been\n-\t * re-implemented in builtin/am.c, this preamble can be removed.\n-\t */\n-\tif (!getenv(\"_GIT_USE_BUILTIN_AM\")) {\n-\t\tconst char *path = mkpath(\"%s/git-am\", git_exec_path());\n-\n-\t\tif (sane_execvp(path, (char **)argv) < 0)\n-\t\t\tdie_errno(\"could not exec %s\", path);\n-\t} else {\n-\t\tprefix = setup_git_directory();\n-\t\ttrace_repo_setup(prefix);\n-\t\tsetup_work_tree();\n-\t}\n-\n \tgit_config(git_default_config, NULL);\n \n \tam_state_init(&state, git_path(\"rebase-apply\"));\ndiff --git a/git-am.sh b/contrib/examples/git-am.sh\nsimilarity index 100%\nrename from git-am.sh\nrename to contrib/examples/git-am.sh\ndiff --git a/git.c b/git.c\nindex e84e1a1..8420e43 100644\n--- a/git.c\n+++ b/git.c\n@@ -370,12 +370,7 @@ static int run_builtin(struct cmd_struct *p, int argc, const char **argv)\n \n static struct cmd_struct commands[] = {\n \t{ \"add\", cmd_add, RUN_SETUP | NEED_WORK_TREE },\n-\t/*\n-\t * NEEDSWORK: Once the redirection to git-am.sh in builtin/am.c has\n-\t * been removed, this entry should be changed to\n-\t * RUN_SETUP | NEED_WORK_TREE\n-\t */\n-\t{ \"am\", cmd_am },\n+\t{ \"am\", cmd_am, RUN_SETUP | NEED_WORK_TREE },\n \t{ \"annotate\", cmd_annotate, RUN_SETUP },\n \t{ \"apply\", cmd_apply, RUN_SETUP_GENTLY },\n \t{ \"archive\", cmd_archive },\n-- \n2.5.0.rc1.76.gf60a929\n"},{"id":"265760","messageId":"xmqqvbdv3imw.fsf@gitster.dls.corp.google.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"Re: [PATCH v5 00/44] Make git-am a builtin","fromName":"Junio C Hamano","fromEmail":"gitster@pobox.com","sentAt":"2015-07-07T18:52:23Z","receivedAt":"2015-07-07T18:52:23Z","isPatch":true,"sender":{"key":"gitster@pobox.com","avatar":"https://avatars.githubusercontent.com/u/54884?v=4"},"body":"Paul Tan <pyokagan@gmail.com> writes:\n\n> This patch series depends on pt/pull-builtin.\n>\n> This is a re-roll of [v4]. Thanks Torsten, Stefan, Junio for the reviews last\n> round. Interdiff below.\n>\n> Previous versions:\n>\n> [WIP v1] http://thread.gmane.org/gmane.comp.version-control.git/270048\n> [WIP v2] http://thread.gmane.org/gmane.comp.version-control.git/271381\n> [WIP v3] http://thread.gmane.org/gmane.comp.version-control.git/271967\n> [v4] http://thread.gmane.org/gmane.comp.version-control.git/272876\n>\n> git-am is a commonly used command for applying a series of patches from a\n> mailbox to the current branch. Currently, it is implemented by the shell script\n> git-am.sh. However, compared to C, shell scripts have certain deficiencies:\n> they need to spawn a lot of processes, introduce a lot of dependencies and\n> cannot take advantage of git's internal caches.\n>\n> This patch series rewrites git-am.sh into optimized C builtin/am.c, and is\n> part of my GSoC project to rewrite git-pull and git-am into C builtins[1].\n>\n> [1] https://gist.github.com/pyokagan/1b7b0d1f4dab6ba3cef1\n\nIs it really a rewrite into \"optimized C\", or just \"C\"?  I suspect\nit is the latter.\n\nThis seems to apply cleanly to 'master' but fails to compile, as it\ndepends on some new stuff that are not even in 'next' yet, e.g.\nargv_array_pushv() that is from pt/pull-builtin, and it does not\napply cleanly on top of that branch, either.\n\nI'll see what's the cleanest way to queue this would be.  Perhaps\nmerge pt/builtin-pull on a copy of 'master' and then apply these, or\nsomething like that.\n\nThanks.\n"},{"id":"265762","messageId":"CACRoPnQdSaK0vWP=Qf9vR4W2HJQkSdSp4Wqbb4VPV6Bs33=nuw@mail.gmail.com","threadId":"39799","inReplyTo":"xmqqvbdv3imw.fsf@gitster.dls.corp.google.com","subject":"Re: [PATCH v5 00/44] Make git-am a builtin","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-07T19:25:12Z","receivedAt":"2015-07-07T19:25:12Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"On Wed, Jul 8, 2015 at 2:52 AM, Junio C Hamano <gitster@pobox.com> wrote:\n> Paul Tan <pyokagan@gmail.com> writes:\n>> This patch series rewrites git-am.sh into optimized C builtin/am.c, and is\n>> part of my GSoC project to rewrite git-pull and git-am into C builtins[1].\n>>\n>> [1] https://gist.github.com/pyokagan/1b7b0d1f4dab6ba3cef1\n>\n> Is it really a rewrite into \"optimized C\", or just \"C\"?  I suspect\n> it is the latter.\n\nWell, \"optimized\" in comparison to the shell script ;-) We don't\nreplicate the shell script in its entirety, but optimize the code\nwhere it is obvious and sensible. It's not the \"most optimized\" (and I\nwill gladly accept any suggestions where there are obvious\noptimizations to be made), but I do consider it an improvement in\nterms of efficiency, while keeping the overall structure of the code\nclose to the shell script for easy review.\n\nI'll remove the word though, because it's true that the main purpose\nof this patch series is to \"make it work\" first.\n\n> This seems to apply cleanly to 'master' but fails to compile, as it\n> depends on some new stuff that are not even in 'next' yet, e.g.\n> argv_array_pushv() that is from pt/pull-builtin, and it does not\n> apply cleanly on top of that branch, either.\n\nI tried applying the series, and yeah it conflicts with 1570856\n(config.c: avoid xmmap error messages, 2015-05-28) because the\npt/pull-builtin branch in pu is based on an old version of master.\nThat's the only conflict though, it applies cleanly otherwise.\n\n> I'll see what's the cleanest way to queue this would be.  Perhaps\n> merge pt/builtin-pull on a copy of 'master' and then apply these, or\n> something like that.\n\nThanks.\n\nRegards,\nPaul\n"},{"id":"265764","messageId":"xmqqpp433f0p.fsf@gitster.dls.corp.google.com","threadId":"39799","inReplyTo":"1436278862-2638-19-git-send-email-pyokagan@gmail.com","subject":"Re: [PATCH v5 18/44] cache-tree: introduce write_index_as_tree()","fromName":"Junio C Hamano","fromEmail":"gitster@pobox.com","sentAt":"2015-07-07T20:10:30Z","receivedAt":"2015-07-07T20:10:30Z","isPatch":true,"sender":{"key":"gitster@pobox.com","avatar":"https://avatars.githubusercontent.com/u/54884?v=4"},"body":"Paul Tan <pyokagan@gmail.com> writes:\n\n> A caller may wish to write a temporary index as a tree. However,\n> write_cache_as_tree() assumes that the index was read from, and will\n> write to, the default index file path. Introduce write_index_as_tree()\n> which removes this limitation by allowing the caller to specify its own\n> index_state and index file path.\n>\n> Signed-off-by: Paul Tan <pyokagan@gmail.com>\n> ---\n>  cache-tree.c | 29 +++++++++++++++++------------\n>  cache-tree.h |  1 +\n>  2 files changed, 18 insertions(+), 12 deletions(-)\n\nMakes sense; thanks.\n"},{"id":"265765","messageId":"xmqqfv4z3etn.fsf@gitster.dls.corp.google.com","threadId":"39799","inReplyTo":"1436278862-2638-20-git-send-email-pyokagan@gmail.com","subject":"Re: [PATCH v5 19/44] builtin-am: implement --3way, am.threeWay","fromName":"Junio C Hamano","fromEmail":"gitster@pobox.com","sentAt":"2015-07-07T20:14:44Z","receivedAt":"2015-07-07T20:14:44Z","isPatch":true,"sender":{"key":"gitster@pobox.com","avatar":"https://avatars.githubusercontent.com/u/54884?v=4"},"body":"Paul Tan <pyokagan@gmail.com> writes:\n\n> @@ -82,6 +84,8 @@ struct am_state {\n>  \t/* number of digits in patch filename */\n>  \tint prec;\n>  \n> +\tint threeway;\n> +\n>  \tint quiet;\n>  \n>  \tint append_signoff;\n\nThese \"one line surrounded by blank on both sides\" starts to get\nirritating, and the structure looksq horrifying after you apply all\nthese patches.  Perhaps have a clean-up patch at the end to make\nthem look more like this?\n\nstruct am_state {\n\t/* state directory path */\n\tchar *dir;\n\n\t/* current and last patch numbers, 1-indexed */\n\tint cur;\n\tint last;\n\n\t/* commit metadata and message */\n\tchar *author_name;\n\tchar *author_email;\n\tchar *author_date;\n\tchar *msg;\n\tsize_t msg_len;\n\n\t/* when --rebasing, records the original commit the patch came from */\n\tunsigned char orig_commit[GIT_SHA1_RAWSZ];\n\n\t/* number of digits in patch filename */\n\tint prec;\n\n\t/* various operating modes and command line options */\n\tint interactive;\n\tint threeway;\n\tint quiet;\n\tint append_signoff;\n\tint utf8;\n\tint committer_date_is_author_date;\n\tint ignore_date;\n\tint allow_rerere_autoupdate;\n\tconst char *sign_commit;\n\tint rebasing;\n\n\t/* one of the enum keep_type values */\n\tint keep;\n\n\t/* pass -m flag to git-mailinfo */\n\tint message_id;\n\n\t/* one of the enum scissors_type values */\n\tint scissors;\n\n        /* used when spawning \"git apply\" via run_command() */\n\tstruct argv_array git_apply_opts;\n\n\t/* override error message when patch failure occurs */\n\tconst char *resolvemsg;\n};\n"},{"id":"265812","messageId":"xmqqmvz7yuk4.fsf@gitster.dls.corp.google.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"Re: [PATCH v5 00/44] Make git-am a builtin","fromName":"Junio C Hamano","fromEmail":"gitster@pobox.com","sentAt":"2015-07-08T07:31:23Z","receivedAt":"2015-07-08T07:31:23Z","isPatch":true,"sender":{"key":"gitster@pobox.com","avatar":"https://avatars.githubusercontent.com/u/54884?v=4"},"body":"Paul Tan <pyokagan@gmail.com> writes:\n\n> This patch series rewrites git-am.sh into optimized C builtin/am.c, and is\n> part of my GSoC project to rewrite git-pull and git-am into C builtins[1].\n\nI merged this to 'jch' (that is somewhere in between 'next' and\n'pu', which is what I use for everyday work) and tried it to apply\nthe 8-patch series that starts at $gmane/273622 on top of 912bd49.\n\nIt appears that your builtin version makes \"am -3s\" barf at the\n[PATCH 7/8] in that series, complaining about lack of author\nidentity.\n"},{"id":"265816","messageId":"CACRoPnS_T6trUC2GcofuXKBRTAf-4u=MyNDp6ir=E5f3SHsq4A@mail.gmail.com","threadId":"39799","inReplyTo":"xmqqmvz7yuk4.fsf@gitster.dls.corp.google.com","subject":"Re: [PATCH v5 00/44] Make git-am a builtin","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-08T07:44:12Z","receivedAt":"2015-07-08T07:44:12Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"On Wed, Jul 8, 2015 at 3:31 PM, Junio C Hamano <gitster@pobox.com> wrote:\n> Paul Tan <pyokagan@gmail.com> writes:\n>\n>> This patch series rewrites git-am.sh into optimized C builtin/am.c, and is\n>> part of my GSoC project to rewrite git-pull and git-am into C builtins[1].\n>\n> I merged this to 'jch' (that is somewhere in between 'next' and\n> 'pu', which is what I use for everyday work) and tried it to apply\n> the 8-patch series that starts at $gmane/273622 on top of 912bd49.\n>\n> It appears that your builtin version makes \"am -3s\" barf at the\n> [PATCH 7/8] in that series, complaining about lack of author\n> identity.\n\nHmm? I compiled jch, and tried to reproduce the problem, but could not\ndo so. Here's what I did:\n\ngit checkout 912bd49\ngit am -3s mbox\nApplying: refs.c: add err arguments to reflog functions\nApplying: cherry-pick: treat CHERRY_PICK_HEAD and REVERT_HEAD as refs\nApplying: bisect: treat BISECT_HEAD as a ref\nApplying: refs: Break out check for reflog autocreation\nApplying: refs: new public ref function: safe_create_reflog\nApplying: git-reflog: add exists command\nApplying: update-ref and tag: add --create-reflog arg\nUsing index info to reconstruct a base tree...\nM    builtin/update-ref.c\nFalling back to patching base and 3-way merge...\nAuto-merging builtin/update-ref.c\nCONFLICT (content): Merge conflict in builtin/update-ref.c\nerror: Failed to merge in the changes.\nPatch failed at 0007 update-ref and tag: add --create-reflog arg\nThe copy of the patch that failed is found in: .git/rebase-apply/patch\nWhen you have resolved this problem, run \"git am --continue\".\nIf you prefer to skip this patch, run \"git am --skip\" instead.\nTo restore the original branch and stop patching, run \"git am --abort\".\n\n... after resolving the conflict ...\n\ngit add builtin/update-ref.c\ngit am --continue\nApplying: update-ref and tag: add --create-reflog arg\nApplying: git-stash: use update-ref --create-reflog instead of creating files\n\nAnd it completes successfully.\n\nThanks,\nPaul\n"},{"id":"265817","messageId":"xmqqa8v7yts9.fsf@gitster.dls.corp.google.com","threadId":"39799","inReplyTo":"xmqqmvz7yuk4.fsf@gitster.dls.corp.google.com","subject":"Re: [PATCH v5 00/44] Make git-am a builtin","fromName":"Junio C Hamano","fromEmail":"gitster@pobox.com","sentAt":"2015-07-08T07:48:06Z","receivedAt":"2015-07-08T07:48:06Z","isPatch":true,"sender":{"key":"gitster@pobox.com","avatar":"https://avatars.githubusercontent.com/u/54884?v=4"},"body":"Junio C Hamano <gitster@pobox.com> writes:\n\n> Paul Tan <pyokagan@gmail.com> writes:\n>\n>> This patch series rewrites git-am.sh into optimized C builtin/am.c, and is\n>> part of my GSoC project to rewrite git-pull and git-am into C builtins[1].\n>\n> I merged this to 'jch' (that is somewhere in between 'next' and\n> 'pu', which is what I use for everyday work) and tried it to apply\n> the 8-patch series that starts at $gmane/273622 on top of 912bd49.\n>\n> It appears that your builtin version makes \"am -3s\" barf at the\n> [PATCH 7/8] in that series, complaining about lack of author\n> identity.\n\n$ git am -s ./+dt\n...\nerror: patch failed: builtin/update-ref.c:421\nerror: builtin/update-ref.c: patch does not apply\nPatch failed at 0007 update-ref and tag: add --create-reflog arg\nThe copy of the patch that failed is found in:.git/rebase-apply/patch\nWhen you have resolved this problem, run \"git am --continue\".\nIf you prefer to skip this patch, run \"git am --skip\" instead.\nTo restore the original branch and stop patching, run \"git am --abort\".\n$ git am -3\ngit: builtin/am.c:1332: parse_mail: Assertion `!state->author_name'\nfailed.\nAborted (core dumped)\n"},{"id":"265820","messageId":"20150708081902.GA8606@yoshi.chippynet.com","threadId":"39799","inReplyTo":"xmqqa8v7yts9.fsf@gitster.dls.corp.google.com","subject":"Re: [PATCH v5 00/44] Make git-am a builtin","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-08T08:19:02Z","receivedAt":"2015-07-08T08:19:02Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"On Wed, Jul 08, 2015 at 12:48:06AM -0700, Junio C Hamano wrote:\n> Junio C Hamano <gitster@pobox.com> writes:\n> $ git am -s ./+dt\n> ...\n> error: patch failed: builtin/update-ref.c:421\n> error: builtin/update-ref.c: patch does not apply\n> Patch failed at 0007 update-ref and tag: add --create-reflog arg\n> The copy of the patch that failed is found in:.git/rebase-apply/patch\n> 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\".\n> $ git am -3\n> git: builtin/am.c:1332: parse_mail: Assertion `!state->author_name'\n> failed.\n> Aborted (core dumped)\n\nAh, it's because parse_mail() does not expect to be called while the\nauthorship and commit msg fields have been filled up. This is a wrong\nassumption, of course.\n\nSo the fix would be to remove the assert()s, as follows:\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex c548129..ab560ab 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -1327,16 +1327,20 @@ static int parse_mail(struct am_state *state, const char *mail)\n \tif (state->append_signoff)\n \t\tappend_signoff(&msg, 0, 0);\n \n-\tassert(!state->author_name);\n+\tif (state->author_name)\n+\t\tfree(state->author_name);\n \tstate->author_name = strbuf_detach(&author_name, NULL);\n \n-\tassert(!state->author_email);\n+\tif (state->author_email)\n+\t\tfree(state->author_email);\n \tstate->author_email = strbuf_detach(&author_email, NULL);\n \n-\tassert(!state->author_date);\n+\tif (state->author_date)\n+\t\tfree(state->author_date);\n \tstate->author_date = strbuf_detach(&author_date, NULL);\n \n-\tassert(!state->msg);\n+\tif (state->msg)\n+\t\tfree(state->msg);\n \tstate->msg = strbuf_detach(&msg, &state->msg_len);\n \n finish:\n@@ -1392,7 +1396,9 @@ static void get_commit_info(struct am_state *state, struct commit *commit)\n \t\tdie(_(\"invalid ident line: %s\"), sb.buf);\n \t}\n \n-\tassert(!state->author_name);\n+\tif (state->author_name)\n+\t\tfree(state->author_name);\n+\n \tif (ident_split.name_begin) {\n \t\tstrbuf_add(&sb, ident_split.name_begin,\n \t\t\tident_split.name_end - ident_split.name_begin);\n@@ -1400,7 +1406,9 @@ static void get_commit_info(struct am_state *state, struct commit *commit)\n \t} else\n \t\tstate->author_name = xstrdup(\"\");\n \n-\tassert(!state->author_email);\n+\tif (state->author_email)\n+\t\tfree(state->author_email);\n+\n \tif (ident_split.mail_begin) {\n \t\tstrbuf_add(&sb, ident_split.mail_begin,\n \t\t\tident_split.mail_end - ident_split.mail_begin);\n@@ -1410,13 +1418,17 @@ static void get_commit_info(struct am_state *state, struct commit *commit)\n \n \tauthor_date = show_ident_date(&ident_split, DATE_NORMAL);\n \tstrbuf_addstr(&sb, author_date);\n-\tassert(!state->author_date);\n+\n+\tif (state->author_date)\n+\t\tfree(state->author_date);\n \tstate->author_date = strbuf_detach(&sb, NULL);\n \n-\tassert(!state->msg);\n \tmsg = strstr(buffer, \"\\n\\n\");\n \tif (!msg)\n \t\tdie(_(\"unable to parse commit %s\"), sha1_to_hex(commit->object.sha1));\n+\n+\tif (state->msg)\n+\t\tfree(state->msg);\n \tstate->msg = xstrdup(msg + 2);\n \tstate->msg_len = strlen(state->msg);\n }\n"},{"id":"265893","messageId":"xmqqio9tx42z.fsf@gitster.dls.corp.google.com","threadId":"39799","inReplyTo":"20150708081902.GA8606@yoshi.chippynet.com","subject":"Re: [PATCH v5 00/44] Make git-am a builtin","fromName":"Junio C Hamano","fromEmail":"gitster@pobox.com","sentAt":"2015-07-09T06:00:52Z","receivedAt":"2015-07-09T06:00:52Z","isPatch":true,"sender":{"key":"gitster@pobox.com","avatar":"https://avatars.githubusercontent.com/u/54884?v=4"},"body":"Paul Tan <pyokagan@gmail.com> writes:\n\n> So the fix would be to remove the assert()s, as follows:\n\nWhat I pushed out tonight should have SQUASH??? (or fixup!) that\nsplits this into appropriate steps in your series.  Please check.\n\nNote that you do not have to say \"if the variable has something,\nthen free it\".  free(NULL) is perfectly fine and we can read\n\n\tfree(var);\n        var = compute_new_value();\n\njust fine.\n\nHowever, I am reluctant to blindly replace assert(!state->field)\nwith free(state->field).  Are there cases where we _must_ call a\nfunction that sets these fields at most once?\n\nOn the other hand, assert() like this is more or less useless.\n\n\tassert(state->field);\n        ...\n        printf(\"%s\", state->field); /* or other uses */\n\n\"The caller must have filled the field\" can be seen by unconditional\nuse of \"state->field\" without such an assert().\n"},{"id":"266059","messageId":"CACRoPnQyPpK3g0G3N-Yf2Zatk5RCEUe_1mbW9LGq8-=zypYcNg@mail.gmail.com","threadId":"39799","inReplyTo":"xmqqio9tx42z.fsf@gitster.dls.corp.google.com","subject":"Re: [PATCH v5 00/44] Make git-am a builtin","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-12T12:29:29Z","receivedAt":"2015-07-12T12:29:29Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"Hi,\n\n(Sorry for the late reply. Caught a nasty stomach bug that kept me in\nbed for a while ><)\n\nOn Thu, Jul 9, 2015 at 2:00 PM, Junio C Hamano <gitster@pobox.com> wrote:\n> What I pushed out tonight should have SQUASH??? (or fixup!) that\n> splits this into appropriate steps in your series.  Please check.\n\nYeah they look good.\n\n> Note that you do not have to say \"if the variable h2as something,\n> then free it\".  free(NULL) is perfectly fine and we can read\n>\n>         free(var);\n>         var = compute_new_value();\n>\n> just fine.\n\nOK. There are other places where I used \"if (x) free(x)\" though (such\nas in am_state_release()), so I will fix them in a re-roll as well.\n\n> However, I am reluctant to blindly replace assert(!state->field)\n> with free(state->field).  Are there cases where we _must_ call a\n> function that sets these fields at most once?\n\nI wouldn't say we are \"blindly\" replacing them. The purpose of the\nassert(!state->field) is to ensure that we are not overwriting any\ncommit metadata already stored in the state directory. And in almost\nall cases, this holds true. However, as you have just shown, running\n\"git am\" again while there is a session in progress will override the\ncommit metadata stored in the state directory, so I believe the\nreplacement with free() is reasonable.\n\n> On the other hand, assert() like this is more or less useless.\n>\n>         assert(state->field);\n>         ...\n>         printf(\"%s\", state->field); /* or other uses */\n>\n> \"The caller must have filled the field\" can be seen by unconditional\n> use of \"state->field\" without such an assert().\n\nOK. Will remove them as well.\n\nThanks,\nPaul\n"},{"id":"266066","messageId":"xmqqvbdpi8nt.fsf@gitster.dls.corp.google.com","threadId":"39799","inReplyTo":"CACRoPnQyPpK3g0G3N-Yf2Zatk5RCEUe_1mbW9LGq8-=zypYcNg@mail.gmail.com","subject":"Re: [PATCH v5 00/44] Make git-am a builtin","fromName":"Junio C Hamano","fromEmail":"gitster@pobox.com","sentAt":"2015-07-12T17:32:22Z","receivedAt":"2015-07-12T17:32:22Z","isPatch":true,"sender":{"key":"gitster@pobox.com","avatar":"https://avatars.githubusercontent.com/u/54884?v=4"},"body":"Paul Tan <pyokagan@gmail.com> writes:\n\n>> However, I am reluctant to blindly replace assert(!state->field)\n>> with free(state->field).  Are there cases where we _must_ call a\n>> function that sets these fields at most once?\n>\n> I wouldn't say we are \"blindly\" replacing them.\n\nI said \"I was\", not \"you and me\".  If there was a case where we\nshould never call into a codepath once these fields are already\ninitialized, then we need to keep assert(!state->field) in such a\ncodepath.  I didn't know if that were the case, hence I would have\nbeen blindly replacing, which I didn't want to do.  And that is why\nI asked _you_ ;-)\n"},{"id":"266088","messageId":"CAGZ79kaWV-hMEgJ8HJP2Jgq78su+YbyBbcYD3sZ0474UUNw=pA@mail.gmail.com","threadId":"39799","inReplyTo":"1436278862-2638-13-git-send-email-pyokagan@gmail.com","subject":"Re: [PATCH v5 12/44] builtin-am: implement --skip","fromName":"Stefan Beller","fromEmail":"sbeller@google.com","sentAt":"2015-07-13T19:05:21Z","receivedAt":"2015-07-13T19:05:21Z","isPatch":true,"sender":{"key":"stefanbeller@gmail.com","avatar":"https://avatars.githubusercontent.com/u/455868?v=4"},"body":"On Tue, Jul 7, 2015 at 7:20 AM, Paul Tan <pyokagan@gmail.com> wrote:\n> Since d1c5f2a (Add git-am, applymbox replacement., 2005-10-07), git-am\n> supported resuming from a failed patch application by skipping the\n> current patch. Re-implement this feature by introducing am_skip().\n>\n> Signed-off-by: Paul Tan <pyokagan@gmail.com>\n> ---\n>  builtin/am.c | 121 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-\n>  1 file changed, 119 insertions(+), 2 deletions(-)\n>\n> diff --git a/builtin/am.c b/builtin/am.c\n> index f21565b..5087094 100644\n> --- a/builtin/am.c\n> +++ b/builtin/am.c\n> @@ -16,6 +16,8 @@\n>  #include \"commit.h\"\n>  #include \"diff.h\"\n>  #include \"diffcore.h\"\n> +#include \"unpack-trees.h\"\n> +#include \"branch.h\"\n>\n>  /**\n>   * Returns 1 if the file is empty or does not exist, 0 otherwise.\n> @@ -872,6 +874,114 @@ static void am_resolve(struct am_state *state)\n>  }\n>\n>  /**\n> + * Performs a checkout fast-forward from `head` to `remote`. If `reset` is\n> + * true, any unmerged entries will be discarded. Returns 0 on success, -1 on\n> + * failure.\n> + */\n> +static int fast_forward_to(struct tree *head, struct tree *remote, int reset)\n> +{\n> +       struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));\n> +       struct unpack_trees_options opts;\n> +       struct tree_desc t[2];\n> +\n> +       if (parse_tree(head) || parse_tree(remote))\n> +               return -1;\n> +\n> +       hold_locked_index(lock_file, 1);\n> +\n> +       refresh_cache(REFRESH_QUIET);\n> +\n> +       memset(&opts, 0, sizeof(opts));\n> +       opts.head_idx = 1;\n> +       opts.src_index = &the_index;\n> +       opts.dst_index = &the_index;\n> +       opts.update = 1;\n> +       opts.merge = 1;\n> +       opts.reset = reset;\n> +       opts.fn = twoway_merge;\n> +       init_tree_desc(&t[0], head->buffer, head->size);\n> +       init_tree_desc(&t[1], remote->buffer, remote->size);\n> +\n> +       if (unpack_trees(2, t, &opts)) {\n> +               rollback_lock_file(lock_file);\n> +               return -1;\n> +       }\n> +\n> +       if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))\n> +               die(_(\"unable to write new index file\"));\n> +\n> +       return 0;\n> +}\n> +\n> +/**\n> + * Clean the index without touching entries that are not modified between\n> + * `head` and `remote`.\n> + */\n> +static int clean_index(const unsigned char *head, const unsigned char *remote)\n> +{\n> +       struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));\n> +       struct tree *head_tree, *remote_tree, *index_tree;\n> +       unsigned char index[GIT_SHA1_RAWSZ];\n> +       struct pathspec pathspec;\n> +\n> +       head_tree = parse_tree_indirect(head);\n> +       if (!head_tree)\n> +               return error(_(\"Could not parse object '%s'.\"), sha1_to_hex(head));\n> +\n> +       remote_tree = parse_tree_indirect(remote);\n> +       if (!remote_tree)\n> +               return error(_(\"Could not parse object '%s'.\"), sha1_to_hex(remote));\n> +\n> +       read_cache_unmerged();\n> +\n> +       if (fast_forward_to(head_tree, head_tree, 1))\n> +               return -1;\n> +\n> +       if (write_cache_as_tree(index, 0, NULL))\n> +               return -1;\n> +\n> +       index_tree = parse_tree_indirect(index);\n> +       if (!index_tree)\n> +               return error(_(\"Could not parse object '%s'.\"), sha1_to_hex(index));\n> +\n> +       if (fast_forward_to(index_tree, remote_tree, 0))\n> +               return -1;\n> +\n> +       memset(&pathspec, 0, sizeof(pathspec));\n> +\n\nAll returns before this point leak the memory of `lock_file`.\n\n> +       hold_locked_index(lock_file, 1);\n> +\n> +       if (read_tree(remote_tree, 0, &pathspec)) {\n> +               rollback_lock_file(lock_file);\n> +               return -1;\n> +       }\n> +\n> +       if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))\n> +               die(_(\"unable to write new index file\"));\n> +\n> +       remove_branch_state();\n> +\n> +       return 0;\n> +}\n> +\n> +/**\n> + * Resume the current am session by skipping the current patch.\n> + */\n> +static void am_skip(struct am_state *state)\n> +{\n> +       unsigned char head[GIT_SHA1_RAWSZ];\n> +\n> +       if (get_sha1(\"HEAD\", head))\n> +               hashcpy(head, EMPTY_TREE_SHA1_BIN);\n> +\n> +       if (clean_index(head, head))\n> +               die(_(\"failed to clean index\"));\n> +\n> +       am_next(state);\n> +       am_run(state);\n> +}\n> +\n> +/**\n>   * parse_options() callback that validates and sets opt->value to the\n>   * PATCH_FORMAT_* enum value corresponding to `arg`.\n>   */\n> @@ -888,7 +998,8 @@ static int parse_opt_patchformat(const struct option *opt, const char *arg, int\n>\n>  enum resume_mode {\n>         RESUME_FALSE = 0,\n> -       RESUME_RESOLVED\n> +       RESUME_RESOLVED,\n> +       RESUME_SKIP\n>  };\n>\n>  int cmd_am(int argc, const char **argv, const char *prefix)\n> @@ -899,7 +1010,7 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n>\n>         const char * const usage[] = {\n>                 N_(\"git am [options] [(<mbox>|<Maildir>)...]\"),\n> -               N_(\"git am [options] --continue\"),\n> +               N_(\"git am [options] (--continue | --skip)\"),\n>                 NULL\n>         };\n>\n> @@ -913,6 +1024,9 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n>                 OPT_CMDMODE('r', \"resolved\", &resume,\n>                         N_(\"synonyms for --continue\"),\n>                         RESUME_RESOLVED),\n> +               OPT_CMDMODE(0, \"skip\", &resume,\n> +                       N_(\"skip the current patch\"),\n> +                       RESUME_SKIP),\n>                 OPT_END()\n>         };\n>\n> @@ -968,6 +1082,9 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n>         case RESUME_RESOLVED:\n>                 am_resolve(&state);\n>                 break;\n> +       case RESUME_SKIP:\n> +               am_skip(&state);\n> +               break;\n>         default:\n>                 die(\"BUG: invalid resume value\");\n>         }\n> --\n> 2.5.0.rc1.76.gf60a929\n>\n"},{"id":"266099","messageId":"xmqqh9p7y9iu.fsf@gitster.dls.corp.google.com","threadId":"39799","inReplyTo":"1436278862-2638-1-git-send-email-pyokagan@gmail.com","subject":"Re: [PATCH v5 00/44] Make git-am a builtin","fromName":"Junio C Hamano","fromEmail":"gitster@pobox.com","sentAt":"2015-07-13T22:31:37Z","receivedAt":"2015-07-13T22:31:37Z","isPatch":true,"sender":{"key":"gitster@pobox.com","avatar":"https://avatars.githubusercontent.com/u/54884?v=4"},"body":"While using this series for real work today, I found another bug\nthat is unfortunately a show-stopper for my workflow.\n\nStore 7 patches from David Turner to a file, ./+dt-7, starting at\nhttp://thread.gmane.org/gmane.comp.version-control.git/273786 and\nthen:\n\n  $ git checkout master...dt/refs-backend-preamble\n\t... \"git checkout 912bd49\" is also fine ...\n  $ git am -s ./+dt-7\n\nThis stops while applying 6th patch, like so:\n\n  Applying: update-ref and tag: add --create-reflog arg\n  error: patch failed: builtin/update-ref.c:431\n  error: builtin/update-ref.c: patch does not apply\n  Patch failed at 0006 update-ref and tag: add --create-reflog arg\n  The copy of the patch that failed is found in:\n     /usr/local/google/home/jch/w/git.git/.git/rebase-apply/patch\n  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\".\n\nThis is expected, but the recovery from this state is what goes\nwrong.  At this point, one of the usual thing to do is to\n\n  $ edit .git/rebase-apply/patch\n\nand match the offending preimage to what the working tree has.\n\nIn this case, the conflict is found near the end of\nbuiltin/update-ref.c, where the call to delete_ref() in the\npre-context of the hunk at around ll.413,+10 was\n\n\treturn delete_ref(refname, oldval ? oldsha1 : NULL, flags);\n\nbut in the newer codebase, the line is split further and the\npre-context would show just\n\n\tflags);\n\nthe latter of which is what $gmane/273793 expects.  \n\nA fix is to edit the patch to replace that \"flags);\" line with full\n\"return delete_ref()\" line and save it.  Then running\n\n  $ git am\n\n(no argument) is supposed to read from the corrected patch file and\ncontinue the application.\n\nThis no longer works with the version with this series, it seems.\n"},{"id":"266108","messageId":"CACRoPnTh+rWhOah3u5Q4td5NDLj9CLU3krvw9xCO2DE-VaPudg@mail.gmail.com","threadId":"39799","inReplyTo":"xmqqfv4z3etn.fsf@gitster.dls.corp.google.com","subject":"Re: [PATCH v5 19/44] builtin-am: implement --3way, am.threeWay","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-14T09:32:48Z","receivedAt":"2015-07-14T09:32:48Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"On Wed, Jul 8, 2015 at 4:14 AM, Junio C Hamano <gitster@pobox.com> wrote:\n> Paul Tan <pyokagan@gmail.com> writes:\n>\n>> @@ -82,6 +84,8 @@ struct am_state {\n>>       /* number of digits in patch filename */\n>>       int prec;\n>>\n>> +     int threeway;\n>> +\n>>       int quiet;\n>>\n>>       int append_signoff;\n>\n> These \"one line surrounded by blank on both sides\" starts to get\n> irritating, and the structure looksq horrifying after you apply all\n> these patches.  Perhaps have a clean-up patch at the end to make\n> them look more like this?\n>\n> struct am_state {\n>         /* state directory path */\n>         char *dir;\n>\n>         /* current and last patch numbers, 1-indexed */\n>         int cur;\n>         int last;\n>\n>         /* commit metadata and message */\n>         char *author_name;\n>         char *author_email;\n>         char *author_date;\n>         char *msg;\n>         size_t msg_len;\n>\n>         /* when --rebasing, records the original commit the patch came from */\n>         unsigned char orig_commit[GIT_SHA1_RAWSZ];\n>\n>         /* number of digits in patch filename */\n>         int prec;\n>\n>         /* various operating modes and command line options */\n>         int interactive;\n>         int threeway;\n>         int quiet;\n>         int append_signoff;\n>         int utf8;\n>         int committer_date_is_author_date;\n>         int ignore_date;\n>         int allow_rerere_autoupdate;\n>         const char *sign_commit;\n>         int rebasing;\n>\n>         /* one of the enum keep_type values */\n>         int keep;\n>\n>         /* pass -m flag to git-mailinfo */\n>         int message_id;\n>\n>         /* one of the enum scissors_type values */\n>         int scissors;\n>\n>         /* used when spawning \"git apply\" via run_command() */\n>         struct argv_array git_apply_opts;\n>\n>         /* override error message when patch failure occurs */\n>         const char *resolvemsg;\n\nOkay. I would prefer to keep the above fields all in the same block\nthough, as they are all \"various operating modes and command line\noptions\". And in retrospect, the comments don't really add much value,\nwith the exception of the \"enum\" comments to make it explicit that we\nexpect an enum value in that field. So, something like this, perhaps?\n\nstruct am_state {\n    /* state directory path */\n    char *dir;\n\n    /* current and last patch numbers, 1-indexed */\n    int cur;\n    int last;\n\n    /* commit metadata and message */\n    char *author_name;\n    char *author_email;\n    char *author_date;\n    char *msg;\n    size_t msg_len;\n\n    /* when --rebasing, records the original commit the patch came from */\n    unsigned char orig_commit[GIT_SHA1_RAWSZ];\n\n    /* number of digits in patch filename */\n    int prec;\n\n    /* various operating modes and command line options */\n    int interactive;\n    int threeway;\n    int quiet;\n    int append_signoff;\n    int utf8;\n    int keep; /* enum keep_type */\n    int message_id;\n    int scissors; /* enum scissors_type */\n    struct argv_array git_apply_opts;\n    const char *resolvemsg;\n    int committer_date_is_author_date;\n    int ignore_date;\n    int allow_rerere_autoupdate;\n    const char *sign_commit;\n    int rebasing;\n};\n\nThanks,\nPaul\n"},{"id":"266109","messageId":"CACRoPnRri5Nu5rj9O7id+PyiDBJpZkBDk8kB0WCuB3Uef76M3g@mail.gmail.com","threadId":"39799","inReplyTo":"CAGZ79kaWV-hMEgJ8HJP2Jgq78su+YbyBbcYD3sZ0474UUNw=pA@mail.gmail.com","subject":"Re: [PATCH v5 12/44] builtin-am: implement --skip","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-14T09:34:23Z","receivedAt":"2015-07-14T09:34:23Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"On Tue, Jul 14, 2015 at 3:05 AM, Stefan Beller <sbeller@google.com> wrote:\n> All returns before this point leak the memory of `lock_file`.\n\nYeah, it's intentional. From Documentation/technical/api-lockfile.txt:\n\n* Allocates a `struct lock_file` either as a static variable or on the\n  heap, initialized to zeros. Once you use the structure to call the\n  `hold_lock_file_*` family of functions, it belongs to the lockfile\n  subsystem and its storage must remain valid throughout the life of\n  the program (i.e. you cannot use an on-stack variable to hold this\n  structure).\n\nThanks,\nPaul\n"},{"id":"266112","messageId":"20150714100803.GA23901@yoshi.chippynet.com","threadId":"39799","inReplyTo":"xmqqh9p7y9iu.fsf@gitster.dls.corp.google.com","subject":"Re: [PATCH v5 00/44] Make git-am a builtin","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-14T10:08:03Z","receivedAt":"2015-07-14T10:08:03Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"On Mon, Jul 13, 2015 at 03:31:37PM -0700, Junio C Hamano wrote:\n> A fix is to edit the patch to replace that \"flags);\" line with full\n> \"return delete_ref()\" line and save it.  Then running\n> \n>   $ git am\n> \n> (no argument) is supposed to read from the corrected patch file and\n> continue the application.\n> \n> This no longer works with the version with this series, it seems.\n\nAh, this is actually the same bug as the previous one, and it actually\nall stems from the fact that I completely overlooked the code path\nchange introduced by 271440e (git-am: make it easier after fixing up an\nunapplicable patch., 2005-10-25). When \"git am\" is run again while\npaused, the mail message should not be re-parsed at all.\n\nSo, I'm thinking of something like the following as a separate patch in\nthis series to re-implement the feature:\n\ndiff a/builtin/am.c b/builtin/am.c\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -1714,6 +1692,21 @@ static void do_commit(const struct am_state *state)\n }\n \n /**\n+ * Validates the am_state for resuming -- the \"msg\" and authorship fields must\n+ * be filled up.\n+ */\n+static void validate_resume_state(const struct am_state *state)\n+{\n+\tif (!state->msg)\n+\t\tdie(_(\"cannot resume: %s does not exist.\"),\n+\t\t\tam_path(state, \"final-commit\"));\n+\n+\tif (!state->author_name || !state->author_email || !state->author_date)\n+\t\tdie(_(\"cannot resume: %s does not exist.\"),\n+\t\t\tam_path(state, \"author-script\"));\n+}\n+\n+/**\n  * Interactively prompt the user on whether the current patch should be\n  * applied.\n  *\n@@ -1774,8 +1767,12 @@ static int do_interactive(struct am_state *state)\n \n /**\n  * Applies all queued mail.\n+ *\n+ * If `resume` is true, we are \"resuming\". The \"msg\" and authorship fields, as\n+ * well as the state directory's \"patch\" file is used as-is for applying the\n+ * patch and committing it.\n  */\n-static void am_run(struct am_state *state)\n+static void am_run(struct am_state *state, int resume)\n {\n \tconst char *argv_gc_auto[] = {\"gc\", \"--auto\", NULL};\n \tstruct strbuf sb = STRBUF_INIT;\n@@ -1793,21 +1790,28 @@ static void am_run(struct am_state *state)\n \n \twhile (state->cur <= state->last) {\n \t\tconst char *mail = am_path(state, msgnum(state));\n-\t\tint apply_status, skip;\n+\t\tint apply_status;\n \n \t\tif (!file_exists(mail))\n \t\t\tgoto next;\n \n-\t\tif (state->rebasing)\n-\t\t\tskip = parse_mail_rebase(state, mail);\n-\t\telse\n-\t\t\tskip = parse_mail(state, mail);\n+\t\tif (resume) {\n+\t\t\tvalidate_resume_state(state);\n+\t\t\tresume = 0;\n+\t\t} else {\n+\t\t\tint skip;\n+\n+\t\t\tif (state->rebasing)\n+\t\t\t\tskip = parse_mail_rebase(state, mail);\n+\t\t\telse\n+\t\t\t\tskip = parse_mail(state, mail);\n \n-\t\tif (skip)\n-\t\t\tgoto next; /* mail should be skipped */\n+\t\t\tif (skip)\n+\t\t\t\tgoto next; /* mail should be skipped */\n \n-\t\twrite_author_script(state);\n-\t\twrite_commit_msg(state);\n+\t\t\twrite_author_script(state);\n+\t\t\twrite_commit_msg(state);\n+\t\t}\n \n \t\tif (state->interactive && do_interactive(state))\n \t\t\tgoto next;\n@@ -1880,13 +1884,7 @@ next:\n  */\n static void am_resolve(struct am_state *state)\n {\n-\tif (!state->msg)\n-\t\tdie(_(\"cannot resume: %s does not exist.\"),\n-\t\t\tam_path(state, \"final-commit\"));\n-\n-\tif (!state->author_name || !state->author_email || !state->author_date)\n-\t\tdie(_(\"cannot resume: %s does not exist.\"),\n-\t\t\tam_path(state, \"author-script\"));\n+\tvalidate_resume_state(state);\n \n \tsay(state, stdout, _(\"Applying: %.*s\"), linelen(state->msg), state->msg);\n \n@@ -1915,7 +1913,7 @@ static void am_resolve(struct am_state *state)\n \n next:\n \tam_next(state);\n-\tam_run(state);\n+\tam_run(state, 0);\n }\n \n /**\n@@ -2040,7 +2038,7 @@ static void am_skip(struct am_state *state)\n \t\tdie(_(\"failed to clean index\"));\n \n \tam_next(state);\n-\tam_run(state);\n+\tam_run(state, 0);\n }\n \n /**\n@@ -2136,6 +2134,7 @@ static int parse_opt_patchformat(const struct option *opt, const char *arg, int\n \n enum resume_mode {\n \tRESUME_FALSE = 0,\n+\tRESUME_APPLY,\n \tRESUME_RESOLVED,\n \tRESUME_SKIP,\n \tRESUME_ABORT\n@@ -2271,6 +2270,9 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \t\t\tdie(_(\"previous rebase directory %s still exists but mbox given.\"),\n \t\t\t\tstate.dir);\n \n+\t\tif (resume == RESUME_FALSE)\n+\t\t\tresume = RESUME_APPLY;\n+\n \t\tam_load(&state);\n \t} else {\n \t\tstruct argv_array paths = ARGV_ARRAY_INIT;\n@@ -2310,7 +2312,10 @@ int cmd_am(int argc, const char **argv, const char *prefix)\n \n \tswitch (resume) {\n \tcase RESUME_FALSE:\n-\t\tam_run(&state);\n+\t\tam_run(&state, 0);\n+\t\tbreak;\n+\tcase RESUME_APPLY:\n+\t\tam_run(&state, 1);\n \t\tbreak;\n \tcase RESUME_RESOLVED:\n \t\tam_resolve(&state);\n\nAt this point I've accumulated a lot of changes on my end so I'll do a\nre-roll.\n\nThanks,\nPaul\n"},{"id":"266134","messageId":"CAGZ79kYYJughaqBD7hzzDBO4xmrJ7P3VT7m=qG-SRLXiK-f_vA@mail.gmail.com","threadId":"39799","inReplyTo":"CACRoPnRri5Nu5rj9O7id+PyiDBJpZkBDk8kB0WCuB3Uef76M3g@mail.gmail.com","subject":"Re: [PATCH v5 12/44] builtin-am: implement --skip","fromName":"Stefan Beller","fromEmail":"sbeller@google.com","sentAt":"2015-07-14T16:54:10Z","receivedAt":"2015-07-14T16:54:10Z","isPatch":true,"sender":{"key":"stefanbeller@gmail.com","avatar":"https://avatars.githubusercontent.com/u/455868?v=4"},"body":"On Tue, Jul 14, 2015 at 2:34 AM, Paul Tan <pyokagan@gmail.com> wrote:\n> On Tue, Jul 14, 2015 at 3:05 AM, Stefan Beller <sbeller@google.com> wrote:\n>> All returns before this point leak the memory of `lock_file`.\n>\n> Yeah, it's intentional. From Documentation/technical/api-lockfile.txt:\n>\n> * Allocates a `struct lock_file` either as a static variable or on the\n>   heap, initialized to zeros. Once you use the structure to call the\n>   `hold_lock_file_*` family of functions, it belongs to the lockfile\n>   subsystem and its storage must remain valid throughout the life of\n>   the program (i.e. you cannot use an on-stack variable to hold this\n>   structure).\n>\n> Thanks,\n> Paul\n\nSo what I meant to suggest, was to only allocate the memory if we really need it\nby moving the allocation further down.\n\nstatic int clean_index(const unsigned char *head, const unsigned char *remote)\n{\n       struct lock_file *lock_file;\n...\n... // includes return -1, which would not leak the memory already allocated\n...\n       lock_file = xalloc (...);\n       hold_locked_index(lock_file, 1);\n"},{"id":"266329","messageId":"20150718152212.GA22976@yoshi.chippynet.com","threadId":"39799","inReplyTo":"CAGZ79kYYJughaqBD7hzzDBO4xmrJ7P3VT7m=qG-SRLXiK-f_vA@mail.gmail.com","subject":"Re: [PATCH v5 12/44] builtin-am: implement --skip","fromName":"Paul Tan","fromEmail":"pyokagan@gmail.com","sentAt":"2015-07-18T15:22:12Z","receivedAt":"2015-07-18T15:22:12Z","isPatch":true,"sender":{"key":"pyokagan@gmail.com","avatar":"https://avatars.githubusercontent.com/u/109479?v=4"},"body":"On Tue, Jul 14, 2015 at 09:54:10AM -0700, Stefan Beller wrote:\n> So what I meant to suggest, was to only allocate the memory if we really need it\n> by moving the allocation further down.\n> \n> static int clean_index(const unsigned char *head, const unsigned char *remote)\n> {\n>        struct lock_file *lock_file;\n> ...\n> ... // includes return -1, which would not leak the memory already allocated\n> ...\n>        lock_file = xalloc (...);\n>        hold_locked_index(lock_file, 1);\n\nAh, sorry, I misinterpreted your message ><. Thanks for catching this.\n\nI've moved all the lock file memory allocation to just before the\nhold_locked_index() calls on my end.\n\ndiff --git a/builtin/am.c b/builtin/am.c\nindex c597325..dc8e862 100644\n--- a/builtin/am.c\n+++ b/builtin/am.c\n@@ -1138,13 +1138,12 @@ static const char *msgnum(const struct am_state *state)\n  */\n static void refresh_and_write_cache(void)\n {\n-\tstatic struct lock_file lock_file;\n+\tstruct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));\n \n-\thold_locked_index(&lock_file, 1);\n+\thold_locked_index(lock_file, 1);\n \trefresh_cache(REFRESH_QUIET);\n-\tif (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))\n+\tif (write_locked_index(&the_index, lock_file, COMMIT_LOCK))\n \t\tdie(_(\"unable to write index file\"));\n-\trollback_lock_file(&lock_file);\n }\n \n /**\n@@ -1923,13 +1922,14 @@ next:\n  */\n static int fast_forward_to(struct tree *head, struct tree *remote, int reset)\n {\n-\tstruct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));\n+\tstruct lock_file *lock_file;\n \tstruct unpack_trees_options opts;\n \tstruct tree_desc t[2];\n \n \tif (parse_tree(head) || parse_tree(remote))\n \t\treturn -1;\n \n+\tlock_file = xcalloc(1, sizeof(struct lock_file));\n \thold_locked_index(lock_file, 1);\n \n \trefresh_cache(REFRESH_QUIET);\n@@ -1962,7 +1962,7 @@ static int fast_forward_to(struct tree *head, struct tree *remote, int reset)\n  */\n static int clean_index(const unsigned char *head, const unsigned char *remote)\n {\n-\tstruct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));\n+\tstruct lock_file *lock_file;\n \tstruct tree *head_tree, *remote_tree, *index_tree;\n \tunsigned char index[GIT_SHA1_RAWSZ];\n \tstruct pathspec pathspec;\n@@ -1992,6 +1992,7 @@ static int clean_index(const unsigned char *head, const unsigned char *remote)\n \n \tmemset(&pathspec, 0, sizeof(pathspec));\n \n+\tlock_file = xcalloc(1, sizeof(struct lock_file));\n \thold_locked_index(lock_file, 1);\n \n \tif (read_tree(remote_tree, 0, &pathspec)) {\n\nThanks,\nPaul\n"}]}