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