THIS IS A TEST INSTANCE ONLY! REPOSITORIES CAN BE DELETED AT ANY TIME!

Git Source Code Mirror - This is a publish-only repository and all pull requests are ignored. Please follow Documentation/SubmittingPatches procedure for any of your improvements.
git
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

5267 líneas
144KB

  1. #include "cache.h"
  2. #include "config.h"
  3. #include "lockfile.h"
  4. #include "dir.h"
  5. #include "object-store.h"
  6. #include "object.h"
  7. #include "commit.h"
  8. #include "sequencer.h"
  9. #include "tag.h"
  10. #include "run-command.h"
  11. #include "exec-cmd.h"
  12. #include "utf8.h"
  13. #include "cache-tree.h"
  14. #include "diff.h"
  15. #include "revision.h"
  16. #include "rerere.h"
  17. #include "merge-recursive.h"
  18. #include "refs.h"
  19. #include "argv-array.h"
  20. #include "quote.h"
  21. #include "trailer.h"
  22. #include "log-tree.h"
  23. #include "wt-status.h"
  24. #include "hashmap.h"
  25. #include "notes-utils.h"
  26. #include "sigchain.h"
  27. #include "unpack-trees.h"
  28. #include "worktree.h"
  29. #include "oidmap.h"
  30. #include "oidset.h"
  31. #include "commit-slab.h"
  32. #include "alias.h"
  33. #include "commit-reach.h"
  34. #include "rebase-interactive.h"
  35. #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
  36. static const char sign_off_header[] = "Signed-off-by: ";
  37. static const char cherry_picked_prefix[] = "(cherry picked from commit ";
  38. GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
  39. GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
  40. static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
  41. static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
  42. static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
  43. static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
  44. static GIT_PATH_FUNC(rebase_path, "rebase-merge")
  45. /*
  46. * The file containing rebase commands, comments, and empty lines.
  47. * This file is created by "git rebase -i" then edited by the user. As
  48. * the lines are processed, they are removed from the front of this
  49. * file and written to the tail of 'done'.
  50. */
  51. GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
  52. GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
  53. /*
  54. * The rebase command lines that have already been processed. A line
  55. * is moved here when it is first handled, before any associated user
  56. * actions.
  57. */
  58. static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
  59. /*
  60. * The file to keep track of how many commands were already processed (e.g.
  61. * for the prompt).
  62. */
  63. static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
  64. /*
  65. * The file to keep track of how many commands are to be processed in total
  66. * (e.g. for the prompt).
  67. */
  68. static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
  69. /*
  70. * The commit message that is planned to be used for any changes that
  71. * need to be committed following a user interaction.
  72. */
  73. static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
  74. /*
  75. * The file into which is accumulated the suggested commit message for
  76. * squash/fixup commands. When the first of a series of squash/fixups
  77. * is seen, the file is created and the commit message from the
  78. * previous commit and from the first squash/fixup commit are written
  79. * to it. The commit message for each subsequent squash/fixup commit
  80. * is appended to the file as it is processed.
  81. */
  82. static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
  83. /*
  84. * If the current series of squash/fixups has not yet included a squash
  85. * command, then this file exists and holds the commit message of the
  86. * original "pick" commit. (If the series ends without a "squash"
  87. * command, then this can be used as the commit message of the combined
  88. * commit without opening the editor.)
  89. */
  90. static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
  91. /*
  92. * This file contains the list fixup/squash commands that have been
  93. * accumulated into message-fixup or message-squash so far.
  94. */
  95. static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
  96. /*
  97. * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
  98. * GIT_AUTHOR_DATE that will be used for the commit that is currently
  99. * being rebased.
  100. */
  101. static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
  102. /*
  103. * When an "edit" rebase command is being processed, the SHA1 of the
  104. * commit to be edited is recorded in this file. When "git rebase
  105. * --continue" is executed, if there are any staged changes then they
  106. * will be amended to the HEAD commit, but only provided the HEAD
  107. * commit is still the commit to be edited. When any other rebase
  108. * command is processed, this file is deleted.
  109. */
  110. static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
  111. /*
  112. * When we stop at a given patch via the "edit" command, this file contains
  113. * the abbreviated commit name of the corresponding patch.
  114. */
  115. static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
  116. /*
  117. * For the post-rewrite hook, we make a list of rewritten commits and
  118. * their new sha1s. The rewritten-pending list keeps the sha1s of
  119. * commits that have been processed, but not committed yet,
  120. * e.g. because they are waiting for a 'squash' command.
  121. */
  122. static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
  123. static GIT_PATH_FUNC(rebase_path_rewritten_pending,
  124. "rebase-merge/rewritten-pending")
  125. /*
  126. * The path of the file containig the OID of the "squash onto" commit, i.e.
  127. * the dummy commit used for `reset [new root]`.
  128. */
  129. static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
  130. /*
  131. * The path of the file listing refs that need to be deleted after the rebase
  132. * finishes. This is used by the `label` command to record the need for cleanup.
  133. */
  134. static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
  135. /*
  136. * The following files are written by git-rebase just after parsing the
  137. * command-line.
  138. */
  139. static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
  140. static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
  141. static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
  142. static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
  143. static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
  144. static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
  145. static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
  146. static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
  147. static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
  148. static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
  149. static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
  150. static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
  151. static int git_sequencer_config(const char *k, const char *v, void *cb)
  152. {
  153. struct replay_opts *opts = cb;
  154. int status;
  155. if (!strcmp(k, "commit.cleanup")) {
  156. const char *s;
  157. status = git_config_string(&s, k, v);
  158. if (status)
  159. return status;
  160. if (!strcmp(s, "verbatim")) {
  161. opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
  162. opts->explicit_cleanup = 1;
  163. } else if (!strcmp(s, "whitespace")) {
  164. opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
  165. opts->explicit_cleanup = 1;
  166. } else if (!strcmp(s, "strip")) {
  167. opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
  168. opts->explicit_cleanup = 1;
  169. } else if (!strcmp(s, "scissors")) {
  170. opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
  171. opts->explicit_cleanup = 1;
  172. } else {
  173. warning(_("invalid commit message cleanup mode '%s'"),
  174. s);
  175. }
  176. free((char *)s);
  177. return status;
  178. }
  179. if (!strcmp(k, "commit.gpgsign")) {
  180. opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
  181. return 0;
  182. }
  183. status = git_gpg_config(k, v, NULL);
  184. if (status)
  185. return status;
  186. return git_diff_basic_config(k, v, NULL);
  187. }
  188. void sequencer_init_config(struct replay_opts *opts)
  189. {
  190. opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
  191. git_config(git_sequencer_config, opts);
  192. }
  193. static inline int is_rebase_i(const struct replay_opts *opts)
  194. {
  195. return opts->action == REPLAY_INTERACTIVE_REBASE;
  196. }
  197. static const char *get_dir(const struct replay_opts *opts)
  198. {
  199. if (is_rebase_i(opts))
  200. return rebase_path();
  201. return git_path_seq_dir();
  202. }
  203. static const char *get_todo_path(const struct replay_opts *opts)
  204. {
  205. if (is_rebase_i(opts))
  206. return rebase_path_todo();
  207. return git_path_todo_file();
  208. }
  209. /*
  210. * Returns 0 for non-conforming footer
  211. * Returns 1 for conforming footer
  212. * Returns 2 when sob exists within conforming footer
  213. * Returns 3 when sob exists within conforming footer as last entry
  214. */
  215. static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
  216. size_t ignore_footer)
  217. {
  218. struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
  219. struct trailer_info info;
  220. size_t i;
  221. int found_sob = 0, found_sob_last = 0;
  222. opts.no_divider = 1;
  223. trailer_info_get(&info, sb->buf, &opts);
  224. if (info.trailer_start == info.trailer_end)
  225. return 0;
  226. for (i = 0; i < info.trailer_nr; i++)
  227. if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
  228. found_sob = 1;
  229. if (i == info.trailer_nr - 1)
  230. found_sob_last = 1;
  231. }
  232. trailer_info_release(&info);
  233. if (found_sob_last)
  234. return 3;
  235. if (found_sob)
  236. return 2;
  237. return 1;
  238. }
  239. static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
  240. {
  241. static struct strbuf buf = STRBUF_INIT;
  242. strbuf_reset(&buf);
  243. if (opts->gpg_sign)
  244. sq_quotef(&buf, "-S%s", opts->gpg_sign);
  245. return buf.buf;
  246. }
  247. int sequencer_remove_state(struct replay_opts *opts)
  248. {
  249. struct strbuf buf = STRBUF_INIT;
  250. int i, ret = 0;
  251. if (is_rebase_i(opts) &&
  252. strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
  253. char *p = buf.buf;
  254. while (*p) {
  255. char *eol = strchr(p, '\n');
  256. if (eol)
  257. *eol = '\0';
  258. if (delete_ref("(rebase -i) cleanup", p, NULL, 0) < 0) {
  259. warning(_("could not delete '%s'"), p);
  260. ret = -1;
  261. }
  262. if (!eol)
  263. break;
  264. p = eol + 1;
  265. }
  266. }
  267. free(opts->gpg_sign);
  268. free(opts->strategy);
  269. for (i = 0; i < opts->xopts_nr; i++)
  270. free(opts->xopts[i]);
  271. free(opts->xopts);
  272. strbuf_release(&opts->current_fixups);
  273. strbuf_reset(&buf);
  274. strbuf_addstr(&buf, get_dir(opts));
  275. if (remove_dir_recursively(&buf, 0))
  276. ret = error(_("could not remove '%s'"), buf.buf);
  277. strbuf_release(&buf);
  278. return ret;
  279. }
  280. static const char *action_name(const struct replay_opts *opts)
  281. {
  282. switch (opts->action) {
  283. case REPLAY_REVERT:
  284. return N_("revert");
  285. case REPLAY_PICK:
  286. return N_("cherry-pick");
  287. case REPLAY_INTERACTIVE_REBASE:
  288. return N_("rebase -i");
  289. }
  290. die(_("unknown action: %d"), opts->action);
  291. }
  292. struct commit_message {
  293. char *parent_label;
  294. char *label;
  295. char *subject;
  296. const char *message;
  297. };
  298. static const char *short_commit_name(struct commit *commit)
  299. {
  300. return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
  301. }
  302. static int get_message(struct commit *commit, struct commit_message *out)
  303. {
  304. const char *abbrev, *subject;
  305. int subject_len;
  306. out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
  307. abbrev = short_commit_name(commit);
  308. subject_len = find_commit_subject(out->message, &subject);
  309. out->subject = xmemdupz(subject, subject_len);
  310. out->label = xstrfmt("%s... %s", abbrev, out->subject);
  311. out->parent_label = xstrfmt("parent of %s", out->label);
  312. return 0;
  313. }
  314. static void free_message(struct commit *commit, struct commit_message *msg)
  315. {
  316. free(msg->parent_label);
  317. free(msg->label);
  318. free(msg->subject);
  319. unuse_commit_buffer(commit, msg->message);
  320. }
  321. static void print_advice(struct repository *r, int show_hint,
  322. struct replay_opts *opts)
  323. {
  324. char *msg = getenv("GIT_CHERRY_PICK_HELP");
  325. if (msg) {
  326. fprintf(stderr, "%s\n", msg);
  327. /*
  328. * A conflict has occurred but the porcelain
  329. * (typically rebase --interactive) wants to take care
  330. * of the commit itself so remove CHERRY_PICK_HEAD
  331. */
  332. unlink(git_path_cherry_pick_head(r));
  333. return;
  334. }
  335. if (show_hint) {
  336. if (opts->no_commit)
  337. advise(_("after resolving the conflicts, mark the corrected paths\n"
  338. "with 'git add <paths>' or 'git rm <paths>'"));
  339. else
  340. advise(_("after resolving the conflicts, mark the corrected paths\n"
  341. "with 'git add <paths>' or 'git rm <paths>'\n"
  342. "and commit the result with 'git commit'"));
  343. }
  344. }
  345. static int write_message(const void *buf, size_t len, const char *filename,
  346. int append_eol)
  347. {
  348. struct lock_file msg_file = LOCK_INIT;
  349. int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
  350. if (msg_fd < 0)
  351. return error_errno(_("could not lock '%s'"), filename);
  352. if (write_in_full(msg_fd, buf, len) < 0) {
  353. error_errno(_("could not write to '%s'"), filename);
  354. rollback_lock_file(&msg_file);
  355. return -1;
  356. }
  357. if (append_eol && write(msg_fd, "\n", 1) < 0) {
  358. error_errno(_("could not write eol to '%s'"), filename);
  359. rollback_lock_file(&msg_file);
  360. return -1;
  361. }
  362. if (commit_lock_file(&msg_file) < 0)
  363. return error(_("failed to finalize '%s'"), filename);
  364. return 0;
  365. }
  366. /*
  367. * Reads a file that was presumably written by a shell script, i.e. with an
  368. * end-of-line marker that needs to be stripped.
  369. *
  370. * Note that only the last end-of-line marker is stripped, consistent with the
  371. * behavior of "$(cat path)" in a shell script.
  372. *
  373. * Returns 1 if the file was read, 0 if it could not be read or does not exist.
  374. */
  375. static int read_oneliner(struct strbuf *buf,
  376. const char *path, int skip_if_empty)
  377. {
  378. int orig_len = buf->len;
  379. if (!file_exists(path))
  380. return 0;
  381. if (strbuf_read_file(buf, path, 0) < 0) {
  382. warning_errno(_("could not read '%s'"), path);
  383. return 0;
  384. }
  385. if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
  386. if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
  387. --buf->len;
  388. buf->buf[buf->len] = '\0';
  389. }
  390. if (skip_if_empty && buf->len == orig_len)
  391. return 0;
  392. return 1;
  393. }
  394. static struct tree *empty_tree(struct repository *r)
  395. {
  396. return lookup_tree(r, the_hash_algo->empty_tree);
  397. }
  398. static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
  399. {
  400. if (repo_read_index_unmerged(repo))
  401. return error_resolve_conflict(_(action_name(opts)));
  402. error(_("your local changes would be overwritten by %s."),
  403. _(action_name(opts)));
  404. if (advice_commit_before_merge)
  405. advise(_("commit your changes or stash them to proceed."));
  406. return -1;
  407. }
  408. static void update_abort_safety_file(void)
  409. {
  410. struct object_id head;
  411. /* Do nothing on a single-pick */
  412. if (!file_exists(git_path_seq_dir()))
  413. return;
  414. if (!get_oid("HEAD", &head))
  415. write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
  416. else
  417. write_file(git_path_abort_safety_file(), "%s", "");
  418. }
  419. static int fast_forward_to(struct repository *r,
  420. const struct object_id *to,
  421. const struct object_id *from,
  422. int unborn,
  423. struct replay_opts *opts)
  424. {
  425. struct ref_transaction *transaction;
  426. struct strbuf sb = STRBUF_INIT;
  427. struct strbuf err = STRBUF_INIT;
  428. repo_read_index(r);
  429. if (checkout_fast_forward(r, from, to, 1))
  430. return -1; /* the callee should have complained already */
  431. strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
  432. transaction = ref_transaction_begin(&err);
  433. if (!transaction ||
  434. ref_transaction_update(transaction, "HEAD",
  435. to, unborn && !is_rebase_i(opts) ?
  436. &null_oid : from,
  437. 0, sb.buf, &err) ||
  438. ref_transaction_commit(transaction, &err)) {
  439. ref_transaction_free(transaction);
  440. error("%s", err.buf);
  441. strbuf_release(&sb);
  442. strbuf_release(&err);
  443. return -1;
  444. }
  445. strbuf_release(&sb);
  446. strbuf_release(&err);
  447. ref_transaction_free(transaction);
  448. update_abort_safety_file();
  449. return 0;
  450. }
  451. enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
  452. int use_editor)
  453. {
  454. if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
  455. return use_editor ? COMMIT_MSG_CLEANUP_ALL :
  456. COMMIT_MSG_CLEANUP_SPACE;
  457. else if (!strcmp(cleanup_arg, "verbatim"))
  458. return COMMIT_MSG_CLEANUP_NONE;
  459. else if (!strcmp(cleanup_arg, "whitespace"))
  460. return COMMIT_MSG_CLEANUP_SPACE;
  461. else if (!strcmp(cleanup_arg, "strip"))
  462. return COMMIT_MSG_CLEANUP_ALL;
  463. else if (!strcmp(cleanup_arg, "scissors"))
  464. return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
  465. COMMIT_MSG_CLEANUP_SPACE;
  466. else
  467. die(_("Invalid cleanup mode %s"), cleanup_arg);
  468. }
  469. /*
  470. * NB using int rather than enum cleanup_mode to stop clang's
  471. * -Wtautological-constant-out-of-range-compare complaining that the comparison
  472. * is always true.
  473. */
  474. static const char *describe_cleanup_mode(int cleanup_mode)
  475. {
  476. static const char *modes[] = { "whitespace",
  477. "verbatim",
  478. "scissors",
  479. "strip" };
  480. if (cleanup_mode < ARRAY_SIZE(modes))
  481. return modes[cleanup_mode];
  482. BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
  483. }
  484. void append_conflicts_hint(struct index_state *istate,
  485. struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
  486. {
  487. int i;
  488. if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
  489. strbuf_addch(msgbuf, '\n');
  490. wt_status_append_cut_line(msgbuf);
  491. strbuf_addch(msgbuf, comment_line_char);
  492. }
  493. strbuf_addch(msgbuf, '\n');
  494. strbuf_commented_addf(msgbuf, "Conflicts:\n");
  495. for (i = 0; i < istate->cache_nr;) {
  496. const struct cache_entry *ce = istate->cache[i++];
  497. if (ce_stage(ce)) {
  498. strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
  499. while (i < istate->cache_nr &&
  500. !strcmp(ce->name, istate->cache[i]->name))
  501. i++;
  502. }
  503. }
  504. }
  505. static int do_recursive_merge(struct repository *r,
  506. struct commit *base, struct commit *next,
  507. const char *base_label, const char *next_label,
  508. struct object_id *head, struct strbuf *msgbuf,
  509. struct replay_opts *opts)
  510. {
  511. struct merge_options o;
  512. struct tree *next_tree, *base_tree, *head_tree;
  513. int clean;
  514. char **xopt;
  515. struct lock_file index_lock = LOCK_INIT;
  516. if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
  517. return -1;
  518. repo_read_index(r);
  519. init_merge_options(&o, r);
  520. o.ancestor = base ? base_label : "(empty tree)";
  521. o.branch1 = "HEAD";
  522. o.branch2 = next ? next_label : "(empty tree)";
  523. if (is_rebase_i(opts))
  524. o.buffer_output = 2;
  525. o.show_rename_progress = 1;
  526. head_tree = parse_tree_indirect(head);
  527. next_tree = next ? get_commit_tree(next) : empty_tree(r);
  528. base_tree = base ? get_commit_tree(base) : empty_tree(r);
  529. for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
  530. parse_merge_opt(&o, *xopt);
  531. clean = merge_trees(&o,
  532. head_tree,
  533. next_tree, base_tree);
  534. if (is_rebase_i(opts) && clean <= 0)
  535. fputs(o.obuf.buf, stdout);
  536. strbuf_release(&o.obuf);
  537. if (clean < 0) {
  538. rollback_lock_file(&index_lock);
  539. return clean;
  540. }
  541. if (write_locked_index(r->index, &index_lock,
  542. COMMIT_LOCK | SKIP_IF_UNCHANGED))
  543. /*
  544. * TRANSLATORS: %s will be "revert", "cherry-pick" or
  545. * "rebase -i".
  546. */
  547. return error(_("%s: Unable to write new index file"),
  548. _(action_name(opts)));
  549. if (!clean)
  550. append_conflicts_hint(r->index, msgbuf,
  551. opts->default_msg_cleanup);
  552. return !clean;
  553. }
  554. static struct object_id *get_cache_tree_oid(struct index_state *istate)
  555. {
  556. if (!istate->cache_tree)
  557. istate->cache_tree = cache_tree();
  558. if (!cache_tree_fully_valid(istate->cache_tree))
  559. if (cache_tree_update(istate, 0)) {
  560. error(_("unable to update cache tree"));
  561. return NULL;
  562. }
  563. return &istate->cache_tree->oid;
  564. }
  565. static int is_index_unchanged(struct repository *r)
  566. {
  567. struct object_id head_oid, *cache_tree_oid;
  568. struct commit *head_commit;
  569. struct index_state *istate = r->index;
  570. if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
  571. return error(_("could not resolve HEAD commit"));
  572. head_commit = lookup_commit(r, &head_oid);
  573. /*
  574. * If head_commit is NULL, check_commit, called from
  575. * lookup_commit, would have indicated that head_commit is not
  576. * a commit object already. parse_commit() will return failure
  577. * without further complaints in such a case. Otherwise, if
  578. * the commit is invalid, parse_commit() will complain. So
  579. * there is nothing for us to say here. Just return failure.
  580. */
  581. if (parse_commit(head_commit))
  582. return -1;
  583. if (!(cache_tree_oid = get_cache_tree_oid(istate)))
  584. return -1;
  585. return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
  586. }
  587. static int write_author_script(const char *message)
  588. {
  589. struct strbuf buf = STRBUF_INIT;
  590. const char *eol;
  591. int res;
  592. for (;;)
  593. if (!*message || starts_with(message, "\n")) {
  594. missing_author:
  595. /* Missing 'author' line? */
  596. unlink(rebase_path_author_script());
  597. return 0;
  598. } else if (skip_prefix(message, "author ", &message))
  599. break;
  600. else if ((eol = strchr(message, '\n')))
  601. message = eol + 1;
  602. else
  603. goto missing_author;
  604. strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
  605. while (*message && *message != '\n' && *message != '\r')
  606. if (skip_prefix(message, " <", &message))
  607. break;
  608. else if (*message != '\'')
  609. strbuf_addch(&buf, *(message++));
  610. else
  611. strbuf_addf(&buf, "'\\%c'", *(message++));
  612. strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
  613. while (*message && *message != '\n' && *message != '\r')
  614. if (skip_prefix(message, "> ", &message))
  615. break;
  616. else if (*message != '\'')
  617. strbuf_addch(&buf, *(message++));
  618. else
  619. strbuf_addf(&buf, "'\\%c'", *(message++));
  620. strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
  621. while (*message && *message != '\n' && *message != '\r')
  622. if (*message != '\'')
  623. strbuf_addch(&buf, *(message++));
  624. else
  625. strbuf_addf(&buf, "'\\%c'", *(message++));
  626. strbuf_addch(&buf, '\'');
  627. res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
  628. strbuf_release(&buf);
  629. return res;
  630. }
  631. /**
  632. * Take a series of KEY='VALUE' lines where VALUE part is
  633. * sq-quoted, and append <KEY, VALUE> at the end of the string list
  634. */
  635. static int parse_key_value_squoted(char *buf, struct string_list *list)
  636. {
  637. while (*buf) {
  638. struct string_list_item *item;
  639. char *np;
  640. char *cp = strchr(buf, '=');
  641. if (!cp) {
  642. np = strchrnul(buf, '\n');
  643. return error(_("no key present in '%.*s'"),
  644. (int) (np - buf), buf);
  645. }
  646. np = strchrnul(cp, '\n');
  647. *cp++ = '\0';
  648. item = string_list_append(list, buf);
  649. buf = np + (*np == '\n');
  650. *np = '\0';
  651. cp = sq_dequote(cp);
  652. if (!cp)
  653. return error(_("unable to dequote value of '%s'"),
  654. item->string);
  655. item->util = xstrdup(cp);
  656. }
  657. return 0;
  658. }
  659. /**
  660. * Reads and parses the state directory's "author-script" file, and sets name,
  661. * email and date accordingly.
  662. * Returns 0 on success, -1 if the file could not be parsed.
  663. *
  664. * The author script is of the format:
  665. *
  666. * GIT_AUTHOR_NAME='$author_name'
  667. * GIT_AUTHOR_EMAIL='$author_email'
  668. * GIT_AUTHOR_DATE='$author_date'
  669. *
  670. * where $author_name, $author_email and $author_date are quoted. We are strict
  671. * with our parsing, as the file was meant to be eval'd in the now-removed
  672. * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
  673. * from what this function expects, it is better to bail out than to do
  674. * something that the user does not expect.
  675. */
  676. int read_author_script(const char *path, char **name, char **email, char **date,
  677. int allow_missing)
  678. {
  679. struct strbuf buf = STRBUF_INIT;
  680. struct string_list kv = STRING_LIST_INIT_DUP;
  681. int retval = -1; /* assume failure */
  682. int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
  683. if (strbuf_read_file(&buf, path, 256) <= 0) {
  684. strbuf_release(&buf);
  685. if (errno == ENOENT && allow_missing)
  686. return 0;
  687. else
  688. return error_errno(_("could not open '%s' for reading"),
  689. path);
  690. }
  691. if (parse_key_value_squoted(buf.buf, &kv))
  692. goto finish;
  693. for (i = 0; i < kv.nr; i++) {
  694. if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
  695. if (name_i != -2)
  696. name_i = error(_("'GIT_AUTHOR_NAME' already given"));
  697. else
  698. name_i = i;
  699. } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
  700. if (email_i != -2)
  701. email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
  702. else
  703. email_i = i;
  704. } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
  705. if (date_i != -2)
  706. date_i = error(_("'GIT_AUTHOR_DATE' already given"));
  707. else
  708. date_i = i;
  709. } else {
  710. err = error(_("unknown variable '%s'"),
  711. kv.items[i].string);
  712. }
  713. }
  714. if (name_i == -2)
  715. error(_("missing 'GIT_AUTHOR_NAME'"));
  716. if (email_i == -2)
  717. error(_("missing 'GIT_AUTHOR_EMAIL'"));
  718. if (date_i == -2)
  719. error(_("missing 'GIT_AUTHOR_DATE'"));
  720. if (date_i < 0 || email_i < 0 || date_i < 0 || err)
  721. goto finish;
  722. *name = kv.items[name_i].util;
  723. *email = kv.items[email_i].util;
  724. *date = kv.items[date_i].util;
  725. retval = 0;
  726. finish:
  727. string_list_clear(&kv, !!retval);
  728. strbuf_release(&buf);
  729. return retval;
  730. }
  731. /*
  732. * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
  733. * file with shell quoting into struct argv_array. Returns -1 on
  734. * error, 0 otherwise.
  735. */
  736. static int read_env_script(struct argv_array *env)
  737. {
  738. char *name, *email, *date;
  739. if (read_author_script(rebase_path_author_script(),
  740. &name, &email, &date, 0))
  741. return -1;
  742. argv_array_pushf(env, "GIT_AUTHOR_NAME=%s", name);
  743. argv_array_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
  744. argv_array_pushf(env, "GIT_AUTHOR_DATE=%s", date);
  745. free(name);
  746. free(email);
  747. free(date);
  748. return 0;
  749. }
  750. static char *get_author(const char *message)
  751. {
  752. size_t len;
  753. const char *a;
  754. a = find_commit_header(message, "author", &len);
  755. if (a)
  756. return xmemdupz(a, len);
  757. return NULL;
  758. }
  759. static const char staged_changes_advice[] =
  760. N_("you have staged changes in your working tree\n"
  761. "If these changes are meant to be squashed into the previous commit, run:\n"
  762. "\n"
  763. " git commit --amend %s\n"
  764. "\n"
  765. "If they are meant to go into a new commit, run:\n"
  766. "\n"
  767. " git commit %s\n"
  768. "\n"
  769. "In both cases, once you're done, continue with:\n"
  770. "\n"
  771. " git rebase --continue\n");
  772. #define ALLOW_EMPTY (1<<0)
  773. #define EDIT_MSG (1<<1)
  774. #define AMEND_MSG (1<<2)
  775. #define CLEANUP_MSG (1<<3)
  776. #define VERIFY_MSG (1<<4)
  777. #define CREATE_ROOT_COMMIT (1<<5)
  778. static int run_command_silent_on_success(struct child_process *cmd)
  779. {
  780. struct strbuf buf = STRBUF_INIT;
  781. int rc;
  782. cmd->stdout_to_stderr = 1;
  783. rc = pipe_command(cmd,
  784. NULL, 0,
  785. NULL, 0,
  786. &buf, 0);
  787. if (rc)
  788. fputs(buf.buf, stderr);
  789. strbuf_release(&buf);
  790. return rc;
  791. }
  792. /*
  793. * If we are cherry-pick, and if the merge did not result in
  794. * hand-editing, we will hit this commit and inherit the original
  795. * author date and name.
  796. *
  797. * If we are revert, or if our cherry-pick results in a hand merge,
  798. * we had better say that the current user is responsible for that.
  799. *
  800. * An exception is when run_git_commit() is called during an
  801. * interactive rebase: in that case, we will want to retain the
  802. * author metadata.
  803. */
  804. static int run_git_commit(struct repository *r,
  805. const char *defmsg,
  806. struct replay_opts *opts,
  807. unsigned int flags)
  808. {
  809. struct child_process cmd = CHILD_PROCESS_INIT;
  810. cmd.git_cmd = 1;
  811. if (is_rebase_i(opts) && read_env_script(&cmd.env_array)) {
  812. const char *gpg_opt = gpg_sign_opt_quoted(opts);
  813. return error(_(staged_changes_advice),
  814. gpg_opt, gpg_opt);
  815. }
  816. argv_array_push(&cmd.args, "commit");
  817. if (!(flags & VERIFY_MSG))
  818. argv_array_push(&cmd.args, "-n");
  819. if ((flags & AMEND_MSG))
  820. argv_array_push(&cmd.args, "--amend");
  821. if (opts->gpg_sign)
  822. argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
  823. if (defmsg)
  824. argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
  825. else if (!(flags & EDIT_MSG))
  826. argv_array_pushl(&cmd.args, "-C", "HEAD", NULL);
  827. if ((flags & CLEANUP_MSG))
  828. argv_array_push(&cmd.args, "--cleanup=strip");
  829. if ((flags & EDIT_MSG))
  830. argv_array_push(&cmd.args, "-e");
  831. else if (!(flags & CLEANUP_MSG) &&
  832. !opts->signoff && !opts->record_origin &&
  833. !opts->explicit_cleanup)
  834. argv_array_push(&cmd.args, "--cleanup=verbatim");
  835. if ((flags & ALLOW_EMPTY))
  836. argv_array_push(&cmd.args, "--allow-empty");
  837. if (!(flags & EDIT_MSG))
  838. argv_array_push(&cmd.args, "--allow-empty-message");
  839. if (is_rebase_i(opts) && !(flags & EDIT_MSG))
  840. return run_command_silent_on_success(&cmd);
  841. else
  842. return run_command(&cmd);
  843. }
  844. static int rest_is_empty(const struct strbuf *sb, int start)
  845. {
  846. int i, eol;
  847. const char *nl;
  848. /* Check if the rest is just whitespace and Signed-off-by's. */
  849. for (i = start; i < sb->len; i++) {
  850. nl = memchr(sb->buf + i, '\n', sb->len - i);
  851. if (nl)
  852. eol = nl - sb->buf;
  853. else
  854. eol = sb->len;
  855. if (strlen(sign_off_header) <= eol - i &&
  856. starts_with(sb->buf + i, sign_off_header)) {
  857. i = eol;
  858. continue;
  859. }
  860. while (i < eol)
  861. if (!isspace(sb->buf[i++]))
  862. return 0;
  863. }
  864. return 1;
  865. }
  866. void cleanup_message(struct strbuf *msgbuf,
  867. enum commit_msg_cleanup_mode cleanup_mode, int verbose)
  868. {
  869. if (verbose || /* Truncate the message just before the diff, if any. */
  870. cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
  871. strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
  872. if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
  873. strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
  874. }
  875. /*
  876. * Find out if the message in the strbuf contains only whitespace and
  877. * Signed-off-by lines.
  878. */
  879. int message_is_empty(const struct strbuf *sb,
  880. enum commit_msg_cleanup_mode cleanup_mode)
  881. {
  882. if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
  883. return 0;
  884. return rest_is_empty(sb, 0);
  885. }
  886. /*
  887. * See if the user edited the message in the editor or left what
  888. * was in the template intact
  889. */
  890. int template_untouched(const struct strbuf *sb, const char *template_file,
  891. enum commit_msg_cleanup_mode cleanup_mode)
  892. {
  893. struct strbuf tmpl = STRBUF_INIT;
  894. const char *start;
  895. if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
  896. return 0;
  897. if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
  898. return 0;
  899. strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
  900. if (!skip_prefix(sb->buf, tmpl.buf, &start))
  901. start = sb->buf;
  902. strbuf_release(&tmpl);
  903. return rest_is_empty(sb, start - sb->buf);
  904. }
  905. int update_head_with_reflog(const struct commit *old_head,
  906. const struct object_id *new_head,
  907. const char *action, const struct strbuf *msg,
  908. struct strbuf *err)
  909. {
  910. struct ref_transaction *transaction;
  911. struct strbuf sb = STRBUF_INIT;
  912. const char *nl;
  913. int ret = 0;
  914. if (action) {
  915. strbuf_addstr(&sb, action);
  916. strbuf_addstr(&sb, ": ");
  917. }
  918. nl = strchr(msg->buf, '\n');
  919. if (nl) {
  920. strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
  921. } else {
  922. strbuf_addbuf(&sb, msg);
  923. strbuf_addch(&sb, '\n');
  924. }
  925. transaction = ref_transaction_begin(err);
  926. if (!transaction ||
  927. ref_transaction_update(transaction, "HEAD", new_head,
  928. old_head ? &old_head->object.oid : &null_oid,
  929. 0, sb.buf, err) ||
  930. ref_transaction_commit(transaction, err)) {
  931. ret = -1;
  932. }
  933. ref_transaction_free(transaction);
  934. strbuf_release(&sb);
  935. return ret;
  936. }
  937. static int run_rewrite_hook(const struct object_id *oldoid,
  938. const struct object_id *newoid)
  939. {
  940. struct child_process proc = CHILD_PROCESS_INIT;
  941. const char *argv[3];
  942. int code;
  943. struct strbuf sb = STRBUF_INIT;
  944. argv[0] = find_hook("post-rewrite");
  945. if (!argv[0])
  946. return 0;
  947. argv[1] = "amend";
  948. argv[2] = NULL;
  949. proc.argv = argv;
  950. proc.in = -1;
  951. proc.stdout_to_stderr = 1;
  952. proc.trace2_hook_name = "post-rewrite";
  953. code = start_command(&proc);
  954. if (code)
  955. return code;
  956. strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
  957. sigchain_push(SIGPIPE, SIG_IGN);
  958. write_in_full(proc.in, sb.buf, sb.len);
  959. close(proc.in);
  960. strbuf_release(&sb);
  961. sigchain_pop(SIGPIPE);
  962. return finish_command(&proc);
  963. }
  964. void commit_post_rewrite(struct repository *r,
  965. const struct commit *old_head,
  966. const struct object_id *new_head)
  967. {
  968. struct notes_rewrite_cfg *cfg;
  969. cfg = init_copy_notes_for_rewrite("amend");
  970. if (cfg) {
  971. /* we are amending, so old_head is not NULL */
  972. copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
  973. finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
  974. }
  975. run_rewrite_hook(&old_head->object.oid, new_head);
  976. }
  977. static int run_prepare_commit_msg_hook(struct repository *r,
  978. struct strbuf *msg,
  979. const char *commit)
  980. {
  981. int ret = 0;
  982. const char *name, *arg1 = NULL, *arg2 = NULL;
  983. name = git_path_commit_editmsg();
  984. if (write_message(msg->buf, msg->len, name, 0))
  985. return -1;
  986. if (commit) {
  987. arg1 = "commit";
  988. arg2 = commit;
  989. } else {
  990. arg1 = "message";
  991. }
  992. if (run_commit_hook(0, r->index_file, "prepare-commit-msg", name,
  993. arg1, arg2, NULL))
  994. ret = error(_("'prepare-commit-msg' hook failed"));
  995. return ret;
  996. }
  997. static const char implicit_ident_advice_noconfig[] =
  998. N_("Your name and email address were configured automatically based\n"
  999. "on your username and hostname. Please check that they are accurate.\n"
  1000. "You can suppress this message by setting them explicitly. Run the\n"
  1001. "following command and follow the instructions in your editor to edit\n"
  1002. "your configuration file:\n"
  1003. "\n"
  1004. " git config --global --edit\n"
  1005. "\n"
  1006. "After doing this, you may fix the identity used for this commit with:\n"
  1007. "\n"
  1008. " git commit --amend --reset-author\n");
  1009. static const char implicit_ident_advice_config[] =
  1010. N_("Your name and email address were configured automatically based\n"
  1011. "on your username and hostname. Please check that they are accurate.\n"
  1012. "You can suppress this message by setting them explicitly:\n"
  1013. "\n"
  1014. " git config --global user.name \"Your Name\"\n"
  1015. " git config --global user.email you@example.com\n"
  1016. "\n"
  1017. "After doing this, you may fix the identity used for this commit with:\n"
  1018. "\n"
  1019. " git commit --amend --reset-author\n");
  1020. static const char *implicit_ident_advice(void)
  1021. {
  1022. char *user_config = expand_user_path("~/.gitconfig", 0);
  1023. char *xdg_config = xdg_config_home("config");
  1024. int config_exists = file_exists(user_config) || file_exists(xdg_config);
  1025. free(user_config);
  1026. free(xdg_config);
  1027. if (config_exists)
  1028. return _(implicit_ident_advice_config);
  1029. else
  1030. return _(implicit_ident_advice_noconfig);
  1031. }
  1032. void print_commit_summary(struct repository *r,
  1033. const char *prefix,
  1034. const struct object_id *oid,
  1035. unsigned int flags)
  1036. {
  1037. struct rev_info rev;
  1038. struct commit *commit;
  1039. struct strbuf format = STRBUF_INIT;
  1040. const char *head;
  1041. struct pretty_print_context pctx = {0};
  1042. struct strbuf author_ident = STRBUF_INIT;
  1043. struct strbuf committer_ident = STRBUF_INIT;
  1044. commit = lookup_commit(r, oid);
  1045. if (!commit)
  1046. die(_("couldn't look up newly created commit"));
  1047. if (parse_commit(commit))
  1048. die(_("could not parse newly created commit"));
  1049. strbuf_addstr(&format, "format:%h] %s");
  1050. format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
  1051. format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
  1052. if (strbuf_cmp(&author_ident, &committer_ident)) {
  1053. strbuf_addstr(&format, "\n Author: ");
  1054. strbuf_addbuf_percentquote(&format, &author_ident);
  1055. }
  1056. if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
  1057. struct strbuf date = STRBUF_INIT;
  1058. format_commit_message(commit, "%ad", &date, &pctx);
  1059. strbuf_addstr(&format, "\n Date: ");
  1060. strbuf_addbuf_percentquote(&format, &date);
  1061. strbuf_release(&date);
  1062. }
  1063. if (!committer_ident_sufficiently_given()) {
  1064. strbuf_addstr(&format, "\n Committer: ");
  1065. strbuf_addbuf_percentquote(&format, &committer_ident);
  1066. if (advice_implicit_identity) {
  1067. strbuf_addch(&format, '\n');
  1068. strbuf_addstr(&format, implicit_ident_advice());
  1069. }
  1070. }
  1071. strbuf_release(&author_ident);
  1072. strbuf_release(&committer_ident);
  1073. repo_init_revisions(r, &rev, prefix);
  1074. setup_revisions(0, NULL, &rev, NULL);
  1075. rev.diff = 1;
  1076. rev.diffopt.output_format =
  1077. DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
  1078. rev.verbose_header = 1;
  1079. rev.show_root_diff = 1;
  1080. get_commit_format(format.buf, &rev);
  1081. rev.always_show_header = 0;
  1082. rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
  1083. rev.diffopt.break_opt = 0;
  1084. diff_setup_done(&rev.diffopt);
  1085. head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
  1086. if (!head)
  1087. die_errno(_("unable to resolve HEAD after creating commit"));
  1088. if (!strcmp(head, "HEAD"))
  1089. head = _("detached HEAD");
  1090. else
  1091. skip_prefix(head, "refs/heads/", &head);
  1092. printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
  1093. _(" (root-commit)") : "");
  1094. if (!log_tree_commit(&rev, commit)) {
  1095. rev.always_show_header = 1;
  1096. rev.use_terminator = 1;
  1097. log_tree_commit(&rev, commit);
  1098. }
  1099. strbuf_release(&format);
  1100. }
  1101. static int parse_head(struct repository *r, struct commit **head)
  1102. {
  1103. struct commit *current_head;
  1104. struct object_id oid;
  1105. if (get_oid("HEAD", &oid)) {
  1106. current_head = NULL;
  1107. } else {
  1108. current_head = lookup_commit_reference(r, &oid);
  1109. if (!current_head)
  1110. return error(_("could not parse HEAD"));
  1111. if (!oideq(&oid, &current_head->object.oid)) {
  1112. warning(_("HEAD %s is not a commit!"),
  1113. oid_to_hex(&oid));
  1114. }
  1115. if (parse_commit(current_head))
  1116. return error(_("could not parse HEAD commit"));
  1117. }
  1118. *head = current_head;
  1119. return 0;
  1120. }
  1121. /*
  1122. * Try to commit without forking 'git commit'. In some cases we need
  1123. * to run 'git commit' to display an error message
  1124. *
  1125. * Returns:
  1126. * -1 - error unable to commit
  1127. * 0 - success
  1128. * 1 - run 'git commit'
  1129. */
  1130. static int try_to_commit(struct repository *r,
  1131. struct strbuf *msg, const char *author,
  1132. struct replay_opts *opts, unsigned int flags,
  1133. struct object_id *oid)
  1134. {
  1135. struct object_id tree;
  1136. struct commit *current_head = NULL;
  1137. struct commit_list *parents = NULL;
  1138. struct commit_extra_header *extra = NULL;
  1139. struct strbuf err = STRBUF_INIT;
  1140. struct strbuf commit_msg = STRBUF_INIT;
  1141. char *amend_author = NULL;
  1142. const char *hook_commit = NULL;
  1143. enum commit_msg_cleanup_mode cleanup;
  1144. int res = 0;
  1145. if (parse_head(r, &current_head))
  1146. return -1;
  1147. if (flags & AMEND_MSG) {
  1148. const char *exclude_gpgsig[] = { "gpgsig", NULL };
  1149. const char *out_enc = get_commit_output_encoding();
  1150. const char *message = logmsg_reencode(current_head, NULL,
  1151. out_enc);
  1152. if (!msg) {
  1153. const char *orig_message = NULL;
  1154. find_commit_subject(message, &orig_message);
  1155. msg = &commit_msg;
  1156. strbuf_addstr(msg, orig_message);
  1157. hook_commit = "HEAD";
  1158. }
  1159. author = amend_author = get_author(message);
  1160. unuse_commit_buffer(current_head, message);
  1161. if (!author) {
  1162. res = error(_("unable to parse commit author"));
  1163. goto out;
  1164. }
  1165. parents = copy_commit_list(current_head->parents);
  1166. extra = read_commit_extra_headers(current_head, exclude_gpgsig);
  1167. } else if (current_head &&
  1168. (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
  1169. commit_list_insert(current_head, &parents);
  1170. }
  1171. if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
  1172. res = error(_("git write-tree failed to write a tree"));
  1173. goto out;
  1174. }
  1175. if (!(flags & ALLOW_EMPTY) && oideq(current_head ?
  1176. get_commit_tree_oid(current_head) :
  1177. the_hash_algo->empty_tree, &tree)) {
  1178. res = 1; /* run 'git commit' to display error message */
  1179. goto out;
  1180. }
  1181. if (find_hook("prepare-commit-msg")) {
  1182. res = run_prepare_commit_msg_hook(r, msg, hook_commit);
  1183. if (res)
  1184. goto out;
  1185. if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
  1186. 2048) < 0) {
  1187. res = error_errno(_("unable to read commit message "
  1188. "from '%s'"),
  1189. git_path_commit_editmsg());
  1190. goto out;
  1191. }
  1192. msg = &commit_msg;
  1193. }
  1194. if (flags & CLEANUP_MSG)
  1195. cleanup = COMMIT_MSG_CLEANUP_ALL;
  1196. else if ((opts->signoff || opts->record_origin) &&
  1197. !opts->explicit_cleanup)
  1198. cleanup = COMMIT_MSG_CLEANUP_SPACE;
  1199. else
  1200. cleanup = opts->default_msg_cleanup;
  1201. if (cleanup != COMMIT_MSG_CLEANUP_NONE)
  1202. strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
  1203. if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
  1204. res = 1; /* run 'git commit' to display error message */
  1205. goto out;
  1206. }
  1207. reset_ident_date();
  1208. if (commit_tree_extended(msg->buf, msg->len, &tree, parents,
  1209. oid, author, opts->gpg_sign, extra)) {
  1210. res = error(_("failed to write commit object"));
  1211. goto out;
  1212. }
  1213. if (update_head_with_reflog(current_head, oid,
  1214. getenv("GIT_REFLOG_ACTION"), msg, &err)) {
  1215. res = error("%s", err.buf);
  1216. goto out;
  1217. }
  1218. run_commit_hook(0, r->index_file, "post-commit", NULL);
  1219. if (flags & AMEND_MSG)
  1220. commit_post_rewrite(r, current_head, oid);
  1221. out:
  1222. free_commit_extra_headers(extra);
  1223. strbuf_release(&err);
  1224. strbuf_release(&commit_msg);
  1225. free(amend_author);
  1226. return res;
  1227. }
  1228. static int do_commit(struct repository *r,
  1229. const char *msg_file, const char *author,
  1230. struct replay_opts *opts, unsigned int flags)
  1231. {
  1232. int res = 1;
  1233. if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
  1234. struct object_id oid;
  1235. struct strbuf sb = STRBUF_INIT;
  1236. if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
  1237. return error_errno(_("unable to read commit message "
  1238. "from '%s'"),
  1239. msg_file);
  1240. res = try_to_commit(r, msg_file ? &sb : NULL,
  1241. author, opts, flags, &oid);
  1242. strbuf_release(&sb);
  1243. if (!res) {
  1244. unlink(git_path_cherry_pick_head(r));
  1245. unlink(git_path_merge_msg(r));
  1246. if (!is_rebase_i(opts))
  1247. print_commit_summary(r, NULL, &oid,
  1248. SUMMARY_SHOW_AUTHOR_DATE);
  1249. return res;
  1250. }
  1251. }
  1252. if (res == 1)
  1253. return run_git_commit(r, msg_file, opts, flags);
  1254. return res;
  1255. }
  1256. static int is_original_commit_empty(struct commit *commit)
  1257. {
  1258. const struct object_id *ptree_oid;
  1259. if (parse_commit(commit))
  1260. return error(_("could not parse commit %s"),
  1261. oid_to_hex(&commit->object.oid));
  1262. if (commit->parents) {
  1263. struct commit *parent = commit->parents->item;
  1264. if (parse_commit(parent))
  1265. return error(_("could not parse parent commit %s"),
  1266. oid_to_hex(&parent->object.oid));
  1267. ptree_oid = get_commit_tree_oid(parent);
  1268. } else {
  1269. ptree_oid = the_hash_algo->empty_tree; /* commit is root */
  1270. }
  1271. return oideq(ptree_oid, get_commit_tree_oid(commit));
  1272. }
  1273. /*
  1274. * Do we run "git commit" with "--allow-empty"?
  1275. */
  1276. static int allow_empty(struct repository *r,
  1277. struct replay_opts *opts,
  1278. struct commit *commit)
  1279. {
  1280. int index_unchanged, empty_commit;
  1281. /*
  1282. * Three cases:
  1283. *
  1284. * (1) we do not allow empty at all and error out.
  1285. *
  1286. * (2) we allow ones that were initially empty, but
  1287. * forbid the ones that become empty;
  1288. *
  1289. * (3) we allow both.
  1290. */
  1291. if (!opts->allow_empty)
  1292. return 0; /* let "git commit" barf as necessary */
  1293. index_unchanged = is_index_unchanged(r);
  1294. if (index_unchanged < 0)
  1295. return index_unchanged;
  1296. if (!index_unchanged)
  1297. return 0; /* we do not have to say --allow-empty */
  1298. if (opts->keep_redundant_commits)
  1299. return 1;
  1300. empty_commit = is_original_commit_empty(commit);
  1301. if (empty_commit < 0)
  1302. return empty_commit;
  1303. if (!empty_commit)
  1304. return 0;
  1305. else
  1306. return 1;
  1307. }
  1308. static struct {
  1309. char c;
  1310. const char *str;
  1311. } todo_command_info[] = {
  1312. { 'p', "pick" },
  1313. { 0, "revert" },
  1314. { 'e', "edit" },
  1315. { 'r', "reword" },
  1316. { 'f', "fixup" },
  1317. { 's', "squash" },
  1318. { 'x', "exec" },
  1319. { 'b', "break" },
  1320. { 'l', "label" },
  1321. { 't', "reset" },
  1322. { 'm', "merge" },
  1323. { 0, "noop" },
  1324. { 'd', "drop" },
  1325. { 0, NULL }
  1326. };
  1327. static const char *command_to_string(const enum todo_command command)
  1328. {
  1329. if (command < TODO_COMMENT)
  1330. return todo_command_info[command].str;
  1331. die(_("unknown command: %d"), command);
  1332. }
  1333. static char command_to_char(const enum todo_command command)
  1334. {
  1335. if (command < TODO_COMMENT && todo_command_info[command].c)
  1336. return todo_command_info[command].c;
  1337. return comment_line_char;
  1338. }
  1339. static int is_noop(const enum todo_command command)
  1340. {
  1341. return TODO_NOOP <= command;
  1342. }
  1343. static int is_fixup(enum todo_command command)
  1344. {
  1345. return command == TODO_FIXUP || command == TODO_SQUASH;
  1346. }
  1347. /* Does this command create a (non-merge) commit? */
  1348. static int is_pick_or_similar(enum todo_command command)
  1349. {
  1350. switch (command) {
  1351. case TODO_PICK:
  1352. case TODO_REVERT:
  1353. case TODO_EDIT:
  1354. case TODO_REWORD:
  1355. case TODO_FIXUP:
  1356. case TODO_SQUASH:
  1357. return 1;
  1358. default:
  1359. return 0;
  1360. }
  1361. }
  1362. static int update_squash_messages(struct repository *r,
  1363. enum todo_command command,
  1364. struct commit *commit,
  1365. struct replay_opts *opts)
  1366. {
  1367. struct strbuf buf = STRBUF_INIT;
  1368. int res;
  1369. const char *message, *body;
  1370. if (opts->current_fixup_count > 0) {
  1371. struct strbuf header = STRBUF_INIT;
  1372. char *eol;
  1373. if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
  1374. return error(_("could not read '%s'"),
  1375. rebase_path_squash_msg());
  1376. eol = buf.buf[0] != comment_line_char ?
  1377. buf.buf : strchrnul(buf.buf, '\n');
  1378. strbuf_addf(&header, "%c ", comment_line_char);
  1379. strbuf_addf(&header, _("This is a combination of %d commits."),
  1380. opts->current_fixup_count + 2);
  1381. strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
  1382. strbuf_release(&header);
  1383. } else {
  1384. struct object_id head;
  1385. struct commit *head_commit;
  1386. const char *head_message, *body;
  1387. if (get_oid("HEAD", &head))
  1388. return error(_("need a HEAD to fixup"));
  1389. if (!(head_commit = lookup_commit_reference(r, &head)))
  1390. return error(_("could not read HEAD"));
  1391. if (!(head_message = get_commit_buffer(head_commit, NULL)))
  1392. return error(_("could not read HEAD's commit message"));
  1393. find_commit_subject(head_message, &body);
  1394. if (write_message(body, strlen(body),
  1395. rebase_path_fixup_msg(), 0)) {
  1396. unuse_commit_buffer(head_commit, head_message);
  1397. return error(_("cannot write '%s'"),
  1398. rebase_path_fixup_msg());
  1399. }
  1400. strbuf_addf(&buf, "%c ", comment_line_char);
  1401. strbuf_addf(&buf, _("This is a combination of %d commits."), 2);
  1402. strbuf_addf(&buf, "\n%c ", comment_line_char);
  1403. strbuf_addstr(&buf, _("This is the 1st commit message:"));
  1404. strbuf_addstr(&buf, "\n\n");
  1405. strbuf_addstr(&buf, body);
  1406. unuse_commit_buffer(head_commit, head_message);
  1407. }
  1408. if (!(message = get_commit_buffer(commit, NULL)))
  1409. return error(_("could not read commit message of %s"),
  1410. oid_to_hex(&commit->object.oid));
  1411. find_commit_subject(message, &body);
  1412. if (command == TODO_SQUASH) {
  1413. unlink(rebase_path_fixup_msg());
  1414. strbuf_addf(&buf, "\n%c ", comment_line_char);
  1415. strbuf_addf(&buf, _("This is the commit message #%d:"),
  1416. ++opts->current_fixup_count + 1);
  1417. strbuf_addstr(&buf, "\n\n");
  1418. strbuf_addstr(&buf, body);
  1419. } else if (command == TODO_FIXUP) {
  1420. strbuf_addf(&buf, "\n%c ", comment_line_char);
  1421. strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
  1422. ++opts->current_fixup_count + 1);
  1423. strbuf_addstr(&buf, "\n\n");
  1424. strbuf_add_commented_lines(&buf, body, strlen(body));
  1425. } else
  1426. return error(_("unknown command: %d"), command);
  1427. unuse_commit_buffer(commit, message);
  1428. res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
  1429. strbuf_release(&buf);
  1430. if (!res) {
  1431. strbuf_addf(&opts->current_fixups, "%s%s %s",
  1432. opts->current_fixups.len ? "\n" : "",
  1433. command_to_string(command),
  1434. oid_to_hex(&commit->object.oid));
  1435. res = write_message(opts->current_fixups.buf,
  1436. opts->current_fixups.len,
  1437. rebase_path_current_fixups(), 0);
  1438. }
  1439. return res;
  1440. }
  1441. static void flush_rewritten_pending(void)
  1442. {
  1443. struct strbuf buf = STRBUF_INIT;
  1444. struct object_id newoid;
  1445. FILE *out;
  1446. if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
  1447. !get_oid("HEAD", &newoid) &&
  1448. (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
  1449. char *bol = buf.buf, *eol;
  1450. while (*bol) {
  1451. eol = strchrnul(bol, '\n');
  1452. fprintf(out, "%.*s %s\n", (int)(eol - bol),
  1453. bol, oid_to_hex(&newoid));
  1454. if (!*eol)
  1455. break;
  1456. bol = eol + 1;
  1457. }
  1458. fclose(out);
  1459. unlink(rebase_path_rewritten_pending());
  1460. }
  1461. strbuf_release(&buf);
  1462. }
  1463. static void record_in_rewritten(struct object_id *oid,
  1464. enum todo_command next_command)
  1465. {
  1466. FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
  1467. if (!out)
  1468. return;
  1469. fprintf(out, "%s\n", oid_to_hex(oid));
  1470. fclose(out);
  1471. if (!is_fixup(next_command))
  1472. flush_rewritten_pending();
  1473. }
  1474. static int do_pick_commit(struct repository *r,
  1475. enum todo_command command,
  1476. struct commit *commit,
  1477. struct replay_opts *opts,
  1478. int final_fixup, int *check_todo)
  1479. {
  1480. unsigned int flags = opts->edit ? EDIT_MSG : 0;
  1481. const char *msg_file = opts->edit ? NULL : git_path_merge_msg(r);
  1482. struct object_id head;
  1483. struct commit *base, *next, *parent;
  1484. const char *base_label, *next_label;
  1485. char *author = NULL;
  1486. struct commit_message msg = { NULL, NULL, NULL, NULL };
  1487. struct strbuf msgbuf = STRBUF_INIT;
  1488. int res, unborn = 0, reword = 0, allow;
  1489. if (opts->no_commit) {
  1490. /*
  1491. * We do not intend to commit immediately. We just want to
  1492. * merge the differences in, so let's compute the tree
  1493. * that represents the "current" state for merge-recursive
  1494. * to work on.
  1495. */
  1496. if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
  1497. return error(_("your index file is unmerged."));
  1498. } else {
  1499. unborn = get_oid("HEAD", &head);
  1500. /* Do we want to generate a root commit? */
  1501. if (is_pick_or_similar(command) && opts->have_squash_onto &&
  1502. oideq(&head, &opts->squash_onto)) {
  1503. if (is_fixup(command))
  1504. return error(_("cannot fixup root commit"));
  1505. flags |= CREATE_ROOT_COMMIT;
  1506. unborn = 1;
  1507. } else if (unborn)
  1508. oidcpy(&head, the_hash_algo->empty_tree);
  1509. if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
  1510. NULL, 0))
  1511. return error_dirty_index(r, opts);
  1512. }
  1513. discard_index(r->index);
  1514. if (!commit->parents)
  1515. parent = NULL;
  1516. else if (commit->parents->next) {
  1517. /* Reverting or cherry-picking a merge commit */
  1518. int cnt;
  1519. struct commit_list *p;
  1520. if (!opts->mainline)
  1521. return error(_("commit %s is a merge but no -m option was given."),
  1522. oid_to_hex(&commit->object.oid));
  1523. for (cnt = 1, p = commit->parents;
  1524. cnt != opts->mainline && p;
  1525. cnt++)
  1526. p = p->next;
  1527. if (cnt != opts->mainline || !p)
  1528. return error(_("commit %s does not have parent %d"),
  1529. oid_to_hex(&commit->object.oid), opts->mainline);
  1530. parent = p->item;
  1531. } else if (1 < opts->mainline)
  1532. /*
  1533. * Non-first parent explicitly specified as mainline for
  1534. * non-merge commit
  1535. */
  1536. return error(_("commit %s does not have parent %d"),
  1537. oid_to_hex(&commit->object.oid), opts->mainline);
  1538. else
  1539. parent = commit->parents->item;
  1540. if (get_message(commit, &msg) != 0)
  1541. return error(_("cannot get commit message for %s"),
  1542. oid_to_hex(&commit->object.oid));
  1543. if (opts->allow_ff && !is_fixup(command) &&
  1544. ((parent && oideq(&parent->object.oid, &head)) ||
  1545. (!parent && unborn))) {
  1546. if (is_rebase_i(opts))
  1547. write_author_script(msg.message);
  1548. res = fast_forward_to(r, &commit->object.oid, &head, unborn,
  1549. opts);
  1550. if (res || command != TODO_REWORD)
  1551. goto leave;
  1552. reword = 1;
  1553. msg_file = NULL;
  1554. goto fast_forward_edit;
  1555. }
  1556. if (parent && parse_commit(parent) < 0)
  1557. /* TRANSLATORS: The first %s will be a "todo" command like
  1558. "revert" or "pick", the second %s a SHA1. */
  1559. return error(_("%s: cannot parse parent commit %s"),
  1560. command_to_string(command),
  1561. oid_to_hex(&parent->object.oid));
  1562. /*
  1563. * "commit" is an existing commit. We would want to apply
  1564. * the difference it introduces since its first parent "prev"
  1565. * on top of the current HEAD if we are cherry-pick. Or the
  1566. * reverse of it if we are revert.
  1567. */
  1568. if (command == TODO_REVERT) {
  1569. base = commit;
  1570. base_label = msg.label;
  1571. next = parent;
  1572. next_label = msg.parent_label;
  1573. strbuf_addstr(&msgbuf, "Revert \"");
  1574. strbuf_addstr(&msgbuf, msg.subject);
  1575. strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
  1576. strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
  1577. if (commit->parents && commit->parents->next) {
  1578. strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
  1579. strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
  1580. }
  1581. strbuf_addstr(&msgbuf, ".\n");
  1582. } else {
  1583. const char *p;
  1584. base = parent;
  1585. base_label = msg.parent_label;
  1586. next = commit;
  1587. next_label = msg.label;
  1588. /* Append the commit log message to msgbuf. */
  1589. if (find_commit_subject(msg.message, &p))
  1590. strbuf_addstr(&msgbuf, p);
  1591. if (opts->record_origin) {
  1592. strbuf_complete_line(&msgbuf);
  1593. if (!has_conforming_footer(&msgbuf, NULL, 0))
  1594. strbuf_addch(&msgbuf, '\n');
  1595. strbuf_addstr(&msgbuf, cherry_picked_prefix);
  1596. strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
  1597. strbuf_addstr(&msgbuf, ")\n");
  1598. }
  1599. if (!is_fixup(command))
  1600. author = get_author(msg.message);
  1601. }
  1602. if (command == TODO_REWORD)
  1603. reword = 1;
  1604. else if (is_fixup(command)) {
  1605. if (update_squash_messages(r, command, commit, opts))
  1606. return -1;
  1607. flags |= AMEND_MSG;
  1608. if (!final_fixup)
  1609. msg_file = rebase_path_squash_msg();
  1610. else if (file_exists(rebase_path_fixup_msg())) {
  1611. flags |= CLEANUP_MSG;
  1612. msg_file = rebase_path_fixup_msg();
  1613. } else {
  1614. const char *dest = git_path_squash_msg(r);
  1615. unlink(dest);
  1616. if (copy_file(dest, rebase_path_squash_msg(), 0666))
  1617. return error(_("could not rename '%s' to '%s'"),
  1618. rebase_path_squash_msg(), dest);
  1619. unlink(git_path_merge_msg(r));
  1620. msg_file = dest;
  1621. flags |= EDIT_MSG;
  1622. }
  1623. }
  1624. if (opts->signoff && !is_fixup(command))
  1625. append_signoff(&msgbuf, 0, 0);
  1626. if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
  1627. res = -1;
  1628. else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
  1629. res = do_recursive_merge(r, base, next, base_label, next_label,
  1630. &head, &msgbuf, opts);
  1631. if (res < 0)
  1632. goto leave;
  1633. res |= write_message(msgbuf.buf, msgbuf.len,
  1634. git_path_merge_msg(r), 0);
  1635. } else {
  1636. struct commit_list *common = NULL;
  1637. struct commit_list *remotes = NULL;
  1638. res = write_message(msgbuf.buf, msgbuf.len,
  1639. git_path_merge_msg(r), 0);
  1640. commit_list_insert(base, &common);
  1641. commit_list_insert(next, &remotes);
  1642. res |= try_merge_command(r, opts->strategy,
  1643. opts->xopts_nr, (const char **)opts->xopts,
  1644. common, oid_to_hex(&head), remotes);
  1645. free_commit_list(common);
  1646. free_commit_list(remotes);
  1647. }
  1648. strbuf_release(&msgbuf);
  1649. /*
  1650. * If the merge was clean or if it failed due to conflict, we write
  1651. * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
  1652. * However, if the merge did not even start, then we don't want to
  1653. * write it at all.
  1654. */
  1655. if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
  1656. update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
  1657. REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
  1658. res = -1;
  1659. if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
  1660. update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
  1661. REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
  1662. res = -1;
  1663. if (res) {
  1664. error(command == TODO_REVERT
  1665. ? _("could not revert %s... %s")
  1666. : _("could not apply %s... %s"),
  1667. short_commit_name(commit), msg.subject);
  1668. print_advice(r, res == 1, opts);
  1669. repo_rerere(r, opts->allow_rerere_auto);
  1670. goto leave;
  1671. }
  1672. allow = allow_empty(r, opts, commit);
  1673. if (allow < 0) {
  1674. res = allow;
  1675. goto leave;
  1676. } else if (allow)
  1677. flags |= ALLOW_EMPTY;
  1678. if (!opts->no_commit) {
  1679. if (author || command == TODO_REVERT || (flags & AMEND_MSG))
  1680. res = do_commit(r, msg_file, author, opts, flags);
  1681. else
  1682. res = error(_("unable to parse commit author"));
  1683. *check_todo = !!(flags & EDIT_MSG);
  1684. if (!res && reword) {
  1685. fast_forward_edit:
  1686. res = run_git_commit(r, NULL, opts, EDIT_MSG |
  1687. VERIFY_MSG | AMEND_MSG |
  1688. (flags & ALLOW_EMPTY));
  1689. *check_todo = 1;
  1690. }
  1691. }
  1692. if (!res && final_fixup) {
  1693. unlink(rebase_path_fixup_msg());
  1694. unlink(rebase_path_squash_msg());
  1695. unlink(rebase_path_current_fixups());
  1696. strbuf_reset(&opts->current_fixups);
  1697. opts->current_fixup_count = 0;
  1698. }
  1699. leave:
  1700. free_message(commit, &msg);
  1701. free(author);
  1702. update_abort_safety_file();
  1703. return res;
  1704. }
  1705. static int prepare_revs(struct replay_opts *opts)
  1706. {
  1707. /*
  1708. * picking (but not reverting) ranges (but not individual revisions)
  1709. * should be done in reverse
  1710. */
  1711. if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
  1712. opts->revs->reverse ^= 1;
  1713. if (prepare_revision_walk(opts->revs))
  1714. return error(_("revision walk setup failed"));
  1715. return 0;
  1716. }
  1717. static int read_and_refresh_cache(struct repository *r,
  1718. struct replay_opts *opts)
  1719. {
  1720. struct lock_file index_lock = LOCK_INIT;
  1721. int index_fd = repo_hold_locked_index(r, &index_lock, 0);
  1722. if (repo_read_index(r) < 0) {
  1723. rollback_lock_file(&index_lock);
  1724. return error(_("git %s: failed to read the index"),
  1725. _(action_name(opts)));
  1726. }
  1727. refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
  1728. if (index_fd >= 0) {
  1729. if (write_locked_index(r->index, &index_lock,
  1730. COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
  1731. return error(_("git %s: failed to refresh the index"),
  1732. _(action_name(opts)));
  1733. }
  1734. }
  1735. return 0;
  1736. }
  1737. enum todo_item_flags {
  1738. TODO_EDIT_MERGE_MSG = 1
  1739. };
  1740. void todo_list_release(struct todo_list *todo_list)
  1741. {
  1742. strbuf_release(&todo_list->buf);
  1743. FREE_AND_NULL(todo_list->items);
  1744. todo_list->nr = todo_list->alloc = 0;
  1745. }
  1746. static struct todo_item *append_new_todo(struct todo_list *todo_list)
  1747. {
  1748. ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
  1749. return todo_list->items + todo_list->nr++;
  1750. }
  1751. const char *todo_item_get_arg(struct todo_list *todo_list,
  1752. struct todo_item *item)
  1753. {
  1754. return todo_list->buf.buf + item->arg_offset;
  1755. }
  1756. static int is_command(enum todo_command command, const char **bol)
  1757. {
  1758. const char *str = todo_command_info[command].str;
  1759. const char nick = todo_command_info[command].c;
  1760. const char *p = *bol + 1;
  1761. return skip_prefix(*bol, str, bol) ||
  1762. ((nick && **bol == nick) &&
  1763. (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
  1764. (*bol = p));
  1765. }
  1766. static int parse_insn_line(struct repository *r, struct todo_item *item,
  1767. const char *buf, const char *bol, char *eol)
  1768. {
  1769. struct object_id commit_oid;
  1770. char *end_of_object_name;
  1771. int i, saved, status, padding;
  1772. item->flags = 0;
  1773. /* left-trim */
  1774. bol += strspn(bol, " \t");
  1775. if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
  1776. item->command = TODO_COMMENT;
  1777. item->commit = NULL;
  1778. item->arg_offset = bol - buf;
  1779. item->arg_len = eol - bol;
  1780. return 0;
  1781. }
  1782. for (i = 0; i < TODO_COMMENT; i++)
  1783. if (is_command(i, &bol)) {
  1784. item->command = i;
  1785. break;
  1786. }
  1787. if (i >= TODO_COMMENT)
  1788. return -1;
  1789. /* Eat up extra spaces/ tabs before object name */
  1790. padding = strspn(bol, " \t");
  1791. bol += padding;
  1792. if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
  1793. if (bol != eol)
  1794. return error(_("%s does not accept arguments: '%s'"),
  1795. command_to_string(item->command), bol);
  1796. item->commit = NULL;
  1797. item->arg_offset = bol - buf;
  1798. item->arg_len = eol - bol;
  1799. return 0;
  1800. }
  1801. if (!padding)
  1802. return error(_("missing arguments for %s"),
  1803. command_to_string(item->command));
  1804. if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
  1805. item->command == TODO_RESET) {
  1806. item->commit = NULL;
  1807. item->arg_offset = bol - buf;
  1808. item->arg_len = (int)(eol - bol);
  1809. return 0;
  1810. }
  1811. if (item->command == TODO_MERGE) {
  1812. if (skip_prefix(bol, "-C", &bol))
  1813. bol += strspn(bol, " \t");
  1814. else if (skip_prefix(bol, "-c", &bol)) {
  1815. bol += strspn(bol, " \t");
  1816. item->flags |= TODO_EDIT_MERGE_MSG;
  1817. } else {
  1818. item->flags |= TODO_EDIT_MERGE_MSG;
  1819. item->commit = NULL;
  1820. item->arg_offset = bol - buf;
  1821. item->arg_len = (int)(eol - bol);
  1822. return 0;
  1823. }
  1824. }
  1825. end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
  1826. saved = *end_of_object_name;
  1827. *end_of_object_name = '\0';
  1828. status = get_oid(bol, &commit_oid);
  1829. *end_of_object_name = saved;
  1830. bol = end_of_object_name + strspn(end_of_object_name, " \t");
  1831. item->arg_offset = bol - buf;
  1832. item->arg_len = (int)(eol - bol);
  1833. if (status < 0)
  1834. return error(_("could not parse '%.*s'"),
  1835. (int)(end_of_object_name - bol), bol);
  1836. item->commit = lookup_commit_reference(r, &commit_oid);
  1837. return !item->commit;
  1838. }
  1839. int sequencer_get_last_command(struct repository *r, enum replay_action *action)
  1840. {
  1841. const char *todo_file, *bol;
  1842. struct strbuf buf = STRBUF_INIT;
  1843. int ret = 0;
  1844. todo_file = git_path_todo_file();
  1845. if (strbuf_read_file(&buf, todo_file, 0) < 0) {
  1846. if (errno == ENOENT || errno == ENOTDIR)
  1847. return -1;
  1848. else
  1849. return error_errno("unable to open '%s'", todo_file);
  1850. }
  1851. bol = buf.buf + strspn(buf.buf, " \t\r\n");
  1852. if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
  1853. *action = REPLAY_PICK;
  1854. else if (is_command(TODO_REVERT, &bol) &&
  1855. (*bol == ' ' || *bol == '\t'))
  1856. *action = REPLAY_REVERT;
  1857. else
  1858. ret = -1;
  1859. strbuf_release(&buf);
  1860. return ret;
  1861. }
  1862. int todo_list_parse_insn_buffer(struct repository *r, char *buf,
  1863. struct todo_list *todo_list)
  1864. {
  1865. struct todo_item *item;
  1866. char *p = buf, *next_p;
  1867. int i, res = 0, fixup_okay = file_exists(rebase_path_done());
  1868. todo_list->current = todo_list->nr = 0;
  1869. for (i = 1; *p; i++, p = next_p) {
  1870. char *eol = strchrnul(p, '\n');
  1871. next_p = *eol ? eol + 1 /* skip LF */ : eol;
  1872. if (p != eol && eol[-1] == '\r')
  1873. eol--; /* strip Carriage Return */
  1874. item = append_new_todo(todo_list);
  1875. item->offset_in_buf = p - todo_list->buf.buf;
  1876. if (parse_insn_line(r, item, buf, p, eol)) {
  1877. res = error(_("invalid line %d: %.*s"),
  1878. i, (int)(eol - p), p);
  1879. item->command = TODO_COMMENT + 1;
  1880. item->arg_offset = p - buf;
  1881. item->arg_len = (int)(eol - p);
  1882. item->commit = NULL;
  1883. }
  1884. if (fixup_okay)
  1885. ; /* do nothing */
  1886. else if (is_fixup(item->command))
  1887. return error(_("cannot '%s' without a previous commit"),
  1888. command_to_string(item->command));
  1889. else if (!is_noop(item->command))
  1890. fixup_okay = 1;
  1891. }
  1892. return res;
  1893. }
  1894. static int count_commands(struct todo_list *todo_list)
  1895. {
  1896. int count = 0, i;
  1897. for (i = 0; i < todo_list->nr; i++)
  1898. if (todo_list->items[i].command != TODO_COMMENT)
  1899. count++;
  1900. return count;
  1901. }
  1902. static int get_item_line_offset(struct todo_list *todo_list, int index)
  1903. {
  1904. return index < todo_list->nr ?
  1905. todo_list->items[index].offset_in_buf : todo_list->buf.len;
  1906. }
  1907. static const char *get_item_line(struct todo_list *todo_list, int index)
  1908. {
  1909. return todo_list->buf.buf + get_item_line_offset(todo_list, index);
  1910. }
  1911. static int get_item_line_length(struct todo_list *todo_list, int index)
  1912. {
  1913. return get_item_line_offset(todo_list, index + 1)
  1914. - get_item_line_offset(todo_list, index);
  1915. }
  1916. static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
  1917. {
  1918. int fd;
  1919. ssize_t len;
  1920. fd = open(path, O_RDONLY);
  1921. if (fd < 0)
  1922. return error_errno(_("could not open '%s'"), path);
  1923. len = strbuf_read(sb, fd, 0);
  1924. close(fd);
  1925. if (len < 0)
  1926. return error(_("could not read '%s'."), path);
  1927. return len;
  1928. }
  1929. static int have_finished_the_last_pick(void)
  1930. {
  1931. struct strbuf buf = STRBUF_INIT;
  1932. const char *eol;
  1933. const char *todo_path = git_path_todo_file();
  1934. int ret = 0;
  1935. if (strbuf_read_file(&buf, todo_path, 0) < 0) {
  1936. if (errno == ENOENT) {
  1937. return 0;
  1938. } else {
  1939. error_errno("unable to open '%s'", todo_path);
  1940. return 0;
  1941. }
  1942. }
  1943. /* If there is only one line then we are done */
  1944. eol = strchr(buf.buf, '\n');
  1945. if (!eol || !eol[1])
  1946. ret = 1;
  1947. strbuf_release(&buf);
  1948. return ret;
  1949. }
  1950. void sequencer_post_commit_cleanup(struct repository *r, int verbose)
  1951. {
  1952. struct replay_opts opts = REPLAY_OPTS_INIT;
  1953. int need_cleanup = 0;
  1954. if (file_exists(git_path_cherry_pick_head(r))) {
  1955. if (!unlink(git_path_cherry_pick_head(r)) && verbose)
  1956. warning(_("cancelling a cherry picking in progress"));
  1957. opts.action = REPLAY_PICK;
  1958. need_cleanup = 1;
  1959. }
  1960. if (file_exists(git_path_revert_head(r))) {
  1961. if (!unlink(git_path_revert_head(r)) && verbose)
  1962. warning(_("cancelling a revert in progress"));
  1963. opts.action = REPLAY_REVERT;
  1964. need_cleanup = 1;
  1965. }
  1966. if (!need_cleanup)
  1967. return;
  1968. if (!have_finished_the_last_pick())
  1969. return;
  1970. sequencer_remove_state(&opts);
  1971. }
  1972. static int read_populate_todo(struct repository *r,
  1973. struct todo_list *todo_list,
  1974. struct replay_opts *opts)
  1975. {
  1976. struct stat st;
  1977. const char *todo_file = get_todo_path(opts);
  1978. int res;
  1979. strbuf_reset(&todo_list->buf);
  1980. if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
  1981. return -1;
  1982. res = stat(todo_file, &st);
  1983. if (res)
  1984. return error(_("could not stat '%s'"), todo_file);
  1985. fill_stat_data(&todo_list->stat, &st);
  1986. res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
  1987. if (res) {
  1988. if (is_rebase_i(opts))
  1989. return error(_("please fix this using "
  1990. "'git rebase --edit-todo'."));
  1991. return error(_("unusable instruction sheet: '%s'"), todo_file);
  1992. }
  1993. if (!todo_list->nr &&
  1994. (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
  1995. return error(_("no commits parsed."));
  1996. if (!is_rebase_i(opts)) {
  1997. enum todo_command valid =
  1998. opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
  1999. int i;
  2000. for (i = 0; i < todo_list->nr; i++)
  2001. if (valid == todo_list->items[i].command)
  2002. continue;
  2003. else if (valid == TODO_PICK)
  2004. return error(_("cannot cherry-pick during a revert."));
  2005. else
  2006. return error(_("cannot revert during a cherry-pick."));
  2007. }
  2008. if (is_rebase_i(opts)) {
  2009. struct todo_list done = TODO_LIST_INIT;
  2010. FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
  2011. if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
  2012. !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
  2013. todo_list->done_nr = count_commands(&done);
  2014. else
  2015. todo_list->done_nr = 0;
  2016. todo_list->total_nr = todo_list->done_nr
  2017. + count_commands(todo_list);
  2018. todo_list_release(&done);
  2019. if (f) {
  2020. fprintf(f, "%d\n", todo_list->total_nr);
  2021. fclose(f);
  2022. }
  2023. }
  2024. return 0;
  2025. }
  2026. static int git_config_string_dup(char **dest,
  2027. const char *var, const char *value)
  2028. {
  2029. if (!value)
  2030. return config_error_nonbool(var);
  2031. free(*dest);
  2032. *dest = xstrdup(value);
  2033. return 0;
  2034. }
  2035. static int populate_opts_cb(const char *key, const char *value, void *data)
  2036. {
  2037. struct replay_opts *opts = data;
  2038. int error_flag = 1;
  2039. if (!value)
  2040. error_flag = 0;
  2041. else if (!strcmp(key, "options.no-commit"))
  2042. opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
  2043. else if (!strcmp(key, "options.edit"))
  2044. opts->edit = git_config_bool_or_int(key, value, &error_flag);
  2045. else if (!strcmp(key, "options.allow-empty"))
  2046. opts->allow_empty =
  2047. git_config_bool_or_int(key, value, &error_flag);
  2048. else if (!strcmp(key, "options.allow-empty-message"))
  2049. opts->allow_empty_message =
  2050. git_config_bool_or_int(key, value, &error_flag);
  2051. else if (!strcmp(key, "options.keep-redundant-commits"))
  2052. opts->keep_redundant_commits =
  2053. git_config_bool_or_int(key, value, &error_flag);
  2054. else if (!strcmp(key, "options.signoff"))
  2055. opts->signoff = git_config_bool_or_int(key, value, &error_flag);
  2056. else if (!strcmp(key, "options.record-origin"))
  2057. opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
  2058. else if (!strcmp(key, "options.allow-ff"))
  2059. opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
  2060. else if (!strcmp(key, "options.mainline"))
  2061. opts->mainline = git_config_int(key, value);
  2062. else if (!strcmp(key, "options.strategy"))
  2063. git_config_string_dup(&opts->strategy, key, value);
  2064. else if (!strcmp(key, "options.gpg-sign"))
  2065. git_config_string_dup(&opts->gpg_sign, key, value);
  2066. else if (!strcmp(key, "options.strategy-option")) {
  2067. ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
  2068. opts->xopts[opts->xopts_nr++] = xstrdup(value);
  2069. } else if (!strcmp(key, "options.allow-rerere-auto"))
  2070. opts->allow_rerere_auto =
  2071. git_config_bool_or_int(key, value, &error_flag) ?
  2072. RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
  2073. else if (!strcmp(key, "options.default-msg-cleanup")) {
  2074. opts->explicit_cleanup = 1;
  2075. opts->default_msg_cleanup = get_cleanup_mode(value, 1);
  2076. } else
  2077. return error(_("invalid key: %s"), key);
  2078. if (!error_flag)
  2079. return error(_("invalid value for %s: %s"), key, value);
  2080. return 0;
  2081. }
  2082. void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
  2083. {
  2084. int i;
  2085. char *strategy_opts_string = raw_opts;
  2086. if (*strategy_opts_string == ' ')
  2087. strategy_opts_string++;
  2088. opts->xopts_nr = split_cmdline(strategy_opts_string,
  2089. (const char ***)&opts->xopts);
  2090. for (i = 0; i < opts->xopts_nr; i++) {
  2091. const char *arg = opts->xopts[i];
  2092. skip_prefix(arg, "--", &arg);
  2093. opts->xopts[i] = xstrdup(arg);
  2094. }
  2095. }
  2096. static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
  2097. {
  2098. strbuf_reset(buf);
  2099. if (!read_oneliner(buf, rebase_path_strategy(), 0))
  2100. return;
  2101. opts->strategy = strbuf_detach(buf, NULL);
  2102. if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
  2103. return;
  2104. parse_strategy_opts(opts, buf->buf);
  2105. }
  2106. static int read_populate_opts(struct replay_opts *opts)
  2107. {
  2108. if (is_rebase_i(opts)) {
  2109. struct strbuf buf = STRBUF_INIT;
  2110. if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
  2111. if (!starts_with(buf.buf, "-S"))
  2112. strbuf_reset(&buf);
  2113. else {
  2114. free(opts->gpg_sign);
  2115. opts->gpg_sign = xstrdup(buf.buf + 2);
  2116. }
  2117. strbuf_reset(&buf);
  2118. }
  2119. if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(), 1)) {
  2120. if (!strcmp(buf.buf, "--rerere-autoupdate"))
  2121. opts->allow_rerere_auto = RERERE_AUTOUPDATE;
  2122. else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
  2123. opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
  2124. strbuf_reset(&buf);
  2125. }
  2126. if (file_exists(rebase_path_verbose()))
  2127. opts->verbose = 1;
  2128. if (file_exists(rebase_path_quiet()))
  2129. opts->quiet = 1;
  2130. if (file_exists(rebase_path_signoff())) {
  2131. opts->allow_ff = 0;
  2132. opts->signoff = 1;
  2133. }
  2134. if (file_exists(rebase_path_reschedule_failed_exec()))
  2135. opts->reschedule_failed_exec = 1;
  2136. read_strategy_opts(opts, &buf);
  2137. strbuf_release(&buf);
  2138. if (read_oneliner(&opts->current_fixups,
  2139. rebase_path_current_fixups(), 1)) {
  2140. const char *p = opts->current_fixups.buf;
  2141. opts->current_fixup_count = 1;
  2142. while ((p = strchr(p, '\n'))) {
  2143. opts->current_fixup_count++;
  2144. p++;
  2145. }
  2146. }
  2147. if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
  2148. if (get_oid_hex(buf.buf, &opts->squash_onto) < 0)
  2149. return error(_("unusable squash-onto"));
  2150. opts->have_squash_onto = 1;
  2151. }
  2152. return 0;
  2153. }
  2154. if (!file_exists(git_path_opts_file()))
  2155. return 0;
  2156. /*
  2157. * The function git_parse_source(), called from git_config_from_file(),
  2158. * may die() in case of a syntactically incorrect file. We do not care
  2159. * about this case, though, because we wrote that file ourselves, so we
  2160. * are pretty certain that it is syntactically correct.
  2161. */
  2162. if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
  2163. return error(_("malformed options sheet: '%s'"),
  2164. git_path_opts_file());
  2165. return 0;
  2166. }
  2167. static void write_strategy_opts(struct replay_opts *opts)
  2168. {
  2169. int i;
  2170. struct strbuf buf = STRBUF_INIT;
  2171. for (i = 0; i < opts->xopts_nr; ++i)
  2172. strbuf_addf(&buf, " --%s", opts->xopts[i]);
  2173. write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
  2174. strbuf_release(&buf);
  2175. }
  2176. int write_basic_state(struct replay_opts *opts, const char *head_name,
  2177. struct commit *onto, const char *orig_head)
  2178. {
  2179. const char *quiet = getenv("GIT_QUIET");
  2180. if (head_name)
  2181. write_file(rebase_path_head_name(), "%s\n", head_name);
  2182. if (onto)
  2183. write_file(rebase_path_onto(), "%s\n",
  2184. oid_to_hex(&onto->object.oid));
  2185. if (orig_head)
  2186. write_file(rebase_path_orig_head(), "%s\n", orig_head);
  2187. if (quiet)
  2188. write_file(rebase_path_quiet(), "%s\n", quiet);
  2189. if (opts->verbose)
  2190. write_file(rebase_path_verbose(), "%s", "");
  2191. if (opts->strategy)
  2192. write_file(rebase_path_strategy(), "%s\n", opts->strategy);
  2193. if (opts->xopts_nr > 0)
  2194. write_strategy_opts(opts);
  2195. if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
  2196. write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
  2197. else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
  2198. write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
  2199. if (opts->gpg_sign)
  2200. write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
  2201. if (opts->signoff)
  2202. write_file(rebase_path_signoff(), "--signoff\n");
  2203. if (opts->reschedule_failed_exec)
  2204. write_file(rebase_path_reschedule_failed_exec(), "%s", "");
  2205. return 0;
  2206. }
  2207. static int walk_revs_populate_todo(struct todo_list *todo_list,
  2208. struct replay_opts *opts)
  2209. {
  2210. enum todo_command command = opts->action == REPLAY_PICK ?
  2211. TODO_PICK : TODO_REVERT;
  2212. const char *command_string = todo_command_info[command].str;
  2213. struct commit *commit;
  2214. if (prepare_revs(opts))
  2215. return -1;
  2216. while ((commit = get_revision(opts->revs))) {
  2217. struct todo_item *item = append_new_todo(todo_list);
  2218. const char *commit_buffer = get_commit_buffer(commit, NULL);
  2219. const char *subject;
  2220. int subject_len;
  2221. item->command = command;
  2222. item->commit = commit;
  2223. item->arg_offset = 0;
  2224. item->arg_len = 0;
  2225. item->offset_in_buf = todo_list->buf.len;
  2226. subject_len = find_commit_subject(commit_buffer, &subject);
  2227. strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
  2228. short_commit_name(commit), subject_len, subject);
  2229. unuse_commit_buffer(commit, commit_buffer);
  2230. }
  2231. if (!todo_list->nr)
  2232. return error(_("empty commit set passed"));
  2233. return 0;
  2234. }
  2235. static int create_seq_dir(struct repository *r)
  2236. {
  2237. enum replay_action action;
  2238. const char *in_progress_error = NULL;
  2239. const char *in_progress_advice = NULL;
  2240. unsigned int advise_skip = file_exists(git_path_revert_head(r)) ||
  2241. file_exists(git_path_cherry_pick_head(r));
  2242. if (!sequencer_get_last_command(r, &action)) {
  2243. switch (action) {
  2244. case REPLAY_REVERT:
  2245. in_progress_error = _("revert is already in progress");
  2246. in_progress_advice =
  2247. _("try \"git revert (--continue | %s--abort | --quit)\"");
  2248. break;
  2249. case REPLAY_PICK:
  2250. in_progress_error = _("cherry-pick is already in progress");
  2251. in_progress_advice =
  2252. _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
  2253. break;
  2254. default:
  2255. BUG("unexpected action in create_seq_dir");
  2256. }
  2257. }
  2258. if (in_progress_error) {
  2259. error("%s", in_progress_error);
  2260. if (advice_sequencer_in_use)
  2261. advise(in_progress_advice,
  2262. advise_skip ? "--skip | " : "");
  2263. return -1;
  2264. }
  2265. if (mkdir(git_path_seq_dir(), 0777) < 0)
  2266. return error_errno(_("could not create sequencer directory '%s'"),
  2267. git_path_seq_dir());
  2268. return 0;
  2269. }
  2270. static int save_head(const char *head)
  2271. {
  2272. struct lock_file head_lock = LOCK_INIT;
  2273. struct strbuf buf = STRBUF_INIT;
  2274. int fd;
  2275. ssize_t written;
  2276. fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
  2277. if (fd < 0)
  2278. return error_errno(_("could not lock HEAD"));
  2279. strbuf_addf(&buf, "%s\n", head);
  2280. written = write_in_full(fd, buf.buf, buf.len);
  2281. strbuf_release(&buf);
  2282. if (written < 0) {
  2283. error_errno(_("could not write to '%s'"), git_path_head_file());
  2284. rollback_lock_file(&head_lock);
  2285. return -1;
  2286. }
  2287. if (commit_lock_file(&head_lock) < 0)
  2288. return error(_("failed to finalize '%s'"), git_path_head_file());
  2289. return 0;
  2290. }
  2291. static int rollback_is_safe(void)
  2292. {
  2293. struct strbuf sb = STRBUF_INIT;
  2294. struct object_id expected_head, actual_head;
  2295. if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
  2296. strbuf_trim(&sb);
  2297. if (get_oid_hex(sb.buf, &expected_head)) {
  2298. strbuf_release(&sb);
  2299. die(_("could not parse %s"), git_path_abort_safety_file());
  2300. }
  2301. strbuf_release(&sb);
  2302. }
  2303. else if (errno == ENOENT)
  2304. oidclr(&expected_head);
  2305. else
  2306. die_errno(_("could not read '%s'"), git_path_abort_safety_file());
  2307. if (get_oid("HEAD", &actual_head))
  2308. oidclr(&actual_head);
  2309. return oideq(&actual_head, &expected_head);
  2310. }
  2311. static int reset_merge(const struct object_id *oid)
  2312. {
  2313. int ret;
  2314. struct argv_array argv = ARGV_ARRAY_INIT;
  2315. argv_array_pushl(&argv, "reset", "--merge", NULL);
  2316. if (!is_null_oid(oid))
  2317. argv_array_push(&argv, oid_to_hex(oid));
  2318. ret = run_command_v_opt(argv.argv, RUN_GIT_CMD);
  2319. argv_array_clear(&argv);
  2320. return ret;
  2321. }
  2322. static int rollback_single_pick(struct repository *r)
  2323. {
  2324. struct object_id head_oid;
  2325. if (!file_exists(git_path_cherry_pick_head(r)) &&
  2326. !file_exists(git_path_revert_head(r)))
  2327. return error(_("no cherry-pick or revert in progress"));
  2328. if (read_ref_full("HEAD", 0, &head_oid, NULL))
  2329. return error(_("cannot resolve HEAD"));
  2330. if (is_null_oid(&head_oid))
  2331. return error(_("cannot abort from a branch yet to be born"));
  2332. return reset_merge(&head_oid);
  2333. }
  2334. static int skip_single_pick(void)
  2335. {
  2336. struct object_id head;
  2337. if (read_ref_full("HEAD", 0, &head, NULL))
  2338. return error(_("cannot resolve HEAD"));
  2339. return reset_merge(&head);
  2340. }
  2341. int sequencer_rollback(struct repository *r, struct replay_opts *opts)
  2342. {
  2343. FILE *f;
  2344. struct object_id oid;
  2345. struct strbuf buf = STRBUF_INIT;
  2346. const char *p;
  2347. f = fopen(git_path_head_file(), "r");
  2348. if (!f && errno == ENOENT) {
  2349. /*
  2350. * There is no multiple-cherry-pick in progress.
  2351. * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
  2352. * a single-cherry-pick in progress, abort that.
  2353. */
  2354. return rollback_single_pick(r);
  2355. }
  2356. if (!f)
  2357. return error_errno(_("cannot open '%s'"), git_path_head_file());
  2358. if (strbuf_getline_lf(&buf, f)) {
  2359. error(_("cannot read '%s': %s"), git_path_head_file(),
  2360. ferror(f) ? strerror(errno) : _("unexpected end of file"));
  2361. fclose(f);
  2362. goto fail;
  2363. }
  2364. fclose(f);
  2365. if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
  2366. error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
  2367. git_path_head_file());
  2368. goto fail;
  2369. }
  2370. if (is_null_oid(&oid)) {
  2371. error(_("cannot abort from a branch yet to be born"));
  2372. goto fail;
  2373. }
  2374. if (!rollback_is_safe()) {
  2375. /* Do not error, just do not rollback */
  2376. warning(_("You seem to have moved HEAD. "
  2377. "Not rewinding, check your HEAD!"));
  2378. } else
  2379. if (reset_merge(&oid))
  2380. goto fail;
  2381. strbuf_release(&buf);
  2382. return sequencer_remove_state(opts);
  2383. fail:
  2384. strbuf_release(&buf);
  2385. return -1;
  2386. }
  2387. int sequencer_skip(struct repository *r, struct replay_opts *opts)
  2388. {
  2389. enum replay_action action = -1;
  2390. sequencer_get_last_command(r, &action);
  2391. /*
  2392. * Check whether the subcommand requested to skip the commit is actually
  2393. * in progress and that it's safe to skip the commit.
  2394. *
  2395. * opts->action tells us which subcommand requested to skip the commit.
  2396. * If the corresponding .git/<ACTION>_HEAD exists, we know that the
  2397. * action is in progress and we can skip the commit.
  2398. *
  2399. * Otherwise we check that the last instruction was related to the
  2400. * particular subcommand we're trying to execute and barf if that's not
  2401. * the case.
  2402. *
  2403. * Finally we check that the rollback is "safe", i.e., has the HEAD
  2404. * moved? In this case, it doesn't make sense to "reset the merge" and
  2405. * "skip the commit" as the user already handled this by committing. But
  2406. * we'd not want to barf here, instead give advice on how to proceed. We
  2407. * only need to check that when .git/<ACTION>_HEAD doesn't exist because
  2408. * it gets removed when the user commits, so if it still exists we're
  2409. * sure the user can't have committed before.
  2410. */
  2411. switch (opts->action) {
  2412. case REPLAY_REVERT:
  2413. if (!file_exists(git_path_revert_head(r))) {
  2414. if (action != REPLAY_REVERT)
  2415. return error(_("no revert in progress"));
  2416. if (!rollback_is_safe())
  2417. goto give_advice;
  2418. }
  2419. break;
  2420. case REPLAY_PICK:
  2421. if (!file_exists(git_path_cherry_pick_head(r))) {
  2422. if (action != REPLAY_PICK)
  2423. return error(_("no cherry-pick in progress"));
  2424. if (!rollback_is_safe())
  2425. goto give_advice;
  2426. }
  2427. break;
  2428. default:
  2429. BUG("unexpected action in sequencer_skip");
  2430. }
  2431. if (skip_single_pick())
  2432. return error(_("failed to skip the commit"));
  2433. if (!is_directory(git_path_seq_dir()))
  2434. return 0;
  2435. return sequencer_continue(r, opts);
  2436. give_advice:
  2437. error(_("there is nothing to skip"));
  2438. if (advice_resolve_conflict) {
  2439. advise(_("have you committed already?\n"
  2440. "try \"git %s --continue\""),
  2441. action == REPLAY_REVERT ? "revert" : "cherry-pick");
  2442. }
  2443. return -1;
  2444. }
  2445. static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
  2446. {
  2447. struct lock_file todo_lock = LOCK_INIT;
  2448. const char *todo_path = get_todo_path(opts);
  2449. int next = todo_list->current, offset, fd;
  2450. /*
  2451. * rebase -i writes "git-rebase-todo" without the currently executing
  2452. * command, appending it to "done" instead.
  2453. */
  2454. if (is_rebase_i(opts))
  2455. next++;
  2456. fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
  2457. if (fd < 0)
  2458. return error_errno(_("could not lock '%s'"), todo_path);
  2459. offset = get_item_line_offset(todo_list, next);
  2460. if (write_in_full(fd, todo_list->buf.buf + offset,
  2461. todo_list->buf.len - offset) < 0)
  2462. return error_errno(_("could not write to '%s'"), todo_path);
  2463. if (commit_lock_file(&todo_lock) < 0)
  2464. return error(_("failed to finalize '%s'"), todo_path);
  2465. if (is_rebase_i(opts) && next > 0) {
  2466. const char *done = rebase_path_done();
  2467. int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
  2468. int ret = 0;
  2469. if (fd < 0)
  2470. return 0;
  2471. if (write_in_full(fd, get_item_line(todo_list, next - 1),
  2472. get_item_line_length(todo_list, next - 1))
  2473. < 0)
  2474. ret = error_errno(_("could not write to '%s'"), done);
  2475. if (close(fd) < 0)
  2476. ret = error_errno(_("failed to finalize '%s'"), done);
  2477. return ret;
  2478. }
  2479. return 0;
  2480. }
  2481. static int save_opts(struct replay_opts *opts)
  2482. {
  2483. const char *opts_file = git_path_opts_file();
  2484. int res = 0;
  2485. if (opts->no_commit)
  2486. res |= git_config_set_in_file_gently(opts_file,
  2487. "options.no-commit", "true");
  2488. if (opts->edit)
  2489. res |= git_config_set_in_file_gently(opts_file,
  2490. "options.edit", "true");
  2491. if (opts->allow_empty)
  2492. res |= git_config_set_in_file_gently(opts_file,
  2493. "options.allow-empty", "true");
  2494. if (opts->allow_empty_message)
  2495. res |= git_config_set_in_file_gently(opts_file,
  2496. "options.allow-empty-message", "true");
  2497. if (opts->keep_redundant_commits)
  2498. res |= git_config_set_in_file_gently(opts_file,
  2499. "options.keep-redundant-commits", "true");
  2500. if (opts->signoff)
  2501. res |= git_config_set_in_file_gently(opts_file,
  2502. "options.signoff", "true");
  2503. if (opts->record_origin)
  2504. res |= git_config_set_in_file_gently(opts_file,
  2505. "options.record-origin", "true");
  2506. if (opts->allow_ff)
  2507. res |= git_config_set_in_file_gently(opts_file,
  2508. "options.allow-ff", "true");
  2509. if (opts->mainline) {
  2510. struct strbuf buf = STRBUF_INIT;
  2511. strbuf_addf(&buf, "%d", opts->mainline);
  2512. res |= git_config_set_in_file_gently(opts_file,
  2513. "options.mainline", buf.buf);
  2514. strbuf_release(&buf);
  2515. }
  2516. if (opts->strategy)
  2517. res |= git_config_set_in_file_gently(opts_file,
  2518. "options.strategy", opts->strategy);
  2519. if (opts->gpg_sign)
  2520. res |= git_config_set_in_file_gently(opts_file,
  2521. "options.gpg-sign", opts->gpg_sign);
  2522. if (opts->xopts) {
  2523. int i;
  2524. for (i = 0; i < opts->xopts_nr; i++)
  2525. res |= git_config_set_multivar_in_file_gently(opts_file,
  2526. "options.strategy-option",
  2527. opts->xopts[i], "^$", 0);
  2528. }
  2529. if (opts->allow_rerere_auto)
  2530. res |= git_config_set_in_file_gently(opts_file,
  2531. "options.allow-rerere-auto",
  2532. opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
  2533. "true" : "false");
  2534. if (opts->explicit_cleanup)
  2535. res |= git_config_set_in_file_gently(opts_file,
  2536. "options.default-msg-cleanup",
  2537. describe_cleanup_mode(opts->default_msg_cleanup));
  2538. return res;
  2539. }
  2540. static int make_patch(struct repository *r,
  2541. struct commit *commit,
  2542. struct replay_opts *opts)
  2543. {
  2544. struct strbuf buf = STRBUF_INIT;
  2545. struct rev_info log_tree_opt;
  2546. const char *subject, *p;
  2547. int res = 0;
  2548. p = short_commit_name(commit);
  2549. if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
  2550. return -1;
  2551. if (update_ref("rebase", "REBASE_HEAD", &commit->object.oid,
  2552. NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
  2553. res |= error(_("could not update %s"), "REBASE_HEAD");
  2554. strbuf_addf(&buf, "%s/patch", get_dir(opts));
  2555. memset(&log_tree_opt, 0, sizeof(log_tree_opt));
  2556. repo_init_revisions(r, &log_tree_opt, NULL);
  2557. log_tree_opt.abbrev = 0;
  2558. log_tree_opt.diff = 1;
  2559. log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
  2560. log_tree_opt.disable_stdin = 1;
  2561. log_tree_opt.no_commit_id = 1;
  2562. log_tree_opt.diffopt.file = fopen(buf.buf, "w");
  2563. log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
  2564. if (!log_tree_opt.diffopt.file)
  2565. res |= error_errno(_("could not open '%s'"), buf.buf);
  2566. else {
  2567. res |= log_tree_commit(&log_tree_opt, commit);
  2568. fclose(log_tree_opt.diffopt.file);
  2569. }
  2570. strbuf_reset(&buf);
  2571. strbuf_addf(&buf, "%s/message", get_dir(opts));
  2572. if (!file_exists(buf.buf)) {
  2573. const char *commit_buffer = get_commit_buffer(commit, NULL);
  2574. find_commit_subject(commit_buffer, &subject);
  2575. res |= write_message(subject, strlen(subject), buf.buf, 1);
  2576. unuse_commit_buffer(commit, commit_buffer);
  2577. }
  2578. strbuf_release(&buf);
  2579. return res;
  2580. }
  2581. static int intend_to_amend(void)
  2582. {
  2583. struct object_id head;
  2584. char *p;
  2585. if (get_oid("HEAD", &head))
  2586. return error(_("cannot read HEAD"));
  2587. p = oid_to_hex(&head);
  2588. return write_message(p, strlen(p), rebase_path_amend(), 1);
  2589. }
  2590. static int error_with_patch(struct repository *r,
  2591. struct commit *commit,
  2592. const char *subject, int subject_len,
  2593. struct replay_opts *opts,
  2594. int exit_code, int to_amend)
  2595. {
  2596. if (commit) {
  2597. if (make_patch(r, commit, opts))
  2598. return -1;
  2599. } else if (copy_file(rebase_path_message(),
  2600. git_path_merge_msg(r), 0666))
  2601. return error(_("unable to copy '%s' to '%s'"),
  2602. git_path_merge_msg(r), rebase_path_message());
  2603. if (to_amend) {
  2604. if (intend_to_amend())
  2605. return -1;
  2606. fprintf(stderr,
  2607. _("You can amend the commit now, with\n"
  2608. "\n"
  2609. " git commit --amend %s\n"
  2610. "\n"
  2611. "Once you are satisfied with your changes, run\n"
  2612. "\n"
  2613. " git rebase --continue\n"),
  2614. gpg_sign_opt_quoted(opts));
  2615. } else if (exit_code) {
  2616. if (commit)
  2617. fprintf_ln(stderr, _("Could not apply %s... %.*s"),
  2618. short_commit_name(commit), subject_len, subject);
  2619. else
  2620. /*
  2621. * We don't have the hash of the parent so
  2622. * just print the line from the todo file.
  2623. */
  2624. fprintf_ln(stderr, _("Could not merge %.*s"),
  2625. subject_len, subject);
  2626. }
  2627. return exit_code;
  2628. }
  2629. static int error_failed_squash(struct repository *r,
  2630. struct commit *commit,
  2631. struct replay_opts *opts,
  2632. int subject_len,
  2633. const char *subject)
  2634. {
  2635. if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
  2636. return error(_("could not copy '%s' to '%s'"),
  2637. rebase_path_squash_msg(), rebase_path_message());
  2638. unlink(git_path_merge_msg(r));
  2639. if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
  2640. return error(_("could not copy '%s' to '%s'"),
  2641. rebase_path_message(),
  2642. git_path_merge_msg(r));
  2643. return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
  2644. }
  2645. static int do_exec(struct repository *r, const char *command_line)
  2646. {
  2647. struct argv_array child_env = ARGV_ARRAY_INIT;
  2648. const char *child_argv[] = { NULL, NULL };
  2649. int dirty, status;
  2650. fprintf(stderr, "Executing: %s\n", command_line);
  2651. child_argv[0] = command_line;
  2652. argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
  2653. argv_array_pushf(&child_env, "GIT_WORK_TREE=%s",
  2654. absolute_path(get_git_work_tree()));
  2655. status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
  2656. child_env.argv);
  2657. /* force re-reading of the cache */
  2658. if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
  2659. return error(_("could not read index"));
  2660. dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
  2661. if (status) {
  2662. warning(_("execution failed: %s\n%s"
  2663. "You can fix the problem, and then run\n"
  2664. "\n"
  2665. " git rebase --continue\n"
  2666. "\n"),
  2667. command_line,
  2668. dirty ? N_("and made changes to the index and/or the "
  2669. "working tree\n") : "");
  2670. if (status == 127)
  2671. /* command not found */
  2672. status = 1;
  2673. } else if (dirty) {
  2674. warning(_("execution succeeded: %s\nbut "
  2675. "left changes to the index and/or the working tree\n"
  2676. "Commit or stash your changes, and then run\n"
  2677. "\n"
  2678. " git rebase --continue\n"
  2679. "\n"), command_line);
  2680. status = 1;
  2681. }
  2682. argv_array_clear(&child_env);
  2683. return status;
  2684. }
  2685. static int safe_append(const char *filename, const char *fmt, ...)
  2686. {
  2687. va_list ap;
  2688. struct lock_file lock = LOCK_INIT;
  2689. int fd = hold_lock_file_for_update(&lock, filename,
  2690. LOCK_REPORT_ON_ERROR);
  2691. struct strbuf buf = STRBUF_INIT;
  2692. if (fd < 0)
  2693. return -1;
  2694. if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
  2695. error_errno(_("could not read '%s'"), filename);
  2696. rollback_lock_file(&lock);
  2697. return -1;
  2698. }
  2699. strbuf_complete(&buf, '\n');
  2700. va_start(ap, fmt);
  2701. strbuf_vaddf(&buf, fmt, ap);
  2702. va_end(ap);
  2703. if (write_in_full(fd, buf.buf, buf.len) < 0) {
  2704. error_errno(_("could not write to '%s'"), filename);
  2705. strbuf_release(&buf);
  2706. rollback_lock_file(&lock);
  2707. return -1;
  2708. }
  2709. if (commit_lock_file(&lock) < 0) {
  2710. strbuf_release(&buf);
  2711. rollback_lock_file(&lock);
  2712. return error(_("failed to finalize '%s'"), filename);
  2713. }
  2714. strbuf_release(&buf);
  2715. return 0;
  2716. }
  2717. static int do_label(struct repository *r, const char *name, int len)
  2718. {
  2719. struct ref_store *refs = get_main_ref_store(r);
  2720. struct ref_transaction *transaction;
  2721. struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
  2722. struct strbuf msg = STRBUF_INIT;
  2723. int ret = 0;
  2724. struct object_id head_oid;
  2725. if (len == 1 && *name == '#')
  2726. return error(_("illegal label name: '%.*s'"), len, name);
  2727. strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
  2728. strbuf_addf(&msg, "rebase -i (label) '%.*s'", len, name);
  2729. transaction = ref_store_transaction_begin(refs, &err);
  2730. if (!transaction) {
  2731. error("%s", err.buf);
  2732. ret = -1;
  2733. } else if (get_oid("HEAD", &head_oid)) {
  2734. error(_("could not read HEAD"));
  2735. ret = -1;
  2736. } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
  2737. NULL, 0, msg.buf, &err) < 0 ||
  2738. ref_transaction_commit(transaction, &err)) {
  2739. error("%s", err.buf);
  2740. ret = -1;
  2741. }
  2742. ref_transaction_free(transaction);
  2743. strbuf_release(&err);
  2744. strbuf_release(&msg);
  2745. if (!ret)
  2746. ret = safe_append(rebase_path_refs_to_delete(),
  2747. "%s\n", ref_name.buf);
  2748. strbuf_release(&ref_name);
  2749. return ret;
  2750. }
  2751. static const char *reflog_message(struct replay_opts *opts,
  2752. const char *sub_action, const char *fmt, ...);
  2753. static int do_reset(struct repository *r,
  2754. const char *name, int len,
  2755. struct replay_opts *opts)
  2756. {
  2757. struct strbuf ref_name = STRBUF_INIT;
  2758. struct object_id oid;
  2759. struct lock_file lock = LOCK_INIT;
  2760. struct tree_desc desc;
  2761. struct tree *tree;
  2762. struct unpack_trees_options unpack_tree_opts;
  2763. int ret = 0;
  2764. if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
  2765. return -1;
  2766. if (len == 10 && !strncmp("[new root]", name, len)) {
  2767. if (!opts->have_squash_onto) {
  2768. const char *hex;
  2769. if (commit_tree("", 0, the_hash_algo->empty_tree,
  2770. NULL, &opts->squash_onto,
  2771. NULL, NULL))
  2772. return error(_("writing fake root commit"));
  2773. opts->have_squash_onto = 1;
  2774. hex = oid_to_hex(&opts->squash_onto);
  2775. if (write_message(hex, strlen(hex),
  2776. rebase_path_squash_onto(), 0))
  2777. return error(_("writing squash-onto"));
  2778. }
  2779. oidcpy(&oid, &opts->squash_onto);
  2780. } else {
  2781. int i;
  2782. /* Determine the length of the label */
  2783. for (i = 0; i < len; i++)
  2784. if (isspace(name[i]))
  2785. break;
  2786. len = i;
  2787. strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
  2788. if (get_oid(ref_name.buf, &oid) &&
  2789. get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
  2790. error(_("could not read '%s'"), ref_name.buf);
  2791. rollback_lock_file(&lock);
  2792. strbuf_release(&ref_name);
  2793. return -1;
  2794. }
  2795. }
  2796. memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
  2797. setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
  2798. unpack_tree_opts.head_idx = 1;
  2799. unpack_tree_opts.src_index = r->index;
  2800. unpack_tree_opts.dst_index = r->index;
  2801. unpack_tree_opts.fn = oneway_merge;
  2802. unpack_tree_opts.merge = 1;
  2803. unpack_tree_opts.update = 1;
  2804. if (repo_read_index_unmerged(r)) {
  2805. rollback_lock_file(&lock);
  2806. strbuf_release(&ref_name);
  2807. return error_resolve_conflict(_(action_name(opts)));
  2808. }
  2809. if (!fill_tree_descriptor(r, &desc, &oid)) {
  2810. error(_("failed to find tree of %s"), oid_to_hex(&oid));
  2811. rollback_lock_file(&lock);
  2812. free((void *)desc.buffer);
  2813. strbuf_release(&ref_name);
  2814. return -1;
  2815. }
  2816. if (unpack_trees(1, &desc, &unpack_tree_opts)) {
  2817. rollback_lock_file(&lock);
  2818. free((void *)desc.buffer);
  2819. strbuf_release(&ref_name);
  2820. return -1;
  2821. }
  2822. tree = parse_tree_indirect(&oid);
  2823. prime_cache_tree(r, r->index, tree);
  2824. if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
  2825. ret = error(_("could not write index"));
  2826. free((void *)desc.buffer);
  2827. if (!ret)
  2828. ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
  2829. len, name), "HEAD", &oid,
  2830. NULL, 0, UPDATE_REFS_MSG_ON_ERR);
  2831. strbuf_release(&ref_name);
  2832. return ret;
  2833. }
  2834. static struct commit *lookup_label(const char *label, int len,
  2835. struct strbuf *buf)
  2836. {
  2837. struct commit *commit;
  2838. strbuf_reset(buf);
  2839. strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
  2840. commit = lookup_commit_reference_by_name(buf->buf);
  2841. if (!commit) {
  2842. /* fall back to non-rewritten ref or commit */
  2843. strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
  2844. commit = lookup_commit_reference_by_name(buf->buf);
  2845. }
  2846. if (!commit)
  2847. error(_("could not resolve '%s'"), buf->buf);
  2848. return commit;
  2849. }
  2850. static int do_merge(struct repository *r,
  2851. struct commit *commit,
  2852. const char *arg, int arg_len,
  2853. int flags, struct replay_opts *opts)
  2854. {
  2855. int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
  2856. EDIT_MSG | VERIFY_MSG : 0;
  2857. struct strbuf ref_name = STRBUF_INIT;
  2858. struct commit *head_commit, *merge_commit, *i;
  2859. struct commit_list *bases, *j, *reversed = NULL;
  2860. struct commit_list *to_merge = NULL, **tail = &to_merge;
  2861. const char *strategy = !opts->xopts_nr &&
  2862. (!opts->strategy || !strcmp(opts->strategy, "recursive")) ?
  2863. NULL : opts->strategy;
  2864. struct merge_options o;
  2865. int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
  2866. static struct lock_file lock;
  2867. const char *p;
  2868. if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
  2869. ret = -1;
  2870. goto leave_merge;
  2871. }
  2872. head_commit = lookup_commit_reference_by_name("HEAD");
  2873. if (!head_commit) {
  2874. ret = error(_("cannot merge without a current revision"));
  2875. goto leave_merge;
  2876. }
  2877. /*
  2878. * For octopus merges, the arg starts with the list of revisions to be
  2879. * merged. The list is optionally followed by '#' and the oneline.
  2880. */
  2881. merge_arg_len = oneline_offset = arg_len;
  2882. for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
  2883. if (!*p)
  2884. break;
  2885. if (*p == '#' && (!p[1] || isspace(p[1]))) {
  2886. p += 1 + strspn(p + 1, " \t\n");
  2887. oneline_offset = p - arg;
  2888. break;
  2889. }
  2890. k = strcspn(p, " \t\n");
  2891. if (!k)
  2892. continue;
  2893. merge_commit = lookup_label(p, k, &ref_name);
  2894. if (!merge_commit) {
  2895. ret = error(_("unable to parse '%.*s'"), k, p);
  2896. goto leave_merge;
  2897. }
  2898. tail = &commit_list_insert(merge_commit, tail)->next;
  2899. p += k;
  2900. merge_arg_len = p - arg;
  2901. }
  2902. if (!to_merge) {
  2903. ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
  2904. goto leave_merge;
  2905. }
  2906. if (opts->have_squash_onto &&
  2907. oideq(&head_commit->object.oid, &opts->squash_onto)) {
  2908. /*
  2909. * When the user tells us to "merge" something into a
  2910. * "[new root]", let's simply fast-forward to the merge head.
  2911. */
  2912. rollback_lock_file(&lock);
  2913. if (to_merge->next)
  2914. ret = error(_("octopus merge cannot be executed on "
  2915. "top of a [new root]"));
  2916. else
  2917. ret = fast_forward_to(r, &to_merge->item->object.oid,
  2918. &head_commit->object.oid, 0,
  2919. opts);
  2920. goto leave_merge;
  2921. }
  2922. if (commit) {
  2923. const char *message = get_commit_buffer(commit, NULL);
  2924. const char *body;
  2925. int len;
  2926. if (!message) {
  2927. ret = error(_("could not get commit message of '%s'"),
  2928. oid_to_hex(&commit->object.oid));
  2929. goto leave_merge;
  2930. }
  2931. write_author_script(message);
  2932. find_commit_subject(message, &body);
  2933. len = strlen(body);
  2934. ret = write_message(body, len, git_path_merge_msg(r), 0);
  2935. unuse_commit_buffer(commit, message);
  2936. if (ret) {
  2937. error_errno(_("could not write '%s'"),
  2938. git_path_merge_msg(r));
  2939. goto leave_merge;
  2940. }
  2941. } else {
  2942. struct strbuf buf = STRBUF_INIT;
  2943. int len;
  2944. strbuf_addf(&buf, "author %s", git_author_info(0));
  2945. write_author_script(buf.buf);
  2946. strbuf_reset(&buf);
  2947. if (oneline_offset < arg_len) {
  2948. p = arg + oneline_offset;
  2949. len = arg_len - oneline_offset;
  2950. } else {
  2951. strbuf_addf(&buf, "Merge %s '%.*s'",
  2952. to_merge->next ? "branches" : "branch",
  2953. merge_arg_len, arg);
  2954. p = buf.buf;
  2955. len = buf.len;
  2956. }
  2957. ret = write_message(p, len, git_path_merge_msg(r), 0);
  2958. strbuf_release(&buf);
  2959. if (ret) {
  2960. error_errno(_("could not write '%s'"),
  2961. git_path_merge_msg(r));
  2962. goto leave_merge;
  2963. }
  2964. }
  2965. /*
  2966. * If HEAD is not identical to the first parent of the original merge
  2967. * commit, we cannot fast-forward.
  2968. */
  2969. can_fast_forward = opts->allow_ff && commit && commit->parents &&
  2970. oideq(&commit->parents->item->object.oid,
  2971. &head_commit->object.oid);
  2972. /*
  2973. * If any merge head is different from the original one, we cannot
  2974. * fast-forward.
  2975. */
  2976. if (can_fast_forward) {
  2977. struct commit_list *p = commit->parents->next;
  2978. for (j = to_merge; j && p; j = j->next, p = p->next)
  2979. if (!oideq(&j->item->object.oid,
  2980. &p->item->object.oid)) {
  2981. can_fast_forward = 0;
  2982. break;
  2983. }
  2984. /*
  2985. * If the number of merge heads differs from the original merge
  2986. * commit, we cannot fast-forward.
  2987. */
  2988. if (j || p)
  2989. can_fast_forward = 0;
  2990. }
  2991. if (can_fast_forward) {
  2992. rollback_lock_file(&lock);
  2993. ret = fast_forward_to(r, &commit->object.oid,
  2994. &head_commit->object.oid, 0, opts);
  2995. if (flags & TODO_EDIT_MERGE_MSG) {
  2996. run_commit_flags |= AMEND_MSG;
  2997. goto fast_forward_edit;
  2998. }
  2999. goto leave_merge;
  3000. }
  3001. if (strategy || to_merge->next) {
  3002. /* Octopus merge */
  3003. struct child_process cmd = CHILD_PROCESS_INIT;
  3004. if (read_env_script(&cmd.env_array)) {
  3005. const char *gpg_opt = gpg_sign_opt_quoted(opts);
  3006. ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
  3007. goto leave_merge;
  3008. }
  3009. cmd.git_cmd = 1;
  3010. argv_array_push(&cmd.args, "merge");
  3011. argv_array_push(&cmd.args, "-s");
  3012. if (!strategy)
  3013. argv_array_push(&cmd.args, "octopus");
  3014. else {
  3015. argv_array_push(&cmd.args, strategy);
  3016. for (k = 0; k < opts->xopts_nr; k++)
  3017. argv_array_pushf(&cmd.args,
  3018. "-X%s", opts->xopts[k]);
  3019. }
  3020. argv_array_push(&cmd.args, "--no-edit");
  3021. argv_array_push(&cmd.args, "--no-ff");
  3022. argv_array_push(&cmd.args, "--no-log");
  3023. argv_array_push(&cmd.args, "--no-stat");
  3024. argv_array_push(&cmd.args, "-F");
  3025. argv_array_push(&cmd.args, git_path_merge_msg(r));
  3026. if (opts->gpg_sign)
  3027. argv_array_push(&cmd.args, opts->gpg_sign);
  3028. /* Add the tips to be merged */
  3029. for (j = to_merge; j; j = j->next)
  3030. argv_array_push(&cmd.args,
  3031. oid_to_hex(&j->item->object.oid));
  3032. strbuf_release(&ref_name);
  3033. unlink(git_path_cherry_pick_head(r));
  3034. rollback_lock_file(&lock);
  3035. rollback_lock_file(&lock);
  3036. ret = run_command(&cmd);
  3037. /* force re-reading of the cache */
  3038. if (!ret && (discard_index(r->index) < 0 ||
  3039. repo_read_index(r) < 0))
  3040. ret = error(_("could not read index"));
  3041. goto leave_merge;
  3042. }
  3043. merge_commit = to_merge->item;
  3044. bases = get_merge_bases(head_commit, merge_commit);
  3045. if (bases && oideq(&merge_commit->object.oid,
  3046. &bases->item->object.oid)) {
  3047. ret = 0;
  3048. /* skip merging an ancestor of HEAD */
  3049. goto leave_merge;
  3050. }
  3051. write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
  3052. git_path_merge_head(r), 0);
  3053. write_message("no-ff", 5, git_path_merge_mode(r), 0);
  3054. for (j = bases; j; j = j->next)
  3055. commit_list_insert(j->item, &reversed);
  3056. free_commit_list(bases);
  3057. repo_read_index(r);
  3058. init_merge_options(&o, r);
  3059. o.branch1 = "HEAD";
  3060. o.branch2 = ref_name.buf;
  3061. o.buffer_output = 2;
  3062. ret = merge_recursive(&o, head_commit, merge_commit, reversed, &i);
  3063. if (ret <= 0)
  3064. fputs(o.obuf.buf, stdout);
  3065. strbuf_release(&o.obuf);
  3066. if (ret < 0) {
  3067. error(_("could not even attempt to merge '%.*s'"),
  3068. merge_arg_len, arg);
  3069. goto leave_merge;
  3070. }
  3071. /*
  3072. * The return value of merge_recursive() is 1 on clean, and 0 on
  3073. * unclean merge.
  3074. *
  3075. * Let's reverse that, so that do_merge() returns 0 upon success and
  3076. * 1 upon failed merge (keeping the return value -1 for the cases where
  3077. * we will want to reschedule the `merge` command).
  3078. */
  3079. ret = !ret;
  3080. if (r->index->cache_changed &&
  3081. write_locked_index(r->index, &lock, COMMIT_LOCK)) {
  3082. ret = error(_("merge: Unable to write new index file"));
  3083. goto leave_merge;
  3084. }
  3085. rollback_lock_file(&lock);
  3086. if (ret)
  3087. repo_rerere(r, opts->allow_rerere_auto);
  3088. else
  3089. /*
  3090. * In case of problems, we now want to return a positive
  3091. * value (a negative one would indicate that the `merge`
  3092. * command needs to be rescheduled).
  3093. */
  3094. fast_forward_edit:
  3095. ret = !!run_git_commit(r, git_path_merge_msg(r), opts,
  3096. run_commit_flags);
  3097. leave_merge:
  3098. strbuf_release(&ref_name);
  3099. rollback_lock_file(&lock);
  3100. free_commit_list(to_merge);
  3101. return ret;
  3102. }
  3103. static int is_final_fixup(struct todo_list *todo_list)
  3104. {
  3105. int i = todo_list->current;
  3106. if (!is_fixup(todo_list->items[i].command))
  3107. return 0;
  3108. while (++i < todo_list->nr)
  3109. if (is_fixup(todo_list->items[i].command))
  3110. return 0;
  3111. else if (!is_noop(todo_list->items[i].command))
  3112. break;
  3113. return 1;
  3114. }
  3115. static enum todo_command peek_command(struct todo_list *todo_list, int offset)
  3116. {
  3117. int i;
  3118. for (i = todo_list->current + offset; i < todo_list->nr; i++)
  3119. if (!is_noop(todo_list->items[i].command))
  3120. return todo_list->items[i].command;
  3121. return -1;
  3122. }
  3123. static int apply_autostash(struct replay_opts *opts)
  3124. {
  3125. struct strbuf stash_sha1 = STRBUF_INIT;
  3126. struct child_process child = CHILD_PROCESS_INIT;
  3127. int ret = 0;
  3128. if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
  3129. strbuf_release(&stash_sha1);
  3130. return 0;
  3131. }
  3132. strbuf_trim(&stash_sha1);
  3133. child.git_cmd = 1;
  3134. child.no_stdout = 1;
  3135. child.no_stderr = 1;
  3136. argv_array_push(&child.args, "stash");
  3137. argv_array_push(&child.args, "apply");
  3138. argv_array_push(&child.args, stash_sha1.buf);
  3139. if (!run_command(&child))
  3140. fprintf(stderr, _("Applied autostash.\n"));
  3141. else {
  3142. struct child_process store = CHILD_PROCESS_INIT;
  3143. store.git_cmd = 1;
  3144. argv_array_push(&store.args, "stash");
  3145. argv_array_push(&store.args, "store");
  3146. argv_array_push(&store.args, "-m");
  3147. argv_array_push(&store.args, "autostash");
  3148. argv_array_push(&store.args, "-q");
  3149. argv_array_push(&store.args, stash_sha1.buf);
  3150. if (run_command(&store))
  3151. ret = error(_("cannot store %s"), stash_sha1.buf);
  3152. else
  3153. fprintf(stderr,
  3154. _("Applying autostash resulted in conflicts.\n"
  3155. "Your changes are safe in the stash.\n"
  3156. "You can run \"git stash pop\" or"
  3157. " \"git stash drop\" at any time.\n"));
  3158. }
  3159. strbuf_release(&stash_sha1);
  3160. return ret;
  3161. }
  3162. static const char *reflog_message(struct replay_opts *opts,
  3163. const char *sub_action, const char *fmt, ...)
  3164. {
  3165. va_list ap;
  3166. static struct strbuf buf = STRBUF_INIT;
  3167. va_start(ap, fmt);
  3168. strbuf_reset(&buf);
  3169. strbuf_addstr(&buf, action_name(opts));
  3170. if (sub_action)
  3171. strbuf_addf(&buf, " (%s)", sub_action);
  3172. if (fmt) {
  3173. strbuf_addstr(&buf, ": ");
  3174. strbuf_vaddf(&buf, fmt, ap);
  3175. }
  3176. va_end(ap);
  3177. return buf.buf;
  3178. }
  3179. static int run_git_checkout(struct repository *r, struct replay_opts *opts,
  3180. const char *commit, const char *action)
  3181. {
  3182. struct child_process cmd = CHILD_PROCESS_INIT;
  3183. int ret;
  3184. cmd.git_cmd = 1;
  3185. argv_array_push(&cmd.args, "checkout");
  3186. argv_array_push(&cmd.args, commit);
  3187. argv_array_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
  3188. if (opts->verbose)
  3189. ret = run_command(&cmd);
  3190. else
  3191. ret = run_command_silent_on_success(&cmd);
  3192. if (!ret)
  3193. discard_index(r->index);
  3194. return ret;
  3195. }
  3196. int prepare_branch_to_be_rebased(struct repository *r, struct replay_opts *opts,
  3197. const char *commit)
  3198. {
  3199. const char *action;
  3200. if (commit && *commit) {
  3201. action = reflog_message(opts, "start", "checkout %s", commit);
  3202. if (run_git_checkout(r, opts, commit, action))
  3203. return error(_("could not checkout %s"), commit);
  3204. }
  3205. return 0;
  3206. }
  3207. static int checkout_onto(struct repository *r, struct replay_opts *opts,
  3208. const char *onto_name, const struct object_id *onto,
  3209. const char *orig_head)
  3210. {
  3211. struct object_id oid;
  3212. const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
  3213. if (get_oid(orig_head, &oid))
  3214. return error(_("%s: not a valid OID"), orig_head);
  3215. if (run_git_checkout(r, opts, oid_to_hex(onto), action)) {
  3216. apply_autostash(opts);
  3217. sequencer_remove_state(opts);
  3218. return error(_("could not detach HEAD"));
  3219. }
  3220. return update_ref(NULL, "ORIG_HEAD", &oid, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
  3221. }
  3222. static int stopped_at_head(struct repository *r)
  3223. {
  3224. struct object_id head;
  3225. struct commit *commit;
  3226. struct commit_message message;
  3227. if (get_oid("HEAD", &head) ||
  3228. !(commit = lookup_commit(r, &head)) ||
  3229. parse_commit(commit) || get_message(commit, &message))
  3230. fprintf(stderr, _("Stopped at HEAD\n"));
  3231. else {
  3232. fprintf(stderr, _("Stopped at %s\n"), message.label);
  3233. free_message(commit, &message);
  3234. }
  3235. return 0;
  3236. }
  3237. static const char rescheduled_advice[] =
  3238. N_("Could not execute the todo command\n"
  3239. "\n"
  3240. " %.*s"
  3241. "\n"
  3242. "It has been rescheduled; To edit the command before continuing, please\n"
  3243. "edit the todo list first:\n"
  3244. "\n"
  3245. " git rebase --edit-todo\n"
  3246. " git rebase --continue\n");
  3247. static int pick_commits(struct repository *r,
  3248. struct todo_list *todo_list,
  3249. struct replay_opts *opts)
  3250. {
  3251. int res = 0, reschedule = 0;
  3252. setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
  3253. if (opts->allow_ff)
  3254. assert(!(opts->signoff || opts->no_commit ||
  3255. opts->record_origin || opts->edit));
  3256. if (read_and_refresh_cache(r, opts))
  3257. return -1;
  3258. while (todo_list->current < todo_list->nr) {
  3259. struct todo_item *item = todo_list->items + todo_list->current;
  3260. const char *arg = todo_item_get_arg(todo_list, item);
  3261. int check_todo = 0;
  3262. if (save_todo(todo_list, opts))
  3263. return -1;
  3264. if (is_rebase_i(opts)) {
  3265. if (item->command != TODO_COMMENT) {
  3266. FILE *f = fopen(rebase_path_msgnum(), "w");
  3267. todo_list->done_nr++;
  3268. if (f) {
  3269. fprintf(f, "%d\n", todo_list->done_nr);
  3270. fclose(f);
  3271. }
  3272. if (!opts->quiet)
  3273. fprintf(stderr, "Rebasing (%d/%d)%s",
  3274. todo_list->done_nr,
  3275. todo_list->total_nr,
  3276. opts->verbose ? "\n" : "\r");
  3277. }
  3278. unlink(rebase_path_message());
  3279. unlink(rebase_path_author_script());
  3280. unlink(rebase_path_stopped_sha());
  3281. unlink(rebase_path_amend());
  3282. unlink(git_path_merge_head(r));
  3283. delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
  3284. if (item->command == TODO_BREAK) {
  3285. if (!opts->verbose)
  3286. term_clear_line();
  3287. return stopped_at_head(r);
  3288. }
  3289. }
  3290. if (item->command <= TODO_SQUASH) {
  3291. if (is_rebase_i(opts))
  3292. setenv("GIT_REFLOG_ACTION", reflog_message(opts,
  3293. command_to_string(item->command), NULL),
  3294. 1);
  3295. res = do_pick_commit(r, item->command, item->commit,
  3296. opts, is_final_fixup(todo_list),
  3297. &check_todo);
  3298. if (is_rebase_i(opts) && res < 0) {
  3299. /* Reschedule */
  3300. advise(_(rescheduled_advice),
  3301. get_item_line_length(todo_list,
  3302. todo_list->current),
  3303. get_item_line(todo_list,
  3304. todo_list->current));
  3305. todo_list->current--;
  3306. if (save_todo(todo_list, opts))
  3307. return -1;
  3308. }
  3309. if (item->command == TODO_EDIT) {
  3310. struct commit *commit = item->commit;
  3311. if (!res) {
  3312. if (!opts->verbose)
  3313. term_clear_line();
  3314. fprintf(stderr,
  3315. _("Stopped at %s... %.*s\n"),
  3316. short_commit_name(commit),
  3317. item->arg_len, arg);
  3318. }
  3319. return error_with_patch(r, commit,
  3320. arg, item->arg_len, opts, res, !res);
  3321. }
  3322. if (is_rebase_i(opts) && !res)
  3323. record_in_rewritten(&item->commit->object.oid,
  3324. peek_command(todo_list, 1));
  3325. if (res && is_fixup(item->command)) {
  3326. if (res == 1)
  3327. intend_to_amend();
  3328. return error_failed_squash(r, item->commit, opts,
  3329. item->arg_len, arg);
  3330. } else if (res && is_rebase_i(opts) && item->commit) {
  3331. int to_amend = 0;
  3332. struct object_id oid;
  3333. /*
  3334. * If we are rewording and have either
  3335. * fast-forwarded already, or are about to
  3336. * create a new root commit, we want to amend,
  3337. * otherwise we do not.
  3338. */
  3339. if (item->command == TODO_REWORD &&
  3340. !get_oid("HEAD", &oid) &&
  3341. (oideq(&item->commit->object.oid, &oid) ||
  3342. (opts->have_squash_onto &&
  3343. oideq(&opts->squash_onto, &oid))))
  3344. to_amend = 1;
  3345. return res | error_with_patch(r, item->commit,
  3346. arg, item->arg_len, opts,
  3347. res, to_amend);
  3348. }
  3349. } else if (item->command == TODO_EXEC) {
  3350. char *end_of_arg = (char *)(arg + item->arg_len);
  3351. int saved = *end_of_arg;
  3352. if (!opts->verbose)
  3353. term_clear_line();
  3354. *end_of_arg = '\0';
  3355. res = do_exec(r, arg);
  3356. *end_of_arg = saved;
  3357. if (res) {
  3358. if (opts->reschedule_failed_exec)
  3359. reschedule = 1;
  3360. }
  3361. check_todo = 1;
  3362. } else if (item->command == TODO_LABEL) {
  3363. if ((res = do_label(r, arg, item->arg_len)))
  3364. reschedule = 1;
  3365. } else if (item->command == TODO_RESET) {
  3366. if ((res = do_reset(r, arg, item->arg_len, opts)))
  3367. reschedule = 1;
  3368. } else if (item->command == TODO_MERGE) {
  3369. if ((res = do_merge(r, item->commit,
  3370. arg, item->arg_len,
  3371. item->flags, opts)) < 0)
  3372. reschedule = 1;
  3373. else if (item->commit)
  3374. record_in_rewritten(&item->commit->object.oid,
  3375. peek_command(todo_list, 1));
  3376. if (res > 0)
  3377. /* failed with merge conflicts */
  3378. return error_with_patch(r, item->commit,
  3379. arg, item->arg_len,
  3380. opts, res, 0);
  3381. } else if (!is_noop(item->command))
  3382. return error(_("unknown command %d"), item->command);
  3383. if (reschedule) {
  3384. advise(_(rescheduled_advice),
  3385. get_item_line_length(todo_list,
  3386. todo_list->current),
  3387. get_item_line(todo_list, todo_list->current));
  3388. todo_list->current--;
  3389. if (save_todo(todo_list, opts))
  3390. return -1;
  3391. if (item->commit)
  3392. return error_with_patch(r,
  3393. item->commit,
  3394. arg, item->arg_len,
  3395. opts, res, 0);
  3396. } else if (check_todo && !res) {
  3397. struct stat st;
  3398. if (stat(get_todo_path(opts), &st)) {
  3399. res = error_errno(_("could not stat '%s'"),
  3400. get_todo_path(opts));
  3401. } else if (match_stat_data(&todo_list->stat, &st)) {
  3402. /* Reread the todo file if it has changed. */
  3403. todo_list_release(todo_list);
  3404. if (read_populate_todo(r, todo_list, opts))
  3405. res = -1; /* message was printed */
  3406. /* `current` will be incremented below */
  3407. todo_list->current = -1;
  3408. }
  3409. }
  3410. todo_list->current++;
  3411. if (res)
  3412. return res;
  3413. }
  3414. if (is_rebase_i(opts)) {
  3415. struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
  3416. struct stat st;
  3417. /* Stopped in the middle, as planned? */
  3418. if (todo_list->current < todo_list->nr)
  3419. return 0;
  3420. if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
  3421. starts_with(head_ref.buf, "refs/")) {
  3422. const char *msg;
  3423. struct object_id head, orig;
  3424. int res;
  3425. if (get_oid("HEAD", &head)) {
  3426. res = error(_("cannot read HEAD"));
  3427. cleanup_head_ref:
  3428. strbuf_release(&head_ref);
  3429. strbuf_release(&buf);
  3430. return res;
  3431. }
  3432. if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
  3433. get_oid_hex(buf.buf, &orig)) {
  3434. res = error(_("could not read orig-head"));
  3435. goto cleanup_head_ref;
  3436. }
  3437. strbuf_reset(&buf);
  3438. if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
  3439. res = error(_("could not read 'onto'"));
  3440. goto cleanup_head_ref;
  3441. }
  3442. msg = reflog_message(opts, "finish", "%s onto %s",
  3443. head_ref.buf, buf.buf);
  3444. if (update_ref(msg, head_ref.buf, &head, &orig,
  3445. REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
  3446. res = error(_("could not update %s"),
  3447. head_ref.buf);
  3448. goto cleanup_head_ref;
  3449. }
  3450. msg = reflog_message(opts, "finish", "returning to %s",
  3451. head_ref.buf);
  3452. if (create_symref("HEAD", head_ref.buf, msg)) {
  3453. res = error(_("could not update HEAD to %s"),
  3454. head_ref.buf);
  3455. goto cleanup_head_ref;
  3456. }
  3457. strbuf_reset(&buf);
  3458. }
  3459. if (opts->verbose) {
  3460. struct rev_info log_tree_opt;
  3461. struct object_id orig, head;
  3462. memset(&log_tree_opt, 0, sizeof(log_tree_opt));
  3463. repo_init_revisions(r, &log_tree_opt, NULL);
  3464. log_tree_opt.diff = 1;
  3465. log_tree_opt.diffopt.output_format =
  3466. DIFF_FORMAT_DIFFSTAT;
  3467. log_tree_opt.disable_stdin = 1;
  3468. if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
  3469. !get_oid(buf.buf, &orig) &&
  3470. !get_oid("HEAD", &head)) {
  3471. diff_tree_oid(&orig, &head, "",
  3472. &log_tree_opt.diffopt);
  3473. log_tree_diff_flush(&log_tree_opt);
  3474. }
  3475. }
  3476. flush_rewritten_pending();
  3477. if (!stat(rebase_path_rewritten_list(), &st) &&
  3478. st.st_size > 0) {
  3479. struct child_process child = CHILD_PROCESS_INIT;
  3480. const char *post_rewrite_hook =
  3481. find_hook("post-rewrite");
  3482. child.in = open(rebase_path_rewritten_list(), O_RDONLY);
  3483. child.git_cmd = 1;
  3484. argv_array_push(&child.args, "notes");
  3485. argv_array_push(&child.args, "copy");
  3486. argv_array_push(&child.args, "--for-rewrite=rebase");
  3487. /* we don't care if this copying failed */
  3488. run_command(&child);
  3489. if (post_rewrite_hook) {
  3490. struct child_process hook = CHILD_PROCESS_INIT;
  3491. hook.in = open(rebase_path_rewritten_list(),
  3492. O_RDONLY);
  3493. hook.stdout_to_stderr = 1;
  3494. hook.trace2_hook_name = "post-rewrite";
  3495. argv_array_push(&hook.args, post_rewrite_hook);
  3496. argv_array_push(&hook.args, "rebase");
  3497. /* we don't care if this hook failed */
  3498. run_command(&hook);
  3499. }
  3500. }
  3501. apply_autostash(opts);
  3502. if (!opts->quiet) {
  3503. if (!opts->verbose)
  3504. term_clear_line();
  3505. fprintf(stderr,
  3506. "Successfully rebased and updated %s.\n",
  3507. head_ref.buf);
  3508. }
  3509. strbuf_release(&buf);
  3510. strbuf_release(&head_ref);
  3511. }
  3512. /*
  3513. * Sequence of picks finished successfully; cleanup by
  3514. * removing the .git/sequencer directory
  3515. */
  3516. return sequencer_remove_state(opts);
  3517. }
  3518. static int continue_single_pick(struct repository *r)
  3519. {
  3520. const char *argv[] = { "commit", NULL };
  3521. if (!file_exists(git_path_cherry_pick_head(r)) &&
  3522. !file_exists(git_path_revert_head(r)))
  3523. return error(_("no cherry-pick or revert in progress"));
  3524. return run_command_v_opt(argv, RUN_GIT_CMD);
  3525. }
  3526. static int commit_staged_changes(struct repository *r,
  3527. struct replay_opts *opts,
  3528. struct todo_list *todo_list)
  3529. {
  3530. unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
  3531. unsigned int final_fixup = 0, is_clean;
  3532. if (has_unstaged_changes(r, 1))
  3533. return error(_("cannot rebase: You have unstaged changes."));
  3534. is_clean = !has_uncommitted_changes(r, 0);
  3535. if (file_exists(rebase_path_amend())) {
  3536. struct strbuf rev = STRBUF_INIT;
  3537. struct object_id head, to_amend;
  3538. if (get_oid("HEAD", &head))
  3539. return error(_("cannot amend non-existing commit"));
  3540. if (!read_oneliner(&rev, rebase_path_amend(), 0))
  3541. return error(_("invalid file: '%s'"), rebase_path_amend());
  3542. if (get_oid_hex(rev.buf, &to_amend))
  3543. return error(_("invalid contents: '%s'"),
  3544. rebase_path_amend());
  3545. if (!is_clean && !oideq(&head, &to_amend))
  3546. return error(_("\nYou have uncommitted changes in your "
  3547. "working tree. Please, commit them\n"
  3548. "first and then run 'git rebase "
  3549. "--continue' again."));
  3550. /*
  3551. * When skipping a failed fixup/squash, we need to edit the
  3552. * commit message, the current fixup list and count, and if it
  3553. * was the last fixup/squash in the chain, we need to clean up
  3554. * the commit message and if there was a squash, let the user
  3555. * edit it.
  3556. */
  3557. if (!is_clean || !opts->current_fixup_count)
  3558. ; /* this is not the final fixup */
  3559. else if (!oideq(&head, &to_amend) ||
  3560. !file_exists(rebase_path_stopped_sha())) {
  3561. /* was a final fixup or squash done manually? */
  3562. if (!is_fixup(peek_command(todo_list, 0))) {
  3563. unlink(rebase_path_fixup_msg());
  3564. unlink(rebase_path_squash_msg());
  3565. unlink(rebase_path_current_fixups());
  3566. strbuf_reset(&opts->current_fixups);
  3567. opts->current_fixup_count = 0;
  3568. }
  3569. } else {
  3570. /* we are in a fixup/squash chain */
  3571. const char *p = opts->current_fixups.buf;
  3572. int len = opts->current_fixups.len;
  3573. opts->current_fixup_count--;
  3574. if (!len)
  3575. BUG("Incorrect current_fixups:\n%s", p);
  3576. while (len && p[len - 1] != '\n')
  3577. len--;
  3578. strbuf_setlen(&opts->current_fixups, len);
  3579. if (write_message(p, len, rebase_path_current_fixups(),
  3580. 0) < 0)
  3581. return error(_("could not write file: '%s'"),
  3582. rebase_path_current_fixups());
  3583. /*
  3584. * If a fixup/squash in a fixup/squash chain failed, the
  3585. * commit message is already correct, no need to commit
  3586. * it again.
  3587. *
  3588. * Only if it is the final command in the fixup/squash
  3589. * chain, and only if the chain is longer than a single
  3590. * fixup/squash command (which was just skipped), do we
  3591. * actually need to re-commit with a cleaned up commit
  3592. * message.
  3593. */
  3594. if (opts->current_fixup_count > 0 &&
  3595. !is_fixup(peek_command(todo_list, 0))) {
  3596. final_fixup = 1;
  3597. /*
  3598. * If there was not a single "squash" in the
  3599. * chain, we only need to clean up the commit
  3600. * message, no need to bother the user with
  3601. * opening the commit message in the editor.
  3602. */
  3603. if (!starts_with(p, "squash ") &&
  3604. !strstr(p, "\nsquash "))
  3605. flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
  3606. } else if (is_fixup(peek_command(todo_list, 0))) {
  3607. /*
  3608. * We need to update the squash message to skip
  3609. * the latest commit message.
  3610. */
  3611. struct commit *commit;
  3612. const char *path = rebase_path_squash_msg();
  3613. if (parse_head(r, &commit) ||
  3614. !(p = get_commit_buffer(commit, NULL)) ||
  3615. write_message(p, strlen(p), path, 0)) {
  3616. unuse_commit_buffer(commit, p);
  3617. return error(_("could not write file: "
  3618. "'%s'"), path);
  3619. }
  3620. unuse_commit_buffer(commit, p);
  3621. }
  3622. }
  3623. strbuf_release(&rev);
  3624. flags |= AMEND_MSG;
  3625. }
  3626. if (is_clean) {
  3627. const char *cherry_pick_head = git_path_cherry_pick_head(r);
  3628. if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
  3629. return error(_("could not remove CHERRY_PICK_HEAD"));
  3630. if (!final_fixup)
  3631. return 0;
  3632. }
  3633. if (run_git_commit(r, final_fixup ? NULL : rebase_path_message(),
  3634. opts, flags))
  3635. return error(_("could not commit staged changes."));
  3636. unlink(rebase_path_amend());
  3637. unlink(git_path_merge_head(r));
  3638. if (final_fixup) {
  3639. unlink(rebase_path_fixup_msg());
  3640. unlink(rebase_path_squash_msg());
  3641. }
  3642. if (opts->current_fixup_count > 0) {
  3643. /*
  3644. * Whether final fixup or not, we just cleaned up the commit
  3645. * message...
  3646. */
  3647. unlink(rebase_path_current_fixups());
  3648. strbuf_reset(&opts->current_fixups);
  3649. opts->current_fixup_count = 0;
  3650. }
  3651. return 0;
  3652. }
  3653. int sequencer_continue(struct repository *r, struct replay_opts *opts)
  3654. {
  3655. struct todo_list todo_list = TODO_LIST_INIT;
  3656. int res;
  3657. if (read_and_refresh_cache(r, opts))
  3658. return -1;
  3659. if (read_populate_opts(opts))
  3660. return -1;
  3661. if (is_rebase_i(opts)) {
  3662. if ((res = read_populate_todo(r, &todo_list, opts)))
  3663. goto release_todo_list;
  3664. if (commit_staged_changes(r, opts, &todo_list))
  3665. return -1;
  3666. } else if (!file_exists(get_todo_path(opts)))
  3667. return continue_single_pick(r);
  3668. else if ((res = read_populate_todo(r, &todo_list, opts)))
  3669. goto release_todo_list;
  3670. if (!is_rebase_i(opts)) {
  3671. /* Verify that the conflict has been resolved */
  3672. if (file_exists(git_path_cherry_pick_head(r)) ||
  3673. file_exists(git_path_revert_head(r))) {
  3674. res = continue_single_pick(r);
  3675. if (res)
  3676. goto release_todo_list;
  3677. }
  3678. if (index_differs_from(r, "HEAD", NULL, 0)) {
  3679. res = error_dirty_index(r, opts);
  3680. goto release_todo_list;
  3681. }
  3682. todo_list.current++;
  3683. } else if (file_exists(rebase_path_stopped_sha())) {
  3684. struct strbuf buf = STRBUF_INIT;
  3685. struct object_id oid;
  3686. if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
  3687. !get_oid_committish(buf.buf, &oid))
  3688. record_in_rewritten(&oid, peek_command(&todo_list, 0));
  3689. strbuf_release(&buf);
  3690. }
  3691. res = pick_commits(r, &todo_list, opts);
  3692. release_todo_list:
  3693. todo_list_release(&todo_list);
  3694. return res;
  3695. }
  3696. static int single_pick(struct repository *r,
  3697. struct commit *cmit,
  3698. struct replay_opts *opts)
  3699. {
  3700. int check_todo;
  3701. setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
  3702. return do_pick_commit(r, opts->action == REPLAY_PICK ?
  3703. TODO_PICK : TODO_REVERT, cmit, opts, 0,
  3704. &check_todo);
  3705. }
  3706. int sequencer_pick_revisions(struct repository *r,
  3707. struct replay_opts *opts)
  3708. {
  3709. struct todo_list todo_list = TODO_LIST_INIT;
  3710. struct object_id oid;
  3711. int i, res;
  3712. assert(opts->revs);
  3713. if (read_and_refresh_cache(r, opts))
  3714. return -1;
  3715. for (i = 0; i < opts->revs->pending.nr; i++) {
  3716. struct object_id oid;
  3717. const char *name = opts->revs->pending.objects[i].name;
  3718. /* This happens when using --stdin. */
  3719. if (!strlen(name))
  3720. continue;
  3721. if (!get_oid(name, &oid)) {
  3722. if (!lookup_commit_reference_gently(r, &oid, 1)) {
  3723. enum object_type type = oid_object_info(r,
  3724. &oid,
  3725. NULL);
  3726. return error(_("%s: can't cherry-pick a %s"),
  3727. name, type_name(type));
  3728. }
  3729. } else
  3730. return error(_("%s: bad revision"), name);
  3731. }
  3732. /*
  3733. * If we were called as "git cherry-pick <commit>", just
  3734. * cherry-pick/revert it, set CHERRY_PICK_HEAD /
  3735. * REVERT_HEAD, and don't touch the sequencer state.
  3736. * This means it is possible to cherry-pick in the middle
  3737. * of a cherry-pick sequence.
  3738. */
  3739. if (opts->revs->cmdline.nr == 1 &&
  3740. opts->revs->cmdline.rev->whence == REV_CMD_REV &&
  3741. opts->revs->no_walk &&
  3742. !opts->revs->cmdline.rev->flags) {
  3743. struct commit *cmit;
  3744. if (prepare_revision_walk(opts->revs))
  3745. return error(_("revision walk setup failed"));
  3746. cmit = get_revision(opts->revs);
  3747. if (!cmit)
  3748. return error(_("empty commit set passed"));
  3749. if (get_revision(opts->revs))
  3750. BUG("unexpected extra commit from walk");
  3751. return single_pick(r, cmit, opts);
  3752. }
  3753. /*
  3754. * Start a new cherry-pick/ revert sequence; but
  3755. * first, make sure that an existing one isn't in
  3756. * progress
  3757. */
  3758. if (walk_revs_populate_todo(&todo_list, opts) ||
  3759. create_seq_dir(r) < 0)
  3760. return -1;
  3761. if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
  3762. return error(_("can't revert as initial commit"));
  3763. if (save_head(oid_to_hex(&oid)))
  3764. return -1;
  3765. if (save_opts(opts))
  3766. return -1;
  3767. update_abort_safety_file();
  3768. res = pick_commits(r, &todo_list, opts);
  3769. todo_list_release(&todo_list);
  3770. return res;
  3771. }
  3772. void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
  3773. {
  3774. unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
  3775. struct strbuf sob = STRBUF_INIT;
  3776. int has_footer;
  3777. strbuf_addstr(&sob, sign_off_header);
  3778. strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
  3779. strbuf_addch(&sob, '\n');
  3780. if (!ignore_footer)
  3781. strbuf_complete_line(msgbuf);
  3782. /*
  3783. * If the whole message buffer is equal to the sob, pretend that we
  3784. * found a conforming footer with a matching sob
  3785. */
  3786. if (msgbuf->len - ignore_footer == sob.len &&
  3787. !strncmp(msgbuf->buf, sob.buf, sob.len))
  3788. has_footer = 3;
  3789. else
  3790. has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
  3791. if (!has_footer) {
  3792. const char *append_newlines = NULL;
  3793. size_t len = msgbuf->len - ignore_footer;
  3794. if (!len) {
  3795. /*
  3796. * The buffer is completely empty. Leave foom for
  3797. * the title and body to be filled in by the user.
  3798. */
  3799. append_newlines = "\n\n";
  3800. } else if (len == 1) {
  3801. /*
  3802. * Buffer contains a single newline. Add another
  3803. * so that we leave room for the title and body.
  3804. */
  3805. append_newlines = "\n";
  3806. } else if (msgbuf->buf[len - 2] != '\n') {
  3807. /*
  3808. * Buffer ends with a single newline. Add another
  3809. * so that there is an empty line between the message
  3810. * body and the sob.
  3811. */
  3812. append_newlines = "\n";
  3813. } /* else, the buffer already ends with two newlines. */
  3814. if (append_newlines)
  3815. strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
  3816. append_newlines, strlen(append_newlines));
  3817. }
  3818. if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
  3819. strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
  3820. sob.buf, sob.len);
  3821. strbuf_release(&sob);
  3822. }
  3823. struct labels_entry {
  3824. struct hashmap_entry entry;
  3825. char label[FLEX_ARRAY];
  3826. };
  3827. static int labels_cmp(const void *fndata, const struct hashmap_entry *eptr,
  3828. const struct hashmap_entry *entry_or_key, const void *key)
  3829. {
  3830. const struct labels_entry *a, *b;
  3831. a = container_of(eptr, const struct labels_entry, entry);
  3832. b = container_of(entry_or_key, const struct labels_entry, entry);
  3833. return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
  3834. }
  3835. struct string_entry {
  3836. struct oidmap_entry entry;
  3837. char string[FLEX_ARRAY];
  3838. };
  3839. struct label_state {
  3840. struct oidmap commit2label;
  3841. struct hashmap labels;
  3842. struct strbuf buf;
  3843. };
  3844. static const char *label_oid(struct object_id *oid, const char *label,
  3845. struct label_state *state)
  3846. {
  3847. struct labels_entry *labels_entry;
  3848. struct string_entry *string_entry;
  3849. struct object_id dummy;
  3850. size_t len;
  3851. int i;
  3852. string_entry = oidmap_get(&state->commit2label, oid);
  3853. if (string_entry)
  3854. return string_entry->string;
  3855. /*
  3856. * For "uninteresting" commits, i.e. commits that are not to be
  3857. * rebased, and which can therefore not be labeled, we use a unique
  3858. * abbreviation of the commit name. This is slightly more complicated
  3859. * than calling find_unique_abbrev() because we also need to make
  3860. * sure that the abbreviation does not conflict with any other
  3861. * label.
  3862. *
  3863. * We disallow "interesting" commits to be labeled by a string that
  3864. * is a valid full-length hash, to ensure that we always can find an
  3865. * abbreviation for any uninteresting commit's names that does not
  3866. * clash with any other label.
  3867. */
  3868. if (!label) {
  3869. char *p;
  3870. strbuf_reset(&state->buf);
  3871. strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
  3872. label = p = state->buf.buf;
  3873. find_unique_abbrev_r(p, oid, default_abbrev);
  3874. /*
  3875. * We may need to extend the abbreviated hash so that there is
  3876. * no conflicting label.
  3877. */
  3878. if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
  3879. size_t i = strlen(p) + 1;
  3880. oid_to_hex_r(p, oid);
  3881. for (; i < the_hash_algo->hexsz; i++) {
  3882. char save = p[i];
  3883. p[i] = '\0';
  3884. if (!hashmap_get_from_hash(&state->labels,
  3885. strihash(p), p))
  3886. break;
  3887. p[i] = save;
  3888. }
  3889. }
  3890. } else if (((len = strlen(label)) == the_hash_algo->hexsz &&
  3891. !get_oid_hex(label, &dummy)) ||
  3892. (len == 1 && *label == '#') ||
  3893. hashmap_get_from_hash(&state->labels,
  3894. strihash(label), label)) {
  3895. /*
  3896. * If the label already exists, or if the label is a valid full
  3897. * OID, or the label is a '#' (which we use as a separator
  3898. * between merge heads and oneline), we append a dash and a
  3899. * number to make it unique.
  3900. */
  3901. struct strbuf *buf = &state->buf;
  3902. strbuf_reset(buf);
  3903. strbuf_add(buf, label, len);
  3904. for (i = 2; ; i++) {
  3905. strbuf_setlen(buf, len);
  3906. strbuf_addf(buf, "-%d", i);
  3907. if (!hashmap_get_from_hash(&state->labels,
  3908. strihash(buf->buf),
  3909. buf->buf))
  3910. break;
  3911. }
  3912. label = buf->buf;
  3913. }
  3914. FLEX_ALLOC_STR(labels_entry, label, label);
  3915. hashmap_entry_init(&labels_entry->entry, strihash(label));
  3916. hashmap_add(&state->labels, &labels_entry->entry);
  3917. FLEX_ALLOC_STR(string_entry, string, label);
  3918. oidcpy(&string_entry->entry.oid, oid);
  3919. oidmap_put(&state->commit2label, string_entry);
  3920. return string_entry->string;
  3921. }
  3922. static int make_script_with_merges(struct pretty_print_context *pp,
  3923. struct rev_info *revs, struct strbuf *out,
  3924. unsigned flags)
  3925. {
  3926. int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
  3927. int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
  3928. int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
  3929. struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
  3930. struct strbuf label = STRBUF_INIT;
  3931. struct commit_list *commits = NULL, **tail = &commits, *iter;
  3932. struct commit_list *tips = NULL, **tips_tail = &tips;
  3933. struct commit *commit;
  3934. struct oidmap commit2todo = OIDMAP_INIT;
  3935. struct string_entry *entry;
  3936. struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
  3937. shown = OIDSET_INIT;
  3938. struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
  3939. int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
  3940. const char *cmd_pick = abbr ? "p" : "pick",
  3941. *cmd_label = abbr ? "l" : "label",
  3942. *cmd_reset = abbr ? "t" : "reset",
  3943. *cmd_merge = abbr ? "m" : "merge";
  3944. oidmap_init(&commit2todo, 0);
  3945. oidmap_init(&state.commit2label, 0);
  3946. hashmap_init(&state.labels, labels_cmp, NULL, 0);
  3947. strbuf_init(&state.buf, 32);
  3948. if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
  3949. struct object_id *oid = &revs->cmdline.rev[0].item->oid;
  3950. FLEX_ALLOC_STR(entry, string, "onto");
  3951. oidcpy(&entry->entry.oid, oid);
  3952. oidmap_put(&state.commit2label, entry);
  3953. }
  3954. /*
  3955. * First phase:
  3956. * - get onelines for all commits
  3957. * - gather all branch tips (i.e. 2nd or later parents of merges)
  3958. * - label all branch tips
  3959. */
  3960. while ((commit = get_revision(revs))) {
  3961. struct commit_list *to_merge;
  3962. const char *p1, *p2;
  3963. struct object_id *oid;
  3964. int is_empty;
  3965. tail = &commit_list_insert(commit, tail)->next;
  3966. oidset_insert(&interesting, &commit->object.oid);
  3967. is_empty = is_original_commit_empty(commit);
  3968. if (!is_empty && (commit->object.flags & PATCHSAME))
  3969. continue;
  3970. strbuf_reset(&oneline);
  3971. pretty_print_commit(pp, commit, &oneline);
  3972. to_merge = commit->parents ? commit->parents->next : NULL;
  3973. if (!to_merge) {
  3974. /* non-merge commit: easy case */
  3975. strbuf_reset(&buf);
  3976. if (!keep_empty && is_empty)
  3977. strbuf_addf(&buf, "%c ", comment_line_char);
  3978. strbuf_addf(&buf, "%s %s %s", cmd_pick,
  3979. oid_to_hex(&commit->object.oid),
  3980. oneline.buf);
  3981. FLEX_ALLOC_STR(entry, string, buf.buf);
  3982. oidcpy(&entry->entry.oid, &commit->object.oid);
  3983. oidmap_put(&commit2todo, entry);
  3984. continue;
  3985. }
  3986. /* Create a label */
  3987. strbuf_reset(&label);
  3988. if (skip_prefix(oneline.buf, "Merge ", &p1) &&
  3989. (p1 = strchr(p1, '\'')) &&
  3990. (p2 = strchr(++p1, '\'')))
  3991. strbuf_add(&label, p1, p2 - p1);
  3992. else if (skip_prefix(oneline.buf, "Merge pull request ",
  3993. &p1) &&
  3994. (p1 = strstr(p1, " from ")))
  3995. strbuf_addstr(&label, p1 + strlen(" from "));
  3996. else
  3997. strbuf_addbuf(&label, &oneline);
  3998. for (p1 = label.buf; *p1; p1++)
  3999. if (isspace(*p1))
  4000. *(char *)p1 = '-';
  4001. strbuf_reset(&buf);
  4002. strbuf_addf(&buf, "%s -C %s",
  4003. cmd_merge, oid_to_hex(&commit->object.oid));
  4004. /* label the tips of merged branches */
  4005. for (; to_merge; to_merge = to_merge->next) {
  4006. oid = &to_merge->item->object.oid;
  4007. strbuf_addch(&buf, ' ');
  4008. if (!oidset_contains(&interesting, oid)) {
  4009. strbuf_addstr(&buf, label_oid(oid, NULL,
  4010. &state));
  4011. continue;
  4012. }
  4013. tips_tail = &commit_list_insert(to_merge->item,
  4014. tips_tail)->next;
  4015. strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
  4016. }
  4017. strbuf_addf(&buf, " # %s", oneline.buf);
  4018. FLEX_ALLOC_STR(entry, string, buf.buf);
  4019. oidcpy(&entry->entry.oid, &commit->object.oid);
  4020. oidmap_put(&commit2todo, entry);
  4021. }
  4022. /*
  4023. * Second phase:
  4024. * - label branch points
  4025. * - add HEAD to the branch tips
  4026. */
  4027. for (iter = commits; iter; iter = iter->next) {
  4028. struct commit_list *parent = iter->item->parents;
  4029. for (; parent; parent = parent->next) {
  4030. struct object_id *oid = &parent->item->object.oid;
  4031. if (!oidset_contains(&interesting, oid))
  4032. continue;
  4033. if (oidset_insert(&child_seen, oid))
  4034. label_oid(oid, "branch-point", &state);
  4035. }
  4036. /* Add HEAD as implict "tip of branch" */
  4037. if (!iter->next)
  4038. tips_tail = &commit_list_insert(iter->item,
  4039. tips_tail)->next;
  4040. }
  4041. /*
  4042. * Third phase: output the todo list. This is a bit tricky, as we
  4043. * want to avoid jumping back and forth between revisions. To
  4044. * accomplish that goal, we walk backwards from the branch tips,
  4045. * gathering commits not yet shown, reversing the list on the fly,
  4046. * then outputting that list (labeling revisions as needed).
  4047. */
  4048. strbuf_addf(out, "%s onto\n", cmd_label);
  4049. for (iter = tips; iter; iter = iter->next) {
  4050. struct commit_list *list = NULL, *iter2;
  4051. commit = iter->item;
  4052. if (oidset_contains(&shown, &commit->object.oid))
  4053. continue;
  4054. entry = oidmap_get(&state.commit2label, &commit->object.oid);
  4055. if (entry)
  4056. strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
  4057. else
  4058. strbuf_addch(out, '\n');
  4059. while (oidset_contains(&interesting, &commit->object.oid) &&
  4060. !oidset_contains(&shown, &commit->object.oid)) {
  4061. commit_list_insert(commit, &list);
  4062. if (!commit->parents) {
  4063. commit = NULL;
  4064. break;
  4065. }
  4066. commit = commit->parents->item;
  4067. }
  4068. if (!commit)
  4069. strbuf_addf(out, "%s %s\n", cmd_reset,
  4070. rebase_cousins || root_with_onto ?
  4071. "onto" : "[new root]");
  4072. else {
  4073. const char *to = NULL;
  4074. entry = oidmap_get(&state.commit2label,
  4075. &commit->object.oid);
  4076. if (entry)
  4077. to = entry->string;
  4078. else if (!rebase_cousins)
  4079. to = label_oid(&commit->object.oid, NULL,
  4080. &state);
  4081. if (!to || !strcmp(to, "onto"))
  4082. strbuf_addf(out, "%s onto\n", cmd_reset);
  4083. else {
  4084. strbuf_reset(&oneline);
  4085. pretty_print_commit(pp, commit, &oneline);
  4086. strbuf_addf(out, "%s %s # %s\n",
  4087. cmd_reset, to, oneline.buf);
  4088. }
  4089. }
  4090. for (iter2 = list; iter2; iter2 = iter2->next) {
  4091. struct object_id *oid = &iter2->item->object.oid;
  4092. entry = oidmap_get(&commit2todo, oid);
  4093. /* only show if not already upstream */
  4094. if (entry)
  4095. strbuf_addf(out, "%s\n", entry->string);
  4096. entry = oidmap_get(&state.commit2label, oid);
  4097. if (entry)
  4098. strbuf_addf(out, "%s %s\n",
  4099. cmd_label, entry->string);
  4100. oidset_insert(&shown, oid);
  4101. }
  4102. free_commit_list(list);
  4103. }
  4104. free_commit_list(commits);
  4105. free_commit_list(tips);
  4106. strbuf_release(&label);
  4107. strbuf_release(&oneline);
  4108. strbuf_release(&buf);
  4109. oidmap_free(&commit2todo, 1);
  4110. oidmap_free(&state.commit2label, 1);
  4111. hashmap_free_entries(&state.labels, struct labels_entry, entry);
  4112. strbuf_release(&state.buf);
  4113. return 0;
  4114. }
  4115. int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
  4116. const char **argv, unsigned flags)
  4117. {
  4118. char *format = NULL;
  4119. struct pretty_print_context pp = {0};
  4120. struct rev_info revs;
  4121. struct commit *commit;
  4122. int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
  4123. const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
  4124. int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
  4125. repo_init_revisions(r, &revs, NULL);
  4126. revs.verbose_header = 1;
  4127. if (!rebase_merges)
  4128. revs.max_parents = 1;
  4129. revs.cherry_mark = 1;
  4130. revs.limited = 1;
  4131. revs.reverse = 1;
  4132. revs.right_only = 1;
  4133. revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
  4134. revs.topo_order = 1;
  4135. revs.pretty_given = 1;
  4136. git_config_get_string("rebase.instructionFormat", &format);
  4137. if (!format || !*format) {
  4138. free(format);
  4139. format = xstrdup("%s");
  4140. }
  4141. get_commit_format(format, &revs);
  4142. free(format);
  4143. pp.fmt = revs.commit_format;
  4144. pp.output_encoding = get_log_output_encoding();
  4145. if (setup_revisions(argc, argv, &revs, NULL) > 1)
  4146. return error(_("make_script: unhandled options"));
  4147. if (prepare_revision_walk(&revs) < 0)
  4148. return error(_("make_script: error preparing revisions"));
  4149. if (rebase_merges)
  4150. return make_script_with_merges(&pp, &revs, out, flags);
  4151. while ((commit = get_revision(&revs))) {
  4152. int is_empty = is_original_commit_empty(commit);
  4153. if (!is_empty && (commit->object.flags & PATCHSAME))
  4154. continue;
  4155. if (!keep_empty && is_empty)
  4156. strbuf_addf(out, "%c ", comment_line_char);
  4157. strbuf_addf(out, "%s %s ", insn,
  4158. oid_to_hex(&commit->object.oid));
  4159. pretty_print_commit(&pp, commit, out);
  4160. strbuf_addch(out, '\n');
  4161. }
  4162. return 0;
  4163. }
  4164. /*
  4165. * Add commands after pick and (series of) squash/fixup commands
  4166. * in the todo list.
  4167. */
  4168. void todo_list_add_exec_commands(struct todo_list *todo_list,
  4169. struct string_list *commands)
  4170. {
  4171. struct strbuf *buf = &todo_list->buf;
  4172. size_t base_offset = buf->len;
  4173. int i, insert, nr = 0, alloc = 0;
  4174. struct todo_item *items = NULL, *base_items = NULL;
  4175. base_items = xcalloc(commands->nr, sizeof(struct todo_item));
  4176. for (i = 0; i < commands->nr; i++) {
  4177. size_t command_len = strlen(commands->items[i].string);
  4178. strbuf_addstr(buf, commands->items[i].string);
  4179. strbuf_addch(buf, '\n');
  4180. base_items[i].command = TODO_EXEC;
  4181. base_items[i].offset_in_buf = base_offset;
  4182. base_items[i].arg_offset = base_offset + strlen("exec ");
  4183. base_items[i].arg_len = command_len - strlen("exec ");
  4184. base_offset += command_len + 1;
  4185. }
  4186. /*
  4187. * Insert <commands> after every pick. Here, fixup/squash chains
  4188. * are considered part of the pick, so we insert the commands *after*
  4189. * those chains if there are any.
  4190. *
  4191. * As we insert the exec commands immediatly after rearranging
  4192. * any fixups and before the user edits the list, a fixup chain
  4193. * can never contain comments (any comments are empty picks that
  4194. * have been commented out because the user did not specify
  4195. * --keep-empty). So, it is safe to insert an exec command
  4196. * without looking at the command following a comment.
  4197. */
  4198. insert = 0;
  4199. for (i = 0; i < todo_list->nr; i++) {
  4200. enum todo_command command = todo_list->items[i].command;
  4201. if (insert && !is_fixup(command)) {
  4202. ALLOC_GROW(items, nr + commands->nr, alloc);
  4203. COPY_ARRAY(items + nr, base_items, commands->nr);
  4204. nr += commands->nr;
  4205. insert = 0;
  4206. }
  4207. ALLOC_GROW(items, nr + 1, alloc);
  4208. items[nr++] = todo_list->items[i];
  4209. if (command == TODO_PICK || command == TODO_MERGE)
  4210. insert = 1;
  4211. }
  4212. /* insert or append final <commands> */
  4213. if (insert || nr == todo_list->nr) {
  4214. ALLOC_GROW(items, nr + commands->nr, alloc);
  4215. COPY_ARRAY(items + nr, base_items, commands->nr);
  4216. nr += commands->nr;
  4217. }
  4218. free(base_items);
  4219. FREE_AND_NULL(todo_list->items);
  4220. todo_list->items = items;
  4221. todo_list->nr = nr;
  4222. todo_list->alloc = alloc;
  4223. }
  4224. static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
  4225. struct strbuf *buf, int num, unsigned flags)
  4226. {
  4227. struct todo_item *item;
  4228. int i, max = todo_list->nr;
  4229. if (num > 0 && num < max)
  4230. max = num;
  4231. for (item = todo_list->items, i = 0; i < max; i++, item++) {
  4232. /* if the item is not a command write it and continue */
  4233. if (item->command >= TODO_COMMENT) {
  4234. strbuf_addf(buf, "%.*s\n", item->arg_len,
  4235. todo_item_get_arg(todo_list, item));
  4236. continue;
  4237. }
  4238. /* add command to the buffer */
  4239. if (flags & TODO_LIST_ABBREVIATE_CMDS)
  4240. strbuf_addch(buf, command_to_char(item->command));
  4241. else
  4242. strbuf_addstr(buf, command_to_string(item->command));
  4243. /* add commit id */
  4244. if (item->commit) {
  4245. const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
  4246. short_commit_name(item->commit) :
  4247. oid_to_hex(&item->commit->object.oid);
  4248. if (item->command == TODO_MERGE) {
  4249. if (item->flags & TODO_EDIT_MERGE_MSG)
  4250. strbuf_addstr(buf, " -c");
  4251. else
  4252. strbuf_addstr(buf, " -C");
  4253. }
  4254. strbuf_addf(buf, " %s", oid);
  4255. }
  4256. /* add all the rest */
  4257. if (!item->arg_len)
  4258. strbuf_addch(buf, '\n');
  4259. else
  4260. strbuf_addf(buf, " %.*s\n", item->arg_len,
  4261. todo_item_get_arg(todo_list, item));
  4262. }
  4263. }
  4264. int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
  4265. const char *file, const char *shortrevisions,
  4266. const char *shortonto, int num, unsigned flags)
  4267. {
  4268. int res;
  4269. struct strbuf buf = STRBUF_INIT;
  4270. todo_list_to_strbuf(r, todo_list, &buf, num, flags);
  4271. if (flags & TODO_LIST_APPEND_TODO_HELP)
  4272. append_todo_help(flags & TODO_LIST_KEEP_EMPTY, count_commands(todo_list),
  4273. shortrevisions, shortonto, &buf);
  4274. res = write_message(buf.buf, buf.len, file, 0);
  4275. strbuf_release(&buf);
  4276. return res;
  4277. }
  4278. static const char edit_todo_list_advice[] =
  4279. N_("You can fix this with 'git rebase --edit-todo' "
  4280. "and then run 'git rebase --continue'.\n"
  4281. "Or you can abort the rebase with 'git rebase"
  4282. " --abort'.\n");
  4283. int check_todo_list_from_file(struct repository *r)
  4284. {
  4285. struct todo_list old_todo = TODO_LIST_INIT, new_todo = TODO_LIST_INIT;
  4286. int res = 0;
  4287. if (strbuf_read_file_or_whine(&new_todo.buf, rebase_path_todo()) < 0) {
  4288. res = -1;
  4289. goto out;
  4290. }
  4291. if (strbuf_read_file_or_whine(&old_todo.buf, rebase_path_todo_backup()) < 0) {
  4292. res = -1;
  4293. goto out;
  4294. }
  4295. res = todo_list_parse_insn_buffer(r, old_todo.buf.buf, &old_todo);
  4296. if (!res)
  4297. res = todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo);
  4298. if (!res)
  4299. res = todo_list_check(&old_todo, &new_todo);
  4300. if (res)
  4301. fprintf(stderr, _(edit_todo_list_advice));
  4302. out:
  4303. todo_list_release(&old_todo);
  4304. todo_list_release(&new_todo);
  4305. return res;
  4306. }
  4307. /* skip picking commits whose parents are unchanged */
  4308. static int skip_unnecessary_picks(struct repository *r,
  4309. struct todo_list *todo_list,
  4310. struct object_id *base_oid)
  4311. {
  4312. struct object_id *parent_oid;
  4313. int i;
  4314. for (i = 0; i < todo_list->nr; i++) {
  4315. struct todo_item *item = todo_list->items + i;
  4316. if (item->command >= TODO_NOOP)
  4317. continue;
  4318. if (item->command != TODO_PICK)
  4319. break;
  4320. if (parse_commit(item->commit)) {
  4321. return error(_("could not parse commit '%s'"),
  4322. oid_to_hex(&item->commit->object.oid));
  4323. }
  4324. if (!item->commit->parents)
  4325. break; /* root commit */
  4326. if (item->commit->parents->next)
  4327. break; /* merge commit */
  4328. parent_oid = &item->commit->parents->item->object.oid;
  4329. if (!oideq(parent_oid, base_oid))
  4330. break;
  4331. oidcpy(base_oid, &item->commit->object.oid);
  4332. }
  4333. if (i > 0) {
  4334. const char *done_path = rebase_path_done();
  4335. if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
  4336. error_errno(_("could not write to '%s'"), done_path);
  4337. return -1;
  4338. }
  4339. MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
  4340. todo_list->nr -= i;
  4341. todo_list->current = 0;
  4342. if (is_fixup(peek_command(todo_list, 0)))
  4343. record_in_rewritten(base_oid, peek_command(todo_list, 0));
  4344. }
  4345. return 0;
  4346. }
  4347. int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
  4348. const char *shortrevisions, const char *onto_name,
  4349. struct commit *onto, const char *orig_head,
  4350. struct string_list *commands, unsigned autosquash,
  4351. struct todo_list *todo_list)
  4352. {
  4353. const char *shortonto, *todo_file = rebase_path_todo();
  4354. struct todo_list new_todo = TODO_LIST_INIT;
  4355. struct strbuf *buf = &todo_list->buf;
  4356. struct object_id oid = onto->object.oid;
  4357. int res;
  4358. shortonto = find_unique_abbrev(&oid, DEFAULT_ABBREV);
  4359. if (buf->len == 0) {
  4360. struct todo_item *item = append_new_todo(todo_list);
  4361. item->command = TODO_NOOP;
  4362. item->commit = NULL;
  4363. item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
  4364. }
  4365. if (autosquash && todo_list_rearrange_squash(todo_list))
  4366. return -1;
  4367. if (commands->nr)
  4368. todo_list_add_exec_commands(todo_list, commands);
  4369. if (count_commands(todo_list) == 0) {
  4370. apply_autostash(opts);
  4371. sequencer_remove_state(opts);
  4372. return error(_("nothing to do"));
  4373. }
  4374. res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
  4375. shortonto, flags);
  4376. if (res == -1)
  4377. return -1;
  4378. else if (res == -2) {
  4379. apply_autostash(opts);
  4380. sequencer_remove_state(opts);
  4381. return -1;
  4382. } else if (res == -3) {
  4383. apply_autostash(opts);
  4384. sequencer_remove_state(opts);
  4385. todo_list_release(&new_todo);
  4386. return error(_("nothing to do"));
  4387. }
  4388. if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) ||
  4389. todo_list_check(todo_list, &new_todo)) {
  4390. fprintf(stderr, _(edit_todo_list_advice));
  4391. checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
  4392. todo_list_release(&new_todo);
  4393. return -1;
  4394. }
  4395. if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
  4396. todo_list_release(&new_todo);
  4397. return error(_("could not skip unnecessary pick commands"));
  4398. }
  4399. if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
  4400. flags & ~(TODO_LIST_SHORTEN_IDS))) {
  4401. todo_list_release(&new_todo);
  4402. return error_errno(_("could not write '%s'"), todo_file);
  4403. }
  4404. todo_list_release(&new_todo);
  4405. if (checkout_onto(r, opts, onto_name, &oid, orig_head))
  4406. return -1;
  4407. if (require_clean_work_tree(r, "rebase", "", 1, 1))
  4408. return -1;
  4409. return sequencer_continue(r, opts);
  4410. }
  4411. struct subject2item_entry {
  4412. struct hashmap_entry entry;
  4413. int i;
  4414. char subject[FLEX_ARRAY];
  4415. };
  4416. static int subject2item_cmp(const void *fndata,
  4417. const struct hashmap_entry *eptr,
  4418. const struct hashmap_entry *entry_or_key,
  4419. const void *key)
  4420. {
  4421. const struct subject2item_entry *a, *b;
  4422. a = container_of(eptr, const struct subject2item_entry, entry);
  4423. b = container_of(entry_or_key, const struct subject2item_entry, entry);
  4424. return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
  4425. }
  4426. define_commit_slab(commit_todo_item, struct todo_item *);
  4427. /*
  4428. * Rearrange the todo list that has both "pick commit-id msg" and "pick
  4429. * commit-id fixup!/squash! msg" in it so that the latter is put immediately
  4430. * after the former, and change "pick" to "fixup"/"squash".
  4431. *
  4432. * Note that if the config has specified a custom instruction format, each log
  4433. * message will have to be retrieved from the commit (as the oneline in the
  4434. * script cannot be trusted) in order to normalize the autosquash arrangement.
  4435. */
  4436. int todo_list_rearrange_squash(struct todo_list *todo_list)
  4437. {
  4438. struct hashmap subject2item;
  4439. int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
  4440. char **subjects;
  4441. struct commit_todo_item commit_todo;
  4442. struct todo_item *items = NULL;
  4443. init_commit_todo_item(&commit_todo);
  4444. /*
  4445. * The hashmap maps onelines to the respective todo list index.
  4446. *
  4447. * If any items need to be rearranged, the next[i] value will indicate
  4448. * which item was moved directly after the i'th.
  4449. *
  4450. * In that case, last[i] will indicate the index of the latest item to
  4451. * be moved to appear after the i'th.
  4452. */
  4453. hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
  4454. ALLOC_ARRAY(next, todo_list->nr);
  4455. ALLOC_ARRAY(tail, todo_list->nr);
  4456. ALLOC_ARRAY(subjects, todo_list->nr);
  4457. for (i = 0; i < todo_list->nr; i++) {
  4458. struct strbuf buf = STRBUF_INIT;
  4459. struct todo_item *item = todo_list->items + i;
  4460. const char *commit_buffer, *subject, *p;
  4461. size_t subject_len;
  4462. int i2 = -1;
  4463. struct subject2item_entry *entry;
  4464. next[i] = tail[i] = -1;
  4465. if (!item->commit || item->command == TODO_DROP) {
  4466. subjects[i] = NULL;
  4467. continue;
  4468. }
  4469. if (is_fixup(item->command)) {
  4470. clear_commit_todo_item(&commit_todo);
  4471. return error(_("the script was already rearranged."));
  4472. }
  4473. *commit_todo_item_at(&commit_todo, item->commit) = item;
  4474. parse_commit(item->commit);
  4475. commit_buffer = get_commit_buffer(item->commit, NULL);
  4476. find_commit_subject(commit_buffer, &subject);
  4477. format_subject(&buf, subject, " ");
  4478. subject = subjects[i] = strbuf_detach(&buf, &subject_len);
  4479. unuse_commit_buffer(item->commit, commit_buffer);
  4480. if ((skip_prefix(subject, "fixup! ", &p) ||
  4481. skip_prefix(subject, "squash! ", &p))) {
  4482. struct commit *commit2;
  4483. for (;;) {
  4484. while (isspace(*p))
  4485. p++;
  4486. if (!skip_prefix(p, "fixup! ", &p) &&
  4487. !skip_prefix(p, "squash! ", &p))
  4488. break;
  4489. }
  4490. entry = hashmap_get_entry_from_hash(&subject2item,
  4491. strhash(p), p,
  4492. struct subject2item_entry,
  4493. entry);
  4494. if (entry)
  4495. /* found by title */
  4496. i2 = entry->i;
  4497. else if (!strchr(p, ' ') &&
  4498. (commit2 =
  4499. lookup_commit_reference_by_name(p)) &&
  4500. *commit_todo_item_at(&commit_todo, commit2))
  4501. /* found by commit name */
  4502. i2 = *commit_todo_item_at(&commit_todo, commit2)
  4503. - todo_list->items;
  4504. else {
  4505. /* copy can be a prefix of the commit subject */
  4506. for (i2 = 0; i2 < i; i2++)
  4507. if (subjects[i2] &&
  4508. starts_with(subjects[i2], p))
  4509. break;
  4510. if (i2 == i)
  4511. i2 = -1;
  4512. }
  4513. }
  4514. if (i2 >= 0) {
  4515. rearranged = 1;
  4516. todo_list->items[i].command =
  4517. starts_with(subject, "fixup!") ?
  4518. TODO_FIXUP : TODO_SQUASH;
  4519. if (next[i2] < 0)
  4520. next[i2] = i;
  4521. else
  4522. next[tail[i2]] = i;
  4523. tail[i2] = i;
  4524. } else if (!hashmap_get_from_hash(&subject2item,
  4525. strhash(subject), subject)) {
  4526. FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
  4527. entry->i = i;
  4528. hashmap_entry_init(&entry->entry,
  4529. strhash(entry->subject));
  4530. hashmap_put(&subject2item, &entry->entry);
  4531. }
  4532. }
  4533. if (rearranged) {
  4534. for (i = 0; i < todo_list->nr; i++) {
  4535. enum todo_command command = todo_list->items[i].command;
  4536. int cur = i;
  4537. /*
  4538. * Initially, all commands are 'pick's. If it is a
  4539. * fixup or a squash now, we have rearranged it.
  4540. */
  4541. if (is_fixup(command))
  4542. continue;
  4543. while (cur >= 0) {
  4544. ALLOC_GROW(items, nr + 1, alloc);
  4545. items[nr++] = todo_list->items[cur];
  4546. cur = next[cur];
  4547. }
  4548. }
  4549. FREE_AND_NULL(todo_list->items);
  4550. todo_list->items = items;
  4551. todo_list->nr = nr;
  4552. todo_list->alloc = alloc;
  4553. }
  4554. free(next);
  4555. free(tail);
  4556. for (i = 0; i < todo_list->nr; i++)
  4557. free(subjects[i]);
  4558. free(subjects);
  4559. hashmap_free_entries(&subject2item, struct subject2item_entry, entry);
  4560. clear_commit_todo_item(&commit_todo);
  4561. return 0;
  4562. }