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