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