Merge branch 'jc/doc-push-satellite'
[git/mjg.git] / sequencer.c
blob22604902aa4c4dd146f562c4841c344a773a9bda
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 const char sign_off_header[] = "Signed-off-by: ";
22 static void remove_sequencer_state(void)
24 struct strbuf seq_dir = STRBUF_INIT;
26 strbuf_addf(&seq_dir, "%s", git_path(SEQ_DIR));
27 remove_dir_recursively(&seq_dir, 0);
28 strbuf_release(&seq_dir);
31 static const char *action_name(const struct replay_opts *opts)
33 return opts->action == REPLAY_REVERT ? "revert" : "cherry-pick";
36 static char *get_encoding(const char *message);
38 struct commit_message {
39 char *parent_label;
40 const char *label;
41 const char *subject;
42 char *reencoded_message;
43 const char *message;
46 static int get_message(struct commit *commit, struct commit_message *out)
48 const char *encoding;
49 const char *abbrev, *subject;
50 int abbrev_len, subject_len;
51 char *q;
53 if (!commit->buffer)
54 return -1;
55 encoding = get_encoding(commit->buffer);
56 if (!encoding)
57 encoding = "UTF-8";
58 if (!git_commit_encoding)
59 git_commit_encoding = "UTF-8";
61 out->reencoded_message = NULL;
62 out->message = commit->buffer;
63 if (same_encoding(encoding, git_commit_encoding))
64 out->reencoded_message = reencode_string(commit->buffer,
65 git_commit_encoding, encoding);
66 if (out->reencoded_message)
67 out->message = out->reencoded_message;
69 abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
70 abbrev_len = strlen(abbrev);
72 subject_len = find_commit_subject(out->message, &subject);
74 out->parent_label = xmalloc(strlen("parent of ") + abbrev_len +
75 strlen("... ") + subject_len + 1);
76 q = out->parent_label;
77 q = mempcpy(q, "parent of ", strlen("parent of "));
78 out->label = q;
79 q = mempcpy(q, abbrev, abbrev_len);
80 q = mempcpy(q, "... ", strlen("... "));
81 out->subject = q;
82 q = mempcpy(q, subject, subject_len);
83 *q = '\0';
84 return 0;
87 static void free_message(struct commit_message *msg)
89 free(msg->parent_label);
90 free(msg->reencoded_message);
93 static char *get_encoding(const char *message)
95 const char *p = message, *eol;
97 while (*p && *p != '\n') {
98 for (eol = p + 1; *eol && *eol != '\n'; eol++)
99 ; /* do nothing */
100 if (!prefixcmp(p, "encoding ")) {
101 char *result = xmalloc(eol - 8 - p);
102 strlcpy(result, p + 9, eol - 8 - p);
103 return result;
105 p = eol;
106 if (*p == '\n')
107 p++;
109 return NULL;
112 static void write_cherry_pick_head(struct commit *commit, const char *pseudoref)
114 const char *filename;
115 int fd;
116 struct strbuf buf = STRBUF_INIT;
118 strbuf_addf(&buf, "%s\n", sha1_to_hex(commit->object.sha1));
120 filename = git_path("%s", pseudoref);
121 fd = open(filename, O_WRONLY | O_CREAT, 0666);
122 if (fd < 0)
123 die_errno(_("Could not open '%s' for writing"), filename);
124 if (write_in_full(fd, buf.buf, buf.len) != buf.len || close(fd))
125 die_errno(_("Could not write to '%s'"), filename);
126 strbuf_release(&buf);
129 static void print_advice(int show_hint, struct replay_opts *opts)
131 char *msg = getenv("GIT_CHERRY_PICK_HELP");
133 if (msg) {
134 fprintf(stderr, "%s\n", msg);
136 * A conflict has occured but the porcelain
137 * (typically rebase --interactive) wants to take care
138 * of the commit itself so remove CHERRY_PICK_HEAD
140 unlink(git_path("CHERRY_PICK_HEAD"));
141 return;
144 if (show_hint) {
145 if (opts->no_commit)
146 advise(_("after resolving the conflicts, mark the corrected paths\n"
147 "with 'git add <paths>' or 'git rm <paths>'"));
148 else
149 advise(_("after resolving the conflicts, mark the corrected paths\n"
150 "with 'git add <paths>' or 'git rm <paths>'\n"
151 "and commit the result with 'git commit'"));
155 static void write_message(struct strbuf *msgbuf, const char *filename)
157 static struct lock_file msg_file;
159 int msg_fd = hold_lock_file_for_update(&msg_file, filename,
160 LOCK_DIE_ON_ERROR);
161 if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
162 die_errno(_("Could not write to %s"), filename);
163 strbuf_release(msgbuf);
164 if (commit_lock_file(&msg_file) < 0)
165 die(_("Error wrapping up %s"), filename);
168 static struct tree *empty_tree(void)
170 return lookup_tree(EMPTY_TREE_SHA1_BIN);
173 static int error_dirty_index(struct replay_opts *opts)
175 if (read_cache_unmerged())
176 return error_resolve_conflict(action_name(opts));
178 /* Different translation strings for cherry-pick and revert */
179 if (opts->action == REPLAY_PICK)
180 error(_("Your local changes would be overwritten by cherry-pick."));
181 else
182 error(_("Your local changes would be overwritten by revert."));
184 if (advice_commit_before_merge)
185 advise(_("Commit your changes or stash them to proceed."));
186 return -1;
189 static int fast_forward_to(const unsigned char *to, const unsigned char *from)
191 struct ref_lock *ref_lock;
193 read_cache();
194 if (checkout_fast_forward(from, to, 1))
195 exit(1); /* the callee should have complained already */
196 ref_lock = lock_any_ref_for_update("HEAD", from, 0);
197 return write_ref_sha1(ref_lock, to, "cherry-pick");
200 static int do_recursive_merge(struct commit *base, struct commit *next,
201 const char *base_label, const char *next_label,
202 unsigned char *head, struct strbuf *msgbuf,
203 struct replay_opts *opts)
205 struct merge_options o;
206 struct tree *result, *next_tree, *base_tree, *head_tree;
207 int clean, index_fd;
208 const char **xopt;
209 static struct lock_file index_lock;
211 index_fd = hold_locked_index(&index_lock, 1);
213 read_cache();
215 init_merge_options(&o);
216 o.ancestor = base ? base_label : "(empty tree)";
217 o.branch1 = "HEAD";
218 o.branch2 = next ? next_label : "(empty tree)";
220 head_tree = parse_tree_indirect(head);
221 next_tree = next ? next->tree : empty_tree();
222 base_tree = base ? base->tree : empty_tree();
224 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
225 parse_merge_opt(&o, *xopt);
227 clean = merge_trees(&o,
228 head_tree,
229 next_tree, base_tree, &result);
231 if (active_cache_changed &&
232 (write_cache(index_fd, active_cache, active_nr) ||
233 commit_locked_index(&index_lock)))
234 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
235 die(_("%s: Unable to write new index file"), action_name(opts));
236 rollback_lock_file(&index_lock);
238 if (opts->signoff)
239 append_signoff(msgbuf, 0);
241 if (!clean) {
242 int i;
243 strbuf_addstr(msgbuf, "\nConflicts:\n");
244 for (i = 0; i < active_nr;) {
245 struct cache_entry *ce = active_cache[i++];
246 if (ce_stage(ce)) {
247 strbuf_addch(msgbuf, '\t');
248 strbuf_addstr(msgbuf, ce->name);
249 strbuf_addch(msgbuf, '\n');
250 while (i < active_nr && !strcmp(ce->name,
251 active_cache[i]->name))
252 i++;
257 return !clean;
260 static int is_index_unchanged(void)
262 unsigned char head_sha1[20];
263 struct commit *head_commit;
265 if (!resolve_ref_unsafe("HEAD", head_sha1, 1, NULL))
266 return error(_("Could not resolve HEAD commit\n"));
268 head_commit = lookup_commit(head_sha1);
271 * If head_commit is NULL, check_commit, called from
272 * lookup_commit, would have indicated that head_commit is not
273 * a commit object already. parse_commit() will return failure
274 * without further complaints in such a case. Otherwise, if
275 * the commit is invalid, parse_commit() will complain. So
276 * there is nothing for us to say here. Just return failure.
278 if (parse_commit(head_commit))
279 return -1;
281 if (!active_cache_tree)
282 active_cache_tree = cache_tree();
284 if (!cache_tree_fully_valid(active_cache_tree))
285 if (cache_tree_update(active_cache_tree, active_cache,
286 active_nr, 0))
287 return error(_("Unable to update cache tree\n"));
289 return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.sha1);
293 * If we are cherry-pick, and if the merge did not result in
294 * hand-editing, we will hit this commit and inherit the original
295 * author date and name.
296 * If we are revert, or if our cherry-pick results in a hand merge,
297 * we had better say that the current user is responsible for that.
299 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
300 int allow_empty)
302 struct argv_array array;
303 int rc;
305 argv_array_init(&array);
306 argv_array_push(&array, "commit");
307 argv_array_push(&array, "-n");
309 if (opts->signoff)
310 argv_array_push(&array, "-s");
311 if (!opts->edit) {
312 argv_array_push(&array, "-F");
313 argv_array_push(&array, defmsg);
316 if (allow_empty)
317 argv_array_push(&array, "--allow-empty");
319 if (opts->allow_empty_message)
320 argv_array_push(&array, "--allow-empty-message");
322 rc = run_command_v_opt(array.argv, RUN_GIT_CMD);
323 argv_array_clear(&array);
324 return rc;
327 static int is_original_commit_empty(struct commit *commit)
329 const unsigned char *ptree_sha1;
331 if (parse_commit(commit))
332 return error(_("Could not parse commit %s\n"),
333 sha1_to_hex(commit->object.sha1));
334 if (commit->parents) {
335 struct commit *parent = commit->parents->item;
336 if (parse_commit(parent))
337 return error(_("Could not parse parent commit %s\n"),
338 sha1_to_hex(parent->object.sha1));
339 ptree_sha1 = parent->tree->object.sha1;
340 } else {
341 ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
344 return !hashcmp(ptree_sha1, commit->tree->object.sha1);
348 * Do we run "git commit" with "--allow-empty"?
350 static int allow_empty(struct replay_opts *opts, struct commit *commit)
352 int index_unchanged, empty_commit;
355 * Three cases:
357 * (1) we do not allow empty at all and error out.
359 * (2) we allow ones that were initially empty, but
360 * forbid the ones that become empty;
362 * (3) we allow both.
364 if (!opts->allow_empty)
365 return 0; /* let "git commit" barf as necessary */
367 index_unchanged = is_index_unchanged();
368 if (index_unchanged < 0)
369 return index_unchanged;
370 if (!index_unchanged)
371 return 0; /* we do not have to say --allow-empty */
373 if (opts->keep_redundant_commits)
374 return 1;
376 empty_commit = is_original_commit_empty(commit);
377 if (empty_commit < 0)
378 return empty_commit;
379 if (!empty_commit)
380 return 0;
381 else
382 return 1;
385 static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
387 unsigned char head[20];
388 struct commit *base, *next, *parent;
389 const char *base_label, *next_label;
390 struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
391 char *defmsg = NULL;
392 struct strbuf msgbuf = STRBUF_INIT;
393 int res;
395 if (opts->no_commit) {
397 * We do not intend to commit immediately. We just want to
398 * merge the differences in, so let's compute the tree
399 * that represents the "current" state for merge-recursive
400 * to work on.
402 if (write_cache_as_tree(head, 0, NULL))
403 die (_("Your index file is unmerged."));
404 } else {
405 if (get_sha1("HEAD", head))
406 return error(_("You do not have a valid HEAD"));
407 if (index_differs_from("HEAD", 0))
408 return error_dirty_index(opts);
410 discard_cache();
412 if (!commit->parents) {
413 parent = NULL;
415 else if (commit->parents->next) {
416 /* Reverting or cherry-picking a merge commit */
417 int cnt;
418 struct commit_list *p;
420 if (!opts->mainline)
421 return error(_("Commit %s is a merge but no -m option was given."),
422 sha1_to_hex(commit->object.sha1));
424 for (cnt = 1, p = commit->parents;
425 cnt != opts->mainline && p;
426 cnt++)
427 p = p->next;
428 if (cnt != opts->mainline || !p)
429 return error(_("Commit %s does not have parent %d"),
430 sha1_to_hex(commit->object.sha1), opts->mainline);
431 parent = p->item;
432 } else if (0 < opts->mainline)
433 return error(_("Mainline was specified but commit %s is not a merge."),
434 sha1_to_hex(commit->object.sha1));
435 else
436 parent = commit->parents->item;
438 if (opts->allow_ff && parent && !hashcmp(parent->object.sha1, head))
439 return fast_forward_to(commit->object.sha1, head);
441 if (parent && parse_commit(parent) < 0)
442 /* TRANSLATORS: The first %s will be "revert" or
443 "cherry-pick", the second %s a SHA1 */
444 return error(_("%s: cannot parse parent commit %s"),
445 action_name(opts), sha1_to_hex(parent->object.sha1));
447 if (get_message(commit, &msg) != 0)
448 return error(_("Cannot get commit message for %s"),
449 sha1_to_hex(commit->object.sha1));
452 * "commit" is an existing commit. We would want to apply
453 * the difference it introduces since its first parent "prev"
454 * on top of the current HEAD if we are cherry-pick. Or the
455 * reverse of it if we are revert.
458 defmsg = git_pathdup("MERGE_MSG");
460 if (opts->action == REPLAY_REVERT) {
461 base = commit;
462 base_label = msg.label;
463 next = parent;
464 next_label = msg.parent_label;
465 strbuf_addstr(&msgbuf, "Revert \"");
466 strbuf_addstr(&msgbuf, msg.subject);
467 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
468 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
470 if (commit->parents && commit->parents->next) {
471 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
472 strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
474 strbuf_addstr(&msgbuf, ".\n");
475 } else {
476 const char *p;
478 base = parent;
479 base_label = msg.parent_label;
480 next = commit;
481 next_label = msg.label;
484 * Append the commit log message to msgbuf; it starts
485 * after the tree, parent, author, committer
486 * information followed by "\n\n".
488 p = strstr(msg.message, "\n\n");
489 if (p) {
490 p += 2;
491 strbuf_addstr(&msgbuf, p);
494 if (opts->record_origin) {
495 strbuf_addstr(&msgbuf, "(cherry picked from commit ");
496 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
497 strbuf_addstr(&msgbuf, ")\n");
501 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REPLAY_REVERT) {
502 res = do_recursive_merge(base, next, base_label, next_label,
503 head, &msgbuf, opts);
504 write_message(&msgbuf, defmsg);
505 } else {
506 struct commit_list *common = NULL;
507 struct commit_list *remotes = NULL;
509 write_message(&msgbuf, defmsg);
511 commit_list_insert(base, &common);
512 commit_list_insert(next, &remotes);
513 res = try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
514 common, sha1_to_hex(head), remotes);
515 free_commit_list(common);
516 free_commit_list(remotes);
520 * If the merge was clean or if it failed due to conflict, we write
521 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
522 * However, if the merge did not even start, then we don't want to
523 * write it at all.
525 if (opts->action == REPLAY_PICK && !opts->no_commit && (res == 0 || res == 1))
526 write_cherry_pick_head(commit, "CHERRY_PICK_HEAD");
527 if (opts->action == REPLAY_REVERT && ((opts->no_commit && res == 0) || res == 1))
528 write_cherry_pick_head(commit, "REVERT_HEAD");
530 if (res) {
531 error(opts->action == REPLAY_REVERT
532 ? _("could not revert %s... %s")
533 : _("could not apply %s... %s"),
534 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
535 msg.subject);
536 print_advice(res == 1, opts);
537 rerere(opts->allow_rerere_auto);
538 } else {
539 int allow = allow_empty(opts, commit);
540 if (allow < 0)
541 return allow;
542 if (!opts->no_commit)
543 res = run_git_commit(defmsg, opts, allow);
546 free_message(&msg);
547 free(defmsg);
549 return res;
552 static void prepare_revs(struct replay_opts *opts)
555 * picking (but not reverting) ranges (but not individual revisions)
556 * should be done in reverse
558 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
559 opts->revs->reverse ^= 1;
561 if (prepare_revision_walk(opts->revs))
562 die(_("revision walk setup failed"));
564 if (!opts->revs->commits)
565 die(_("empty commit set passed"));
568 static void read_and_refresh_cache(struct replay_opts *opts)
570 static struct lock_file index_lock;
571 int index_fd = hold_locked_index(&index_lock, 0);
572 if (read_index_preload(&the_index, NULL) < 0)
573 die(_("git %s: failed to read the index"), action_name(opts));
574 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
575 if (the_index.cache_changed) {
576 if (write_index(&the_index, index_fd) ||
577 commit_locked_index(&index_lock))
578 die(_("git %s: failed to refresh the index"), action_name(opts));
580 rollback_lock_file(&index_lock);
583 static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
584 struct replay_opts *opts)
586 struct commit_list *cur = NULL;
587 const char *sha1_abbrev = NULL;
588 const char *action_str = opts->action == REPLAY_REVERT ? "revert" : "pick";
589 const char *subject;
590 int subject_len;
592 for (cur = todo_list; cur; cur = cur->next) {
593 sha1_abbrev = find_unique_abbrev(cur->item->object.sha1, DEFAULT_ABBREV);
594 subject_len = find_commit_subject(cur->item->buffer, &subject);
595 strbuf_addf(buf, "%s %s %.*s\n", action_str, sha1_abbrev,
596 subject_len, subject);
598 return 0;
601 static struct commit *parse_insn_line(char *bol, char *eol, struct replay_opts *opts)
603 unsigned char commit_sha1[20];
604 enum replay_action action;
605 char *end_of_object_name;
606 int saved, status, padding;
608 if (!prefixcmp(bol, "pick")) {
609 action = REPLAY_PICK;
610 bol += strlen("pick");
611 } else if (!prefixcmp(bol, "revert")) {
612 action = REPLAY_REVERT;
613 bol += strlen("revert");
614 } else
615 return NULL;
617 /* Eat up extra spaces/ tabs before object name */
618 padding = strspn(bol, " \t");
619 if (!padding)
620 return NULL;
621 bol += padding;
623 end_of_object_name = bol + strcspn(bol, " \t\n");
624 saved = *end_of_object_name;
625 *end_of_object_name = '\0';
626 status = get_sha1(bol, commit_sha1);
627 *end_of_object_name = saved;
630 * Verify that the action matches up with the one in
631 * opts; we don't support arbitrary instructions
633 if (action != opts->action) {
634 const char *action_str;
635 action_str = action == REPLAY_REVERT ? "revert" : "cherry-pick";
636 error(_("Cannot %s during a %s"), action_str, action_name(opts));
637 return NULL;
640 if (status < 0)
641 return NULL;
643 return lookup_commit_reference(commit_sha1);
646 static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
647 struct replay_opts *opts)
649 struct commit_list **next = todo_list;
650 struct commit *commit;
651 char *p = buf;
652 int i;
654 for (i = 1; *p; i++) {
655 char *eol = strchrnul(p, '\n');
656 commit = parse_insn_line(p, eol, opts);
657 if (!commit)
658 return error(_("Could not parse line %d."), i);
659 next = commit_list_append(commit, next);
660 p = *eol ? eol + 1 : eol;
662 if (!*todo_list)
663 return error(_("No commits parsed."));
664 return 0;
667 static void read_populate_todo(struct commit_list **todo_list,
668 struct replay_opts *opts)
670 const char *todo_file = git_path(SEQ_TODO_FILE);
671 struct strbuf buf = STRBUF_INIT;
672 int fd, res;
674 fd = open(todo_file, O_RDONLY);
675 if (fd < 0)
676 die_errno(_("Could not open %s"), todo_file);
677 if (strbuf_read(&buf, fd, 0) < 0) {
678 close(fd);
679 strbuf_release(&buf);
680 die(_("Could not read %s."), todo_file);
682 close(fd);
684 res = parse_insn_buffer(buf.buf, todo_list, opts);
685 strbuf_release(&buf);
686 if (res)
687 die(_("Unusable instruction sheet: %s"), todo_file);
690 static int populate_opts_cb(const char *key, const char *value, void *data)
692 struct replay_opts *opts = data;
693 int error_flag = 1;
695 if (!value)
696 error_flag = 0;
697 else if (!strcmp(key, "options.no-commit"))
698 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
699 else if (!strcmp(key, "options.edit"))
700 opts->edit = git_config_bool_or_int(key, value, &error_flag);
701 else if (!strcmp(key, "options.signoff"))
702 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
703 else if (!strcmp(key, "options.record-origin"))
704 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
705 else if (!strcmp(key, "options.allow-ff"))
706 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
707 else if (!strcmp(key, "options.mainline"))
708 opts->mainline = git_config_int(key, value);
709 else if (!strcmp(key, "options.strategy"))
710 git_config_string(&opts->strategy, key, value);
711 else if (!strcmp(key, "options.strategy-option")) {
712 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
713 opts->xopts[opts->xopts_nr++] = xstrdup(value);
714 } else
715 return error(_("Invalid key: %s"), key);
717 if (!error_flag)
718 return error(_("Invalid value for %s: %s"), key, value);
720 return 0;
723 static void read_populate_opts(struct replay_opts **opts_ptr)
725 const char *opts_file = git_path(SEQ_OPTS_FILE);
727 if (!file_exists(opts_file))
728 return;
729 if (git_config_from_file(populate_opts_cb, opts_file, *opts_ptr) < 0)
730 die(_("Malformed options sheet: %s"), opts_file);
733 static void walk_revs_populate_todo(struct commit_list **todo_list,
734 struct replay_opts *opts)
736 struct commit *commit;
737 struct commit_list **next;
739 prepare_revs(opts);
741 next = todo_list;
742 while ((commit = get_revision(opts->revs)))
743 next = commit_list_append(commit, next);
746 static int create_seq_dir(void)
748 const char *seq_dir = git_path(SEQ_DIR);
750 if (file_exists(seq_dir)) {
751 error(_("a cherry-pick or revert is already in progress"));
752 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
753 return -1;
755 else if (mkdir(seq_dir, 0777) < 0)
756 die_errno(_("Could not create sequencer directory %s"), seq_dir);
757 return 0;
760 static void save_head(const char *head)
762 const char *head_file = git_path(SEQ_HEAD_FILE);
763 static struct lock_file head_lock;
764 struct strbuf buf = STRBUF_INIT;
765 int fd;
767 fd = hold_lock_file_for_update(&head_lock, head_file, LOCK_DIE_ON_ERROR);
768 strbuf_addf(&buf, "%s\n", head);
769 if (write_in_full(fd, buf.buf, buf.len) < 0)
770 die_errno(_("Could not write to %s"), head_file);
771 if (commit_lock_file(&head_lock) < 0)
772 die(_("Error wrapping up %s."), head_file);
775 static int reset_for_rollback(const unsigned char *sha1)
777 const char *argv[4]; /* reset --merge <arg> + NULL */
778 argv[0] = "reset";
779 argv[1] = "--merge";
780 argv[2] = sha1_to_hex(sha1);
781 argv[3] = NULL;
782 return run_command_v_opt(argv, RUN_GIT_CMD);
785 static int rollback_single_pick(void)
787 unsigned char head_sha1[20];
789 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
790 !file_exists(git_path("REVERT_HEAD")))
791 return error(_("no cherry-pick or revert in progress"));
792 if (read_ref_full("HEAD", head_sha1, 0, NULL))
793 return error(_("cannot resolve HEAD"));
794 if (is_null_sha1(head_sha1))
795 return error(_("cannot abort from a branch yet to be born"));
796 return reset_for_rollback(head_sha1);
799 static int sequencer_rollback(struct replay_opts *opts)
801 const char *filename;
802 FILE *f;
803 unsigned char sha1[20];
804 struct strbuf buf = STRBUF_INIT;
806 filename = git_path(SEQ_HEAD_FILE);
807 f = fopen(filename, "r");
808 if (!f && errno == ENOENT) {
810 * There is no multiple-cherry-pick in progress.
811 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
812 * a single-cherry-pick in progress, abort that.
814 return rollback_single_pick();
816 if (!f)
817 return error(_("cannot open %s: %s"), filename,
818 strerror(errno));
819 if (strbuf_getline(&buf, f, '\n')) {
820 error(_("cannot read %s: %s"), filename, ferror(f) ?
821 strerror(errno) : _("unexpected end of file"));
822 fclose(f);
823 goto fail;
825 fclose(f);
826 if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
827 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
828 filename);
829 goto fail;
831 if (reset_for_rollback(sha1))
832 goto fail;
833 remove_sequencer_state();
834 strbuf_release(&buf);
835 return 0;
836 fail:
837 strbuf_release(&buf);
838 return -1;
841 static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
843 const char *todo_file = git_path(SEQ_TODO_FILE);
844 static struct lock_file todo_lock;
845 struct strbuf buf = STRBUF_INIT;
846 int fd;
848 fd = hold_lock_file_for_update(&todo_lock, todo_file, LOCK_DIE_ON_ERROR);
849 if (format_todo(&buf, todo_list, opts) < 0)
850 die(_("Could not format %s."), todo_file);
851 if (write_in_full(fd, buf.buf, buf.len) < 0) {
852 strbuf_release(&buf);
853 die_errno(_("Could not write to %s"), todo_file);
855 if (commit_lock_file(&todo_lock) < 0) {
856 strbuf_release(&buf);
857 die(_("Error wrapping up %s."), todo_file);
859 strbuf_release(&buf);
862 static void save_opts(struct replay_opts *opts)
864 const char *opts_file = git_path(SEQ_OPTS_FILE);
866 if (opts->no_commit)
867 git_config_set_in_file(opts_file, "options.no-commit", "true");
868 if (opts->edit)
869 git_config_set_in_file(opts_file, "options.edit", "true");
870 if (opts->signoff)
871 git_config_set_in_file(opts_file, "options.signoff", "true");
872 if (opts->record_origin)
873 git_config_set_in_file(opts_file, "options.record-origin", "true");
874 if (opts->allow_ff)
875 git_config_set_in_file(opts_file, "options.allow-ff", "true");
876 if (opts->mainline) {
877 struct strbuf buf = STRBUF_INIT;
878 strbuf_addf(&buf, "%d", opts->mainline);
879 git_config_set_in_file(opts_file, "options.mainline", buf.buf);
880 strbuf_release(&buf);
882 if (opts->strategy)
883 git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
884 if (opts->xopts) {
885 int i;
886 for (i = 0; i < opts->xopts_nr; i++)
887 git_config_set_multivar_in_file(opts_file,
888 "options.strategy-option",
889 opts->xopts[i], "^$", 0);
893 static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
895 struct commit_list *cur;
896 int res;
898 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
899 if (opts->allow_ff)
900 assert(!(opts->signoff || opts->no_commit ||
901 opts->record_origin || opts->edit));
902 read_and_refresh_cache(opts);
904 for (cur = todo_list; cur; cur = cur->next) {
905 save_todo(cur, opts);
906 res = do_pick_commit(cur->item, opts);
907 if (res)
908 return res;
912 * Sequence of picks finished successfully; cleanup by
913 * removing the .git/sequencer directory
915 remove_sequencer_state();
916 return 0;
919 static int continue_single_pick(void)
921 const char *argv[] = { "commit", NULL };
923 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
924 !file_exists(git_path("REVERT_HEAD")))
925 return error(_("no cherry-pick or revert in progress"));
926 return run_command_v_opt(argv, RUN_GIT_CMD);
929 static int sequencer_continue(struct replay_opts *opts)
931 struct commit_list *todo_list = NULL;
933 if (!file_exists(git_path(SEQ_TODO_FILE)))
934 return continue_single_pick();
935 read_populate_opts(&opts);
936 read_populate_todo(&todo_list, opts);
938 /* Verify that the conflict has been resolved */
939 if (file_exists(git_path("CHERRY_PICK_HEAD")) ||
940 file_exists(git_path("REVERT_HEAD"))) {
941 int ret = continue_single_pick();
942 if (ret)
943 return ret;
945 if (index_differs_from("HEAD", 0))
946 return error_dirty_index(opts);
947 todo_list = todo_list->next;
948 return pick_commits(todo_list, opts);
951 static int single_pick(struct commit *cmit, struct replay_opts *opts)
953 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
954 return do_pick_commit(cmit, opts);
957 int sequencer_pick_revisions(struct replay_opts *opts)
959 struct commit_list *todo_list = NULL;
960 unsigned char sha1[20];
962 if (opts->subcommand == REPLAY_NONE)
963 assert(opts->revs);
965 read_and_refresh_cache(opts);
968 * Decide what to do depending on the arguments; a fresh
969 * cherry-pick should be handled differently from an existing
970 * one that is being continued
972 if (opts->subcommand == REPLAY_REMOVE_STATE) {
973 remove_sequencer_state();
974 return 0;
976 if (opts->subcommand == REPLAY_ROLLBACK)
977 return sequencer_rollback(opts);
978 if (opts->subcommand == REPLAY_CONTINUE)
979 return sequencer_continue(opts);
982 * If we were called as "git cherry-pick <commit>", just
983 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
984 * REVERT_HEAD, and don't touch the sequencer state.
985 * This means it is possible to cherry-pick in the middle
986 * of a cherry-pick sequence.
988 if (opts->revs->cmdline.nr == 1 &&
989 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
990 opts->revs->no_walk &&
991 !opts->revs->cmdline.rev->flags) {
992 struct commit *cmit;
993 if (prepare_revision_walk(opts->revs))
994 die(_("revision walk setup failed"));
995 cmit = get_revision(opts->revs);
996 if (!cmit || get_revision(opts->revs))
997 die("BUG: expected exactly one commit from walk");
998 return single_pick(cmit, opts);
1002 * Start a new cherry-pick/ revert sequence; but
1003 * first, make sure that an existing one isn't in
1004 * progress
1007 walk_revs_populate_todo(&todo_list, opts);
1008 if (create_seq_dir() < 0)
1009 return -1;
1010 if (get_sha1("HEAD", sha1)) {
1011 if (opts->action == REPLAY_REVERT)
1012 return error(_("Can't revert as initial commit"));
1013 return error(_("Can't cherry-pick into empty head"));
1015 save_head(sha1_to_hex(sha1));
1016 save_opts(opts);
1017 return pick_commits(todo_list, opts);
1020 static int ends_rfc2822_footer(struct strbuf *sb, int ignore_footer)
1022 int ch;
1023 int hit = 0;
1024 int i, j, k;
1025 int len = sb->len - ignore_footer;
1026 int first = 1;
1027 const char *buf = sb->buf;
1029 for (i = len - 1; i > 0; i--) {
1030 if (hit && buf[i] == '\n')
1031 break;
1032 hit = (buf[i] == '\n');
1035 while (i < len - 1 && buf[i] == '\n')
1036 i++;
1038 for (; i < len; i = k) {
1039 for (k = i; k < len && buf[k] != '\n'; k++)
1040 ; /* do nothing */
1041 k++;
1043 if ((buf[k] == ' ' || buf[k] == '\t') && !first)
1044 continue;
1046 first = 0;
1048 for (j = 0; i + j < len; j++) {
1049 ch = buf[i + j];
1050 if (ch == ':')
1051 break;
1052 if (isalnum(ch) ||
1053 (ch == '-'))
1054 continue;
1055 return 0;
1058 return 1;
1061 void append_signoff(struct strbuf *msgbuf, int ignore_footer)
1063 struct strbuf sob = STRBUF_INIT;
1064 int i;
1066 strbuf_addstr(&sob, sign_off_header);
1067 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
1068 getenv("GIT_COMMITTER_EMAIL")));
1069 strbuf_addch(&sob, '\n');
1070 for (i = msgbuf->len - 1 - ignore_footer; i > 0 && msgbuf->buf[i - 1] != '\n'; i--)
1071 ; /* do nothing */
1072 if (prefixcmp(msgbuf->buf + i, sob.buf)) {
1073 if (!i || !ends_rfc2822_footer(msgbuf, ignore_footer))
1074 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0, "\n", 1);
1075 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0, sob.buf, sob.len);
1077 strbuf_release(&sob);