MSVC: require pton and ntop emulation
[git/dscho.git] / sequencer.c
blobf83cdfd63764b6c20432b2226648f4fd9eda62fe
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);
264 if (!head_commit || parse_commit(head_commit))
265 return error(_("could not parse commit %s\n"),
266 sha1_to_hex(head_commit->object.sha1));
268 if (!active_cache_tree)
269 active_cache_tree = cache_tree();
271 if (!cache_tree_fully_valid(active_cache_tree))
272 if (cache_tree_update(active_cache_tree, active_cache,
273 active_nr, 0))
274 return error(_("Unable to update cache tree\n"));
276 return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.sha1);
280 * If we are cherry-pick, and if the merge did not result in
281 * hand-editing, we will hit this commit and inherit the original
282 * author date and name.
283 * If we are revert, or if our cherry-pick results in a hand merge,
284 * we had better say that the current user is responsible for that.
286 static int run_git_commit(const char *defmsg, struct replay_opts *opts)
288 struct argv_array array;
289 int rc;
291 argv_array_init(&array);
292 argv_array_push(&array, "commit");
293 argv_array_push(&array, "-n");
295 if (opts->signoff)
296 argv_array_push(&array, "-s");
297 if (!opts->edit) {
298 argv_array_push(&array, "-F");
299 argv_array_push(&array, defmsg);
302 if (opts->allow_empty)
303 argv_array_push(&array, "--allow-empty");
305 rc = run_command_v_opt(array.argv, RUN_GIT_CMD);
306 argv_array_clear(&array);
307 return rc;
310 static int is_original_commit_empty(struct commit *commit)
312 const unsigned char *ptree_sha1;
314 if (parse_commit(commit))
315 return error(_("Could not parse commit %s\n"),
316 sha1_to_hex(commit->object.sha1));
317 if (commit->parents) {
318 struct commit *parent = commit->parents->item;
319 if (parse_commit(parent))
320 return error(_("Could not parse parent commit %s\n"),
321 sha1_to_hex(parent->object.sha1));
322 ptree_sha1 = parent->tree->object.sha1;
323 } else {
324 ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
327 return !hashcmp(ptree_sha1, commit->tree->object.sha1);
330 static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
332 unsigned char head[20];
333 struct commit *base, *next, *parent;
334 const char *base_label, *next_label;
335 struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
336 char *defmsg = NULL;
337 struct strbuf msgbuf = STRBUF_INIT;
338 int res;
339 int empty_commit;
340 int index_unchanged;
342 if (opts->no_commit) {
344 * We do not intend to commit immediately. We just want to
345 * merge the differences in, so let's compute the tree
346 * that represents the "current" state for merge-recursive
347 * to work on.
349 if (write_cache_as_tree(head, 0, NULL))
350 die (_("Your index file is unmerged."));
351 } else {
352 if (get_sha1("HEAD", head))
353 return error(_("You do not have a valid HEAD"));
354 if (index_differs_from("HEAD", 0))
355 return error_dirty_index(opts);
357 discard_cache();
359 if (!commit->parents) {
360 parent = NULL;
362 else if (commit->parents->next) {
363 /* Reverting or cherry-picking a merge commit */
364 int cnt;
365 struct commit_list *p;
367 if (!opts->mainline)
368 return error(_("Commit %s is a merge but no -m option was given."),
369 sha1_to_hex(commit->object.sha1));
371 for (cnt = 1, p = commit->parents;
372 cnt != opts->mainline && p;
373 cnt++)
374 p = p->next;
375 if (cnt != opts->mainline || !p)
376 return error(_("Commit %s does not have parent %d"),
377 sha1_to_hex(commit->object.sha1), opts->mainline);
378 parent = p->item;
379 } else if (0 < opts->mainline)
380 return error(_("Mainline was specified but commit %s is not a merge."),
381 sha1_to_hex(commit->object.sha1));
382 else
383 parent = commit->parents->item;
385 if (opts->allow_ff && parent && !hashcmp(parent->object.sha1, head))
386 return fast_forward_to(commit->object.sha1, head);
388 if (parent && parse_commit(parent) < 0)
389 /* TRANSLATORS: The first %s will be "revert" or
390 "cherry-pick", the second %s a SHA1 */
391 return error(_("%s: cannot parse parent commit %s"),
392 action_name(opts), sha1_to_hex(parent->object.sha1));
394 if (get_message(commit, &msg) != 0)
395 return error(_("Cannot get commit message for %s"),
396 sha1_to_hex(commit->object.sha1));
399 * "commit" is an existing commit. We would want to apply
400 * the difference it introduces since its first parent "prev"
401 * on top of the current HEAD if we are cherry-pick. Or the
402 * reverse of it if we are revert.
405 defmsg = git_pathdup("MERGE_MSG");
407 if (opts->action == REPLAY_REVERT) {
408 base = commit;
409 base_label = msg.label;
410 next = parent;
411 next_label = msg.parent_label;
412 strbuf_addstr(&msgbuf, "Revert \"");
413 strbuf_addstr(&msgbuf, msg.subject);
414 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
415 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
417 if (commit->parents && commit->parents->next) {
418 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
419 strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
421 strbuf_addstr(&msgbuf, ".\n");
422 } else {
423 const char *p;
425 base = parent;
426 base_label = msg.parent_label;
427 next = commit;
428 next_label = msg.label;
431 * Append the commit log message to msgbuf; it starts
432 * after the tree, parent, author, committer
433 * information followed by "\n\n".
435 p = strstr(msg.message, "\n\n");
436 if (p) {
437 p += 2;
438 strbuf_addstr(&msgbuf, p);
441 if (opts->record_origin) {
442 strbuf_addstr(&msgbuf, "(cherry picked from commit ");
443 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
444 strbuf_addstr(&msgbuf, ")\n");
448 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REPLAY_REVERT) {
449 res = do_recursive_merge(base, next, base_label, next_label,
450 head, &msgbuf, opts);
451 write_message(&msgbuf, defmsg);
452 } else {
453 struct commit_list *common = NULL;
454 struct commit_list *remotes = NULL;
456 write_message(&msgbuf, defmsg);
458 commit_list_insert(base, &common);
459 commit_list_insert(next, &remotes);
460 res = try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
461 common, sha1_to_hex(head), remotes);
462 free_commit_list(common);
463 free_commit_list(remotes);
466 empty_commit = is_original_commit_empty(commit);
467 if (empty_commit < 0)
468 return empty_commit;
471 * If the merge was clean or if it failed due to conflict, we write
472 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
473 * However, if the merge did not even start, then we don't want to
474 * write it at all.
476 if (opts->action == REPLAY_PICK && !opts->no_commit && (res == 0 || res == 1))
477 write_cherry_pick_head(commit, "CHERRY_PICK_HEAD");
478 if (opts->action == REPLAY_REVERT && ((opts->no_commit && res == 0) || res == 1))
479 write_cherry_pick_head(commit, "REVERT_HEAD");
481 if (res) {
482 error(opts->action == REPLAY_REVERT
483 ? _("could not revert %s... %s")
484 : _("could not apply %s... %s"),
485 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
486 msg.subject);
487 print_advice(res == 1, opts);
488 rerere(opts->allow_rerere_auto);
489 } else {
490 index_unchanged = is_index_unchanged();
492 * If index_unchanged is less than 0, that indicates we either
493 * couldn't parse HEAD or the index, so error out here.
495 if (index_unchanged < 0)
496 return index_unchanged;
498 if (!empty_commit && !opts->keep_redundant_commits && index_unchanged)
500 * The head tree and the index match
501 * meaning the commit is empty. Since it wasn't created
502 * empty (based on the previous test), we can conclude
503 * the commit has been made redundant. Since we don't
504 * want to keep redundant commits, we can just return
505 * here, skipping this commit
507 return 0;
509 if (!opts->no_commit)
510 res = run_git_commit(defmsg, opts);
513 free_message(&msg);
514 free(defmsg);
516 return res;
519 static void prepare_revs(struct replay_opts *opts)
521 if (opts->action != REPLAY_REVERT)
522 opts->revs->reverse ^= 1;
524 if (prepare_revision_walk(opts->revs))
525 die(_("revision walk setup failed"));
527 if (!opts->revs->commits)
528 die(_("empty commit set passed"));
531 static void read_and_refresh_cache(struct replay_opts *opts)
533 static struct lock_file index_lock;
534 int index_fd = hold_locked_index(&index_lock, 0);
535 if (read_index_preload(&the_index, NULL) < 0)
536 die(_("git %s: failed to read the index"), action_name(opts));
537 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
538 if (the_index.cache_changed) {
539 if (write_index(&the_index, index_fd) ||
540 commit_locked_index(&index_lock))
541 die(_("git %s: failed to refresh the index"), action_name(opts));
543 rollback_lock_file(&index_lock);
546 static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
547 struct replay_opts *opts)
549 struct commit_list *cur = NULL;
550 const char *sha1_abbrev = NULL;
551 const char *action_str = opts->action == REPLAY_REVERT ? "revert" : "pick";
552 const char *subject;
553 int subject_len;
555 for (cur = todo_list; cur; cur = cur->next) {
556 sha1_abbrev = find_unique_abbrev(cur->item->object.sha1, DEFAULT_ABBREV);
557 subject_len = find_commit_subject(cur->item->buffer, &subject);
558 strbuf_addf(buf, "%s %s %.*s\n", action_str, sha1_abbrev,
559 subject_len, subject);
561 return 0;
564 static struct commit *parse_insn_line(char *bol, char *eol, struct replay_opts *opts)
566 unsigned char commit_sha1[20];
567 enum replay_action action;
568 char *end_of_object_name;
569 int saved, status, padding;
571 if (!prefixcmp(bol, "pick")) {
572 action = REPLAY_PICK;
573 bol += strlen("pick");
574 } else if (!prefixcmp(bol, "revert")) {
575 action = REPLAY_REVERT;
576 bol += strlen("revert");
577 } else
578 return NULL;
580 /* Eat up extra spaces/ tabs before object name */
581 padding = strspn(bol, " \t");
582 if (!padding)
583 return NULL;
584 bol += padding;
586 end_of_object_name = bol + strcspn(bol, " \t\n");
587 saved = *end_of_object_name;
588 *end_of_object_name = '\0';
589 status = get_sha1(bol, commit_sha1);
590 *end_of_object_name = saved;
593 * Verify that the action matches up with the one in
594 * opts; we don't support arbitrary instructions
596 if (action != opts->action) {
597 const char *action_str;
598 action_str = action == REPLAY_REVERT ? "revert" : "cherry-pick";
599 error(_("Cannot %s during a %s"), action_str, action_name(opts));
600 return NULL;
603 if (status < 0)
604 return NULL;
606 return lookup_commit_reference(commit_sha1);
609 static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
610 struct replay_opts *opts)
612 struct commit_list **next = todo_list;
613 struct commit *commit;
614 char *p = buf;
615 int i;
617 for (i = 1; *p; i++) {
618 char *eol = strchrnul(p, '\n');
619 commit = parse_insn_line(p, eol, opts);
620 if (!commit)
621 return error(_("Could not parse line %d."), i);
622 next = commit_list_append(commit, next);
623 p = *eol ? eol + 1 : eol;
625 if (!*todo_list)
626 return error(_("No commits parsed."));
627 return 0;
630 static void read_populate_todo(struct commit_list **todo_list,
631 struct replay_opts *opts)
633 const char *todo_file = git_path(SEQ_TODO_FILE);
634 struct strbuf buf = STRBUF_INIT;
635 int fd, res;
637 fd = open(todo_file, O_RDONLY);
638 if (fd < 0)
639 die_errno(_("Could not open %s"), todo_file);
640 if (strbuf_read(&buf, fd, 0) < 0) {
641 close(fd);
642 strbuf_release(&buf);
643 die(_("Could not read %s."), todo_file);
645 close(fd);
647 res = parse_insn_buffer(buf.buf, todo_list, opts);
648 strbuf_release(&buf);
649 if (res)
650 die(_("Unusable instruction sheet: %s"), todo_file);
653 static int populate_opts_cb(const char *key, const char *value, void *data)
655 struct replay_opts *opts = data;
656 int error_flag = 1;
658 if (!value)
659 error_flag = 0;
660 else if (!strcmp(key, "options.no-commit"))
661 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
662 else if (!strcmp(key, "options.edit"))
663 opts->edit = git_config_bool_or_int(key, value, &error_flag);
664 else if (!strcmp(key, "options.signoff"))
665 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
666 else if (!strcmp(key, "options.record-origin"))
667 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
668 else if (!strcmp(key, "options.allow-ff"))
669 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
670 else if (!strcmp(key, "options.mainline"))
671 opts->mainline = git_config_int(key, value);
672 else if (!strcmp(key, "options.strategy"))
673 git_config_string(&opts->strategy, key, value);
674 else if (!strcmp(key, "options.strategy-option")) {
675 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
676 opts->xopts[opts->xopts_nr++] = xstrdup(value);
677 } else
678 return error(_("Invalid key: %s"), key);
680 if (!error_flag)
681 return error(_("Invalid value for %s: %s"), key, value);
683 return 0;
686 static void read_populate_opts(struct replay_opts **opts_ptr)
688 const char *opts_file = git_path(SEQ_OPTS_FILE);
690 if (!file_exists(opts_file))
691 return;
692 if (git_config_from_file(populate_opts_cb, opts_file, *opts_ptr) < 0)
693 die(_("Malformed options sheet: %s"), opts_file);
696 static void walk_revs_populate_todo(struct commit_list **todo_list,
697 struct replay_opts *opts)
699 struct commit *commit;
700 struct commit_list **next;
702 prepare_revs(opts);
704 next = todo_list;
705 while ((commit = get_revision(opts->revs)))
706 next = commit_list_append(commit, next);
709 static int create_seq_dir(void)
711 const char *seq_dir = git_path(SEQ_DIR);
713 if (file_exists(seq_dir)) {
714 error(_("a cherry-pick or revert is already in progress"));
715 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
716 return -1;
718 else if (mkdir(seq_dir, 0777) < 0)
719 die_errno(_("Could not create sequencer directory %s"), seq_dir);
720 return 0;
723 static void save_head(const char *head)
725 const char *head_file = git_path(SEQ_HEAD_FILE);
726 static struct lock_file head_lock;
727 struct strbuf buf = STRBUF_INIT;
728 int fd;
730 fd = hold_lock_file_for_update(&head_lock, head_file, LOCK_DIE_ON_ERROR);
731 strbuf_addf(&buf, "%s\n", head);
732 if (write_in_full(fd, buf.buf, buf.len) < 0)
733 die_errno(_("Could not write to %s"), head_file);
734 if (commit_lock_file(&head_lock) < 0)
735 die(_("Error wrapping up %s."), head_file);
738 static int reset_for_rollback(const unsigned char *sha1)
740 const char *argv[4]; /* reset --merge <arg> + NULL */
741 argv[0] = "reset";
742 argv[1] = "--merge";
743 argv[2] = sha1_to_hex(sha1);
744 argv[3] = NULL;
745 return run_command_v_opt(argv, RUN_GIT_CMD);
748 static int rollback_single_pick(void)
750 unsigned char head_sha1[20];
752 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
753 !file_exists(git_path("REVERT_HEAD")))
754 return error(_("no cherry-pick or revert in progress"));
755 if (read_ref_full("HEAD", head_sha1, 0, NULL))
756 return error(_("cannot resolve HEAD"));
757 if (is_null_sha1(head_sha1))
758 return error(_("cannot abort from a branch yet to be born"));
759 return reset_for_rollback(head_sha1);
762 static int sequencer_rollback(struct replay_opts *opts)
764 const char *filename;
765 FILE *f;
766 unsigned char sha1[20];
767 struct strbuf buf = STRBUF_INIT;
769 filename = git_path(SEQ_HEAD_FILE);
770 f = fopen(filename, "r");
771 if (!f && errno == ENOENT) {
773 * There is no multiple-cherry-pick in progress.
774 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
775 * a single-cherry-pick in progress, abort that.
777 return rollback_single_pick();
779 if (!f)
780 return error(_("cannot open %s: %s"), filename,
781 strerror(errno));
782 if (strbuf_getline(&buf, f, '\n')) {
783 error(_("cannot read %s: %s"), filename, ferror(f) ?
784 strerror(errno) : _("unexpected end of file"));
785 fclose(f);
786 goto fail;
788 fclose(f);
789 if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
790 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
791 filename);
792 goto fail;
794 if (reset_for_rollback(sha1))
795 goto fail;
796 remove_sequencer_state();
797 strbuf_release(&buf);
798 return 0;
799 fail:
800 strbuf_release(&buf);
801 return -1;
804 static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
806 const char *todo_file = git_path(SEQ_TODO_FILE);
807 static struct lock_file todo_lock;
808 struct strbuf buf = STRBUF_INIT;
809 int fd;
811 fd = hold_lock_file_for_update(&todo_lock, todo_file, LOCK_DIE_ON_ERROR);
812 if (format_todo(&buf, todo_list, opts) < 0)
813 die(_("Could not format %s."), todo_file);
814 if (write_in_full(fd, buf.buf, buf.len) < 0) {
815 strbuf_release(&buf);
816 die_errno(_("Could not write to %s"), todo_file);
818 if (commit_lock_file(&todo_lock) < 0) {
819 strbuf_release(&buf);
820 die(_("Error wrapping up %s."), todo_file);
822 strbuf_release(&buf);
825 static void save_opts(struct replay_opts *opts)
827 const char *opts_file = git_path(SEQ_OPTS_FILE);
829 if (opts->no_commit)
830 git_config_set_in_file(opts_file, "options.no-commit", "true");
831 if (opts->edit)
832 git_config_set_in_file(opts_file, "options.edit", "true");
833 if (opts->signoff)
834 git_config_set_in_file(opts_file, "options.signoff", "true");
835 if (opts->record_origin)
836 git_config_set_in_file(opts_file, "options.record-origin", "true");
837 if (opts->allow_ff)
838 git_config_set_in_file(opts_file, "options.allow-ff", "true");
839 if (opts->mainline) {
840 struct strbuf buf = STRBUF_INIT;
841 strbuf_addf(&buf, "%d", opts->mainline);
842 git_config_set_in_file(opts_file, "options.mainline", buf.buf);
843 strbuf_release(&buf);
845 if (opts->strategy)
846 git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
847 if (opts->xopts) {
848 int i;
849 for (i = 0; i < opts->xopts_nr; i++)
850 git_config_set_multivar_in_file(opts_file,
851 "options.strategy-option",
852 opts->xopts[i], "^$", 0);
856 static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
858 struct commit_list *cur;
859 int res;
861 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
862 if (opts->allow_ff)
863 assert(!(opts->signoff || opts->no_commit ||
864 opts->record_origin || opts->edit));
865 read_and_refresh_cache(opts);
867 for (cur = todo_list; cur; cur = cur->next) {
868 save_todo(cur, opts);
869 res = do_pick_commit(cur->item, opts);
870 if (res)
871 return res;
875 * Sequence of picks finished successfully; cleanup by
876 * removing the .git/sequencer directory
878 remove_sequencer_state();
879 return 0;
882 static int continue_single_pick(void)
884 const char *argv[] = { "commit", NULL };
886 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
887 !file_exists(git_path("REVERT_HEAD")))
888 return error(_("no cherry-pick or revert in progress"));
889 return run_command_v_opt(argv, RUN_GIT_CMD);
892 static int sequencer_continue(struct replay_opts *opts)
894 struct commit_list *todo_list = NULL;
896 if (!file_exists(git_path(SEQ_TODO_FILE)))
897 return continue_single_pick();
898 read_populate_opts(&opts);
899 read_populate_todo(&todo_list, opts);
901 /* Verify that the conflict has been resolved */
902 if (file_exists(git_path("CHERRY_PICK_HEAD")) ||
903 file_exists(git_path("REVERT_HEAD"))) {
904 int ret = continue_single_pick();
905 if (ret)
906 return ret;
908 if (index_differs_from("HEAD", 0))
909 return error_dirty_index(opts);
910 todo_list = todo_list->next;
911 return pick_commits(todo_list, opts);
914 static int single_pick(struct commit *cmit, struct replay_opts *opts)
916 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
917 return do_pick_commit(cmit, opts);
920 int sequencer_pick_revisions(struct replay_opts *opts)
922 struct commit_list *todo_list = NULL;
923 unsigned char sha1[20];
925 if (opts->subcommand == REPLAY_NONE)
926 assert(opts->revs);
928 read_and_refresh_cache(opts);
931 * Decide what to do depending on the arguments; a fresh
932 * cherry-pick should be handled differently from an existing
933 * one that is being continued
935 if (opts->subcommand == REPLAY_REMOVE_STATE) {
936 remove_sequencer_state();
937 return 0;
939 if (opts->subcommand == REPLAY_ROLLBACK)
940 return sequencer_rollback(opts);
941 if (opts->subcommand == REPLAY_CONTINUE)
942 return sequencer_continue(opts);
945 * If we were called as "git cherry-pick <commit>", just
946 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
947 * REVERT_HEAD, and don't touch the sequencer state.
948 * This means it is possible to cherry-pick in the middle
949 * of a cherry-pick sequence.
951 if (opts->revs->cmdline.nr == 1 &&
952 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
953 opts->revs->no_walk &&
954 !opts->revs->cmdline.rev->flags) {
955 struct commit *cmit;
956 if (prepare_revision_walk(opts->revs))
957 die(_("revision walk setup failed"));
958 cmit = get_revision(opts->revs);
959 if (!cmit || get_revision(opts->revs))
960 die("BUG: expected exactly one commit from walk");
961 return single_pick(cmit, opts);
965 * Start a new cherry-pick/ revert sequence; but
966 * first, make sure that an existing one isn't in
967 * progress
970 walk_revs_populate_todo(&todo_list, opts);
971 if (create_seq_dir() < 0)
972 return -1;
973 if (get_sha1("HEAD", sha1)) {
974 if (opts->action == REPLAY_REVERT)
975 return error(_("Can't revert as initial commit"));
976 return error(_("Can't cherry-pick into empty head"));
978 save_head(sha1_to_hex(sha1));
979 save_opts(opts);
980 return pick_commits(todo_list, opts);