builtin-am: refuse to apply patches if index is dirty
authorPaul Tan <pyokagan@gmail.com>
Tue, 4 Aug 2015 13:51:31 +0000 (21:51 +0800)
committerJunio C Hamano <gitster@pobox.com>
Wed, 5 Aug 2015 05:02:11 +0000 (22:02 -0700)
Since d1c5f2a (Add git-am, applymbox replacement., 2005-10-07), git-am
will refuse to apply patches if the index is dirty. Re-implement this
behavior in builtin/am.c.

Signed-off-by: Paul Tan <pyokagan@gmail.com>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
builtin/am.c
index a2811b687a76bfc0f6829ee781270fd446618028..537ad62501971012768d0f91da23adfd36c19603 100644 (file)
@@ -14,6 +14,8 @@
 #include "cache-tree.h"
 #include "refs.h"
 #include "commit.h"
+#include "diff.h"
+#include "diffcore.h"
 
 /**
  * Returns 1 if the file is empty or does not exist, 0 otherwise.
@@ -564,6 +566,43 @@ static void refresh_and_write_cache(void)
                die(_("unable to write index file"));
 }
 
+/**
+ * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn
+ * branch, returns 1 if there are entries in the index, 0 otherwise. If an
+ * strbuf is provided, the space-separated list of files that differ will be
+ * appended to it.
+ */
+static int index_has_changes(struct strbuf *sb)
+{
+       unsigned char head[GIT_SHA1_RAWSZ];
+       int i;
+
+       if (!get_sha1_tree("HEAD", head)) {
+               struct diff_options opt;
+
+               diff_setup(&opt);
+               DIFF_OPT_SET(&opt, EXIT_WITH_STATUS);
+               if (!sb)
+                       DIFF_OPT_SET(&opt, QUICK);
+               do_diff_cache(head, &opt);
+               diffcore_std(&opt);
+               for (i = 0; sb && i < diff_queued_diff.nr; i++) {
+                       if (i)
+                               strbuf_addch(sb, ' ');
+                       strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);
+               }
+               diff_flush(&opt);
+               return DIFF_OPT_TST(&opt, HAS_CHANGES) != 0;
+       } else {
+               for (i = 0; sb && i < active_nr; i++) {
+                       if (i)
+                               strbuf_addch(sb, ' ');
+                       strbuf_addstr(sb, active_cache[i]->name);
+               }
+               return !!active_nr;
+       }
+}
+
 /**
  * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
  * state->msg will be set to the patch message. state->author_name,
@@ -726,9 +765,15 @@ static void do_commit(const struct am_state *state)
 static void am_run(struct am_state *state)
 {
        const char *argv_gc_auto[] = {"gc", "--auto", NULL};
+       struct strbuf sb = STRBUF_INIT;
 
        refresh_and_write_cache();
 
+       if (index_has_changes(&sb))
+               die(_("Dirty index: cannot apply patches (dirty: %s)"), sb.buf);
+
+       strbuf_release(&sb);
+
        while (state->cur <= state->last) {
                const char *mail = am_path(state, msgnum(state));