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