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