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