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