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