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