builtin-am: refuse to apply patches if index is dirty

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>

Paul Tan committed Aug 4, 2015 at 21:51 UTC 32a5fcbfe9e9436224278ec7eb137b0f2905928d
1 file changed +45
builtin/am.c
+45
@@ -14,6 +14,8 @@
14 #include "cache-tree.h"
15 #include "refs.h"
16 #include "commit.h"
17 +#include "diff.h"
18 +#include "diffcore.h"
19
20 /**
21 * Returns 1 if the file is empty or does not exist, 0 otherwise.
@@ -564,6 +566,43 @@ static void refresh_and_write_cache(void)
566 die(_("unable to write index file"));
567 }
568
569 +/**
570 + * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn
571 + * branch, returns 1 if there are entries in the index, 0 otherwise. If an
572 + * strbuf is provided, the space-separated list of files that differ will be
573 + * appended to it.
574 + */
575 +static int index_has_changes(struct strbuf *sb)
576 +{
577 + unsigned char head[GIT_SHA1_RAWSZ];
578 + int i;
579 +
580 + if (!get_sha1_tree("HEAD", head)) {
581 + struct diff_options opt;
582 +
583 + diff_setup(&opt);
584 + DIFF_OPT_SET(&opt, EXIT_WITH_STATUS);
585 + if (!sb)
586 + DIFF_OPT_SET(&opt, QUICK);
587 + do_diff_cache(head, &opt);
588 + diffcore_std(&opt);
589 + for (i = 0; sb && i < diff_queued_diff.nr; i++) {
590 + if (i)
591 + strbuf_addch(sb, ' ');
592 + strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);
593 + }
594 + diff_flush(&opt);
595 + return DIFF_OPT_TST(&opt, HAS_CHANGES) != 0;
596 + } else {
597 + for (i = 0; sb && i < active_nr; i++) {
598 + if (i)
599 + strbuf_addch(sb, ' ');
600 + strbuf_addstr(sb, active_cache[i]->name);
601 + }
602 + return !!active_nr;
603 + }
604 +}
605 +
606 /**
607 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
608 * 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)
765 static void am_run(struct am_state *state)
766 {
767 const char *argv_gc_auto[] = {"gc", "--auto", NULL};
768 + struct strbuf sb = STRBUF_INIT;
769
770 refresh_and_write_cache();
771
772 + if (index_has_changes(&sb))
773 + die(_("Dirty index: cannot apply patches (dirty: %s)"), sb.buf);
774 +
775 + strbuf_release(&sb);
776 +
777 while (state->cur <= state->last) {
778 const char *mail = am_path(state, msgnum(state));
779