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