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