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