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