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