builtin-am: implement --skip
[git/mingw.git] / builtin / am.c
blob765844b7821f77442a147ecaa65ed2847de35669
1 /*
2 * Builtin "git am"
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"
22 /**
23 * Returns 1 if the file is empty or does not exist, 0 otherwise.
25 static int is_empty_file(const char *filename)
27 struct stat st;
29 if (stat(filename, &st) < 0) {
30 if (errno == ENOENT)
31 return 1;
32 die_errno(_("could not stat %s"), filename);
35 return !st.st_size;
38 /**
39 * Like strbuf_getline(), but treats both '\n' and "\r\n" as line terminators.
41 static int strbuf_getline_crlf(struct strbuf *sb, FILE *fp)
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);
50 return 0;
53 /**
54 * Returns the length of the first line of msg.
56 static int linelen(const char *msg)
58 return strchrnul(msg, '\n') - msg;
61 enum patch_format {
62 PATCH_FORMAT_UNKNOWN = 0,
63 PATCH_FORMAT_MBOX
66 struct am_state {
67 /* state directory path */
68 char *dir;
70 /* current and last patch numbers, 1-indexed */
71 int cur;
72 int last;
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;
81 /* number of digits in patch filename */
82 int prec;
85 /**
86 * Initializes am_state with the default values. The state directory is set to
87 * dir.
89 static void am_state_init(struct am_state *state, const char *dir)
91 memset(state, 0, sizeof(*state));
93 assert(dir);
94 state->dir = xstrdup(dir);
96 state->prec = 4;
99 /**
100 * Releases memory allocated by an am_state.
102 static void am_state_release(struct am_state *state)
104 free(state->dir);
105 free(state->author_name);
106 free(state->author_email);
107 free(state->author_date);
108 free(state->msg);
112 * Returns path relative to the am_state directory.
114 static inline const char *am_path(const struct am_state *state, const char *path)
116 return mkpath("%s/%s", state->dir, path);
120 * Returns 1 if there is an am session in progress, 0 otherwise.
122 static int am_in_progress(const struct am_state *state)
124 struct stat st;
126 if (lstat(state->dir, &st) < 0 || !S_ISDIR(st.st_mode))
127 return 0;
128 if (lstat(am_path(state, "last"), &st) || !S_ISREG(st.st_mode))
129 return 0;
130 if (lstat(am_path(state, "next"), &st) || !S_ISREG(st.st_mode))
131 return 0;
132 return 1;
136 * Reads the contents of `file` in the `state` directory into `sb`. Returns the
137 * number of bytes read on success, -1 if the file does not exist. If `trim` is
138 * set, trailing whitespace will be removed.
140 static int read_state_file(struct strbuf *sb, const struct am_state *state,
141 const char *file, int trim)
143 strbuf_reset(sb);
145 if (strbuf_read_file(sb, am_path(state, file), 0) >= 0) {
146 if (trim)
147 strbuf_trim(sb);
149 return sb->len;
152 if (errno == ENOENT)
153 return -1;
155 die_errno(_("could not read '%s'"), am_path(state, file));
159 * Reads a KEY=VALUE shell variable assignment from `fp`, returning the VALUE
160 * as a newly-allocated string. VALUE must be a quoted string, and the KEY must
161 * match `key`. Returns NULL on failure.
163 * This is used by read_author_script() to read the GIT_AUTHOR_* variables from
164 * the author-script.
166 static char *read_shell_var(FILE *fp, const char *key)
168 struct strbuf sb = STRBUF_INIT;
169 const char *str;
171 if (strbuf_getline(&sb, fp, '\n'))
172 goto fail;
174 if (!skip_prefix(sb.buf, key, &str))
175 goto fail;
177 if (!skip_prefix(str, "=", &str))
178 goto fail;
180 strbuf_remove(&sb, 0, str - sb.buf);
182 str = sq_dequote(sb.buf);
183 if (!str)
184 goto fail;
186 return strbuf_detach(&sb, NULL);
188 fail:
189 strbuf_release(&sb);
190 return NULL;
194 * Reads and parses the state directory's "author-script" file, and sets
195 * state->author_name, state->author_email and state->author_date accordingly.
196 * Returns 0 on success, -1 if the file could not be parsed.
198 * The author script is of the format:
200 * GIT_AUTHOR_NAME='$author_name'
201 * GIT_AUTHOR_EMAIL='$author_email'
202 * GIT_AUTHOR_DATE='$author_date'
204 * where $author_name, $author_email and $author_date are quoted. We are strict
205 * with our parsing, as the file was meant to be eval'd in the old git-am.sh
206 * script, and thus if the file differs from what this function expects, it is
207 * better to bail out than to do something that the user does not expect.
209 static int read_author_script(struct am_state *state)
211 const char *filename = am_path(state, "author-script");
212 FILE *fp;
214 assert(!state->author_name);
215 assert(!state->author_email);
216 assert(!state->author_date);
218 fp = fopen(filename, "r");
219 if (!fp) {
220 if (errno == ENOENT)
221 return 0;
222 die_errno(_("could not open '%s' for reading"), filename);
225 state->author_name = read_shell_var(fp, "GIT_AUTHOR_NAME");
226 if (!state->author_name) {
227 fclose(fp);
228 return -1;
231 state->author_email = read_shell_var(fp, "GIT_AUTHOR_EMAIL");
232 if (!state->author_email) {
233 fclose(fp);
234 return -1;
237 state->author_date = read_shell_var(fp, "GIT_AUTHOR_DATE");
238 if (!state->author_date) {
239 fclose(fp);
240 return -1;
243 if (fgetc(fp) != EOF) {
244 fclose(fp);
245 return -1;
248 fclose(fp);
249 return 0;
253 * Saves state->author_name, state->author_email and state->author_date in the
254 * state directory's "author-script" file.
256 static void write_author_script(const struct am_state *state)
258 struct strbuf sb = STRBUF_INIT;
260 strbuf_addstr(&sb, "GIT_AUTHOR_NAME=");
261 sq_quote_buf(&sb, state->author_name);
262 strbuf_addch(&sb, '\n');
264 strbuf_addstr(&sb, "GIT_AUTHOR_EMAIL=");
265 sq_quote_buf(&sb, state->author_email);
266 strbuf_addch(&sb, '\n');
268 strbuf_addstr(&sb, "GIT_AUTHOR_DATE=");
269 sq_quote_buf(&sb, state->author_date);
270 strbuf_addch(&sb, '\n');
272 write_file(am_path(state, "author-script"), 1, "%s", sb.buf);
274 strbuf_release(&sb);
278 * Reads the commit message from the state directory's "final-commit" file,
279 * setting state->msg to its contents and state->msg_len to the length of its
280 * contents in bytes.
282 * Returns 0 on success, -1 if the file does not exist.
284 static int read_commit_msg(struct am_state *state)
286 struct strbuf sb = STRBUF_INIT;
288 assert(!state->msg);
290 if (read_state_file(&sb, state, "final-commit", 0) < 0) {
291 strbuf_release(&sb);
292 return -1;
295 state->msg = strbuf_detach(&sb, &state->msg_len);
296 return 0;
300 * Saves state->msg in the state directory's "final-commit" file.
302 static void write_commit_msg(const struct am_state *state)
304 int fd;
305 const char *filename = am_path(state, "final-commit");
307 fd = xopen(filename, O_WRONLY | O_CREAT, 0666);
308 if (write_in_full(fd, state->msg, state->msg_len) < 0)
309 die_errno(_("could not write to %s"), filename);
310 close(fd);
314 * Loads state from disk.
316 static void am_load(struct am_state *state)
318 struct strbuf sb = STRBUF_INIT;
320 if (read_state_file(&sb, state, "next", 1) < 0)
321 die("BUG: state file 'next' does not exist");
322 state->cur = strtol(sb.buf, NULL, 10);
324 if (read_state_file(&sb, state, "last", 1) < 0)
325 die("BUG: state file 'last' does not exist");
326 state->last = strtol(sb.buf, NULL, 10);
328 if (read_author_script(state) < 0)
329 die(_("could not parse author script"));
331 read_commit_msg(state);
333 strbuf_release(&sb);
337 * Removes the am_state directory, forcefully terminating the current am
338 * session.
340 static void am_destroy(const struct am_state *state)
342 struct strbuf sb = STRBUF_INIT;
344 strbuf_addstr(&sb, state->dir);
345 remove_dir_recursively(&sb, 0);
346 strbuf_release(&sb);
350 * Determines if the file looks like a piece of RFC2822 mail by grabbing all
351 * non-indented lines and checking if they look like they begin with valid
352 * header field names.
354 * Returns 1 if the file looks like a piece of mail, 0 otherwise.
356 static int is_mail(FILE *fp)
358 const char *header_regex = "^[!-9;-~]+:";
359 struct strbuf sb = STRBUF_INIT;
360 regex_t regex;
361 int ret = 1;
363 if (fseek(fp, 0L, SEEK_SET))
364 die_errno(_("fseek failed"));
366 if (regcomp(&regex, header_regex, REG_NOSUB | REG_EXTENDED))
367 die("invalid pattern: %s", header_regex);
369 while (!strbuf_getline_crlf(&sb, fp)) {
370 if (!sb.len)
371 break; /* End of header */
373 /* Ignore indented folded lines */
374 if (*sb.buf == '\t' || *sb.buf == ' ')
375 continue;
377 /* It's a header if it matches header_regex */
378 if (regexec(&regex, sb.buf, 0, NULL, 0)) {
379 ret = 0;
380 goto done;
384 done:
385 regfree(&regex);
386 strbuf_release(&sb);
387 return ret;
391 * Attempts to detect the patch_format of the patches contained in `paths`,
392 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
393 * detection fails.
395 static int detect_patch_format(const char **paths)
397 enum patch_format ret = PATCH_FORMAT_UNKNOWN;
398 struct strbuf l1 = STRBUF_INIT;
399 FILE *fp;
402 * We default to mbox format if input is from stdin and for directories
404 if (!*paths || !strcmp(*paths, "-") || is_directory(*paths))
405 return PATCH_FORMAT_MBOX;
408 * Otherwise, check the first few lines of the first patch, starting
409 * from the first non-blank line, to try to detect its format.
412 fp = xfopen(*paths, "r");
414 while (!strbuf_getline_crlf(&l1, fp)) {
415 if (l1.len)
416 break;
419 if (starts_with(l1.buf, "From ") || starts_with(l1.buf, "From: ")) {
420 ret = PATCH_FORMAT_MBOX;
421 goto done;
424 if (l1.len && is_mail(fp)) {
425 ret = PATCH_FORMAT_MBOX;
426 goto done;
429 done:
430 fclose(fp);
431 strbuf_release(&l1);
432 return ret;
436 * Splits out individual email patches from `paths`, where each path is either
437 * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
439 static int split_mail_mbox(struct am_state *state, const char **paths)
441 struct child_process cp = CHILD_PROCESS_INIT;
442 struct strbuf last = STRBUF_INIT;
444 cp.git_cmd = 1;
445 argv_array_push(&cp.args, "mailsplit");
446 argv_array_pushf(&cp.args, "-d%d", state->prec);
447 argv_array_pushf(&cp.args, "-o%s", state->dir);
448 argv_array_push(&cp.args, "-b");
449 argv_array_push(&cp.args, "--");
450 argv_array_pushv(&cp.args, paths);
452 if (capture_command(&cp, &last, 8))
453 return -1;
455 state->cur = 1;
456 state->last = strtol(last.buf, NULL, 10);
458 return 0;
462 * Splits a list of files/directories into individual email patches. Each path
463 * in `paths` must be a file/directory that is formatted according to
464 * `patch_format`.
466 * Once split out, the individual email patches will be stored in the state
467 * directory, with each patch's filename being its index, padded to state->prec
468 * digits.
470 * state->cur will be set to the index of the first mail, and state->last will
471 * be set to the index of the last mail.
473 * Returns 0 on success, -1 on failure.
475 static int split_mail(struct am_state *state, enum patch_format patch_format,
476 const char **paths)
478 switch (patch_format) {
479 case PATCH_FORMAT_MBOX:
480 return split_mail_mbox(state, paths);
481 default:
482 die("BUG: invalid patch_format");
484 return -1;
488 * Setup a new am session for applying patches
490 static void am_setup(struct am_state *state, enum patch_format patch_format,
491 const char **paths)
493 if (!patch_format)
494 patch_format = detect_patch_format(paths);
496 if (!patch_format) {
497 fprintf_ln(stderr, _("Patch format detection failed."));
498 exit(128);
501 if (mkdir(state->dir, 0777) < 0 && errno != EEXIST)
502 die_errno(_("failed to create directory '%s'"), state->dir);
504 if (split_mail(state, patch_format, paths) < 0) {
505 am_destroy(state);
506 die(_("Failed to split patches."));
510 * NOTE: Since the "next" and "last" files determine if an am_state
511 * session is in progress, they should be written last.
514 write_file(am_path(state, "next"), 1, "%d", state->cur);
516 write_file(am_path(state, "last"), 1, "%d", state->last);
520 * Increments the patch pointer, and cleans am_state for the application of the
521 * next patch.
523 static void am_next(struct am_state *state)
525 free(state->author_name);
526 state->author_name = NULL;
528 free(state->author_email);
529 state->author_email = NULL;
531 free(state->author_date);
532 state->author_date = NULL;
534 free(state->msg);
535 state->msg = NULL;
536 state->msg_len = 0;
538 unlink(am_path(state, "author-script"));
539 unlink(am_path(state, "final-commit"));
541 state->cur++;
542 write_file(am_path(state, "next"), 1, "%d", state->cur);
546 * Returns the filename of the current patch email.
548 static const char *msgnum(const struct am_state *state)
550 static struct strbuf sb = STRBUF_INIT;
552 strbuf_reset(&sb);
553 strbuf_addf(&sb, "%0*d", state->prec, state->cur);
555 return sb.buf;
559 * Refresh and write index.
561 static void refresh_and_write_cache(void)
563 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
565 hold_locked_index(lock_file, 1);
566 refresh_cache(REFRESH_QUIET);
567 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
568 die(_("unable to write index file"));
572 * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn
573 * branch, returns 1 if there are entries in the index, 0 otherwise. If an
574 * strbuf is provided, the space-separated list of files that differ will be
575 * appended to it.
577 static int index_has_changes(struct strbuf *sb)
579 unsigned char head[GIT_SHA1_RAWSZ];
580 int i;
582 if (!get_sha1_tree("HEAD", head)) {
583 struct diff_options opt;
585 diff_setup(&opt);
586 DIFF_OPT_SET(&opt, EXIT_WITH_STATUS);
587 if (!sb)
588 DIFF_OPT_SET(&opt, QUICK);
589 do_diff_cache(head, &opt);
590 diffcore_std(&opt);
591 for (i = 0; sb && i < diff_queued_diff.nr; i++) {
592 if (i)
593 strbuf_addch(sb, ' ');
594 strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);
596 diff_flush(&opt);
597 return DIFF_OPT_TST(&opt, HAS_CHANGES) != 0;
598 } else {
599 for (i = 0; sb && i < active_nr; i++) {
600 if (i)
601 strbuf_addch(sb, ' ');
602 strbuf_addstr(sb, active_cache[i]->name);
604 return !!active_nr;
609 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
610 * state->msg will be set to the patch message. state->author_name,
611 * state->author_email and state->author_date will be set to the patch author's
612 * name, email and date respectively. The patch body will be written to the
613 * state directory's "patch" file.
615 * Returns 1 if the patch should be skipped, 0 otherwise.
617 static int parse_mail(struct am_state *state, const char *mail)
619 FILE *fp;
620 struct child_process cp = CHILD_PROCESS_INIT;
621 struct strbuf sb = STRBUF_INIT;
622 struct strbuf msg = STRBUF_INIT;
623 struct strbuf author_name = STRBUF_INIT;
624 struct strbuf author_date = STRBUF_INIT;
625 struct strbuf author_email = STRBUF_INIT;
626 int ret = 0;
628 cp.git_cmd = 1;
629 cp.in = xopen(mail, O_RDONLY, 0);
630 cp.out = xopen(am_path(state, "info"), O_WRONLY | O_CREAT, 0777);
632 argv_array_push(&cp.args, "mailinfo");
633 argv_array_push(&cp.args, am_path(state, "msg"));
634 argv_array_push(&cp.args, am_path(state, "patch"));
636 if (run_command(&cp) < 0)
637 die("could not parse patch");
639 close(cp.in);
640 close(cp.out);
642 /* Extract message and author information */
643 fp = xfopen(am_path(state, "info"), "r");
644 while (!strbuf_getline(&sb, fp, '\n')) {
645 const char *x;
647 if (skip_prefix(sb.buf, "Subject: ", &x)) {
648 if (msg.len)
649 strbuf_addch(&msg, '\n');
650 strbuf_addstr(&msg, x);
651 } else if (skip_prefix(sb.buf, "Author: ", &x))
652 strbuf_addstr(&author_name, x);
653 else if (skip_prefix(sb.buf, "Email: ", &x))
654 strbuf_addstr(&author_email, x);
655 else if (skip_prefix(sb.buf, "Date: ", &x))
656 strbuf_addstr(&author_date, x);
658 fclose(fp);
660 /* Skip pine's internal folder data */
661 if (!strcmp(author_name.buf, "Mail System Internal Data")) {
662 ret = 1;
663 goto finish;
666 if (is_empty_file(am_path(state, "patch"))) {
667 printf_ln(_("Patch is empty. Was it split wrong?"));
668 exit(128);
671 strbuf_addstr(&msg, "\n\n");
672 if (strbuf_read_file(&msg, am_path(state, "msg"), 0) < 0)
673 die_errno(_("could not read '%s'"), am_path(state, "msg"));
674 stripspace(&msg, 0);
676 assert(!state->author_name);
677 state->author_name = strbuf_detach(&author_name, NULL);
679 assert(!state->author_email);
680 state->author_email = strbuf_detach(&author_email, NULL);
682 assert(!state->author_date);
683 state->author_date = strbuf_detach(&author_date, NULL);
685 assert(!state->msg);
686 state->msg = strbuf_detach(&msg, &state->msg_len);
688 finish:
689 strbuf_release(&msg);
690 strbuf_release(&author_date);
691 strbuf_release(&author_email);
692 strbuf_release(&author_name);
693 strbuf_release(&sb);
694 return ret;
698 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise.
700 static int run_apply(const struct am_state *state)
702 struct child_process cp = CHILD_PROCESS_INIT;
704 cp.git_cmd = 1;
706 argv_array_push(&cp.args, "apply");
707 argv_array_push(&cp.args, "--index");
708 argv_array_push(&cp.args, am_path(state, "patch"));
710 if (run_command(&cp))
711 return -1;
713 /* Reload index as git-apply will have modified it. */
714 discard_cache();
715 read_cache();
717 return 0;
721 * Commits the current index with state->msg as the commit message and
722 * state->author_name, state->author_email and state->author_date as the author
723 * information.
725 static void do_commit(const struct am_state *state)
727 unsigned char tree[GIT_SHA1_RAWSZ], parent[GIT_SHA1_RAWSZ],
728 commit[GIT_SHA1_RAWSZ];
729 unsigned char *ptr;
730 struct commit_list *parents = NULL;
731 const char *reflog_msg, *author;
732 struct strbuf sb = STRBUF_INIT;
734 if (write_cache_as_tree(tree, 0, NULL))
735 die(_("git write-tree failed to write a tree"));
737 if (!get_sha1_commit("HEAD", parent)) {
738 ptr = parent;
739 commit_list_insert(lookup_commit(parent), &parents);
740 } else {
741 ptr = NULL;
742 fprintf_ln(stderr, _("applying to an empty history"));
745 author = fmt_ident(state->author_name, state->author_email,
746 state->author_date, IDENT_STRICT);
748 if (commit_tree(state->msg, state->msg_len, tree, parents, commit,
749 author, NULL))
750 die(_("failed to write commit object"));
752 reflog_msg = getenv("GIT_REFLOG_ACTION");
753 if (!reflog_msg)
754 reflog_msg = "am";
756 strbuf_addf(&sb, "%s: %.*s", reflog_msg, linelen(state->msg),
757 state->msg);
759 update_ref(sb.buf, "HEAD", commit, ptr, 0, UPDATE_REFS_DIE_ON_ERR);
761 strbuf_release(&sb);
765 * Validates the am_state for resuming -- the "msg" and authorship fields must
766 * be filled up.
768 static void validate_resume_state(const struct am_state *state)
770 if (!state->msg)
771 die(_("cannot resume: %s does not exist."),
772 am_path(state, "final-commit"));
774 if (!state->author_name || !state->author_email || !state->author_date)
775 die(_("cannot resume: %s does not exist."),
776 am_path(state, "author-script"));
780 * Applies all queued mail.
782 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
783 * well as the state directory's "patch" file is used as-is for applying the
784 * patch and committing it.
786 static void am_run(struct am_state *state, int resume)
788 const char *argv_gc_auto[] = {"gc", "--auto", NULL};
789 struct strbuf sb = STRBUF_INIT;
791 refresh_and_write_cache();
793 if (index_has_changes(&sb))
794 die(_("Dirty index: cannot apply patches (dirty: %s)"), sb.buf);
796 strbuf_release(&sb);
798 while (state->cur <= state->last) {
799 const char *mail = am_path(state, msgnum(state));
801 if (!file_exists(mail))
802 goto next;
804 if (resume) {
805 validate_resume_state(state);
806 resume = 0;
807 } else {
808 if (parse_mail(state, mail))
809 goto next; /* mail should be skipped */
811 write_author_script(state);
812 write_commit_msg(state);
815 printf_ln(_("Applying: %.*s"), linelen(state->msg), state->msg);
817 if (run_apply(state) < 0) {
818 int advice_amworkdir = 1;
820 printf_ln(_("Patch failed at %s %.*s"), msgnum(state),
821 linelen(state->msg), state->msg);
823 git_config_get_bool("advice.amworkdir", &advice_amworkdir);
825 if (advice_amworkdir)
826 printf_ln(_("The copy of the patch that failed is found in: %s"),
827 am_path(state, "patch"));
829 exit(128);
832 do_commit(state);
834 next:
835 am_next(state);
838 am_destroy(state);
839 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
843 * Resume the current am session after patch application failure. The user did
844 * all the hard work, and we do not have to do any patch application. Just
845 * trust and commit what the user has in the index and working tree.
847 static void am_resolve(struct am_state *state)
849 validate_resume_state(state);
851 printf_ln(_("Applying: %.*s"), linelen(state->msg), state->msg);
853 if (!index_has_changes(NULL)) {
854 printf_ln(_("No changes - did you forget to use 'git add'?\n"
855 "If there is nothing left to stage, chances are that something else\n"
856 "already introduced the same changes; you might want to skip this patch."));
857 exit(128);
860 if (unmerged_cache()) {
861 printf_ln(_("You still have unmerged paths in your index.\n"
862 "Did you forget to use 'git add'?"));
863 exit(128);
866 do_commit(state);
868 am_next(state);
869 am_run(state, 0);
873 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
874 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
875 * failure.
877 static int fast_forward_to(struct tree *head, struct tree *remote, int reset)
879 struct lock_file *lock_file;
880 struct unpack_trees_options opts;
881 struct tree_desc t[2];
883 if (parse_tree(head) || parse_tree(remote))
884 return -1;
886 lock_file = xcalloc(1, sizeof(struct lock_file));
887 hold_locked_index(lock_file, 1);
889 refresh_cache(REFRESH_QUIET);
891 memset(&opts, 0, sizeof(opts));
892 opts.head_idx = 1;
893 opts.src_index = &the_index;
894 opts.dst_index = &the_index;
895 opts.update = 1;
896 opts.merge = 1;
897 opts.reset = reset;
898 opts.fn = twoway_merge;
899 init_tree_desc(&t[0], head->buffer, head->size);
900 init_tree_desc(&t[1], remote->buffer, remote->size);
902 if (unpack_trees(2, t, &opts)) {
903 rollback_lock_file(lock_file);
904 return -1;
907 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
908 die(_("unable to write new index file"));
910 return 0;
914 * Clean the index without touching entries that are not modified between
915 * `head` and `remote`.
917 static int clean_index(const unsigned char *head, const unsigned char *remote)
919 struct lock_file *lock_file;
920 struct tree *head_tree, *remote_tree, *index_tree;
921 unsigned char index[GIT_SHA1_RAWSZ];
922 struct pathspec pathspec;
924 head_tree = parse_tree_indirect(head);
925 if (!head_tree)
926 return error(_("Could not parse object '%s'."), sha1_to_hex(head));
928 remote_tree = parse_tree_indirect(remote);
929 if (!remote_tree)
930 return error(_("Could not parse object '%s'."), sha1_to_hex(remote));
932 read_cache_unmerged();
934 if (fast_forward_to(head_tree, head_tree, 1))
935 return -1;
937 if (write_cache_as_tree(index, 0, NULL))
938 return -1;
940 index_tree = parse_tree_indirect(index);
941 if (!index_tree)
942 return error(_("Could not parse object '%s'."), sha1_to_hex(index));
944 if (fast_forward_to(index_tree, remote_tree, 0))
945 return -1;
947 memset(&pathspec, 0, sizeof(pathspec));
949 lock_file = xcalloc(1, sizeof(struct lock_file));
950 hold_locked_index(lock_file, 1);
952 if (read_tree(remote_tree, 0, &pathspec)) {
953 rollback_lock_file(lock_file);
954 return -1;
957 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
958 die(_("unable to write new index file"));
960 remove_branch_state();
962 return 0;
966 * Resume the current am session by skipping the current patch.
968 static void am_skip(struct am_state *state)
970 unsigned char head[GIT_SHA1_RAWSZ];
972 if (get_sha1("HEAD", head))
973 hashcpy(head, EMPTY_TREE_SHA1_BIN);
975 if (clean_index(head, head))
976 die(_("failed to clean index"));
978 am_next(state);
979 am_run(state, 0);
983 * parse_options() callback that validates and sets opt->value to the
984 * PATCH_FORMAT_* enum value corresponding to `arg`.
986 static int parse_opt_patchformat(const struct option *opt, const char *arg, int unset)
988 int *opt_value = opt->value;
990 if (!strcmp(arg, "mbox"))
991 *opt_value = PATCH_FORMAT_MBOX;
992 else
993 return error(_("Invalid value for --patch-format: %s"), arg);
994 return 0;
997 enum resume_mode {
998 RESUME_FALSE = 0,
999 RESUME_APPLY,
1000 RESUME_RESOLVED,
1001 RESUME_SKIP
1004 int cmd_am(int argc, const char **argv, const char *prefix)
1006 struct am_state state;
1007 int patch_format = PATCH_FORMAT_UNKNOWN;
1008 enum resume_mode resume = RESUME_FALSE;
1010 const char * const usage[] = {
1011 N_("git am [options] [(<mbox>|<Maildir>)...]"),
1012 N_("git am [options] (--continue | --skip)"),
1013 NULL
1016 struct option options[] = {
1017 OPT_CALLBACK(0, "patch-format", &patch_format, N_("format"),
1018 N_("format the patch(es) are in"),
1019 parse_opt_patchformat),
1020 OPT_CMDMODE(0, "continue", &resume,
1021 N_("continue applying patches after resolving a conflict"),
1022 RESUME_RESOLVED),
1023 OPT_CMDMODE('r', "resolved", &resume,
1024 N_("synonyms for --continue"),
1025 RESUME_RESOLVED),
1026 OPT_CMDMODE(0, "skip", &resume,
1027 N_("skip the current patch"),
1028 RESUME_SKIP),
1029 OPT_END()
1033 * NEEDSWORK: Once all the features of git-am.sh have been
1034 * re-implemented in builtin/am.c, this preamble can be removed.
1036 if (!getenv("_GIT_USE_BUILTIN_AM")) {
1037 const char *path = mkpath("%s/git-am", git_exec_path());
1039 if (sane_execvp(path, (char **)argv) < 0)
1040 die_errno("could not exec %s", path);
1041 } else {
1042 prefix = setup_git_directory();
1043 trace_repo_setup(prefix);
1044 setup_work_tree();
1047 git_config(git_default_config, NULL);
1049 am_state_init(&state, git_path("rebase-apply"));
1051 argc = parse_options(argc, argv, prefix, options, usage, 0);
1053 if (read_index_preload(&the_index, NULL) < 0)
1054 die(_("failed to read the index"));
1056 if (am_in_progress(&state)) {
1057 if (resume == RESUME_FALSE)
1058 resume = RESUME_APPLY;
1060 am_load(&state);
1061 } else {
1062 struct argv_array paths = ARGV_ARRAY_INIT;
1063 int i;
1065 if (resume)
1066 die(_("Resolve operation not in progress, we are not resuming."));
1068 for (i = 0; i < argc; i++) {
1069 if (is_absolute_path(argv[i]) || !prefix)
1070 argv_array_push(&paths, argv[i]);
1071 else
1072 argv_array_push(&paths, mkpath("%s/%s", prefix, argv[i]));
1075 am_setup(&state, patch_format, paths.argv);
1077 argv_array_clear(&paths);
1080 switch (resume) {
1081 case RESUME_FALSE:
1082 am_run(&state, 0);
1083 break;
1084 case RESUME_APPLY:
1085 am_run(&state, 1);
1086 break;
1087 case RESUME_RESOLVED:
1088 am_resolve(&state);
1089 break;
1090 case RESUME_SKIP:
1091 am_skip(&state);
1092 break;
1093 default:
1094 die("BUG: invalid resume value");
1097 am_state_release(&state);
1099 return 0;