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