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