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