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