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