builtin/commit.c: extract ignore_non_trailer() helper function
[git/git.git] / sequencer.c
CommitLineData
26ae337b
RR
1#include "cache.h"
2#include "sequencer.h"
26ae337b 3#include "dir.h"
043a4492
RR
4#include "object.h"
5#include "commit.h"
6#include "tag.h"
7#include "run-command.h"
8#include "exec_cmd.h"
9#include "utf8.h"
10#include "cache-tree.h"
11#include "diff.h"
12#include "revision.h"
13#include "rerere.h"
14#include "merge-recursive.h"
15#include "refs.h"
b27cfb0d 16#include "argv-array.h"
043a4492
RR
17
18#define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
26ae337b 19
5ed75e2a 20const char sign_off_header[] = "Signed-off-by: ";
cd650a4e 21static const char cherry_picked_prefix[] = "(cherry picked from commit ";
5ed75e2a 22
b971e04f
BC
23static int is_rfc2822_line(const char *buf, int len)
24{
25 int i;
26
27 for (i = 0; i < len; i++) {
28 int ch = buf[i];
29 if (ch == ':')
30 return 1;
31 if (!isalnum(ch) && ch != '-')
32 break;
33 }
34
35 return 0;
36}
37
38static int is_cherry_picked_from_line(const char *buf, int len)
39{
40 /*
41 * We only care that it looks roughly like (cherry picked from ...)
42 */
43 return len > strlen(cherry_picked_prefix) + 1 &&
44 !prefixcmp(buf, cherry_picked_prefix) && buf[len - 1] == ')';
45}
46
bab4d109
BC
47/*
48 * Returns 0 for non-conforming footer
49 * Returns 1 for conforming footer
50 * Returns 2 when sob exists within conforming footer
51 * Returns 3 when sob exists within conforming footer as last entry
52 */
53static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
54 int ignore_footer)
b971e04f
BC
55{
56 char prev;
57 int i, k;
58 int len = sb->len - ignore_footer;
59 const char *buf = sb->buf;
bab4d109 60 int found_sob = 0;
b971e04f
BC
61
62 /* footer must end with newline */
63 if (!len || buf[len - 1] != '\n')
64 return 0;
65
66 prev = '\0';
67 for (i = len - 1; i > 0; i--) {
68 char ch = buf[i];
69 if (prev == '\n' && ch == '\n') /* paragraph break */
70 break;
71 prev = ch;
72 }
73
74 /* require at least one blank line */
75 if (prev != '\n' || buf[i] != '\n')
76 return 0;
77
78 /* advance to start of last paragraph */
79 while (i < len - 1 && buf[i] == '\n')
80 i++;
81
82 for (; i < len; i = k) {
bab4d109
BC
83 int found_rfc2822;
84
b971e04f
BC
85 for (k = i; k < len && buf[k] != '\n'; k++)
86 ; /* do nothing */
87 k++;
88
bab4d109
BC
89 found_rfc2822 = is_rfc2822_line(buf + i, k - i - 1);
90 if (found_rfc2822 && sob &&
91 !strncmp(buf + i, sob->buf, sob->len))
92 found_sob = k;
93
94 if (!(found_rfc2822 ||
95 is_cherry_picked_from_line(buf + i, k - i - 1)))
b971e04f
BC
96 return 0;
97 }
bab4d109
BC
98 if (found_sob == i)
99 return 3;
100 if (found_sob)
101 return 2;
b971e04f
BC
102 return 1;
103}
5ed75e2a 104
250f2492 105static void remove_sequencer_state(void)
26ae337b
RR
106{
107 struct strbuf seq_dir = STRBUF_INIT;
26ae337b
RR
108
109 strbuf_addf(&seq_dir, "%s", git_path(SEQ_DIR));
d596118d 110 remove_dir_recursively(&seq_dir, 0);
26ae337b 111 strbuf_release(&seq_dir);
26ae337b 112}
043a4492
RR
113
114static const char *action_name(const struct replay_opts *opts)
115{
116 return opts->action == REPLAY_REVERT ? "revert" : "cherry-pick";
117}
118
119static char *get_encoding(const char *message);
120
121struct commit_message {
122 char *parent_label;
123 const char *label;
124 const char *subject;
125 char *reencoded_message;
126 const char *message;
127};
128
129static int get_message(struct commit *commit, struct commit_message *out)
130{
131 const char *encoding;
132 const char *abbrev, *subject;
133 int abbrev_len, subject_len;
134 char *q;
135
136 if (!commit->buffer)
137 return -1;
138 encoding = get_encoding(commit->buffer);
139 if (!encoding)
140 encoding = "UTF-8";
141 if (!git_commit_encoding)
142 git_commit_encoding = "UTF-8";
143
144 out->reencoded_message = NULL;
145 out->message = commit->buffer;
0e18bcd5 146 if (same_encoding(encoding, git_commit_encoding))
043a4492
RR
147 out->reencoded_message = reencode_string(commit->buffer,
148 git_commit_encoding, encoding);
149 if (out->reencoded_message)
150 out->message = out->reencoded_message;
151
152 abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
153 abbrev_len = strlen(abbrev);
154
155 subject_len = find_commit_subject(out->message, &subject);
156
157 out->parent_label = xmalloc(strlen("parent of ") + abbrev_len +
158 strlen("... ") + subject_len + 1);
159 q = out->parent_label;
160 q = mempcpy(q, "parent of ", strlen("parent of "));
161 out->label = q;
162 q = mempcpy(q, abbrev, abbrev_len);
163 q = mempcpy(q, "... ", strlen("... "));
164 out->subject = q;
165 q = mempcpy(q, subject, subject_len);
166 *q = '\0';
167 return 0;
168}
169
170static void free_message(struct commit_message *msg)
171{
172 free(msg->parent_label);
173 free(msg->reencoded_message);
174}
175
176static char *get_encoding(const char *message)
177{
178 const char *p = message, *eol;
179
180 while (*p && *p != '\n') {
181 for (eol = p + 1; *eol && *eol != '\n'; eol++)
182 ; /* do nothing */
183 if (!prefixcmp(p, "encoding ")) {
184 char *result = xmalloc(eol - 8 - p);
185 strlcpy(result, p + 9, eol - 8 - p);
186 return result;
187 }
188 p = eol;
189 if (*p == '\n')
190 p++;
191 }
192 return NULL;
193}
194
195static void write_cherry_pick_head(struct commit *commit, const char *pseudoref)
196{
197 const char *filename;
198 int fd;
199 struct strbuf buf = STRBUF_INIT;
200
201 strbuf_addf(&buf, "%s\n", sha1_to_hex(commit->object.sha1));
202
203 filename = git_path("%s", pseudoref);
204 fd = open(filename, O_WRONLY | O_CREAT, 0666);
205 if (fd < 0)
206 die_errno(_("Could not open '%s' for writing"), filename);
207 if (write_in_full(fd, buf.buf, buf.len) != buf.len || close(fd))
208 die_errno(_("Could not write to '%s'"), filename);
209 strbuf_release(&buf);
210}
211
ed727b19 212static void print_advice(int show_hint, struct replay_opts *opts)
043a4492
RR
213{
214 char *msg = getenv("GIT_CHERRY_PICK_HELP");
215
216 if (msg) {
217 fprintf(stderr, "%s\n", msg);
218 /*
41ccfdd9 219 * A conflict has occurred but the porcelain
043a4492
RR
220 * (typically rebase --interactive) wants to take care
221 * of the commit itself so remove CHERRY_PICK_HEAD
222 */
223 unlink(git_path("CHERRY_PICK_HEAD"));
224 return;
225 }
226
ed727b19
PH
227 if (show_hint) {
228 if (opts->no_commit)
229 advise(_("after resolving the conflicts, mark the corrected paths\n"
230 "with 'git add <paths>' or 'git rm <paths>'"));
231 else
232 advise(_("after resolving the conflicts, mark the corrected paths\n"
233 "with 'git add <paths>' or 'git rm <paths>'\n"
234 "and commit the result with 'git commit'"));
235 }
043a4492
RR
236}
237
238static void write_message(struct strbuf *msgbuf, const char *filename)
239{
240 static struct lock_file msg_file;
241
242 int msg_fd = hold_lock_file_for_update(&msg_file, filename,
243 LOCK_DIE_ON_ERROR);
244 if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
245 die_errno(_("Could not write to %s"), filename);
246 strbuf_release(msgbuf);
247 if (commit_lock_file(&msg_file) < 0)
248 die(_("Error wrapping up %s"), filename);
249}
250
251static struct tree *empty_tree(void)
252{
cba595bd 253 return lookup_tree(EMPTY_TREE_SHA1_BIN);
043a4492
RR
254}
255
256static int error_dirty_index(struct replay_opts *opts)
257{
258 if (read_cache_unmerged())
259 return error_resolve_conflict(action_name(opts));
260
261 /* Different translation strings for cherry-pick and revert */
262 if (opts->action == REPLAY_PICK)
263 error(_("Your local changes would be overwritten by cherry-pick."));
264 else
265 error(_("Your local changes would be overwritten by revert."));
266
267 if (advice_commit_before_merge)
268 advise(_("Commit your changes or stash them to proceed."));
269 return -1;
270}
271
334ae397 272static int fast_forward_to(const unsigned char *to, const unsigned char *from,
eb4be1cb 273 int unborn, struct replay_opts *opts)
043a4492
RR
274{
275 struct ref_lock *ref_lock;
eb4be1cb
RR
276 struct strbuf sb = STRBUF_INIT;
277 int ret;
043a4492
RR
278
279 read_cache();
db699a8a 280 if (checkout_fast_forward(from, to, 1))
043a4492 281 exit(1); /* the callee should have complained already */
9bbb0fa1
BK
282 ref_lock = lock_any_ref_for_update("HEAD", unborn ? null_sha1 : from,
283 0, NULL);
eb4be1cb
RR
284 strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
285 ret = write_ref_sha1(ref_lock, to, sb.buf);
286 strbuf_release(&sb);
287 return ret;
043a4492
RR
288}
289
75c961b7
JH
290void append_conflicts_hint(struct strbuf *msgbuf)
291{
292 int i;
293
294 strbuf_addstr(msgbuf, "\nConflicts:\n");
295 for (i = 0; i < active_nr;) {
296 const struct cache_entry *ce = active_cache[i++];
297 if (ce_stage(ce)) {
298 strbuf_addch(msgbuf, '\t');
299 strbuf_addstr(msgbuf, ce->name);
300 strbuf_addch(msgbuf, '\n');
301 while (i < active_nr && !strcmp(ce->name,
302 active_cache[i]->name))
303 i++;
304 }
305 }
306}
307
043a4492
RR
308static int do_recursive_merge(struct commit *base, struct commit *next,
309 const char *base_label, const char *next_label,
310 unsigned char *head, struct strbuf *msgbuf,
311 struct replay_opts *opts)
312{
313 struct merge_options o;
314 struct tree *result, *next_tree, *base_tree, *head_tree;
315 int clean, index_fd;
316 const char **xopt;
317 static struct lock_file index_lock;
318
319 index_fd = hold_locked_index(&index_lock, 1);
320
321 read_cache();
322
323 init_merge_options(&o);
324 o.ancestor = base ? base_label : "(empty tree)";
325 o.branch1 = "HEAD";
326 o.branch2 = next ? next_label : "(empty tree)";
327
328 head_tree = parse_tree_indirect(head);
329 next_tree = next ? next->tree : empty_tree();
330 base_tree = base ? base->tree : empty_tree();
331
332 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
333 parse_merge_opt(&o, *xopt);
334
335 clean = merge_trees(&o,
336 head_tree,
337 next_tree, base_tree, &result);
338
339 if (active_cache_changed &&
340 (write_cache(index_fd, active_cache, active_nr) ||
341 commit_locked_index(&index_lock)))
342 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
343 die(_("%s: Unable to write new index file"), action_name(opts));
344 rollback_lock_file(&index_lock);
345
5ed75e2a 346 if (opts->signoff)
bab4d109 347 append_signoff(msgbuf, 0, 0);
5ed75e2a 348
75c961b7
JH
349 if (!clean)
350 append_conflicts_hint(msgbuf);
043a4492
RR
351
352 return !clean;
353}
354
b27cfb0d
NH
355static int is_index_unchanged(void)
356{
357 unsigned char head_sha1[20];
358 struct commit *head_commit;
359
360 if (!resolve_ref_unsafe("HEAD", head_sha1, 1, NULL))
361 return error(_("Could not resolve HEAD commit\n"));
362
363 head_commit = lookup_commit(head_sha1);
4b580061
NH
364
365 /*
366 * If head_commit is NULL, check_commit, called from
367 * lookup_commit, would have indicated that head_commit is not
368 * a commit object already. parse_commit() will return failure
369 * without further complaints in such a case. Otherwise, if
370 * the commit is invalid, parse_commit() will complain. So
371 * there is nothing for us to say here. Just return failure.
372 */
373 if (parse_commit(head_commit))
374 return -1;
b27cfb0d
NH
375
376 if (!active_cache_tree)
377 active_cache_tree = cache_tree();
378
379 if (!cache_tree_fully_valid(active_cache_tree))
9c5e6c80
NTND
380 if (cache_tree_update(active_cache_tree,
381 (const struct cache_entry * const *)active_cache,
382 active_nr, 0))
b27cfb0d
NH
383 return error(_("Unable to update cache tree\n"));
384
385 return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.sha1);
386}
387
043a4492
RR
388/*
389 * If we are cherry-pick, and if the merge did not result in
390 * hand-editing, we will hit this commit and inherit the original
391 * author date and name.
392 * If we are revert, or if our cherry-pick results in a hand merge,
393 * we had better say that the current user is responsible for that.
394 */
ac2b0e8f
JH
395static int run_git_commit(const char *defmsg, struct replay_opts *opts,
396 int allow_empty)
043a4492 397{
b27cfb0d
NH
398 struct argv_array array;
399 int rc;
400
401 argv_array_init(&array);
402 argv_array_push(&array, "commit");
403 argv_array_push(&array, "-n");
043a4492 404
043a4492 405 if (opts->signoff)
b27cfb0d 406 argv_array_push(&array, "-s");
043a4492 407 if (!opts->edit) {
b27cfb0d
NH
408 argv_array_push(&array, "-F");
409 argv_array_push(&array, defmsg);
043a4492 410 }
b27cfb0d 411
ac2b0e8f 412 if (allow_empty)
b27cfb0d 413 argv_array_push(&array, "--allow-empty");
df478b74 414
4bee9584
CW
415 if (opts->allow_empty_message)
416 argv_array_push(&array, "--allow-empty-message");
417
b27cfb0d
NH
418 rc = run_command_v_opt(array.argv, RUN_GIT_CMD);
419 argv_array_clear(&array);
420 return rc;
421}
422
423static int is_original_commit_empty(struct commit *commit)
424{
425 const unsigned char *ptree_sha1;
426
427 if (parse_commit(commit))
428 return error(_("Could not parse commit %s\n"),
429 sha1_to_hex(commit->object.sha1));
430 if (commit->parents) {
431 struct commit *parent = commit->parents->item;
432 if (parse_commit(parent))
433 return error(_("Could not parse parent commit %s\n"),
434 sha1_to_hex(parent->object.sha1));
435 ptree_sha1 = parent->tree->object.sha1;
436 } else {
437 ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
043a4492 438 }
043a4492 439
b27cfb0d 440 return !hashcmp(ptree_sha1, commit->tree->object.sha1);
043a4492
RR
441}
442
ac2b0e8f
JH
443/*
444 * Do we run "git commit" with "--allow-empty"?
445 */
446static int allow_empty(struct replay_opts *opts, struct commit *commit)
447{
448 int index_unchanged, empty_commit;
449
450 /*
451 * Three cases:
452 *
453 * (1) we do not allow empty at all and error out.
454 *
455 * (2) we allow ones that were initially empty, but
456 * forbid the ones that become empty;
457 *
458 * (3) we allow both.
459 */
460 if (!opts->allow_empty)
461 return 0; /* let "git commit" barf as necessary */
462
463 index_unchanged = is_index_unchanged();
464 if (index_unchanged < 0)
465 return index_unchanged;
466 if (!index_unchanged)
467 return 0; /* we do not have to say --allow-empty */
468
469 if (opts->keep_redundant_commits)
470 return 1;
471
472 empty_commit = is_original_commit_empty(commit);
473 if (empty_commit < 0)
474 return empty_commit;
475 if (!empty_commit)
476 return 0;
477 else
478 return 1;
479}
480
043a4492
RR
481static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
482{
483 unsigned char head[20];
484 struct commit *base, *next, *parent;
485 const char *base_label, *next_label;
486 struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
487 char *defmsg = NULL;
488 struct strbuf msgbuf = STRBUF_INIT;
c8d1351d 489 int res, unborn = 0, allow;
043a4492
RR
490
491 if (opts->no_commit) {
492 /*
493 * We do not intend to commit immediately. We just want to
494 * merge the differences in, so let's compute the tree
495 * that represents the "current" state for merge-recursive
496 * to work on.
497 */
498 if (write_cache_as_tree(head, 0, NULL))
499 die (_("Your index file is unmerged."));
500 } else {
334ae397
MZ
501 unborn = get_sha1("HEAD", head);
502 if (unborn)
503 hashcpy(head, EMPTY_TREE_SHA1_BIN);
504 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD", 0))
043a4492
RR
505 return error_dirty_index(opts);
506 }
507 discard_cache();
508
509 if (!commit->parents) {
510 parent = NULL;
511 }
512 else if (commit->parents->next) {
513 /* Reverting or cherry-picking a merge commit */
514 int cnt;
515 struct commit_list *p;
516
517 if (!opts->mainline)
518 return error(_("Commit %s is a merge but no -m option was given."),
519 sha1_to_hex(commit->object.sha1));
520
521 for (cnt = 1, p = commit->parents;
522 cnt != opts->mainline && p;
523 cnt++)
524 p = p->next;
525 if (cnt != opts->mainline || !p)
526 return error(_("Commit %s does not have parent %d"),
527 sha1_to_hex(commit->object.sha1), opts->mainline);
528 parent = p->item;
529 } else if (0 < opts->mainline)
530 return error(_("Mainline was specified but commit %s is not a merge."),
531 sha1_to_hex(commit->object.sha1));
532 else
533 parent = commit->parents->item;
534
334ae397
MZ
535 if (opts->allow_ff &&
536 ((parent && !hashcmp(parent->object.sha1, head)) ||
537 (!parent && unborn)))
eb4be1cb 538 return fast_forward_to(commit->object.sha1, head, unborn, opts);
043a4492
RR
539
540 if (parent && parse_commit(parent) < 0)
541 /* TRANSLATORS: The first %s will be "revert" or
542 "cherry-pick", the second %s a SHA1 */
543 return error(_("%s: cannot parse parent commit %s"),
544 action_name(opts), sha1_to_hex(parent->object.sha1));
545
546 if (get_message(commit, &msg) != 0)
547 return error(_("Cannot get commit message for %s"),
548 sha1_to_hex(commit->object.sha1));
549
550 /*
551 * "commit" is an existing commit. We would want to apply
552 * the difference it introduces since its first parent "prev"
553 * on top of the current HEAD if we are cherry-pick. Or the
554 * reverse of it if we are revert.
555 */
556
557 defmsg = git_pathdup("MERGE_MSG");
558
559 if (opts->action == REPLAY_REVERT) {
560 base = commit;
561 base_label = msg.label;
562 next = parent;
563 next_label = msg.parent_label;
564 strbuf_addstr(&msgbuf, "Revert \"");
565 strbuf_addstr(&msgbuf, msg.subject);
566 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
567 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
568
569 if (commit->parents && commit->parents->next) {
570 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
571 strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
572 }
573 strbuf_addstr(&msgbuf, ".\n");
574 } else {
575 const char *p;
576
577 base = parent;
578 base_label = msg.parent_label;
579 next = commit;
580 next_label = msg.label;
581
582 /*
583 * Append the commit log message to msgbuf; it starts
584 * after the tree, parent, author, committer
585 * information followed by "\n\n".
586 */
587 p = strstr(msg.message, "\n\n");
588 if (p) {
589 p += 2;
590 strbuf_addstr(&msgbuf, p);
591 }
592
593 if (opts->record_origin) {
bab4d109 594 if (!has_conforming_footer(&msgbuf, NULL, 0))
b971e04f 595 strbuf_addch(&msgbuf, '\n');
cd650a4e 596 strbuf_addstr(&msgbuf, cherry_picked_prefix);
043a4492
RR
597 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
598 strbuf_addstr(&msgbuf, ")\n");
599 }
600 }
601
602 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REPLAY_REVERT) {
603 res = do_recursive_merge(base, next, base_label, next_label,
604 head, &msgbuf, opts);
605 write_message(&msgbuf, defmsg);
606 } else {
607 struct commit_list *common = NULL;
608 struct commit_list *remotes = NULL;
609
610 write_message(&msgbuf, defmsg);
611
612 commit_list_insert(base, &common);
613 commit_list_insert(next, &remotes);
614 res = try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
615 common, sha1_to_hex(head), remotes);
616 free_commit_list(common);
617 free_commit_list(remotes);
618 }
619
620 /*
621 * If the merge was clean or if it failed due to conflict, we write
622 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
623 * However, if the merge did not even start, then we don't want to
624 * write it at all.
625 */
626 if (opts->action == REPLAY_PICK && !opts->no_commit && (res == 0 || res == 1))
627 write_cherry_pick_head(commit, "CHERRY_PICK_HEAD");
628 if (opts->action == REPLAY_REVERT && ((opts->no_commit && res == 0) || res == 1))
629 write_cherry_pick_head(commit, "REVERT_HEAD");
630
631 if (res) {
632 error(opts->action == REPLAY_REVERT
633 ? _("could not revert %s... %s")
634 : _("could not apply %s... %s"),
635 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
636 msg.subject);
ed727b19 637 print_advice(res == 1, opts);
043a4492 638 rerere(opts->allow_rerere_auto);
c8d1351d 639 goto leave;
043a4492
RR
640 }
641
c8d1351d 642 allow = allow_empty(opts, commit);
706728a3
FC
643 if (allow < 0) {
644 res = allow;
645 goto leave;
646 }
c8d1351d
FC
647 if (!opts->no_commit)
648 res = run_git_commit(defmsg, opts, allow);
649
650leave:
043a4492
RR
651 free_message(&msg);
652 free(defmsg);
653
654 return res;
655}
656
657static void prepare_revs(struct replay_opts *opts)
658{
a73e22e9
MZ
659 /*
660 * picking (but not reverting) ranges (but not individual revisions)
661 * should be done in reverse
662 */
663 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
043a4492
RR
664 opts->revs->reverse ^= 1;
665
666 if (prepare_revision_walk(opts->revs))
667 die(_("revision walk setup failed"));
668
669 if (!opts->revs->commits)
670 die(_("empty commit set passed"));
671}
672
673static void read_and_refresh_cache(struct replay_opts *opts)
674{
675 static struct lock_file index_lock;
676 int index_fd = hold_locked_index(&index_lock, 0);
677 if (read_index_preload(&the_index, NULL) < 0)
678 die(_("git %s: failed to read the index"), action_name(opts));
679 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
680 if (the_index.cache_changed) {
681 if (write_index(&the_index, index_fd) ||
682 commit_locked_index(&index_lock))
683 die(_("git %s: failed to refresh the index"), action_name(opts));
684 }
685 rollback_lock_file(&index_lock);
686}
687
043a4492
RR
688static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
689 struct replay_opts *opts)
690{
691 struct commit_list *cur = NULL;
692 const char *sha1_abbrev = NULL;
693 const char *action_str = opts->action == REPLAY_REVERT ? "revert" : "pick";
694 const char *subject;
695 int subject_len;
696
697 for (cur = todo_list; cur; cur = cur->next) {
698 sha1_abbrev = find_unique_abbrev(cur->item->object.sha1, DEFAULT_ABBREV);
699 subject_len = find_commit_subject(cur->item->buffer, &subject);
700 strbuf_addf(buf, "%s %s %.*s\n", action_str, sha1_abbrev,
701 subject_len, subject);
702 }
703 return 0;
704}
705
706static struct commit *parse_insn_line(char *bol, char *eol, struct replay_opts *opts)
707{
708 unsigned char commit_sha1[20];
709 enum replay_action action;
710 char *end_of_object_name;
711 int saved, status, padding;
712
713 if (!prefixcmp(bol, "pick")) {
714 action = REPLAY_PICK;
715 bol += strlen("pick");
716 } else if (!prefixcmp(bol, "revert")) {
717 action = REPLAY_REVERT;
718 bol += strlen("revert");
719 } else
720 return NULL;
721
722 /* Eat up extra spaces/ tabs before object name */
723 padding = strspn(bol, " \t");
724 if (!padding)
725 return NULL;
726 bol += padding;
727
728 end_of_object_name = bol + strcspn(bol, " \t\n");
729 saved = *end_of_object_name;
730 *end_of_object_name = '\0';
731 status = get_sha1(bol, commit_sha1);
732 *end_of_object_name = saved;
733
734 /*
735 * Verify that the action matches up with the one in
736 * opts; we don't support arbitrary instructions
737 */
738 if (action != opts->action) {
739 const char *action_str;
740 action_str = action == REPLAY_REVERT ? "revert" : "cherry-pick";
741 error(_("Cannot %s during a %s"), action_str, action_name(opts));
742 return NULL;
743 }
744
745 if (status < 0)
746 return NULL;
747
748 return lookup_commit_reference(commit_sha1);
749}
750
751static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
752 struct replay_opts *opts)
753{
754 struct commit_list **next = todo_list;
755 struct commit *commit;
756 char *p = buf;
757 int i;
758
759 for (i = 1; *p; i++) {
760 char *eol = strchrnul(p, '\n');
761 commit = parse_insn_line(p, eol, opts);
762 if (!commit)
763 return error(_("Could not parse line %d."), i);
764 next = commit_list_append(commit, next);
765 p = *eol ? eol + 1 : eol;
766 }
767 if (!*todo_list)
768 return error(_("No commits parsed."));
769 return 0;
770}
771
772static void read_populate_todo(struct commit_list **todo_list,
773 struct replay_opts *opts)
774{
775 const char *todo_file = git_path(SEQ_TODO_FILE);
776 struct strbuf buf = STRBUF_INIT;
777 int fd, res;
778
779 fd = open(todo_file, O_RDONLY);
780 if (fd < 0)
781 die_errno(_("Could not open %s"), todo_file);
782 if (strbuf_read(&buf, fd, 0) < 0) {
783 close(fd);
784 strbuf_release(&buf);
785 die(_("Could not read %s."), todo_file);
786 }
787 close(fd);
788
789 res = parse_insn_buffer(buf.buf, todo_list, opts);
790 strbuf_release(&buf);
791 if (res)
792 die(_("Unusable instruction sheet: %s"), todo_file);
793}
794
795static int populate_opts_cb(const char *key, const char *value, void *data)
796{
797 struct replay_opts *opts = data;
798 int error_flag = 1;
799
800 if (!value)
801 error_flag = 0;
802 else if (!strcmp(key, "options.no-commit"))
803 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
804 else if (!strcmp(key, "options.edit"))
805 opts->edit = git_config_bool_or_int(key, value, &error_flag);
806 else if (!strcmp(key, "options.signoff"))
807 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
808 else if (!strcmp(key, "options.record-origin"))
809 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
810 else if (!strcmp(key, "options.allow-ff"))
811 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
812 else if (!strcmp(key, "options.mainline"))
813 opts->mainline = git_config_int(key, value);
814 else if (!strcmp(key, "options.strategy"))
815 git_config_string(&opts->strategy, key, value);
816 else if (!strcmp(key, "options.strategy-option")) {
817 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
818 opts->xopts[opts->xopts_nr++] = xstrdup(value);
819 } else
820 return error(_("Invalid key: %s"), key);
821
822 if (!error_flag)
823 return error(_("Invalid value for %s: %s"), key, value);
824
825 return 0;
826}
827
828static void read_populate_opts(struct replay_opts **opts_ptr)
829{
830 const char *opts_file = git_path(SEQ_OPTS_FILE);
831
832 if (!file_exists(opts_file))
833 return;
834 if (git_config_from_file(populate_opts_cb, opts_file, *opts_ptr) < 0)
835 die(_("Malformed options sheet: %s"), opts_file);
836}
837
838static void walk_revs_populate_todo(struct commit_list **todo_list,
839 struct replay_opts *opts)
840{
841 struct commit *commit;
842 struct commit_list **next;
843
844 prepare_revs(opts);
845
846 next = todo_list;
847 while ((commit = get_revision(opts->revs)))
848 next = commit_list_append(commit, next);
849}
850
851static int create_seq_dir(void)
852{
853 const char *seq_dir = git_path(SEQ_DIR);
854
855 if (file_exists(seq_dir)) {
856 error(_("a cherry-pick or revert is already in progress"));
857 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
858 return -1;
859 }
860 else if (mkdir(seq_dir, 0777) < 0)
861 die_errno(_("Could not create sequencer directory %s"), seq_dir);
862 return 0;
863}
864
865static void save_head(const char *head)
866{
867 const char *head_file = git_path(SEQ_HEAD_FILE);
868 static struct lock_file head_lock;
869 struct strbuf buf = STRBUF_INIT;
870 int fd;
871
872 fd = hold_lock_file_for_update(&head_lock, head_file, LOCK_DIE_ON_ERROR);
873 strbuf_addf(&buf, "%s\n", head);
874 if (write_in_full(fd, buf.buf, buf.len) < 0)
875 die_errno(_("Could not write to %s"), head_file);
876 if (commit_lock_file(&head_lock) < 0)
877 die(_("Error wrapping up %s."), head_file);
878}
879
880static int reset_for_rollback(const unsigned char *sha1)
881{
882 const char *argv[4]; /* reset --merge <arg> + NULL */
883 argv[0] = "reset";
884 argv[1] = "--merge";
885 argv[2] = sha1_to_hex(sha1);
886 argv[3] = NULL;
887 return run_command_v_opt(argv, RUN_GIT_CMD);
888}
889
890static int rollback_single_pick(void)
891{
892 unsigned char head_sha1[20];
893
894 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
895 !file_exists(git_path("REVERT_HEAD")))
896 return error(_("no cherry-pick or revert in progress"));
897 if (read_ref_full("HEAD", head_sha1, 0, NULL))
898 return error(_("cannot resolve HEAD"));
899 if (is_null_sha1(head_sha1))
900 return error(_("cannot abort from a branch yet to be born"));
901 return reset_for_rollback(head_sha1);
902}
903
904static int sequencer_rollback(struct replay_opts *opts)
905{
906 const char *filename;
907 FILE *f;
908 unsigned char sha1[20];
909 struct strbuf buf = STRBUF_INIT;
910
911 filename = git_path(SEQ_HEAD_FILE);
912 f = fopen(filename, "r");
913 if (!f && errno == ENOENT) {
914 /*
915 * There is no multiple-cherry-pick in progress.
916 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
917 * a single-cherry-pick in progress, abort that.
918 */
919 return rollback_single_pick();
920 }
921 if (!f)
922 return error(_("cannot open %s: %s"), filename,
923 strerror(errno));
924 if (strbuf_getline(&buf, f, '\n')) {
925 error(_("cannot read %s: %s"), filename, ferror(f) ?
926 strerror(errno) : _("unexpected end of file"));
927 fclose(f);
928 goto fail;
929 }
930 fclose(f);
931 if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
932 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
933 filename);
934 goto fail;
935 }
936 if (reset_for_rollback(sha1))
937 goto fail;
938 remove_sequencer_state();
939 strbuf_release(&buf);
940 return 0;
941fail:
942 strbuf_release(&buf);
943 return -1;
944}
945
946static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
947{
948 const char *todo_file = git_path(SEQ_TODO_FILE);
949 static struct lock_file todo_lock;
950 struct strbuf buf = STRBUF_INIT;
951 int fd;
952
953 fd = hold_lock_file_for_update(&todo_lock, todo_file, LOCK_DIE_ON_ERROR);
954 if (format_todo(&buf, todo_list, opts) < 0)
955 die(_("Could not format %s."), todo_file);
956 if (write_in_full(fd, buf.buf, buf.len) < 0) {
957 strbuf_release(&buf);
958 die_errno(_("Could not write to %s"), todo_file);
959 }
960 if (commit_lock_file(&todo_lock) < 0) {
961 strbuf_release(&buf);
962 die(_("Error wrapping up %s."), todo_file);
963 }
964 strbuf_release(&buf);
965}
966
967static void save_opts(struct replay_opts *opts)
968{
969 const char *opts_file = git_path(SEQ_OPTS_FILE);
970
971 if (opts->no_commit)
972 git_config_set_in_file(opts_file, "options.no-commit", "true");
973 if (opts->edit)
974 git_config_set_in_file(opts_file, "options.edit", "true");
975 if (opts->signoff)
976 git_config_set_in_file(opts_file, "options.signoff", "true");
977 if (opts->record_origin)
978 git_config_set_in_file(opts_file, "options.record-origin", "true");
979 if (opts->allow_ff)
980 git_config_set_in_file(opts_file, "options.allow-ff", "true");
981 if (opts->mainline) {
982 struct strbuf buf = STRBUF_INIT;
983 strbuf_addf(&buf, "%d", opts->mainline);
984 git_config_set_in_file(opts_file, "options.mainline", buf.buf);
985 strbuf_release(&buf);
986 }
987 if (opts->strategy)
988 git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
989 if (opts->xopts) {
990 int i;
991 for (i = 0; i < opts->xopts_nr; i++)
992 git_config_set_multivar_in_file(opts_file,
993 "options.strategy-option",
994 opts->xopts[i], "^$", 0);
995 }
996}
997
998static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
999{
1000 struct commit_list *cur;
1001 int res;
1002
1003 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1004 if (opts->allow_ff)
1005 assert(!(opts->signoff || opts->no_commit ||
1006 opts->record_origin || opts->edit));
1007 read_and_refresh_cache(opts);
1008
1009 for (cur = todo_list; cur; cur = cur->next) {
1010 save_todo(cur, opts);
1011 res = do_pick_commit(cur->item, opts);
1012 if (res)
1013 return res;
1014 }
1015
1016 /*
1017 * Sequence of picks finished successfully; cleanup by
1018 * removing the .git/sequencer directory
1019 */
1020 remove_sequencer_state();
1021 return 0;
1022}
1023
1024static int continue_single_pick(void)
1025{
1026 const char *argv[] = { "commit", NULL };
1027
1028 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
1029 !file_exists(git_path("REVERT_HEAD")))
1030 return error(_("no cherry-pick or revert in progress"));
1031 return run_command_v_opt(argv, RUN_GIT_CMD);
1032}
1033
1034static int sequencer_continue(struct replay_opts *opts)
1035{
1036 struct commit_list *todo_list = NULL;
1037
1038 if (!file_exists(git_path(SEQ_TODO_FILE)))
1039 return continue_single_pick();
1040 read_populate_opts(&opts);
1041 read_populate_todo(&todo_list, opts);
1042
1043 /* Verify that the conflict has been resolved */
1044 if (file_exists(git_path("CHERRY_PICK_HEAD")) ||
1045 file_exists(git_path("REVERT_HEAD"))) {
1046 int ret = continue_single_pick();
1047 if (ret)
1048 return ret;
1049 }
1050 if (index_differs_from("HEAD", 0))
1051 return error_dirty_index(opts);
1052 todo_list = todo_list->next;
1053 return pick_commits(todo_list, opts);
1054}
1055
1056static int single_pick(struct commit *cmit, struct replay_opts *opts)
1057{
1058 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1059 return do_pick_commit(cmit, opts);
1060}
1061
1062int sequencer_pick_revisions(struct replay_opts *opts)
1063{
1064 struct commit_list *todo_list = NULL;
1065 unsigned char sha1[20];
21246dbb 1066 int i;
043a4492
RR
1067
1068 if (opts->subcommand == REPLAY_NONE)
1069 assert(opts->revs);
1070
1071 read_and_refresh_cache(opts);
1072
1073 /*
1074 * Decide what to do depending on the arguments; a fresh
1075 * cherry-pick should be handled differently from an existing
1076 * one that is being continued
1077 */
1078 if (opts->subcommand == REPLAY_REMOVE_STATE) {
1079 remove_sequencer_state();
1080 return 0;
1081 }
1082 if (opts->subcommand == REPLAY_ROLLBACK)
1083 return sequencer_rollback(opts);
1084 if (opts->subcommand == REPLAY_CONTINUE)
1085 return sequencer_continue(opts);
1086
21246dbb
MV
1087 for (i = 0; i < opts->revs->pending.nr; i++) {
1088 unsigned char sha1[20];
1089 const char *name = opts->revs->pending.objects[i].name;
1090
1091 /* This happens when using --stdin. */
1092 if (!strlen(name))
1093 continue;
1094
1095 if (!get_sha1(name, sha1)) {
7c0b0d8d
JH
1096 if (!lookup_commit_reference_gently(sha1, 1)) {
1097 enum object_type type = sha1_object_info(sha1, NULL);
21246dbb 1098 die(_("%s: can't cherry-pick a %s"), name, typename(type));
7c0b0d8d 1099 }
21246dbb
MV
1100 } else
1101 die(_("%s: bad revision"), name);
1102 }
1103
043a4492
RR
1104 /*
1105 * If we were called as "git cherry-pick <commit>", just
1106 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
1107 * REVERT_HEAD, and don't touch the sequencer state.
1108 * This means it is possible to cherry-pick in the middle
1109 * of a cherry-pick sequence.
1110 */
1111 if (opts->revs->cmdline.nr == 1 &&
1112 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
1113 opts->revs->no_walk &&
1114 !opts->revs->cmdline.rev->flags) {
1115 struct commit *cmit;
1116 if (prepare_revision_walk(opts->revs))
1117 die(_("revision walk setup failed"));
1118 cmit = get_revision(opts->revs);
1119 if (!cmit || get_revision(opts->revs))
1120 die("BUG: expected exactly one commit from walk");
1121 return single_pick(cmit, opts);
1122 }
1123
1124 /*
1125 * Start a new cherry-pick/ revert sequence; but
1126 * first, make sure that an existing one isn't in
1127 * progress
1128 */
1129
1130 walk_revs_populate_todo(&todo_list, opts);
1131 if (create_seq_dir() < 0)
1132 return -1;
1133 if (get_sha1("HEAD", sha1)) {
1134 if (opts->action == REPLAY_REVERT)
1135 return error(_("Can't revert as initial commit"));
1136 return error(_("Can't cherry-pick into empty head"));
1137 }
1138 save_head(sha1_to_hex(sha1));
1139 save_opts(opts);
1140 return pick_commits(todo_list, opts);
1141}
5ed75e2a 1142
bab4d109 1143void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
5ed75e2a 1144{
bab4d109 1145 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
5ed75e2a 1146 struct strbuf sob = STRBUF_INIT;
bab4d109 1147 int has_footer;
5ed75e2a
MV
1148
1149 strbuf_addstr(&sob, sign_off_header);
1150 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
1151 getenv("GIT_COMMITTER_EMAIL")));
1152 strbuf_addch(&sob, '\n');
bab4d109
BC
1153
1154 /*
1155 * If the whole message buffer is equal to the sob, pretend that we
1156 * found a conforming footer with a matching sob
1157 */
1158 if (msgbuf->len - ignore_footer == sob.len &&
1159 !strncmp(msgbuf->buf, sob.buf, sob.len))
1160 has_footer = 3;
1161 else
1162 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
1163
33f2f9ab
BC
1164 if (!has_footer) {
1165 const char *append_newlines = NULL;
1166 size_t len = msgbuf->len - ignore_footer;
1167
8c613fd5
BC
1168 if (!len) {
1169 /*
1170 * The buffer is completely empty. Leave foom for
1171 * the title and body to be filled in by the user.
1172 */
33f2f9ab 1173 append_newlines = "\n\n";
8c613fd5
BC
1174 } else if (msgbuf->buf[len - 1] != '\n') {
1175 /*
1176 * Incomplete line. Complete the line and add a
1177 * blank one so that there is an empty line between
1178 * the message body and the sob.
1179 */
1180 append_newlines = "\n\n";
1181 } else if (len == 1) {
1182 /*
1183 * Buffer contains a single newline. Add another
1184 * so that we leave room for the title and body.
1185 */
1186 append_newlines = "\n";
1187 } else if (msgbuf->buf[len - 2] != '\n') {
1188 /*
1189 * Buffer ends with a single newline. Add another
1190 * so that there is an empty line between the message
1191 * body and the sob.
1192 */
33f2f9ab 1193 append_newlines = "\n";
8c613fd5 1194 } /* else, the buffer already ends with two newlines. */
33f2f9ab
BC
1195
1196 if (append_newlines)
1197 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1198 append_newlines, strlen(append_newlines));
5ed75e2a 1199 }
bab4d109
BC
1200
1201 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
1202 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1203 sob.buf, sob.len);
1204
5ed75e2a
MV
1205 strbuf_release(&sob);
1206}