Merge branch 'cb/printf-empty-format'
[git/git.git] / builtin / rebase.c
1 /*
2 * "git rebase" builtin command
3 *
4 * Copyright (c) 2018 Pratik Karki
5 */
6
7 #include "builtin.h"
8 #include "run-command.h"
9 #include "exec-cmd.h"
10 #include "argv-array.h"
11 #include "dir.h"
12 #include "packfile.h"
13 #include "refs.h"
14 #include "quote.h"
15 #include "config.h"
16 #include "cache-tree.h"
17 #include "unpack-trees.h"
18 #include "lockfile.h"
19 #include "parse-options.h"
20 #include "commit.h"
21 #include "diff.h"
22 #include "wt-status.h"
23 #include "revision.h"
24 #include "commit-reach.h"
25 #include "rerere.h"
26
27 static char const * const builtin_rebase_usage[] = {
28 N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
29 "[<upstream>] [<branch>]"),
30 N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
31 "--root [<branch>]"),
32 N_("git rebase --continue | --abort | --skip | --edit-todo"),
33 NULL
34 };
35
36 static GIT_PATH_FUNC(apply_dir, "rebase-apply")
37 static GIT_PATH_FUNC(merge_dir, "rebase-merge")
38
39 enum rebase_type {
40 REBASE_UNSPECIFIED = -1,
41 REBASE_AM,
42 REBASE_MERGE,
43 REBASE_INTERACTIVE,
44 REBASE_PRESERVE_MERGES
45 };
46
47 static int use_builtin_rebase(void)
48 {
49 struct child_process cp = CHILD_PROCESS_INIT;
50 struct strbuf out = STRBUF_INIT;
51 int ret;
52
53 argv_array_pushl(&cp.args,
54 "config", "--bool", "rebase.usebuiltin", NULL);
55 cp.git_cmd = 1;
56 if (capture_command(&cp, &out, 6)) {
57 strbuf_release(&out);
58 return 1;
59 }
60
61 strbuf_trim(&out);
62 ret = !strcmp("true", out.buf);
63 strbuf_release(&out);
64 return ret;
65 }
66
67 struct rebase_options {
68 enum rebase_type type;
69 const char *state_dir;
70 struct commit *upstream;
71 const char *upstream_name;
72 const char *upstream_arg;
73 char *head_name;
74 struct object_id orig_head;
75 struct commit *onto;
76 const char *onto_name;
77 const char *revisions;
78 const char *switch_to;
79 int root;
80 struct object_id *squash_onto;
81 struct commit *restrict_revision;
82 int dont_finish_rebase;
83 enum {
84 REBASE_NO_QUIET = 1<<0,
85 REBASE_VERBOSE = 1<<1,
86 REBASE_DIFFSTAT = 1<<2,
87 REBASE_FORCE = 1<<3,
88 REBASE_INTERACTIVE_EXPLICIT = 1<<4,
89 } flags;
90 struct strbuf git_am_opt;
91 const char *action;
92 int signoff;
93 int allow_rerere_autoupdate;
94 int keep_empty;
95 int autosquash;
96 char *gpg_sign_opt;
97 int autostash;
98 char *cmd;
99 int allow_empty_message;
100 int rebase_merges, rebase_cousins;
101 char *strategy, *strategy_opts;
102 struct strbuf git_format_patch_opt;
103 };
104
105 static int is_interactive(struct rebase_options *opts)
106 {
107 return opts->type == REBASE_INTERACTIVE ||
108 opts->type == REBASE_PRESERVE_MERGES;
109 }
110
111 static void imply_interactive(struct rebase_options *opts, const char *option)
112 {
113 switch (opts->type) {
114 case REBASE_AM:
115 die(_("%s requires an interactive rebase"), option);
116 break;
117 case REBASE_INTERACTIVE:
118 case REBASE_PRESERVE_MERGES:
119 break;
120 case REBASE_MERGE:
121 /* we silently *upgrade* --merge to --interactive if needed */
122 default:
123 opts->type = REBASE_INTERACTIVE; /* implied */
124 break;
125 }
126 }
127
128 /* Returns the filename prefixed by the state_dir */
129 static const char *state_dir_path(const char *filename, struct rebase_options *opts)
130 {
131 static struct strbuf path = STRBUF_INIT;
132 static size_t prefix_len;
133
134 if (!prefix_len) {
135 strbuf_addf(&path, "%s/", opts->state_dir);
136 prefix_len = path.len;
137 }
138
139 strbuf_setlen(&path, prefix_len);
140 strbuf_addstr(&path, filename);
141 return path.buf;
142 }
143
144 /* Read one file, then strip line endings */
145 static int read_one(const char *path, struct strbuf *buf)
146 {
147 if (strbuf_read_file(buf, path, 0) < 0)
148 return error_errno(_("could not read '%s'"), path);
149 strbuf_trim_trailing_newline(buf);
150 return 0;
151 }
152
153 /* Initialize the rebase options from the state directory. */
154 static int read_basic_state(struct rebase_options *opts)
155 {
156 struct strbuf head_name = STRBUF_INIT;
157 struct strbuf buf = STRBUF_INIT;
158 struct object_id oid;
159
160 if (read_one(state_dir_path("head-name", opts), &head_name) ||
161 read_one(state_dir_path("onto", opts), &buf))
162 return -1;
163 opts->head_name = starts_with(head_name.buf, "refs/") ?
164 xstrdup(head_name.buf) : NULL;
165 strbuf_release(&head_name);
166 if (get_oid(buf.buf, &oid))
167 return error(_("could not get 'onto': '%s'"), buf.buf);
168 opts->onto = lookup_commit_or_die(&oid, buf.buf);
169
170 /*
171 * We always write to orig-head, but interactive rebase used to write to
172 * head. Fall back to reading from head to cover for the case that the
173 * user upgraded git with an ongoing interactive rebase.
174 */
175 strbuf_reset(&buf);
176 if (file_exists(state_dir_path("orig-head", opts))) {
177 if (read_one(state_dir_path("orig-head", opts), &buf))
178 return -1;
179 } else if (read_one(state_dir_path("head", opts), &buf))
180 return -1;
181 if (get_oid(buf.buf, &opts->orig_head))
182 return error(_("invalid orig-head: '%s'"), buf.buf);
183
184 strbuf_reset(&buf);
185 if (read_one(state_dir_path("quiet", opts), &buf))
186 return -1;
187 if (buf.len)
188 opts->flags &= ~REBASE_NO_QUIET;
189 else
190 opts->flags |= REBASE_NO_QUIET;
191
192 if (file_exists(state_dir_path("verbose", opts)))
193 opts->flags |= REBASE_VERBOSE;
194
195 if (file_exists(state_dir_path("signoff", opts))) {
196 opts->signoff = 1;
197 opts->flags |= REBASE_FORCE;
198 }
199
200 if (file_exists(state_dir_path("allow_rerere_autoupdate", opts))) {
201 strbuf_reset(&buf);
202 if (read_one(state_dir_path("allow_rerere_autoupdate", opts),
203 &buf))
204 return -1;
205 if (!strcmp(buf.buf, "--rerere-autoupdate"))
206 opts->allow_rerere_autoupdate = 1;
207 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
208 opts->allow_rerere_autoupdate = 0;
209 else
210 warning(_("ignoring invalid allow_rerere_autoupdate: "
211 "'%s'"), buf.buf);
212 } else
213 opts->allow_rerere_autoupdate = -1;
214
215 if (file_exists(state_dir_path("gpg_sign_opt", opts))) {
216 strbuf_reset(&buf);
217 if (read_one(state_dir_path("gpg_sign_opt", opts),
218 &buf))
219 return -1;
220 free(opts->gpg_sign_opt);
221 opts->gpg_sign_opt = xstrdup(buf.buf);
222 }
223
224 if (file_exists(state_dir_path("strategy", opts))) {
225 strbuf_reset(&buf);
226 if (read_one(state_dir_path("strategy", opts), &buf))
227 return -1;
228 free(opts->strategy);
229 opts->strategy = xstrdup(buf.buf);
230 }
231
232 if (file_exists(state_dir_path("strategy_opts", opts))) {
233 strbuf_reset(&buf);
234 if (read_one(state_dir_path("strategy_opts", opts), &buf))
235 return -1;
236 free(opts->strategy_opts);
237 opts->strategy_opts = xstrdup(buf.buf);
238 }
239
240 strbuf_release(&buf);
241
242 return 0;
243 }
244
245 static int apply_autostash(struct rebase_options *opts)
246 {
247 const char *path = state_dir_path("autostash", opts);
248 struct strbuf autostash = STRBUF_INIT;
249 struct child_process stash_apply = CHILD_PROCESS_INIT;
250
251 if (!file_exists(path))
252 return 0;
253
254 if (read_one(state_dir_path("autostash", opts), &autostash))
255 return error(_("Could not read '%s'"), path);
256 argv_array_pushl(&stash_apply.args,
257 "stash", "apply", autostash.buf, NULL);
258 stash_apply.git_cmd = 1;
259 stash_apply.no_stderr = stash_apply.no_stdout =
260 stash_apply.no_stdin = 1;
261 if (!run_command(&stash_apply))
262 printf(_("Applied autostash.\n"));
263 else {
264 struct argv_array args = ARGV_ARRAY_INIT;
265 int res = 0;
266
267 argv_array_pushl(&args,
268 "stash", "store", "-m", "autostash", "-q",
269 autostash.buf, NULL);
270 if (run_command_v_opt(args.argv, RUN_GIT_CMD))
271 res = error(_("Cannot store %s"), autostash.buf);
272 argv_array_clear(&args);
273 strbuf_release(&autostash);
274 if (res)
275 return res;
276
277 fprintf(stderr,
278 _("Applying autostash resulted in conflicts.\n"
279 "Your changes are safe in the stash.\n"
280 "You can run \"git stash pop\" or \"git stash drop\" "
281 "at any time.\n"));
282 }
283
284 strbuf_release(&autostash);
285 return 0;
286 }
287
288 static int finish_rebase(struct rebase_options *opts)
289 {
290 struct strbuf dir = STRBUF_INIT;
291 const char *argv_gc_auto[] = { "gc", "--auto", NULL };
292
293 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
294 apply_autostash(opts);
295 close_all_packs(the_repository->objects);
296 /*
297 * We ignore errors in 'gc --auto', since the
298 * user should see them.
299 */
300 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
301 strbuf_addstr(&dir, opts->state_dir);
302 remove_dir_recursively(&dir, 0);
303 strbuf_release(&dir);
304
305 return 0;
306 }
307
308 static struct commit *peel_committish(const char *name)
309 {
310 struct object *obj;
311 struct object_id oid;
312
313 if (get_oid(name, &oid))
314 return NULL;
315 obj = parse_object(the_repository, &oid);
316 return (struct commit *)peel_to_type(name, 0, obj, OBJ_COMMIT);
317 }
318
319 static void add_var(struct strbuf *buf, const char *name, const char *value)
320 {
321 if (!value)
322 strbuf_addf(buf, "unset %s; ", name);
323 else {
324 strbuf_addf(buf, "%s=", name);
325 sq_quote_buf(buf, value);
326 strbuf_addstr(buf, "; ");
327 }
328 }
329
330 static const char *resolvemsg =
331 N_("Resolve all conflicts manually, mark them as resolved with\n"
332 "\"git add/rm <conflicted_files>\", then run \"git rebase --continue\".\n"
333 "You can instead skip this commit: run \"git rebase --skip\".\n"
334 "To abort and get back to the state before \"git rebase\", run "
335 "\"git rebase --abort\".");
336
337 static int run_specific_rebase(struct rebase_options *opts)
338 {
339 const char *argv[] = { NULL, NULL };
340 struct strbuf script_snippet = STRBUF_INIT;
341 int status;
342 const char *backend, *backend_func;
343
344 if (opts->type == REBASE_INTERACTIVE) {
345 /* Run builtin interactive rebase */
346 struct child_process child = CHILD_PROCESS_INIT;
347
348 argv_array_pushf(&child.env_array, "GIT_CHERRY_PICK_HELP=%s",
349 resolvemsg);
350 if (!(opts->flags & REBASE_INTERACTIVE_EXPLICIT)) {
351 argv_array_push(&child.env_array, "GIT_EDITOR=:");
352 opts->autosquash = 0;
353 }
354
355 child.git_cmd = 1;
356 argv_array_push(&child.args, "rebase--interactive");
357
358 if (opts->action)
359 argv_array_pushf(&child.args, "--%s", opts->action);
360 if (opts->keep_empty)
361 argv_array_push(&child.args, "--keep-empty");
362 if (opts->rebase_merges)
363 argv_array_push(&child.args, "--rebase-merges");
364 if (opts->rebase_cousins)
365 argv_array_push(&child.args, "--rebase-cousins");
366 if (opts->autosquash)
367 argv_array_push(&child.args, "--autosquash");
368 if (opts->flags & REBASE_VERBOSE)
369 argv_array_push(&child.args, "--verbose");
370 if (opts->flags & REBASE_FORCE)
371 argv_array_push(&child.args, "--no-ff");
372 if (opts->restrict_revision)
373 argv_array_pushf(&child.args,
374 "--restrict-revision=^%s",
375 oid_to_hex(&opts->restrict_revision->object.oid));
376 if (opts->upstream)
377 argv_array_pushf(&child.args, "--upstream=%s",
378 oid_to_hex(&opts->upstream->object.oid));
379 if (opts->onto)
380 argv_array_pushf(&child.args, "--onto=%s",
381 oid_to_hex(&opts->onto->object.oid));
382 if (opts->squash_onto)
383 argv_array_pushf(&child.args, "--squash-onto=%s",
384 oid_to_hex(opts->squash_onto));
385 if (opts->onto_name)
386 argv_array_pushf(&child.args, "--onto-name=%s",
387 opts->onto_name);
388 argv_array_pushf(&child.args, "--head-name=%s",
389 opts->head_name ?
390 opts->head_name : "detached HEAD");
391 if (opts->strategy)
392 argv_array_pushf(&child.args, "--strategy=%s",
393 opts->strategy);
394 if (opts->strategy_opts)
395 argv_array_pushf(&child.args, "--strategy-opts=%s",
396 opts->strategy_opts);
397 if (opts->switch_to)
398 argv_array_pushf(&child.args, "--switch-to=%s",
399 opts->switch_to);
400 if (opts->cmd)
401 argv_array_pushf(&child.args, "--cmd=%s", opts->cmd);
402 if (opts->allow_empty_message)
403 argv_array_push(&child.args, "--allow-empty-message");
404 if (opts->allow_rerere_autoupdate > 0)
405 argv_array_push(&child.args, "--rerere-autoupdate");
406 else if (opts->allow_rerere_autoupdate == 0)
407 argv_array_push(&child.args, "--no-rerere-autoupdate");
408 if (opts->gpg_sign_opt)
409 argv_array_push(&child.args, opts->gpg_sign_opt);
410 if (opts->signoff)
411 argv_array_push(&child.args, "--signoff");
412
413 status = run_command(&child);
414 goto finished_rebase;
415 }
416
417 add_var(&script_snippet, "GIT_DIR", absolute_path(get_git_dir()));
418 add_var(&script_snippet, "state_dir", opts->state_dir);
419
420 add_var(&script_snippet, "upstream_name", opts->upstream_name);
421 add_var(&script_snippet, "upstream", opts->upstream ?
422 oid_to_hex(&opts->upstream->object.oid) : NULL);
423 add_var(&script_snippet, "head_name",
424 opts->head_name ? opts->head_name : "detached HEAD");
425 add_var(&script_snippet, "orig_head", oid_to_hex(&opts->orig_head));
426 add_var(&script_snippet, "onto", opts->onto ?
427 oid_to_hex(&opts->onto->object.oid) : NULL);
428 add_var(&script_snippet, "onto_name", opts->onto_name);
429 add_var(&script_snippet, "revisions", opts->revisions);
430 add_var(&script_snippet, "restrict_revision", opts->restrict_revision ?
431 oid_to_hex(&opts->restrict_revision->object.oid) : NULL);
432 add_var(&script_snippet, "GIT_QUIET",
433 opts->flags & REBASE_NO_QUIET ? "" : "t");
434 add_var(&script_snippet, "git_am_opt", opts->git_am_opt.buf);
435 add_var(&script_snippet, "verbose",
436 opts->flags & REBASE_VERBOSE ? "t" : "");
437 add_var(&script_snippet, "diffstat",
438 opts->flags & REBASE_DIFFSTAT ? "t" : "");
439 add_var(&script_snippet, "force_rebase",
440 opts->flags & REBASE_FORCE ? "t" : "");
441 if (opts->switch_to)
442 add_var(&script_snippet, "switch_to", opts->switch_to);
443 add_var(&script_snippet, "action", opts->action ? opts->action : "");
444 add_var(&script_snippet, "signoff", opts->signoff ? "--signoff" : "");
445 add_var(&script_snippet, "allow_rerere_autoupdate",
446 opts->allow_rerere_autoupdate < 0 ? "" :
447 opts->allow_rerere_autoupdate ?
448 "--rerere-autoupdate" : "--no-rerere-autoupdate");
449 add_var(&script_snippet, "keep_empty", opts->keep_empty ? "yes" : "");
450 add_var(&script_snippet, "autosquash", opts->autosquash ? "t" : "");
451 add_var(&script_snippet, "gpg_sign_opt", opts->gpg_sign_opt);
452 add_var(&script_snippet, "cmd", opts->cmd);
453 add_var(&script_snippet, "allow_empty_message",
454 opts->allow_empty_message ? "--allow-empty-message" : "");
455 add_var(&script_snippet, "rebase_merges",
456 opts->rebase_merges ? "t" : "");
457 add_var(&script_snippet, "rebase_cousins",
458 opts->rebase_cousins ? "t" : "");
459 add_var(&script_snippet, "strategy", opts->strategy);
460 add_var(&script_snippet, "strategy_opts", opts->strategy_opts);
461 add_var(&script_snippet, "rebase_root", opts->root ? "t" : "");
462 add_var(&script_snippet, "squash_onto",
463 opts->squash_onto ? oid_to_hex(opts->squash_onto) : "");
464 add_var(&script_snippet, "git_format_patch_opt",
465 opts->git_format_patch_opt.buf);
466
467 if (is_interactive(opts) &&
468 !(opts->flags & REBASE_INTERACTIVE_EXPLICIT)) {
469 strbuf_addstr(&script_snippet,
470 "GIT_EDITOR=:; export GIT_EDITOR; ");
471 opts->autosquash = 0;
472 }
473
474 switch (opts->type) {
475 case REBASE_AM:
476 backend = "git-rebase--am";
477 backend_func = "git_rebase__am";
478 break;
479 case REBASE_MERGE:
480 backend = "git-rebase--merge";
481 backend_func = "git_rebase__merge";
482 break;
483 case REBASE_PRESERVE_MERGES:
484 backend = "git-rebase--preserve-merges";
485 backend_func = "git_rebase__preserve_merges";
486 break;
487 default:
488 BUG("Unhandled rebase type %d", opts->type);
489 break;
490 }
491
492 strbuf_addf(&script_snippet,
493 ". git-sh-setup && . git-rebase--common &&"
494 " . %s && %s", backend, backend_func);
495 argv[0] = script_snippet.buf;
496
497 status = run_command_v_opt(argv, RUN_USING_SHELL);
498 finished_rebase:
499 if (opts->dont_finish_rebase)
500 ; /* do nothing */
501 else if (opts->type == REBASE_INTERACTIVE)
502 ; /* interactive rebase cleans up after itself */
503 else if (status == 0) {
504 if (!file_exists(state_dir_path("stopped-sha", opts)))
505 finish_rebase(opts);
506 } else if (status == 2) {
507 struct strbuf dir = STRBUF_INIT;
508
509 apply_autostash(opts);
510 strbuf_addstr(&dir, opts->state_dir);
511 remove_dir_recursively(&dir, 0);
512 strbuf_release(&dir);
513 die("Nothing to do");
514 }
515
516 strbuf_release(&script_snippet);
517
518 return status ? -1 : 0;
519 }
520
521 #define GIT_REFLOG_ACTION_ENVIRONMENT "GIT_REFLOG_ACTION"
522
523 static int reset_head(struct object_id *oid, const char *action,
524 const char *switch_to_branch, int detach_head,
525 const char *reflog_orig_head, const char *reflog_head)
526 {
527 struct object_id head_oid;
528 struct tree_desc desc;
529 struct lock_file lock = LOCK_INIT;
530 struct unpack_trees_options unpack_tree_opts;
531 struct tree *tree;
532 const char *reflog_action;
533 struct strbuf msg = STRBUF_INIT;
534 size_t prefix_len;
535 struct object_id *orig = NULL, oid_orig,
536 *old_orig = NULL, oid_old_orig;
537 int ret = 0;
538
539 if (switch_to_branch && !starts_with(switch_to_branch, "refs/"))
540 BUG("Not a fully qualified branch: '%s'", switch_to_branch);
541
542 if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0)
543 return -1;
544
545 if (!oid) {
546 if (get_oid("HEAD", &head_oid)) {
547 rollback_lock_file(&lock);
548 return error(_("could not determine HEAD revision"));
549 }
550 oid = &head_oid;
551 }
552
553 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
554 setup_unpack_trees_porcelain(&unpack_tree_opts, action);
555 unpack_tree_opts.head_idx = 1;
556 unpack_tree_opts.src_index = the_repository->index;
557 unpack_tree_opts.dst_index = the_repository->index;
558 unpack_tree_opts.fn = oneway_merge;
559 unpack_tree_opts.update = 1;
560 unpack_tree_opts.merge = 1;
561 if (!detach_head)
562 unpack_tree_opts.reset = 1;
563
564 if (read_index_unmerged(the_repository->index) < 0) {
565 rollback_lock_file(&lock);
566 return error(_("could not read index"));
567 }
568
569 if (!fill_tree_descriptor(&desc, oid)) {
570 error(_("failed to find tree of %s"), oid_to_hex(oid));
571 rollback_lock_file(&lock);
572 free((void *)desc.buffer);
573 return -1;
574 }
575
576 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
577 rollback_lock_file(&lock);
578 free((void *)desc.buffer);
579 return -1;
580 }
581
582 tree = parse_tree_indirect(oid);
583 prime_cache_tree(the_repository->index, tree);
584
585 if (write_locked_index(the_repository->index, &lock, COMMIT_LOCK) < 0)
586 ret = error(_("could not write index"));
587 free((void *)desc.buffer);
588
589 if (ret)
590 return ret;
591
592 reflog_action = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
593 strbuf_addf(&msg, "%s: ", reflog_action ? reflog_action : "rebase");
594 prefix_len = msg.len;
595
596 if (!get_oid("ORIG_HEAD", &oid_old_orig))
597 old_orig = &oid_old_orig;
598 if (!get_oid("HEAD", &oid_orig)) {
599 orig = &oid_orig;
600 if (!reflog_orig_head) {
601 strbuf_addstr(&msg, "updating ORIG_HEAD");
602 reflog_orig_head = msg.buf;
603 }
604 update_ref(reflog_orig_head, "ORIG_HEAD", orig, old_orig, 0,
605 UPDATE_REFS_MSG_ON_ERR);
606 } else if (old_orig)
607 delete_ref(NULL, "ORIG_HEAD", old_orig, 0);
608 if (!reflog_head) {
609 strbuf_setlen(&msg, prefix_len);
610 strbuf_addstr(&msg, "updating HEAD");
611 reflog_head = msg.buf;
612 }
613 if (!switch_to_branch)
614 ret = update_ref(reflog_head, "HEAD", oid, orig, REF_NO_DEREF,
615 UPDATE_REFS_MSG_ON_ERR);
616 else {
617 ret = create_symref("HEAD", switch_to_branch, msg.buf);
618 if (!ret)
619 ret = update_ref(reflog_head, "HEAD", oid, NULL, 0,
620 UPDATE_REFS_MSG_ON_ERR);
621 }
622
623 strbuf_release(&msg);
624 return ret;
625 }
626
627 static int rebase_config(const char *var, const char *value, void *data)
628 {
629 struct rebase_options *opts = data;
630
631 if (!strcmp(var, "rebase.stat")) {
632 if (git_config_bool(var, value))
633 opts->flags |= REBASE_DIFFSTAT;
634 else
635 opts->flags &= !REBASE_DIFFSTAT;
636 return 0;
637 }
638
639 if (!strcmp(var, "rebase.autosquash")) {
640 opts->autosquash = git_config_bool(var, value);
641 return 0;
642 }
643
644 if (!strcmp(var, "commit.gpgsign")) {
645 free(opts->gpg_sign_opt);
646 opts->gpg_sign_opt = git_config_bool(var, value) ?
647 xstrdup("-S") : NULL;
648 return 0;
649 }
650
651 if (!strcmp(var, "rebase.autostash")) {
652 opts->autostash = git_config_bool(var, value);
653 return 0;
654 }
655
656 return git_default_config(var, value, data);
657 }
658
659 /*
660 * Determines whether the commits in from..to are linear, i.e. contain
661 * no merge commits. This function *expects* `from` to be an ancestor of
662 * `to`.
663 */
664 static int is_linear_history(struct commit *from, struct commit *to)
665 {
666 while (to && to != from) {
667 parse_commit(to);
668 if (!to->parents)
669 return 1;
670 if (to->parents->next)
671 return 0;
672 to = to->parents->item;
673 }
674 return 1;
675 }
676
677 static int can_fast_forward(struct commit *onto, struct object_id *head_oid,
678 struct object_id *merge_base)
679 {
680 struct commit *head = lookup_commit(the_repository, head_oid);
681 struct commit_list *merge_bases;
682 int res;
683
684 if (!head)
685 return 0;
686
687 merge_bases = get_merge_bases(onto, head);
688 if (merge_bases && !merge_bases->next) {
689 oidcpy(merge_base, &merge_bases->item->object.oid);
690 res = !oidcmp(merge_base, &onto->object.oid);
691 } else {
692 oidcpy(merge_base, &null_oid);
693 res = 0;
694 }
695 free_commit_list(merge_bases);
696 return res && is_linear_history(onto, head);
697 }
698
699 /* -i followed by -m is still -i */
700 static int parse_opt_merge(const struct option *opt, const char *arg, int unset)
701 {
702 struct rebase_options *opts = opt->value;
703
704 if (!is_interactive(opts))
705 opts->type = REBASE_MERGE;
706
707 return 0;
708 }
709
710 /* -i followed by -p is still explicitly interactive, but -p alone is not */
711 static int parse_opt_interactive(const struct option *opt, const char *arg,
712 int unset)
713 {
714 struct rebase_options *opts = opt->value;
715
716 opts->type = REBASE_INTERACTIVE;
717 opts->flags |= REBASE_INTERACTIVE_EXPLICIT;
718
719 return 0;
720 }
721
722 static void NORETURN error_on_missing_default_upstream(void)
723 {
724 struct branch *current_branch = branch_get(NULL);
725
726 printf(_("%s\n"
727 "Please specify which branch you want to rebase against.\n"
728 "See git-rebase(1) for details.\n"
729 "\n"
730 " git rebase '<branch>'\n"
731 "\n"),
732 current_branch ? _("There is no tracking information for "
733 "the current branch.") :
734 _("You are not currently on a branch."));
735
736 if (current_branch) {
737 const char *remote = current_branch->remote_name;
738
739 if (!remote)
740 remote = _("<remote>");
741
742 printf(_("If you wish to set tracking information for this "
743 "branch you can do so with:\n"
744 "\n"
745 " git branch --set-upstream-to=%s/<branch> %s\n"
746 "\n"),
747 remote, current_branch->name);
748 }
749 exit(1);
750 }
751
752 int cmd_rebase(int argc, const char **argv, const char *prefix)
753 {
754 struct rebase_options options = {
755 .type = REBASE_UNSPECIFIED,
756 .flags = REBASE_NO_QUIET,
757 .git_am_opt = STRBUF_INIT,
758 .allow_rerere_autoupdate = -1,
759 .allow_empty_message = 1,
760 .git_format_patch_opt = STRBUF_INIT,
761 };
762 const char *branch_name;
763 int ret, flags, total_argc, in_progress = 0;
764 int ok_to_skip_pre_rebase = 0;
765 struct strbuf msg = STRBUF_INIT;
766 struct strbuf revisions = STRBUF_INIT;
767 struct strbuf buf = STRBUF_INIT;
768 struct object_id merge_base;
769 enum {
770 NO_ACTION,
771 ACTION_CONTINUE,
772 ACTION_SKIP,
773 ACTION_ABORT,
774 ACTION_QUIT,
775 ACTION_EDIT_TODO,
776 ACTION_SHOW_CURRENT_PATCH,
777 } action = NO_ACTION;
778 int committer_date_is_author_date = 0;
779 int ignore_date = 0;
780 int ignore_whitespace = 0;
781 const char *gpg_sign = NULL;
782 int opt_c = -1;
783 struct string_list whitespace = STRING_LIST_INIT_NODUP;
784 struct string_list exec = STRING_LIST_INIT_NODUP;
785 const char *rebase_merges = NULL;
786 int fork_point = -1;
787 struct string_list strategy_options = STRING_LIST_INIT_NODUP;
788 struct object_id squash_onto;
789 char *squash_onto_name = NULL;
790 struct option builtin_rebase_options[] = {
791 OPT_STRING(0, "onto", &options.onto_name,
792 N_("revision"),
793 N_("rebase onto given branch instead of upstream")),
794 OPT_BOOL(0, "no-verify", &ok_to_skip_pre_rebase,
795 N_("allow pre-rebase hook to run")),
796 OPT_NEGBIT('q', "quiet", &options.flags,
797 N_("be quiet. implies --no-stat"),
798 REBASE_NO_QUIET| REBASE_VERBOSE | REBASE_DIFFSTAT),
799 OPT_BIT('v', "verbose", &options.flags,
800 N_("display a diffstat of what changed upstream"),
801 REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
802 {OPTION_NEGBIT, 'n', "no-stat", &options.flags, NULL,
803 N_("do not show diffstat of what changed upstream"),
804 PARSE_OPT_NOARG, NULL, REBASE_DIFFSTAT },
805 OPT_BOOL(0, "ignore-whitespace", &ignore_whitespace,
806 N_("passed to 'git apply'")),
807 OPT_BOOL(0, "signoff", &options.signoff,
808 N_("add a Signed-off-by: line to each commit")),
809 OPT_BOOL(0, "committer-date-is-author-date",
810 &committer_date_is_author_date,
811 N_("passed to 'git am'")),
812 OPT_BOOL(0, "ignore-date", &ignore_date,
813 N_("passed to 'git am'")),
814 OPT_BIT('f', "force-rebase", &options.flags,
815 N_("cherry-pick all commits, even if unchanged"),
816 REBASE_FORCE),
817 OPT_BIT(0, "no-ff", &options.flags,
818 N_("cherry-pick all commits, even if unchanged"),
819 REBASE_FORCE),
820 OPT_CMDMODE(0, "continue", &action, N_("continue"),
821 ACTION_CONTINUE),
822 OPT_CMDMODE(0, "skip", &action,
823 N_("skip current patch and continue"), ACTION_SKIP),
824 OPT_CMDMODE(0, "abort", &action,
825 N_("abort and check out the original branch"),
826 ACTION_ABORT),
827 OPT_CMDMODE(0, "quit", &action,
828 N_("abort but keep HEAD where it is"), ACTION_QUIT),
829 OPT_CMDMODE(0, "edit-todo", &action, N_("edit the todo list "
830 "during an interactive rebase"), ACTION_EDIT_TODO),
831 OPT_CMDMODE(0, "show-current-patch", &action,
832 N_("show the patch file being applied or merged"),
833 ACTION_SHOW_CURRENT_PATCH),
834 { OPTION_CALLBACK, 'm', "merge", &options, NULL,
835 N_("use merging strategies to rebase"),
836 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
837 parse_opt_merge },
838 { OPTION_CALLBACK, 'i', "interactive", &options, NULL,
839 N_("let the user edit the list of commits to rebase"),
840 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
841 parse_opt_interactive },
842 OPT_SET_INT('p', "preserve-merges", &options.type,
843 N_("try to recreate merges instead of ignoring "
844 "them"), REBASE_PRESERVE_MERGES),
845 OPT_BOOL(0, "rerere-autoupdate",
846 &options.allow_rerere_autoupdate,
847 N_("allow rerere to update index with resolved "
848 "conflict")),
849 OPT_BOOL('k', "keep-empty", &options.keep_empty,
850 N_("preserve empty commits during rebase")),
851 OPT_BOOL(0, "autosquash", &options.autosquash,
852 N_("move commits that begin with "
853 "squash!/fixup! under -i")),
854 { OPTION_STRING, 'S', "gpg-sign", &gpg_sign, N_("key-id"),
855 N_("GPG-sign commits"),
856 PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
857 OPT_STRING_LIST(0, "whitespace", &whitespace,
858 N_("whitespace"), N_("passed to 'git apply'")),
859 OPT_SET_INT('C', NULL, &opt_c, N_("passed to 'git apply'"),
860 REBASE_AM),
861 OPT_BOOL(0, "autostash", &options.autostash,
862 N_("automatically stash/stash pop before and after")),
863 OPT_STRING_LIST('x', "exec", &exec, N_("exec"),
864 N_("add exec lines after each commit of the "
865 "editable list")),
866 OPT_BOOL(0, "allow-empty-message",
867 &options.allow_empty_message,
868 N_("allow rebasing commits with empty messages")),
869 {OPTION_STRING, 'r', "rebase-merges", &rebase_merges,
870 N_("mode"),
871 N_("try to rebase merges instead of skipping them"),
872 PARSE_OPT_OPTARG, NULL, (intptr_t)""},
873 OPT_BOOL(0, "fork-point", &fork_point,
874 N_("use 'merge-base --fork-point' to refine upstream")),
875 OPT_STRING('s', "strategy", &options.strategy,
876 N_("strategy"), N_("use the given merge strategy")),
877 OPT_STRING_LIST('X', "strategy-option", &strategy_options,
878 N_("option"),
879 N_("pass the argument through to the merge "
880 "strategy")),
881 OPT_BOOL(0, "root", &options.root,
882 N_("rebase all reachable commits up to the root(s)")),
883 OPT_END(),
884 };
885
886 /*
887 * NEEDSWORK: Once the builtin rebase has been tested enough
888 * and git-legacy-rebase.sh is retired to contrib/, this preamble
889 * can be removed.
890 */
891
892 if (!use_builtin_rebase()) {
893 const char *path = mkpath("%s/git-legacy-rebase",
894 git_exec_path());
895
896 if (sane_execvp(path, (char **)argv) < 0)
897 die_errno(_("could not exec %s"), path);
898 else
899 BUG("sane_execvp() returned???");
900 }
901
902 if (argc == 2 && !strcmp(argv[1], "-h"))
903 usage_with_options(builtin_rebase_usage,
904 builtin_rebase_options);
905
906 prefix = setup_git_directory();
907 trace_repo_setup(prefix);
908 setup_work_tree();
909
910 git_config(rebase_config, &options);
911
912 strbuf_reset(&buf);
913 strbuf_addf(&buf, "%s/applying", apply_dir());
914 if(file_exists(buf.buf))
915 die(_("It looks like 'git am' is in progress. Cannot rebase."));
916
917 if (is_directory(apply_dir())) {
918 options.type = REBASE_AM;
919 options.state_dir = apply_dir();
920 } else if (is_directory(merge_dir())) {
921 strbuf_reset(&buf);
922 strbuf_addf(&buf, "%s/rewritten", merge_dir());
923 if (is_directory(buf.buf)) {
924 options.type = REBASE_PRESERVE_MERGES;
925 options.flags |= REBASE_INTERACTIVE_EXPLICIT;
926 } else {
927 strbuf_reset(&buf);
928 strbuf_addf(&buf, "%s/interactive", merge_dir());
929 if(file_exists(buf.buf)) {
930 options.type = REBASE_INTERACTIVE;
931 options.flags |= REBASE_INTERACTIVE_EXPLICIT;
932 } else
933 options.type = REBASE_MERGE;
934 }
935 options.state_dir = merge_dir();
936 }
937
938 if (options.type != REBASE_UNSPECIFIED)
939 in_progress = 1;
940
941 total_argc = argc;
942 argc = parse_options(argc, argv, prefix,
943 builtin_rebase_options,
944 builtin_rebase_usage, 0);
945
946 if (action != NO_ACTION && total_argc != 2) {
947 usage_with_options(builtin_rebase_usage,
948 builtin_rebase_options);
949 }
950
951 if (argc > 2)
952 usage_with_options(builtin_rebase_usage,
953 builtin_rebase_options);
954
955 if (action != NO_ACTION && !in_progress)
956 die(_("No rebase in progress?"));
957
958 if (action == ACTION_EDIT_TODO && !is_interactive(&options))
959 die(_("The --edit-todo action can only be used during "
960 "interactive rebase."));
961
962 switch (action) {
963 case ACTION_CONTINUE: {
964 struct object_id head;
965 struct lock_file lock_file = LOCK_INIT;
966 int fd;
967
968 options.action = "continue";
969
970 /* Sanity check */
971 if (get_oid("HEAD", &head))
972 die(_("Cannot read HEAD"));
973
974 fd = hold_locked_index(&lock_file, 0);
975 if (read_index(the_repository->index) < 0)
976 die(_("could not read index"));
977 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL,
978 NULL);
979 if (0 <= fd)
980 update_index_if_able(the_repository->index,
981 &lock_file);
982 rollback_lock_file(&lock_file);
983
984 if (has_unstaged_changes(1)) {
985 puts(_("You must edit all merge conflicts and then\n"
986 "mark them as resolved using git add"));
987 exit(1);
988 }
989 if (read_basic_state(&options))
990 exit(1);
991 goto run_rebase;
992 }
993 case ACTION_SKIP: {
994 struct string_list merge_rr = STRING_LIST_INIT_DUP;
995
996 options.action = "skip";
997
998 rerere_clear(&merge_rr);
999 string_list_clear(&merge_rr, 1);
1000
1001 if (reset_head(NULL, "reset", NULL, 0, NULL, NULL) < 0)
1002 die(_("could not discard worktree changes"));
1003 if (read_basic_state(&options))
1004 exit(1);
1005 goto run_rebase;
1006 }
1007 case ACTION_ABORT: {
1008 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1009 options.action = "abort";
1010
1011 rerere_clear(&merge_rr);
1012 string_list_clear(&merge_rr, 1);
1013
1014 if (read_basic_state(&options))
1015 exit(1);
1016 if (reset_head(&options.orig_head, "reset",
1017 options.head_name, 0, NULL, NULL) < 0)
1018 die(_("could not move back to %s"),
1019 oid_to_hex(&options.orig_head));
1020 ret = finish_rebase(&options);
1021 goto cleanup;
1022 }
1023 case ACTION_QUIT: {
1024 strbuf_reset(&buf);
1025 strbuf_addstr(&buf, options.state_dir);
1026 ret = !!remove_dir_recursively(&buf, 0);
1027 if (ret)
1028 die(_("could not remove '%s'"), options.state_dir);
1029 goto cleanup;
1030 }
1031 case ACTION_EDIT_TODO:
1032 options.action = "edit-todo";
1033 options.dont_finish_rebase = 1;
1034 goto run_rebase;
1035 case ACTION_SHOW_CURRENT_PATCH:
1036 options.action = "show-current-patch";
1037 options.dont_finish_rebase = 1;
1038 goto run_rebase;
1039 case NO_ACTION:
1040 break;
1041 default:
1042 BUG("action: %d", action);
1043 }
1044
1045 /* Make sure no rebase is in progress */
1046 if (in_progress) {
1047 const char *last_slash = strrchr(options.state_dir, '/');
1048 const char *state_dir_base =
1049 last_slash ? last_slash + 1 : options.state_dir;
1050 const char *cmd_live_rebase =
1051 "git rebase (--continue | --abort | --skip)";
1052 strbuf_reset(&buf);
1053 strbuf_addf(&buf, "rm -fr \"%s\"", options.state_dir);
1054 die(_("It seems that there is already a %s directory, and\n"
1055 "I wonder if you are in the middle of another rebase. "
1056 "If that is the\n"
1057 "case, please try\n\t%s\n"
1058 "If that is not the case, please\n\t%s\n"
1059 "and run me again. I am stopping in case you still "
1060 "have something\n"
1061 "valuable there.\n"),
1062 state_dir_base, cmd_live_rebase, buf.buf);
1063 }
1064
1065 if (!(options.flags & REBASE_NO_QUIET))
1066 strbuf_addstr(&options.git_am_opt, " -q");
1067
1068 if (committer_date_is_author_date) {
1069 strbuf_addstr(&options.git_am_opt,
1070 " --committer-date-is-author-date");
1071 options.flags |= REBASE_FORCE;
1072 }
1073
1074 if (ignore_whitespace)
1075 strbuf_addstr(&options.git_am_opt, " --ignore-whitespace");
1076
1077 if (ignore_date) {
1078 strbuf_addstr(&options.git_am_opt, " --ignore-date");
1079 options.flags |= REBASE_FORCE;
1080 }
1081
1082 if (options.keep_empty)
1083 imply_interactive(&options, "--keep-empty");
1084
1085 if (gpg_sign) {
1086 free(options.gpg_sign_opt);
1087 options.gpg_sign_opt = xstrfmt("-S%s", gpg_sign);
1088 }
1089
1090 if (opt_c >= 0)
1091 strbuf_addf(&options.git_am_opt, " -C%d", opt_c);
1092
1093 if (whitespace.nr) {
1094 int i;
1095
1096 for (i = 0; i < whitespace.nr; i++) {
1097 const char *item = whitespace.items[i].string;
1098
1099 strbuf_addf(&options.git_am_opt, " --whitespace=%s",
1100 item);
1101
1102 if ((!strcmp(item, "fix")) || (!strcmp(item, "strip")))
1103 options.flags |= REBASE_FORCE;
1104 }
1105 }
1106
1107 if (exec.nr) {
1108 int i;
1109
1110 imply_interactive(&options, "--exec");
1111
1112 strbuf_reset(&buf);
1113 for (i = 0; i < exec.nr; i++)
1114 strbuf_addf(&buf, "exec %s\n", exec.items[i].string);
1115 options.cmd = xstrdup(buf.buf);
1116 }
1117
1118 if (rebase_merges) {
1119 if (!*rebase_merges)
1120 ; /* default mode; do nothing */
1121 else if (!strcmp("rebase-cousins", rebase_merges))
1122 options.rebase_cousins = 1;
1123 else if (strcmp("no-rebase-cousins", rebase_merges))
1124 die(_("Unknown mode: %s"), rebase_merges);
1125 options.rebase_merges = 1;
1126 imply_interactive(&options, "--rebase-merges");
1127 }
1128
1129 if (strategy_options.nr) {
1130 int i;
1131
1132 if (!options.strategy)
1133 options.strategy = "recursive";
1134
1135 strbuf_reset(&buf);
1136 for (i = 0; i < strategy_options.nr; i++)
1137 strbuf_addf(&buf, " --%s",
1138 strategy_options.items[i].string);
1139 options.strategy_opts = xstrdup(buf.buf);
1140 }
1141
1142 if (options.strategy) {
1143 options.strategy = xstrdup(options.strategy);
1144 switch (options.type) {
1145 case REBASE_AM:
1146 die(_("--strategy requires --merge or --interactive"));
1147 case REBASE_MERGE:
1148 case REBASE_INTERACTIVE:
1149 case REBASE_PRESERVE_MERGES:
1150 /* compatible */
1151 break;
1152 case REBASE_UNSPECIFIED:
1153 options.type = REBASE_MERGE;
1154 break;
1155 default:
1156 BUG("unhandled rebase type (%d)", options.type);
1157 }
1158 }
1159
1160 if (options.root && !options.onto_name)
1161 imply_interactive(&options, "--root without --onto");
1162
1163 if (isatty(2) && options.flags & REBASE_NO_QUIET)
1164 strbuf_addstr(&options.git_format_patch_opt, " --progress");
1165
1166 switch (options.type) {
1167 case REBASE_MERGE:
1168 case REBASE_INTERACTIVE:
1169 case REBASE_PRESERVE_MERGES:
1170 options.state_dir = merge_dir();
1171 break;
1172 case REBASE_AM:
1173 options.state_dir = apply_dir();
1174 break;
1175 default:
1176 /* the default rebase backend is `--am` */
1177 options.type = REBASE_AM;
1178 options.state_dir = apply_dir();
1179 break;
1180 }
1181
1182 if (options.git_am_opt.len) {
1183 const char *p;
1184
1185 /* all am options except -q are compatible only with --am */
1186 strbuf_reset(&buf);
1187 strbuf_addbuf(&buf, &options.git_am_opt);
1188 strbuf_addch(&buf, ' ');
1189 while ((p = strstr(buf.buf, " -q ")))
1190 strbuf_splice(&buf, p - buf.buf, 4, " ", 1);
1191 strbuf_trim(&buf);
1192
1193 if (is_interactive(&options) && buf.len)
1194 die(_("error: cannot combine interactive options "
1195 "(--interactive, --exec, --rebase-merges, "
1196 "--preserve-merges, --keep-empty, --root + "
1197 "--onto) with am options (%s)"), buf.buf);
1198 if (options.type == REBASE_MERGE && buf.len)
1199 die(_("error: cannot combine merge options (--merge, "
1200 "--strategy, --strategy-option) with am options "
1201 "(%s)"), buf.buf);
1202 }
1203
1204 if (options.signoff) {
1205 if (options.type == REBASE_PRESERVE_MERGES)
1206 die("cannot combine '--signoff' with "
1207 "'--preserve-merges'");
1208 strbuf_addstr(&options.git_am_opt, " --signoff");
1209 options.flags |= REBASE_FORCE;
1210 }
1211
1212 if (options.type == REBASE_PRESERVE_MERGES)
1213 /*
1214 * Note: incompatibility with --signoff handled in signoff block above
1215 * Note: incompatibility with --interactive is just a strong warning;
1216 * git-rebase.txt caveats with "unless you know what you are doing"
1217 */
1218 if (options.rebase_merges)
1219 die(_("error: cannot combine '--preserve-merges' with "
1220 "'--rebase-merges'"));
1221
1222 if (options.rebase_merges) {
1223 if (strategy_options.nr)
1224 die(_("error: cannot combine '--rebase-merges' with "
1225 "'--strategy-option'"));
1226 if (options.strategy)
1227 die(_("error: cannot combine '--rebase-merges' with "
1228 "'--strategy'"));
1229 }
1230
1231 if (!options.root) {
1232 if (argc < 1) {
1233 struct branch *branch;
1234
1235 branch = branch_get(NULL);
1236 options.upstream_name = branch_get_upstream(branch,
1237 NULL);
1238 if (!options.upstream_name)
1239 error_on_missing_default_upstream();
1240 if (fork_point < 0)
1241 fork_point = 1;
1242 } else {
1243 options.upstream_name = argv[0];
1244 argc--;
1245 argv++;
1246 if (!strcmp(options.upstream_name, "-"))
1247 options.upstream_name = "@{-1}";
1248 }
1249 options.upstream = peel_committish(options.upstream_name);
1250 if (!options.upstream)
1251 die(_("invalid upstream '%s'"), options.upstream_name);
1252 options.upstream_arg = options.upstream_name;
1253 } else {
1254 if (!options.onto_name) {
1255 if (commit_tree("", 0, the_hash_algo->empty_tree, NULL,
1256 &squash_onto, NULL, NULL) < 0)
1257 die(_("Could not create new root commit"));
1258 options.squash_onto = &squash_onto;
1259 options.onto_name = squash_onto_name =
1260 xstrdup(oid_to_hex(&squash_onto));
1261 }
1262 options.upstream_name = NULL;
1263 options.upstream = NULL;
1264 if (argc > 1)
1265 usage_with_options(builtin_rebase_usage,
1266 builtin_rebase_options);
1267 options.upstream_arg = "--root";
1268 }
1269
1270 /* Make sure the branch to rebase onto is valid. */
1271 if (!options.onto_name)
1272 options.onto_name = options.upstream_name;
1273 if (strstr(options.onto_name, "...")) {
1274 if (get_oid_mb(options.onto_name, &merge_base) < 0)
1275 die(_("'%s': need exactly one merge base"),
1276 options.onto_name);
1277 options.onto = lookup_commit_or_die(&merge_base,
1278 options.onto_name);
1279 } else {
1280 options.onto = peel_committish(options.onto_name);
1281 if (!options.onto)
1282 die(_("Does not point to a valid commit '%s'"),
1283 options.onto_name);
1284 }
1285
1286 /*
1287 * If the branch to rebase is given, that is the branch we will rebase
1288 * branch_name -- branch/commit being rebased, or
1289 * HEAD (already detached)
1290 * orig_head -- commit object name of tip of the branch before rebasing
1291 * head_name -- refs/heads/<that-branch> or NULL (detached HEAD)
1292 */
1293 if (argc == 1) {
1294 /* Is it "rebase other branchname" or "rebase other commit"? */
1295 branch_name = argv[0];
1296 options.switch_to = argv[0];
1297
1298 /* Is it a local branch? */
1299 strbuf_reset(&buf);
1300 strbuf_addf(&buf, "refs/heads/%s", branch_name);
1301 if (!read_ref(buf.buf, &options.orig_head))
1302 options.head_name = xstrdup(buf.buf);
1303 /* If not is it a valid ref (branch or commit)? */
1304 else if (!get_oid(branch_name, &options.orig_head))
1305 options.head_name = NULL;
1306 else
1307 die(_("fatal: no such branch/commit '%s'"),
1308 branch_name);
1309 } else if (argc == 0) {
1310 /* Do not need to switch branches, we are already on it. */
1311 options.head_name =
1312 xstrdup_or_null(resolve_ref_unsafe("HEAD", 0, NULL,
1313 &flags));
1314 if (!options.head_name)
1315 die(_("No such ref: %s"), "HEAD");
1316 if (flags & REF_ISSYMREF) {
1317 if (!skip_prefix(options.head_name,
1318 "refs/heads/", &branch_name))
1319 branch_name = options.head_name;
1320
1321 } else {
1322 free(options.head_name);
1323 options.head_name = NULL;
1324 branch_name = "HEAD";
1325 }
1326 if (get_oid("HEAD", &options.orig_head))
1327 die(_("Could not resolve HEAD to a revision"));
1328 } else
1329 BUG("unexpected number of arguments left to parse");
1330
1331 if (fork_point > 0) {
1332 struct commit *head =
1333 lookup_commit_reference(the_repository,
1334 &options.orig_head);
1335 options.restrict_revision =
1336 get_fork_point(options.upstream_name, head);
1337 }
1338
1339 if (read_index(the_repository->index) < 0)
1340 die(_("could not read index"));
1341
1342 if (options.autostash) {
1343 struct lock_file lock_file = LOCK_INIT;
1344 int fd;
1345
1346 fd = hold_locked_index(&lock_file, 0);
1347 refresh_cache(REFRESH_QUIET);
1348 if (0 <= fd)
1349 update_index_if_able(&the_index, &lock_file);
1350 rollback_lock_file(&lock_file);
1351
1352 if (has_unstaged_changes(0) || has_uncommitted_changes(0)) {
1353 const char *autostash =
1354 state_dir_path("autostash", &options);
1355 struct child_process stash = CHILD_PROCESS_INIT;
1356 struct object_id oid;
1357 struct commit *head =
1358 lookup_commit_reference(the_repository,
1359 &options.orig_head);
1360
1361 argv_array_pushl(&stash.args,
1362 "stash", "create", "autostash", NULL);
1363 stash.git_cmd = 1;
1364 stash.no_stdin = 1;
1365 strbuf_reset(&buf);
1366 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
1367 die(_("Cannot autostash"));
1368 strbuf_trim_trailing_newline(&buf);
1369 if (get_oid(buf.buf, &oid))
1370 die(_("Unexpected stash response: '%s'"),
1371 buf.buf);
1372 strbuf_reset(&buf);
1373 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
1374
1375 if (safe_create_leading_directories_const(autostash))
1376 die(_("Could not create directory for '%s'"),
1377 options.state_dir);
1378 write_file(autostash, "%s", buf.buf);
1379 printf(_("Created autostash: %s\n"), buf.buf);
1380 if (reset_head(&head->object.oid, "reset --hard",
1381 NULL, 0, NULL, NULL) < 0)
1382 die(_("could not reset --hard"));
1383 printf(_("HEAD is now at %s"),
1384 find_unique_abbrev(&head->object.oid,
1385 DEFAULT_ABBREV));
1386 strbuf_reset(&buf);
1387 pp_commit_easy(CMIT_FMT_ONELINE, head, &buf);
1388 if (buf.len > 0)
1389 printf(" %s", buf.buf);
1390 putchar('\n');
1391
1392 if (discard_index(the_repository->index) < 0 ||
1393 read_index(the_repository->index) < 0)
1394 die(_("could not read index"));
1395 }
1396 }
1397
1398 if (require_clean_work_tree("rebase",
1399 _("Please commit or stash them."), 1, 1)) {
1400 ret = 1;
1401 goto cleanup;
1402 }
1403
1404 /*
1405 * Now we are rebasing commits upstream..orig_head (or with --root,
1406 * everything leading up to orig_head) on top of onto.
1407 */
1408
1409 /*
1410 * Check if we are already based on onto with linear history,
1411 * but this should be done only when upstream and onto are the same
1412 * and if this is not an interactive rebase.
1413 */
1414 if (can_fast_forward(options.onto, &options.orig_head, &merge_base) &&
1415 !is_interactive(&options) && !options.restrict_revision &&
1416 options.upstream &&
1417 !oidcmp(&options.upstream->object.oid, &options.onto->object.oid)) {
1418 int flag;
1419
1420 if (!(options.flags & REBASE_FORCE)) {
1421 /* Lazily switch to the target branch if needed... */
1422 if (options.switch_to) {
1423 struct object_id oid;
1424
1425 if (get_oid(options.switch_to, &oid) < 0) {
1426 ret = !!error(_("could not parse '%s'"),
1427 options.switch_to);
1428 goto cleanup;
1429 }
1430
1431 strbuf_reset(&buf);
1432 strbuf_addf(&buf, "rebase: checkout %s",
1433 options.switch_to);
1434 if (reset_head(&oid, "checkout",
1435 options.head_name, 0,
1436 NULL, NULL) < 0) {
1437 ret = !!error(_("could not switch to "
1438 "%s"),
1439 options.switch_to);
1440 goto cleanup;
1441 }
1442 }
1443
1444 if (!(options.flags & REBASE_NO_QUIET))
1445 ; /* be quiet */
1446 else if (!strcmp(branch_name, "HEAD") &&
1447 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
1448 puts(_("HEAD is up to date."));
1449 else
1450 printf(_("Current branch %s is up to date.\n"),
1451 branch_name);
1452 ret = !!finish_rebase(&options);
1453 goto cleanup;
1454 } else if (!(options.flags & REBASE_NO_QUIET))
1455 ; /* be quiet */
1456 else if (!strcmp(branch_name, "HEAD") &&
1457 resolve_ref_unsafe("HEAD", 0, NULL, &flag))
1458 puts(_("HEAD is up to date, rebase forced."));
1459 else
1460 printf(_("Current branch %s is up to date, rebase "
1461 "forced.\n"), branch_name);
1462 }
1463
1464 /* If a hook exists, give it a chance to interrupt*/
1465 if (!ok_to_skip_pre_rebase &&
1466 run_hook_le(NULL, "pre-rebase", options.upstream_arg,
1467 argc ? argv[0] : NULL, NULL))
1468 die(_("The pre-rebase hook refused to rebase."));
1469
1470 if (options.flags & REBASE_DIFFSTAT) {
1471 struct diff_options opts;
1472
1473 if (options.flags & REBASE_VERBOSE)
1474 printf(_("Changes from %s to %s:\n"),
1475 oid_to_hex(&merge_base),
1476 oid_to_hex(&options.onto->object.oid));
1477
1478 /* We want color (if set), but no pager */
1479 diff_setup(&opts);
1480 opts.stat_width = -1; /* use full terminal width */
1481 opts.stat_graph_width = -1; /* respect statGraphWidth config */
1482 opts.output_format |=
1483 DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1484 opts.detect_rename = DIFF_DETECT_RENAME;
1485 diff_setup_done(&opts);
1486 diff_tree_oid(&merge_base, &options.onto->object.oid,
1487 "", &opts);
1488 diffcore_std(&opts);
1489 diff_flush(&opts);
1490 }
1491
1492 if (is_interactive(&options))
1493 goto run_rebase;
1494
1495 /* Detach HEAD and reset the tree */
1496 if (options.flags & REBASE_NO_QUIET)
1497 printf(_("First, rewinding head to replay your work on top of "
1498 "it...\n"));
1499
1500 strbuf_addf(&msg, "rebase: checkout %s", options.onto_name);
1501 if (reset_head(&options.onto->object.oid, "checkout", NULL, 1,
1502 NULL, msg.buf))
1503 die(_("Could not detach HEAD"));
1504 strbuf_release(&msg);
1505
1506 /*
1507 * If the onto is a proper descendant of the tip of the branch, then
1508 * we just fast-forwarded.
1509 */
1510 strbuf_reset(&msg);
1511 if (!oidcmp(&merge_base, &options.orig_head)) {
1512 printf(_("Fast-forwarded %s to %s. \n"),
1513 branch_name, options.onto_name);
1514 strbuf_addf(&msg, "rebase finished: %s onto %s",
1515 options.head_name ? options.head_name : "detached HEAD",
1516 oid_to_hex(&options.onto->object.oid));
1517 reset_head(NULL, "Fast-forwarded", options.head_name, 0,
1518 "HEAD", msg.buf);
1519 strbuf_release(&msg);
1520 ret = !!finish_rebase(&options);
1521 goto cleanup;
1522 }
1523
1524 strbuf_addf(&revisions, "%s..%s",
1525 options.root ? oid_to_hex(&options.onto->object.oid) :
1526 (options.restrict_revision ?
1527 oid_to_hex(&options.restrict_revision->object.oid) :
1528 oid_to_hex(&options.upstream->object.oid)),
1529 oid_to_hex(&options.orig_head));
1530
1531 options.revisions = revisions.buf;
1532
1533 run_rebase:
1534 ret = !!run_specific_rebase(&options);
1535
1536 cleanup:
1537 strbuf_release(&revisions);
1538 free(options.head_name);
1539 free(options.gpg_sign_opt);
1540 free(options.cmd);
1541 free(squash_onto_name);
1542 return ret;
1543 }