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