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