builtin / am.con commit builtin-am: implement -k/--keep, --keep-non-patch (4f1b696)
   1/*
   2 * Builtin "git am"
   3 *
   4 * Based on git-am.sh by Junio C Hamano.
   5 */
   6#include "cache.h"
   7#include "builtin.h"
   8#include "exec_cmd.h"
   9#include "parse-options.h"
  10#include "dir.h"
  11#include "run-command.h"
  12#include "quote.h"
  13#include "lockfile.h"
  14#include "cache-tree.h"
  15#include "refs.h"
  16#include "commit.h"
  17#include "diff.h"
  18#include "diffcore.h"
  19#include "unpack-trees.h"
  20#include "branch.h"
  21#include "sequencer.h"
  22#include "revision.h"
  23#include "merge-recursive.h"
  24#include "revision.h"
  25#include "log-tree.h"
  26
  27/**
  28 * Returns 1 if the file is empty or does not exist, 0 otherwise.
  29 */
  30static int is_empty_file(const char *filename)
  31{
  32        struct stat st;
  33
  34        if (stat(filename, &st) < 0) {
  35                if (errno == ENOENT)
  36                        return 1;
  37                die_errno(_("could not stat %s"), filename);
  38        }
  39
  40        return !st.st_size;
  41}
  42
  43/**
  44 * Like strbuf_getline(), but treats both '\n' and "\r\n" as line terminators.
  45 */
  46static int strbuf_getline_crlf(struct strbuf *sb, FILE *fp)
  47{
  48        if (strbuf_getwholeline(sb, fp, '\n'))
  49                return EOF;
  50        if (sb->buf[sb->len - 1] == '\n') {
  51                strbuf_setlen(sb, sb->len - 1);
  52                if (sb->len > 0 && sb->buf[sb->len - 1] == '\r')
  53                        strbuf_setlen(sb, sb->len - 1);
  54        }
  55        return 0;
  56}
  57
  58/**
  59 * Returns the length of the first line of msg.
  60 */
  61static int linelen(const char *msg)
  62{
  63        return strchrnul(msg, '\n') - msg;
  64}
  65
  66enum patch_format {
  67        PATCH_FORMAT_UNKNOWN = 0,
  68        PATCH_FORMAT_MBOX
  69};
  70
  71enum keep_type {
  72        KEEP_FALSE = 0,
  73        KEEP_TRUE,      /* pass -k flag to git-mailinfo */
  74        KEEP_NON_PATCH  /* pass -b flag to git-mailinfo */
  75};
  76
  77struct am_state {
  78        /* state directory path */
  79        char *dir;
  80
  81        /* current and last patch numbers, 1-indexed */
  82        int cur;
  83        int last;
  84
  85        /* commit metadata and message */
  86        char *author_name;
  87        char *author_email;
  88        char *author_date;
  89        char *msg;
  90        size_t msg_len;
  91
  92        /* number of digits in patch filename */
  93        int prec;
  94
  95        /* various operating modes and command line options */
  96        int threeway;
  97        int quiet;
  98        int signoff;
  99        int utf8;
 100        int keep; /* enum keep_type */
 101        const char *resolvemsg;
 102        int rebasing;
 103};
 104
 105/**
 106 * Initializes am_state with the default values. The state directory is set to
 107 * dir.
 108 */
 109static void am_state_init(struct am_state *state, const char *dir)
 110{
 111        memset(state, 0, sizeof(*state));
 112
 113        assert(dir);
 114        state->dir = xstrdup(dir);
 115
 116        state->prec = 4;
 117
 118        state->utf8 = 1;
 119}
 120
 121/**
 122 * Releases memory allocated by an am_state.
 123 */
 124static void am_state_release(struct am_state *state)
 125{
 126        free(state->dir);
 127        free(state->author_name);
 128        free(state->author_email);
 129        free(state->author_date);
 130        free(state->msg);
 131}
 132
 133/**
 134 * Returns path relative to the am_state directory.
 135 */
 136static inline const char *am_path(const struct am_state *state, const char *path)
 137{
 138        return mkpath("%s/%s", state->dir, path);
 139}
 140
 141/**
 142 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
 143 * at the end.
 144 */
 145static void say(const struct am_state *state, FILE *fp, const char *fmt, ...)
 146{
 147        va_list ap;
 148
 149        va_start(ap, fmt);
 150        if (!state->quiet) {
 151                vfprintf(fp, fmt, ap);
 152                putc('\n', fp);
 153        }
 154        va_end(ap);
 155}
 156
 157/**
 158 * Returns 1 if there is an am session in progress, 0 otherwise.
 159 */
 160static int am_in_progress(const struct am_state *state)
 161{
 162        struct stat st;
 163
 164        if (lstat(state->dir, &st) < 0 || !S_ISDIR(st.st_mode))
 165                return 0;
 166        if (lstat(am_path(state, "last"), &st) || !S_ISREG(st.st_mode))
 167                return 0;
 168        if (lstat(am_path(state, "next"), &st) || !S_ISREG(st.st_mode))
 169                return 0;
 170        return 1;
 171}
 172
 173/**
 174 * Reads the contents of `file` in the `state` directory into `sb`. Returns the
 175 * number of bytes read on success, -1 if the file does not exist. If `trim` is
 176 * set, trailing whitespace will be removed.
 177 */
 178static int read_state_file(struct strbuf *sb, const struct am_state *state,
 179                        const char *file, int trim)
 180{
 181        strbuf_reset(sb);
 182
 183        if (strbuf_read_file(sb, am_path(state, file), 0) >= 0) {
 184                if (trim)
 185                        strbuf_trim(sb);
 186
 187                return sb->len;
 188        }
 189
 190        if (errno == ENOENT)
 191                return -1;
 192
 193        die_errno(_("could not read '%s'"), am_path(state, file));
 194}
 195
 196/**
 197 * Reads a KEY=VALUE shell variable assignment from `fp`, returning the VALUE
 198 * as a newly-allocated string. VALUE must be a quoted string, and the KEY must
 199 * match `key`. Returns NULL on failure.
 200 *
 201 * This is used by read_author_script() to read the GIT_AUTHOR_* variables from
 202 * the author-script.
 203 */
 204static char *read_shell_var(FILE *fp, const char *key)
 205{
 206        struct strbuf sb = STRBUF_INIT;
 207        const char *str;
 208
 209        if (strbuf_getline(&sb, fp, '\n'))
 210                goto fail;
 211
 212        if (!skip_prefix(sb.buf, key, &str))
 213                goto fail;
 214
 215        if (!skip_prefix(str, "=", &str))
 216                goto fail;
 217
 218        strbuf_remove(&sb, 0, str - sb.buf);
 219
 220        str = sq_dequote(sb.buf);
 221        if (!str)
 222                goto fail;
 223
 224        return strbuf_detach(&sb, NULL);
 225
 226fail:
 227        strbuf_release(&sb);
 228        return NULL;
 229}
 230
 231/**
 232 * Reads and parses the state directory's "author-script" file, and sets
 233 * state->author_name, state->author_email and state->author_date accordingly.
 234 * Returns 0 on success, -1 if the file could not be parsed.
 235 *
 236 * The author script is of the format:
 237 *
 238 *      GIT_AUTHOR_NAME='$author_name'
 239 *      GIT_AUTHOR_EMAIL='$author_email'
 240 *      GIT_AUTHOR_DATE='$author_date'
 241 *
 242 * where $author_name, $author_email and $author_date are quoted. We are strict
 243 * with our parsing, as the file was meant to be eval'd in the old git-am.sh
 244 * script, and thus if the file differs from what this function expects, it is
 245 * better to bail out than to do something that the user does not expect.
 246 */
 247static int read_author_script(struct am_state *state)
 248{
 249        const char *filename = am_path(state, "author-script");
 250        FILE *fp;
 251
 252        assert(!state->author_name);
 253        assert(!state->author_email);
 254        assert(!state->author_date);
 255
 256        fp = fopen(filename, "r");
 257        if (!fp) {
 258                if (errno == ENOENT)
 259                        return 0;
 260                die_errno(_("could not open '%s' for reading"), filename);
 261        }
 262
 263        state->author_name = read_shell_var(fp, "GIT_AUTHOR_NAME");
 264        if (!state->author_name) {
 265                fclose(fp);
 266                return -1;
 267        }
 268
 269        state->author_email = read_shell_var(fp, "GIT_AUTHOR_EMAIL");
 270        if (!state->author_email) {
 271                fclose(fp);
 272                return -1;
 273        }
 274
 275        state->author_date = read_shell_var(fp, "GIT_AUTHOR_DATE");
 276        if (!state->author_date) {
 277                fclose(fp);
 278                return -1;
 279        }
 280
 281        if (fgetc(fp) != EOF) {
 282                fclose(fp);
 283                return -1;
 284        }
 285
 286        fclose(fp);
 287        return 0;
 288}
 289
 290/**
 291 * Saves state->author_name, state->author_email and state->author_date in the
 292 * state directory's "author-script" file.
 293 */
 294static void write_author_script(const struct am_state *state)
 295{
 296        struct strbuf sb = STRBUF_INIT;
 297
 298        strbuf_addstr(&sb, "GIT_AUTHOR_NAME=");
 299        sq_quote_buf(&sb, state->author_name);
 300        strbuf_addch(&sb, '\n');
 301
 302        strbuf_addstr(&sb, "GIT_AUTHOR_EMAIL=");
 303        sq_quote_buf(&sb, state->author_email);
 304        strbuf_addch(&sb, '\n');
 305
 306        strbuf_addstr(&sb, "GIT_AUTHOR_DATE=");
 307        sq_quote_buf(&sb, state->author_date);
 308        strbuf_addch(&sb, '\n');
 309
 310        write_file(am_path(state, "author-script"), 1, "%s", sb.buf);
 311
 312        strbuf_release(&sb);
 313}
 314
 315/**
 316 * Reads the commit message from the state directory's "final-commit" file,
 317 * setting state->msg to its contents and state->msg_len to the length of its
 318 * contents in bytes.
 319 *
 320 * Returns 0 on success, -1 if the file does not exist.
 321 */
 322static int read_commit_msg(struct am_state *state)
 323{
 324        struct strbuf sb = STRBUF_INIT;
 325
 326        assert(!state->msg);
 327
 328        if (read_state_file(&sb, state, "final-commit", 0) < 0) {
 329                strbuf_release(&sb);
 330                return -1;
 331        }
 332
 333        state->msg = strbuf_detach(&sb, &state->msg_len);
 334        return 0;
 335}
 336
 337/**
 338 * Saves state->msg in the state directory's "final-commit" file.
 339 */
 340static void write_commit_msg(const struct am_state *state)
 341{
 342        int fd;
 343        const char *filename = am_path(state, "final-commit");
 344
 345        fd = xopen(filename, O_WRONLY | O_CREAT, 0666);
 346        if (write_in_full(fd, state->msg, state->msg_len) < 0)
 347                die_errno(_("could not write to %s"), filename);
 348        close(fd);
 349}
 350
 351/**
 352 * Loads state from disk.
 353 */
 354static void am_load(struct am_state *state)
 355{
 356        struct strbuf sb = STRBUF_INIT;
 357
 358        if (read_state_file(&sb, state, "next", 1) < 0)
 359                die("BUG: state file 'next' does not exist");
 360        state->cur = strtol(sb.buf, NULL, 10);
 361
 362        if (read_state_file(&sb, state, "last", 1) < 0)
 363                die("BUG: state file 'last' does not exist");
 364        state->last = strtol(sb.buf, NULL, 10);
 365
 366        if (read_author_script(state) < 0)
 367                die(_("could not parse author script"));
 368
 369        read_commit_msg(state);
 370
 371        read_state_file(&sb, state, "threeway", 1);
 372        state->threeway = !strcmp(sb.buf, "t");
 373
 374        read_state_file(&sb, state, "quiet", 1);
 375        state->quiet = !strcmp(sb.buf, "t");
 376
 377        read_state_file(&sb, state, "sign", 1);
 378        state->signoff = !strcmp(sb.buf, "t");
 379
 380        read_state_file(&sb, state, "utf8", 1);
 381        state->utf8 = !strcmp(sb.buf, "t");
 382
 383        read_state_file(&sb, state, "keep", 1);
 384        if (!strcmp(sb.buf, "t"))
 385                state->keep = KEEP_TRUE;
 386        else if (!strcmp(sb.buf, "b"))
 387                state->keep = KEEP_NON_PATCH;
 388        else
 389                state->keep = KEEP_FALSE;
 390
 391        state->rebasing = !!file_exists(am_path(state, "rebasing"));
 392
 393        strbuf_release(&sb);
 394}
 395
 396/**
 397 * Removes the am_state directory, forcefully terminating the current am
 398 * session.
 399 */
 400static void am_destroy(const struct am_state *state)
 401{
 402        struct strbuf sb = STRBUF_INIT;
 403
 404        strbuf_addstr(&sb, state->dir);
 405        remove_dir_recursively(&sb, 0);
 406        strbuf_release(&sb);
 407}
 408
 409/**
 410 * Determines if the file looks like a piece of RFC2822 mail by grabbing all
 411 * non-indented lines and checking if they look like they begin with valid
 412 * header field names.
 413 *
 414 * Returns 1 if the file looks like a piece of mail, 0 otherwise.
 415 */
 416static int is_mail(FILE *fp)
 417{
 418        const char *header_regex = "^[!-9;-~]+:";
 419        struct strbuf sb = STRBUF_INIT;
 420        regex_t regex;
 421        int ret = 1;
 422
 423        if (fseek(fp, 0L, SEEK_SET))
 424                die_errno(_("fseek failed"));
 425
 426        if (regcomp(&regex, header_regex, REG_NOSUB | REG_EXTENDED))
 427                die("invalid pattern: %s", header_regex);
 428
 429        while (!strbuf_getline_crlf(&sb, fp)) {
 430                if (!sb.len)
 431                        break; /* End of header */
 432
 433                /* Ignore indented folded lines */
 434                if (*sb.buf == '\t' || *sb.buf == ' ')
 435                        continue;
 436
 437                /* It's a header if it matches header_regex */
 438                if (regexec(&regex, sb.buf, 0, NULL, 0)) {
 439                        ret = 0;
 440                        goto done;
 441                }
 442        }
 443
 444done:
 445        regfree(&regex);
 446        strbuf_release(&sb);
 447        return ret;
 448}
 449
 450/**
 451 * Attempts to detect the patch_format of the patches contained in `paths`,
 452 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
 453 * detection fails.
 454 */
 455static int detect_patch_format(const char **paths)
 456{
 457        enum patch_format ret = PATCH_FORMAT_UNKNOWN;
 458        struct strbuf l1 = STRBUF_INIT;
 459        FILE *fp;
 460
 461        /*
 462         * We default to mbox format if input is from stdin and for directories
 463         */
 464        if (!*paths || !strcmp(*paths, "-") || is_directory(*paths))
 465                return PATCH_FORMAT_MBOX;
 466
 467        /*
 468         * Otherwise, check the first few lines of the first patch, starting
 469         * from the first non-blank line, to try to detect its format.
 470         */
 471
 472        fp = xfopen(*paths, "r");
 473
 474        while (!strbuf_getline_crlf(&l1, fp)) {
 475                if (l1.len)
 476                        break;
 477        }
 478
 479        if (starts_with(l1.buf, "From ") || starts_with(l1.buf, "From: ")) {
 480                ret = PATCH_FORMAT_MBOX;
 481                goto done;
 482        }
 483
 484        if (l1.len && is_mail(fp)) {
 485                ret = PATCH_FORMAT_MBOX;
 486                goto done;
 487        }
 488
 489done:
 490        fclose(fp);
 491        strbuf_release(&l1);
 492        return ret;
 493}
 494
 495/**
 496 * Splits out individual email patches from `paths`, where each path is either
 497 * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
 498 */
 499static int split_mail_mbox(struct am_state *state, const char **paths)
 500{
 501        struct child_process cp = CHILD_PROCESS_INIT;
 502        struct strbuf last = STRBUF_INIT;
 503
 504        cp.git_cmd = 1;
 505        argv_array_push(&cp.args, "mailsplit");
 506        argv_array_pushf(&cp.args, "-d%d", state->prec);
 507        argv_array_pushf(&cp.args, "-o%s", state->dir);
 508        argv_array_push(&cp.args, "-b");
 509        argv_array_push(&cp.args, "--");
 510        argv_array_pushv(&cp.args, paths);
 511
 512        if (capture_command(&cp, &last, 8))
 513                return -1;
 514
 515        state->cur = 1;
 516        state->last = strtol(last.buf, NULL, 10);
 517
 518        return 0;
 519}
 520
 521/**
 522 * Splits a list of files/directories into individual email patches. Each path
 523 * in `paths` must be a file/directory that is formatted according to
 524 * `patch_format`.
 525 *
 526 * Once split out, the individual email patches will be stored in the state
 527 * directory, with each patch's filename being its index, padded to state->prec
 528 * digits.
 529 *
 530 * state->cur will be set to the index of the first mail, and state->last will
 531 * be set to the index of the last mail.
 532 *
 533 * Returns 0 on success, -1 on failure.
 534 */
 535static int split_mail(struct am_state *state, enum patch_format patch_format,
 536                        const char **paths)
 537{
 538        switch (patch_format) {
 539        case PATCH_FORMAT_MBOX:
 540                return split_mail_mbox(state, paths);
 541        default:
 542                die("BUG: invalid patch_format");
 543        }
 544        return -1;
 545}
 546
 547/**
 548 * Setup a new am session for applying patches
 549 */
 550static void am_setup(struct am_state *state, enum patch_format patch_format,
 551                        const char **paths)
 552{
 553        unsigned char curr_head[GIT_SHA1_RAWSZ];
 554        const char *str;
 555
 556        if (!patch_format)
 557                patch_format = detect_patch_format(paths);
 558
 559        if (!patch_format) {
 560                fprintf_ln(stderr, _("Patch format detection failed."));
 561                exit(128);
 562        }
 563
 564        if (mkdir(state->dir, 0777) < 0 && errno != EEXIST)
 565                die_errno(_("failed to create directory '%s'"), state->dir);
 566
 567        if (split_mail(state, patch_format, paths) < 0) {
 568                am_destroy(state);
 569                die(_("Failed to split patches."));
 570        }
 571
 572        if (state->rebasing)
 573                state->threeway = 1;
 574
 575        write_file(am_path(state, "threeway"), 1, state->threeway ? "t" : "f");
 576
 577        write_file(am_path(state, "quiet"), 1, state->quiet ? "t" : "f");
 578
 579        write_file(am_path(state, "sign"), 1, state->signoff ? "t" : "f");
 580
 581        write_file(am_path(state, "utf8"), 1, state->utf8 ? "t" : "f");
 582
 583        switch (state->keep) {
 584        case KEEP_FALSE:
 585                str = "f";
 586                break;
 587        case KEEP_TRUE:
 588                str = "t";
 589                break;
 590        case KEEP_NON_PATCH:
 591                str = "b";
 592                break;
 593        default:
 594                die("BUG: invalid value for state->keep");
 595        }
 596
 597        write_file(am_path(state, "keep"), 1, "%s", str);
 598
 599        if (state->rebasing)
 600                write_file(am_path(state, "rebasing"), 1, "%s", "");
 601        else
 602                write_file(am_path(state, "applying"), 1, "%s", "");
 603
 604        if (!get_sha1("HEAD", curr_head)) {
 605                write_file(am_path(state, "abort-safety"), 1, "%s", sha1_to_hex(curr_head));
 606                if (!state->rebasing)
 607                        update_ref("am", "ORIG_HEAD", curr_head, NULL, 0,
 608                                        UPDATE_REFS_DIE_ON_ERR);
 609        } else {
 610                write_file(am_path(state, "abort-safety"), 1, "%s", "");
 611                if (!state->rebasing)
 612                        delete_ref("ORIG_HEAD", NULL, 0);
 613        }
 614
 615        /*
 616         * NOTE: Since the "next" and "last" files determine if an am_state
 617         * session is in progress, they should be written last.
 618         */
 619
 620        write_file(am_path(state, "next"), 1, "%d", state->cur);
 621
 622        write_file(am_path(state, "last"), 1, "%d", state->last);
 623}
 624
 625/**
 626 * Increments the patch pointer, and cleans am_state for the application of the
 627 * next patch.
 628 */
 629static void am_next(struct am_state *state)
 630{
 631        unsigned char head[GIT_SHA1_RAWSZ];
 632
 633        free(state->author_name);
 634        state->author_name = NULL;
 635
 636        free(state->author_email);
 637        state->author_email = NULL;
 638
 639        free(state->author_date);
 640        state->author_date = NULL;
 641
 642        free(state->msg);
 643        state->msg = NULL;
 644        state->msg_len = 0;
 645
 646        unlink(am_path(state, "author-script"));
 647        unlink(am_path(state, "final-commit"));
 648
 649        if (!get_sha1("HEAD", head))
 650                write_file(am_path(state, "abort-safety"), 1, "%s", sha1_to_hex(head));
 651        else
 652                write_file(am_path(state, "abort-safety"), 1, "%s", "");
 653
 654        state->cur++;
 655        write_file(am_path(state, "next"), 1, "%d", state->cur);
 656}
 657
 658/**
 659 * Returns the filename of the current patch email.
 660 */
 661static const char *msgnum(const struct am_state *state)
 662{
 663        static struct strbuf sb = STRBUF_INIT;
 664
 665        strbuf_reset(&sb);
 666        strbuf_addf(&sb, "%0*d", state->prec, state->cur);
 667
 668        return sb.buf;
 669}
 670
 671/**
 672 * Refresh and write index.
 673 */
 674static void refresh_and_write_cache(void)
 675{
 676        struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
 677
 678        hold_locked_index(lock_file, 1);
 679        refresh_cache(REFRESH_QUIET);
 680        if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
 681                die(_("unable to write index file"));
 682}
 683
 684/**
 685 * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn
 686 * branch, returns 1 if there are entries in the index, 0 otherwise. If an
 687 * strbuf is provided, the space-separated list of files that differ will be
 688 * appended to it.
 689 */
 690static int index_has_changes(struct strbuf *sb)
 691{
 692        unsigned char head[GIT_SHA1_RAWSZ];
 693        int i;
 694
 695        if (!get_sha1_tree("HEAD", head)) {
 696                struct diff_options opt;
 697
 698                diff_setup(&opt);
 699                DIFF_OPT_SET(&opt, EXIT_WITH_STATUS);
 700                if (!sb)
 701                        DIFF_OPT_SET(&opt, QUICK);
 702                do_diff_cache(head, &opt);
 703                diffcore_std(&opt);
 704                for (i = 0; sb && i < diff_queued_diff.nr; i++) {
 705                        if (i)
 706                                strbuf_addch(sb, ' ');
 707                        strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);
 708                }
 709                diff_flush(&opt);
 710                return DIFF_OPT_TST(&opt, HAS_CHANGES) != 0;
 711        } else {
 712                for (i = 0; sb && i < active_nr; i++) {
 713                        if (i)
 714                                strbuf_addch(sb, ' ');
 715                        strbuf_addstr(sb, active_cache[i]->name);
 716                }
 717                return !!active_nr;
 718        }
 719}
 720
 721/**
 722 * Dies with a user-friendly message on how to proceed after resolving the
 723 * problem. This message can be overridden with state->resolvemsg.
 724 */
 725static void NORETURN die_user_resolve(const struct am_state *state)
 726{
 727        if (state->resolvemsg) {
 728                printf_ln("%s", state->resolvemsg);
 729        } else {
 730                const char *cmdline = "git am";
 731
 732                printf_ln(_("When you have resolved this problem, run \"%s --continue\"."), cmdline);
 733                printf_ln(_("If you prefer to skip this patch, run \"%s --skip\" instead."), cmdline);
 734                printf_ln(_("To restore the original branch and stop patching, run \"%s --abort\"."), cmdline);
 735        }
 736
 737        exit(128);
 738}
 739
 740/**
 741 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
 742 * state->msg will be set to the patch message. state->author_name,
 743 * state->author_email and state->author_date will be set to the patch author's
 744 * name, email and date respectively. The patch body will be written to the
 745 * state directory's "patch" file.
 746 *
 747 * Returns 1 if the patch should be skipped, 0 otherwise.
 748 */
 749static int parse_mail(struct am_state *state, const char *mail)
 750{
 751        FILE *fp;
 752        struct child_process cp = CHILD_PROCESS_INIT;
 753        struct strbuf sb = STRBUF_INIT;
 754        struct strbuf msg = STRBUF_INIT;
 755        struct strbuf author_name = STRBUF_INIT;
 756        struct strbuf author_date = STRBUF_INIT;
 757        struct strbuf author_email = STRBUF_INIT;
 758        int ret = 0;
 759
 760        cp.git_cmd = 1;
 761        cp.in = xopen(mail, O_RDONLY, 0);
 762        cp.out = xopen(am_path(state, "info"), O_WRONLY | O_CREAT, 0777);
 763
 764        argv_array_push(&cp.args, "mailinfo");
 765        argv_array_push(&cp.args, state->utf8 ? "-u" : "-n");
 766
 767        switch (state->keep) {
 768        case KEEP_FALSE:
 769                break;
 770        case KEEP_TRUE:
 771                argv_array_push(&cp.args, "-k");
 772                break;
 773        case KEEP_NON_PATCH:
 774                argv_array_push(&cp.args, "-b");
 775                break;
 776        default:
 777                die("BUG: invalid value for state->keep");
 778        }
 779
 780        argv_array_push(&cp.args, am_path(state, "msg"));
 781        argv_array_push(&cp.args, am_path(state, "patch"));
 782
 783        if (run_command(&cp) < 0)
 784                die("could not parse patch");
 785
 786        close(cp.in);
 787        close(cp.out);
 788
 789        /* Extract message and author information */
 790        fp = xfopen(am_path(state, "info"), "r");
 791        while (!strbuf_getline(&sb, fp, '\n')) {
 792                const char *x;
 793
 794                if (skip_prefix(sb.buf, "Subject: ", &x)) {
 795                        if (msg.len)
 796                                strbuf_addch(&msg, '\n');
 797                        strbuf_addstr(&msg, x);
 798                } else if (skip_prefix(sb.buf, "Author: ", &x))
 799                        strbuf_addstr(&author_name, x);
 800                else if (skip_prefix(sb.buf, "Email: ", &x))
 801                        strbuf_addstr(&author_email, x);
 802                else if (skip_prefix(sb.buf, "Date: ", &x))
 803                        strbuf_addstr(&author_date, x);
 804        }
 805        fclose(fp);
 806
 807        /* Skip pine's internal folder data */
 808        if (!strcmp(author_name.buf, "Mail System Internal Data")) {
 809                ret = 1;
 810                goto finish;
 811        }
 812
 813        if (is_empty_file(am_path(state, "patch"))) {
 814                printf_ln(_("Patch is empty. Was it split wrong?"));
 815                die_user_resolve(state);
 816        }
 817
 818        strbuf_addstr(&msg, "\n\n");
 819        if (strbuf_read_file(&msg, am_path(state, "msg"), 0) < 0)
 820                die_errno(_("could not read '%s'"), am_path(state, "msg"));
 821        stripspace(&msg, 0);
 822
 823        if (state->signoff)
 824                append_signoff(&msg, 0, 0);
 825
 826        assert(!state->author_name);
 827        state->author_name = strbuf_detach(&author_name, NULL);
 828
 829        assert(!state->author_email);
 830        state->author_email = strbuf_detach(&author_email, NULL);
 831
 832        assert(!state->author_date);
 833        state->author_date = strbuf_detach(&author_date, NULL);
 834
 835        assert(!state->msg);
 836        state->msg = strbuf_detach(&msg, &state->msg_len);
 837
 838finish:
 839        strbuf_release(&msg);
 840        strbuf_release(&author_date);
 841        strbuf_release(&author_email);
 842        strbuf_release(&author_name);
 843        strbuf_release(&sb);
 844        return ret;
 845}
 846
 847/**
 848 * Sets commit_id to the commit hash where the mail was generated from.
 849 * Returns 0 on success, -1 on failure.
 850 */
 851static int get_mail_commit_sha1(unsigned char *commit_id, const char *mail)
 852{
 853        struct strbuf sb = STRBUF_INIT;
 854        FILE *fp = xfopen(mail, "r");
 855        const char *x;
 856
 857        if (strbuf_getline(&sb, fp, '\n'))
 858                return -1;
 859
 860        if (!skip_prefix(sb.buf, "From ", &x))
 861                return -1;
 862
 863        if (get_sha1_hex(x, commit_id) < 0)
 864                return -1;
 865
 866        strbuf_release(&sb);
 867        fclose(fp);
 868        return 0;
 869}
 870
 871/**
 872 * Sets state->msg, state->author_name, state->author_email, state->author_date
 873 * to the commit's respective info.
 874 */
 875static void get_commit_info(struct am_state *state, struct commit *commit)
 876{
 877        const char *buffer, *ident_line, *author_date, *msg;
 878        size_t ident_len;
 879        struct ident_split ident_split;
 880        struct strbuf sb = STRBUF_INIT;
 881
 882        buffer = logmsg_reencode(commit, NULL, get_commit_output_encoding());
 883
 884        ident_line = find_commit_header(buffer, "author", &ident_len);
 885
 886        if (split_ident_line(&ident_split, ident_line, ident_len) < 0) {
 887                strbuf_add(&sb, ident_line, ident_len);
 888                die(_("invalid ident line: %s"), sb.buf);
 889        }
 890
 891        assert(!state->author_name);
 892        if (ident_split.name_begin) {
 893                strbuf_add(&sb, ident_split.name_begin,
 894                        ident_split.name_end - ident_split.name_begin);
 895                state->author_name = strbuf_detach(&sb, NULL);
 896        } else
 897                state->author_name = xstrdup("");
 898
 899        assert(!state->author_email);
 900        if (ident_split.mail_begin) {
 901                strbuf_add(&sb, ident_split.mail_begin,
 902                        ident_split.mail_end - ident_split.mail_begin);
 903                state->author_email = strbuf_detach(&sb, NULL);
 904        } else
 905                state->author_email = xstrdup("");
 906
 907        author_date = show_ident_date(&ident_split, DATE_MODE(NORMAL));
 908        strbuf_addstr(&sb, author_date);
 909        assert(!state->author_date);
 910        state->author_date = strbuf_detach(&sb, NULL);
 911
 912        assert(!state->msg);
 913        msg = strstr(buffer, "\n\n");
 914        if (!msg)
 915                die(_("unable to parse commit %s"), sha1_to_hex(commit->object.sha1));
 916        state->msg = xstrdup(msg + 2);
 917        state->msg_len = strlen(state->msg);
 918}
 919
 920/**
 921 * Writes `commit` as a patch to the state directory's "patch" file.
 922 */
 923static void write_commit_patch(const struct am_state *state, struct commit *commit)
 924{
 925        struct rev_info rev_info;
 926        FILE *fp;
 927
 928        fp = xfopen(am_path(state, "patch"), "w");
 929        init_revisions(&rev_info, NULL);
 930        rev_info.diff = 1;
 931        rev_info.abbrev = 0;
 932        rev_info.disable_stdin = 1;
 933        rev_info.show_root_diff = 1;
 934        rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
 935        rev_info.no_commit_id = 1;
 936        DIFF_OPT_SET(&rev_info.diffopt, BINARY);
 937        DIFF_OPT_SET(&rev_info.diffopt, FULL_INDEX);
 938        rev_info.diffopt.use_color = 0;
 939        rev_info.diffopt.file = fp;
 940        rev_info.diffopt.close_file = 1;
 941        add_pending_object(&rev_info, &commit->object, "");
 942        diff_setup_done(&rev_info.diffopt);
 943        log_tree_commit(&rev_info, commit);
 944}
 945
 946/**
 947 * Like parse_mail(), but parses the mail by looking up its commit ID
 948 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
 949 * of patches.
 950 *
 951 * Will always return 0 as the patch should never be skipped.
 952 */
 953static int parse_mail_rebase(struct am_state *state, const char *mail)
 954{
 955        struct commit *commit;
 956        unsigned char commit_sha1[GIT_SHA1_RAWSZ];
 957
 958        if (get_mail_commit_sha1(commit_sha1, mail) < 0)
 959                die(_("could not parse %s"), mail);
 960
 961        commit = lookup_commit_or_die(commit_sha1, mail);
 962
 963        get_commit_info(state, commit);
 964
 965        write_commit_patch(state, commit);
 966
 967        return 0;
 968}
 969
 970/**
 971 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
 972 * `index_file` is not NULL, the patch will be applied to that index.
 973 */
 974static int run_apply(const struct am_state *state, const char *index_file)
 975{
 976        struct child_process cp = CHILD_PROCESS_INIT;
 977
 978        cp.git_cmd = 1;
 979
 980        if (index_file)
 981                argv_array_pushf(&cp.env_array, "GIT_INDEX_FILE=%s", index_file);
 982
 983        /*
 984         * If we are allowed to fall back on 3-way merge, don't give false
 985         * errors during the initial attempt.
 986         */
 987        if (state->threeway && !index_file) {
 988                cp.no_stdout = 1;
 989                cp.no_stderr = 1;
 990        }
 991
 992        argv_array_push(&cp.args, "apply");
 993
 994        if (index_file)
 995                argv_array_push(&cp.args, "--cached");
 996        else
 997                argv_array_push(&cp.args, "--index");
 998
 999        argv_array_push(&cp.args, am_path(state, "patch"));
1000
1001        if (run_command(&cp))
1002                return -1;
1003
1004        /* Reload index as git-apply will have modified it. */
1005        discard_cache();
1006        read_cache_from(index_file ? index_file : get_index_file());
1007
1008        return 0;
1009}
1010
1011/**
1012 * Builds an index that contains just the blobs needed for a 3way merge.
1013 */
1014static int build_fake_ancestor(const struct am_state *state, const char *index_file)
1015{
1016        struct child_process cp = CHILD_PROCESS_INIT;
1017
1018        cp.git_cmd = 1;
1019        argv_array_push(&cp.args, "apply");
1020        argv_array_pushf(&cp.args, "--build-fake-ancestor=%s", index_file);
1021        argv_array_push(&cp.args, am_path(state, "patch"));
1022
1023        if (run_command(&cp))
1024                return -1;
1025
1026        return 0;
1027}
1028
1029/**
1030 * Attempt a threeway merge, using index_path as the temporary index.
1031 */
1032static int fall_back_threeway(const struct am_state *state, const char *index_path)
1033{
1034        unsigned char orig_tree[GIT_SHA1_RAWSZ], his_tree[GIT_SHA1_RAWSZ],
1035                      our_tree[GIT_SHA1_RAWSZ];
1036        const unsigned char *bases[1] = {orig_tree};
1037        struct merge_options o;
1038        struct commit *result;
1039        char *his_tree_name;
1040
1041        if (get_sha1("HEAD", our_tree) < 0)
1042                hashcpy(our_tree, EMPTY_TREE_SHA1_BIN);
1043
1044        if (build_fake_ancestor(state, index_path))
1045                return error("could not build fake ancestor");
1046
1047        discard_cache();
1048        read_cache_from(index_path);
1049
1050        if (write_index_as_tree(orig_tree, &the_index, index_path, 0, NULL))
1051                return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));
1052
1053        say(state, stdout, _("Using index info to reconstruct a base tree..."));
1054
1055        if (!state->quiet) {
1056                /*
1057                 * List paths that needed 3-way fallback, so that the user can
1058                 * review them with extra care to spot mismerges.
1059                 */
1060                struct rev_info rev_info;
1061                const char *diff_filter_str = "--diff-filter=AM";
1062
1063                init_revisions(&rev_info, NULL);
1064                rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;
1065                diff_opt_parse(&rev_info.diffopt, &diff_filter_str, 1);
1066                add_pending_sha1(&rev_info, "HEAD", our_tree, 0);
1067                diff_setup_done(&rev_info.diffopt);
1068                run_diff_index(&rev_info, 1);
1069        }
1070
1071        if (run_apply(state, index_path))
1072                return error(_("Did you hand edit your patch?\n"
1073                                "It does not apply to blobs recorded in its index."));
1074
1075        if (write_index_as_tree(his_tree, &the_index, index_path, 0, NULL))
1076                return error("could not write tree");
1077
1078        say(state, stdout, _("Falling back to patching base and 3-way merge..."));
1079
1080        discard_cache();
1081        read_cache();
1082
1083        /*
1084         * This is not so wrong. Depending on which base we picked, orig_tree
1085         * may be wildly different from ours, but his_tree has the same set of
1086         * wildly different changes in parts the patch did not touch, so
1087         * recursive ends up canceling them, saying that we reverted all those
1088         * changes.
1089         */
1090
1091        init_merge_options(&o);
1092
1093        o.branch1 = "HEAD";
1094        his_tree_name = xstrfmt("%.*s", linelen(state->msg), state->msg);
1095        o.branch2 = his_tree_name;
1096
1097        if (state->quiet)
1098                o.verbosity = 0;
1099
1100        if (merge_recursive_generic(&o, our_tree, his_tree, 1, bases, &result)) {
1101                free(his_tree_name);
1102                return error(_("Failed to merge in the changes."));
1103        }
1104
1105        free(his_tree_name);
1106        return 0;
1107}
1108
1109/**
1110 * Commits the current index with state->msg as the commit message and
1111 * state->author_name, state->author_email and state->author_date as the author
1112 * information.
1113 */
1114static void do_commit(const struct am_state *state)
1115{
1116        unsigned char tree[GIT_SHA1_RAWSZ], parent[GIT_SHA1_RAWSZ],
1117                      commit[GIT_SHA1_RAWSZ];
1118        unsigned char *ptr;
1119        struct commit_list *parents = NULL;
1120        const char *reflog_msg, *author;
1121        struct strbuf sb = STRBUF_INIT;
1122
1123        if (write_cache_as_tree(tree, 0, NULL))
1124                die(_("git write-tree failed to write a tree"));
1125
1126        if (!get_sha1_commit("HEAD", parent)) {
1127                ptr = parent;
1128                commit_list_insert(lookup_commit(parent), &parents);
1129        } else {
1130                ptr = NULL;
1131                say(state, stderr, _("applying to an empty history"));
1132        }
1133
1134        author = fmt_ident(state->author_name, state->author_email,
1135                        state->author_date, IDENT_STRICT);
1136
1137        if (commit_tree(state->msg, state->msg_len, tree, parents, commit,
1138                                author, NULL))
1139                die(_("failed to write commit object"));
1140
1141        reflog_msg = getenv("GIT_REFLOG_ACTION");
1142        if (!reflog_msg)
1143                reflog_msg = "am";
1144
1145        strbuf_addf(&sb, "%s: %.*s", reflog_msg, linelen(state->msg),
1146                        state->msg);
1147
1148        update_ref(sb.buf, "HEAD", commit, ptr, 0, UPDATE_REFS_DIE_ON_ERR);
1149
1150        strbuf_release(&sb);
1151}
1152
1153/**
1154 * Validates the am_state for resuming -- the "msg" and authorship fields must
1155 * be filled up.
1156 */
1157static void validate_resume_state(const struct am_state *state)
1158{
1159        if (!state->msg)
1160                die(_("cannot resume: %s does not exist."),
1161                        am_path(state, "final-commit"));
1162
1163        if (!state->author_name || !state->author_email || !state->author_date)
1164                die(_("cannot resume: %s does not exist."),
1165                        am_path(state, "author-script"));
1166}
1167
1168/**
1169 * Applies all queued mail.
1170 *
1171 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
1172 * well as the state directory's "patch" file is used as-is for applying the
1173 * patch and committing it.
1174 */
1175static void am_run(struct am_state *state, int resume)
1176{
1177        const char *argv_gc_auto[] = {"gc", "--auto", NULL};
1178        struct strbuf sb = STRBUF_INIT;
1179
1180        unlink(am_path(state, "dirtyindex"));
1181
1182        refresh_and_write_cache();
1183
1184        if (index_has_changes(&sb)) {
1185                write_file(am_path(state, "dirtyindex"), 1, "t");
1186                die(_("Dirty index: cannot apply patches (dirty: %s)"), sb.buf);
1187        }
1188
1189        strbuf_release(&sb);
1190
1191        while (state->cur <= state->last) {
1192                const char *mail = am_path(state, msgnum(state));
1193                int apply_status;
1194
1195                if (!file_exists(mail))
1196                        goto next;
1197
1198                if (resume) {
1199                        validate_resume_state(state);
1200                        resume = 0;
1201                } else {
1202                        int skip;
1203
1204                        if (state->rebasing)
1205                                skip = parse_mail_rebase(state, mail);
1206                        else
1207                                skip = parse_mail(state, mail);
1208
1209                        if (skip)
1210                                goto next; /* mail should be skipped */
1211
1212                        write_author_script(state);
1213                        write_commit_msg(state);
1214                }
1215
1216                say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1217
1218                apply_status = run_apply(state, NULL);
1219
1220                if (apply_status && state->threeway) {
1221                        struct strbuf sb = STRBUF_INIT;
1222
1223                        strbuf_addstr(&sb, am_path(state, "patch-merge-index"));
1224                        apply_status = fall_back_threeway(state, sb.buf);
1225                        strbuf_release(&sb);
1226
1227                        /*
1228                         * Applying the patch to an earlier tree and merging
1229                         * the result may have produced the same tree as ours.
1230                         */
1231                        if (!apply_status && !index_has_changes(NULL)) {
1232                                say(state, stdout, _("No changes -- Patch already applied."));
1233                                goto next;
1234                        }
1235                }
1236
1237                if (apply_status) {
1238                        int advice_amworkdir = 1;
1239
1240                        printf_ln(_("Patch failed at %s %.*s"), msgnum(state),
1241                                linelen(state->msg), state->msg);
1242
1243                        git_config_get_bool("advice.amworkdir", &advice_amworkdir);
1244
1245                        if (advice_amworkdir)
1246                                printf_ln(_("The copy of the patch that failed is found in: %s"),
1247                                                am_path(state, "patch"));
1248
1249                        die_user_resolve(state);
1250                }
1251
1252                do_commit(state);
1253
1254next:
1255                am_next(state);
1256        }
1257
1258        /*
1259         * In rebasing mode, it's up to the caller to take care of
1260         * housekeeping.
1261         */
1262        if (!state->rebasing) {
1263                am_destroy(state);
1264                run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
1265        }
1266}
1267
1268/**
1269 * Resume the current am session after patch application failure. The user did
1270 * all the hard work, and we do not have to do any patch application. Just
1271 * trust and commit what the user has in the index and working tree.
1272 */
1273static void am_resolve(struct am_state *state)
1274{
1275        validate_resume_state(state);
1276
1277        say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1278
1279        if (!index_has_changes(NULL)) {
1280                printf_ln(_("No changes - did you forget to use 'git add'?\n"
1281                        "If there is nothing left to stage, chances are that something else\n"
1282                        "already introduced the same changes; you might want to skip this patch."));
1283                die_user_resolve(state);
1284        }
1285
1286        if (unmerged_cache()) {
1287                printf_ln(_("You still have unmerged paths in your index.\n"
1288                        "Did you forget to use 'git add'?"));
1289                die_user_resolve(state);
1290        }
1291
1292        do_commit(state);
1293
1294        am_next(state);
1295        am_run(state, 0);
1296}
1297
1298/**
1299 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
1300 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
1301 * failure.
1302 */
1303static int fast_forward_to(struct tree *head, struct tree *remote, int reset)
1304{
1305        struct lock_file *lock_file;
1306        struct unpack_trees_options opts;
1307        struct tree_desc t[2];
1308
1309        if (parse_tree(head) || parse_tree(remote))
1310                return -1;
1311
1312        lock_file = xcalloc(1, sizeof(struct lock_file));
1313        hold_locked_index(lock_file, 1);
1314
1315        refresh_cache(REFRESH_QUIET);
1316
1317        memset(&opts, 0, sizeof(opts));
1318        opts.head_idx = 1;
1319        opts.src_index = &the_index;
1320        opts.dst_index = &the_index;
1321        opts.update = 1;
1322        opts.merge = 1;
1323        opts.reset = reset;
1324        opts.fn = twoway_merge;
1325        init_tree_desc(&t[0], head->buffer, head->size);
1326        init_tree_desc(&t[1], remote->buffer, remote->size);
1327
1328        if (unpack_trees(2, t, &opts)) {
1329                rollback_lock_file(lock_file);
1330                return -1;
1331        }
1332
1333        if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
1334                die(_("unable to write new index file"));
1335
1336        return 0;
1337}
1338
1339/**
1340 * Clean the index without touching entries that are not modified between
1341 * `head` and `remote`.
1342 */
1343static int clean_index(const unsigned char *head, const unsigned char *remote)
1344{
1345        struct lock_file *lock_file;
1346        struct tree *head_tree, *remote_tree, *index_tree;
1347        unsigned char index[GIT_SHA1_RAWSZ];
1348        struct pathspec pathspec;
1349
1350        head_tree = parse_tree_indirect(head);
1351        if (!head_tree)
1352                return error(_("Could not parse object '%s'."), sha1_to_hex(head));
1353
1354        remote_tree = parse_tree_indirect(remote);
1355        if (!remote_tree)
1356                return error(_("Could not parse object '%s'."), sha1_to_hex(remote));
1357
1358        read_cache_unmerged();
1359
1360        if (fast_forward_to(head_tree, head_tree, 1))
1361                return -1;
1362
1363        if (write_cache_as_tree(index, 0, NULL))
1364                return -1;
1365
1366        index_tree = parse_tree_indirect(index);
1367        if (!index_tree)
1368                return error(_("Could not parse object '%s'."), sha1_to_hex(index));
1369
1370        if (fast_forward_to(index_tree, remote_tree, 0))
1371                return -1;
1372
1373        memset(&pathspec, 0, sizeof(pathspec));
1374
1375        lock_file = xcalloc(1, sizeof(struct lock_file));
1376        hold_locked_index(lock_file, 1);
1377
1378        if (read_tree(remote_tree, 0, &pathspec)) {
1379                rollback_lock_file(lock_file);
1380                return -1;
1381        }
1382
1383        if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
1384                die(_("unable to write new index file"));
1385
1386        remove_branch_state();
1387
1388        return 0;
1389}
1390
1391/**
1392 * Resume the current am session by skipping the current patch.
1393 */
1394static void am_skip(struct am_state *state)
1395{
1396        unsigned char head[GIT_SHA1_RAWSZ];
1397
1398        if (get_sha1("HEAD", head))
1399                hashcpy(head, EMPTY_TREE_SHA1_BIN);
1400
1401        if (clean_index(head, head))
1402                die(_("failed to clean index"));
1403
1404        am_next(state);
1405        am_run(state, 0);
1406}
1407
1408/**
1409 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
1410 *
1411 * It is not safe to reset HEAD when:
1412 * 1. git-am previously failed because the index was dirty.
1413 * 2. HEAD has moved since git-am previously failed.
1414 */
1415static int safe_to_abort(const struct am_state *state)
1416{
1417        struct strbuf sb = STRBUF_INIT;
1418        unsigned char abort_safety[GIT_SHA1_RAWSZ], head[GIT_SHA1_RAWSZ];
1419
1420        if (file_exists(am_path(state, "dirtyindex")))
1421                return 0;
1422
1423        if (read_state_file(&sb, state, "abort-safety", 1) > 0) {
1424                if (get_sha1_hex(sb.buf, abort_safety))
1425                        die(_("could not parse %s"), am_path(state, "abort_safety"));
1426        } else
1427                hashclr(abort_safety);
1428
1429        if (get_sha1("HEAD", head))
1430                hashclr(head);
1431
1432        if (!hashcmp(head, abort_safety))
1433                return 1;
1434
1435        error(_("You seem to have moved HEAD since the last 'am' failure.\n"
1436                "Not rewinding to ORIG_HEAD"));
1437
1438        return 0;
1439}
1440
1441/**
1442 * Aborts the current am session if it is safe to do so.
1443 */
1444static void am_abort(struct am_state *state)
1445{
1446        unsigned char curr_head[GIT_SHA1_RAWSZ], orig_head[GIT_SHA1_RAWSZ];
1447        int has_curr_head, has_orig_head;
1448        char *curr_branch;
1449
1450        if (!safe_to_abort(state)) {
1451                am_destroy(state);
1452                return;
1453        }
1454
1455        curr_branch = resolve_refdup("HEAD", 0, curr_head, NULL);
1456        has_curr_head = !is_null_sha1(curr_head);
1457        if (!has_curr_head)
1458                hashcpy(curr_head, EMPTY_TREE_SHA1_BIN);
1459
1460        has_orig_head = !get_sha1("ORIG_HEAD", orig_head);
1461        if (!has_orig_head)
1462                hashcpy(orig_head, EMPTY_TREE_SHA1_BIN);
1463
1464        clean_index(curr_head, orig_head);
1465
1466        if (has_orig_head)
1467                update_ref("am --abort", "HEAD", orig_head,
1468                                has_curr_head ? curr_head : NULL, 0,
1469                                UPDATE_REFS_DIE_ON_ERR);
1470        else if (curr_branch)
1471                delete_ref(curr_branch, NULL, REF_NODEREF);
1472
1473        free(curr_branch);
1474        am_destroy(state);
1475}
1476
1477/**
1478 * parse_options() callback that validates and sets opt->value to the
1479 * PATCH_FORMAT_* enum value corresponding to `arg`.
1480 */
1481static int parse_opt_patchformat(const struct option *opt, const char *arg, int unset)
1482{
1483        int *opt_value = opt->value;
1484
1485        if (!strcmp(arg, "mbox"))
1486                *opt_value = PATCH_FORMAT_MBOX;
1487        else
1488                return error(_("Invalid value for --patch-format: %s"), arg);
1489        return 0;
1490}
1491
1492enum resume_mode {
1493        RESUME_FALSE = 0,
1494        RESUME_APPLY,
1495        RESUME_RESOLVED,
1496        RESUME_SKIP,
1497        RESUME_ABORT
1498};
1499
1500int cmd_am(int argc, const char **argv, const char *prefix)
1501{
1502        struct am_state state;
1503        int patch_format = PATCH_FORMAT_UNKNOWN;
1504        enum resume_mode resume = RESUME_FALSE;
1505
1506        const char * const usage[] = {
1507                N_("git am [options] [(<mbox>|<Maildir>)...]"),
1508                N_("git am [options] (--continue | --skip | --abort)"),
1509                NULL
1510        };
1511
1512        struct option options[] = {
1513                OPT_BOOL('3', "3way", &state.threeway,
1514                        N_("allow fall back on 3way merging if needed")),
1515                OPT__QUIET(&state.quiet, N_("be quiet")),
1516                OPT_BOOL('s', "signoff", &state.signoff,
1517                        N_("add a Signed-off-by line to the commit message")),
1518                OPT_BOOL('u', "utf8", &state.utf8,
1519                        N_("recode into utf8 (default)")),
1520                OPT_SET_INT('k', "keep", &state.keep,
1521                        N_("pass -k flag to git-mailinfo"), KEEP_TRUE),
1522                OPT_SET_INT(0, "keep-non-patch", &state.keep,
1523                        N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH),
1524                OPT_CALLBACK(0, "patch-format", &patch_format, N_("format"),
1525                        N_("format the patch(es) are in"),
1526                        parse_opt_patchformat),
1527                OPT_STRING(0, "resolvemsg", &state.resolvemsg, NULL,
1528                        N_("override error message when patch failure occurs")),
1529                OPT_CMDMODE(0, "continue", &resume,
1530                        N_("continue applying patches after resolving a conflict"),
1531                        RESUME_RESOLVED),
1532                OPT_CMDMODE('r', "resolved", &resume,
1533                        N_("synonyms for --continue"),
1534                        RESUME_RESOLVED),
1535                OPT_CMDMODE(0, "skip", &resume,
1536                        N_("skip the current patch"),
1537                        RESUME_SKIP),
1538                OPT_CMDMODE(0, "abort", &resume,
1539                        N_("restore the original branch and abort the patching operation."),
1540                        RESUME_ABORT),
1541                OPT_HIDDEN_BOOL(0, "rebasing", &state.rebasing,
1542                        N_("(internal use for git-rebase)")),
1543                OPT_END()
1544        };
1545
1546        /*
1547         * NEEDSWORK: Once all the features of git-am.sh have been
1548         * re-implemented in builtin/am.c, this preamble can be removed.
1549         */
1550        if (!getenv("_GIT_USE_BUILTIN_AM")) {
1551                const char *path = mkpath("%s/git-am", git_exec_path());
1552
1553                if (sane_execvp(path, (char **)argv) < 0)
1554                        die_errno("could not exec %s", path);
1555        } else {
1556                prefix = setup_git_directory();
1557                trace_repo_setup(prefix);
1558                setup_work_tree();
1559        }
1560
1561        git_config(git_default_config, NULL);
1562
1563        am_state_init(&state, git_path("rebase-apply"));
1564
1565        argc = parse_options(argc, argv, prefix, options, usage, 0);
1566
1567        if (read_index_preload(&the_index, NULL) < 0)
1568                die(_("failed to read the index"));
1569
1570        if (am_in_progress(&state)) {
1571                /*
1572                 * Catch user error to feed us patches when there is a session
1573                 * in progress:
1574                 *
1575                 * 1. mbox path(s) are provided on the command-line.
1576                 * 2. stdin is not a tty: the user is trying to feed us a patch
1577                 *    from standard input. This is somewhat unreliable -- stdin
1578                 *    could be /dev/null for example and the caller did not
1579                 *    intend to feed us a patch but wanted to continue
1580                 *    unattended.
1581                 */
1582                if (argc || (resume == RESUME_FALSE && !isatty(0)))
1583                        die(_("previous rebase directory %s still exists but mbox given."),
1584                                state.dir);
1585
1586                if (resume == RESUME_FALSE)
1587                        resume = RESUME_APPLY;
1588
1589                am_load(&state);
1590        } else {
1591                struct argv_array paths = ARGV_ARRAY_INIT;
1592                int i;
1593
1594                /*
1595                 * Handle stray state directory in the independent-run case. In
1596                 * the --rebasing case, it is up to the caller to take care of
1597                 * stray directories.
1598                 */
1599                if (file_exists(state.dir) && !state.rebasing) {
1600                        if (resume == RESUME_ABORT) {
1601                                am_destroy(&state);
1602                                am_state_release(&state);
1603                                return 0;
1604                        }
1605
1606                        die(_("Stray %s directory found.\n"
1607                                "Use \"git am --abort\" to remove it."),
1608                                state.dir);
1609                }
1610
1611                if (resume)
1612                        die(_("Resolve operation not in progress, we are not resuming."));
1613
1614                for (i = 0; i < argc; i++) {
1615                        if (is_absolute_path(argv[i]) || !prefix)
1616                                argv_array_push(&paths, argv[i]);
1617                        else
1618                                argv_array_push(&paths, mkpath("%s/%s", prefix, argv[i]));
1619                }
1620
1621                am_setup(&state, patch_format, paths.argv);
1622
1623                argv_array_clear(&paths);
1624        }
1625
1626        switch (resume) {
1627        case RESUME_FALSE:
1628                am_run(&state, 0);
1629                break;
1630        case RESUME_APPLY:
1631                am_run(&state, 1);
1632                break;
1633        case RESUME_RESOLVED:
1634                am_resolve(&state);
1635                break;
1636        case RESUME_SKIP:
1637                am_skip(&state);
1638                break;
1639        case RESUME_ABORT:
1640                am_abort(&state);
1641                break;
1642        default:
1643                die("BUG: invalid resume value");
1644        }
1645
1646        am_state_release(&state);
1647
1648        return 0;
1649}