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