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