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