git-rebase: add keep_empty flag
[git/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"
b27cfb0d 16#include "argv-array.h"
043a4492
RR
17
18#define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
26ae337b 19
d596118d 20void remove_sequencer_state(void)
26ae337b
RR
21{
22 struct strbuf seq_dir = STRBUF_INIT;
26ae337b
RR
23
24 strbuf_addf(&seq_dir, "%s", git_path(SEQ_DIR));
d596118d 25 remove_dir_recursively(&seq_dir, 0);
26ae337b 26 strbuf_release(&seq_dir);
26ae337b 27}
043a4492
RR
28
29static const char *action_name(const struct replay_opts *opts)
30{
31 return opts->action == REPLAY_REVERT ? "revert" : "cherry-pick";
32}
33
34static char *get_encoding(const char *message);
35
36struct commit_message {
37 char *parent_label;
38 const char *label;
39 const char *subject;
40 char *reencoded_message;
41 const char *message;
42};
43
44static int get_message(struct commit *commit, struct commit_message *out)
45{
46 const char *encoding;
47 const char *abbrev, *subject;
48 int abbrev_len, subject_len;
49 char *q;
50
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";
58
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;
66
67 abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
68 abbrev_len = strlen(abbrev);
69
70 subject_len = find_commit_subject(out->message, &subject);
71
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;
83}
84
85static void free_message(struct commit_message *msg)
86{
87 free(msg->parent_label);
88 free(msg->reencoded_message);
89}
90
91static char *get_encoding(const char *message)
92{
93 const char *p = message, *eol;
94
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;
102 }
103 p = eol;
104 if (*p == '\n')
105 p++;
106 }
107 return NULL;
108}
109
110static void write_cherry_pick_head(struct commit *commit, const char *pseudoref)
111{
112 const char *filename;
113 int fd;
114 struct strbuf buf = STRBUF_INIT;
115
116 strbuf_addf(&buf, "%s\n", sha1_to_hex(commit->object.sha1));
117
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);
125}
126
ed727b19 127static void print_advice(int show_hint, struct replay_opts *opts)
043a4492
RR
128{
129 char *msg = getenv("GIT_CHERRY_PICK_HELP");
130
131 if (msg) {
132 fprintf(stderr, "%s\n", msg);
133 /*
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
137 */
138 unlink(git_path("CHERRY_PICK_HEAD"));
139 return;
140 }
141
ed727b19
PH
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'"));
150 }
043a4492
RR
151}
152
153static void write_message(struct strbuf *msgbuf, const char *filename)
154{
155 static struct lock_file msg_file;
156
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);
164}
165
166static struct tree *empty_tree(void)
167{
168 return lookup_tree((const unsigned char *)EMPTY_TREE_SHA1_BIN);
169}
170
171static int error_dirty_index(struct replay_opts *opts)
172{
173 if (read_cache_unmerged())
174 return error_resolve_conflict(action_name(opts));
175
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."));
181
182 if (advice_commit_before_merge)
183 advise(_("Commit your changes or stash them to proceed."));
184 return -1;
185}
186
187static int fast_forward_to(const unsigned char *to, const unsigned char *from)
188{
189 struct ref_lock *ref_lock;
190
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");
196}
197
198static 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)
202{
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;
208
209 index_fd = hold_locked_index(&index_lock, 1);
210
211 read_cache();
212
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)";
217
218 head_tree = parse_tree_indirect(head);
219 next_tree = next ? next->tree : empty_tree();
220 base_tree = base ? base->tree : empty_tree();
221
222 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
223 parse_merge_opt(&o, *xopt);
224
225 clean = merge_trees(&o,
226 head_tree,
227 next_tree, base_tree, &result);
228
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);
235
236 if (!clean) {
237 int i;
238 strbuf_addstr(msgbuf, "\nConflicts:\n\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++;
248 }
249 }
250 }
251
252 return !clean;
253}
254
b27cfb0d
NH
255static int is_index_unchanged(void)
256{
257 unsigned char head_sha1[20];
258 struct commit *head_commit;
259
260 if (!resolve_ref_unsafe("HEAD", head_sha1, 1, NULL))
261 return error(_("Could not resolve HEAD commit\n"));
262
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));
267
268 if (!active_cache_tree)
269 active_cache_tree = cache_tree();
270
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"));
275
276 return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.sha1);
277}
278
043a4492
RR
279/*
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.
285 */
286static int run_git_commit(const char *defmsg, struct replay_opts *opts)
287{
b27cfb0d
NH
288 struct argv_array array;
289 int rc;
290
291 argv_array_init(&array);
292 argv_array_push(&array, "commit");
293 argv_array_push(&array, "-n");
043a4492 294
043a4492 295 if (opts->signoff)
b27cfb0d 296 argv_array_push(&array, "-s");
043a4492 297 if (!opts->edit) {
b27cfb0d
NH
298 argv_array_push(&array, "-F");
299 argv_array_push(&array, defmsg);
043a4492 300 }
b27cfb0d 301
df478b74 302 if (opts->allow_empty)
b27cfb0d 303 argv_array_push(&array, "--allow-empty");
df478b74 304
b27cfb0d
NH
305 rc = run_command_v_opt(array.argv, RUN_GIT_CMD);
306 argv_array_clear(&array);
307 return rc;
308}
309
310static int is_original_commit_empty(struct commit *commit)
311{
312 const unsigned char *ptree_sha1;
313
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 */
325 }
043a4492 326
b27cfb0d 327 return !hashcmp(ptree_sha1, commit->tree->object.sha1);
043a4492
RR
328}
329
330static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
331{
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;
b27cfb0d
NH
339 int empty_commit;
340 int index_unchanged;
043a4492
RR
341
342 if (opts->no_commit) {
343 /*
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.
348 */
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);
356 }
357 discard_cache();
358
359 if (!commit->parents) {
360 parent = NULL;
361 }
362 else if (commit->parents->next) {
363 /* Reverting or cherry-picking a merge commit */
364 int cnt;
365 struct commit_list *p;
366
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));
370
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;
384
385 if (opts->allow_ff && parent && !hashcmp(parent->object.sha1, head))
386 return fast_forward_to(commit->object.sha1, head);
387
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));
393
394 if (get_message(commit, &msg) != 0)
395 return error(_("Cannot get commit message for %s"),
396 sha1_to_hex(commit->object.sha1));
397
398 /*
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.
403 */
404
405 defmsg = git_pathdup("MERGE_MSG");
406
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));
416
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));
420 }
421 strbuf_addstr(&msgbuf, ".\n");
422 } else {
423 const char *p;
424
425 base = parent;
426 base_label = msg.parent_label;
427 next = commit;
428 next_label = msg.label;
429
430 /*
431 * Append the commit log message to msgbuf; it starts
432 * after the tree, parent, author, committer
433 * information followed by "\n\n".
434 */
435 p = strstr(msg.message, "\n\n");
436 if (p) {
437 p += 2;
438 strbuf_addstr(&msgbuf, p);
439 }
440
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");
445 }
446 }
447
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;
455
456 write_message(&msgbuf, defmsg);
457
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);
464 }
465
b27cfb0d
NH
466 empty_commit = is_original_commit_empty(commit);
467 if (empty_commit < 0)
468 return empty_commit;
469
043a4492
RR
470 /*
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.
475 */
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");
480
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);
ed727b19 487 print_advice(res == 1, opts);
043a4492
RR
488 rerere(opts->allow_rerere_auto);
489 } else {
b27cfb0d
NH
490 index_unchanged = is_index_unchanged();
491 /*
492 * If index_unchanged is less than 0, that indicates we either
493 * couldn't parse HEAD or the index, so error out here.
494 */
495 if (index_unchanged < 0)
496 return index_unchanged;
497
498 if (!empty_commit && !opts->keep_redundant_commits && index_unchanged)
499 /*
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
506 */
507 return 0;
508
043a4492
RR
509 if (!opts->no_commit)
510 res = run_git_commit(defmsg, opts);
511 }
512
513 free_message(&msg);
514 free(defmsg);
515
516 return res;
517}
518
519static void prepare_revs(struct replay_opts *opts)
520{
521 if (opts->action != REPLAY_REVERT)
522 opts->revs->reverse ^= 1;
523
524 if (prepare_revision_walk(opts->revs))
525 die(_("revision walk setup failed"));
526
527 if (!opts->revs->commits)
528 die(_("empty commit set passed"));
529}
530
531static void read_and_refresh_cache(struct replay_opts *opts)
532{
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));
542 }
543 rollback_lock_file(&index_lock);
544}
545
546/*
547 * Append a commit to the end of the commit_list.
548 *
549 * next starts by pointing to the variable that holds the head of an
550 * empty commit_list, and is updated to point to the "next" field of
551 * the last item on the list as new commits are appended.
552 *
553 * Usage example:
554 *
555 * struct commit_list *list;
556 * struct commit_list **next = &list;
557 *
558 * next = commit_list_append(c1, next);
559 * next = commit_list_append(c2, next);
560 * assert(commit_list_count(list) == 2);
561 * return list;
562 */
563static struct commit_list **commit_list_append(struct commit *commit,
564 struct commit_list **next)
565{
566 struct commit_list *new = xmalloc(sizeof(struct commit_list));
567 new->item = commit;
568 *next = new;
569 new->next = NULL;
570 return &new->next;
571}
572
573static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
574 struct replay_opts *opts)
575{
576 struct commit_list *cur = NULL;
577 const char *sha1_abbrev = NULL;
578 const char *action_str = opts->action == REPLAY_REVERT ? "revert" : "pick";
579 const char *subject;
580 int subject_len;
581
582 for (cur = todo_list; cur; cur = cur->next) {
583 sha1_abbrev = find_unique_abbrev(cur->item->object.sha1, DEFAULT_ABBREV);
584 subject_len = find_commit_subject(cur->item->buffer, &subject);
585 strbuf_addf(buf, "%s %s %.*s\n", action_str, sha1_abbrev,
586 subject_len, subject);
587 }
588 return 0;
589}
590
591static struct commit *parse_insn_line(char *bol, char *eol, struct replay_opts *opts)
592{
593 unsigned char commit_sha1[20];
594 enum replay_action action;
595 char *end_of_object_name;
596 int saved, status, padding;
597
598 if (!prefixcmp(bol, "pick")) {
599 action = REPLAY_PICK;
600 bol += strlen("pick");
601 } else if (!prefixcmp(bol, "revert")) {
602 action = REPLAY_REVERT;
603 bol += strlen("revert");
604 } else
605 return NULL;
606
607 /* Eat up extra spaces/ tabs before object name */
608 padding = strspn(bol, " \t");
609 if (!padding)
610 return NULL;
611 bol += padding;
612
613 end_of_object_name = bol + strcspn(bol, " \t\n");
614 saved = *end_of_object_name;
615 *end_of_object_name = '\0';
616 status = get_sha1(bol, commit_sha1);
617 *end_of_object_name = saved;
618
619 /*
620 * Verify that the action matches up with the one in
621 * opts; we don't support arbitrary instructions
622 */
623 if (action != opts->action) {
624 const char *action_str;
625 action_str = action == REPLAY_REVERT ? "revert" : "cherry-pick";
626 error(_("Cannot %s during a %s"), action_str, action_name(opts));
627 return NULL;
628 }
629
630 if (status < 0)
631 return NULL;
632
633 return lookup_commit_reference(commit_sha1);
634}
635
636static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
637 struct replay_opts *opts)
638{
639 struct commit_list **next = todo_list;
640 struct commit *commit;
641 char *p = buf;
642 int i;
643
644 for (i = 1; *p; i++) {
645 char *eol = strchrnul(p, '\n');
646 commit = parse_insn_line(p, eol, opts);
647 if (!commit)
648 return error(_("Could not parse line %d."), i);
649 next = commit_list_append(commit, next);
650 p = *eol ? eol + 1 : eol;
651 }
652 if (!*todo_list)
653 return error(_("No commits parsed."));
654 return 0;
655}
656
657static void read_populate_todo(struct commit_list **todo_list,
658 struct replay_opts *opts)
659{
660 const char *todo_file = git_path(SEQ_TODO_FILE);
661 struct strbuf buf = STRBUF_INIT;
662 int fd, res;
663
664 fd = open(todo_file, O_RDONLY);
665 if (fd < 0)
666 die_errno(_("Could not open %s"), todo_file);
667 if (strbuf_read(&buf, fd, 0) < 0) {
668 close(fd);
669 strbuf_release(&buf);
670 die(_("Could not read %s."), todo_file);
671 }
672 close(fd);
673
674 res = parse_insn_buffer(buf.buf, todo_list, opts);
675 strbuf_release(&buf);
676 if (res)
677 die(_("Unusable instruction sheet: %s"), todo_file);
678}
679
680static int populate_opts_cb(const char *key, const char *value, void *data)
681{
682 struct replay_opts *opts = data;
683 int error_flag = 1;
684
685 if (!value)
686 error_flag = 0;
687 else if (!strcmp(key, "options.no-commit"))
688 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
689 else if (!strcmp(key, "options.edit"))
690 opts->edit = git_config_bool_or_int(key, value, &error_flag);
691 else if (!strcmp(key, "options.signoff"))
692 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
693 else if (!strcmp(key, "options.record-origin"))
694 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
695 else if (!strcmp(key, "options.allow-ff"))
696 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
697 else if (!strcmp(key, "options.mainline"))
698 opts->mainline = git_config_int(key, value);
699 else if (!strcmp(key, "options.strategy"))
700 git_config_string(&opts->strategy, key, value);
701 else if (!strcmp(key, "options.strategy-option")) {
702 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
703 opts->xopts[opts->xopts_nr++] = xstrdup(value);
704 } else
705 return error(_("Invalid key: %s"), key);
706
707 if (!error_flag)
708 return error(_("Invalid value for %s: %s"), key, value);
709
710 return 0;
711}
712
713static void read_populate_opts(struct replay_opts **opts_ptr)
714{
715 const char *opts_file = git_path(SEQ_OPTS_FILE);
716
717 if (!file_exists(opts_file))
718 return;
719 if (git_config_from_file(populate_opts_cb, opts_file, *opts_ptr) < 0)
720 die(_("Malformed options sheet: %s"), opts_file);
721}
722
723static void walk_revs_populate_todo(struct commit_list **todo_list,
724 struct replay_opts *opts)
725{
726 struct commit *commit;
727 struct commit_list **next;
728
729 prepare_revs(opts);
730
731 next = todo_list;
732 while ((commit = get_revision(opts->revs)))
733 next = commit_list_append(commit, next);
734}
735
736static int create_seq_dir(void)
737{
738 const char *seq_dir = git_path(SEQ_DIR);
739
740 if (file_exists(seq_dir)) {
741 error(_("a cherry-pick or revert is already in progress"));
742 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
743 return -1;
744 }
745 else if (mkdir(seq_dir, 0777) < 0)
746 die_errno(_("Could not create sequencer directory %s"), seq_dir);
747 return 0;
748}
749
750static void save_head(const char *head)
751{
752 const char *head_file = git_path(SEQ_HEAD_FILE);
753 static struct lock_file head_lock;
754 struct strbuf buf = STRBUF_INIT;
755 int fd;
756
757 fd = hold_lock_file_for_update(&head_lock, head_file, LOCK_DIE_ON_ERROR);
758 strbuf_addf(&buf, "%s\n", head);
759 if (write_in_full(fd, buf.buf, buf.len) < 0)
760 die_errno(_("Could not write to %s"), head_file);
761 if (commit_lock_file(&head_lock) < 0)
762 die(_("Error wrapping up %s."), head_file);
763}
764
765static int reset_for_rollback(const unsigned char *sha1)
766{
767 const char *argv[4]; /* reset --merge <arg> + NULL */
768 argv[0] = "reset";
769 argv[1] = "--merge";
770 argv[2] = sha1_to_hex(sha1);
771 argv[3] = NULL;
772 return run_command_v_opt(argv, RUN_GIT_CMD);
773}
774
775static int rollback_single_pick(void)
776{
777 unsigned char head_sha1[20];
778
779 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
780 !file_exists(git_path("REVERT_HEAD")))
781 return error(_("no cherry-pick or revert in progress"));
782 if (read_ref_full("HEAD", head_sha1, 0, NULL))
783 return error(_("cannot resolve HEAD"));
784 if (is_null_sha1(head_sha1))
785 return error(_("cannot abort from a branch yet to be born"));
786 return reset_for_rollback(head_sha1);
787}
788
789static int sequencer_rollback(struct replay_opts *opts)
790{
791 const char *filename;
792 FILE *f;
793 unsigned char sha1[20];
794 struct strbuf buf = STRBUF_INIT;
795
796 filename = git_path(SEQ_HEAD_FILE);
797 f = fopen(filename, "r");
798 if (!f && errno == ENOENT) {
799 /*
800 * There is no multiple-cherry-pick in progress.
801 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
802 * a single-cherry-pick in progress, abort that.
803 */
804 return rollback_single_pick();
805 }
806 if (!f)
807 return error(_("cannot open %s: %s"), filename,
808 strerror(errno));
809 if (strbuf_getline(&buf, f, '\n')) {
810 error(_("cannot read %s: %s"), filename, ferror(f) ?
811 strerror(errno) : _("unexpected end of file"));
812 fclose(f);
813 goto fail;
814 }
815 fclose(f);
816 if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
817 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
818 filename);
819 goto fail;
820 }
821 if (reset_for_rollback(sha1))
822 goto fail;
823 remove_sequencer_state();
824 strbuf_release(&buf);
825 return 0;
826fail:
827 strbuf_release(&buf);
828 return -1;
829}
830
831static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
832{
833 const char *todo_file = git_path(SEQ_TODO_FILE);
834 static struct lock_file todo_lock;
835 struct strbuf buf = STRBUF_INIT;
836 int fd;
837
838 fd = hold_lock_file_for_update(&todo_lock, todo_file, LOCK_DIE_ON_ERROR);
839 if (format_todo(&buf, todo_list, opts) < 0)
840 die(_("Could not format %s."), todo_file);
841 if (write_in_full(fd, buf.buf, buf.len) < 0) {
842 strbuf_release(&buf);
843 die_errno(_("Could not write to %s"), todo_file);
844 }
845 if (commit_lock_file(&todo_lock) < 0) {
846 strbuf_release(&buf);
847 die(_("Error wrapping up %s."), todo_file);
848 }
849 strbuf_release(&buf);
850}
851
852static void save_opts(struct replay_opts *opts)
853{
854 const char *opts_file = git_path(SEQ_OPTS_FILE);
855
856 if (opts->no_commit)
857 git_config_set_in_file(opts_file, "options.no-commit", "true");
858 if (opts->edit)
859 git_config_set_in_file(opts_file, "options.edit", "true");
860 if (opts->signoff)
861 git_config_set_in_file(opts_file, "options.signoff", "true");
862 if (opts->record_origin)
863 git_config_set_in_file(opts_file, "options.record-origin", "true");
864 if (opts->allow_ff)
865 git_config_set_in_file(opts_file, "options.allow-ff", "true");
866 if (opts->mainline) {
867 struct strbuf buf = STRBUF_INIT;
868 strbuf_addf(&buf, "%d", opts->mainline);
869 git_config_set_in_file(opts_file, "options.mainline", buf.buf);
870 strbuf_release(&buf);
871 }
872 if (opts->strategy)
873 git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
874 if (opts->xopts) {
875 int i;
876 for (i = 0; i < opts->xopts_nr; i++)
877 git_config_set_multivar_in_file(opts_file,
878 "options.strategy-option",
879 opts->xopts[i], "^$", 0);
880 }
881}
882
883static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
884{
885 struct commit_list *cur;
886 int res;
887
888 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
889 if (opts->allow_ff)
890 assert(!(opts->signoff || opts->no_commit ||
891 opts->record_origin || opts->edit));
892 read_and_refresh_cache(opts);
893
894 for (cur = todo_list; cur; cur = cur->next) {
895 save_todo(cur, opts);
896 res = do_pick_commit(cur->item, opts);
897 if (res)
898 return res;
899 }
900
901 /*
902 * Sequence of picks finished successfully; cleanup by
903 * removing the .git/sequencer directory
904 */
905 remove_sequencer_state();
906 return 0;
907}
908
909static int continue_single_pick(void)
910{
911 const char *argv[] = { "commit", NULL };
912
913 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
914 !file_exists(git_path("REVERT_HEAD")))
915 return error(_("no cherry-pick or revert in progress"));
916 return run_command_v_opt(argv, RUN_GIT_CMD);
917}
918
919static int sequencer_continue(struct replay_opts *opts)
920{
921 struct commit_list *todo_list = NULL;
922
923 if (!file_exists(git_path(SEQ_TODO_FILE)))
924 return continue_single_pick();
925 read_populate_opts(&opts);
926 read_populate_todo(&todo_list, opts);
927
928 /* Verify that the conflict has been resolved */
929 if (file_exists(git_path("CHERRY_PICK_HEAD")) ||
930 file_exists(git_path("REVERT_HEAD"))) {
931 int ret = continue_single_pick();
932 if (ret)
933 return ret;
934 }
935 if (index_differs_from("HEAD", 0))
936 return error_dirty_index(opts);
937 todo_list = todo_list->next;
938 return pick_commits(todo_list, opts);
939}
940
941static int single_pick(struct commit *cmit, struct replay_opts *opts)
942{
943 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
944 return do_pick_commit(cmit, opts);
945}
946
947int sequencer_pick_revisions(struct replay_opts *opts)
948{
949 struct commit_list *todo_list = NULL;
950 unsigned char sha1[20];
951
952 if (opts->subcommand == REPLAY_NONE)
953 assert(opts->revs);
954
955 read_and_refresh_cache(opts);
956
957 /*
958 * Decide what to do depending on the arguments; a fresh
959 * cherry-pick should be handled differently from an existing
960 * one that is being continued
961 */
962 if (opts->subcommand == REPLAY_REMOVE_STATE) {
963 remove_sequencer_state();
964 return 0;
965 }
966 if (opts->subcommand == REPLAY_ROLLBACK)
967 return sequencer_rollback(opts);
968 if (opts->subcommand == REPLAY_CONTINUE)
969 return sequencer_continue(opts);
970
971 /*
972 * If we were called as "git cherry-pick <commit>", just
973 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
974 * REVERT_HEAD, and don't touch the sequencer state.
975 * This means it is possible to cherry-pick in the middle
976 * of a cherry-pick sequence.
977 */
978 if (opts->revs->cmdline.nr == 1 &&
979 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
980 opts->revs->no_walk &&
981 !opts->revs->cmdline.rev->flags) {
982 struct commit *cmit;
983 if (prepare_revision_walk(opts->revs))
984 die(_("revision walk setup failed"));
985 cmit = get_revision(opts->revs);
986 if (!cmit || get_revision(opts->revs))
987 die("BUG: expected exactly one commit from walk");
988 return single_pick(cmit, opts);
989 }
990
991 /*
992 * Start a new cherry-pick/ revert sequence; but
993 * first, make sure that an existing one isn't in
994 * progress
995 */
996
997 walk_revs_populate_todo(&todo_list, opts);
998 if (create_seq_dir() < 0)
999 return -1;
1000 if (get_sha1("HEAD", sha1)) {
1001 if (opts->action == REPLAY_REVERT)
1002 return error(_("Can't revert as initial commit"));
1003 return error(_("Can't cherry-pick into empty head"));
1004 }
1005 save_head(sha1_to_hex(sha1));
1006 save_opts(opts);
1007 return pick_commits(todo_list, opts);
1008}