Merge branch 'nd/i18n-parseopt-help'
[git/mjg.git] / sequencer.c
blob1ea5293f6ed5395b95fbf63fc41aa28c33db0fa8
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 #include "argv-array.h"
18 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
20 void remove_sequencer_state(void)
22 struct strbuf seq_dir = STRBUF_INIT;
24 strbuf_addf(&seq_dir, "%s", git_path(SEQ_DIR));
25 remove_dir_recursively(&seq_dir, 0);
26 strbuf_release(&seq_dir);
29 static const char *action_name(const struct replay_opts *opts)
31 return opts->action == REPLAY_REVERT ? "revert" : "cherry-pick";
34 static char *get_encoding(const char *message);
36 struct commit_message {
37 char *parent_label;
38 const char *label;
39 const char *subject;
40 char *reencoded_message;
41 const char *message;
44 static int get_message(struct commit *commit, struct commit_message *out)
46 const char *encoding;
47 const char *abbrev, *subject;
48 int abbrev_len, subject_len;
49 char *q;
51 if (!commit->buffer)
52 return -1;
53 encoding = get_encoding(commit->buffer);
54 if (!encoding)
55 encoding = "UTF-8";
56 if (!git_commit_encoding)
57 git_commit_encoding = "UTF-8";
59 out->reencoded_message = NULL;
60 out->message = commit->buffer;
61 if (strcmp(encoding, git_commit_encoding))
62 out->reencoded_message = reencode_string(commit->buffer,
63 git_commit_encoding, encoding);
64 if (out->reencoded_message)
65 out->message = out->reencoded_message;
67 abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
68 abbrev_len = strlen(abbrev);
70 subject_len = find_commit_subject(out->message, &subject);
72 out->parent_label = xmalloc(strlen("parent of ") + abbrev_len +
73 strlen("... ") + subject_len + 1);
74 q = out->parent_label;
75 q = mempcpy(q, "parent of ", strlen("parent of "));
76 out->label = q;
77 q = mempcpy(q, abbrev, abbrev_len);
78 q = mempcpy(q, "... ", strlen("... "));
79 out->subject = q;
80 q = mempcpy(q, subject, subject_len);
81 *q = '\0';
82 return 0;
85 static void free_message(struct commit_message *msg)
87 free(msg->parent_label);
88 free(msg->reencoded_message);
91 static char *get_encoding(const char *message)
93 const char *p = message, *eol;
95 while (*p && *p != '\n') {
96 for (eol = p + 1; *eol && *eol != '\n'; eol++)
97 ; /* do nothing */
98 if (!prefixcmp(p, "encoding ")) {
99 char *result = xmalloc(eol - 8 - p);
100 strlcpy(result, p + 9, eol - 8 - p);
101 return result;
103 p = eol;
104 if (*p == '\n')
105 p++;
107 return NULL;
110 static void write_cherry_pick_head(struct commit *commit, const char *pseudoref)
112 const char *filename;
113 int fd;
114 struct strbuf buf = STRBUF_INIT;
116 strbuf_addf(&buf, "%s\n", sha1_to_hex(commit->object.sha1));
118 filename = git_path("%s", pseudoref);
119 fd = open(filename, O_WRONLY | O_CREAT, 0666);
120 if (fd < 0)
121 die_errno(_("Could not open '%s' for writing"), filename);
122 if (write_in_full(fd, buf.buf, buf.len) != buf.len || close(fd))
123 die_errno(_("Could not write to '%s'"), filename);
124 strbuf_release(&buf);
127 static void print_advice(int show_hint, struct replay_opts *opts)
129 char *msg = getenv("GIT_CHERRY_PICK_HELP");
131 if (msg) {
132 fprintf(stderr, "%s\n", msg);
134 * A conflict has occured but the porcelain
135 * (typically rebase --interactive) wants to take care
136 * of the commit itself so remove CHERRY_PICK_HEAD
138 unlink(git_path("CHERRY_PICK_HEAD"));
139 return;
142 if (show_hint) {
143 if (opts->no_commit)
144 advise(_("after resolving the conflicts, mark the corrected paths\n"
145 "with 'git add <paths>' or 'git rm <paths>'"));
146 else
147 advise(_("after resolving the conflicts, mark the corrected paths\n"
148 "with 'git add <paths>' or 'git rm <paths>'\n"
149 "and commit the result with 'git commit'"));
153 static void write_message(struct strbuf *msgbuf, const char *filename)
155 static struct lock_file msg_file;
157 int msg_fd = hold_lock_file_for_update(&msg_file, filename,
158 LOCK_DIE_ON_ERROR);
159 if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
160 die_errno(_("Could not write to %s"), filename);
161 strbuf_release(msgbuf);
162 if (commit_lock_file(&msg_file) < 0)
163 die(_("Error wrapping up %s"), filename);
166 static struct tree *empty_tree(void)
168 return lookup_tree(EMPTY_TREE_SHA1_BIN);
171 static int error_dirty_index(struct replay_opts *opts)
173 if (read_cache_unmerged())
174 return error_resolve_conflict(action_name(opts));
176 /* Different translation strings for cherry-pick and revert */
177 if (opts->action == REPLAY_PICK)
178 error(_("Your local changes would be overwritten by cherry-pick."));
179 else
180 error(_("Your local changes would be overwritten by revert."));
182 if (advice_commit_before_merge)
183 advise(_("Commit your changes or stash them to proceed."));
184 return -1;
187 static int fast_forward_to(const unsigned char *to, const unsigned char *from)
189 struct ref_lock *ref_lock;
191 read_cache();
192 if (checkout_fast_forward(from, to))
193 exit(1); /* the callee should have complained already */
194 ref_lock = lock_any_ref_for_update("HEAD", from, 0);
195 return write_ref_sha1(ref_lock, to, "cherry-pick");
198 static int do_recursive_merge(struct commit *base, struct commit *next,
199 const char *base_label, const char *next_label,
200 unsigned char *head, struct strbuf *msgbuf,
201 struct replay_opts *opts)
203 struct merge_options o;
204 struct tree *result, *next_tree, *base_tree, *head_tree;
205 int clean, index_fd;
206 const char **xopt;
207 static struct lock_file index_lock;
209 index_fd = hold_locked_index(&index_lock, 1);
211 read_cache();
213 init_merge_options(&o);
214 o.ancestor = base ? base_label : "(empty tree)";
215 o.branch1 = "HEAD";
216 o.branch2 = next ? next_label : "(empty tree)";
218 head_tree = parse_tree_indirect(head);
219 next_tree = next ? next->tree : empty_tree();
220 base_tree = base ? base->tree : empty_tree();
222 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
223 parse_merge_opt(&o, *xopt);
225 clean = merge_trees(&o,
226 head_tree,
227 next_tree, base_tree, &result);
229 if (active_cache_changed &&
230 (write_cache(index_fd, active_cache, active_nr) ||
231 commit_locked_index(&index_lock)))
232 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
233 die(_("%s: Unable to write new index file"), action_name(opts));
234 rollback_lock_file(&index_lock);
236 if (!clean) {
237 int i;
238 strbuf_addstr(msgbuf, "\nConflicts:\n");
239 for (i = 0; i < active_nr;) {
240 struct cache_entry *ce = active_cache[i++];
241 if (ce_stage(ce)) {
242 strbuf_addch(msgbuf, '\t');
243 strbuf_addstr(msgbuf, ce->name);
244 strbuf_addch(msgbuf, '\n');
245 while (i < active_nr && !strcmp(ce->name,
246 active_cache[i]->name))
247 i++;
252 return !clean;
255 static int is_index_unchanged(void)
257 unsigned char head_sha1[20];
258 struct commit *head_commit;
260 if (!resolve_ref_unsafe("HEAD", head_sha1, 1, NULL))
261 return error(_("Could not resolve HEAD commit\n"));
263 head_commit = lookup_commit(head_sha1);
266 * If head_commit is NULL, check_commit, called from
267 * lookup_commit, would have indicated that head_commit is not
268 * a commit object already. parse_commit() will return failure
269 * without further complaints in such a case. Otherwise, if
270 * the commit is invalid, parse_commit() will complain. So
271 * there is nothing for us to say here. Just return failure.
273 if (parse_commit(head_commit))
274 return -1;
276 if (!active_cache_tree)
277 active_cache_tree = cache_tree();
279 if (!cache_tree_fully_valid(active_cache_tree))
280 if (cache_tree_update(active_cache_tree, active_cache,
281 active_nr, 0))
282 return error(_("Unable to update cache tree\n"));
284 return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.sha1);
288 * If we are cherry-pick, and if the merge did not result in
289 * hand-editing, we will hit this commit and inherit the original
290 * author date and name.
291 * If we are revert, or if our cherry-pick results in a hand merge,
292 * we had better say that the current user is responsible for that.
294 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
295 int allow_empty)
297 struct argv_array array;
298 int rc;
300 argv_array_init(&array);
301 argv_array_push(&array, "commit");
302 argv_array_push(&array, "-n");
304 if (opts->signoff)
305 argv_array_push(&array, "-s");
306 if (!opts->edit) {
307 argv_array_push(&array, "-F");
308 argv_array_push(&array, defmsg);
311 if (allow_empty)
312 argv_array_push(&array, "--allow-empty");
314 if (opts->allow_empty_message)
315 argv_array_push(&array, "--allow-empty-message");
317 rc = run_command_v_opt(array.argv, RUN_GIT_CMD);
318 argv_array_clear(&array);
319 return rc;
322 static int is_original_commit_empty(struct commit *commit)
324 const unsigned char *ptree_sha1;
326 if (parse_commit(commit))
327 return error(_("Could not parse commit %s\n"),
328 sha1_to_hex(commit->object.sha1));
329 if (commit->parents) {
330 struct commit *parent = commit->parents->item;
331 if (parse_commit(parent))
332 return error(_("Could not parse parent commit %s\n"),
333 sha1_to_hex(parent->object.sha1));
334 ptree_sha1 = parent->tree->object.sha1;
335 } else {
336 ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
339 return !hashcmp(ptree_sha1, commit->tree->object.sha1);
343 * Do we run "git commit" with "--allow-empty"?
345 static int allow_empty(struct replay_opts *opts, struct commit *commit)
347 int index_unchanged, empty_commit;
350 * Three cases:
352 * (1) we do not allow empty at all and error out.
354 * (2) we allow ones that were initially empty, but
355 * forbid the ones that become empty;
357 * (3) we allow both.
359 if (!opts->allow_empty)
360 return 0; /* let "git commit" barf as necessary */
362 index_unchanged = is_index_unchanged();
363 if (index_unchanged < 0)
364 return index_unchanged;
365 if (!index_unchanged)
366 return 0; /* we do not have to say --allow-empty */
368 if (opts->keep_redundant_commits)
369 return 1;
371 empty_commit = is_original_commit_empty(commit);
372 if (empty_commit < 0)
373 return empty_commit;
374 if (!empty_commit)
375 return 0;
376 else
377 return 1;
380 static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
382 unsigned char head[20];
383 struct commit *base, *next, *parent;
384 const char *base_label, *next_label;
385 struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
386 char *defmsg = NULL;
387 struct strbuf msgbuf = STRBUF_INIT;
388 int res;
390 if (opts->no_commit) {
392 * We do not intend to commit immediately. We just want to
393 * merge the differences in, so let's compute the tree
394 * that represents the "current" state for merge-recursive
395 * to work on.
397 if (write_cache_as_tree(head, 0, NULL))
398 die (_("Your index file is unmerged."));
399 } else {
400 if (get_sha1("HEAD", head))
401 return error(_("You do not have a valid HEAD"));
402 if (index_differs_from("HEAD", 0))
403 return error_dirty_index(opts);
405 discard_cache();
407 if (!commit->parents) {
408 parent = NULL;
410 else if (commit->parents->next) {
411 /* Reverting or cherry-picking a merge commit */
412 int cnt;
413 struct commit_list *p;
415 if (!opts->mainline)
416 return error(_("Commit %s is a merge but no -m option was given."),
417 sha1_to_hex(commit->object.sha1));
419 for (cnt = 1, p = commit->parents;
420 cnt != opts->mainline && p;
421 cnt++)
422 p = p->next;
423 if (cnt != opts->mainline || !p)
424 return error(_("Commit %s does not have parent %d"),
425 sha1_to_hex(commit->object.sha1), opts->mainline);
426 parent = p->item;
427 } else if (0 < opts->mainline)
428 return error(_("Mainline was specified but commit %s is not a merge."),
429 sha1_to_hex(commit->object.sha1));
430 else
431 parent = commit->parents->item;
433 if (opts->allow_ff && parent && !hashcmp(parent->object.sha1, head))
434 return fast_forward_to(commit->object.sha1, head);
436 if (parent && parse_commit(parent) < 0)
437 /* TRANSLATORS: The first %s will be "revert" or
438 "cherry-pick", the second %s a SHA1 */
439 return error(_("%s: cannot parse parent commit %s"),
440 action_name(opts), sha1_to_hex(parent->object.sha1));
442 if (get_message(commit, &msg) != 0)
443 return error(_("Cannot get commit message for %s"),
444 sha1_to_hex(commit->object.sha1));
447 * "commit" is an existing commit. We would want to apply
448 * the difference it introduces since its first parent "prev"
449 * on top of the current HEAD if we are cherry-pick. Or the
450 * reverse of it if we are revert.
453 defmsg = git_pathdup("MERGE_MSG");
455 if (opts->action == REPLAY_REVERT) {
456 base = commit;
457 base_label = msg.label;
458 next = parent;
459 next_label = msg.parent_label;
460 strbuf_addstr(&msgbuf, "Revert \"");
461 strbuf_addstr(&msgbuf, msg.subject);
462 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
463 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
465 if (commit->parents && commit->parents->next) {
466 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
467 strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
469 strbuf_addstr(&msgbuf, ".\n");
470 } else {
471 const char *p;
473 base = parent;
474 base_label = msg.parent_label;
475 next = commit;
476 next_label = msg.label;
479 * Append the commit log message to msgbuf; it starts
480 * after the tree, parent, author, committer
481 * information followed by "\n\n".
483 p = strstr(msg.message, "\n\n");
484 if (p) {
485 p += 2;
486 strbuf_addstr(&msgbuf, p);
489 if (opts->record_origin) {
490 strbuf_addstr(&msgbuf, "(cherry picked from commit ");
491 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
492 strbuf_addstr(&msgbuf, ")\n");
496 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REPLAY_REVERT) {
497 res = do_recursive_merge(base, next, base_label, next_label,
498 head, &msgbuf, opts);
499 write_message(&msgbuf, defmsg);
500 } else {
501 struct commit_list *common = NULL;
502 struct commit_list *remotes = NULL;
504 write_message(&msgbuf, defmsg);
506 commit_list_insert(base, &common);
507 commit_list_insert(next, &remotes);
508 res = try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
509 common, sha1_to_hex(head), remotes);
510 free_commit_list(common);
511 free_commit_list(remotes);
515 * If the merge was clean or if it failed due to conflict, we write
516 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
517 * However, if the merge did not even start, then we don't want to
518 * write it at all.
520 if (opts->action == REPLAY_PICK && !opts->no_commit && (res == 0 || res == 1))
521 write_cherry_pick_head(commit, "CHERRY_PICK_HEAD");
522 if (opts->action == REPLAY_REVERT && ((opts->no_commit && res == 0) || res == 1))
523 write_cherry_pick_head(commit, "REVERT_HEAD");
525 if (res) {
526 error(opts->action == REPLAY_REVERT
527 ? _("could not revert %s... %s")
528 : _("could not apply %s... %s"),
529 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
530 msg.subject);
531 print_advice(res == 1, opts);
532 rerere(opts->allow_rerere_auto);
533 } else {
534 int allow = allow_empty(opts, commit);
535 if (allow < 0)
536 return allow;
537 if (!opts->no_commit)
538 res = run_git_commit(defmsg, opts, allow);
541 free_message(&msg);
542 free(defmsg);
544 return res;
547 static void prepare_revs(struct replay_opts *opts)
549 if (opts->action != REPLAY_REVERT)
550 opts->revs->reverse ^= 1;
552 if (prepare_revision_walk(opts->revs))
553 die(_("revision walk setup failed"));
555 if (!opts->revs->commits)
556 die(_("empty commit set passed"));
559 static void read_and_refresh_cache(struct replay_opts *opts)
561 static struct lock_file index_lock;
562 int index_fd = hold_locked_index(&index_lock, 0);
563 if (read_index_preload(&the_index, NULL) < 0)
564 die(_("git %s: failed to read the index"), action_name(opts));
565 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
566 if (the_index.cache_changed) {
567 if (write_index(&the_index, index_fd) ||
568 commit_locked_index(&index_lock))
569 die(_("git %s: failed to refresh the index"), action_name(opts));
571 rollback_lock_file(&index_lock);
574 static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
575 struct replay_opts *opts)
577 struct commit_list *cur = NULL;
578 const char *sha1_abbrev = NULL;
579 const char *action_str = opts->action == REPLAY_REVERT ? "revert" : "pick";
580 const char *subject;
581 int subject_len;
583 for (cur = todo_list; cur; cur = cur->next) {
584 sha1_abbrev = find_unique_abbrev(cur->item->object.sha1, DEFAULT_ABBREV);
585 subject_len = find_commit_subject(cur->item->buffer, &subject);
586 strbuf_addf(buf, "%s %s %.*s\n", action_str, sha1_abbrev,
587 subject_len, subject);
589 return 0;
592 static struct commit *parse_insn_line(char *bol, char *eol, struct replay_opts *opts)
594 unsigned char commit_sha1[20];
595 enum replay_action action;
596 char *end_of_object_name;
597 int saved, status, padding;
599 if (!prefixcmp(bol, "pick")) {
600 action = REPLAY_PICK;
601 bol += strlen("pick");
602 } else if (!prefixcmp(bol, "revert")) {
603 action = REPLAY_REVERT;
604 bol += strlen("revert");
605 } else
606 return NULL;
608 /* Eat up extra spaces/ tabs before object name */
609 padding = strspn(bol, " \t");
610 if (!padding)
611 return NULL;
612 bol += padding;
614 end_of_object_name = bol + strcspn(bol, " \t\n");
615 saved = *end_of_object_name;
616 *end_of_object_name = '\0';
617 status = get_sha1(bol, commit_sha1);
618 *end_of_object_name = saved;
621 * Verify that the action matches up with the one in
622 * opts; we don't support arbitrary instructions
624 if (action != opts->action) {
625 const char *action_str;
626 action_str = action == REPLAY_REVERT ? "revert" : "cherry-pick";
627 error(_("Cannot %s during a %s"), action_str, action_name(opts));
628 return NULL;
631 if (status < 0)
632 return NULL;
634 return lookup_commit_reference(commit_sha1);
637 static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
638 struct replay_opts *opts)
640 struct commit_list **next = todo_list;
641 struct commit *commit;
642 char *p = buf;
643 int i;
645 for (i = 1; *p; i++) {
646 char *eol = strchrnul(p, '\n');
647 commit = parse_insn_line(p, eol, opts);
648 if (!commit)
649 return error(_("Could not parse line %d."), i);
650 next = commit_list_append(commit, next);
651 p = *eol ? eol + 1 : eol;
653 if (!*todo_list)
654 return error(_("No commits parsed."));
655 return 0;
658 static void read_populate_todo(struct commit_list **todo_list,
659 struct replay_opts *opts)
661 const char *todo_file = git_path(SEQ_TODO_FILE);
662 struct strbuf buf = STRBUF_INIT;
663 int fd, res;
665 fd = open(todo_file, O_RDONLY);
666 if (fd < 0)
667 die_errno(_("Could not open %s"), todo_file);
668 if (strbuf_read(&buf, fd, 0) < 0) {
669 close(fd);
670 strbuf_release(&buf);
671 die(_("Could not read %s."), todo_file);
673 close(fd);
675 res = parse_insn_buffer(buf.buf, todo_list, opts);
676 strbuf_release(&buf);
677 if (res)
678 die(_("Unusable instruction sheet: %s"), todo_file);
681 static int populate_opts_cb(const char *key, const char *value, void *data)
683 struct replay_opts *opts = data;
684 int error_flag = 1;
686 if (!value)
687 error_flag = 0;
688 else if (!strcmp(key, "options.no-commit"))
689 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
690 else if (!strcmp(key, "options.edit"))
691 opts->edit = git_config_bool_or_int(key, value, &error_flag);
692 else if (!strcmp(key, "options.signoff"))
693 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
694 else if (!strcmp(key, "options.record-origin"))
695 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
696 else if (!strcmp(key, "options.allow-ff"))
697 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
698 else if (!strcmp(key, "options.mainline"))
699 opts->mainline = git_config_int(key, value);
700 else if (!strcmp(key, "options.strategy"))
701 git_config_string(&opts->strategy, key, value);
702 else if (!strcmp(key, "options.strategy-option")) {
703 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
704 opts->xopts[opts->xopts_nr++] = xstrdup(value);
705 } else
706 return error(_("Invalid key: %s"), key);
708 if (!error_flag)
709 return error(_("Invalid value for %s: %s"), key, value);
711 return 0;
714 static void read_populate_opts(struct replay_opts **opts_ptr)
716 const char *opts_file = git_path(SEQ_OPTS_FILE);
718 if (!file_exists(opts_file))
719 return;
720 if (git_config_from_file(populate_opts_cb, opts_file, *opts_ptr) < 0)
721 die(_("Malformed options sheet: %s"), opts_file);
724 static void walk_revs_populate_todo(struct commit_list **todo_list,
725 struct replay_opts *opts)
727 struct commit *commit;
728 struct commit_list **next;
730 prepare_revs(opts);
732 next = todo_list;
733 while ((commit = get_revision(opts->revs)))
734 next = commit_list_append(commit, next);
737 static int create_seq_dir(void)
739 const char *seq_dir = git_path(SEQ_DIR);
741 if (file_exists(seq_dir)) {
742 error(_("a cherry-pick or revert is already in progress"));
743 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
744 return -1;
746 else if (mkdir(seq_dir, 0777) < 0)
747 die_errno(_("Could not create sequencer directory %s"), seq_dir);
748 return 0;
751 static void save_head(const char *head)
753 const char *head_file = git_path(SEQ_HEAD_FILE);
754 static struct lock_file head_lock;
755 struct strbuf buf = STRBUF_INIT;
756 int fd;
758 fd = hold_lock_file_for_update(&head_lock, head_file, LOCK_DIE_ON_ERROR);
759 strbuf_addf(&buf, "%s\n", head);
760 if (write_in_full(fd, buf.buf, buf.len) < 0)
761 die_errno(_("Could not write to %s"), head_file);
762 if (commit_lock_file(&head_lock) < 0)
763 die(_("Error wrapping up %s."), head_file);
766 static int reset_for_rollback(const unsigned char *sha1)
768 const char *argv[4]; /* reset --merge <arg> + NULL */
769 argv[0] = "reset";
770 argv[1] = "--merge";
771 argv[2] = sha1_to_hex(sha1);
772 argv[3] = NULL;
773 return run_command_v_opt(argv, RUN_GIT_CMD);
776 static int rollback_single_pick(void)
778 unsigned char head_sha1[20];
780 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
781 !file_exists(git_path("REVERT_HEAD")))
782 return error(_("no cherry-pick or revert in progress"));
783 if (read_ref_full("HEAD", head_sha1, 0, NULL))
784 return error(_("cannot resolve HEAD"));
785 if (is_null_sha1(head_sha1))
786 return error(_("cannot abort from a branch yet to be born"));
787 return reset_for_rollback(head_sha1);
790 static int sequencer_rollback(struct replay_opts *opts)
792 const char *filename;
793 FILE *f;
794 unsigned char sha1[20];
795 struct strbuf buf = STRBUF_INIT;
797 filename = git_path(SEQ_HEAD_FILE);
798 f = fopen(filename, "r");
799 if (!f && errno == ENOENT) {
801 * There is no multiple-cherry-pick in progress.
802 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
803 * a single-cherry-pick in progress, abort that.
805 return rollback_single_pick();
807 if (!f)
808 return error(_("cannot open %s: %s"), filename,
809 strerror(errno));
810 if (strbuf_getline(&buf, f, '\n')) {
811 error(_("cannot read %s: %s"), filename, ferror(f) ?
812 strerror(errno) : _("unexpected end of file"));
813 fclose(f);
814 goto fail;
816 fclose(f);
817 if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
818 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
819 filename);
820 goto fail;
822 if (reset_for_rollback(sha1))
823 goto fail;
824 remove_sequencer_state();
825 strbuf_release(&buf);
826 return 0;
827 fail:
828 strbuf_release(&buf);
829 return -1;
832 static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
834 const char *todo_file = git_path(SEQ_TODO_FILE);
835 static struct lock_file todo_lock;
836 struct strbuf buf = STRBUF_INIT;
837 int fd;
839 fd = hold_lock_file_for_update(&todo_lock, todo_file, LOCK_DIE_ON_ERROR);
840 if (format_todo(&buf, todo_list, opts) < 0)
841 die(_("Could not format %s."), todo_file);
842 if (write_in_full(fd, buf.buf, buf.len) < 0) {
843 strbuf_release(&buf);
844 die_errno(_("Could not write to %s"), todo_file);
846 if (commit_lock_file(&todo_lock) < 0) {
847 strbuf_release(&buf);
848 die(_("Error wrapping up %s."), todo_file);
850 strbuf_release(&buf);
853 static void save_opts(struct replay_opts *opts)
855 const char *opts_file = git_path(SEQ_OPTS_FILE);
857 if (opts->no_commit)
858 git_config_set_in_file(opts_file, "options.no-commit", "true");
859 if (opts->edit)
860 git_config_set_in_file(opts_file, "options.edit", "true");
861 if (opts->signoff)
862 git_config_set_in_file(opts_file, "options.signoff", "true");
863 if (opts->record_origin)
864 git_config_set_in_file(opts_file, "options.record-origin", "true");
865 if (opts->allow_ff)
866 git_config_set_in_file(opts_file, "options.allow-ff", "true");
867 if (opts->mainline) {
868 struct strbuf buf = STRBUF_INIT;
869 strbuf_addf(&buf, "%d", opts->mainline);
870 git_config_set_in_file(opts_file, "options.mainline", buf.buf);
871 strbuf_release(&buf);
873 if (opts->strategy)
874 git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
875 if (opts->xopts) {
876 int i;
877 for (i = 0; i < opts->xopts_nr; i++)
878 git_config_set_multivar_in_file(opts_file,
879 "options.strategy-option",
880 opts->xopts[i], "^$", 0);
884 static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
886 struct commit_list *cur;
887 int res;
889 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
890 if (opts->allow_ff)
891 assert(!(opts->signoff || opts->no_commit ||
892 opts->record_origin || opts->edit));
893 read_and_refresh_cache(opts);
895 for (cur = todo_list; cur; cur = cur->next) {
896 save_todo(cur, opts);
897 res = do_pick_commit(cur->item, opts);
898 if (res)
899 return res;
903 * Sequence of picks finished successfully; cleanup by
904 * removing the .git/sequencer directory
906 remove_sequencer_state();
907 return 0;
910 static int continue_single_pick(void)
912 const char *argv[] = { "commit", NULL };
914 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
915 !file_exists(git_path("REVERT_HEAD")))
916 return error(_("no cherry-pick or revert in progress"));
917 return run_command_v_opt(argv, RUN_GIT_CMD);
920 static int sequencer_continue(struct replay_opts *opts)
922 struct commit_list *todo_list = NULL;
924 if (!file_exists(git_path(SEQ_TODO_FILE)))
925 return continue_single_pick();
926 read_populate_opts(&opts);
927 read_populate_todo(&todo_list, opts);
929 /* Verify that the conflict has been resolved */
930 if (file_exists(git_path("CHERRY_PICK_HEAD")) ||
931 file_exists(git_path("REVERT_HEAD"))) {
932 int ret = continue_single_pick();
933 if (ret)
934 return ret;
936 if (index_differs_from("HEAD", 0))
937 return error_dirty_index(opts);
938 todo_list = todo_list->next;
939 return pick_commits(todo_list, opts);
942 static int single_pick(struct commit *cmit, struct replay_opts *opts)
944 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
945 return do_pick_commit(cmit, opts);
948 int sequencer_pick_revisions(struct replay_opts *opts)
950 struct commit_list *todo_list = NULL;
951 unsigned char sha1[20];
953 if (opts->subcommand == REPLAY_NONE)
954 assert(opts->revs);
956 read_and_refresh_cache(opts);
959 * Decide what to do depending on the arguments; a fresh
960 * cherry-pick should be handled differently from an existing
961 * one that is being continued
963 if (opts->subcommand == REPLAY_REMOVE_STATE) {
964 remove_sequencer_state();
965 return 0;
967 if (opts->subcommand == REPLAY_ROLLBACK)
968 return sequencer_rollback(opts);
969 if (opts->subcommand == REPLAY_CONTINUE)
970 return sequencer_continue(opts);
973 * If we were called as "git cherry-pick <commit>", just
974 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
975 * REVERT_HEAD, and don't touch the sequencer state.
976 * This means it is possible to cherry-pick in the middle
977 * of a cherry-pick sequence.
979 if (opts->revs->cmdline.nr == 1 &&
980 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
981 opts->revs->no_walk &&
982 !opts->revs->cmdline.rev->flags) {
983 struct commit *cmit;
984 if (prepare_revision_walk(opts->revs))
985 die(_("revision walk setup failed"));
986 cmit = get_revision(opts->revs);
987 if (!cmit || get_revision(opts->revs))
988 die("BUG: expected exactly one commit from walk");
989 return single_pick(cmit, opts);
993 * Start a new cherry-pick/ revert sequence; but
994 * first, make sure that an existing one isn't in
995 * progress
998 walk_revs_populate_todo(&todo_list, opts);
999 if (create_seq_dir() < 0)
1000 return -1;
1001 if (get_sha1("HEAD", sha1)) {
1002 if (opts->action == REPLAY_REVERT)
1003 return error(_("Can't revert as initial commit"));
1004 return error(_("Can't cherry-pick into empty head"));
1006 save_head(sha1_to_hex(sha1));
1007 save_opts(opts);
1008 return pick_commits(todo_list, opts);