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