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