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