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