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