builtin / am.con commit Merge branch 'js/color-on-windows-comment' (627c9f2)
   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 "tempfile.h"
  14#include "lockfile.h"
  15#include "cache-tree.h"
  16#include "refs.h"
  17#include "commit.h"
  18#include "diff.h"
  19#include "diffcore.h"
  20#include "unpack-trees.h"
  21#include "branch.h"
  22#include "sequencer.h"
  23#include "revision.h"
  24#include "merge-recursive.h"
  25#include "revision.h"
  26#include "log-tree.h"
  27#include "notes-utils.h"
  28#include "rerere.h"
  29#include "prompt.h"
  30#include "mailinfo.h"
  31
  32/**
  33 * Returns 1 if the file is empty or does not exist, 0 otherwise.
  34 */
  35static int is_empty_file(const char *filename)
  36{
  37        struct stat st;
  38
  39        if (stat(filename, &st) < 0) {
  40                if (errno == ENOENT)
  41                        return 1;
  42                die_errno(_("could not stat %s"), filename);
  43        }
  44
  45        return !st.st_size;
  46}
  47
  48/**
  49 * Returns the length of the first line of msg.
  50 */
  51static int linelen(const char *msg)
  52{
  53        return strchrnul(msg, '\n') - msg;
  54}
  55
  56/**
  57 * Returns true if `str` consists of only whitespace, false otherwise.
  58 */
  59static int str_isspace(const char *str)
  60{
  61        for (; *str; str++)
  62                if (!isspace(*str))
  63                        return 0;
  64
  65        return 1;
  66}
  67
  68enum patch_format {
  69        PATCH_FORMAT_UNKNOWN = 0,
  70        PATCH_FORMAT_MBOX,
  71        PATCH_FORMAT_STGIT,
  72        PATCH_FORMAT_STGIT_SERIES,
  73        PATCH_FORMAT_HG,
  74        PATCH_FORMAT_MBOXRD
  75};
  76
  77enum keep_type {
  78        KEEP_FALSE = 0,
  79        KEEP_TRUE,      /* pass -k flag to git-mailinfo */
  80        KEEP_NON_PATCH  /* pass -b flag to git-mailinfo */
  81};
  82
  83enum scissors_type {
  84        SCISSORS_UNSET = -1,
  85        SCISSORS_FALSE = 0,  /* pass --no-scissors to git-mailinfo */
  86        SCISSORS_TRUE        /* pass --scissors to git-mailinfo */
  87};
  88
  89enum signoff_type {
  90        SIGNOFF_FALSE = 0,
  91        SIGNOFF_TRUE = 1,
  92        SIGNOFF_EXPLICIT /* --signoff was set on the command-line */
  93};
  94
  95struct am_state {
  96        /* state directory path */
  97        char *dir;
  98
  99        /* current and last patch numbers, 1-indexed */
 100        int cur;
 101        int last;
 102
 103        /* commit metadata and message */
 104        char *author_name;
 105        char *author_email;
 106        char *author_date;
 107        char *msg;
 108        size_t msg_len;
 109
 110        /* when --rebasing, records the original commit the patch came from */
 111        unsigned char orig_commit[GIT_SHA1_RAWSZ];
 112
 113        /* number of digits in patch filename */
 114        int prec;
 115
 116        /* various operating modes and command line options */
 117        int interactive;
 118        int threeway;
 119        int quiet;
 120        int signoff; /* enum signoff_type */
 121        int utf8;
 122        int keep; /* enum keep_type */
 123        int message_id;
 124        int scissors; /* enum scissors_type */
 125        struct argv_array git_apply_opts;
 126        const char *resolvemsg;
 127        int committer_date_is_author_date;
 128        int ignore_date;
 129        int allow_rerere_autoupdate;
 130        const char *sign_commit;
 131        int rebasing;
 132};
 133
 134/**
 135 * Initializes am_state with the default values. The state directory is set to
 136 * dir.
 137 */
 138static void am_state_init(struct am_state *state, const char *dir)
 139{
 140        int gpgsign;
 141
 142        memset(state, 0, sizeof(*state));
 143
 144        assert(dir);
 145        state->dir = xstrdup(dir);
 146
 147        state->prec = 4;
 148
 149        git_config_get_bool("am.threeway", &state->threeway);
 150
 151        state->utf8 = 1;
 152
 153        git_config_get_bool("am.messageid", &state->message_id);
 154
 155        state->scissors = SCISSORS_UNSET;
 156
 157        argv_array_init(&state->git_apply_opts);
 158
 159        if (!git_config_get_bool("commit.gpgsign", &gpgsign))
 160                state->sign_commit = gpgsign ? "" : NULL;
 161}
 162
 163/**
 164 * Releases memory allocated by an am_state.
 165 */
 166static void am_state_release(struct am_state *state)
 167{
 168        free(state->dir);
 169        free(state->author_name);
 170        free(state->author_email);
 171        free(state->author_date);
 172        free(state->msg);
 173        argv_array_clear(&state->git_apply_opts);
 174}
 175
 176/**
 177 * Returns path relative to the am_state directory.
 178 */
 179static inline const char *am_path(const struct am_state *state, const char *path)
 180{
 181        return mkpath("%s/%s", state->dir, path);
 182}
 183
 184/**
 185 * For convenience to call write_file()
 186 */
 187static int write_state_text(const struct am_state *state,
 188                            const char *name, const char *string)
 189{
 190        return write_file(am_path(state, name), "%s", string);
 191}
 192
 193static int write_state_count(const struct am_state *state,
 194                             const char *name, int value)
 195{
 196        return write_file(am_path(state, name), "%d", value);
 197}
 198
 199static int write_state_bool(const struct am_state *state,
 200                            const char *name, int value)
 201{
 202        return write_state_text(state, name, value ? "t" : "f");
 203}
 204
 205/**
 206 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
 207 * at the end.
 208 */
 209static void say(const struct am_state *state, FILE *fp, const char *fmt, ...)
 210{
 211        va_list ap;
 212
 213        va_start(ap, fmt);
 214        if (!state->quiet) {
 215                vfprintf(fp, fmt, ap);
 216                putc('\n', fp);
 217        }
 218        va_end(ap);
 219}
 220
 221/**
 222 * Returns 1 if there is an am session in progress, 0 otherwise.
 223 */
 224static int am_in_progress(const struct am_state *state)
 225{
 226        struct stat st;
 227
 228        if (lstat(state->dir, &st) < 0 || !S_ISDIR(st.st_mode))
 229                return 0;
 230        if (lstat(am_path(state, "last"), &st) || !S_ISREG(st.st_mode))
 231                return 0;
 232        if (lstat(am_path(state, "next"), &st) || !S_ISREG(st.st_mode))
 233                return 0;
 234        return 1;
 235}
 236
 237/**
 238 * Reads the contents of `file` in the `state` directory into `sb`. Returns the
 239 * number of bytes read on success, -1 if the file does not exist. If `trim` is
 240 * set, trailing whitespace will be removed.
 241 */
 242static int read_state_file(struct strbuf *sb, const struct am_state *state,
 243                        const char *file, int trim)
 244{
 245        strbuf_reset(sb);
 246
 247        if (strbuf_read_file(sb, am_path(state, file), 0) >= 0) {
 248                if (trim)
 249                        strbuf_trim(sb);
 250
 251                return sb->len;
 252        }
 253
 254        if (errno == ENOENT)
 255                return -1;
 256
 257        die_errno(_("could not read '%s'"), am_path(state, file));
 258}
 259
 260/**
 261 * Reads a KEY=VALUE shell variable assignment from `fp`, returning the VALUE
 262 * as a newly-allocated string. VALUE must be a quoted string, and the KEY must
 263 * match `key`. Returns NULL on failure.
 264 *
 265 * This is used by read_author_script() to read the GIT_AUTHOR_* variables from
 266 * the author-script.
 267 */
 268static char *read_shell_var(FILE *fp, const char *key)
 269{
 270        struct strbuf sb = STRBUF_INIT;
 271        const char *str;
 272
 273        if (strbuf_getline_lf(&sb, fp))
 274                goto fail;
 275
 276        if (!skip_prefix(sb.buf, key, &str))
 277                goto fail;
 278
 279        if (!skip_prefix(str, "=", &str))
 280                goto fail;
 281
 282        strbuf_remove(&sb, 0, str - sb.buf);
 283
 284        str = sq_dequote(sb.buf);
 285        if (!str)
 286                goto fail;
 287
 288        return strbuf_detach(&sb, NULL);
 289
 290fail:
 291        strbuf_release(&sb);
 292        return NULL;
 293}
 294
 295/**
 296 * Reads and parses the state directory's "author-script" file, and sets
 297 * state->author_name, state->author_email and state->author_date accordingly.
 298 * Returns 0 on success, -1 if the file could not be parsed.
 299 *
 300 * The author script is of the format:
 301 *
 302 *      GIT_AUTHOR_NAME='$author_name'
 303 *      GIT_AUTHOR_EMAIL='$author_email'
 304 *      GIT_AUTHOR_DATE='$author_date'
 305 *
 306 * where $author_name, $author_email and $author_date are quoted. We are strict
 307 * with our parsing, as the file was meant to be eval'd in the old git-am.sh
 308 * script, and thus if the file differs from what this function expects, it is
 309 * better to bail out than to do something that the user does not expect.
 310 */
 311static int read_author_script(struct am_state *state)
 312{
 313        const char *filename = am_path(state, "author-script");
 314        FILE *fp;
 315
 316        assert(!state->author_name);
 317        assert(!state->author_email);
 318        assert(!state->author_date);
 319
 320        fp = fopen(filename, "r");
 321        if (!fp) {
 322                if (errno == ENOENT)
 323                        return 0;
 324                die_errno(_("could not open '%s' for reading"), filename);
 325        }
 326
 327        state->author_name = read_shell_var(fp, "GIT_AUTHOR_NAME");
 328        if (!state->author_name) {
 329                fclose(fp);
 330                return -1;
 331        }
 332
 333        state->author_email = read_shell_var(fp, "GIT_AUTHOR_EMAIL");
 334        if (!state->author_email) {
 335                fclose(fp);
 336                return -1;
 337        }
 338
 339        state->author_date = read_shell_var(fp, "GIT_AUTHOR_DATE");
 340        if (!state->author_date) {
 341                fclose(fp);
 342                return -1;
 343        }
 344
 345        if (fgetc(fp) != EOF) {
 346                fclose(fp);
 347                return -1;
 348        }
 349
 350        fclose(fp);
 351        return 0;
 352}
 353
 354/**
 355 * Saves state->author_name, state->author_email and state->author_date in the
 356 * state directory's "author-script" file.
 357 */
 358static void write_author_script(const struct am_state *state)
 359{
 360        struct strbuf sb = STRBUF_INIT;
 361
 362        strbuf_addstr(&sb, "GIT_AUTHOR_NAME=");
 363        sq_quote_buf(&sb, state->author_name);
 364        strbuf_addch(&sb, '\n');
 365
 366        strbuf_addstr(&sb, "GIT_AUTHOR_EMAIL=");
 367        sq_quote_buf(&sb, state->author_email);
 368        strbuf_addch(&sb, '\n');
 369
 370        strbuf_addstr(&sb, "GIT_AUTHOR_DATE=");
 371        sq_quote_buf(&sb, state->author_date);
 372        strbuf_addch(&sb, '\n');
 373
 374        write_state_text(state, "author-script", sb.buf);
 375
 376        strbuf_release(&sb);
 377}
 378
 379/**
 380 * Reads the commit message from the state directory's "final-commit" file,
 381 * setting state->msg to its contents and state->msg_len to the length of its
 382 * contents in bytes.
 383 *
 384 * Returns 0 on success, -1 if the file does not exist.
 385 */
 386static int read_commit_msg(struct am_state *state)
 387{
 388        struct strbuf sb = STRBUF_INIT;
 389
 390        assert(!state->msg);
 391
 392        if (read_state_file(&sb, state, "final-commit", 0) < 0) {
 393                strbuf_release(&sb);
 394                return -1;
 395        }
 396
 397        state->msg = strbuf_detach(&sb, &state->msg_len);
 398        return 0;
 399}
 400
 401/**
 402 * Saves state->msg in the state directory's "final-commit" file.
 403 */
 404static void write_commit_msg(const struct am_state *state)
 405{
 406        int fd;
 407        const char *filename = am_path(state, "final-commit");
 408
 409        fd = xopen(filename, O_WRONLY | O_CREAT, 0666);
 410        if (write_in_full(fd, state->msg, state->msg_len) < 0)
 411                die_errno(_("could not write to %s"), filename);
 412        close(fd);
 413}
 414
 415/**
 416 * Loads state from disk.
 417 */
 418static void am_load(struct am_state *state)
 419{
 420        struct strbuf sb = STRBUF_INIT;
 421
 422        if (read_state_file(&sb, state, "next", 1) < 0)
 423                die("BUG: state file 'next' does not exist");
 424        state->cur = strtol(sb.buf, NULL, 10);
 425
 426        if (read_state_file(&sb, state, "last", 1) < 0)
 427                die("BUG: state file 'last' does not exist");
 428        state->last = strtol(sb.buf, NULL, 10);
 429
 430        if (read_author_script(state) < 0)
 431                die(_("could not parse author script"));
 432
 433        read_commit_msg(state);
 434
 435        if (read_state_file(&sb, state, "original-commit", 1) < 0)
 436                hashclr(state->orig_commit);
 437        else if (get_sha1_hex(sb.buf, state->orig_commit) < 0)
 438                die(_("could not parse %s"), am_path(state, "original-commit"));
 439
 440        read_state_file(&sb, state, "threeway", 1);
 441        state->threeway = !strcmp(sb.buf, "t");
 442
 443        read_state_file(&sb, state, "quiet", 1);
 444        state->quiet = !strcmp(sb.buf, "t");
 445
 446        read_state_file(&sb, state, "sign", 1);
 447        state->signoff = !strcmp(sb.buf, "t");
 448
 449        read_state_file(&sb, state, "utf8", 1);
 450        state->utf8 = !strcmp(sb.buf, "t");
 451
 452        read_state_file(&sb, state, "keep", 1);
 453        if (!strcmp(sb.buf, "t"))
 454                state->keep = KEEP_TRUE;
 455        else if (!strcmp(sb.buf, "b"))
 456                state->keep = KEEP_NON_PATCH;
 457        else
 458                state->keep = KEEP_FALSE;
 459
 460        read_state_file(&sb, state, "messageid", 1);
 461        state->message_id = !strcmp(sb.buf, "t");
 462
 463        read_state_file(&sb, state, "scissors", 1);
 464        if (!strcmp(sb.buf, "t"))
 465                state->scissors = SCISSORS_TRUE;
 466        else if (!strcmp(sb.buf, "f"))
 467                state->scissors = SCISSORS_FALSE;
 468        else
 469                state->scissors = SCISSORS_UNSET;
 470
 471        read_state_file(&sb, state, "apply-opt", 1);
 472        argv_array_clear(&state->git_apply_opts);
 473        if (sq_dequote_to_argv_array(sb.buf, &state->git_apply_opts) < 0)
 474                die(_("could not parse %s"), am_path(state, "apply-opt"));
 475
 476        state->rebasing = !!file_exists(am_path(state, "rebasing"));
 477
 478        strbuf_release(&sb);
 479}
 480
 481/**
 482 * Removes the am_state directory, forcefully terminating the current am
 483 * session.
 484 */
 485static void am_destroy(const struct am_state *state)
 486{
 487        struct strbuf sb = STRBUF_INIT;
 488
 489        strbuf_addstr(&sb, state->dir);
 490        remove_dir_recursively(&sb, 0);
 491        strbuf_release(&sb);
 492}
 493
 494/**
 495 * Runs applypatch-msg hook. Returns its exit code.
 496 */
 497static int run_applypatch_msg_hook(struct am_state *state)
 498{
 499        int ret;
 500
 501        assert(state->msg);
 502        ret = run_hook_le(NULL, "applypatch-msg", am_path(state, "final-commit"), NULL);
 503
 504        if (!ret) {
 505                free(state->msg);
 506                state->msg = NULL;
 507                if (read_commit_msg(state) < 0)
 508                        die(_("'%s' was deleted by the applypatch-msg hook"),
 509                                am_path(state, "final-commit"));
 510        }
 511
 512        return ret;
 513}
 514
 515/**
 516 * Runs post-rewrite hook. Returns it exit code.
 517 */
 518static int run_post_rewrite_hook(const struct am_state *state)
 519{
 520        struct child_process cp = CHILD_PROCESS_INIT;
 521        const char *hook = find_hook("post-rewrite");
 522        int ret;
 523
 524        if (!hook)
 525                return 0;
 526
 527        argv_array_push(&cp.args, hook);
 528        argv_array_push(&cp.args, "rebase");
 529
 530        cp.in = xopen(am_path(state, "rewritten"), O_RDONLY);
 531        cp.stdout_to_stderr = 1;
 532
 533        ret = run_command(&cp);
 534
 535        close(cp.in);
 536        return ret;
 537}
 538
 539/**
 540 * Reads the state directory's "rewritten" file, and copies notes from the old
 541 * commits listed in the file to their rewritten commits.
 542 *
 543 * Returns 0 on success, -1 on failure.
 544 */
 545static int copy_notes_for_rebase(const struct am_state *state)
 546{
 547        struct notes_rewrite_cfg *c;
 548        struct strbuf sb = STRBUF_INIT;
 549        const char *invalid_line = _("Malformed input line: '%s'.");
 550        const char *msg = "Notes added by 'git rebase'";
 551        FILE *fp;
 552        int ret = 0;
 553
 554        assert(state->rebasing);
 555
 556        c = init_copy_notes_for_rewrite("rebase");
 557        if (!c)
 558                return 0;
 559
 560        fp = xfopen(am_path(state, "rewritten"), "r");
 561
 562        while (!strbuf_getline_lf(&sb, fp)) {
 563                unsigned char from_obj[GIT_SHA1_RAWSZ], to_obj[GIT_SHA1_RAWSZ];
 564
 565                if (sb.len != GIT_SHA1_HEXSZ * 2 + 1) {
 566                        ret = error(invalid_line, sb.buf);
 567                        goto finish;
 568                }
 569
 570                if (get_sha1_hex(sb.buf, from_obj)) {
 571                        ret = error(invalid_line, sb.buf);
 572                        goto finish;
 573                }
 574
 575                if (sb.buf[GIT_SHA1_HEXSZ] != ' ') {
 576                        ret = error(invalid_line, sb.buf);
 577                        goto finish;
 578                }
 579
 580                if (get_sha1_hex(sb.buf + GIT_SHA1_HEXSZ + 1, to_obj)) {
 581                        ret = error(invalid_line, sb.buf);
 582                        goto finish;
 583                }
 584
 585                if (copy_note_for_rewrite(c, from_obj, to_obj))
 586                        ret = error(_("Failed to copy notes from '%s' to '%s'"),
 587                                        sha1_to_hex(from_obj), sha1_to_hex(to_obj));
 588        }
 589
 590finish:
 591        finish_copy_notes_for_rewrite(c, msg);
 592        fclose(fp);
 593        strbuf_release(&sb);
 594        return ret;
 595}
 596
 597/**
 598 * Determines if the file looks like a piece of RFC2822 mail by grabbing all
 599 * non-indented lines and checking if they look like they begin with valid
 600 * header field names.
 601 *
 602 * Returns 1 if the file looks like a piece of mail, 0 otherwise.
 603 */
 604static int is_mail(FILE *fp)
 605{
 606        const char *header_regex = "^[!-9;-~]+:";
 607        struct strbuf sb = STRBUF_INIT;
 608        regex_t regex;
 609        int ret = 1;
 610
 611        if (fseek(fp, 0L, SEEK_SET))
 612                die_errno(_("fseek failed"));
 613
 614        if (regcomp(&regex, header_regex, REG_NOSUB | REG_EXTENDED))
 615                die("invalid pattern: %s", header_regex);
 616
 617        while (!strbuf_getline(&sb, fp)) {
 618                if (!sb.len)
 619                        break; /* End of header */
 620
 621                /* Ignore indented folded lines */
 622                if (*sb.buf == '\t' || *sb.buf == ' ')
 623                        continue;
 624
 625                /* It's a header if it matches header_regex */
 626                if (regexec(&regex, sb.buf, 0, NULL, 0)) {
 627                        ret = 0;
 628                        goto done;
 629                }
 630        }
 631
 632done:
 633        regfree(&regex);
 634        strbuf_release(&sb);
 635        return ret;
 636}
 637
 638/**
 639 * Attempts to detect the patch_format of the patches contained in `paths`,
 640 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
 641 * detection fails.
 642 */
 643static int detect_patch_format(const char **paths)
 644{
 645        enum patch_format ret = PATCH_FORMAT_UNKNOWN;
 646        struct strbuf l1 = STRBUF_INIT;
 647        struct strbuf l2 = STRBUF_INIT;
 648        struct strbuf l3 = STRBUF_INIT;
 649        FILE *fp;
 650
 651        /*
 652         * We default to mbox format if input is from stdin and for directories
 653         */
 654        if (!*paths || !strcmp(*paths, "-") || is_directory(*paths))
 655                return PATCH_FORMAT_MBOX;
 656
 657        /*
 658         * Otherwise, check the first few lines of the first patch, starting
 659         * from the first non-blank line, to try to detect its format.
 660         */
 661
 662        fp = xfopen(*paths, "r");
 663
 664        while (!strbuf_getline(&l1, fp)) {
 665                if (l1.len)
 666                        break;
 667        }
 668
 669        if (starts_with(l1.buf, "From ") || starts_with(l1.buf, "From: ")) {
 670                ret = PATCH_FORMAT_MBOX;
 671                goto done;
 672        }
 673
 674        if (starts_with(l1.buf, "# This series applies on GIT commit")) {
 675                ret = PATCH_FORMAT_STGIT_SERIES;
 676                goto done;
 677        }
 678
 679        if (!strcmp(l1.buf, "# HG changeset patch")) {
 680                ret = PATCH_FORMAT_HG;
 681                goto done;
 682        }
 683
 684        strbuf_reset(&l2);
 685        strbuf_getline(&l2, fp);
 686        strbuf_reset(&l3);
 687        strbuf_getline(&l3, fp);
 688
 689        /*
 690         * If the second line is empty and the third is a From, Author or Date
 691         * entry, this is likely an StGit patch.
 692         */
 693        if (l1.len && !l2.len &&
 694                (starts_with(l3.buf, "From:") ||
 695                 starts_with(l3.buf, "Author:") ||
 696                 starts_with(l3.buf, "Date:"))) {
 697                ret = PATCH_FORMAT_STGIT;
 698                goto done;
 699        }
 700
 701        if (l1.len && is_mail(fp)) {
 702                ret = PATCH_FORMAT_MBOX;
 703                goto done;
 704        }
 705
 706done:
 707        fclose(fp);
 708        strbuf_release(&l1);
 709        return ret;
 710}
 711
 712/**
 713 * Splits out individual email patches from `paths`, where each path is either
 714 * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
 715 */
 716static int split_mail_mbox(struct am_state *state, const char **paths,
 717                                int keep_cr, int mboxrd)
 718{
 719        struct child_process cp = CHILD_PROCESS_INIT;
 720        struct strbuf last = STRBUF_INIT;
 721
 722        cp.git_cmd = 1;
 723        argv_array_push(&cp.args, "mailsplit");
 724        argv_array_pushf(&cp.args, "-d%d", state->prec);
 725        argv_array_pushf(&cp.args, "-o%s", state->dir);
 726        argv_array_push(&cp.args, "-b");
 727        if (keep_cr)
 728                argv_array_push(&cp.args, "--keep-cr");
 729        if (mboxrd)
 730                argv_array_push(&cp.args, "--mboxrd");
 731        argv_array_push(&cp.args, "--");
 732        argv_array_pushv(&cp.args, paths);
 733
 734        if (capture_command(&cp, &last, 8))
 735                return -1;
 736
 737        state->cur = 1;
 738        state->last = strtol(last.buf, NULL, 10);
 739
 740        return 0;
 741}
 742
 743/**
 744 * Callback signature for split_mail_conv(). The foreign patch should be
 745 * read from `in`, and the converted patch (in RFC2822 mail format) should be
 746 * written to `out`. Return 0 on success, or -1 on failure.
 747 */
 748typedef int (*mail_conv_fn)(FILE *out, FILE *in, int keep_cr);
 749
 750/**
 751 * Calls `fn` for each file in `paths` to convert the foreign patch to the
 752 * RFC2822 mail format suitable for parsing with git-mailinfo.
 753 *
 754 * Returns 0 on success, -1 on failure.
 755 */
 756static int split_mail_conv(mail_conv_fn fn, struct am_state *state,
 757                        const char **paths, int keep_cr)
 758{
 759        static const char *stdin_only[] = {"-", NULL};
 760        int i;
 761
 762        if (!*paths)
 763                paths = stdin_only;
 764
 765        for (i = 0; *paths; paths++, i++) {
 766                FILE *in, *out;
 767                const char *mail;
 768                int ret;
 769
 770                if (!strcmp(*paths, "-"))
 771                        in = stdin;
 772                else
 773                        in = fopen(*paths, "r");
 774
 775                if (!in)
 776                        return error_errno(_("could not open '%s' for reading"),
 777                                           *paths);
 778
 779                mail = mkpath("%s/%0*d", state->dir, state->prec, i + 1);
 780
 781                out = fopen(mail, "w");
 782                if (!out)
 783                        return error_errno(_("could not open '%s' for writing"),
 784                                           mail);
 785
 786                ret = fn(out, in, keep_cr);
 787
 788                fclose(out);
 789                fclose(in);
 790
 791                if (ret)
 792                        return error(_("could not parse patch '%s'"), *paths);
 793        }
 794
 795        state->cur = 1;
 796        state->last = i;
 797        return 0;
 798}
 799
 800/**
 801 * A split_mail_conv() callback that converts an StGit patch to an RFC2822
 802 * message suitable for parsing with git-mailinfo.
 803 */
 804static int stgit_patch_to_mail(FILE *out, FILE *in, int keep_cr)
 805{
 806        struct strbuf sb = STRBUF_INIT;
 807        int subject_printed = 0;
 808
 809        while (!strbuf_getline_lf(&sb, in)) {
 810                const char *str;
 811
 812                if (str_isspace(sb.buf))
 813                        continue;
 814                else if (skip_prefix(sb.buf, "Author:", &str))
 815                        fprintf(out, "From:%s\n", str);
 816                else if (starts_with(sb.buf, "From") || starts_with(sb.buf, "Date"))
 817                        fprintf(out, "%s\n", sb.buf);
 818                else if (!subject_printed) {
 819                        fprintf(out, "Subject: %s\n", sb.buf);
 820                        subject_printed = 1;
 821                } else {
 822                        fprintf(out, "\n%s\n", sb.buf);
 823                        break;
 824                }
 825        }
 826
 827        strbuf_reset(&sb);
 828        while (strbuf_fread(&sb, 8192, in) > 0) {
 829                fwrite(sb.buf, 1, sb.len, out);
 830                strbuf_reset(&sb);
 831        }
 832
 833        strbuf_release(&sb);
 834        return 0;
 835}
 836
 837/**
 838 * This function only supports a single StGit series file in `paths`.
 839 *
 840 * Given an StGit series file, converts the StGit patches in the series into
 841 * RFC2822 messages suitable for parsing with git-mailinfo, and queues them in
 842 * the state directory.
 843 *
 844 * Returns 0 on success, -1 on failure.
 845 */
 846static int split_mail_stgit_series(struct am_state *state, const char **paths,
 847                                        int keep_cr)
 848{
 849        const char *series_dir;
 850        char *series_dir_buf;
 851        FILE *fp;
 852        struct argv_array patches = ARGV_ARRAY_INIT;
 853        struct strbuf sb = STRBUF_INIT;
 854        int ret;
 855
 856        if (!paths[0] || paths[1])
 857                return error(_("Only one StGIT patch series can be applied at once"));
 858
 859        series_dir_buf = xstrdup(*paths);
 860        series_dir = dirname(series_dir_buf);
 861
 862        fp = fopen(*paths, "r");
 863        if (!fp)
 864                return error_errno(_("could not open '%s' for reading"), *paths);
 865
 866        while (!strbuf_getline_lf(&sb, fp)) {
 867                if (*sb.buf == '#')
 868                        continue; /* skip comment lines */
 869
 870                argv_array_push(&patches, mkpath("%s/%s", series_dir, sb.buf));
 871        }
 872
 873        fclose(fp);
 874        strbuf_release(&sb);
 875        free(series_dir_buf);
 876
 877        ret = split_mail_conv(stgit_patch_to_mail, state, patches.argv, keep_cr);
 878
 879        argv_array_clear(&patches);
 880        return ret;
 881}
 882
 883/**
 884 * A split_patches_conv() callback that converts a mercurial patch to a RFC2822
 885 * message suitable for parsing with git-mailinfo.
 886 */
 887static int hg_patch_to_mail(FILE *out, FILE *in, int keep_cr)
 888{
 889        struct strbuf sb = STRBUF_INIT;
 890
 891        while (!strbuf_getline_lf(&sb, in)) {
 892                const char *str;
 893
 894                if (skip_prefix(sb.buf, "# User ", &str))
 895                        fprintf(out, "From: %s\n", str);
 896                else if (skip_prefix(sb.buf, "# Date ", &str)) {
 897                        unsigned long timestamp;
 898                        long tz, tz2;
 899                        char *end;
 900
 901                        errno = 0;
 902                        timestamp = strtoul(str, &end, 10);
 903                        if (errno)
 904                                return error(_("invalid timestamp"));
 905
 906                        if (!skip_prefix(end, " ", &str))
 907                                return error(_("invalid Date line"));
 908
 909                        errno = 0;
 910                        tz = strtol(str, &end, 10);
 911                        if (errno)
 912                                return error(_("invalid timezone offset"));
 913
 914                        if (*end)
 915                                return error(_("invalid Date line"));
 916
 917                        /*
 918                         * mercurial's timezone is in seconds west of UTC,
 919                         * however git's timezone is in hours + minutes east of
 920                         * UTC. Convert it.
 921                         */
 922                        tz2 = labs(tz) / 3600 * 100 + labs(tz) % 3600 / 60;
 923                        if (tz > 0)
 924                                tz2 = -tz2;
 925
 926                        fprintf(out, "Date: %s\n", show_date(timestamp, tz2, DATE_MODE(RFC2822)));
 927                } else if (starts_with(sb.buf, "# ")) {
 928                        continue;
 929                } else {
 930                        fprintf(out, "\n%s\n", sb.buf);
 931                        break;
 932                }
 933        }
 934
 935        strbuf_reset(&sb);
 936        while (strbuf_fread(&sb, 8192, in) > 0) {
 937                fwrite(sb.buf, 1, sb.len, out);
 938                strbuf_reset(&sb);
 939        }
 940
 941        strbuf_release(&sb);
 942        return 0;
 943}
 944
 945/**
 946 * Splits a list of files/directories into individual email patches. Each path
 947 * in `paths` must be a file/directory that is formatted according to
 948 * `patch_format`.
 949 *
 950 * Once split out, the individual email patches will be stored in the state
 951 * directory, with each patch's filename being its index, padded to state->prec
 952 * digits.
 953 *
 954 * state->cur will be set to the index of the first mail, and state->last will
 955 * be set to the index of the last mail.
 956 *
 957 * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1
 958 * to disable this behavior, -1 to use the default configured setting.
 959 *
 960 * Returns 0 on success, -1 on failure.
 961 */
 962static int split_mail(struct am_state *state, enum patch_format patch_format,
 963                        const char **paths, int keep_cr)
 964{
 965        if (keep_cr < 0) {
 966                keep_cr = 0;
 967                git_config_get_bool("am.keepcr", &keep_cr);
 968        }
 969
 970        switch (patch_format) {
 971        case PATCH_FORMAT_MBOX:
 972                return split_mail_mbox(state, paths, keep_cr, 0);
 973        case PATCH_FORMAT_STGIT:
 974                return split_mail_conv(stgit_patch_to_mail, state, paths, keep_cr);
 975        case PATCH_FORMAT_STGIT_SERIES:
 976                return split_mail_stgit_series(state, paths, keep_cr);
 977        case PATCH_FORMAT_HG:
 978                return split_mail_conv(hg_patch_to_mail, state, paths, keep_cr);
 979        case PATCH_FORMAT_MBOXRD:
 980                return split_mail_mbox(state, paths, keep_cr, 1);
 981        default:
 982                die("BUG: invalid patch_format");
 983        }
 984        return -1;
 985}
 986
 987/**
 988 * Setup a new am session for applying patches
 989 */
 990static void am_setup(struct am_state *state, enum patch_format patch_format,
 991                        const char **paths, int keep_cr)
 992{
 993        unsigned char curr_head[GIT_SHA1_RAWSZ];
 994        const char *str;
 995        struct strbuf sb = STRBUF_INIT;
 996
 997        if (!patch_format)
 998                patch_format = detect_patch_format(paths);
 999
1000        if (!patch_format) {
1001                fprintf_ln(stderr, _("Patch format detection failed."));
1002                exit(128);
1003        }
1004
1005        if (mkdir(state->dir, 0777) < 0 && errno != EEXIST)
1006                die_errno(_("failed to create directory '%s'"), state->dir);
1007
1008        if (split_mail(state, patch_format, paths, keep_cr) < 0) {
1009                am_destroy(state);
1010                die(_("Failed to split patches."));
1011        }
1012
1013        if (state->rebasing)
1014                state->threeway = 1;
1015
1016        write_state_bool(state, "threeway", state->threeway);
1017        write_state_bool(state, "quiet", state->quiet);
1018        write_state_bool(state, "sign", state->signoff);
1019        write_state_bool(state, "utf8", state->utf8);
1020
1021        switch (state->keep) {
1022        case KEEP_FALSE:
1023                str = "f";
1024                break;
1025        case KEEP_TRUE:
1026                str = "t";
1027                break;
1028        case KEEP_NON_PATCH:
1029                str = "b";
1030                break;
1031        default:
1032                die("BUG: invalid value for state->keep");
1033        }
1034
1035        write_state_text(state, "keep", str);
1036        write_state_bool(state, "messageid", state->message_id);
1037
1038        switch (state->scissors) {
1039        case SCISSORS_UNSET:
1040                str = "";
1041                break;
1042        case SCISSORS_FALSE:
1043                str = "f";
1044                break;
1045        case SCISSORS_TRUE:
1046                str = "t";
1047                break;
1048        default:
1049                die("BUG: invalid value for state->scissors");
1050        }
1051        write_state_text(state, "scissors", str);
1052
1053        sq_quote_argv(&sb, state->git_apply_opts.argv, 0);
1054        write_state_text(state, "apply-opt", sb.buf);
1055
1056        if (state->rebasing)
1057                write_state_text(state, "rebasing", "");
1058        else
1059                write_state_text(state, "applying", "");
1060
1061        if (!get_sha1("HEAD", curr_head)) {
1062                write_state_text(state, "abort-safety", sha1_to_hex(curr_head));
1063                if (!state->rebasing)
1064                        update_ref("am", "ORIG_HEAD", curr_head, NULL, 0,
1065                                        UPDATE_REFS_DIE_ON_ERR);
1066        } else {
1067                write_state_text(state, "abort-safety", "");
1068                if (!state->rebasing)
1069                        delete_ref("ORIG_HEAD", NULL, 0);
1070        }
1071
1072        /*
1073         * NOTE: Since the "next" and "last" files determine if an am_state
1074         * session is in progress, they should be written last.
1075         */
1076
1077        write_state_count(state, "next", state->cur);
1078        write_state_count(state, "last", state->last);
1079
1080        strbuf_release(&sb);
1081}
1082
1083/**
1084 * Increments the patch pointer, and cleans am_state for the application of the
1085 * next patch.
1086 */
1087static void am_next(struct am_state *state)
1088{
1089        unsigned char head[GIT_SHA1_RAWSZ];
1090
1091        free(state->author_name);
1092        state->author_name = NULL;
1093
1094        free(state->author_email);
1095        state->author_email = NULL;
1096
1097        free(state->author_date);
1098        state->author_date = NULL;
1099
1100        free(state->msg);
1101        state->msg = NULL;
1102        state->msg_len = 0;
1103
1104        unlink(am_path(state, "author-script"));
1105        unlink(am_path(state, "final-commit"));
1106
1107        hashclr(state->orig_commit);
1108        unlink(am_path(state, "original-commit"));
1109
1110        if (!get_sha1("HEAD", head))
1111                write_state_text(state, "abort-safety", sha1_to_hex(head));
1112        else
1113                write_state_text(state, "abort-safety", "");
1114
1115        state->cur++;
1116        write_state_count(state, "next", state->cur);
1117}
1118
1119/**
1120 * Returns the filename of the current patch email.
1121 */
1122static const char *msgnum(const struct am_state *state)
1123{
1124        static struct strbuf sb = STRBUF_INIT;
1125
1126        strbuf_reset(&sb);
1127        strbuf_addf(&sb, "%0*d", state->prec, state->cur);
1128
1129        return sb.buf;
1130}
1131
1132/**
1133 * Refresh and write index.
1134 */
1135static void refresh_and_write_cache(void)
1136{
1137        struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
1138
1139        hold_locked_index(lock_file, 1);
1140        refresh_cache(REFRESH_QUIET);
1141        if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
1142                die(_("unable to write index file"));
1143}
1144
1145/**
1146 * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn
1147 * branch, returns 1 if there are entries in the index, 0 otherwise. If an
1148 * strbuf is provided, the space-separated list of files that differ will be
1149 * appended to it.
1150 */
1151static int index_has_changes(struct strbuf *sb)
1152{
1153        unsigned char head[GIT_SHA1_RAWSZ];
1154        int i;
1155
1156        if (!get_sha1_tree("HEAD", head)) {
1157                struct diff_options opt;
1158
1159                diff_setup(&opt);
1160                DIFF_OPT_SET(&opt, EXIT_WITH_STATUS);
1161                if (!sb)
1162                        DIFF_OPT_SET(&opt, QUICK);
1163                do_diff_cache(head, &opt);
1164                diffcore_std(&opt);
1165                for (i = 0; sb && i < diff_queued_diff.nr; i++) {
1166                        if (i)
1167                                strbuf_addch(sb, ' ');
1168                        strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);
1169                }
1170                diff_flush(&opt);
1171                return DIFF_OPT_TST(&opt, HAS_CHANGES) != 0;
1172        } else {
1173                for (i = 0; sb && i < active_nr; i++) {
1174                        if (i)
1175                                strbuf_addch(sb, ' ');
1176                        strbuf_addstr(sb, active_cache[i]->name);
1177                }
1178                return !!active_nr;
1179        }
1180}
1181
1182/**
1183 * Dies with a user-friendly message on how to proceed after resolving the
1184 * problem. This message can be overridden with state->resolvemsg.
1185 */
1186static void NORETURN die_user_resolve(const struct am_state *state)
1187{
1188        if (state->resolvemsg) {
1189                printf_ln("%s", state->resolvemsg);
1190        } else {
1191                const char *cmdline = state->interactive ? "git am -i" : "git am";
1192
1193                printf_ln(_("When you have resolved this problem, run \"%s --continue\"."), cmdline);
1194                printf_ln(_("If you prefer to skip this patch, run \"%s --skip\" instead."), cmdline);
1195                printf_ln(_("To restore the original branch and stop patching, run \"%s --abort\"."), cmdline);
1196        }
1197
1198        exit(128);
1199}
1200
1201static void am_signoff(struct strbuf *sb)
1202{
1203        char *cp;
1204        struct strbuf mine = STRBUF_INIT;
1205
1206        /* Does it end with our own sign-off? */
1207        strbuf_addf(&mine, "\n%s%s\n",
1208                    sign_off_header,
1209                    fmt_name(getenv("GIT_COMMITTER_NAME"),
1210                             getenv("GIT_COMMITTER_EMAIL")));
1211        if (mine.len < sb->len &&
1212            !strcmp(mine.buf, sb->buf + sb->len - mine.len))
1213                goto exit; /* no need to duplicate */
1214
1215        /* Does it have any Signed-off-by: in the text */
1216        for (cp = sb->buf;
1217             cp && *cp && (cp = strstr(cp, sign_off_header)) != NULL;
1218             cp = strchr(cp, '\n')) {
1219                if (sb->buf == cp || cp[-1] == '\n')
1220                        break;
1221        }
1222
1223        strbuf_addstr(sb, mine.buf + !!cp);
1224exit:
1225        strbuf_release(&mine);
1226}
1227
1228/**
1229 * Appends signoff to the "msg" field of the am_state.
1230 */
1231static void am_append_signoff(struct am_state *state)
1232{
1233        struct strbuf sb = STRBUF_INIT;
1234
1235        strbuf_attach(&sb, state->msg, state->msg_len, state->msg_len);
1236        am_signoff(&sb);
1237        state->msg = strbuf_detach(&sb, &state->msg_len);
1238}
1239
1240/**
1241 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
1242 * state->msg will be set to the patch message. state->author_name,
1243 * state->author_email and state->author_date will be set to the patch author's
1244 * name, email and date respectively. The patch body will be written to the
1245 * state directory's "patch" file.
1246 *
1247 * Returns 1 if the patch should be skipped, 0 otherwise.
1248 */
1249static int parse_mail(struct am_state *state, const char *mail)
1250{
1251        FILE *fp;
1252        struct strbuf sb = STRBUF_INIT;
1253        struct strbuf msg = STRBUF_INIT;
1254        struct strbuf author_name = STRBUF_INIT;
1255        struct strbuf author_date = STRBUF_INIT;
1256        struct strbuf author_email = STRBUF_INIT;
1257        int ret = 0;
1258        struct mailinfo mi;
1259
1260        setup_mailinfo(&mi);
1261
1262        if (state->utf8)
1263                mi.metainfo_charset = get_commit_output_encoding();
1264        else
1265                mi.metainfo_charset = NULL;
1266
1267        switch (state->keep) {
1268        case KEEP_FALSE:
1269                break;
1270        case KEEP_TRUE:
1271                mi.keep_subject = 1;
1272                break;
1273        case KEEP_NON_PATCH:
1274                mi.keep_non_patch_brackets_in_subject = 1;
1275                break;
1276        default:
1277                die("BUG: invalid value for state->keep");
1278        }
1279
1280        if (state->message_id)
1281                mi.add_message_id = 1;
1282
1283        switch (state->scissors) {
1284        case SCISSORS_UNSET:
1285                break;
1286        case SCISSORS_FALSE:
1287                mi.use_scissors = 0;
1288                break;
1289        case SCISSORS_TRUE:
1290                mi.use_scissors = 1;
1291                break;
1292        default:
1293                die("BUG: invalid value for state->scissors");
1294        }
1295
1296        mi.input = fopen(mail, "r");
1297        if (!mi.input)
1298                die("could not open input");
1299        mi.output = fopen(am_path(state, "info"), "w");
1300        if (!mi.output)
1301                die("could not open output 'info'");
1302        if (mailinfo(&mi, am_path(state, "msg"), am_path(state, "patch")))
1303                die("could not parse patch");
1304
1305        fclose(mi.input);
1306        fclose(mi.output);
1307
1308        /* Extract message and author information */
1309        fp = xfopen(am_path(state, "info"), "r");
1310        while (!strbuf_getline_lf(&sb, fp)) {
1311                const char *x;
1312
1313                if (skip_prefix(sb.buf, "Subject: ", &x)) {
1314                        if (msg.len)
1315                                strbuf_addch(&msg, '\n');
1316                        strbuf_addstr(&msg, x);
1317                } else if (skip_prefix(sb.buf, "Author: ", &x))
1318                        strbuf_addstr(&author_name, x);
1319                else if (skip_prefix(sb.buf, "Email: ", &x))
1320                        strbuf_addstr(&author_email, x);
1321                else if (skip_prefix(sb.buf, "Date: ", &x))
1322                        strbuf_addstr(&author_date, x);
1323        }
1324        fclose(fp);
1325
1326        /* Skip pine's internal folder data */
1327        if (!strcmp(author_name.buf, "Mail System Internal Data")) {
1328                ret = 1;
1329                goto finish;
1330        }
1331
1332        if (is_empty_file(am_path(state, "patch"))) {
1333                printf_ln(_("Patch is empty. Was it split wrong?"));
1334                die_user_resolve(state);
1335        }
1336
1337        strbuf_addstr(&msg, "\n\n");
1338        strbuf_addbuf(&msg, &mi.log_message);
1339        strbuf_stripspace(&msg, 0);
1340
1341        if (state->signoff)
1342                am_signoff(&msg);
1343
1344        assert(!state->author_name);
1345        state->author_name = strbuf_detach(&author_name, NULL);
1346
1347        assert(!state->author_email);
1348        state->author_email = strbuf_detach(&author_email, NULL);
1349
1350        assert(!state->author_date);
1351        state->author_date = strbuf_detach(&author_date, NULL);
1352
1353        assert(!state->msg);
1354        state->msg = strbuf_detach(&msg, &state->msg_len);
1355
1356finish:
1357        strbuf_release(&msg);
1358        strbuf_release(&author_date);
1359        strbuf_release(&author_email);
1360        strbuf_release(&author_name);
1361        strbuf_release(&sb);
1362        clear_mailinfo(&mi);
1363        return ret;
1364}
1365
1366/**
1367 * Sets commit_id to the commit hash where the mail was generated from.
1368 * Returns 0 on success, -1 on failure.
1369 */
1370static int get_mail_commit_sha1(unsigned char *commit_id, const char *mail)
1371{
1372        struct strbuf sb = STRBUF_INIT;
1373        FILE *fp = xfopen(mail, "r");
1374        const char *x;
1375
1376        if (strbuf_getline_lf(&sb, fp))
1377                return -1;
1378
1379        if (!skip_prefix(sb.buf, "From ", &x))
1380                return -1;
1381
1382        if (get_sha1_hex(x, commit_id) < 0)
1383                return -1;
1384
1385        strbuf_release(&sb);
1386        fclose(fp);
1387        return 0;
1388}
1389
1390/**
1391 * Sets state->msg, state->author_name, state->author_email, state->author_date
1392 * to the commit's respective info.
1393 */
1394static void get_commit_info(struct am_state *state, struct commit *commit)
1395{
1396        const char *buffer, *ident_line, *author_date, *msg;
1397        size_t ident_len;
1398        struct ident_split ident_split;
1399        struct strbuf sb = STRBUF_INIT;
1400
1401        buffer = logmsg_reencode(commit, NULL, get_commit_output_encoding());
1402
1403        ident_line = find_commit_header(buffer, "author", &ident_len);
1404
1405        if (split_ident_line(&ident_split, ident_line, ident_len) < 0) {
1406                strbuf_add(&sb, ident_line, ident_len);
1407                die(_("invalid ident line: %s"), sb.buf);
1408        }
1409
1410        assert(!state->author_name);
1411        if (ident_split.name_begin) {
1412                strbuf_add(&sb, ident_split.name_begin,
1413                        ident_split.name_end - ident_split.name_begin);
1414                state->author_name = strbuf_detach(&sb, NULL);
1415        } else
1416                state->author_name = xstrdup("");
1417
1418        assert(!state->author_email);
1419        if (ident_split.mail_begin) {
1420                strbuf_add(&sb, ident_split.mail_begin,
1421                        ident_split.mail_end - ident_split.mail_begin);
1422                state->author_email = strbuf_detach(&sb, NULL);
1423        } else
1424                state->author_email = xstrdup("");
1425
1426        author_date = show_ident_date(&ident_split, DATE_MODE(NORMAL));
1427        strbuf_addstr(&sb, author_date);
1428        assert(!state->author_date);
1429        state->author_date = strbuf_detach(&sb, NULL);
1430
1431        assert(!state->msg);
1432        msg = strstr(buffer, "\n\n");
1433        if (!msg)
1434                die(_("unable to parse commit %s"), oid_to_hex(&commit->object.oid));
1435        state->msg = xstrdup(msg + 2);
1436        state->msg_len = strlen(state->msg);
1437}
1438
1439/**
1440 * Writes `commit` as a patch to the state directory's "patch" file.
1441 */
1442static void write_commit_patch(const struct am_state *state, struct commit *commit)
1443{
1444        struct rev_info rev_info;
1445        FILE *fp;
1446
1447        fp = xfopen(am_path(state, "patch"), "w");
1448        init_revisions(&rev_info, NULL);
1449        rev_info.diff = 1;
1450        rev_info.abbrev = 0;
1451        rev_info.disable_stdin = 1;
1452        rev_info.show_root_diff = 1;
1453        rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
1454        rev_info.no_commit_id = 1;
1455        DIFF_OPT_SET(&rev_info.diffopt, BINARY);
1456        DIFF_OPT_SET(&rev_info.diffopt, FULL_INDEX);
1457        rev_info.diffopt.use_color = 0;
1458        rev_info.diffopt.file = fp;
1459        rev_info.diffopt.close_file = 1;
1460        add_pending_object(&rev_info, &commit->object, "");
1461        diff_setup_done(&rev_info.diffopt);
1462        log_tree_commit(&rev_info, commit);
1463}
1464
1465/**
1466 * Writes the diff of the index against HEAD as a patch to the state
1467 * directory's "patch" file.
1468 */
1469static void write_index_patch(const struct am_state *state)
1470{
1471        struct tree *tree;
1472        unsigned char head[GIT_SHA1_RAWSZ];
1473        struct rev_info rev_info;
1474        FILE *fp;
1475
1476        if (!get_sha1_tree("HEAD", head))
1477                tree = lookup_tree(head);
1478        else
1479                tree = lookup_tree(EMPTY_TREE_SHA1_BIN);
1480
1481        fp = xfopen(am_path(state, "patch"), "w");
1482        init_revisions(&rev_info, NULL);
1483        rev_info.diff = 1;
1484        rev_info.disable_stdin = 1;
1485        rev_info.no_commit_id = 1;
1486        rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
1487        rev_info.diffopt.use_color = 0;
1488        rev_info.diffopt.file = fp;
1489        rev_info.diffopt.close_file = 1;
1490        add_pending_object(&rev_info, &tree->object, "");
1491        diff_setup_done(&rev_info.diffopt);
1492        run_diff_index(&rev_info, 1);
1493}
1494
1495/**
1496 * Like parse_mail(), but parses the mail by looking up its commit ID
1497 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
1498 * of patches.
1499 *
1500 * state->orig_commit will be set to the original commit ID.
1501 *
1502 * Will always return 0 as the patch should never be skipped.
1503 */
1504static int parse_mail_rebase(struct am_state *state, const char *mail)
1505{
1506        struct commit *commit;
1507        unsigned char commit_sha1[GIT_SHA1_RAWSZ];
1508
1509        if (get_mail_commit_sha1(commit_sha1, mail) < 0)
1510                die(_("could not parse %s"), mail);
1511
1512        commit = lookup_commit_or_die(commit_sha1, mail);
1513
1514        get_commit_info(state, commit);
1515
1516        write_commit_patch(state, commit);
1517
1518        hashcpy(state->orig_commit, commit_sha1);
1519        write_state_text(state, "original-commit", sha1_to_hex(commit_sha1));
1520
1521        return 0;
1522}
1523
1524/**
1525 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
1526 * `index_file` is not NULL, the patch will be applied to that index.
1527 */
1528static int run_apply(const struct am_state *state, const char *index_file)
1529{
1530        struct child_process cp = CHILD_PROCESS_INIT;
1531
1532        cp.git_cmd = 1;
1533
1534        if (index_file)
1535                argv_array_pushf(&cp.env_array, "GIT_INDEX_FILE=%s", index_file);
1536
1537        /*
1538         * If we are allowed to fall back on 3-way merge, don't give false
1539         * errors during the initial attempt.
1540         */
1541        if (state->threeway && !index_file) {
1542                cp.no_stdout = 1;
1543                cp.no_stderr = 1;
1544        }
1545
1546        argv_array_push(&cp.args, "apply");
1547
1548        argv_array_pushv(&cp.args, state->git_apply_opts.argv);
1549
1550        if (index_file)
1551                argv_array_push(&cp.args, "--cached");
1552        else
1553                argv_array_push(&cp.args, "--index");
1554
1555        argv_array_push(&cp.args, am_path(state, "patch"));
1556
1557        if (run_command(&cp))
1558                return -1;
1559
1560        /* Reload index as git-apply will have modified it. */
1561        discard_cache();
1562        read_cache_from(index_file ? index_file : get_index_file());
1563
1564        return 0;
1565}
1566
1567/**
1568 * Builds an index that contains just the blobs needed for a 3way merge.
1569 */
1570static int build_fake_ancestor(const struct am_state *state, const char *index_file)
1571{
1572        struct child_process cp = CHILD_PROCESS_INIT;
1573
1574        cp.git_cmd = 1;
1575        argv_array_push(&cp.args, "apply");
1576        argv_array_pushv(&cp.args, state->git_apply_opts.argv);
1577        argv_array_pushf(&cp.args, "--build-fake-ancestor=%s", index_file);
1578        argv_array_push(&cp.args, am_path(state, "patch"));
1579
1580        if (run_command(&cp))
1581                return -1;
1582
1583        return 0;
1584}
1585
1586/**
1587 * Do the three-way merge using fake ancestor, his tree constructed
1588 * from the fake ancestor and the postimage of the patch, and our
1589 * state.
1590 */
1591static int run_fallback_merge_recursive(const struct am_state *state,
1592                                        unsigned char *orig_tree,
1593                                        unsigned char *our_tree,
1594                                        unsigned char *his_tree)
1595{
1596        struct child_process cp = CHILD_PROCESS_INIT;
1597        int status;
1598
1599        cp.git_cmd = 1;
1600
1601        argv_array_pushf(&cp.env_array, "GITHEAD_%s=%.*s",
1602                         sha1_to_hex(his_tree), linelen(state->msg), state->msg);
1603        if (state->quiet)
1604                argv_array_push(&cp.env_array, "GIT_MERGE_VERBOSITY=0");
1605
1606        argv_array_push(&cp.args, "merge-recursive");
1607        argv_array_push(&cp.args, sha1_to_hex(orig_tree));
1608        argv_array_push(&cp.args, "--");
1609        argv_array_push(&cp.args, sha1_to_hex(our_tree));
1610        argv_array_push(&cp.args, sha1_to_hex(his_tree));
1611
1612        status = run_command(&cp) ? (-1) : 0;
1613        discard_cache();
1614        read_cache();
1615        return status;
1616}
1617
1618/**
1619 * Attempt a threeway merge, using index_path as the temporary index.
1620 */
1621static int fall_back_threeway(const struct am_state *state, const char *index_path)
1622{
1623        unsigned char orig_tree[GIT_SHA1_RAWSZ], his_tree[GIT_SHA1_RAWSZ],
1624                      our_tree[GIT_SHA1_RAWSZ];
1625
1626        if (get_sha1("HEAD", our_tree) < 0)
1627                hashcpy(our_tree, EMPTY_TREE_SHA1_BIN);
1628
1629        if (build_fake_ancestor(state, index_path))
1630                return error("could not build fake ancestor");
1631
1632        discard_cache();
1633        read_cache_from(index_path);
1634
1635        if (write_index_as_tree(orig_tree, &the_index, index_path, 0, NULL))
1636                return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));
1637
1638        say(state, stdout, _("Using index info to reconstruct a base tree..."));
1639
1640        if (!state->quiet) {
1641                /*
1642                 * List paths that needed 3-way fallback, so that the user can
1643                 * review them with extra care to spot mismerges.
1644                 */
1645                struct rev_info rev_info;
1646                const char *diff_filter_str = "--diff-filter=AM";
1647
1648                init_revisions(&rev_info, NULL);
1649                rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;
1650                diff_opt_parse(&rev_info.diffopt, &diff_filter_str, 1, rev_info.prefix);
1651                add_pending_sha1(&rev_info, "HEAD", our_tree, 0);
1652                diff_setup_done(&rev_info.diffopt);
1653                run_diff_index(&rev_info, 1);
1654        }
1655
1656        if (run_apply(state, index_path))
1657                return error(_("Did you hand edit your patch?\n"
1658                                "It does not apply to blobs recorded in its index."));
1659
1660        if (write_index_as_tree(his_tree, &the_index, index_path, 0, NULL))
1661                return error("could not write tree");
1662
1663        say(state, stdout, _("Falling back to patching base and 3-way merge..."));
1664
1665        discard_cache();
1666        read_cache();
1667
1668        /*
1669         * This is not so wrong. Depending on which base we picked, orig_tree
1670         * may be wildly different from ours, but his_tree has the same set of
1671         * wildly different changes in parts the patch did not touch, so
1672         * recursive ends up canceling them, saying that we reverted all those
1673         * changes.
1674         */
1675
1676        if (run_fallback_merge_recursive(state, orig_tree, our_tree, his_tree)) {
1677                rerere(state->allow_rerere_autoupdate);
1678                return error(_("Failed to merge in the changes."));
1679        }
1680
1681        return 0;
1682}
1683
1684/**
1685 * Commits the current index with state->msg as the commit message and
1686 * state->author_name, state->author_email and state->author_date as the author
1687 * information.
1688 */
1689static void do_commit(const struct am_state *state)
1690{
1691        unsigned char tree[GIT_SHA1_RAWSZ], parent[GIT_SHA1_RAWSZ],
1692                      commit[GIT_SHA1_RAWSZ];
1693        unsigned char *ptr;
1694        struct commit_list *parents = NULL;
1695        const char *reflog_msg, *author;
1696        struct strbuf sb = STRBUF_INIT;
1697
1698        if (run_hook_le(NULL, "pre-applypatch", NULL))
1699                exit(1);
1700
1701        if (write_cache_as_tree(tree, 0, NULL))
1702                die(_("git write-tree failed to write a tree"));
1703
1704        if (!get_sha1_commit("HEAD", parent)) {
1705                ptr = parent;
1706                commit_list_insert(lookup_commit(parent), &parents);
1707        } else {
1708                ptr = NULL;
1709                say(state, stderr, _("applying to an empty history"));
1710        }
1711
1712        author = fmt_ident(state->author_name, state->author_email,
1713                        state->ignore_date ? NULL : state->author_date,
1714                        IDENT_STRICT);
1715
1716        if (state->committer_date_is_author_date)
1717                setenv("GIT_COMMITTER_DATE",
1718                        state->ignore_date ? "" : state->author_date, 1);
1719
1720        if (commit_tree(state->msg, state->msg_len, tree, parents, commit,
1721                                author, state->sign_commit))
1722                die(_("failed to write commit object"));
1723
1724        reflog_msg = getenv("GIT_REFLOG_ACTION");
1725        if (!reflog_msg)
1726                reflog_msg = "am";
1727
1728        strbuf_addf(&sb, "%s: %.*s", reflog_msg, linelen(state->msg),
1729                        state->msg);
1730
1731        update_ref(sb.buf, "HEAD", commit, ptr, 0, UPDATE_REFS_DIE_ON_ERR);
1732
1733        if (state->rebasing) {
1734                FILE *fp = xfopen(am_path(state, "rewritten"), "a");
1735
1736                assert(!is_null_sha1(state->orig_commit));
1737                fprintf(fp, "%s ", sha1_to_hex(state->orig_commit));
1738                fprintf(fp, "%s\n", sha1_to_hex(commit));
1739                fclose(fp);
1740        }
1741
1742        run_hook_le(NULL, "post-applypatch", NULL);
1743
1744        strbuf_release(&sb);
1745}
1746
1747/**
1748 * Validates the am_state for resuming -- the "msg" and authorship fields must
1749 * be filled up.
1750 */
1751static void validate_resume_state(const struct am_state *state)
1752{
1753        if (!state->msg)
1754                die(_("cannot resume: %s does not exist."),
1755                        am_path(state, "final-commit"));
1756
1757        if (!state->author_name || !state->author_email || !state->author_date)
1758                die(_("cannot resume: %s does not exist."),
1759                        am_path(state, "author-script"));
1760}
1761
1762/**
1763 * Interactively prompt the user on whether the current patch should be
1764 * applied.
1765 *
1766 * Returns 0 if the user chooses to apply the patch, 1 if the user chooses to
1767 * skip it.
1768 */
1769static int do_interactive(struct am_state *state)
1770{
1771        assert(state->msg);
1772
1773        if (!isatty(0))
1774                die(_("cannot be interactive without stdin connected to a terminal."));
1775
1776        for (;;) {
1777                const char *reply;
1778
1779                puts(_("Commit Body is:"));
1780                puts("--------------------------");
1781                printf("%s", state->msg);
1782                puts("--------------------------");
1783
1784                /*
1785                 * TRANSLATORS: Make sure to include [y], [n], [e], [v] and [a]
1786                 * in your translation. The program will only accept English
1787                 * input at this point.
1788                 */
1789                reply = git_prompt(_("Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all: "), PROMPT_ECHO);
1790
1791                if (!reply) {
1792                        continue;
1793                } else if (*reply == 'y' || *reply == 'Y') {
1794                        return 0;
1795                } else if (*reply == 'a' || *reply == 'A') {
1796                        state->interactive = 0;
1797                        return 0;
1798                } else if (*reply == 'n' || *reply == 'N') {
1799                        return 1;
1800                } else if (*reply == 'e' || *reply == 'E') {
1801                        struct strbuf msg = STRBUF_INIT;
1802
1803                        if (!launch_editor(am_path(state, "final-commit"), &msg, NULL)) {
1804                                free(state->msg);
1805                                state->msg = strbuf_detach(&msg, &state->msg_len);
1806                        }
1807                        strbuf_release(&msg);
1808                } else if (*reply == 'v' || *reply == 'V') {
1809                        const char *pager = git_pager(1);
1810                        struct child_process cp = CHILD_PROCESS_INIT;
1811
1812                        if (!pager)
1813                                pager = "cat";
1814                        prepare_pager_args(&cp, pager);
1815                        argv_array_push(&cp.args, am_path(state, "patch"));
1816                        run_command(&cp);
1817                }
1818        }
1819}
1820
1821/**
1822 * Applies all queued mail.
1823 *
1824 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
1825 * well as the state directory's "patch" file is used as-is for applying the
1826 * patch and committing it.
1827 */
1828static void am_run(struct am_state *state, int resume)
1829{
1830        const char *argv_gc_auto[] = {"gc", "--auto", NULL};
1831        struct strbuf sb = STRBUF_INIT;
1832
1833        unlink(am_path(state, "dirtyindex"));
1834
1835        refresh_and_write_cache();
1836
1837        if (index_has_changes(&sb)) {
1838                write_state_bool(state, "dirtyindex", 1);
1839                die(_("Dirty index: cannot apply patches (dirty: %s)"), sb.buf);
1840        }
1841
1842        strbuf_release(&sb);
1843
1844        while (state->cur <= state->last) {
1845                const char *mail = am_path(state, msgnum(state));
1846                int apply_status;
1847
1848                if (!file_exists(mail))
1849                        goto next;
1850
1851                if (resume) {
1852                        validate_resume_state(state);
1853                } else {
1854                        int skip;
1855
1856                        if (state->rebasing)
1857                                skip = parse_mail_rebase(state, mail);
1858                        else
1859                                skip = parse_mail(state, mail);
1860
1861                        if (skip)
1862                                goto next; /* mail should be skipped */
1863
1864                        write_author_script(state);
1865                        write_commit_msg(state);
1866                }
1867
1868                if (state->interactive && do_interactive(state))
1869                        goto next;
1870
1871                if (run_applypatch_msg_hook(state))
1872                        exit(1);
1873
1874                say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1875
1876                apply_status = run_apply(state, NULL);
1877
1878                if (apply_status && state->threeway) {
1879                        struct strbuf sb = STRBUF_INIT;
1880
1881                        strbuf_addstr(&sb, am_path(state, "patch-merge-index"));
1882                        apply_status = fall_back_threeway(state, sb.buf);
1883                        strbuf_release(&sb);
1884
1885                        /*
1886                         * Applying the patch to an earlier tree and merging
1887                         * the result may have produced the same tree as ours.
1888                         */
1889                        if (!apply_status && !index_has_changes(NULL)) {
1890                                say(state, stdout, _("No changes -- Patch already applied."));
1891                                goto next;
1892                        }
1893                }
1894
1895                if (apply_status) {
1896                        int advice_amworkdir = 1;
1897
1898                        printf_ln(_("Patch failed at %s %.*s"), msgnum(state),
1899                                linelen(state->msg), state->msg);
1900
1901                        git_config_get_bool("advice.amworkdir", &advice_amworkdir);
1902
1903                        if (advice_amworkdir)
1904                                printf_ln(_("The copy of the patch that failed is found in: %s"),
1905                                                am_path(state, "patch"));
1906
1907                        die_user_resolve(state);
1908                }
1909
1910                do_commit(state);
1911
1912next:
1913                am_next(state);
1914
1915                if (resume)
1916                        am_load(state);
1917                resume = 0;
1918        }
1919
1920        if (!is_empty_file(am_path(state, "rewritten"))) {
1921                assert(state->rebasing);
1922                copy_notes_for_rebase(state);
1923                run_post_rewrite_hook(state);
1924        }
1925
1926        /*
1927         * In rebasing mode, it's up to the caller to take care of
1928         * housekeeping.
1929         */
1930        if (!state->rebasing) {
1931                am_destroy(state);
1932                close_all_packs();
1933                run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
1934        }
1935}
1936
1937/**
1938 * Resume the current am session after patch application failure. The user did
1939 * all the hard work, and we do not have to do any patch application. Just
1940 * trust and commit what the user has in the index and working tree.
1941 */
1942static void am_resolve(struct am_state *state)
1943{
1944        validate_resume_state(state);
1945
1946        say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1947
1948        if (!index_has_changes(NULL)) {
1949                printf_ln(_("No changes - did you forget to use 'git add'?\n"
1950                        "If there is nothing left to stage, chances are that something else\n"
1951                        "already introduced the same changes; you might want to skip this patch."));
1952                die_user_resolve(state);
1953        }
1954
1955        if (unmerged_cache()) {
1956                printf_ln(_("You still have unmerged paths in your index.\n"
1957                        "Did you forget to use 'git add'?"));
1958                die_user_resolve(state);
1959        }
1960
1961        if (state->interactive) {
1962                write_index_patch(state);
1963                if (do_interactive(state))
1964                        goto next;
1965        }
1966
1967        rerere(0);
1968
1969        do_commit(state);
1970
1971next:
1972        am_next(state);
1973        am_load(state);
1974        am_run(state, 0);
1975}
1976
1977/**
1978 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
1979 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
1980 * failure.
1981 */
1982static int fast_forward_to(struct tree *head, struct tree *remote, int reset)
1983{
1984        struct lock_file *lock_file;
1985        struct unpack_trees_options opts;
1986        struct tree_desc t[2];
1987
1988        if (parse_tree(head) || parse_tree(remote))
1989                return -1;
1990
1991        lock_file = xcalloc(1, sizeof(struct lock_file));
1992        hold_locked_index(lock_file, 1);
1993
1994        refresh_cache(REFRESH_QUIET);
1995
1996        memset(&opts, 0, sizeof(opts));
1997        opts.head_idx = 1;
1998        opts.src_index = &the_index;
1999        opts.dst_index = &the_index;
2000        opts.update = 1;
2001        opts.merge = 1;
2002        opts.reset = reset;
2003        opts.fn = twoway_merge;
2004        init_tree_desc(&t[0], head->buffer, head->size);
2005        init_tree_desc(&t[1], remote->buffer, remote->size);
2006
2007        if (unpack_trees(2, t, &opts)) {
2008                rollback_lock_file(lock_file);
2009                return -1;
2010        }
2011
2012        if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
2013                die(_("unable to write new index file"));
2014
2015        return 0;
2016}
2017
2018/**
2019 * Merges a tree into the index. The index's stat info will take precedence
2020 * over the merged tree's. Returns 0 on success, -1 on failure.
2021 */
2022static int merge_tree(struct tree *tree)
2023{
2024        struct lock_file *lock_file;
2025        struct unpack_trees_options opts;
2026        struct tree_desc t[1];
2027
2028        if (parse_tree(tree))
2029                return -1;
2030
2031        lock_file = xcalloc(1, sizeof(struct lock_file));
2032        hold_locked_index(lock_file, 1);
2033
2034        memset(&opts, 0, sizeof(opts));
2035        opts.head_idx = 1;
2036        opts.src_index = &the_index;
2037        opts.dst_index = &the_index;
2038        opts.merge = 1;
2039        opts.fn = oneway_merge;
2040        init_tree_desc(&t[0], tree->buffer, tree->size);
2041
2042        if (unpack_trees(1, t, &opts)) {
2043                rollback_lock_file(lock_file);
2044                return -1;
2045        }
2046
2047        if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
2048                die(_("unable to write new index file"));
2049
2050        return 0;
2051}
2052
2053/**
2054 * Clean the index without touching entries that are not modified between
2055 * `head` and `remote`.
2056 */
2057static int clean_index(const unsigned char *head, const unsigned char *remote)
2058{
2059        struct tree *head_tree, *remote_tree, *index_tree;
2060        unsigned char index[GIT_SHA1_RAWSZ];
2061
2062        head_tree = parse_tree_indirect(head);
2063        if (!head_tree)
2064                return error(_("Could not parse object '%s'."), sha1_to_hex(head));
2065
2066        remote_tree = parse_tree_indirect(remote);
2067        if (!remote_tree)
2068                return error(_("Could not parse object '%s'."), sha1_to_hex(remote));
2069
2070        read_cache_unmerged();
2071
2072        if (fast_forward_to(head_tree, head_tree, 1))
2073                return -1;
2074
2075        if (write_cache_as_tree(index, 0, NULL))
2076                return -1;
2077
2078        index_tree = parse_tree_indirect(index);
2079        if (!index_tree)
2080                return error(_("Could not parse object '%s'."), sha1_to_hex(index));
2081
2082        if (fast_forward_to(index_tree, remote_tree, 0))
2083                return -1;
2084
2085        if (merge_tree(remote_tree))
2086                return -1;
2087
2088        remove_branch_state();
2089
2090        return 0;
2091}
2092
2093/**
2094 * Resets rerere's merge resolution metadata.
2095 */
2096static void am_rerere_clear(void)
2097{
2098        struct string_list merge_rr = STRING_LIST_INIT_DUP;
2099        rerere_clear(&merge_rr);
2100        string_list_clear(&merge_rr, 1);
2101}
2102
2103/**
2104 * Resume the current am session by skipping the current patch.
2105 */
2106static void am_skip(struct am_state *state)
2107{
2108        unsigned char head[GIT_SHA1_RAWSZ];
2109
2110        am_rerere_clear();
2111
2112        if (get_sha1("HEAD", head))
2113                hashcpy(head, EMPTY_TREE_SHA1_BIN);
2114
2115        if (clean_index(head, head))
2116                die(_("failed to clean index"));
2117
2118        am_next(state);
2119        am_load(state);
2120        am_run(state, 0);
2121}
2122
2123/**
2124 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
2125 *
2126 * It is not safe to reset HEAD when:
2127 * 1. git-am previously failed because the index was dirty.
2128 * 2. HEAD has moved since git-am previously failed.
2129 */
2130static int safe_to_abort(const struct am_state *state)
2131{
2132        struct strbuf sb = STRBUF_INIT;
2133        unsigned char abort_safety[GIT_SHA1_RAWSZ], head[GIT_SHA1_RAWSZ];
2134
2135        if (file_exists(am_path(state, "dirtyindex")))
2136                return 0;
2137
2138        if (read_state_file(&sb, state, "abort-safety", 1) > 0) {
2139                if (get_sha1_hex(sb.buf, abort_safety))
2140                        die(_("could not parse %s"), am_path(state, "abort_safety"));
2141        } else
2142                hashclr(abort_safety);
2143
2144        if (get_sha1("HEAD", head))
2145                hashclr(head);
2146
2147        if (!hashcmp(head, abort_safety))
2148                return 1;
2149
2150        error(_("You seem to have moved HEAD since the last 'am' failure.\n"
2151                "Not rewinding to ORIG_HEAD"));
2152
2153        return 0;
2154}
2155
2156/**
2157 * Aborts the current am session if it is safe to do so.
2158 */
2159static void am_abort(struct am_state *state)
2160{
2161        unsigned char curr_head[GIT_SHA1_RAWSZ], orig_head[GIT_SHA1_RAWSZ];
2162        int has_curr_head, has_orig_head;
2163        char *curr_branch;
2164
2165        if (!safe_to_abort(state)) {
2166                am_destroy(state);
2167                return;
2168        }
2169
2170        am_rerere_clear();
2171
2172        curr_branch = resolve_refdup("HEAD", 0, curr_head, NULL);
2173        has_curr_head = !is_null_sha1(curr_head);
2174        if (!has_curr_head)
2175                hashcpy(curr_head, EMPTY_TREE_SHA1_BIN);
2176
2177        has_orig_head = !get_sha1("ORIG_HEAD", orig_head);
2178        if (!has_orig_head)
2179                hashcpy(orig_head, EMPTY_TREE_SHA1_BIN);
2180
2181        clean_index(curr_head, orig_head);
2182
2183        if (has_orig_head)
2184                update_ref("am --abort", "HEAD", orig_head,
2185                                has_curr_head ? curr_head : NULL, 0,
2186                                UPDATE_REFS_DIE_ON_ERR);
2187        else if (curr_branch)
2188                delete_ref(curr_branch, NULL, REF_NODEREF);
2189
2190        free(curr_branch);
2191        am_destroy(state);
2192}
2193
2194/**
2195 * parse_options() callback that validates and sets opt->value to the
2196 * PATCH_FORMAT_* enum value corresponding to `arg`.
2197 */
2198static int parse_opt_patchformat(const struct option *opt, const char *arg, int unset)
2199{
2200        int *opt_value = opt->value;
2201
2202        if (!strcmp(arg, "mbox"))
2203                *opt_value = PATCH_FORMAT_MBOX;
2204        else if (!strcmp(arg, "stgit"))
2205                *opt_value = PATCH_FORMAT_STGIT;
2206        else if (!strcmp(arg, "stgit-series"))
2207                *opt_value = PATCH_FORMAT_STGIT_SERIES;
2208        else if (!strcmp(arg, "hg"))
2209                *opt_value = PATCH_FORMAT_HG;
2210        else if (!strcmp(arg, "mboxrd"))
2211                *opt_value = PATCH_FORMAT_MBOXRD;
2212        else
2213                return error(_("Invalid value for --patch-format: %s"), arg);
2214        return 0;
2215}
2216
2217enum resume_mode {
2218        RESUME_FALSE = 0,
2219        RESUME_APPLY,
2220        RESUME_RESOLVED,
2221        RESUME_SKIP,
2222        RESUME_ABORT
2223};
2224
2225static int git_am_config(const char *k, const char *v, void *cb)
2226{
2227        int status;
2228
2229        status = git_gpg_config(k, v, NULL);
2230        if (status)
2231                return status;
2232
2233        return git_default_config(k, v, NULL);
2234}
2235
2236int cmd_am(int argc, const char **argv, const char *prefix)
2237{
2238        struct am_state state;
2239        int binary = -1;
2240        int keep_cr = -1;
2241        int patch_format = PATCH_FORMAT_UNKNOWN;
2242        enum resume_mode resume = RESUME_FALSE;
2243        int in_progress;
2244
2245        const char * const usage[] = {
2246                N_("git am [<options>] [(<mbox>|<Maildir>)...]"),
2247                N_("git am [<options>] (--continue | --skip | --abort)"),
2248                NULL
2249        };
2250
2251        struct option options[] = {
2252                OPT_BOOL('i', "interactive", &state.interactive,
2253                        N_("run interactively")),
2254                OPT_HIDDEN_BOOL('b', "binary", &binary,
2255                        N_("historical option -- no-op")),
2256                OPT_BOOL('3', "3way", &state.threeway,
2257                        N_("allow fall back on 3way merging if needed")),
2258                OPT__QUIET(&state.quiet, N_("be quiet")),
2259                OPT_SET_INT('s', "signoff", &state.signoff,
2260                        N_("add a Signed-off-by line to the commit message"),
2261                        SIGNOFF_EXPLICIT),
2262                OPT_BOOL('u', "utf8", &state.utf8,
2263                        N_("recode into utf8 (default)")),
2264                OPT_SET_INT('k', "keep", &state.keep,
2265                        N_("pass -k flag to git-mailinfo"), KEEP_TRUE),
2266                OPT_SET_INT(0, "keep-non-patch", &state.keep,
2267                        N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH),
2268                OPT_BOOL('m', "message-id", &state.message_id,
2269                        N_("pass -m flag to git-mailinfo")),
2270                { OPTION_SET_INT, 0, "keep-cr", &keep_cr, NULL,
2271                  N_("pass --keep-cr flag to git-mailsplit for mbox format"),
2272                  PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1},
2273                { OPTION_SET_INT, 0, "no-keep-cr", &keep_cr, NULL,
2274                  N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),
2275                  PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 0},
2276                OPT_BOOL('c', "scissors", &state.scissors,
2277                        N_("strip everything before a scissors line")),
2278                OPT_PASSTHRU_ARGV(0, "whitespace", &state.git_apply_opts, N_("action"),
2279                        N_("pass it through git-apply"),
2280                        0),
2281                OPT_PASSTHRU_ARGV(0, "ignore-space-change", &state.git_apply_opts, NULL,
2282                        N_("pass it through git-apply"),
2283                        PARSE_OPT_NOARG),
2284                OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &state.git_apply_opts, NULL,
2285                        N_("pass it through git-apply"),
2286                        PARSE_OPT_NOARG),
2287                OPT_PASSTHRU_ARGV(0, "directory", &state.git_apply_opts, N_("root"),
2288                        N_("pass it through git-apply"),
2289                        0),
2290                OPT_PASSTHRU_ARGV(0, "exclude", &state.git_apply_opts, N_("path"),
2291                        N_("pass it through git-apply"),
2292                        0),
2293                OPT_PASSTHRU_ARGV(0, "include", &state.git_apply_opts, N_("path"),
2294                        N_("pass it through git-apply"),
2295                        0),
2296                OPT_PASSTHRU_ARGV('C', NULL, &state.git_apply_opts, N_("n"),
2297                        N_("pass it through git-apply"),
2298                        0),
2299                OPT_PASSTHRU_ARGV('p', NULL, &state.git_apply_opts, N_("num"),
2300                        N_("pass it through git-apply"),
2301                        0),
2302                OPT_CALLBACK(0, "patch-format", &patch_format, N_("format"),
2303                        N_("format the patch(es) are in"),
2304                        parse_opt_patchformat),
2305                OPT_PASSTHRU_ARGV(0, "reject", &state.git_apply_opts, NULL,
2306                        N_("pass it through git-apply"),
2307                        PARSE_OPT_NOARG),
2308                OPT_STRING(0, "resolvemsg", &state.resolvemsg, NULL,
2309                        N_("override error message when patch failure occurs")),
2310                OPT_CMDMODE(0, "continue", &resume,
2311                        N_("continue applying patches after resolving a conflict"),
2312                        RESUME_RESOLVED),
2313                OPT_CMDMODE('r', "resolved", &resume,
2314                        N_("synonyms for --continue"),
2315                        RESUME_RESOLVED),
2316                OPT_CMDMODE(0, "skip", &resume,
2317                        N_("skip the current patch"),
2318                        RESUME_SKIP),
2319                OPT_CMDMODE(0, "abort", &resume,
2320                        N_("restore the original branch and abort the patching operation."),
2321                        RESUME_ABORT),
2322                OPT_BOOL(0, "committer-date-is-author-date",
2323                        &state.committer_date_is_author_date,
2324                        N_("lie about committer date")),
2325                OPT_BOOL(0, "ignore-date", &state.ignore_date,
2326                        N_("use current timestamp for author date")),
2327                OPT_RERERE_AUTOUPDATE(&state.allow_rerere_autoupdate),
2328                { OPTION_STRING, 'S', "gpg-sign", &state.sign_commit, N_("key-id"),
2329                  N_("GPG-sign commits"),
2330                  PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
2331                OPT_HIDDEN_BOOL(0, "rebasing", &state.rebasing,
2332                        N_("(internal use for git-rebase)")),
2333                OPT_END()
2334        };
2335
2336        git_config(git_am_config, NULL);
2337
2338        am_state_init(&state, git_path("rebase-apply"));
2339
2340        in_progress = am_in_progress(&state);
2341        if (in_progress)
2342                am_load(&state);
2343
2344        argc = parse_options(argc, argv, prefix, options, usage, 0);
2345
2346        if (binary >= 0)
2347                fprintf_ln(stderr, _("The -b/--binary option has been a no-op for long time, and\n"
2348                                "it will be removed. Please do not use it anymore."));
2349
2350        /* Ensure a valid committer ident can be constructed */
2351        git_committer_info(IDENT_STRICT);
2352
2353        if (read_index_preload(&the_index, NULL) < 0)
2354                die(_("failed to read the index"));
2355
2356        if (in_progress) {
2357                /*
2358                 * Catch user error to feed us patches when there is a session
2359                 * in progress:
2360                 *
2361                 * 1. mbox path(s) are provided on the command-line.
2362                 * 2. stdin is not a tty: the user is trying to feed us a patch
2363                 *    from standard input. This is somewhat unreliable -- stdin
2364                 *    could be /dev/null for example and the caller did not
2365                 *    intend to feed us a patch but wanted to continue
2366                 *    unattended.
2367                 */
2368                if (argc || (resume == RESUME_FALSE && !isatty(0)))
2369                        die(_("previous rebase directory %s still exists but mbox given."),
2370                                state.dir);
2371
2372                if (resume == RESUME_FALSE)
2373                        resume = RESUME_APPLY;
2374
2375                if (state.signoff == SIGNOFF_EXPLICIT)
2376                        am_append_signoff(&state);
2377        } else {
2378                struct argv_array paths = ARGV_ARRAY_INIT;
2379                int i;
2380
2381                /*
2382                 * Handle stray state directory in the independent-run case. In
2383                 * the --rebasing case, it is up to the caller to take care of
2384                 * stray directories.
2385                 */
2386                if (file_exists(state.dir) && !state.rebasing) {
2387                        if (resume == RESUME_ABORT) {
2388                                am_destroy(&state);
2389                                am_state_release(&state);
2390                                return 0;
2391                        }
2392
2393                        die(_("Stray %s directory found.\n"
2394                                "Use \"git am --abort\" to remove it."),
2395                                state.dir);
2396                }
2397
2398                if (resume)
2399                        die(_("Resolve operation not in progress, we are not resuming."));
2400
2401                for (i = 0; i < argc; i++) {
2402                        if (is_absolute_path(argv[i]) || !prefix)
2403                                argv_array_push(&paths, argv[i]);
2404                        else
2405                                argv_array_push(&paths, mkpath("%s/%s", prefix, argv[i]));
2406                }
2407
2408                am_setup(&state, patch_format, paths.argv, keep_cr);
2409
2410                argv_array_clear(&paths);
2411        }
2412
2413        switch (resume) {
2414        case RESUME_FALSE:
2415                am_run(&state, 0);
2416                break;
2417        case RESUME_APPLY:
2418                am_run(&state, 1);
2419                break;
2420        case RESUME_RESOLVED:
2421                am_resolve(&state);
2422                break;
2423        case RESUME_SKIP:
2424                am_skip(&state);
2425                break;
2426        case RESUME_ABORT:
2427                am_abort(&state);
2428                break;
2429        default:
2430                die("BUG: invalid resume value");
2431        }
2432
2433        am_state_release(&state);
2434
2435        return 0;
2436}