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