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