]> git.ipfire.org Git - thirdparty/git.git/blame - sequencer.c
sequencer: introduce a helper to read files written by scripts
[thirdparty/git.git] / sequencer.c
CommitLineData
26ae337b 1#include "cache.h"
697cc8ef 2#include "lockfile.h"
26ae337b 3#include "sequencer.h"
26ae337b 4#include "dir.h"
043a4492
RR
5#include "object.h"
6#include "commit.h"
7#include "tag.h"
8#include "run-command.h"
9#include "exec_cmd.h"
10#include "utf8.h"
11#include "cache-tree.h"
12#include "diff.h"
13#include "revision.h"
14#include "rerere.h"
15#include "merge-recursive.h"
16#include "refs.h"
b27cfb0d 17#include "argv-array.h"
043a4492
RR
18
19#define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
26ae337b 20
5ed75e2a 21const char sign_off_header[] = "Signed-off-by: ";
cd650a4e 22static const char cherry_picked_prefix[] = "(cherry picked from commit ";
5ed75e2a 23
8a2a0f53
JS
24GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
25
26static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
27static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
28static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
f932729c 29
b5a67045
JS
30/*
31 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
32 * GIT_AUTHOR_DATE that will be used for the commit that is currently
33 * being rebased.
34 */
35static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
36
37/* We will introduce the 'interactive rebase' mode later */
38static inline int is_rebase_i(const struct replay_opts *opts)
39{
40 return 0;
41}
42
285abf56
JS
43static const char *get_dir(const struct replay_opts *opts)
44{
45 return git_path_seq_dir();
46}
47
c0246501
JS
48static const char *get_todo_path(const struct replay_opts *opts)
49{
50 return git_path_todo_file();
51}
52
b971e04f
BC
53static int is_rfc2822_line(const char *buf, int len)
54{
55 int i;
56
57 for (i = 0; i < len; i++) {
58 int ch = buf[i];
59 if (ch == ':')
60 return 1;
61 if (!isalnum(ch) && ch != '-')
62 break;
63 }
64
65 return 0;
66}
67
68static int is_cherry_picked_from_line(const char *buf, int len)
69{
70 /*
71 * We only care that it looks roughly like (cherry picked from ...)
72 */
73 return len > strlen(cherry_picked_prefix) + 1 &&
59556548 74 starts_with(buf, cherry_picked_prefix) && buf[len - 1] == ')';
b971e04f
BC
75}
76
bab4d109
BC
77/*
78 * Returns 0 for non-conforming footer
79 * Returns 1 for conforming footer
80 * Returns 2 when sob exists within conforming footer
81 * Returns 3 when sob exists within conforming footer as last entry
82 */
83static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
84 int ignore_footer)
b971e04f
BC
85{
86 char prev;
87 int i, k;
88 int len = sb->len - ignore_footer;
89 const char *buf = sb->buf;
bab4d109 90 int found_sob = 0;
b971e04f
BC
91
92 /* footer must end with newline */
93 if (!len || buf[len - 1] != '\n')
94 return 0;
95
96 prev = '\0';
97 for (i = len - 1; i > 0; i--) {
98 char ch = buf[i];
99 if (prev == '\n' && ch == '\n') /* paragraph break */
100 break;
101 prev = ch;
102 }
103
104 /* require at least one blank line */
105 if (prev != '\n' || buf[i] != '\n')
106 return 0;
107
108 /* advance to start of last paragraph */
109 while (i < len - 1 && buf[i] == '\n')
110 i++;
111
112 for (; i < len; i = k) {
bab4d109
BC
113 int found_rfc2822;
114
b971e04f
BC
115 for (k = i; k < len && buf[k] != '\n'; k++)
116 ; /* do nothing */
117 k++;
118
bab4d109
BC
119 found_rfc2822 = is_rfc2822_line(buf + i, k - i - 1);
120 if (found_rfc2822 && sob &&
121 !strncmp(buf + i, sob->buf, sob->len))
122 found_sob = k;
123
124 if (!(found_rfc2822 ||
125 is_cherry_picked_from_line(buf + i, k - i - 1)))
b971e04f
BC
126 return 0;
127 }
bab4d109
BC
128 if (found_sob == i)
129 return 3;
130 if (found_sob)
131 return 2;
b971e04f
BC
132 return 1;
133}
5ed75e2a 134
2863584f 135int sequencer_remove_state(struct replay_opts *opts)
26ae337b 136{
285abf56 137 struct strbuf dir = STRBUF_INIT;
03a4e260
JS
138 int i;
139
140 free(opts->gpg_sign);
141 free(opts->strategy);
142 for (i = 0; i < opts->xopts_nr; i++)
143 free(opts->xopts[i]);
144 free(opts->xopts);
26ae337b 145
285abf56
JS
146 strbuf_addf(&dir, "%s", get_dir(opts));
147 remove_dir_recursively(&dir, 0);
148 strbuf_release(&dir);
2863584f
JS
149
150 return 0;
26ae337b 151}
043a4492
RR
152
153static const char *action_name(const struct replay_opts *opts)
154{
155 return opts->action == REPLAY_REVERT ? "revert" : "cherry-pick";
156}
157
043a4492
RR
158struct commit_message {
159 char *parent_label;
7b35eaf8
JK
160 char *label;
161 char *subject;
043a4492
RR
162 const char *message;
163};
164
39755964
JS
165static const char *short_commit_name(struct commit *commit)
166{
167 return find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV);
168}
169
043a4492
RR
170static int get_message(struct commit *commit, struct commit_message *out)
171{
043a4492 172 const char *abbrev, *subject;
7b35eaf8 173 int subject_len;
043a4492 174
7b35eaf8 175 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
39755964 176 abbrev = short_commit_name(commit);
043a4492
RR
177
178 subject_len = find_commit_subject(out->message, &subject);
179
7b35eaf8
JK
180 out->subject = xmemdupz(subject, subject_len);
181 out->label = xstrfmt("%s... %s", abbrev, out->subject);
182 out->parent_label = xstrfmt("parent of %s", out->label);
183
043a4492
RR
184 return 0;
185}
186
d74a4e57 187static void free_message(struct commit *commit, struct commit_message *msg)
043a4492
RR
188{
189 free(msg->parent_label);
7b35eaf8
JK
190 free(msg->label);
191 free(msg->subject);
b66103c3 192 unuse_commit_buffer(commit, msg->message);
043a4492
RR
193}
194
ed727b19 195static void print_advice(int show_hint, struct replay_opts *opts)
043a4492
RR
196{
197 char *msg = getenv("GIT_CHERRY_PICK_HELP");
198
199 if (msg) {
200 fprintf(stderr, "%s\n", msg);
201 /*
41ccfdd9 202 * A conflict has occurred but the porcelain
043a4492
RR
203 * (typically rebase --interactive) wants to take care
204 * of the commit itself so remove CHERRY_PICK_HEAD
205 */
f932729c 206 unlink(git_path_cherry_pick_head());
043a4492
RR
207 return;
208 }
209
ed727b19
PH
210 if (show_hint) {
211 if (opts->no_commit)
212 advise(_("after resolving the conflicts, mark the corrected paths\n"
213 "with 'git add <paths>' or 'git rm <paths>'"));
214 else
215 advise(_("after resolving the conflicts, mark the corrected paths\n"
216 "with 'git add <paths>' or 'git rm <paths>'\n"
217 "and commit the result with 'git commit'"));
218 }
043a4492
RR
219}
220
4ef3d8f0 221static int write_message(struct strbuf *msgbuf, const char *filename)
043a4492
RR
222{
223 static struct lock_file msg_file;
224
4ef3d8f0
JS
225 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
226 if (msg_fd < 0)
227 return error_errno(_("Could not lock '%s'"), filename);
043a4492 228 if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
4ef3d8f0 229 return error_errno(_("Could not write to %s"), filename);
043a4492
RR
230 strbuf_release(msgbuf);
231 if (commit_lock_file(&msg_file) < 0)
4ef3d8f0
JS
232 return error(_("Error wrapping up %s."), filename);
233
234 return 0;
043a4492
RR
235}
236
1dfc84e9
JS
237/*
238 * Reads a file that was presumably written by a shell script, i.e. with an
239 * end-of-line marker that needs to be stripped.
240 *
241 * Note that only the last end-of-line marker is stripped, consistent with the
242 * behavior of "$(cat path)" in a shell script.
243 *
244 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
245 */
246static int read_oneliner(struct strbuf *buf,
247 const char *path, int skip_if_empty)
248{
249 int orig_len = buf->len;
250
251 if (!file_exists(path))
252 return 0;
253
254 if (strbuf_read_file(buf, path, 0) < 0) {
255 warning_errno(_("could not read '%s'"), path);
256 return 0;
257 }
258
259 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
260 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
261 --buf->len;
262 buf->buf[buf->len] = '\0';
263 }
264
265 if (skip_if_empty && buf->len == orig_len)
266 return 0;
267
268 return 1;
269}
270
043a4492
RR
271static struct tree *empty_tree(void)
272{
cba595bd 273 return lookup_tree(EMPTY_TREE_SHA1_BIN);
043a4492
RR
274}
275
276static int error_dirty_index(struct replay_opts *opts)
277{
278 if (read_cache_unmerged())
279 return error_resolve_conflict(action_name(opts));
280
e635d5ce
JS
281 error(_("Your local changes would be overwritten by %s."),
282 action_name(opts));
043a4492
RR
283
284 if (advice_commit_before_merge)
285 advise(_("Commit your changes or stash them to proceed."));
286 return -1;
287}
288
334ae397 289static int fast_forward_to(const unsigned char *to, const unsigned char *from,
eb4be1cb 290 int unborn, struct replay_opts *opts)
043a4492 291{
d668d16c 292 struct ref_transaction *transaction;
eb4be1cb 293 struct strbuf sb = STRBUF_INIT;
d668d16c 294 struct strbuf err = STRBUF_INIT;
043a4492
RR
295
296 read_cache();
db699a8a 297 if (checkout_fast_forward(from, to, 1))
0e408fc3 298 return -1; /* the callee should have complained already */
651ab9f5 299
e8d7c390 300 strbuf_addf(&sb, _("%s: fast-forward"), action_name(opts));
d668d16c
RS
301
302 transaction = ref_transaction_begin(&err);
303 if (!transaction ||
304 ref_transaction_update(transaction, "HEAD",
305 to, unborn ? null_sha1 : from,
1d147bdf 306 0, sb.buf, &err) ||
db7516ab 307 ref_transaction_commit(transaction, &err)) {
d668d16c
RS
308 ref_transaction_free(transaction);
309 error("%s", err.buf);
310 strbuf_release(&sb);
311 strbuf_release(&err);
312 return -1;
313 }
651ab9f5 314
eb4be1cb 315 strbuf_release(&sb);
d668d16c
RS
316 strbuf_release(&err);
317 ref_transaction_free(transaction);
318 return 0;
043a4492
RR
319}
320
75c961b7
JH
321void append_conflicts_hint(struct strbuf *msgbuf)
322{
323 int i;
324
261f315b
JH
325 strbuf_addch(msgbuf, '\n');
326 strbuf_commented_addf(msgbuf, "Conflicts:\n");
75c961b7
JH
327 for (i = 0; i < active_nr;) {
328 const struct cache_entry *ce = active_cache[i++];
329 if (ce_stage(ce)) {
261f315b 330 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
75c961b7
JH
331 while (i < active_nr && !strcmp(ce->name,
332 active_cache[i]->name))
333 i++;
334 }
335 }
336}
337
043a4492
RR
338static int do_recursive_merge(struct commit *base, struct commit *next,
339 const char *base_label, const char *next_label,
340 unsigned char *head, struct strbuf *msgbuf,
341 struct replay_opts *opts)
342{
343 struct merge_options o;
344 struct tree *result, *next_tree, *base_tree, *head_tree;
03b86647 345 int clean;
03a4e260 346 char **xopt;
043a4492
RR
347 static struct lock_file index_lock;
348
03b86647 349 hold_locked_index(&index_lock, 1);
043a4492
RR
350
351 read_cache();
352
353 init_merge_options(&o);
354 o.ancestor = base ? base_label : "(empty tree)";
355 o.branch1 = "HEAD";
356 o.branch2 = next ? next_label : "(empty tree)";
357
358 head_tree = parse_tree_indirect(head);
359 next_tree = next ? next->tree : empty_tree();
360 base_tree = base ? base->tree : empty_tree();
361
362 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
363 parse_merge_opt(&o, *xopt);
364
365 clean = merge_trees(&o,
366 head_tree,
367 next_tree, base_tree, &result);
548009c0 368 strbuf_release(&o.obuf);
f241ff0d
JS
369 if (clean < 0)
370 return clean;
043a4492
RR
371
372 if (active_cache_changed &&
03b86647 373 write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
043a4492 374 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
c527b55e
JS
375 return error(_("%s: Unable to write new index file"),
376 action_name(opts));
043a4492
RR
377 rollback_lock_file(&index_lock);
378
5ed75e2a 379 if (opts->signoff)
bab4d109 380 append_signoff(msgbuf, 0, 0);
5ed75e2a 381
75c961b7
JH
382 if (!clean)
383 append_conflicts_hint(msgbuf);
043a4492
RR
384
385 return !clean;
386}
387
b27cfb0d
NH
388static int is_index_unchanged(void)
389{
390 unsigned char head_sha1[20];
391 struct commit *head_commit;
392
7695d118 393 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))
b27cfb0d
NH
394 return error(_("Could not resolve HEAD commit\n"));
395
396 head_commit = lookup_commit(head_sha1);
4b580061
NH
397
398 /*
399 * If head_commit is NULL, check_commit, called from
400 * lookup_commit, would have indicated that head_commit is not
401 * a commit object already. parse_commit() will return failure
402 * without further complaints in such a case. Otherwise, if
403 * the commit is invalid, parse_commit() will complain. So
404 * there is nothing for us to say here. Just return failure.
405 */
406 if (parse_commit(head_commit))
407 return -1;
b27cfb0d
NH
408
409 if (!active_cache_tree)
410 active_cache_tree = cache_tree();
411
412 if (!cache_tree_fully_valid(active_cache_tree))
d0cfc3e8 413 if (cache_tree_update(&the_index, 0))
b27cfb0d
NH
414 return error(_("Unable to update cache tree\n"));
415
ed1c9977 416 return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.oid.hash);
b27cfb0d
NH
417}
418
b5a67045
JS
419/*
420 * Read the author-script file into an environment block, ready for use in
421 * run_command(), that can be free()d afterwards.
422 */
423static char **read_author_script(void)
424{
425 struct strbuf script = STRBUF_INIT;
426 int i, count = 0;
427 char *p, *p2, **env;
428 size_t env_size;
429
430 if (strbuf_read_file(&script, rebase_path_author_script(), 256) <= 0)
431 return NULL;
432
433 for (p = script.buf; *p; p++)
434 if (skip_prefix(p, "'\\\\''", (const char **)&p2))
435 strbuf_splice(&script, p - script.buf, p2 - p, "'", 1);
436 else if (*p == '\'')
437 strbuf_splice(&script, p-- - script.buf, 1, "", 0);
438 else if (*p == '\n') {
439 *p = '\0';
440 count++;
441 }
442
443 env_size = (count + 1) * sizeof(*env);
444 strbuf_grow(&script, env_size);
445 memmove(script.buf + env_size, script.buf, script.len);
446 p = script.buf + env_size;
447 env = (char **)strbuf_detach(&script, NULL);
448
449 for (i = 0; i < count; i++) {
450 env[i] = p;
451 p += strlen(p) + 1;
452 }
453 env[count] = NULL;
454
455 return env;
456}
457
043a4492
RR
458/*
459 * If we are cherry-pick, and if the merge did not result in
460 * hand-editing, we will hit this commit and inherit the original
461 * author date and name.
b5a67045 462 *
043a4492
RR
463 * If we are revert, or if our cherry-pick results in a hand merge,
464 * we had better say that the current user is responsible for that.
b5a67045
JS
465 *
466 * An exception is when run_git_commit() is called during an
467 * interactive rebase: in that case, we will want to retain the
468 * author metadata.
043a4492 469 */
ac2b0e8f
JH
470static int run_git_commit(const char *defmsg, struct replay_opts *opts,
471 int allow_empty)
043a4492 472{
b5a67045 473 char **env = NULL;
b27cfb0d
NH
474 struct argv_array array;
475 int rc;
17d65f03 476 const char *value;
b27cfb0d 477
b5a67045
JS
478 if (is_rebase_i(opts)) {
479 env = read_author_script();
480 if (!env)
481 return error("You have staged changes in your working "
482 "tree. If these changes are meant to be\n"
483 "squashed into the previous commit, run:\n\n"
484 " git commit --amend $gpg_sign_opt_quoted\n\n"
485 "If they are meant to go into a new commit, "
486 "run:\n\n"
487 " git commit $gpg_sign_opt_quoted\n\n"
488 "In both cases, once you're done, continue "
489 "with:\n\n"
490 " git rebase --continue\n");
491 }
492
b27cfb0d
NH
493 argv_array_init(&array);
494 argv_array_push(&array, "commit");
495 argv_array_push(&array, "-n");
043a4492 496
3bdd5522
JK
497 if (opts->gpg_sign)
498 argv_array_pushf(&array, "-S%s", opts->gpg_sign);
043a4492 499 if (opts->signoff)
b27cfb0d 500 argv_array_push(&array, "-s");
b5a67045
JS
501 if (defmsg)
502 argv_array_pushl(&array, "-F", defmsg, NULL);
503 if (opts->edit)
504 argv_array_push(&array, "-e");
505 else if (!opts->signoff && !opts->record_origin &&
506 git_config_get_value("commit.cleanup", &value))
507 argv_array_push(&array, "--cleanup=verbatim");
b27cfb0d 508
ac2b0e8f 509 if (allow_empty)
b27cfb0d 510 argv_array_push(&array, "--allow-empty");
df478b74 511
4bee9584
CW
512 if (opts->allow_empty_message)
513 argv_array_push(&array, "--allow-empty-message");
514
b5a67045
JS
515 rc = run_command_v_opt_cd_env(array.argv, RUN_GIT_CMD, NULL,
516 (const char *const *)env);
b27cfb0d 517 argv_array_clear(&array);
b5a67045
JS
518 free(env);
519
b27cfb0d
NH
520 return rc;
521}
522
523static int is_original_commit_empty(struct commit *commit)
524{
525 const unsigned char *ptree_sha1;
526
527 if (parse_commit(commit))
528 return error(_("Could not parse commit %s\n"),
f2fd0760 529 oid_to_hex(&commit->object.oid));
b27cfb0d
NH
530 if (commit->parents) {
531 struct commit *parent = commit->parents->item;
532 if (parse_commit(parent))
533 return error(_("Could not parse parent commit %s\n"),
f2fd0760 534 oid_to_hex(&parent->object.oid));
ed1c9977 535 ptree_sha1 = parent->tree->object.oid.hash;
b27cfb0d
NH
536 } else {
537 ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
043a4492 538 }
043a4492 539
ed1c9977 540 return !hashcmp(ptree_sha1, commit->tree->object.oid.hash);
043a4492
RR
541}
542
ac2b0e8f
JH
543/*
544 * Do we run "git commit" with "--allow-empty"?
545 */
546static int allow_empty(struct replay_opts *opts, struct commit *commit)
547{
548 int index_unchanged, empty_commit;
549
550 /*
551 * Three cases:
552 *
553 * (1) we do not allow empty at all and error out.
554 *
555 * (2) we allow ones that were initially empty, but
556 * forbid the ones that become empty;
557 *
558 * (3) we allow both.
559 */
560 if (!opts->allow_empty)
561 return 0; /* let "git commit" barf as necessary */
562
563 index_unchanged = is_index_unchanged();
564 if (index_unchanged < 0)
565 return index_unchanged;
566 if (!index_unchanged)
567 return 0; /* we do not have to say --allow-empty */
568
569 if (opts->keep_redundant_commits)
570 return 1;
571
572 empty_commit = is_original_commit_empty(commit);
573 if (empty_commit < 0)
574 return empty_commit;
575 if (!empty_commit)
576 return 0;
577 else
578 return 1;
579}
580
004fefa7
JS
581enum todo_command {
582 TODO_PICK = 0,
583 TODO_REVERT
584};
585
586static const char *todo_command_strings[] = {
587 "pick",
588 "revert"
589};
590
591static const char *command_to_string(const enum todo_command command)
592{
593 if (command < ARRAY_SIZE(todo_command_strings))
594 return todo_command_strings[command];
595 die("Unknown command: %d", command);
596}
597
598
599static int do_pick_commit(enum todo_command command, struct commit *commit,
600 struct replay_opts *opts)
043a4492
RR
601{
602 unsigned char head[20];
603 struct commit *base, *next, *parent;
604 const char *base_label, *next_label;
d74a4e57 605 struct commit_message msg = { NULL, NULL, NULL, NULL };
043a4492 606 struct strbuf msgbuf = STRBUF_INIT;
c8d1351d 607 int res, unborn = 0, allow;
043a4492
RR
608
609 if (opts->no_commit) {
610 /*
611 * We do not intend to commit immediately. We just want to
612 * merge the differences in, so let's compute the tree
613 * that represents the "current" state for merge-recursive
614 * to work on.
615 */
616 if (write_cache_as_tree(head, 0, NULL))
f74087f6 617 return error(_("Your index file is unmerged."));
043a4492 618 } else {
334ae397
MZ
619 unborn = get_sha1("HEAD", head);
620 if (unborn)
621 hashcpy(head, EMPTY_TREE_SHA1_BIN);
622 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD", 0))
043a4492
RR
623 return error_dirty_index(opts);
624 }
625 discard_cache();
626
627 if (!commit->parents) {
628 parent = NULL;
629 }
630 else if (commit->parents->next) {
631 /* Reverting or cherry-picking a merge commit */
632 int cnt;
633 struct commit_list *p;
634
635 if (!opts->mainline)
636 return error(_("Commit %s is a merge but no -m option was given."),
f2fd0760 637 oid_to_hex(&commit->object.oid));
043a4492
RR
638
639 for (cnt = 1, p = commit->parents;
640 cnt != opts->mainline && p;
641 cnt++)
642 p = p->next;
643 if (cnt != opts->mainline || !p)
644 return error(_("Commit %s does not have parent %d"),
f2fd0760 645 oid_to_hex(&commit->object.oid), opts->mainline);
043a4492
RR
646 parent = p->item;
647 } else if (0 < opts->mainline)
648 return error(_("Mainline was specified but commit %s is not a merge."),
f2fd0760 649 oid_to_hex(&commit->object.oid));
043a4492
RR
650 else
651 parent = commit->parents->item;
652
334ae397 653 if (opts->allow_ff &&
ed1c9977 654 ((parent && !hashcmp(parent->object.oid.hash, head)) ||
334ae397 655 (!parent && unborn)))
ed1c9977 656 return fast_forward_to(commit->object.oid.hash, head, unborn, opts);
043a4492
RR
657
658 if (parent && parse_commit(parent) < 0)
004fefa7
JS
659 /* TRANSLATORS: The first %s will be a "todo" command like
660 "revert" or "pick", the second %s a SHA1. */
043a4492 661 return error(_("%s: cannot parse parent commit %s"),
004fefa7
JS
662 command_to_string(command),
663 oid_to_hex(&parent->object.oid));
043a4492
RR
664
665 if (get_message(commit, &msg) != 0)
666 return error(_("Cannot get commit message for %s"),
f2fd0760 667 oid_to_hex(&commit->object.oid));
043a4492
RR
668
669 /*
670 * "commit" is an existing commit. We would want to apply
671 * the difference it introduces since its first parent "prev"
672 * on top of the current HEAD if we are cherry-pick. Or the
673 * reverse of it if we are revert.
674 */
675
004fefa7 676 if (command == TODO_REVERT) {
043a4492
RR
677 base = commit;
678 base_label = msg.label;
679 next = parent;
680 next_label = msg.parent_label;
681 strbuf_addstr(&msgbuf, "Revert \"");
682 strbuf_addstr(&msgbuf, msg.subject);
683 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
f2fd0760 684 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
043a4492
RR
685
686 if (commit->parents && commit->parents->next) {
687 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
f2fd0760 688 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
043a4492
RR
689 }
690 strbuf_addstr(&msgbuf, ".\n");
691 } else {
692 const char *p;
693
694 base = parent;
695 base_label = msg.parent_label;
696 next = commit;
697 next_label = msg.label;
698
699 /*
700 * Append the commit log message to msgbuf; it starts
701 * after the tree, parent, author, committer
702 * information followed by "\n\n".
703 */
704 p = strstr(msg.message, "\n\n");
88ef402f
JS
705 if (p)
706 strbuf_addstr(&msgbuf, skip_blank_lines(p + 2));
043a4492
RR
707
708 if (opts->record_origin) {
bab4d109 709 if (!has_conforming_footer(&msgbuf, NULL, 0))
b971e04f 710 strbuf_addch(&msgbuf, '\n');
cd650a4e 711 strbuf_addstr(&msgbuf, cherry_picked_prefix);
f2fd0760 712 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
043a4492
RR
713 strbuf_addstr(&msgbuf, ")\n");
714 }
715 }
716
004fefa7 717 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
043a4492
RR
718 res = do_recursive_merge(base, next, base_label, next_label,
719 head, &msgbuf, opts);
f241ff0d
JS
720 if (res < 0)
721 return res;
4ef3d8f0 722 res |= write_message(&msgbuf, git_path_merge_msg());
043a4492
RR
723 } else {
724 struct commit_list *common = NULL;
725 struct commit_list *remotes = NULL;
726
4ef3d8f0 727 res = write_message(&msgbuf, git_path_merge_msg());
043a4492
RR
728
729 commit_list_insert(base, &common);
730 commit_list_insert(next, &remotes);
03a4e260
JS
731 res |= try_merge_command(opts->strategy,
732 opts->xopts_nr, (const char **)opts->xopts,
043a4492
RR
733 common, sha1_to_hex(head), remotes);
734 free_commit_list(common);
735 free_commit_list(remotes);
736 }
737
738 /*
739 * If the merge was clean or if it failed due to conflict, we write
740 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
741 * However, if the merge did not even start, then we don't want to
742 * write it at all.
743 */
004fefa7 744 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
dbfad033
JS
745 update_ref(NULL, "CHERRY_PICK_HEAD", commit->object.oid.hash, NULL,
746 REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
747 res = -1;
004fefa7 748 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
dbfad033
JS
749 update_ref(NULL, "REVERT_HEAD", commit->object.oid.hash, NULL,
750 REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
751 res = -1;
043a4492
RR
752
753 if (res) {
004fefa7 754 error(command == TODO_REVERT
043a4492
RR
755 ? _("could not revert %s... %s")
756 : _("could not apply %s... %s"),
39755964 757 short_commit_name(commit), msg.subject);
ed727b19 758 print_advice(res == 1, opts);
043a4492 759 rerere(opts->allow_rerere_auto);
c8d1351d 760 goto leave;
043a4492
RR
761 }
762
c8d1351d 763 allow = allow_empty(opts, commit);
706728a3
FC
764 if (allow < 0) {
765 res = allow;
766 goto leave;
767 }
c8d1351d 768 if (!opts->no_commit)
b5a67045
JS
769 res = run_git_commit(opts->edit ? NULL : git_path_merge_msg(),
770 opts, allow);
c8d1351d
FC
771
772leave:
d74a4e57 773 free_message(commit, &msg);
043a4492
RR
774
775 return res;
776}
777
c3e8618c 778static int prepare_revs(struct replay_opts *opts)
043a4492 779{
a73e22e9
MZ
780 /*
781 * picking (but not reverting) ranges (but not individual revisions)
782 * should be done in reverse
783 */
784 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
043a4492
RR
785 opts->revs->reverse ^= 1;
786
787 if (prepare_revision_walk(opts->revs))
c3e8618c 788 return error(_("revision walk setup failed"));
043a4492
RR
789
790 if (!opts->revs->commits)
c3e8618c
JS
791 return error(_("empty commit set passed"));
792 return 0;
043a4492
RR
793}
794
0d9c6dc9 795static int read_and_refresh_cache(struct replay_opts *opts)
043a4492
RR
796{
797 static struct lock_file index_lock;
798 int index_fd = hold_locked_index(&index_lock, 0);
49fb937e
JS
799 if (read_index_preload(&the_index, NULL) < 0) {
800 rollback_lock_file(&index_lock);
0d9c6dc9
JS
801 return error(_("git %s: failed to read the index"),
802 action_name(opts));
49fb937e 803 }
043a4492 804 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
33c297aa 805 if (the_index.cache_changed && index_fd >= 0) {
49fb937e
JS
806 if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK)) {
807 rollback_lock_file(&index_lock);
0d9c6dc9
JS
808 return error(_("git %s: failed to refresh the index"),
809 action_name(opts));
49fb937e 810 }
043a4492
RR
811 }
812 rollback_lock_file(&index_lock);
0d9c6dc9 813 return 0;
043a4492
RR
814}
815
004fefa7
JS
816struct todo_item {
817 enum todo_command command;
818 struct commit *commit;
c22f7dfb
JS
819 const char *arg;
820 int arg_len;
004fefa7
JS
821 size_t offset_in_buf;
822};
823
824struct todo_list {
825 struct strbuf buf;
826 struct todo_item *items;
827 int nr, alloc, current;
828};
829
830#define TODO_LIST_INIT { STRBUF_INIT }
831
832static void todo_list_release(struct todo_list *todo_list)
043a4492 833{
004fefa7
JS
834 strbuf_release(&todo_list->buf);
835 free(todo_list->items);
836 todo_list->items = NULL;
837 todo_list->nr = todo_list->alloc = 0;
838}
043a4492 839
004fefa7
JS
840static struct todo_item *append_new_todo(struct todo_list *todo_list)
841{
842 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
843 return todo_list->items + todo_list->nr++;
043a4492
RR
844}
845
004fefa7 846static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
043a4492
RR
847{
848 unsigned char commit_sha1[20];
043a4492 849 char *end_of_object_name;
004fefa7
JS
850 int i, saved, status, padding;
851
852 for (i = 0; i < ARRAY_SIZE(todo_command_strings); i++)
853 if (skip_prefix(bol, todo_command_strings[i], &bol)) {
854 item->command = i;
855 break;
856 }
857 if (i >= ARRAY_SIZE(todo_command_strings))
858 return -1;
043a4492
RR
859
860 /* Eat up extra spaces/ tabs before object name */
861 padding = strspn(bol, " \t");
862 if (!padding)
004fefa7 863 return -1;
043a4492
RR
864 bol += padding;
865
004fefa7 866 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
043a4492
RR
867 saved = *end_of_object_name;
868 *end_of_object_name = '\0';
869 status = get_sha1(bol, commit_sha1);
870 *end_of_object_name = saved;
871
c22f7dfb
JS
872 item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
873 item->arg_len = (int)(eol - item->arg);
874
043a4492 875 if (status < 0)
004fefa7 876 return -1;
043a4492 877
004fefa7
JS
878 item->commit = lookup_commit_reference(commit_sha1);
879 return !item->commit;
043a4492
RR
880}
881
004fefa7 882static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
043a4492 883{
004fefa7
JS
884 struct todo_item *item;
885 char *p = buf, *next_p;
886 int i, res = 0;
043a4492 887
004fefa7 888 for (i = 1; *p; i++, p = next_p) {
043a4492 889 char *eol = strchrnul(p, '\n');
004fefa7
JS
890
891 next_p = *eol ? eol + 1 /* skip LF */ : eol;
892
6307041d
JS
893 if (p != eol && eol[-1] == '\r')
894 eol--; /* strip Carriage Return */
895
004fefa7
JS
896 item = append_new_todo(todo_list);
897 item->offset_in_buf = p - todo_list->buf.buf;
898 if (parse_insn_line(item, p, eol)) {
899 res = error(_("Invalid line %d: %.*s"),
900 i, (int)(eol - p), p);
901 item->command = -1;
902 }
043a4492 903 }
004fefa7 904 if (!todo_list->nr)
043a4492 905 return error(_("No commits parsed."));
004fefa7 906 return res;
043a4492
RR
907}
908
004fefa7 909static int read_populate_todo(struct todo_list *todo_list,
043a4492
RR
910 struct replay_opts *opts)
911{
c0246501 912 const char *todo_file = get_todo_path(opts);
043a4492
RR
913 int fd, res;
914
004fefa7 915 strbuf_reset(&todo_list->buf);
c0246501 916 fd = open(todo_file, O_RDONLY);
043a4492 917 if (fd < 0)
c0246501 918 return error_errno(_("Could not open %s"), todo_file);
004fefa7 919 if (strbuf_read(&todo_list->buf, fd, 0) < 0) {
043a4492 920 close(fd);
c0246501 921 return error(_("Could not read %s."), todo_file);
043a4492
RR
922 }
923 close(fd);
924
004fefa7
JS
925 res = parse_insn_buffer(todo_list->buf.buf, todo_list);
926 if (!res) {
927 enum todo_command valid =
928 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
929 int i;
930
931 for (i = 0; i < todo_list->nr; i++)
932 if (valid == todo_list->items[i].command)
933 continue;
934 else if (valid == TODO_PICK)
935 return error(_("Cannot cherry-pick during a revert."));
936 else
937 return error(_("Cannot revert during a cherry-pick."));
938 }
939
043a4492 940 if (res)
c0246501 941 return error(_("Unusable instruction sheet: %s"), todo_file);
0ae42a03 942 return 0;
043a4492
RR
943}
944
03a4e260
JS
945static int git_config_string_dup(char **dest,
946 const char *var, const char *value)
947{
948 if (!value)
949 return config_error_nonbool(var);
950 free(*dest);
951 *dest = xstrdup(value);
952 return 0;
953}
954
043a4492
RR
955static int populate_opts_cb(const char *key, const char *value, void *data)
956{
957 struct replay_opts *opts = data;
958 int error_flag = 1;
959
960 if (!value)
961 error_flag = 0;
962 else if (!strcmp(key, "options.no-commit"))
963 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
964 else if (!strcmp(key, "options.edit"))
965 opts->edit = git_config_bool_or_int(key, value, &error_flag);
966 else if (!strcmp(key, "options.signoff"))
967 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
968 else if (!strcmp(key, "options.record-origin"))
969 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
970 else if (!strcmp(key, "options.allow-ff"))
971 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
972 else if (!strcmp(key, "options.mainline"))
973 opts->mainline = git_config_int(key, value);
974 else if (!strcmp(key, "options.strategy"))
03a4e260 975 git_config_string_dup(&opts->strategy, key, value);
3253553e 976 else if (!strcmp(key, "options.gpg-sign"))
03a4e260 977 git_config_string_dup(&opts->gpg_sign, key, value);
043a4492
RR
978 else if (!strcmp(key, "options.strategy-option")) {
979 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
980 opts->xopts[opts->xopts_nr++] = xstrdup(value);
981 } else
982 return error(_("Invalid key: %s"), key);
983
984 if (!error_flag)
985 return error(_("Invalid value for %s: %s"), key, value);
986
987 return 0;
988}
989
5adf9bdc 990static int read_populate_opts(struct replay_opts *opts)
043a4492 991{
b5a67045
JS
992 if (is_rebase_i(opts))
993 return 0;
994
f932729c 995 if (!file_exists(git_path_opts_file()))
0d00da7b
JS
996 return 0;
997 /*
998 * The function git_parse_source(), called from git_config_from_file(),
999 * may die() in case of a syntactically incorrect file. We do not care
1000 * about this case, though, because we wrote that file ourselves, so we
1001 * are pretty certain that it is syntactically correct.
1002 */
5adf9bdc 1003 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
0d00da7b
JS
1004 return error(_("Malformed options sheet: %s"),
1005 git_path_opts_file());
1006 return 0;
043a4492
RR
1007}
1008
004fefa7 1009static int walk_revs_populate_todo(struct todo_list *todo_list,
043a4492
RR
1010 struct replay_opts *opts)
1011{
004fefa7
JS
1012 enum todo_command command = opts->action == REPLAY_PICK ?
1013 TODO_PICK : TODO_REVERT;
1014 const char *command_string = todo_command_strings[command];
043a4492 1015 struct commit *commit;
043a4492 1016
34b0528b
JS
1017 if (prepare_revs(opts))
1018 return -1;
043a4492 1019
004fefa7
JS
1020 while ((commit = get_revision(opts->revs))) {
1021 struct todo_item *item = append_new_todo(todo_list);
1022 const char *commit_buffer = get_commit_buffer(commit, NULL);
1023 const char *subject;
1024 int subject_len;
1025
1026 item->command = command;
1027 item->commit = commit;
c22f7dfb
JS
1028 item->arg = NULL;
1029 item->arg_len = 0;
004fefa7
JS
1030 item->offset_in_buf = todo_list->buf.len;
1031 subject_len = find_commit_subject(commit_buffer, &subject);
1032 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
1033 short_commit_name(commit), subject_len, subject);
1034 unuse_commit_buffer(commit, commit_buffer);
1035 }
34b0528b 1036 return 0;
043a4492
RR
1037}
1038
1039static int create_seq_dir(void)
1040{
f932729c 1041 if (file_exists(git_path_seq_dir())) {
043a4492
RR
1042 error(_("a cherry-pick or revert is already in progress"));
1043 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
1044 return -1;
1045 }
f932729c 1046 else if (mkdir(git_path_seq_dir(), 0777) < 0)
f6e82b0d
JS
1047 return error_errno(_("Could not create sequencer directory %s"),
1048 git_path_seq_dir());
043a4492
RR
1049 return 0;
1050}
1051
311fd397 1052static int save_head(const char *head)
043a4492 1053{
043a4492
RR
1054 static struct lock_file head_lock;
1055 struct strbuf buf = STRBUF_INIT;
1056 int fd;
1057
311fd397
JS
1058 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
1059 if (fd < 0) {
1060 rollback_lock_file(&head_lock);
1061 return error_errno(_("Could not lock HEAD"));
1062 }
043a4492 1063 strbuf_addf(&buf, "%s\n", head);
311fd397
JS
1064 if (write_in_full(fd, buf.buf, buf.len) < 0) {
1065 rollback_lock_file(&head_lock);
1066 return error_errno(_("Could not write to %s"),
1067 git_path_head_file());
1068 }
1069 if (commit_lock_file(&head_lock) < 0) {
1070 rollback_lock_file(&head_lock);
1071 return error(_("Error wrapping up %s."), git_path_head_file());
1072 }
1073 return 0;
043a4492
RR
1074}
1075
1076static int reset_for_rollback(const unsigned char *sha1)
1077{
1078 const char *argv[4]; /* reset --merge <arg> + NULL */
1079 argv[0] = "reset";
1080 argv[1] = "--merge";
1081 argv[2] = sha1_to_hex(sha1);
1082 argv[3] = NULL;
1083 return run_command_v_opt(argv, RUN_GIT_CMD);
1084}
1085
1086static int rollback_single_pick(void)
1087{
1088 unsigned char head_sha1[20];
1089
f932729c
JK
1090 if (!file_exists(git_path_cherry_pick_head()) &&
1091 !file_exists(git_path_revert_head()))
043a4492 1092 return error(_("no cherry-pick or revert in progress"));
7695d118 1093 if (read_ref_full("HEAD", 0, head_sha1, NULL))
043a4492
RR
1094 return error(_("cannot resolve HEAD"));
1095 if (is_null_sha1(head_sha1))
1096 return error(_("cannot abort from a branch yet to be born"));
1097 return reset_for_rollback(head_sha1);
1098}
1099
2863584f 1100int sequencer_rollback(struct replay_opts *opts)
043a4492 1101{
043a4492
RR
1102 FILE *f;
1103 unsigned char sha1[20];
1104 struct strbuf buf = STRBUF_INIT;
1105
f932729c 1106 f = fopen(git_path_head_file(), "r");
043a4492
RR
1107 if (!f && errno == ENOENT) {
1108 /*
1109 * There is no multiple-cherry-pick in progress.
1110 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
1111 * a single-cherry-pick in progress, abort that.
1112 */
1113 return rollback_single_pick();
1114 }
1115 if (!f)
6c979c74 1116 return error_errno(_("cannot open %s"), git_path_head_file());
8f309aeb 1117 if (strbuf_getline_lf(&buf, f)) {
f932729c
JK
1118 error(_("cannot read %s: %s"), git_path_head_file(),
1119 ferror(f) ? strerror(errno) : _("unexpected end of file"));
043a4492
RR
1120 fclose(f);
1121 goto fail;
1122 }
1123 fclose(f);
1124 if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
1125 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
f932729c 1126 git_path_head_file());
043a4492
RR
1127 goto fail;
1128 }
0f974e21
MG
1129 if (is_null_sha1(sha1)) {
1130 error(_("cannot abort from a branch yet to be born"));
1131 goto fail;
1132 }
043a4492
RR
1133 if (reset_for_rollback(sha1))
1134 goto fail;
043a4492 1135 strbuf_release(&buf);
2863584f 1136 return sequencer_remove_state(opts);
043a4492
RR
1137fail:
1138 strbuf_release(&buf);
1139 return -1;
1140}
1141
004fefa7 1142static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
043a4492 1143{
043a4492 1144 static struct lock_file todo_lock;
004fefa7
JS
1145 const char *todo_path = get_todo_path(opts);
1146 int next = todo_list->current, offset, fd;
043a4492 1147
004fefa7 1148 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
221675de 1149 if (fd < 0)
004fefa7
JS
1150 return error_errno(_("Could not lock '%s'"), todo_path);
1151 offset = next < todo_list->nr ?
1152 todo_list->items[next].offset_in_buf : todo_list->buf.len;
1153 if (write_in_full(fd, todo_list->buf.buf + offset,
1154 todo_list->buf.len - offset) < 0)
1155 return error_errno(_("Could not write to '%s'"), todo_path);
1156 if (commit_lock_file(&todo_lock) < 0)
1157 return error(_("Error wrapping up %s."), todo_path);
221675de 1158 return 0;
043a4492
RR
1159}
1160
88d5a271 1161static int save_opts(struct replay_opts *opts)
043a4492 1162{
f932729c 1163 const char *opts_file = git_path_opts_file();
88d5a271 1164 int res = 0;
043a4492
RR
1165
1166 if (opts->no_commit)
88d5a271 1167 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
043a4492 1168 if (opts->edit)
88d5a271 1169 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
043a4492 1170 if (opts->signoff)
88d5a271 1171 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
043a4492 1172 if (opts->record_origin)
88d5a271 1173 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
043a4492 1174 if (opts->allow_ff)
88d5a271 1175 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
043a4492
RR
1176 if (opts->mainline) {
1177 struct strbuf buf = STRBUF_INIT;
1178 strbuf_addf(&buf, "%d", opts->mainline);
88d5a271 1179 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
043a4492
RR
1180 strbuf_release(&buf);
1181 }
1182 if (opts->strategy)
88d5a271 1183 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
3253553e 1184 if (opts->gpg_sign)
88d5a271 1185 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
043a4492
RR
1186 if (opts->xopts) {
1187 int i;
1188 for (i = 0; i < opts->xopts_nr; i++)
88d5a271 1189 res |= git_config_set_multivar_in_file_gently(opts_file,
043a4492
RR
1190 "options.strategy-option",
1191 opts->xopts[i], "^$", 0);
1192 }
88d5a271 1193 return res;
043a4492
RR
1194}
1195
004fefa7 1196static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
043a4492 1197{
043a4492
RR
1198 int res;
1199
1200 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1201 if (opts->allow_ff)
1202 assert(!(opts->signoff || opts->no_commit ||
1203 opts->record_origin || opts->edit));
0d9c6dc9
JS
1204 if (read_and_refresh_cache(opts))
1205 return -1;
043a4492 1206
004fefa7
JS
1207 while (todo_list->current < todo_list->nr) {
1208 struct todo_item *item = todo_list->items + todo_list->current;
1209 if (save_todo(todo_list, opts))
221675de 1210 return -1;
004fefa7
JS
1211 res = do_pick_commit(item->command, item->commit, opts);
1212 todo_list->current++;
043a4492
RR
1213 if (res)
1214 return res;
1215 }
1216
1217 /*
1218 * Sequence of picks finished successfully; cleanup by
1219 * removing the .git/sequencer directory
1220 */
2863584f 1221 return sequencer_remove_state(opts);
043a4492
RR
1222}
1223
1224static int continue_single_pick(void)
1225{
1226 const char *argv[] = { "commit", NULL };
1227
f932729c
JK
1228 if (!file_exists(git_path_cherry_pick_head()) &&
1229 !file_exists(git_path_revert_head()))
043a4492
RR
1230 return error(_("no cherry-pick or revert in progress"));
1231 return run_command_v_opt(argv, RUN_GIT_CMD);
1232}
1233
2863584f 1234int sequencer_continue(struct replay_opts *opts)
043a4492 1235{
004fefa7
JS
1236 struct todo_list todo_list = TODO_LIST_INIT;
1237 int res;
043a4492 1238
2863584f
JS
1239 if (read_and_refresh_cache(opts))
1240 return -1;
1241
c0246501 1242 if (!file_exists(get_todo_path(opts)))
043a4492 1243 return continue_single_pick();
004fefa7 1244 if (read_populate_opts(opts))
0ae42a03 1245 return -1;
004fefa7
JS
1246 if ((res = read_populate_todo(&todo_list, opts)))
1247 goto release_todo_list;
043a4492
RR
1248
1249 /* Verify that the conflict has been resolved */
f932729c
JK
1250 if (file_exists(git_path_cherry_pick_head()) ||
1251 file_exists(git_path_revert_head())) {
004fefa7
JS
1252 res = continue_single_pick();
1253 if (res)
1254 goto release_todo_list;
043a4492 1255 }
004fefa7
JS
1256 if (index_differs_from("HEAD", 0)) {
1257 res = error_dirty_index(opts);
1258 goto release_todo_list;
1259 }
1260 todo_list.current++;
1261 res = pick_commits(&todo_list, opts);
1262release_todo_list:
1263 todo_list_release(&todo_list);
1264 return res;
043a4492
RR
1265}
1266
1267static int single_pick(struct commit *cmit, struct replay_opts *opts)
1268{
1269 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
004fefa7
JS
1270 return do_pick_commit(opts->action == REPLAY_PICK ?
1271 TODO_PICK : TODO_REVERT, cmit, opts);
043a4492
RR
1272}
1273
1274int sequencer_pick_revisions(struct replay_opts *opts)
1275{
004fefa7 1276 struct todo_list todo_list = TODO_LIST_INIT;
043a4492 1277 unsigned char sha1[20];
004fefa7 1278 int i, res;
043a4492 1279
2863584f 1280 assert(opts->revs);
0d9c6dc9
JS
1281 if (read_and_refresh_cache(opts))
1282 return -1;
043a4492 1283
21246dbb
MV
1284 for (i = 0; i < opts->revs->pending.nr; i++) {
1285 unsigned char sha1[20];
1286 const char *name = opts->revs->pending.objects[i].name;
1287
1288 /* This happens when using --stdin. */
1289 if (!strlen(name))
1290 continue;
1291
1292 if (!get_sha1(name, sha1)) {
7c0b0d8d
JH
1293 if (!lookup_commit_reference_gently(sha1, 1)) {
1294 enum object_type type = sha1_object_info(sha1, NULL);
b9b946d4
JS
1295 return error(_("%s: can't cherry-pick a %s"),
1296 name, typename(type));
7c0b0d8d 1297 }
21246dbb 1298 } else
b9b946d4 1299 return error(_("%s: bad revision"), name);
21246dbb
MV
1300 }
1301
043a4492
RR
1302 /*
1303 * If we were called as "git cherry-pick <commit>", just
1304 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
1305 * REVERT_HEAD, and don't touch the sequencer state.
1306 * This means it is possible to cherry-pick in the middle
1307 * of a cherry-pick sequence.
1308 */
1309 if (opts->revs->cmdline.nr == 1 &&
1310 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
1311 opts->revs->no_walk &&
1312 !opts->revs->cmdline.rev->flags) {
1313 struct commit *cmit;
1314 if (prepare_revision_walk(opts->revs))
b9b946d4 1315 return error(_("revision walk setup failed"));
043a4492
RR
1316 cmit = get_revision(opts->revs);
1317 if (!cmit || get_revision(opts->revs))
b9b946d4 1318 return error("BUG: expected exactly one commit from walk");
043a4492
RR
1319 return single_pick(cmit, opts);
1320 }
1321
1322 /*
1323 * Start a new cherry-pick/ revert sequence; but
1324 * first, make sure that an existing one isn't in
1325 * progress
1326 */
1327
34b0528b
JS
1328 if (walk_revs_populate_todo(&todo_list, opts) ||
1329 create_seq_dir() < 0)
043a4492 1330 return -1;
0f974e21
MG
1331 if (get_sha1("HEAD", sha1) && (opts->action == REPLAY_REVERT))
1332 return error(_("Can't revert as initial commit"));
311fd397
JS
1333 if (save_head(sha1_to_hex(sha1)))
1334 return -1;
88d5a271
JS
1335 if (save_opts(opts))
1336 return -1;
004fefa7
JS
1337 res = pick_commits(&todo_list, opts);
1338 todo_list_release(&todo_list);
1339 return res;
043a4492 1340}
5ed75e2a 1341
bab4d109 1342void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
5ed75e2a 1343{
bab4d109 1344 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
5ed75e2a 1345 struct strbuf sob = STRBUF_INIT;
bab4d109 1346 int has_footer;
5ed75e2a
MV
1347
1348 strbuf_addstr(&sob, sign_off_header);
1349 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
1350 getenv("GIT_COMMITTER_EMAIL")));
1351 strbuf_addch(&sob, '\n');
bab4d109
BC
1352
1353 /*
1354 * If the whole message buffer is equal to the sob, pretend that we
1355 * found a conforming footer with a matching sob
1356 */
1357 if (msgbuf->len - ignore_footer == sob.len &&
1358 !strncmp(msgbuf->buf, sob.buf, sob.len))
1359 has_footer = 3;
1360 else
1361 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
1362
33f2f9ab
BC
1363 if (!has_footer) {
1364 const char *append_newlines = NULL;
1365 size_t len = msgbuf->len - ignore_footer;
1366
8c613fd5
BC
1367 if (!len) {
1368 /*
1369 * The buffer is completely empty. Leave foom for
1370 * the title and body to be filled in by the user.
1371 */
33f2f9ab 1372 append_newlines = "\n\n";
8c613fd5
BC
1373 } else if (msgbuf->buf[len - 1] != '\n') {
1374 /*
1375 * Incomplete line. Complete the line and add a
1376 * blank one so that there is an empty line between
1377 * the message body and the sob.
1378 */
1379 append_newlines = "\n\n";
1380 } else if (len == 1) {
1381 /*
1382 * Buffer contains a single newline. Add another
1383 * so that we leave room for the title and body.
1384 */
1385 append_newlines = "\n";
1386 } else if (msgbuf->buf[len - 2] != '\n') {
1387 /*
1388 * Buffer ends with a single newline. Add another
1389 * so that there is an empty line between the message
1390 * body and the sob.
1391 */
33f2f9ab 1392 append_newlines = "\n";
8c613fd5 1393 } /* else, the buffer already ends with two newlines. */
33f2f9ab
BC
1394
1395 if (append_newlines)
1396 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1397 append_newlines, strlen(append_newlines));
5ed75e2a 1398 }
bab4d109
BC
1399
1400 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
1401 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1402 sob.buf, sob.len);
1403
5ed75e2a
MV
1404 strbuf_release(&sob);
1405}