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