]> git.ipfire.org Git - thirdparty/git.git/blob - sequencer.c
commit: move print_commit_summary() to libgit
[thirdparty/git.git] / sequencer.c
1 #include "cache.h"
2 #include "config.h"
3 #include "lockfile.h"
4 #include "dir.h"
5 #include "object.h"
6 #include "commit.h"
7 #include "sequencer.h"
8 #include "tag.h"
9 #include "run-command.h"
10 #include "exec_cmd.h"
11 #include "utf8.h"
12 #include "cache-tree.h"
13 #include "diff.h"
14 #include "revision.h"
15 #include "rerere.h"
16 #include "merge-recursive.h"
17 #include "refs.h"
18 #include "argv-array.h"
19 #include "quote.h"
20 #include "trailer.h"
21 #include "log-tree.h"
22 #include "wt-status.h"
23 #include "hashmap.h"
24 #include "notes-utils.h"
25 #include "sigchain.h"
26
27 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
28
29 const char sign_off_header[] = "Signed-off-by: ";
30 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
31
32 GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
33
34 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
35 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
36 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
37 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
38
39 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
40 /*
41 * The file containing rebase commands, comments, and empty lines.
42 * This file is created by "git rebase -i" then edited by the user. As
43 * the lines are processed, they are removed from the front of this
44 * file and written to the tail of 'done'.
45 */
46 static GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
47 /*
48 * The rebase command lines that have already been processed. A line
49 * is moved here when it is first handled, before any associated user
50 * actions.
51 */
52 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
53 /*
54 * The file to keep track of how many commands were already processed (e.g.
55 * for the prompt).
56 */
57 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum");
58 /*
59 * The file to keep track of how many commands are to be processed in total
60 * (e.g. for the prompt).
61 */
62 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end");
63 /*
64 * The commit message that is planned to be used for any changes that
65 * need to be committed following a user interaction.
66 */
67 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
68 /*
69 * The file into which is accumulated the suggested commit message for
70 * squash/fixup commands. When the first of a series of squash/fixups
71 * is seen, the file is created and the commit message from the
72 * previous commit and from the first squash/fixup commit are written
73 * to it. The commit message for each subsequent squash/fixup commit
74 * is appended to the file as it is processed.
75 *
76 * The first line of the file is of the form
77 * # This is a combination of $count commits.
78 * where $count is the number of commits whose messages have been
79 * written to the file so far (including the initial "pick" commit).
80 * Each time that a commit message is processed, this line is read and
81 * updated. It is deleted just before the combined commit is made.
82 */
83 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
84 /*
85 * If the current series of squash/fixups has not yet included a squash
86 * command, then this file exists and holds the commit message of the
87 * original "pick" commit. (If the series ends without a "squash"
88 * command, then this can be used as the commit message of the combined
89 * commit without opening the editor.)
90 */
91 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
92 /*
93 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
94 * GIT_AUTHOR_DATE that will be used for the commit that is currently
95 * being rebased.
96 */
97 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
98 /*
99 * When an "edit" rebase command is being processed, the SHA1 of the
100 * commit to be edited is recorded in this file. When "git rebase
101 * --continue" is executed, if there are any staged changes then they
102 * will be amended to the HEAD commit, but only provided the HEAD
103 * commit is still the commit to be edited. When any other rebase
104 * command is processed, this file is deleted.
105 */
106 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
107 /*
108 * When we stop at a given patch via the "edit" command, this file contains
109 * the abbreviated commit name of the corresponding patch.
110 */
111 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
112 /*
113 * For the post-rewrite hook, we make a list of rewritten commits and
114 * their new sha1s. The rewritten-pending list keeps the sha1s of
115 * commits that have been processed, but not committed yet,
116 * e.g. because they are waiting for a 'squash' command.
117 */
118 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
119 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
120 "rebase-merge/rewritten-pending")
121 /*
122 * The following files are written by git-rebase just after parsing the
123 * command-line (and are only consumed, not modified, by the sequencer).
124 */
125 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
126 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
127 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
128 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
129 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
130 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
131 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
132 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
133 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
134
135 static inline int is_rebase_i(const struct replay_opts *opts)
136 {
137 return opts->action == REPLAY_INTERACTIVE_REBASE;
138 }
139
140 static const char *get_dir(const struct replay_opts *opts)
141 {
142 if (is_rebase_i(opts))
143 return rebase_path();
144 return git_path_seq_dir();
145 }
146
147 static const char *get_todo_path(const struct replay_opts *opts)
148 {
149 if (is_rebase_i(opts))
150 return rebase_path_todo();
151 return git_path_todo_file();
152 }
153
154 /*
155 * Returns 0 for non-conforming footer
156 * Returns 1 for conforming footer
157 * Returns 2 when sob exists within conforming footer
158 * Returns 3 when sob exists within conforming footer as last entry
159 */
160 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
161 int ignore_footer)
162 {
163 struct trailer_info info;
164 int i;
165 int found_sob = 0, found_sob_last = 0;
166
167 trailer_info_get(&info, sb->buf);
168
169 if (info.trailer_start == info.trailer_end)
170 return 0;
171
172 for (i = 0; i < info.trailer_nr; i++)
173 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
174 found_sob = 1;
175 if (i == info.trailer_nr - 1)
176 found_sob_last = 1;
177 }
178
179 trailer_info_release(&info);
180
181 if (found_sob_last)
182 return 3;
183 if (found_sob)
184 return 2;
185 return 1;
186 }
187
188 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
189 {
190 static struct strbuf buf = STRBUF_INIT;
191
192 strbuf_reset(&buf);
193 if (opts->gpg_sign)
194 sq_quotef(&buf, "-S%s", opts->gpg_sign);
195 return buf.buf;
196 }
197
198 int sequencer_remove_state(struct replay_opts *opts)
199 {
200 struct strbuf dir = STRBUF_INIT;
201 int i;
202
203 free(opts->gpg_sign);
204 free(opts->strategy);
205 for (i = 0; i < opts->xopts_nr; i++)
206 free(opts->xopts[i]);
207 free(opts->xopts);
208
209 strbuf_addstr(&dir, get_dir(opts));
210 remove_dir_recursively(&dir, 0);
211 strbuf_release(&dir);
212
213 return 0;
214 }
215
216 static const char *action_name(const struct replay_opts *opts)
217 {
218 switch (opts->action) {
219 case REPLAY_REVERT:
220 return N_("revert");
221 case REPLAY_PICK:
222 return N_("cherry-pick");
223 case REPLAY_INTERACTIVE_REBASE:
224 return N_("rebase -i");
225 }
226 die(_("Unknown action: %d"), opts->action);
227 }
228
229 struct commit_message {
230 char *parent_label;
231 char *label;
232 char *subject;
233 const char *message;
234 };
235
236 static const char *short_commit_name(struct commit *commit)
237 {
238 return find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV);
239 }
240
241 static int get_message(struct commit *commit, struct commit_message *out)
242 {
243 const char *abbrev, *subject;
244 int subject_len;
245
246 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
247 abbrev = short_commit_name(commit);
248
249 subject_len = find_commit_subject(out->message, &subject);
250
251 out->subject = xmemdupz(subject, subject_len);
252 out->label = xstrfmt("%s... %s", abbrev, out->subject);
253 out->parent_label = xstrfmt("parent of %s", out->label);
254
255 return 0;
256 }
257
258 static void free_message(struct commit *commit, struct commit_message *msg)
259 {
260 free(msg->parent_label);
261 free(msg->label);
262 free(msg->subject);
263 unuse_commit_buffer(commit, msg->message);
264 }
265
266 static void print_advice(int show_hint, struct replay_opts *opts)
267 {
268 char *msg = getenv("GIT_CHERRY_PICK_HELP");
269
270 if (msg) {
271 fprintf(stderr, "%s\n", msg);
272 /*
273 * A conflict has occurred but the porcelain
274 * (typically rebase --interactive) wants to take care
275 * of the commit itself so remove CHERRY_PICK_HEAD
276 */
277 unlink(git_path_cherry_pick_head());
278 return;
279 }
280
281 if (show_hint) {
282 if (opts->no_commit)
283 advise(_("after resolving the conflicts, mark the corrected paths\n"
284 "with 'git add <paths>' or 'git rm <paths>'"));
285 else
286 advise(_("after resolving the conflicts, mark the corrected paths\n"
287 "with 'git add <paths>' or 'git rm <paths>'\n"
288 "and commit the result with 'git commit'"));
289 }
290 }
291
292 static int write_message(const void *buf, size_t len, const char *filename,
293 int append_eol)
294 {
295 static struct lock_file msg_file;
296
297 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
298 if (msg_fd < 0)
299 return error_errno(_("could not lock '%s'"), filename);
300 if (write_in_full(msg_fd, buf, len) < 0) {
301 rollback_lock_file(&msg_file);
302 return error_errno(_("could not write to '%s'"), filename);
303 }
304 if (append_eol && write(msg_fd, "\n", 1) < 0) {
305 rollback_lock_file(&msg_file);
306 return error_errno(_("could not write eol to '%s'"), filename);
307 }
308 if (commit_lock_file(&msg_file) < 0) {
309 rollback_lock_file(&msg_file);
310 return error(_("failed to finalize '%s'."), filename);
311 }
312
313 return 0;
314 }
315
316 /*
317 * Reads a file that was presumably written by a shell script, i.e. with an
318 * end-of-line marker that needs to be stripped.
319 *
320 * Note that only the last end-of-line marker is stripped, consistent with the
321 * behavior of "$(cat path)" in a shell script.
322 *
323 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
324 */
325 static int read_oneliner(struct strbuf *buf,
326 const char *path, int skip_if_empty)
327 {
328 int orig_len = buf->len;
329
330 if (!file_exists(path))
331 return 0;
332
333 if (strbuf_read_file(buf, path, 0) < 0) {
334 warning_errno(_("could not read '%s'"), path);
335 return 0;
336 }
337
338 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
339 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
340 --buf->len;
341 buf->buf[buf->len] = '\0';
342 }
343
344 if (skip_if_empty && buf->len == orig_len)
345 return 0;
346
347 return 1;
348 }
349
350 static struct tree *empty_tree(void)
351 {
352 return lookup_tree(&empty_tree_oid);
353 }
354
355 static int error_dirty_index(struct replay_opts *opts)
356 {
357 if (read_cache_unmerged())
358 return error_resolve_conflict(_(action_name(opts)));
359
360 error(_("your local changes would be overwritten by %s."),
361 _(action_name(opts)));
362
363 if (advice_commit_before_merge)
364 advise(_("commit your changes or stash them to proceed."));
365 return -1;
366 }
367
368 static void update_abort_safety_file(void)
369 {
370 struct object_id head;
371
372 /* Do nothing on a single-pick */
373 if (!file_exists(git_path_seq_dir()))
374 return;
375
376 if (!get_oid("HEAD", &head))
377 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
378 else
379 write_file(git_path_abort_safety_file(), "%s", "");
380 }
381
382 static int fast_forward_to(const struct object_id *to, const struct object_id *from,
383 int unborn, struct replay_opts *opts)
384 {
385 struct ref_transaction *transaction;
386 struct strbuf sb = STRBUF_INIT;
387 struct strbuf err = STRBUF_INIT;
388
389 read_cache();
390 if (checkout_fast_forward(from, to, 1))
391 return -1; /* the callee should have complained already */
392
393 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
394
395 transaction = ref_transaction_begin(&err);
396 if (!transaction ||
397 ref_transaction_update(transaction, "HEAD",
398 to, unborn ? &null_oid : from,
399 0, sb.buf, &err) ||
400 ref_transaction_commit(transaction, &err)) {
401 ref_transaction_free(transaction);
402 error("%s", err.buf);
403 strbuf_release(&sb);
404 strbuf_release(&err);
405 return -1;
406 }
407
408 strbuf_release(&sb);
409 strbuf_release(&err);
410 ref_transaction_free(transaction);
411 update_abort_safety_file();
412 return 0;
413 }
414
415 void append_conflicts_hint(struct strbuf *msgbuf)
416 {
417 int i;
418
419 strbuf_addch(msgbuf, '\n');
420 strbuf_commented_addf(msgbuf, "Conflicts:\n");
421 for (i = 0; i < active_nr;) {
422 const struct cache_entry *ce = active_cache[i++];
423 if (ce_stage(ce)) {
424 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
425 while (i < active_nr && !strcmp(ce->name,
426 active_cache[i]->name))
427 i++;
428 }
429 }
430 }
431
432 static int do_recursive_merge(struct commit *base, struct commit *next,
433 const char *base_label, const char *next_label,
434 struct object_id *head, struct strbuf *msgbuf,
435 struct replay_opts *opts)
436 {
437 struct merge_options o;
438 struct tree *result, *next_tree, *base_tree, *head_tree;
439 int clean;
440 char **xopt;
441 static struct lock_file index_lock;
442
443 hold_locked_index(&index_lock, LOCK_DIE_ON_ERROR);
444
445 read_cache();
446
447 init_merge_options(&o);
448 o.ancestor = base ? base_label : "(empty tree)";
449 o.branch1 = "HEAD";
450 o.branch2 = next ? next_label : "(empty tree)";
451 if (is_rebase_i(opts))
452 o.buffer_output = 2;
453
454 head_tree = parse_tree_indirect(head);
455 next_tree = next ? next->tree : empty_tree();
456 base_tree = base ? base->tree : empty_tree();
457
458 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
459 parse_merge_opt(&o, *xopt);
460
461 clean = merge_trees(&o,
462 head_tree,
463 next_tree, base_tree, &result);
464 if (is_rebase_i(opts) && clean <= 0)
465 fputs(o.obuf.buf, stdout);
466 strbuf_release(&o.obuf);
467 if (clean < 0)
468 return clean;
469
470 if (active_cache_changed &&
471 write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
472 /*
473 * TRANSLATORS: %s will be "revert", "cherry-pick" or
474 * "rebase -i".
475 */
476 return error(_("%s: Unable to write new index file"),
477 _(action_name(opts)));
478 rollback_lock_file(&index_lock);
479
480 if (opts->signoff)
481 append_signoff(msgbuf, 0, 0);
482
483 if (!clean)
484 append_conflicts_hint(msgbuf);
485
486 return !clean;
487 }
488
489 static int is_index_unchanged(void)
490 {
491 struct object_id head_oid;
492 struct commit *head_commit;
493
494 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
495 return error(_("could not resolve HEAD commit\n"));
496
497 head_commit = lookup_commit(&head_oid);
498
499 /*
500 * If head_commit is NULL, check_commit, called from
501 * lookup_commit, would have indicated that head_commit is not
502 * a commit object already. parse_commit() will return failure
503 * without further complaints in such a case. Otherwise, if
504 * the commit is invalid, parse_commit() will complain. So
505 * there is nothing for us to say here. Just return failure.
506 */
507 if (parse_commit(head_commit))
508 return -1;
509
510 if (!active_cache_tree)
511 active_cache_tree = cache_tree();
512
513 if (!cache_tree_fully_valid(active_cache_tree))
514 if (cache_tree_update(&the_index, 0))
515 return error(_("unable to update cache tree\n"));
516
517 return !oidcmp(&active_cache_tree->oid,
518 &head_commit->tree->object.oid);
519 }
520
521 static int write_author_script(const char *message)
522 {
523 struct strbuf buf = STRBUF_INIT;
524 const char *eol;
525 int res;
526
527 for (;;)
528 if (!*message || starts_with(message, "\n")) {
529 missing_author:
530 /* Missing 'author' line? */
531 unlink(rebase_path_author_script());
532 return 0;
533 } else if (skip_prefix(message, "author ", &message))
534 break;
535 else if ((eol = strchr(message, '\n')))
536 message = eol + 1;
537 else
538 goto missing_author;
539
540 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
541 while (*message && *message != '\n' && *message != '\r')
542 if (skip_prefix(message, " <", &message))
543 break;
544 else if (*message != '\'')
545 strbuf_addch(&buf, *(message++));
546 else
547 strbuf_addf(&buf, "'\\\\%c'", *(message++));
548 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
549 while (*message && *message != '\n' && *message != '\r')
550 if (skip_prefix(message, "> ", &message))
551 break;
552 else if (*message != '\'')
553 strbuf_addch(&buf, *(message++));
554 else
555 strbuf_addf(&buf, "'\\\\%c'", *(message++));
556 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
557 while (*message && *message != '\n' && *message != '\r')
558 if (*message != '\'')
559 strbuf_addch(&buf, *(message++));
560 else
561 strbuf_addf(&buf, "'\\\\%c'", *(message++));
562 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
563 strbuf_release(&buf);
564 return res;
565 }
566
567 /*
568 * Read a list of environment variable assignments (such as the author-script
569 * file) into an environment block. Returns -1 on error, 0 otherwise.
570 */
571 static int read_env_script(struct argv_array *env)
572 {
573 struct strbuf script = STRBUF_INIT;
574 int i, count = 0;
575 char *p, *p2;
576
577 if (strbuf_read_file(&script, rebase_path_author_script(), 256) <= 0)
578 return -1;
579
580 for (p = script.buf; *p; p++)
581 if (skip_prefix(p, "'\\\\''", (const char **)&p2))
582 strbuf_splice(&script, p - script.buf, p2 - p, "'", 1);
583 else if (*p == '\'')
584 strbuf_splice(&script, p-- - script.buf, 1, "", 0);
585 else if (*p == '\n') {
586 *p = '\0';
587 count++;
588 }
589
590 for (i = 0, p = script.buf; i < count; i++) {
591 argv_array_push(env, p);
592 p += strlen(p) + 1;
593 }
594
595 return 0;
596 }
597
598 static const char staged_changes_advice[] =
599 N_("you have staged changes in your working tree\n"
600 "If these changes are meant to be squashed into the previous commit, run:\n"
601 "\n"
602 " git commit --amend %s\n"
603 "\n"
604 "If they are meant to go into a new commit, run:\n"
605 "\n"
606 " git commit %s\n"
607 "\n"
608 "In both cases, once you're done, continue with:\n"
609 "\n"
610 " git rebase --continue\n");
611
612 #define ALLOW_EMPTY (1<<0)
613 #define EDIT_MSG (1<<1)
614 #define AMEND_MSG (1<<2)
615 #define CLEANUP_MSG (1<<3)
616 #define VERIFY_MSG (1<<4)
617
618 /*
619 * If we are cherry-pick, and if the merge did not result in
620 * hand-editing, we will hit this commit and inherit the original
621 * author date and name.
622 *
623 * If we are revert, or if our cherry-pick results in a hand merge,
624 * we had better say that the current user is responsible for that.
625 *
626 * An exception is when run_git_commit() is called during an
627 * interactive rebase: in that case, we will want to retain the
628 * author metadata.
629 */
630 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
631 unsigned int flags)
632 {
633 struct child_process cmd = CHILD_PROCESS_INIT;
634 const char *value;
635
636 cmd.git_cmd = 1;
637
638 if (is_rebase_i(opts)) {
639 if (!(flags & EDIT_MSG)) {
640 cmd.stdout_to_stderr = 1;
641 cmd.err = -1;
642 }
643
644 if (read_env_script(&cmd.env_array)) {
645 const char *gpg_opt = gpg_sign_opt_quoted(opts);
646
647 return error(_(staged_changes_advice),
648 gpg_opt, gpg_opt);
649 }
650 }
651
652 argv_array_push(&cmd.args, "commit");
653
654 if (!(flags & VERIFY_MSG))
655 argv_array_push(&cmd.args, "-n");
656 if ((flags & AMEND_MSG))
657 argv_array_push(&cmd.args, "--amend");
658 if (opts->gpg_sign)
659 argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
660 if (opts->signoff)
661 argv_array_push(&cmd.args, "-s");
662 if (defmsg)
663 argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
664 if ((flags & CLEANUP_MSG))
665 argv_array_push(&cmd.args, "--cleanup=strip");
666 if ((flags & EDIT_MSG))
667 argv_array_push(&cmd.args, "-e");
668 else if (!(flags & CLEANUP_MSG) &&
669 !opts->signoff && !opts->record_origin &&
670 git_config_get_value("commit.cleanup", &value))
671 argv_array_push(&cmd.args, "--cleanup=verbatim");
672
673 if ((flags & ALLOW_EMPTY))
674 argv_array_push(&cmd.args, "--allow-empty");
675
676 if (opts->allow_empty_message)
677 argv_array_push(&cmd.args, "--allow-empty-message");
678
679 if (cmd.err == -1) {
680 /* hide stderr on success */
681 struct strbuf buf = STRBUF_INIT;
682 int rc = pipe_command(&cmd,
683 NULL, 0,
684 /* stdout is already redirected */
685 NULL, 0,
686 &buf, 0);
687 if (rc)
688 fputs(buf.buf, stderr);
689 strbuf_release(&buf);
690 return rc;
691 }
692
693 return run_command(&cmd);
694 }
695
696 static int rest_is_empty(const struct strbuf *sb, int start)
697 {
698 int i, eol;
699 const char *nl;
700
701 /* Check if the rest is just whitespace and Signed-off-by's. */
702 for (i = start; i < sb->len; i++) {
703 nl = memchr(sb->buf + i, '\n', sb->len - i);
704 if (nl)
705 eol = nl - sb->buf;
706 else
707 eol = sb->len;
708
709 if (strlen(sign_off_header) <= eol - i &&
710 starts_with(sb->buf + i, sign_off_header)) {
711 i = eol;
712 continue;
713 }
714 while (i < eol)
715 if (!isspace(sb->buf[i++]))
716 return 0;
717 }
718
719 return 1;
720 }
721
722 /*
723 * Find out if the message in the strbuf contains only whitespace and
724 * Signed-off-by lines.
725 */
726 int message_is_empty(const struct strbuf *sb,
727 enum commit_msg_cleanup_mode cleanup_mode)
728 {
729 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
730 return 0;
731 return rest_is_empty(sb, 0);
732 }
733
734 /*
735 * See if the user edited the message in the editor or left what
736 * was in the template intact
737 */
738 int template_untouched(const struct strbuf *sb, const char *template_file,
739 enum commit_msg_cleanup_mode cleanup_mode)
740 {
741 struct strbuf tmpl = STRBUF_INIT;
742 const char *start;
743
744 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
745 return 0;
746
747 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
748 return 0;
749
750 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
751 if (!skip_prefix(sb->buf, tmpl.buf, &start))
752 start = sb->buf;
753 strbuf_release(&tmpl);
754 return rest_is_empty(sb, start - sb->buf);
755 }
756
757 int update_head_with_reflog(const struct commit *old_head,
758 const struct object_id *new_head,
759 const char *action, const struct strbuf *msg,
760 struct strbuf *err)
761 {
762 struct ref_transaction *transaction;
763 struct strbuf sb = STRBUF_INIT;
764 const char *nl;
765 int ret = 0;
766
767 if (action) {
768 strbuf_addstr(&sb, action);
769 strbuf_addstr(&sb, ": ");
770 }
771
772 nl = strchr(msg->buf, '\n');
773 if (nl) {
774 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
775 } else {
776 strbuf_addbuf(&sb, msg);
777 strbuf_addch(&sb, '\n');
778 }
779
780 transaction = ref_transaction_begin(err);
781 if (!transaction ||
782 ref_transaction_update(transaction, "HEAD", new_head,
783 old_head ? &old_head->object.oid : &null_oid,
784 0, sb.buf, err) ||
785 ref_transaction_commit(transaction, err)) {
786 ret = -1;
787 }
788 ref_transaction_free(transaction);
789 strbuf_release(&sb);
790
791 return ret;
792 }
793
794 static int run_rewrite_hook(const struct object_id *oldoid,
795 const struct object_id *newoid)
796 {
797 struct child_process proc = CHILD_PROCESS_INIT;
798 const char *argv[3];
799 int code;
800 struct strbuf sb = STRBUF_INIT;
801
802 argv[0] = find_hook("post-rewrite");
803 if (!argv[0])
804 return 0;
805
806 argv[1] = "amend";
807 argv[2] = NULL;
808
809 proc.argv = argv;
810 proc.in = -1;
811 proc.stdout_to_stderr = 1;
812
813 code = start_command(&proc);
814 if (code)
815 return code;
816 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
817 sigchain_push(SIGPIPE, SIG_IGN);
818 write_in_full(proc.in, sb.buf, sb.len);
819 close(proc.in);
820 strbuf_release(&sb);
821 sigchain_pop(SIGPIPE);
822 return finish_command(&proc);
823 }
824
825 void commit_post_rewrite(const struct commit *old_head,
826 const struct object_id *new_head)
827 {
828 struct notes_rewrite_cfg *cfg;
829
830 cfg = init_copy_notes_for_rewrite("amend");
831 if (cfg) {
832 /* we are amending, so old_head is not NULL */
833 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
834 finish_copy_notes_for_rewrite(cfg, "Notes added by 'git commit --amend'");
835 }
836 run_rewrite_hook(&old_head->object.oid, new_head);
837 }
838
839 static const char implicit_ident_advice_noconfig[] =
840 N_("Your name and email address were configured automatically based\n"
841 "on your username and hostname. Please check that they are accurate.\n"
842 "You can suppress this message by setting them explicitly. Run the\n"
843 "following command and follow the instructions in your editor to edit\n"
844 "your configuration file:\n"
845 "\n"
846 " git config --global --edit\n"
847 "\n"
848 "After doing this, you may fix the identity used for this commit with:\n"
849 "\n"
850 " git commit --amend --reset-author\n");
851
852 static const char implicit_ident_advice_config[] =
853 N_("Your name and email address were configured automatically based\n"
854 "on your username and hostname. Please check that they are accurate.\n"
855 "You can suppress this message by setting them explicitly:\n"
856 "\n"
857 " git config --global user.name \"Your Name\"\n"
858 " git config --global user.email you@example.com\n"
859 "\n"
860 "After doing this, you may fix the identity used for this commit with:\n"
861 "\n"
862 " git commit --amend --reset-author\n");
863
864 static const char *implicit_ident_advice(void)
865 {
866 char *user_config = expand_user_path("~/.gitconfig", 0);
867 char *xdg_config = xdg_config_home("config");
868 int config_exists = file_exists(user_config) || file_exists(xdg_config);
869
870 free(user_config);
871 free(xdg_config);
872
873 if (config_exists)
874 return _(implicit_ident_advice_config);
875 else
876 return _(implicit_ident_advice_noconfig);
877
878 }
879
880 void print_commit_summary(const char *prefix, const struct object_id *oid,
881 unsigned int flags)
882 {
883 struct rev_info rev;
884 struct commit *commit;
885 struct strbuf format = STRBUF_INIT;
886 const char *head;
887 struct pretty_print_context pctx = {0};
888 struct strbuf author_ident = STRBUF_INIT;
889 struct strbuf committer_ident = STRBUF_INIT;
890
891 commit = lookup_commit(oid);
892 if (!commit)
893 die(_("couldn't look up newly created commit"));
894 if (parse_commit(commit))
895 die(_("could not parse newly created commit"));
896
897 strbuf_addstr(&format, "format:%h] %s");
898
899 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
900 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
901 if (strbuf_cmp(&author_ident, &committer_ident)) {
902 strbuf_addstr(&format, "\n Author: ");
903 strbuf_addbuf_percentquote(&format, &author_ident);
904 }
905 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
906 struct strbuf date = STRBUF_INIT;
907
908 format_commit_message(commit, "%ad", &date, &pctx);
909 strbuf_addstr(&format, "\n Date: ");
910 strbuf_addbuf_percentquote(&format, &date);
911 strbuf_release(&date);
912 }
913 if (!committer_ident_sufficiently_given()) {
914 strbuf_addstr(&format, "\n Committer: ");
915 strbuf_addbuf_percentquote(&format, &committer_ident);
916 if (advice_implicit_identity) {
917 strbuf_addch(&format, '\n');
918 strbuf_addstr(&format, implicit_ident_advice());
919 }
920 }
921 strbuf_release(&author_ident);
922 strbuf_release(&committer_ident);
923
924 init_revisions(&rev, prefix);
925 setup_revisions(0, NULL, &rev, NULL);
926
927 rev.diff = 1;
928 rev.diffopt.output_format =
929 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
930
931 rev.verbose_header = 1;
932 rev.show_root_diff = 1;
933 get_commit_format(format.buf, &rev);
934 rev.always_show_header = 0;
935 rev.diffopt.detect_rename = 1;
936 rev.diffopt.break_opt = 0;
937 diff_setup_done(&rev.diffopt);
938
939 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
940 if (!head)
941 die_errno(_("unable to resolve HEAD after creating commit"));
942 if (!strcmp(head, "HEAD"))
943 head = _("detached HEAD");
944 else
945 skip_prefix(head, "refs/heads/", &head);
946 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
947 _(" (root-commit)") : "");
948
949 if (!log_tree_commit(&rev, commit)) {
950 rev.always_show_header = 1;
951 rev.use_terminator = 1;
952 log_tree_commit(&rev, commit);
953 }
954
955 strbuf_release(&format);
956 }
957
958 static int is_original_commit_empty(struct commit *commit)
959 {
960 const struct object_id *ptree_oid;
961
962 if (parse_commit(commit))
963 return error(_("could not parse commit %s\n"),
964 oid_to_hex(&commit->object.oid));
965 if (commit->parents) {
966 struct commit *parent = commit->parents->item;
967 if (parse_commit(parent))
968 return error(_("could not parse parent commit %s\n"),
969 oid_to_hex(&parent->object.oid));
970 ptree_oid = &parent->tree->object.oid;
971 } else {
972 ptree_oid = &empty_tree_oid; /* commit is root */
973 }
974
975 return !oidcmp(ptree_oid, &commit->tree->object.oid);
976 }
977
978 /*
979 * Do we run "git commit" with "--allow-empty"?
980 */
981 static int allow_empty(struct replay_opts *opts, struct commit *commit)
982 {
983 int index_unchanged, empty_commit;
984
985 /*
986 * Three cases:
987 *
988 * (1) we do not allow empty at all and error out.
989 *
990 * (2) we allow ones that were initially empty, but
991 * forbid the ones that become empty;
992 *
993 * (3) we allow both.
994 */
995 if (!opts->allow_empty)
996 return 0; /* let "git commit" barf as necessary */
997
998 index_unchanged = is_index_unchanged();
999 if (index_unchanged < 0)
1000 return index_unchanged;
1001 if (!index_unchanged)
1002 return 0; /* we do not have to say --allow-empty */
1003
1004 if (opts->keep_redundant_commits)
1005 return 1;
1006
1007 empty_commit = is_original_commit_empty(commit);
1008 if (empty_commit < 0)
1009 return empty_commit;
1010 if (!empty_commit)
1011 return 0;
1012 else
1013 return 1;
1014 }
1015
1016 /*
1017 * Note that ordering matters in this enum. Not only must it match the mapping
1018 * below, it is also divided into several sections that matter. When adding
1019 * new commands, make sure you add it in the right section.
1020 */
1021 enum todo_command {
1022 /* commands that handle commits */
1023 TODO_PICK = 0,
1024 TODO_REVERT,
1025 TODO_EDIT,
1026 TODO_REWORD,
1027 TODO_FIXUP,
1028 TODO_SQUASH,
1029 /* commands that do something else than handling a single commit */
1030 TODO_EXEC,
1031 /* commands that do nothing but are counted for reporting progress */
1032 TODO_NOOP,
1033 TODO_DROP,
1034 /* comments (not counted for reporting progress) */
1035 TODO_COMMENT
1036 };
1037
1038 static struct {
1039 char c;
1040 const char *str;
1041 } todo_command_info[] = {
1042 { 'p', "pick" },
1043 { 0, "revert" },
1044 { 'e', "edit" },
1045 { 'r', "reword" },
1046 { 'f', "fixup" },
1047 { 's', "squash" },
1048 { 'x', "exec" },
1049 { 0, "noop" },
1050 { 'd', "drop" },
1051 { 0, NULL }
1052 };
1053
1054 static const char *command_to_string(const enum todo_command command)
1055 {
1056 if (command < TODO_COMMENT)
1057 return todo_command_info[command].str;
1058 die("Unknown command: %d", command);
1059 }
1060
1061 static int is_noop(const enum todo_command command)
1062 {
1063 return TODO_NOOP <= command;
1064 }
1065
1066 static int is_fixup(enum todo_command command)
1067 {
1068 return command == TODO_FIXUP || command == TODO_SQUASH;
1069 }
1070
1071 static int update_squash_messages(enum todo_command command,
1072 struct commit *commit, struct replay_opts *opts)
1073 {
1074 struct strbuf buf = STRBUF_INIT;
1075 int count, res;
1076 const char *message, *body;
1077
1078 if (file_exists(rebase_path_squash_msg())) {
1079 struct strbuf header = STRBUF_INIT;
1080 char *eol, *p;
1081
1082 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 2048) <= 0)
1083 return error(_("could not read '%s'"),
1084 rebase_path_squash_msg());
1085
1086 p = buf.buf + 1;
1087 eol = strchrnul(buf.buf, '\n');
1088 if (buf.buf[0] != comment_line_char ||
1089 (p += strcspn(p, "0123456789\n")) == eol)
1090 return error(_("unexpected 1st line of squash message:"
1091 "\n\n\t%.*s"),
1092 (int)(eol - buf.buf), buf.buf);
1093 count = strtol(p, NULL, 10);
1094
1095 if (count < 1)
1096 return error(_("invalid 1st line of squash message:\n"
1097 "\n\t%.*s"),
1098 (int)(eol - buf.buf), buf.buf);
1099
1100 strbuf_addf(&header, "%c ", comment_line_char);
1101 strbuf_addf(&header,
1102 _("This is a combination of %d commits."), ++count);
1103 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1104 strbuf_release(&header);
1105 } else {
1106 struct object_id head;
1107 struct commit *head_commit;
1108 const char *head_message, *body;
1109
1110 if (get_oid("HEAD", &head))
1111 return error(_("need a HEAD to fixup"));
1112 if (!(head_commit = lookup_commit_reference(&head)))
1113 return error(_("could not read HEAD"));
1114 if (!(head_message = get_commit_buffer(head_commit, NULL)))
1115 return error(_("could not read HEAD's commit message"));
1116
1117 find_commit_subject(head_message, &body);
1118 if (write_message(body, strlen(body),
1119 rebase_path_fixup_msg(), 0)) {
1120 unuse_commit_buffer(head_commit, head_message);
1121 return error(_("cannot write '%s'"),
1122 rebase_path_fixup_msg());
1123 }
1124
1125 count = 2;
1126 strbuf_addf(&buf, "%c ", comment_line_char);
1127 strbuf_addf(&buf, _("This is a combination of %d commits."),
1128 count);
1129 strbuf_addf(&buf, "\n%c ", comment_line_char);
1130 strbuf_addstr(&buf, _("This is the 1st commit message:"));
1131 strbuf_addstr(&buf, "\n\n");
1132 strbuf_addstr(&buf, body);
1133
1134 unuse_commit_buffer(head_commit, head_message);
1135 }
1136
1137 if (!(message = get_commit_buffer(commit, NULL)))
1138 return error(_("could not read commit message of %s"),
1139 oid_to_hex(&commit->object.oid));
1140 find_commit_subject(message, &body);
1141
1142 if (command == TODO_SQUASH) {
1143 unlink(rebase_path_fixup_msg());
1144 strbuf_addf(&buf, "\n%c ", comment_line_char);
1145 strbuf_addf(&buf, _("This is the commit message #%d:"), count);
1146 strbuf_addstr(&buf, "\n\n");
1147 strbuf_addstr(&buf, body);
1148 } else if (command == TODO_FIXUP) {
1149 strbuf_addf(&buf, "\n%c ", comment_line_char);
1150 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
1151 count);
1152 strbuf_addstr(&buf, "\n\n");
1153 strbuf_add_commented_lines(&buf, body, strlen(body));
1154 } else
1155 return error(_("unknown command: %d"), command);
1156 unuse_commit_buffer(commit, message);
1157
1158 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1159 strbuf_release(&buf);
1160 return res;
1161 }
1162
1163 static void flush_rewritten_pending(void) {
1164 struct strbuf buf = STRBUF_INIT;
1165 struct object_id newoid;
1166 FILE *out;
1167
1168 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1169 !get_oid("HEAD", &newoid) &&
1170 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
1171 char *bol = buf.buf, *eol;
1172
1173 while (*bol) {
1174 eol = strchrnul(bol, '\n');
1175 fprintf(out, "%.*s %s\n", (int)(eol - bol),
1176 bol, oid_to_hex(&newoid));
1177 if (!*eol)
1178 break;
1179 bol = eol + 1;
1180 }
1181 fclose(out);
1182 unlink(rebase_path_rewritten_pending());
1183 }
1184 strbuf_release(&buf);
1185 }
1186
1187 static void record_in_rewritten(struct object_id *oid,
1188 enum todo_command next_command) {
1189 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
1190
1191 if (!out)
1192 return;
1193
1194 fprintf(out, "%s\n", oid_to_hex(oid));
1195 fclose(out);
1196
1197 if (!is_fixup(next_command))
1198 flush_rewritten_pending();
1199 }
1200
1201 static int do_pick_commit(enum todo_command command, struct commit *commit,
1202 struct replay_opts *opts, int final_fixup)
1203 {
1204 unsigned int flags = opts->edit ? EDIT_MSG : 0;
1205 const char *msg_file = opts->edit ? NULL : git_path_merge_msg();
1206 struct object_id head;
1207 struct commit *base, *next, *parent;
1208 const char *base_label, *next_label;
1209 struct commit_message msg = { NULL, NULL, NULL, NULL };
1210 struct strbuf msgbuf = STRBUF_INIT;
1211 int res, unborn = 0, allow;
1212
1213 if (opts->no_commit) {
1214 /*
1215 * We do not intend to commit immediately. We just want to
1216 * merge the differences in, so let's compute the tree
1217 * that represents the "current" state for merge-recursive
1218 * to work on.
1219 */
1220 if (write_cache_as_tree(head.hash, 0, NULL))
1221 return error(_("your index file is unmerged."));
1222 } else {
1223 unborn = get_oid("HEAD", &head);
1224 if (unborn)
1225 oidcpy(&head, &empty_tree_oid);
1226 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD",
1227 NULL, 0))
1228 return error_dirty_index(opts);
1229 }
1230 discard_cache();
1231
1232 if (!commit->parents)
1233 parent = NULL;
1234 else if (commit->parents->next) {
1235 /* Reverting or cherry-picking a merge commit */
1236 int cnt;
1237 struct commit_list *p;
1238
1239 if (!opts->mainline)
1240 return error(_("commit %s is a merge but no -m option was given."),
1241 oid_to_hex(&commit->object.oid));
1242
1243 for (cnt = 1, p = commit->parents;
1244 cnt != opts->mainline && p;
1245 cnt++)
1246 p = p->next;
1247 if (cnt != opts->mainline || !p)
1248 return error(_("commit %s does not have parent %d"),
1249 oid_to_hex(&commit->object.oid), opts->mainline);
1250 parent = p->item;
1251 } else if (0 < opts->mainline)
1252 return error(_("mainline was specified but commit %s is not a merge."),
1253 oid_to_hex(&commit->object.oid));
1254 else
1255 parent = commit->parents->item;
1256
1257 if (get_message(commit, &msg) != 0)
1258 return error(_("cannot get commit message for %s"),
1259 oid_to_hex(&commit->object.oid));
1260
1261 if (opts->allow_ff && !is_fixup(command) &&
1262 ((parent && !oidcmp(&parent->object.oid, &head)) ||
1263 (!parent && unborn))) {
1264 if (is_rebase_i(opts))
1265 write_author_script(msg.message);
1266 res = fast_forward_to(&commit->object.oid, &head, unborn,
1267 opts);
1268 if (res || command != TODO_REWORD)
1269 goto leave;
1270 flags |= EDIT_MSG | AMEND_MSG;
1271 if (command == TODO_REWORD)
1272 flags |= VERIFY_MSG;
1273 msg_file = NULL;
1274 goto fast_forward_edit;
1275 }
1276 if (parent && parse_commit(parent) < 0)
1277 /* TRANSLATORS: The first %s will be a "todo" command like
1278 "revert" or "pick", the second %s a SHA1. */
1279 return error(_("%s: cannot parse parent commit %s"),
1280 command_to_string(command),
1281 oid_to_hex(&parent->object.oid));
1282
1283 /*
1284 * "commit" is an existing commit. We would want to apply
1285 * the difference it introduces since its first parent "prev"
1286 * on top of the current HEAD if we are cherry-pick. Or the
1287 * reverse of it if we are revert.
1288 */
1289
1290 if (command == TODO_REVERT) {
1291 base = commit;
1292 base_label = msg.label;
1293 next = parent;
1294 next_label = msg.parent_label;
1295 strbuf_addstr(&msgbuf, "Revert \"");
1296 strbuf_addstr(&msgbuf, msg.subject);
1297 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1298 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1299
1300 if (commit->parents && commit->parents->next) {
1301 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1302 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1303 }
1304 strbuf_addstr(&msgbuf, ".\n");
1305 } else {
1306 const char *p;
1307
1308 base = parent;
1309 base_label = msg.parent_label;
1310 next = commit;
1311 next_label = msg.label;
1312
1313 /* Append the commit log message to msgbuf. */
1314 if (find_commit_subject(msg.message, &p))
1315 strbuf_addstr(&msgbuf, p);
1316
1317 if (opts->record_origin) {
1318 strbuf_complete_line(&msgbuf);
1319 if (!has_conforming_footer(&msgbuf, NULL, 0))
1320 strbuf_addch(&msgbuf, '\n');
1321 strbuf_addstr(&msgbuf, cherry_picked_prefix);
1322 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1323 strbuf_addstr(&msgbuf, ")\n");
1324 }
1325 }
1326
1327 if (command == TODO_REWORD)
1328 flags |= EDIT_MSG | VERIFY_MSG;
1329 else if (is_fixup(command)) {
1330 if (update_squash_messages(command, commit, opts))
1331 return -1;
1332 flags |= AMEND_MSG;
1333 if (!final_fixup)
1334 msg_file = rebase_path_squash_msg();
1335 else if (file_exists(rebase_path_fixup_msg())) {
1336 flags |= CLEANUP_MSG;
1337 msg_file = rebase_path_fixup_msg();
1338 } else {
1339 const char *dest = git_path_squash_msg();
1340 unlink(dest);
1341 if (copy_file(dest, rebase_path_squash_msg(), 0666))
1342 return error(_("could not rename '%s' to '%s'"),
1343 rebase_path_squash_msg(), dest);
1344 unlink(git_path_merge_msg());
1345 msg_file = dest;
1346 flags |= EDIT_MSG;
1347 }
1348 }
1349
1350 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1351 res = -1;
1352 else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
1353 res = do_recursive_merge(base, next, base_label, next_label,
1354 &head, &msgbuf, opts);
1355 if (res < 0)
1356 return res;
1357 res |= write_message(msgbuf.buf, msgbuf.len,
1358 git_path_merge_msg(), 0);
1359 } else {
1360 struct commit_list *common = NULL;
1361 struct commit_list *remotes = NULL;
1362
1363 res = write_message(msgbuf.buf, msgbuf.len,
1364 git_path_merge_msg(), 0);
1365
1366 commit_list_insert(base, &common);
1367 commit_list_insert(next, &remotes);
1368 res |= try_merge_command(opts->strategy,
1369 opts->xopts_nr, (const char **)opts->xopts,
1370 common, oid_to_hex(&head), remotes);
1371 free_commit_list(common);
1372 free_commit_list(remotes);
1373 }
1374 strbuf_release(&msgbuf);
1375
1376 /*
1377 * If the merge was clean or if it failed due to conflict, we write
1378 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1379 * However, if the merge did not even start, then we don't want to
1380 * write it at all.
1381 */
1382 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
1383 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
1384 REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
1385 res = -1;
1386 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
1387 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
1388 REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
1389 res = -1;
1390
1391 if (res) {
1392 error(command == TODO_REVERT
1393 ? _("could not revert %s... %s")
1394 : _("could not apply %s... %s"),
1395 short_commit_name(commit), msg.subject);
1396 print_advice(res == 1, opts);
1397 rerere(opts->allow_rerere_auto);
1398 goto leave;
1399 }
1400
1401 allow = allow_empty(opts, commit);
1402 if (allow < 0) {
1403 res = allow;
1404 goto leave;
1405 } else if (allow)
1406 flags |= ALLOW_EMPTY;
1407 if (!opts->no_commit)
1408 fast_forward_edit:
1409 res = run_git_commit(msg_file, opts, flags);
1410
1411 if (!res && final_fixup) {
1412 unlink(rebase_path_fixup_msg());
1413 unlink(rebase_path_squash_msg());
1414 }
1415
1416 leave:
1417 free_message(commit, &msg);
1418 update_abort_safety_file();
1419
1420 return res;
1421 }
1422
1423 static int prepare_revs(struct replay_opts *opts)
1424 {
1425 /*
1426 * picking (but not reverting) ranges (but not individual revisions)
1427 * should be done in reverse
1428 */
1429 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
1430 opts->revs->reverse ^= 1;
1431
1432 if (prepare_revision_walk(opts->revs))
1433 return error(_("revision walk setup failed"));
1434
1435 if (!opts->revs->commits)
1436 return error(_("empty commit set passed"));
1437 return 0;
1438 }
1439
1440 static int read_and_refresh_cache(struct replay_opts *opts)
1441 {
1442 static struct lock_file index_lock;
1443 int index_fd = hold_locked_index(&index_lock, 0);
1444 if (read_index_preload(&the_index, NULL) < 0) {
1445 rollback_lock_file(&index_lock);
1446 return error(_("git %s: failed to read the index"),
1447 _(action_name(opts)));
1448 }
1449 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
1450 if (the_index.cache_changed && index_fd >= 0) {
1451 if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK)) {
1452 return error(_("git %s: failed to refresh the index"),
1453 _(action_name(opts)));
1454 }
1455 }
1456 rollback_lock_file(&index_lock);
1457 return 0;
1458 }
1459
1460 struct todo_item {
1461 enum todo_command command;
1462 struct commit *commit;
1463 const char *arg;
1464 int arg_len;
1465 size_t offset_in_buf;
1466 };
1467
1468 struct todo_list {
1469 struct strbuf buf;
1470 struct todo_item *items;
1471 int nr, alloc, current;
1472 int done_nr, total_nr;
1473 struct stat_data stat;
1474 };
1475
1476 #define TODO_LIST_INIT { STRBUF_INIT }
1477
1478 static void todo_list_release(struct todo_list *todo_list)
1479 {
1480 strbuf_release(&todo_list->buf);
1481 FREE_AND_NULL(todo_list->items);
1482 todo_list->nr = todo_list->alloc = 0;
1483 }
1484
1485 static struct todo_item *append_new_todo(struct todo_list *todo_list)
1486 {
1487 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
1488 return todo_list->items + todo_list->nr++;
1489 }
1490
1491 static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
1492 {
1493 struct object_id commit_oid;
1494 char *end_of_object_name;
1495 int i, saved, status, padding;
1496
1497 /* left-trim */
1498 bol += strspn(bol, " \t");
1499
1500 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
1501 item->command = TODO_COMMENT;
1502 item->commit = NULL;
1503 item->arg = bol;
1504 item->arg_len = eol - bol;
1505 return 0;
1506 }
1507
1508 for (i = 0; i < TODO_COMMENT; i++)
1509 if (skip_prefix(bol, todo_command_info[i].str, &bol)) {
1510 item->command = i;
1511 break;
1512 } else if (bol[1] == ' ' && *bol == todo_command_info[i].c) {
1513 bol++;
1514 item->command = i;
1515 break;
1516 }
1517 if (i >= TODO_COMMENT)
1518 return -1;
1519
1520 if (item->command == TODO_NOOP) {
1521 item->commit = NULL;
1522 item->arg = bol;
1523 item->arg_len = eol - bol;
1524 return 0;
1525 }
1526
1527 /* Eat up extra spaces/ tabs before object name */
1528 padding = strspn(bol, " \t");
1529 if (!padding)
1530 return -1;
1531 bol += padding;
1532
1533 if (item->command == TODO_EXEC) {
1534 item->arg = bol;
1535 item->arg_len = (int)(eol - bol);
1536 return 0;
1537 }
1538
1539 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
1540 saved = *end_of_object_name;
1541 *end_of_object_name = '\0';
1542 status = get_oid(bol, &commit_oid);
1543 *end_of_object_name = saved;
1544
1545 item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
1546 item->arg_len = (int)(eol - item->arg);
1547
1548 if (status < 0)
1549 return -1;
1550
1551 item->commit = lookup_commit_reference(&commit_oid);
1552 return !item->commit;
1553 }
1554
1555 static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
1556 {
1557 struct todo_item *item;
1558 char *p = buf, *next_p;
1559 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
1560
1561 for (i = 1; *p; i++, p = next_p) {
1562 char *eol = strchrnul(p, '\n');
1563
1564 next_p = *eol ? eol + 1 /* skip LF */ : eol;
1565
1566 if (p != eol && eol[-1] == '\r')
1567 eol--; /* strip Carriage Return */
1568
1569 item = append_new_todo(todo_list);
1570 item->offset_in_buf = p - todo_list->buf.buf;
1571 if (parse_insn_line(item, p, eol)) {
1572 res = error(_("invalid line %d: %.*s"),
1573 i, (int)(eol - p), p);
1574 item->command = TODO_NOOP;
1575 }
1576
1577 if (fixup_okay)
1578 ; /* do nothing */
1579 else if (is_fixup(item->command))
1580 return error(_("cannot '%s' without a previous commit"),
1581 command_to_string(item->command));
1582 else if (!is_noop(item->command))
1583 fixup_okay = 1;
1584 }
1585
1586 return res;
1587 }
1588
1589 static int count_commands(struct todo_list *todo_list)
1590 {
1591 int count = 0, i;
1592
1593 for (i = 0; i < todo_list->nr; i++)
1594 if (todo_list->items[i].command != TODO_COMMENT)
1595 count++;
1596
1597 return count;
1598 }
1599
1600 static int read_populate_todo(struct todo_list *todo_list,
1601 struct replay_opts *opts)
1602 {
1603 struct stat st;
1604 const char *todo_file = get_todo_path(opts);
1605 int fd, res;
1606
1607 strbuf_reset(&todo_list->buf);
1608 fd = open(todo_file, O_RDONLY);
1609 if (fd < 0)
1610 return error_errno(_("could not open '%s'"), todo_file);
1611 if (strbuf_read(&todo_list->buf, fd, 0) < 0) {
1612 close(fd);
1613 return error(_("could not read '%s'."), todo_file);
1614 }
1615 close(fd);
1616
1617 res = stat(todo_file, &st);
1618 if (res)
1619 return error(_("could not stat '%s'"), todo_file);
1620 fill_stat_data(&todo_list->stat, &st);
1621
1622 res = parse_insn_buffer(todo_list->buf.buf, todo_list);
1623 if (res) {
1624 if (is_rebase_i(opts))
1625 return error(_("please fix this using "
1626 "'git rebase --edit-todo'."));
1627 return error(_("unusable instruction sheet: '%s'"), todo_file);
1628 }
1629
1630 if (!todo_list->nr &&
1631 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
1632 return error(_("no commits parsed."));
1633
1634 if (!is_rebase_i(opts)) {
1635 enum todo_command valid =
1636 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
1637 int i;
1638
1639 for (i = 0; i < todo_list->nr; i++)
1640 if (valid == todo_list->items[i].command)
1641 continue;
1642 else if (valid == TODO_PICK)
1643 return error(_("cannot cherry-pick during a revert."));
1644 else
1645 return error(_("cannot revert during a cherry-pick."));
1646 }
1647
1648 if (is_rebase_i(opts)) {
1649 struct todo_list done = TODO_LIST_INIT;
1650 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
1651
1652 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
1653 !parse_insn_buffer(done.buf.buf, &done))
1654 todo_list->done_nr = count_commands(&done);
1655 else
1656 todo_list->done_nr = 0;
1657
1658 todo_list->total_nr = todo_list->done_nr
1659 + count_commands(todo_list);
1660 todo_list_release(&done);
1661
1662 if (f) {
1663 fprintf(f, "%d\n", todo_list->total_nr);
1664 fclose(f);
1665 }
1666 }
1667
1668 return 0;
1669 }
1670
1671 static int git_config_string_dup(char **dest,
1672 const char *var, const char *value)
1673 {
1674 if (!value)
1675 return config_error_nonbool(var);
1676 free(*dest);
1677 *dest = xstrdup(value);
1678 return 0;
1679 }
1680
1681 static int populate_opts_cb(const char *key, const char *value, void *data)
1682 {
1683 struct replay_opts *opts = data;
1684 int error_flag = 1;
1685
1686 if (!value)
1687 error_flag = 0;
1688 else if (!strcmp(key, "options.no-commit"))
1689 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
1690 else if (!strcmp(key, "options.edit"))
1691 opts->edit = git_config_bool_or_int(key, value, &error_flag);
1692 else if (!strcmp(key, "options.signoff"))
1693 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
1694 else if (!strcmp(key, "options.record-origin"))
1695 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
1696 else if (!strcmp(key, "options.allow-ff"))
1697 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
1698 else if (!strcmp(key, "options.mainline"))
1699 opts->mainline = git_config_int(key, value);
1700 else if (!strcmp(key, "options.strategy"))
1701 git_config_string_dup(&opts->strategy, key, value);
1702 else if (!strcmp(key, "options.gpg-sign"))
1703 git_config_string_dup(&opts->gpg_sign, key, value);
1704 else if (!strcmp(key, "options.strategy-option")) {
1705 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
1706 opts->xopts[opts->xopts_nr++] = xstrdup(value);
1707 } else if (!strcmp(key, "options.allow-rerere-auto"))
1708 opts->allow_rerere_auto =
1709 git_config_bool_or_int(key, value, &error_flag) ?
1710 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
1711 else
1712 return error(_("invalid key: %s"), key);
1713
1714 if (!error_flag)
1715 return error(_("invalid value for %s: %s"), key, value);
1716
1717 return 0;
1718 }
1719
1720 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
1721 {
1722 int i;
1723
1724 strbuf_reset(buf);
1725 if (!read_oneliner(buf, rebase_path_strategy(), 0))
1726 return;
1727 opts->strategy = strbuf_detach(buf, NULL);
1728 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
1729 return;
1730
1731 opts->xopts_nr = split_cmdline(buf->buf, (const char ***)&opts->xopts);
1732 for (i = 0; i < opts->xopts_nr; i++) {
1733 const char *arg = opts->xopts[i];
1734
1735 skip_prefix(arg, "--", &arg);
1736 opts->xopts[i] = xstrdup(arg);
1737 }
1738 }
1739
1740 static int read_populate_opts(struct replay_opts *opts)
1741 {
1742 if (is_rebase_i(opts)) {
1743 struct strbuf buf = STRBUF_INIT;
1744
1745 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
1746 if (!starts_with(buf.buf, "-S"))
1747 strbuf_reset(&buf);
1748 else {
1749 free(opts->gpg_sign);
1750 opts->gpg_sign = xstrdup(buf.buf + 2);
1751 }
1752 strbuf_reset(&buf);
1753 }
1754
1755 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(), 1)) {
1756 if (!strcmp(buf.buf, "--rerere-autoupdate"))
1757 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
1758 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
1759 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
1760 strbuf_reset(&buf);
1761 }
1762
1763 if (file_exists(rebase_path_verbose()))
1764 opts->verbose = 1;
1765
1766 read_strategy_opts(opts, &buf);
1767 strbuf_release(&buf);
1768
1769 return 0;
1770 }
1771
1772 if (!file_exists(git_path_opts_file()))
1773 return 0;
1774 /*
1775 * The function git_parse_source(), called from git_config_from_file(),
1776 * may die() in case of a syntactically incorrect file. We do not care
1777 * about this case, though, because we wrote that file ourselves, so we
1778 * are pretty certain that it is syntactically correct.
1779 */
1780 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
1781 return error(_("malformed options sheet: '%s'"),
1782 git_path_opts_file());
1783 return 0;
1784 }
1785
1786 static int walk_revs_populate_todo(struct todo_list *todo_list,
1787 struct replay_opts *opts)
1788 {
1789 enum todo_command command = opts->action == REPLAY_PICK ?
1790 TODO_PICK : TODO_REVERT;
1791 const char *command_string = todo_command_info[command].str;
1792 struct commit *commit;
1793
1794 if (prepare_revs(opts))
1795 return -1;
1796
1797 while ((commit = get_revision(opts->revs))) {
1798 struct todo_item *item = append_new_todo(todo_list);
1799 const char *commit_buffer = get_commit_buffer(commit, NULL);
1800 const char *subject;
1801 int subject_len;
1802
1803 item->command = command;
1804 item->commit = commit;
1805 item->arg = NULL;
1806 item->arg_len = 0;
1807 item->offset_in_buf = todo_list->buf.len;
1808 subject_len = find_commit_subject(commit_buffer, &subject);
1809 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
1810 short_commit_name(commit), subject_len, subject);
1811 unuse_commit_buffer(commit, commit_buffer);
1812 }
1813 return 0;
1814 }
1815
1816 static int create_seq_dir(void)
1817 {
1818 if (file_exists(git_path_seq_dir())) {
1819 error(_("a cherry-pick or revert is already in progress"));
1820 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
1821 return -1;
1822 } else if (mkdir(git_path_seq_dir(), 0777) < 0)
1823 return error_errno(_("could not create sequencer directory '%s'"),
1824 git_path_seq_dir());
1825 return 0;
1826 }
1827
1828 static int save_head(const char *head)
1829 {
1830 static struct lock_file head_lock;
1831 struct strbuf buf = STRBUF_INIT;
1832 int fd;
1833 ssize_t written;
1834
1835 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
1836 if (fd < 0) {
1837 rollback_lock_file(&head_lock);
1838 return error_errno(_("could not lock HEAD"));
1839 }
1840 strbuf_addf(&buf, "%s\n", head);
1841 written = write_in_full(fd, buf.buf, buf.len);
1842 strbuf_release(&buf);
1843 if (written < 0) {
1844 rollback_lock_file(&head_lock);
1845 return error_errno(_("could not write to '%s'"),
1846 git_path_head_file());
1847 }
1848 if (commit_lock_file(&head_lock) < 0) {
1849 rollback_lock_file(&head_lock);
1850 return error(_("failed to finalize '%s'."), git_path_head_file());
1851 }
1852 return 0;
1853 }
1854
1855 static int rollback_is_safe(void)
1856 {
1857 struct strbuf sb = STRBUF_INIT;
1858 struct object_id expected_head, actual_head;
1859
1860 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
1861 strbuf_trim(&sb);
1862 if (get_oid_hex(sb.buf, &expected_head)) {
1863 strbuf_release(&sb);
1864 die(_("could not parse %s"), git_path_abort_safety_file());
1865 }
1866 strbuf_release(&sb);
1867 }
1868 else if (errno == ENOENT)
1869 oidclr(&expected_head);
1870 else
1871 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
1872
1873 if (get_oid("HEAD", &actual_head))
1874 oidclr(&actual_head);
1875
1876 return !oidcmp(&actual_head, &expected_head);
1877 }
1878
1879 static int reset_for_rollback(const struct object_id *oid)
1880 {
1881 const char *argv[4]; /* reset --merge <arg> + NULL */
1882
1883 argv[0] = "reset";
1884 argv[1] = "--merge";
1885 argv[2] = oid_to_hex(oid);
1886 argv[3] = NULL;
1887 return run_command_v_opt(argv, RUN_GIT_CMD);
1888 }
1889
1890 static int rollback_single_pick(void)
1891 {
1892 struct object_id head_oid;
1893
1894 if (!file_exists(git_path_cherry_pick_head()) &&
1895 !file_exists(git_path_revert_head()))
1896 return error(_("no cherry-pick or revert in progress"));
1897 if (read_ref_full("HEAD", 0, &head_oid, NULL))
1898 return error(_("cannot resolve HEAD"));
1899 if (is_null_oid(&head_oid))
1900 return error(_("cannot abort from a branch yet to be born"));
1901 return reset_for_rollback(&head_oid);
1902 }
1903
1904 int sequencer_rollback(struct replay_opts *opts)
1905 {
1906 FILE *f;
1907 struct object_id oid;
1908 struct strbuf buf = STRBUF_INIT;
1909 const char *p;
1910
1911 f = fopen(git_path_head_file(), "r");
1912 if (!f && errno == ENOENT) {
1913 /*
1914 * There is no multiple-cherry-pick in progress.
1915 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
1916 * a single-cherry-pick in progress, abort that.
1917 */
1918 return rollback_single_pick();
1919 }
1920 if (!f)
1921 return error_errno(_("cannot open '%s'"), git_path_head_file());
1922 if (strbuf_getline_lf(&buf, f)) {
1923 error(_("cannot read '%s': %s"), git_path_head_file(),
1924 ferror(f) ? strerror(errno) : _("unexpected end of file"));
1925 fclose(f);
1926 goto fail;
1927 }
1928 fclose(f);
1929 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
1930 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
1931 git_path_head_file());
1932 goto fail;
1933 }
1934 if (is_null_oid(&oid)) {
1935 error(_("cannot abort from a branch yet to be born"));
1936 goto fail;
1937 }
1938
1939 if (!rollback_is_safe()) {
1940 /* Do not error, just do not rollback */
1941 warning(_("You seem to have moved HEAD. "
1942 "Not rewinding, check your HEAD!"));
1943 } else
1944 if (reset_for_rollback(&oid))
1945 goto fail;
1946 strbuf_release(&buf);
1947 return sequencer_remove_state(opts);
1948 fail:
1949 strbuf_release(&buf);
1950 return -1;
1951 }
1952
1953 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
1954 {
1955 static struct lock_file todo_lock;
1956 const char *todo_path = get_todo_path(opts);
1957 int next = todo_list->current, offset, fd;
1958
1959 /*
1960 * rebase -i writes "git-rebase-todo" without the currently executing
1961 * command, appending it to "done" instead.
1962 */
1963 if (is_rebase_i(opts))
1964 next++;
1965
1966 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
1967 if (fd < 0)
1968 return error_errno(_("could not lock '%s'"), todo_path);
1969 offset = next < todo_list->nr ?
1970 todo_list->items[next].offset_in_buf : todo_list->buf.len;
1971 if (write_in_full(fd, todo_list->buf.buf + offset,
1972 todo_list->buf.len - offset) < 0)
1973 return error_errno(_("could not write to '%s'"), todo_path);
1974 if (commit_lock_file(&todo_lock) < 0)
1975 return error(_("failed to finalize '%s'."), todo_path);
1976
1977 if (is_rebase_i(opts)) {
1978 const char *done_path = rebase_path_done();
1979 int fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
1980 int prev_offset = !next ? 0 :
1981 todo_list->items[next - 1].offset_in_buf;
1982
1983 if (fd >= 0 && offset > prev_offset &&
1984 write_in_full(fd, todo_list->buf.buf + prev_offset,
1985 offset - prev_offset) < 0) {
1986 close(fd);
1987 return error_errno(_("could not write to '%s'"),
1988 done_path);
1989 }
1990 if (fd >= 0)
1991 close(fd);
1992 }
1993 return 0;
1994 }
1995
1996 static int save_opts(struct replay_opts *opts)
1997 {
1998 const char *opts_file = git_path_opts_file();
1999 int res = 0;
2000
2001 if (opts->no_commit)
2002 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
2003 if (opts->edit)
2004 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
2005 if (opts->signoff)
2006 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
2007 if (opts->record_origin)
2008 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
2009 if (opts->allow_ff)
2010 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
2011 if (opts->mainline) {
2012 struct strbuf buf = STRBUF_INIT;
2013 strbuf_addf(&buf, "%d", opts->mainline);
2014 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
2015 strbuf_release(&buf);
2016 }
2017 if (opts->strategy)
2018 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
2019 if (opts->gpg_sign)
2020 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
2021 if (opts->xopts) {
2022 int i;
2023 for (i = 0; i < opts->xopts_nr; i++)
2024 res |= git_config_set_multivar_in_file_gently(opts_file,
2025 "options.strategy-option",
2026 opts->xopts[i], "^$", 0);
2027 }
2028 if (opts->allow_rerere_auto)
2029 res |= git_config_set_in_file_gently(opts_file, "options.allow-rerere-auto",
2030 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
2031 "true" : "false");
2032 return res;
2033 }
2034
2035 static int make_patch(struct commit *commit, struct replay_opts *opts)
2036 {
2037 struct strbuf buf = STRBUF_INIT;
2038 struct rev_info log_tree_opt;
2039 const char *subject, *p;
2040 int res = 0;
2041
2042 p = short_commit_name(commit);
2043 if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
2044 return -1;
2045
2046 strbuf_addf(&buf, "%s/patch", get_dir(opts));
2047 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2048 init_revisions(&log_tree_opt, NULL);
2049 log_tree_opt.abbrev = 0;
2050 log_tree_opt.diff = 1;
2051 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
2052 log_tree_opt.disable_stdin = 1;
2053 log_tree_opt.no_commit_id = 1;
2054 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
2055 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
2056 if (!log_tree_opt.diffopt.file)
2057 res |= error_errno(_("could not open '%s'"), buf.buf);
2058 else {
2059 res |= log_tree_commit(&log_tree_opt, commit);
2060 fclose(log_tree_opt.diffopt.file);
2061 }
2062 strbuf_reset(&buf);
2063
2064 strbuf_addf(&buf, "%s/message", get_dir(opts));
2065 if (!file_exists(buf.buf)) {
2066 const char *commit_buffer = get_commit_buffer(commit, NULL);
2067 find_commit_subject(commit_buffer, &subject);
2068 res |= write_message(subject, strlen(subject), buf.buf, 1);
2069 unuse_commit_buffer(commit, commit_buffer);
2070 }
2071 strbuf_release(&buf);
2072
2073 return res;
2074 }
2075
2076 static int intend_to_amend(void)
2077 {
2078 struct object_id head;
2079 char *p;
2080
2081 if (get_oid("HEAD", &head))
2082 return error(_("cannot read HEAD"));
2083
2084 p = oid_to_hex(&head);
2085 return write_message(p, strlen(p), rebase_path_amend(), 1);
2086 }
2087
2088 static int error_with_patch(struct commit *commit,
2089 const char *subject, int subject_len,
2090 struct replay_opts *opts, int exit_code, int to_amend)
2091 {
2092 if (make_patch(commit, opts))
2093 return -1;
2094
2095 if (to_amend) {
2096 if (intend_to_amend())
2097 return -1;
2098
2099 fprintf(stderr, "You can amend the commit now, with\n"
2100 "\n"
2101 " git commit --amend %s\n"
2102 "\n"
2103 "Once you are satisfied with your changes, run\n"
2104 "\n"
2105 " git rebase --continue\n", gpg_sign_opt_quoted(opts));
2106 } else if (exit_code)
2107 fprintf(stderr, "Could not apply %s... %.*s\n",
2108 short_commit_name(commit), subject_len, subject);
2109
2110 return exit_code;
2111 }
2112
2113 static int error_failed_squash(struct commit *commit,
2114 struct replay_opts *opts, int subject_len, const char *subject)
2115 {
2116 if (rename(rebase_path_squash_msg(), rebase_path_message()))
2117 return error(_("could not rename '%s' to '%s'"),
2118 rebase_path_squash_msg(), rebase_path_message());
2119 unlink(rebase_path_fixup_msg());
2120 unlink(git_path_merge_msg());
2121 if (copy_file(git_path_merge_msg(), rebase_path_message(), 0666))
2122 return error(_("could not copy '%s' to '%s'"),
2123 rebase_path_message(), git_path_merge_msg());
2124 return error_with_patch(commit, subject, subject_len, opts, 1, 0);
2125 }
2126
2127 static int do_exec(const char *command_line)
2128 {
2129 struct argv_array child_env = ARGV_ARRAY_INIT;
2130 const char *child_argv[] = { NULL, NULL };
2131 int dirty, status;
2132
2133 fprintf(stderr, "Executing: %s\n", command_line);
2134 child_argv[0] = command_line;
2135 argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
2136 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
2137 child_env.argv);
2138
2139 /* force re-reading of the cache */
2140 if (discard_cache() < 0 || read_cache() < 0)
2141 return error(_("could not read index"));
2142
2143 dirty = require_clean_work_tree("rebase", NULL, 1, 1);
2144
2145 if (status) {
2146 warning(_("execution failed: %s\n%s"
2147 "You can fix the problem, and then run\n"
2148 "\n"
2149 " git rebase --continue\n"
2150 "\n"),
2151 command_line,
2152 dirty ? N_("and made changes to the index and/or the "
2153 "working tree\n") : "");
2154 if (status == 127)
2155 /* command not found */
2156 status = 1;
2157 } else if (dirty) {
2158 warning(_("execution succeeded: %s\nbut "
2159 "left changes to the index and/or the working tree\n"
2160 "Commit or stash your changes, and then run\n"
2161 "\n"
2162 " git rebase --continue\n"
2163 "\n"), command_line);
2164 status = 1;
2165 }
2166
2167 argv_array_clear(&child_env);
2168
2169 return status;
2170 }
2171
2172 static int is_final_fixup(struct todo_list *todo_list)
2173 {
2174 int i = todo_list->current;
2175
2176 if (!is_fixup(todo_list->items[i].command))
2177 return 0;
2178
2179 while (++i < todo_list->nr)
2180 if (is_fixup(todo_list->items[i].command))
2181 return 0;
2182 else if (!is_noop(todo_list->items[i].command))
2183 break;
2184 return 1;
2185 }
2186
2187 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
2188 {
2189 int i;
2190
2191 for (i = todo_list->current + offset; i < todo_list->nr; i++)
2192 if (!is_noop(todo_list->items[i].command))
2193 return todo_list->items[i].command;
2194
2195 return -1;
2196 }
2197
2198 static int apply_autostash(struct replay_opts *opts)
2199 {
2200 struct strbuf stash_sha1 = STRBUF_INIT;
2201 struct child_process child = CHILD_PROCESS_INIT;
2202 int ret = 0;
2203
2204 if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
2205 strbuf_release(&stash_sha1);
2206 return 0;
2207 }
2208 strbuf_trim(&stash_sha1);
2209
2210 child.git_cmd = 1;
2211 child.no_stdout = 1;
2212 child.no_stderr = 1;
2213 argv_array_push(&child.args, "stash");
2214 argv_array_push(&child.args, "apply");
2215 argv_array_push(&child.args, stash_sha1.buf);
2216 if (!run_command(&child))
2217 fprintf(stderr, _("Applied autostash.\n"));
2218 else {
2219 struct child_process store = CHILD_PROCESS_INIT;
2220
2221 store.git_cmd = 1;
2222 argv_array_push(&store.args, "stash");
2223 argv_array_push(&store.args, "store");
2224 argv_array_push(&store.args, "-m");
2225 argv_array_push(&store.args, "autostash");
2226 argv_array_push(&store.args, "-q");
2227 argv_array_push(&store.args, stash_sha1.buf);
2228 if (run_command(&store))
2229 ret = error(_("cannot store %s"), stash_sha1.buf);
2230 else
2231 fprintf(stderr,
2232 _("Applying autostash resulted in conflicts.\n"
2233 "Your changes are safe in the stash.\n"
2234 "You can run \"git stash pop\" or"
2235 " \"git stash drop\" at any time.\n"));
2236 }
2237
2238 strbuf_release(&stash_sha1);
2239 return ret;
2240 }
2241
2242 static const char *reflog_message(struct replay_opts *opts,
2243 const char *sub_action, const char *fmt, ...)
2244 {
2245 va_list ap;
2246 static struct strbuf buf = STRBUF_INIT;
2247
2248 va_start(ap, fmt);
2249 strbuf_reset(&buf);
2250 strbuf_addstr(&buf, action_name(opts));
2251 if (sub_action)
2252 strbuf_addf(&buf, " (%s)", sub_action);
2253 if (fmt) {
2254 strbuf_addstr(&buf, ": ");
2255 strbuf_vaddf(&buf, fmt, ap);
2256 }
2257 va_end(ap);
2258
2259 return buf.buf;
2260 }
2261
2262 static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
2263 {
2264 int res = 0;
2265
2266 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
2267 if (opts->allow_ff)
2268 assert(!(opts->signoff || opts->no_commit ||
2269 opts->record_origin || opts->edit));
2270 if (read_and_refresh_cache(opts))
2271 return -1;
2272
2273 while (todo_list->current < todo_list->nr) {
2274 struct todo_item *item = todo_list->items + todo_list->current;
2275 if (save_todo(todo_list, opts))
2276 return -1;
2277 if (is_rebase_i(opts)) {
2278 if (item->command != TODO_COMMENT) {
2279 FILE *f = fopen(rebase_path_msgnum(), "w");
2280
2281 todo_list->done_nr++;
2282
2283 if (f) {
2284 fprintf(f, "%d\n", todo_list->done_nr);
2285 fclose(f);
2286 }
2287 fprintf(stderr, "Rebasing (%d/%d)%s",
2288 todo_list->done_nr,
2289 todo_list->total_nr,
2290 opts->verbose ? "\n" : "\r");
2291 }
2292 unlink(rebase_path_message());
2293 unlink(rebase_path_author_script());
2294 unlink(rebase_path_stopped_sha());
2295 unlink(rebase_path_amend());
2296 }
2297 if (item->command <= TODO_SQUASH) {
2298 if (is_rebase_i(opts))
2299 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
2300 command_to_string(item->command), NULL),
2301 1);
2302 res = do_pick_commit(item->command, item->commit,
2303 opts, is_final_fixup(todo_list));
2304 if (is_rebase_i(opts) && res < 0) {
2305 /* Reschedule */
2306 todo_list->current--;
2307 if (save_todo(todo_list, opts))
2308 return -1;
2309 }
2310 if (item->command == TODO_EDIT) {
2311 struct commit *commit = item->commit;
2312 if (!res)
2313 fprintf(stderr,
2314 _("Stopped at %s... %.*s\n"),
2315 short_commit_name(commit),
2316 item->arg_len, item->arg);
2317 return error_with_patch(commit,
2318 item->arg, item->arg_len, opts, res,
2319 !res);
2320 }
2321 if (is_rebase_i(opts) && !res)
2322 record_in_rewritten(&item->commit->object.oid,
2323 peek_command(todo_list, 1));
2324 if (res && is_fixup(item->command)) {
2325 if (res == 1)
2326 intend_to_amend();
2327 return error_failed_squash(item->commit, opts,
2328 item->arg_len, item->arg);
2329 } else if (res && is_rebase_i(opts))
2330 return res | error_with_patch(item->commit,
2331 item->arg, item->arg_len, opts, res,
2332 item->command == TODO_REWORD);
2333 } else if (item->command == TODO_EXEC) {
2334 char *end_of_arg = (char *)(item->arg + item->arg_len);
2335 int saved = *end_of_arg;
2336 struct stat st;
2337
2338 *end_of_arg = '\0';
2339 res = do_exec(item->arg);
2340 *end_of_arg = saved;
2341
2342 /* Reread the todo file if it has changed. */
2343 if (res)
2344 ; /* fall through */
2345 else if (stat(get_todo_path(opts), &st))
2346 res = error_errno(_("could not stat '%s'"),
2347 get_todo_path(opts));
2348 else if (match_stat_data(&todo_list->stat, &st)) {
2349 todo_list_release(todo_list);
2350 if (read_populate_todo(todo_list, opts))
2351 res = -1; /* message was printed */
2352 /* `current` will be incremented below */
2353 todo_list->current = -1;
2354 }
2355 } else if (!is_noop(item->command))
2356 return error(_("unknown command %d"), item->command);
2357
2358 todo_list->current++;
2359 if (res)
2360 return res;
2361 }
2362
2363 if (is_rebase_i(opts)) {
2364 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
2365 struct stat st;
2366
2367 /* Stopped in the middle, as planned? */
2368 if (todo_list->current < todo_list->nr)
2369 return 0;
2370
2371 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
2372 starts_with(head_ref.buf, "refs/")) {
2373 const char *msg;
2374 struct object_id head, orig;
2375 int res;
2376
2377 if (get_oid("HEAD", &head)) {
2378 res = error(_("cannot read HEAD"));
2379 cleanup_head_ref:
2380 strbuf_release(&head_ref);
2381 strbuf_release(&buf);
2382 return res;
2383 }
2384 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
2385 get_oid_hex(buf.buf, &orig)) {
2386 res = error(_("could not read orig-head"));
2387 goto cleanup_head_ref;
2388 }
2389 strbuf_reset(&buf);
2390 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
2391 res = error(_("could not read 'onto'"));
2392 goto cleanup_head_ref;
2393 }
2394 msg = reflog_message(opts, "finish", "%s onto %s",
2395 head_ref.buf, buf.buf);
2396 if (update_ref(msg, head_ref.buf, &head, &orig,
2397 REF_NODEREF, UPDATE_REFS_MSG_ON_ERR)) {
2398 res = error(_("could not update %s"),
2399 head_ref.buf);
2400 goto cleanup_head_ref;
2401 }
2402 msg = reflog_message(opts, "finish", "returning to %s",
2403 head_ref.buf);
2404 if (create_symref("HEAD", head_ref.buf, msg)) {
2405 res = error(_("could not update HEAD to %s"),
2406 head_ref.buf);
2407 goto cleanup_head_ref;
2408 }
2409 strbuf_reset(&buf);
2410 }
2411
2412 if (opts->verbose) {
2413 struct rev_info log_tree_opt;
2414 struct object_id orig, head;
2415
2416 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2417 init_revisions(&log_tree_opt, NULL);
2418 log_tree_opt.diff = 1;
2419 log_tree_opt.diffopt.output_format =
2420 DIFF_FORMAT_DIFFSTAT;
2421 log_tree_opt.disable_stdin = 1;
2422
2423 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
2424 !get_oid(buf.buf, &orig) &&
2425 !get_oid("HEAD", &head)) {
2426 diff_tree_oid(&orig, &head, "",
2427 &log_tree_opt.diffopt);
2428 log_tree_diff_flush(&log_tree_opt);
2429 }
2430 }
2431 flush_rewritten_pending();
2432 if (!stat(rebase_path_rewritten_list(), &st) &&
2433 st.st_size > 0) {
2434 struct child_process child = CHILD_PROCESS_INIT;
2435 const char *post_rewrite_hook =
2436 find_hook("post-rewrite");
2437
2438 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
2439 child.git_cmd = 1;
2440 argv_array_push(&child.args, "notes");
2441 argv_array_push(&child.args, "copy");
2442 argv_array_push(&child.args, "--for-rewrite=rebase");
2443 /* we don't care if this copying failed */
2444 run_command(&child);
2445
2446 if (post_rewrite_hook) {
2447 struct child_process hook = CHILD_PROCESS_INIT;
2448
2449 hook.in = open(rebase_path_rewritten_list(),
2450 O_RDONLY);
2451 hook.stdout_to_stderr = 1;
2452 argv_array_push(&hook.args, post_rewrite_hook);
2453 argv_array_push(&hook.args, "rebase");
2454 /* we don't care if this hook failed */
2455 run_command(&hook);
2456 }
2457 }
2458 apply_autostash(opts);
2459
2460 fprintf(stderr, "Successfully rebased and updated %s.\n",
2461 head_ref.buf);
2462
2463 strbuf_release(&buf);
2464 strbuf_release(&head_ref);
2465 }
2466
2467 /*
2468 * Sequence of picks finished successfully; cleanup by
2469 * removing the .git/sequencer directory
2470 */
2471 return sequencer_remove_state(opts);
2472 }
2473
2474 static int continue_single_pick(void)
2475 {
2476 const char *argv[] = { "commit", NULL };
2477
2478 if (!file_exists(git_path_cherry_pick_head()) &&
2479 !file_exists(git_path_revert_head()))
2480 return error(_("no cherry-pick or revert in progress"));
2481 return run_command_v_opt(argv, RUN_GIT_CMD);
2482 }
2483
2484 static int commit_staged_changes(struct replay_opts *opts)
2485 {
2486 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
2487
2488 if (has_unstaged_changes(1))
2489 return error(_("cannot rebase: You have unstaged changes."));
2490 if (!has_uncommitted_changes(0)) {
2491 const char *cherry_pick_head = git_path_cherry_pick_head();
2492
2493 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
2494 return error(_("could not remove CHERRY_PICK_HEAD"));
2495 return 0;
2496 }
2497
2498 if (file_exists(rebase_path_amend())) {
2499 struct strbuf rev = STRBUF_INIT;
2500 struct object_id head, to_amend;
2501
2502 if (get_oid("HEAD", &head))
2503 return error(_("cannot amend non-existing commit"));
2504 if (!read_oneliner(&rev, rebase_path_amend(), 0))
2505 return error(_("invalid file: '%s'"), rebase_path_amend());
2506 if (get_oid_hex(rev.buf, &to_amend))
2507 return error(_("invalid contents: '%s'"),
2508 rebase_path_amend());
2509 if (oidcmp(&head, &to_amend))
2510 return error(_("\nYou have uncommitted changes in your "
2511 "working tree. Please, commit them\n"
2512 "first and then run 'git rebase "
2513 "--continue' again."));
2514
2515 strbuf_release(&rev);
2516 flags |= AMEND_MSG;
2517 }
2518
2519 if (run_git_commit(rebase_path_message(), opts, flags))
2520 return error(_("could not commit staged changes."));
2521 unlink(rebase_path_amend());
2522 return 0;
2523 }
2524
2525 int sequencer_continue(struct replay_opts *opts)
2526 {
2527 struct todo_list todo_list = TODO_LIST_INIT;
2528 int res;
2529
2530 if (read_and_refresh_cache(opts))
2531 return -1;
2532
2533 if (is_rebase_i(opts)) {
2534 if (commit_staged_changes(opts))
2535 return -1;
2536 } else if (!file_exists(get_todo_path(opts)))
2537 return continue_single_pick();
2538 if (read_populate_opts(opts))
2539 return -1;
2540 if ((res = read_populate_todo(&todo_list, opts)))
2541 goto release_todo_list;
2542
2543 if (!is_rebase_i(opts)) {
2544 /* Verify that the conflict has been resolved */
2545 if (file_exists(git_path_cherry_pick_head()) ||
2546 file_exists(git_path_revert_head())) {
2547 res = continue_single_pick();
2548 if (res)
2549 goto release_todo_list;
2550 }
2551 if (index_differs_from("HEAD", NULL, 0)) {
2552 res = error_dirty_index(opts);
2553 goto release_todo_list;
2554 }
2555 todo_list.current++;
2556 } else if (file_exists(rebase_path_stopped_sha())) {
2557 struct strbuf buf = STRBUF_INIT;
2558 struct object_id oid;
2559
2560 if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
2561 !get_oid_committish(buf.buf, &oid))
2562 record_in_rewritten(&oid, peek_command(&todo_list, 0));
2563 strbuf_release(&buf);
2564 }
2565
2566 res = pick_commits(&todo_list, opts);
2567 release_todo_list:
2568 todo_list_release(&todo_list);
2569 return res;
2570 }
2571
2572 static int single_pick(struct commit *cmit, struct replay_opts *opts)
2573 {
2574 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
2575 return do_pick_commit(opts->action == REPLAY_PICK ?
2576 TODO_PICK : TODO_REVERT, cmit, opts, 0);
2577 }
2578
2579 int sequencer_pick_revisions(struct replay_opts *opts)
2580 {
2581 struct todo_list todo_list = TODO_LIST_INIT;
2582 struct object_id oid;
2583 int i, res;
2584
2585 assert(opts->revs);
2586 if (read_and_refresh_cache(opts))
2587 return -1;
2588
2589 for (i = 0; i < opts->revs->pending.nr; i++) {
2590 struct object_id oid;
2591 const char *name = opts->revs->pending.objects[i].name;
2592
2593 /* This happens when using --stdin. */
2594 if (!strlen(name))
2595 continue;
2596
2597 if (!get_oid(name, &oid)) {
2598 if (!lookup_commit_reference_gently(&oid, 1)) {
2599 enum object_type type = sha1_object_info(oid.hash, NULL);
2600 return error(_("%s: can't cherry-pick a %s"),
2601 name, typename(type));
2602 }
2603 } else
2604 return error(_("%s: bad revision"), name);
2605 }
2606
2607 /*
2608 * If we were called as "git cherry-pick <commit>", just
2609 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
2610 * REVERT_HEAD, and don't touch the sequencer state.
2611 * This means it is possible to cherry-pick in the middle
2612 * of a cherry-pick sequence.
2613 */
2614 if (opts->revs->cmdline.nr == 1 &&
2615 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
2616 opts->revs->no_walk &&
2617 !opts->revs->cmdline.rev->flags) {
2618 struct commit *cmit;
2619 if (prepare_revision_walk(opts->revs))
2620 return error(_("revision walk setup failed"));
2621 cmit = get_revision(opts->revs);
2622 if (!cmit || get_revision(opts->revs))
2623 return error("BUG: expected exactly one commit from walk");
2624 return single_pick(cmit, opts);
2625 }
2626
2627 /*
2628 * Start a new cherry-pick/ revert sequence; but
2629 * first, make sure that an existing one isn't in
2630 * progress
2631 */
2632
2633 if (walk_revs_populate_todo(&todo_list, opts) ||
2634 create_seq_dir() < 0)
2635 return -1;
2636 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
2637 return error(_("can't revert as initial commit"));
2638 if (save_head(oid_to_hex(&oid)))
2639 return -1;
2640 if (save_opts(opts))
2641 return -1;
2642 update_abort_safety_file();
2643 res = pick_commits(&todo_list, opts);
2644 todo_list_release(&todo_list);
2645 return res;
2646 }
2647
2648 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
2649 {
2650 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
2651 struct strbuf sob = STRBUF_INIT;
2652 int has_footer;
2653
2654 strbuf_addstr(&sob, sign_off_header);
2655 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
2656 getenv("GIT_COMMITTER_EMAIL")));
2657 strbuf_addch(&sob, '\n');
2658
2659 if (!ignore_footer)
2660 strbuf_complete_line(msgbuf);
2661
2662 /*
2663 * If the whole message buffer is equal to the sob, pretend that we
2664 * found a conforming footer with a matching sob
2665 */
2666 if (msgbuf->len - ignore_footer == sob.len &&
2667 !strncmp(msgbuf->buf, sob.buf, sob.len))
2668 has_footer = 3;
2669 else
2670 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
2671
2672 if (!has_footer) {
2673 const char *append_newlines = NULL;
2674 size_t len = msgbuf->len - ignore_footer;
2675
2676 if (!len) {
2677 /*
2678 * The buffer is completely empty. Leave foom for
2679 * the title and body to be filled in by the user.
2680 */
2681 append_newlines = "\n\n";
2682 } else if (len == 1) {
2683 /*
2684 * Buffer contains a single newline. Add another
2685 * so that we leave room for the title and body.
2686 */
2687 append_newlines = "\n";
2688 } else if (msgbuf->buf[len - 2] != '\n') {
2689 /*
2690 * Buffer ends with a single newline. Add another
2691 * so that there is an empty line between the message
2692 * body and the sob.
2693 */
2694 append_newlines = "\n";
2695 } /* else, the buffer already ends with two newlines. */
2696
2697 if (append_newlines)
2698 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
2699 append_newlines, strlen(append_newlines));
2700 }
2701
2702 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
2703 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
2704 sob.buf, sob.len);
2705
2706 strbuf_release(&sob);
2707 }
2708
2709 int sequencer_make_script(int keep_empty, FILE *out,
2710 int argc, const char **argv)
2711 {
2712 char *format = NULL;
2713 struct pretty_print_context pp = {0};
2714 struct strbuf buf = STRBUF_INIT;
2715 struct rev_info revs;
2716 struct commit *commit;
2717
2718 init_revisions(&revs, NULL);
2719 revs.verbose_header = 1;
2720 revs.max_parents = 1;
2721 revs.cherry_pick = 1;
2722 revs.limited = 1;
2723 revs.reverse = 1;
2724 revs.right_only = 1;
2725 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
2726 revs.topo_order = 1;
2727
2728 revs.pretty_given = 1;
2729 git_config_get_string("rebase.instructionFormat", &format);
2730 if (!format || !*format) {
2731 free(format);
2732 format = xstrdup("%s");
2733 }
2734 get_commit_format(format, &revs);
2735 free(format);
2736 pp.fmt = revs.commit_format;
2737 pp.output_encoding = get_log_output_encoding();
2738
2739 if (setup_revisions(argc, argv, &revs, NULL) > 1)
2740 return error(_("make_script: unhandled options"));
2741
2742 if (prepare_revision_walk(&revs) < 0)
2743 return error(_("make_script: error preparing revisions"));
2744
2745 while ((commit = get_revision(&revs))) {
2746 strbuf_reset(&buf);
2747 if (!keep_empty && is_original_commit_empty(commit))
2748 strbuf_addf(&buf, "%c ", comment_line_char);
2749 strbuf_addf(&buf, "pick %s ", oid_to_hex(&commit->object.oid));
2750 pretty_print_commit(&pp, commit, &buf);
2751 strbuf_addch(&buf, '\n');
2752 fputs(buf.buf, out);
2753 }
2754 strbuf_release(&buf);
2755 return 0;
2756 }
2757
2758
2759 int transform_todo_ids(int shorten_ids)
2760 {
2761 const char *todo_file = rebase_path_todo();
2762 struct todo_list todo_list = TODO_LIST_INIT;
2763 int fd, res, i;
2764 FILE *out;
2765
2766 strbuf_reset(&todo_list.buf);
2767 fd = open(todo_file, O_RDONLY);
2768 if (fd < 0)
2769 return error_errno(_("could not open '%s'"), todo_file);
2770 if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
2771 close(fd);
2772 return error(_("could not read '%s'."), todo_file);
2773 }
2774 close(fd);
2775
2776 res = parse_insn_buffer(todo_list.buf.buf, &todo_list);
2777 if (res) {
2778 todo_list_release(&todo_list);
2779 return error(_("unusable todo list: '%s'"), todo_file);
2780 }
2781
2782 out = fopen(todo_file, "w");
2783 if (!out) {
2784 todo_list_release(&todo_list);
2785 return error(_("unable to open '%s' for writing"), todo_file);
2786 }
2787 for (i = 0; i < todo_list.nr; i++) {
2788 struct todo_item *item = todo_list.items + i;
2789 int bol = item->offset_in_buf;
2790 const char *p = todo_list.buf.buf + bol;
2791 int eol = i + 1 < todo_list.nr ?
2792 todo_list.items[i + 1].offset_in_buf :
2793 todo_list.buf.len;
2794
2795 if (item->command >= TODO_EXEC && item->command != TODO_DROP)
2796 fwrite(p, eol - bol, 1, out);
2797 else {
2798 const char *id = shorten_ids ?
2799 short_commit_name(item->commit) :
2800 oid_to_hex(&item->commit->object.oid);
2801 int len;
2802
2803 p += strspn(p, " \t"); /* left-trim command */
2804 len = strcspn(p, " \t"); /* length of command */
2805
2806 fprintf(out, "%.*s %s %.*s\n",
2807 len, p, id, item->arg_len, item->arg);
2808 }
2809 }
2810 fclose(out);
2811 todo_list_release(&todo_list);
2812 return 0;
2813 }
2814
2815 enum check_level {
2816 CHECK_IGNORE = 0, CHECK_WARN, CHECK_ERROR
2817 };
2818
2819 static enum check_level get_missing_commit_check_level(void)
2820 {
2821 const char *value;
2822
2823 if (git_config_get_value("rebase.missingcommitscheck", &value) ||
2824 !strcasecmp("ignore", value))
2825 return CHECK_IGNORE;
2826 if (!strcasecmp("warn", value))
2827 return CHECK_WARN;
2828 if (!strcasecmp("error", value))
2829 return CHECK_ERROR;
2830 warning(_("unrecognized setting %s for option "
2831 "rebase.missingCommitsCheck. Ignoring."), value);
2832 return CHECK_IGNORE;
2833 }
2834
2835 /*
2836 * Check if the user dropped some commits by mistake
2837 * Behaviour determined by rebase.missingCommitsCheck.
2838 * Check if there is an unrecognized command or a
2839 * bad SHA-1 in a command.
2840 */
2841 int check_todo_list(void)
2842 {
2843 enum check_level check_level = get_missing_commit_check_level();
2844 struct strbuf todo_file = STRBUF_INIT;
2845 struct todo_list todo_list = TODO_LIST_INIT;
2846 struct strbuf missing = STRBUF_INIT;
2847 int advise_to_edit_todo = 0, res = 0, fd, i;
2848
2849 strbuf_addstr(&todo_file, rebase_path_todo());
2850 fd = open(todo_file.buf, O_RDONLY);
2851 if (fd < 0) {
2852 res = error_errno(_("could not open '%s'"), todo_file.buf);
2853 goto leave_check;
2854 }
2855 if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
2856 close(fd);
2857 res = error(_("could not read '%s'."), todo_file.buf);
2858 goto leave_check;
2859 }
2860 close(fd);
2861 advise_to_edit_todo = res =
2862 parse_insn_buffer(todo_list.buf.buf, &todo_list);
2863
2864 if (res || check_level == CHECK_IGNORE)
2865 goto leave_check;
2866
2867 /* Mark the commits in git-rebase-todo as seen */
2868 for (i = 0; i < todo_list.nr; i++) {
2869 struct commit *commit = todo_list.items[i].commit;
2870 if (commit)
2871 commit->util = (void *)1;
2872 }
2873
2874 todo_list_release(&todo_list);
2875 strbuf_addstr(&todo_file, ".backup");
2876 fd = open(todo_file.buf, O_RDONLY);
2877 if (fd < 0) {
2878 res = error_errno(_("could not open '%s'"), todo_file.buf);
2879 goto leave_check;
2880 }
2881 if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
2882 close(fd);
2883 res = error(_("could not read '%s'."), todo_file.buf);
2884 goto leave_check;
2885 }
2886 close(fd);
2887 strbuf_release(&todo_file);
2888 res = !!parse_insn_buffer(todo_list.buf.buf, &todo_list);
2889
2890 /* Find commits in git-rebase-todo.backup yet unseen */
2891 for (i = todo_list.nr - 1; i >= 0; i--) {
2892 struct todo_item *item = todo_list.items + i;
2893 struct commit *commit = item->commit;
2894 if (commit && !commit->util) {
2895 strbuf_addf(&missing, " - %s %.*s\n",
2896 short_commit_name(commit),
2897 item->arg_len, item->arg);
2898 commit->util = (void *)1;
2899 }
2900 }
2901
2902 /* Warn about missing commits */
2903 if (!missing.len)
2904 goto leave_check;
2905
2906 if (check_level == CHECK_ERROR)
2907 advise_to_edit_todo = res = 1;
2908
2909 fprintf(stderr,
2910 _("Warning: some commits may have been dropped accidentally.\n"
2911 "Dropped commits (newer to older):\n"));
2912
2913 /* Make the list user-friendly and display */
2914 fputs(missing.buf, stderr);
2915 strbuf_release(&missing);
2916
2917 fprintf(stderr, _("To avoid this message, use \"drop\" to "
2918 "explicitly remove a commit.\n\n"
2919 "Use 'git config rebase.missingCommitsCheck' to change "
2920 "the level of warnings.\n"
2921 "The possible behaviours are: ignore, warn, error.\n\n"));
2922
2923 leave_check:
2924 strbuf_release(&todo_file);
2925 todo_list_release(&todo_list);
2926
2927 if (advise_to_edit_todo)
2928 fprintf(stderr,
2929 _("You can fix this with 'git rebase --edit-todo' "
2930 "and then run 'git rebase --continue'.\n"
2931 "Or you can abort the rebase with 'git rebase"
2932 " --abort'.\n"));
2933
2934 return res;
2935 }
2936
2937 /* skip picking commits whose parents are unchanged */
2938 int skip_unnecessary_picks(void)
2939 {
2940 const char *todo_file = rebase_path_todo();
2941 struct strbuf buf = STRBUF_INIT;
2942 struct todo_list todo_list = TODO_LIST_INIT;
2943 struct object_id onto_oid, *oid = &onto_oid, *parent_oid;
2944 int fd, i;
2945
2946 if (!read_oneliner(&buf, rebase_path_onto(), 0))
2947 return error(_("could not read 'onto'"));
2948 if (get_oid(buf.buf, &onto_oid)) {
2949 strbuf_release(&buf);
2950 return error(_("need a HEAD to fixup"));
2951 }
2952 strbuf_release(&buf);
2953
2954 fd = open(todo_file, O_RDONLY);
2955 if (fd < 0) {
2956 return error_errno(_("could not open '%s'"), todo_file);
2957 }
2958 if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
2959 close(fd);
2960 return error(_("could not read '%s'."), todo_file);
2961 }
2962 close(fd);
2963 if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
2964 todo_list_release(&todo_list);
2965 return -1;
2966 }
2967
2968 for (i = 0; i < todo_list.nr; i++) {
2969 struct todo_item *item = todo_list.items + i;
2970
2971 if (item->command >= TODO_NOOP)
2972 continue;
2973 if (item->command != TODO_PICK)
2974 break;
2975 if (parse_commit(item->commit)) {
2976 todo_list_release(&todo_list);
2977 return error(_("could not parse commit '%s'"),
2978 oid_to_hex(&item->commit->object.oid));
2979 }
2980 if (!item->commit->parents)
2981 break; /* root commit */
2982 if (item->commit->parents->next)
2983 break; /* merge commit */
2984 parent_oid = &item->commit->parents->item->object.oid;
2985 if (hashcmp(parent_oid->hash, oid->hash))
2986 break;
2987 oid = &item->commit->object.oid;
2988 }
2989 if (i > 0) {
2990 int offset = i < todo_list.nr ?
2991 todo_list.items[i].offset_in_buf : todo_list.buf.len;
2992 const char *done_path = rebase_path_done();
2993
2994 fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
2995 if (fd < 0) {
2996 error_errno(_("could not open '%s' for writing"),
2997 done_path);
2998 todo_list_release(&todo_list);
2999 return -1;
3000 }
3001 if (write_in_full(fd, todo_list.buf.buf, offset) < 0) {
3002 error_errno(_("could not write to '%s'"), done_path);
3003 todo_list_release(&todo_list);
3004 close(fd);
3005 return -1;
3006 }
3007 close(fd);
3008
3009 fd = open(rebase_path_todo(), O_WRONLY, 0666);
3010 if (fd < 0) {
3011 error_errno(_("could not open '%s' for writing"),
3012 rebase_path_todo());
3013 todo_list_release(&todo_list);
3014 return -1;
3015 }
3016 if (write_in_full(fd, todo_list.buf.buf + offset,
3017 todo_list.buf.len - offset) < 0) {
3018 error_errno(_("could not write to '%s'"),
3019 rebase_path_todo());
3020 close(fd);
3021 todo_list_release(&todo_list);
3022 return -1;
3023 }
3024 if (ftruncate(fd, todo_list.buf.len - offset) < 0) {
3025 error_errno(_("could not truncate '%s'"),
3026 rebase_path_todo());
3027 todo_list_release(&todo_list);
3028 close(fd);
3029 return -1;
3030 }
3031 close(fd);
3032
3033 todo_list.current = i;
3034 if (is_fixup(peek_command(&todo_list, 0)))
3035 record_in_rewritten(oid, peek_command(&todo_list, 0));
3036 }
3037
3038 todo_list_release(&todo_list);
3039 printf("%s\n", oid_to_hex(oid));
3040
3041 return 0;
3042 }
3043
3044 struct subject2item_entry {
3045 struct hashmap_entry entry;
3046 int i;
3047 char subject[FLEX_ARRAY];
3048 };
3049
3050 static int subject2item_cmp(const void *fndata,
3051 const struct subject2item_entry *a,
3052 const struct subject2item_entry *b, const void *key)
3053 {
3054 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
3055 }
3056
3057 /*
3058 * Rearrange the todo list that has both "pick commit-id msg" and "pick
3059 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
3060 * after the former, and change "pick" to "fixup"/"squash".
3061 *
3062 * Note that if the config has specified a custom instruction format, each log
3063 * message will have to be retrieved from the commit (as the oneline in the
3064 * script cannot be trusted) in order to normalize the autosquash arrangement.
3065 */
3066 int rearrange_squash(void)
3067 {
3068 const char *todo_file = rebase_path_todo();
3069 struct todo_list todo_list = TODO_LIST_INIT;
3070 struct hashmap subject2item;
3071 int res = 0, rearranged = 0, *next, *tail, fd, i;
3072 char **subjects;
3073
3074 fd = open(todo_file, O_RDONLY);
3075 if (fd < 0)
3076 return error_errno(_("could not open '%s'"), todo_file);
3077 if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
3078 close(fd);
3079 return error(_("could not read '%s'."), todo_file);
3080 }
3081 close(fd);
3082 if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
3083 todo_list_release(&todo_list);
3084 return -1;
3085 }
3086
3087 /*
3088 * The hashmap maps onelines to the respective todo list index.
3089 *
3090 * If any items need to be rearranged, the next[i] value will indicate
3091 * which item was moved directly after the i'th.
3092 *
3093 * In that case, last[i] will indicate the index of the latest item to
3094 * be moved to appear after the i'th.
3095 */
3096 hashmap_init(&subject2item, (hashmap_cmp_fn) subject2item_cmp,
3097 NULL, todo_list.nr);
3098 ALLOC_ARRAY(next, todo_list.nr);
3099 ALLOC_ARRAY(tail, todo_list.nr);
3100 ALLOC_ARRAY(subjects, todo_list.nr);
3101 for (i = 0; i < todo_list.nr; i++) {
3102 struct strbuf buf = STRBUF_INIT;
3103 struct todo_item *item = todo_list.items + i;
3104 const char *commit_buffer, *subject, *p;
3105 size_t subject_len;
3106 int i2 = -1;
3107 struct subject2item_entry *entry;
3108
3109 next[i] = tail[i] = -1;
3110 if (item->command >= TODO_EXEC) {
3111 subjects[i] = NULL;
3112 continue;
3113 }
3114
3115 if (is_fixup(item->command)) {
3116 todo_list_release(&todo_list);
3117 return error(_("the script was already rearranged."));
3118 }
3119
3120 item->commit->util = item;
3121
3122 parse_commit(item->commit);
3123 commit_buffer = get_commit_buffer(item->commit, NULL);
3124 find_commit_subject(commit_buffer, &subject);
3125 format_subject(&buf, subject, " ");
3126 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
3127 unuse_commit_buffer(item->commit, commit_buffer);
3128 if ((skip_prefix(subject, "fixup! ", &p) ||
3129 skip_prefix(subject, "squash! ", &p))) {
3130 struct commit *commit2;
3131
3132 for (;;) {
3133 while (isspace(*p))
3134 p++;
3135 if (!skip_prefix(p, "fixup! ", &p) &&
3136 !skip_prefix(p, "squash! ", &p))
3137 break;
3138 }
3139
3140 if ((entry = hashmap_get_from_hash(&subject2item,
3141 strhash(p), p)))
3142 /* found by title */
3143 i2 = entry->i;
3144 else if (!strchr(p, ' ') &&
3145 (commit2 =
3146 lookup_commit_reference_by_name(p)) &&
3147 commit2->util)
3148 /* found by commit name */
3149 i2 = (struct todo_item *)commit2->util
3150 - todo_list.items;
3151 else {
3152 /* copy can be a prefix of the commit subject */
3153 for (i2 = 0; i2 < i; i2++)
3154 if (subjects[i2] &&
3155 starts_with(subjects[i2], p))
3156 break;
3157 if (i2 == i)
3158 i2 = -1;
3159 }
3160 }
3161 if (i2 >= 0) {
3162 rearranged = 1;
3163 todo_list.items[i].command =
3164 starts_with(subject, "fixup!") ?
3165 TODO_FIXUP : TODO_SQUASH;
3166 if (next[i2] < 0)
3167 next[i2] = i;
3168 else
3169 next[tail[i2]] = i;
3170 tail[i2] = i;
3171 } else if (!hashmap_get_from_hash(&subject2item,
3172 strhash(subject), subject)) {
3173 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
3174 entry->i = i;
3175 hashmap_entry_init(entry, strhash(entry->subject));
3176 hashmap_put(&subject2item, entry);
3177 }
3178 }
3179
3180 if (rearranged) {
3181 struct strbuf buf = STRBUF_INIT;
3182
3183 for (i = 0; i < todo_list.nr; i++) {
3184 enum todo_command command = todo_list.items[i].command;
3185 int cur = i;
3186
3187 /*
3188 * Initially, all commands are 'pick's. If it is a
3189 * fixup or a squash now, we have rearranged it.
3190 */
3191 if (is_fixup(command))
3192 continue;
3193
3194 while (cur >= 0) {
3195 int offset = todo_list.items[cur].offset_in_buf;
3196 int end_offset = cur + 1 < todo_list.nr ?
3197 todo_list.items[cur + 1].offset_in_buf :
3198 todo_list.buf.len;
3199 char *bol = todo_list.buf.buf + offset;
3200 char *eol = todo_list.buf.buf + end_offset;
3201
3202 /* replace 'pick', by 'fixup' or 'squash' */
3203 command = todo_list.items[cur].command;
3204 if (is_fixup(command)) {
3205 strbuf_addstr(&buf,
3206 todo_command_info[command].str);
3207 bol += strcspn(bol, " \t");
3208 }
3209
3210 strbuf_add(&buf, bol, eol - bol);
3211
3212 cur = next[cur];
3213 }
3214 }
3215
3216 fd = open(todo_file, O_WRONLY);
3217 if (fd < 0)
3218 res = error_errno(_("could not open '%s'"), todo_file);
3219 else if (write(fd, buf.buf, buf.len) < 0)
3220 res = error_errno(_("could not write to '%s'"), todo_file);
3221 else if (ftruncate(fd, buf.len) < 0)
3222 res = error_errno(_("could not truncate '%s'"),
3223 todo_file);
3224 close(fd);
3225 strbuf_release(&buf);
3226 }
3227
3228 free(next);
3229 free(tail);
3230 for (i = 0; i < todo_list.nr; i++)
3231 free(subjects[i]);
3232 free(subjects);
3233 hashmap_free(&subject2item, 1);
3234 todo_list_release(&todo_list);
3235
3236 return res;
3237 }