builtin rebase: support `--autosquash`
[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 "rerere.h"
25
26 static char const * const builtin_rebase_usage[] = {
27         N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
28                 "[<upstream>] [<branch>]"),
29         N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
30                 "--root [<branch>]"),
31         N_("git rebase --continue | --abort | --skip | --edit-todo"),
32         NULL
33 };
34
35 static GIT_PATH_FUNC(apply_dir, "rebase-apply")
36 static GIT_PATH_FUNC(merge_dir, "rebase-merge")
37
38 enum rebase_type {
39         REBASE_UNSPECIFIED = -1,
40         REBASE_AM,
41         REBASE_MERGE,
42         REBASE_INTERACTIVE,
43         REBASE_PRESERVE_MERGES
44 };
45
46 static int use_builtin_rebase(void)
47 {
48         struct child_process cp = CHILD_PROCESS_INIT;
49         struct strbuf out = STRBUF_INIT;
50         int ret;
51
52         argv_array_pushl(&cp.args,
53                          "config", "--bool", "rebase.usebuiltin", NULL);
54         cp.git_cmd = 1;
55         if (capture_command(&cp, &out, 6)) {
56                 strbuf_release(&out);
57                 return 0;
58         }
59
60         strbuf_trim(&out);
61         ret = !strcmp("true", out.buf);
62         strbuf_release(&out);
63         return ret;
64 }
65
66 static int apply_autostash(void)
67 {
68         warning("TODO");
69         return 0;
70 }
71
72 struct rebase_options {
73         enum rebase_type type;
74         const char *state_dir;
75         struct commit *upstream;
76         const char *upstream_name;
77         const char *upstream_arg;
78         char *head_name;
79         struct object_id orig_head;
80         struct commit *onto;
81         const char *onto_name;
82         const char *revisions;
83         const char *switch_to;
84         int root;
85         struct commit *restrict_revision;
86         int dont_finish_rebase;
87         enum {
88                 REBASE_NO_QUIET = 1<<0,
89                 REBASE_VERBOSE = 1<<1,
90                 REBASE_DIFFSTAT = 1<<2,
91                 REBASE_FORCE = 1<<3,
92                 REBASE_INTERACTIVE_EXPLICIT = 1<<4,
93         } flags;
94         struct strbuf git_am_opt;
95         const char *action;
96         int signoff;
97         int allow_rerere_autoupdate;
98         int keep_empty;
99         int autosquash;
100 };
101
102 static int is_interactive(struct rebase_options *opts)
103 {
104         return opts->type == REBASE_INTERACTIVE ||
105                 opts->type == REBASE_PRESERVE_MERGES;
106 }
107
108 static void imply_interactive(struct rebase_options *opts, const char *option)
109 {
110         switch (opts->type) {
111         case REBASE_AM:
112                 die(_("%s requires an interactive rebase"), option);
113                 break;
114         case REBASE_INTERACTIVE:
115         case REBASE_PRESERVE_MERGES:
116                 break;
117         case REBASE_MERGE:
118                 /* we silently *upgrade* --merge to --interactive if needed */
119         default:
120                 opts->type = REBASE_INTERACTIVE; /* implied */
121                 break;
122         }
123 }
124
125 /* Returns the filename prefixed by the state_dir */
126 static const char *state_dir_path(const char *filename, struct rebase_options *opts)
127 {
128         static struct strbuf path = STRBUF_INIT;
129         static size_t prefix_len;
130
131         if (!prefix_len) {
132                 strbuf_addf(&path, "%s/", opts->state_dir);
133                 prefix_len = path.len;
134         }
135
136         strbuf_setlen(&path, prefix_len);
137         strbuf_addstr(&path, filename);
138         return path.buf;
139 }
140
141 /* Read one file, then strip line endings */
142 static int read_one(const char *path, struct strbuf *buf)
143 {
144         if (strbuf_read_file(buf, path, 0) < 0)
145                 return error_errno(_("could not read '%s'"), path);
146         strbuf_trim_trailing_newline(buf);
147         return 0;
148 }
149
150 /* Initialize the rebase options from the state directory. */
151 static int read_basic_state(struct rebase_options *opts)
152 {
153         struct strbuf head_name = STRBUF_INIT;
154         struct strbuf buf = STRBUF_INIT;
155         struct object_id oid;
156
157         if (read_one(state_dir_path("head-name", opts), &head_name) ||
158             read_one(state_dir_path("onto", opts), &buf))
159                 return -1;
160         opts->head_name = starts_with(head_name.buf, "refs/") ?
161                 xstrdup(head_name.buf) : NULL;
162         strbuf_release(&head_name);
163         if (get_oid(buf.buf, &oid))
164                 return error(_("could not get 'onto': '%s'"), buf.buf);
165         opts->onto = lookup_commit_or_die(&oid, buf.buf);
166
167         /*
168          * We always write to orig-head, but interactive rebase used to write to
169          * head. Fall back to reading from head to cover for the case that the
170          * user upgraded git with an ongoing interactive rebase.
171          */
172         strbuf_reset(&buf);
173         if (file_exists(state_dir_path("orig-head", opts))) {
174                 if (read_one(state_dir_path("orig-head", opts), &buf))
175                         return -1;
176         } else if (read_one(state_dir_path("head", opts), &buf))
177                 return -1;
178         if (get_oid(buf.buf, &opts->orig_head))
179                 return error(_("invalid orig-head: '%s'"), buf.buf);
180
181         strbuf_reset(&buf);
182         if (read_one(state_dir_path("quiet", opts), &buf))
183                 return -1;
184         if (buf.len)
185                 opts->flags &= ~REBASE_NO_QUIET;
186         else
187                 opts->flags |= REBASE_NO_QUIET;
188
189         if (file_exists(state_dir_path("verbose", opts)))
190                 opts->flags |= REBASE_VERBOSE;
191
192         if (file_exists(state_dir_path("signoff", opts))) {
193                 opts->signoff = 1;
194                 opts->flags |= REBASE_FORCE;
195         }
196
197         if (file_exists(state_dir_path("allow_rerere_autoupdate", opts))) {
198                 strbuf_reset(&buf);
199                 if (read_one(state_dir_path("allow_rerere_autoupdate", opts),
200                             &buf))
201                         return -1;
202                 if (!strcmp(buf.buf, "--rerere-autoupdate"))
203                         opts->allow_rerere_autoupdate = 1;
204                 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
205                         opts->allow_rerere_autoupdate = 0;
206                 else
207                         warning(_("ignoring invalid allow_rerere_autoupdate: "
208                                   "'%s'"), buf.buf);
209         } else
210                 opts->allow_rerere_autoupdate = -1;
211
212         strbuf_release(&buf);
213
214         return 0;
215 }
216
217 static int finish_rebase(struct rebase_options *opts)
218 {
219         struct strbuf dir = STRBUF_INIT;
220         const char *argv_gc_auto[] = { "gc", "--auto", NULL };
221
222         delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
223         apply_autostash();
224         close_all_packs(the_repository->objects);
225         /*
226          * We ignore errors in 'gc --auto', since the
227          * user should see them.
228          */
229         run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
230         strbuf_addstr(&dir, opts->state_dir);
231         remove_dir_recursively(&dir, 0);
232         strbuf_release(&dir);
233
234         return 0;
235 }
236
237 static struct commit *peel_committish(const char *name)
238 {
239         struct object *obj;
240         struct object_id oid;
241
242         if (get_oid(name, &oid))
243                 return NULL;
244         obj = parse_object(the_repository, &oid);
245         return (struct commit *)peel_to_type(name, 0, obj, OBJ_COMMIT);
246 }
247
248 static void add_var(struct strbuf *buf, const char *name, const char *value)
249 {
250         if (!value)
251                 strbuf_addf(buf, "unset %s; ", name);
252         else {
253                 strbuf_addf(buf, "%s=", name);
254                 sq_quote_buf(buf, value);
255                 strbuf_addstr(buf, "; ");
256         }
257 }
258
259 static int run_specific_rebase(struct rebase_options *opts)
260 {
261         const char *argv[] = { NULL, NULL };
262         struct strbuf script_snippet = STRBUF_INIT;
263         int status;
264         const char *backend, *backend_func;
265
266         add_var(&script_snippet, "GIT_DIR", absolute_path(get_git_dir()));
267         add_var(&script_snippet, "state_dir", opts->state_dir);
268
269         add_var(&script_snippet, "upstream_name", opts->upstream_name);
270         add_var(&script_snippet, "upstream", opts->upstream ?
271                 oid_to_hex(&opts->upstream->object.oid) : NULL);
272         add_var(&script_snippet, "head_name",
273                 opts->head_name ? opts->head_name : "detached HEAD");
274         add_var(&script_snippet, "orig_head", oid_to_hex(&opts->orig_head));
275         add_var(&script_snippet, "onto", opts->onto ?
276                 oid_to_hex(&opts->onto->object.oid) : NULL);
277         add_var(&script_snippet, "onto_name", opts->onto_name);
278         add_var(&script_snippet, "revisions", opts->revisions);
279         add_var(&script_snippet, "restrict_revision", opts->restrict_revision ?
280                 oid_to_hex(&opts->restrict_revision->object.oid) : NULL);
281         add_var(&script_snippet, "GIT_QUIET",
282                 opts->flags & REBASE_NO_QUIET ? "" : "t");
283         add_var(&script_snippet, "git_am_opt", opts->git_am_opt.buf);
284         add_var(&script_snippet, "verbose",
285                 opts->flags & REBASE_VERBOSE ? "t" : "");
286         add_var(&script_snippet, "diffstat",
287                 opts->flags & REBASE_DIFFSTAT ? "t" : "");
288         add_var(&script_snippet, "force_rebase",
289                 opts->flags & REBASE_FORCE ? "t" : "");
290         if (opts->switch_to)
291                 add_var(&script_snippet, "switch_to", opts->switch_to);
292         add_var(&script_snippet, "action", opts->action ? opts->action : "");
293         add_var(&script_snippet, "signoff", opts->signoff ? "--signoff" : "");
294         add_var(&script_snippet, "allow_rerere_autoupdate",
295                 opts->allow_rerere_autoupdate < 0 ? "" :
296                 opts->allow_rerere_autoupdate ?
297                 "--rerere-autoupdate" : "--no-rerere-autoupdate");
298         add_var(&script_snippet, "keep_empty", opts->keep_empty ? "yes" : "");
299         add_var(&script_snippet, "autosquash", opts->autosquash ? "t" : "");
300
301         switch (opts->type) {
302         case REBASE_AM:
303                 backend = "git-rebase--am";
304                 backend_func = "git_rebase__am";
305                 break;
306         case REBASE_INTERACTIVE:
307                 backend = "git-rebase--interactive";
308                 backend_func = "git_rebase__interactive";
309                 break;
310         case REBASE_MERGE:
311                 backend = "git-rebase--merge";
312                 backend_func = "git_rebase__merge";
313                 break;
314         case REBASE_PRESERVE_MERGES:
315                 backend = "git-rebase--preserve-merges";
316                 backend_func = "git_rebase__preserve_merges";
317                 break;
318         default:
319                 BUG("Unhandled rebase type %d", opts->type);
320                 break;
321         }
322
323         strbuf_addf(&script_snippet,
324                     ". git-sh-setup && . git-rebase--common &&"
325                     " . %s && %s", backend, backend_func);
326         argv[0] = script_snippet.buf;
327
328         status = run_command_v_opt(argv, RUN_USING_SHELL);
329         if (opts->dont_finish_rebase)
330                 ; /* do nothing */
331         else if (status == 0) {
332                 if (!file_exists(state_dir_path("stopped-sha", opts)))
333                         finish_rebase(opts);
334         } else if (status == 2) {
335                 struct strbuf dir = STRBUF_INIT;
336
337                 apply_autostash();
338                 strbuf_addstr(&dir, opts->state_dir);
339                 remove_dir_recursively(&dir, 0);
340                 strbuf_release(&dir);
341                 die("Nothing to do");
342         }
343
344         strbuf_release(&script_snippet);
345
346         return status ? -1 : 0;
347 }
348
349 #define GIT_REFLOG_ACTION_ENVIRONMENT "GIT_REFLOG_ACTION"
350
351 static int reset_head(struct object_id *oid, const char *action,
352                       const char *switch_to_branch, int detach_head)
353 {
354         struct object_id head_oid;
355         struct tree_desc desc;
356         struct lock_file lock = LOCK_INIT;
357         struct unpack_trees_options unpack_tree_opts;
358         struct tree *tree;
359         const char *reflog_action;
360         struct strbuf msg = STRBUF_INIT;
361         size_t prefix_len;
362         struct object_id *orig = NULL, oid_orig,
363                 *old_orig = NULL, oid_old_orig;
364         int ret = 0;
365
366         if (switch_to_branch && !starts_with(switch_to_branch, "refs/"))
367                 BUG("Not a fully qualified branch: '%s'", switch_to_branch);
368
369         if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0)
370                 return -1;
371
372         if (!oid) {
373                 if (get_oid("HEAD", &head_oid)) {
374                         rollback_lock_file(&lock);
375                         return error(_("could not determine HEAD revision"));
376                 }
377                 oid = &head_oid;
378         }
379
380         memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
381         setup_unpack_trees_porcelain(&unpack_tree_opts, action);
382         unpack_tree_opts.head_idx = 1;
383         unpack_tree_opts.src_index = the_repository->index;
384         unpack_tree_opts.dst_index = the_repository->index;
385         unpack_tree_opts.fn = oneway_merge;
386         unpack_tree_opts.update = 1;
387         unpack_tree_opts.merge = 1;
388         if (!detach_head)
389                 unpack_tree_opts.reset = 1;
390
391         if (read_index_unmerged(the_repository->index) < 0) {
392                 rollback_lock_file(&lock);
393                 return error(_("could not read index"));
394         }
395
396         if (!fill_tree_descriptor(&desc, oid)) {
397                 error(_("failed to find tree of %s"), oid_to_hex(oid));
398                 rollback_lock_file(&lock);
399                 free((void *)desc.buffer);
400                 return -1;
401         }
402
403         if (unpack_trees(1, &desc, &unpack_tree_opts)) {
404                 rollback_lock_file(&lock);
405                 free((void *)desc.buffer);
406                 return -1;
407         }
408
409         tree = parse_tree_indirect(oid);
410         prime_cache_tree(the_repository->index, tree);
411
412         if (write_locked_index(the_repository->index, &lock, COMMIT_LOCK) < 0)
413                 ret = error(_("could not write index"));
414         free((void *)desc.buffer);
415
416         if (ret)
417                 return ret;
418
419         reflog_action = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
420         strbuf_addf(&msg, "%s: ", reflog_action ? reflog_action : "rebase");
421         prefix_len = msg.len;
422
423         if (!get_oid("ORIG_HEAD", &oid_old_orig))
424                 old_orig = &oid_old_orig;
425         if (!get_oid("HEAD", &oid_orig)) {
426                 orig = &oid_orig;
427                 strbuf_addstr(&msg, "updating ORIG_HEAD");
428                 update_ref(msg.buf, "ORIG_HEAD", orig, old_orig, 0,
429                            UPDATE_REFS_MSG_ON_ERR);
430         } else if (old_orig)
431                 delete_ref(NULL, "ORIG_HEAD", old_orig, 0);
432         strbuf_setlen(&msg, prefix_len);
433         strbuf_addstr(&msg, "updating HEAD");
434         if (!switch_to_branch)
435                 ret = update_ref(msg.buf, "HEAD", oid, orig, REF_NO_DEREF,
436                                  UPDATE_REFS_MSG_ON_ERR);
437         else {
438                 ret = create_symref("HEAD", switch_to_branch, msg.buf);
439                 if (!ret)
440                         ret = update_ref(msg.buf, "HEAD", oid, NULL, 0,
441                                          UPDATE_REFS_MSG_ON_ERR);
442         }
443
444         strbuf_release(&msg);
445         return ret;
446 }
447
448 static int rebase_config(const char *var, const char *value, void *data)
449 {
450         struct rebase_options *opts = data;
451
452         if (!strcmp(var, "rebase.stat")) {
453                 if (git_config_bool(var, value))
454                         opts->flags |= REBASE_DIFFSTAT;
455                 else
456                         opts->flags &= !REBASE_DIFFSTAT;
457                 return 0;
458         }
459
460         if (!strcmp(var, "rebase.autosquash")) {
461                 opts->autosquash = git_config_bool(var, value);
462                 return 0;
463         }
464
465         return git_default_config(var, value, data);
466 }
467
468 /*
469  * Determines whether the commits in from..to are linear, i.e. contain
470  * no merge commits. This function *expects* `from` to be an ancestor of
471  * `to`.
472  */
473 static int is_linear_history(struct commit *from, struct commit *to)
474 {
475         while (to && to != from) {
476                 parse_commit(to);
477                 if (!to->parents)
478                         return 1;
479                 if (to->parents->next)
480                         return 0;
481                 to = to->parents->item;
482         }
483         return 1;
484 }
485
486 static int can_fast_forward(struct commit *onto, struct object_id *head_oid,
487                             struct object_id *merge_base)
488 {
489         struct commit *head = lookup_commit(the_repository, head_oid);
490         struct commit_list *merge_bases;
491         int res;
492
493         if (!head)
494                 return 0;
495
496         merge_bases = get_merge_bases(onto, head);
497         if (merge_bases && !merge_bases->next) {
498                 oidcpy(merge_base, &merge_bases->item->object.oid);
499                 res = !oidcmp(merge_base, &onto->object.oid);
500         } else {
501                 oidcpy(merge_base, &null_oid);
502                 res = 0;
503         }
504         free_commit_list(merge_bases);
505         return res && is_linear_history(onto, head);
506 }
507
508 /* -i followed by -m is still -i */
509 static int parse_opt_merge(const struct option *opt, const char *arg, int unset)
510 {
511         struct rebase_options *opts = opt->value;
512
513         if (!is_interactive(opts))
514                 opts->type = REBASE_MERGE;
515
516         return 0;
517 }
518
519 /* -i followed by -p is still explicitly interactive, but -p alone is not */
520 static int parse_opt_interactive(const struct option *opt, const char *arg,
521                                  int unset)
522 {
523         struct rebase_options *opts = opt->value;
524
525         opts->type = REBASE_INTERACTIVE;
526         opts->flags |= REBASE_INTERACTIVE_EXPLICIT;
527
528         return 0;
529 }
530
531 int cmd_rebase(int argc, const char **argv, const char *prefix)
532 {
533         struct rebase_options options = {
534                 .type = REBASE_UNSPECIFIED,
535                 .flags = REBASE_NO_QUIET,
536                 .git_am_opt = STRBUF_INIT,
537                 .allow_rerere_autoupdate  = -1,
538         };
539         const char *branch_name;
540         int ret, flags, total_argc, in_progress = 0;
541         int ok_to_skip_pre_rebase = 0;
542         struct strbuf msg = STRBUF_INIT;
543         struct strbuf revisions = STRBUF_INIT;
544         struct strbuf buf = STRBUF_INIT;
545         struct object_id merge_base;
546         enum {
547                 NO_ACTION,
548                 ACTION_CONTINUE,
549                 ACTION_SKIP,
550                 ACTION_ABORT,
551                 ACTION_QUIT,
552                 ACTION_EDIT_TODO,
553                 ACTION_SHOW_CURRENT_PATCH,
554         } action = NO_ACTION;
555         int committer_date_is_author_date = 0;
556         int ignore_date = 0;
557         int ignore_whitespace = 0;
558         struct option builtin_rebase_options[] = {
559                 OPT_STRING(0, "onto", &options.onto_name,
560                            N_("revision"),
561                            N_("rebase onto given branch instead of upstream")),
562                 OPT_BOOL(0, "no-verify", &ok_to_skip_pre_rebase,
563                          N_("allow pre-rebase hook to run")),
564                 OPT_NEGBIT('q', "quiet", &options.flags,
565                            N_("be quiet. implies --no-stat"),
566                            REBASE_NO_QUIET| REBASE_VERBOSE | REBASE_DIFFSTAT),
567                 OPT_BIT('v', "verbose", &options.flags,
568                         N_("display a diffstat of what changed upstream"),
569                         REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
570                 {OPTION_NEGBIT, 'n', "no-stat", &options.flags, NULL,
571                         N_("do not show diffstat of what changed upstream"),
572                         PARSE_OPT_NOARG, NULL, REBASE_DIFFSTAT },
573                 OPT_BOOL(0, "ignore-whitespace", &ignore_whitespace,
574                          N_("passed to 'git apply'")),
575                 OPT_BOOL(0, "signoff", &options.signoff,
576                          N_("add a Signed-off-by: line to each commit")),
577                 OPT_BOOL(0, "committer-date-is-author-date",
578                          &committer_date_is_author_date,
579                          N_("passed to 'git am'")),
580                 OPT_BOOL(0, "ignore-date", &ignore_date,
581                          N_("passed to 'git am'")),
582                 OPT_BIT('f', "force-rebase", &options.flags,
583                         N_("cherry-pick all commits, even if unchanged"),
584                         REBASE_FORCE),
585                 OPT_BIT(0, "no-ff", &options.flags,
586                         N_("cherry-pick all commits, even if unchanged"),
587                         REBASE_FORCE),
588                 OPT_CMDMODE(0, "continue", &action, N_("continue"),
589                             ACTION_CONTINUE),
590                 OPT_CMDMODE(0, "skip", &action,
591                             N_("skip current patch and continue"), ACTION_SKIP),
592                 OPT_CMDMODE(0, "abort", &action,
593                             N_("abort and check out the original branch"),
594                             ACTION_ABORT),
595                 OPT_CMDMODE(0, "quit", &action,
596                             N_("abort but keep HEAD where it is"), ACTION_QUIT),
597                 OPT_CMDMODE(0, "edit-todo", &action, N_("edit the todo list "
598                             "during an interactive rebase"), ACTION_EDIT_TODO),
599                 OPT_CMDMODE(0, "show-current-patch", &action,
600                             N_("show the patch file being applied or merged"),
601                             ACTION_SHOW_CURRENT_PATCH),
602                 { OPTION_CALLBACK, 'm', "merge", &options, NULL,
603                         N_("use merging strategies to rebase"),
604                         PARSE_OPT_NOARG | PARSE_OPT_NONEG,
605                         parse_opt_merge },
606                 { OPTION_CALLBACK, 'i', "interactive", &options, NULL,
607                         N_("let the user edit the list of commits to rebase"),
608                         PARSE_OPT_NOARG | PARSE_OPT_NONEG,
609                         parse_opt_interactive },
610                 OPT_SET_INT('p', "preserve-merges", &options.type,
611                             N_("try to recreate merges instead of ignoring "
612                                "them"), REBASE_PRESERVE_MERGES),
613                 OPT_BOOL(0, "rerere-autoupdate",
614                          &options.allow_rerere_autoupdate,
615                          N_("allow rerere to update index  with resolved "
616                             "conflict")),
617                 OPT_BOOL('k', "keep-empty", &options.keep_empty,
618                          N_("preserve empty commits during rebase")),
619                 OPT_BOOL(0, "autosquash", &options.autosquash,
620                          N_("move commits that begin with "
621                             "squash!/fixup! under -i")),
622                 OPT_END(),
623         };
624
625         /*
626          * NEEDSWORK: Once the builtin rebase has been tested enough
627          * and git-legacy-rebase.sh is retired to contrib/, this preamble
628          * can be removed.
629          */
630
631         if (!use_builtin_rebase()) {
632                 const char *path = mkpath("%s/git-legacy-rebase",
633                                           git_exec_path());
634
635                 if (sane_execvp(path, (char **)argv) < 0)
636                         die_errno(_("could not exec %s"), path);
637                 else
638                         BUG("sane_execvp() returned???");
639         }
640
641         if (argc == 2 && !strcmp(argv[1], "-h"))
642                 usage_with_options(builtin_rebase_usage,
643                                    builtin_rebase_options);
644
645         prefix = setup_git_directory();
646         trace_repo_setup(prefix);
647         setup_work_tree();
648
649         git_config(rebase_config, &options);
650
651         strbuf_reset(&buf);
652         strbuf_addf(&buf, "%s/applying", apply_dir());
653         if(file_exists(buf.buf))
654                 die(_("It looks like 'git am' is in progress. Cannot rebase."));
655
656         if (is_directory(apply_dir())) {
657                 options.type = REBASE_AM;
658                 options.state_dir = apply_dir();
659         } else if (is_directory(merge_dir())) {
660                 strbuf_reset(&buf);
661                 strbuf_addf(&buf, "%s/rewritten", merge_dir());
662                 if (is_directory(buf.buf)) {
663                         options.type = REBASE_PRESERVE_MERGES;
664                         options.flags |= REBASE_INTERACTIVE_EXPLICIT;
665                 } else {
666                         strbuf_reset(&buf);
667                         strbuf_addf(&buf, "%s/interactive", merge_dir());
668                         if(file_exists(buf.buf)) {
669                                 options.type = REBASE_INTERACTIVE;
670                                 options.flags |= REBASE_INTERACTIVE_EXPLICIT;
671                         } else
672                                 options.type = REBASE_MERGE;
673                 }
674                 options.state_dir = merge_dir();
675         }
676
677         if (options.type != REBASE_UNSPECIFIED)
678                 in_progress = 1;
679
680         total_argc = argc;
681         argc = parse_options(argc, argv, prefix,
682                              builtin_rebase_options,
683                              builtin_rebase_usage, 0);
684
685         if (action != NO_ACTION && total_argc != 2) {
686                 usage_with_options(builtin_rebase_usage,
687                                    builtin_rebase_options);
688         }
689
690         if (argc > 2)
691                 usage_with_options(builtin_rebase_usage,
692                                    builtin_rebase_options);
693
694         if (action != NO_ACTION && !in_progress)
695                 die(_("No rebase in progress?"));
696
697         if (action == ACTION_EDIT_TODO && !is_interactive(&options))
698                 die(_("The --edit-todo action can only be used during "
699                       "interactive rebase."));
700
701         switch (action) {
702         case ACTION_CONTINUE: {
703                 struct object_id head;
704                 struct lock_file lock_file = LOCK_INIT;
705                 int fd;
706
707                 options.action = "continue";
708
709                 /* Sanity check */
710                 if (get_oid("HEAD", &head))
711                         die(_("Cannot read HEAD"));
712
713                 fd = hold_locked_index(&lock_file, 0);
714                 if (read_index(the_repository->index) < 0)
715                         die(_("could not read index"));
716                 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL,
717                               NULL);
718                 if (0 <= fd)
719                         update_index_if_able(the_repository->index,
720                                              &lock_file);
721                 rollback_lock_file(&lock_file);
722
723                 if (has_unstaged_changes(1)) {
724                         puts(_("You must edit all merge conflicts and then\n"
725                                "mark them as resolved using git add"));
726                         exit(1);
727                 }
728                 if (read_basic_state(&options))
729                         exit(1);
730                 goto run_rebase;
731         }
732         case ACTION_SKIP: {
733                 struct string_list merge_rr = STRING_LIST_INIT_DUP;
734
735                 options.action = "skip";
736
737                 rerere_clear(&merge_rr);
738                 string_list_clear(&merge_rr, 1);
739
740                 if (reset_head(NULL, "reset", NULL, 0) < 0)
741                         die(_("could not discard worktree changes"));
742                 if (read_basic_state(&options))
743                         exit(1);
744                 goto run_rebase;
745         }
746         case ACTION_ABORT: {
747                 struct string_list merge_rr = STRING_LIST_INIT_DUP;
748                 options.action = "abort";
749
750                 rerere_clear(&merge_rr);
751                 string_list_clear(&merge_rr, 1);
752
753                 if (read_basic_state(&options))
754                         exit(1);
755                 if (reset_head(&options.orig_head, "reset",
756                                options.head_name, 0) < 0)
757                         die(_("could not move back to %s"),
758                             oid_to_hex(&options.orig_head));
759                 ret = finish_rebase(&options);
760                 goto cleanup;
761         }
762         case ACTION_QUIT: {
763                 strbuf_reset(&buf);
764                 strbuf_addstr(&buf, options.state_dir);
765                 ret = !!remove_dir_recursively(&buf, 0);
766                 if (ret)
767                         die(_("could not remove '%s'"), options.state_dir);
768                 goto cleanup;
769         }
770         case ACTION_EDIT_TODO:
771                 options.action = "edit-todo";
772                 options.dont_finish_rebase = 1;
773                 goto run_rebase;
774         case ACTION_SHOW_CURRENT_PATCH:
775                 options.action = "show-current-patch";
776                 options.dont_finish_rebase = 1;
777                 goto run_rebase;
778         case NO_ACTION:
779                 break;
780         default:
781                 BUG("action: %d", action);
782         }
783
784         /* Make sure no rebase is in progress */
785         if (in_progress) {
786                 const char *last_slash = strrchr(options.state_dir, '/');
787                 const char *state_dir_base =
788                         last_slash ? last_slash + 1 : options.state_dir;
789                 const char *cmd_live_rebase =
790                         "git rebase (--continue | --abort | --skip)";
791                 strbuf_reset(&buf);
792                 strbuf_addf(&buf, "rm -fr \"%s\"", options.state_dir);
793                 die(_("It seems that there is already a %s directory, and\n"
794                       "I wonder if you are in the middle of another rebase.  "
795                       "If that is the\n"
796                       "case, please try\n\t%s\n"
797                       "If that is not the case, please\n\t%s\n"
798                       "and run me again.  I am stopping in case you still "
799                       "have something\n"
800                       "valuable there.\n"),
801                     state_dir_base, cmd_live_rebase, buf.buf);
802         }
803
804         if (!(options.flags & REBASE_NO_QUIET))
805                 strbuf_addstr(&options.git_am_opt, " -q");
806
807         if (committer_date_is_author_date) {
808                 strbuf_addstr(&options.git_am_opt,
809                               " --committer-date-is-author-date");
810                 options.flags |= REBASE_FORCE;
811         }
812
813         if (ignore_whitespace)
814                 strbuf_addstr(&options.git_am_opt, " --ignore-whitespace");
815
816         if (ignore_date) {
817                 strbuf_addstr(&options.git_am_opt, " --ignore-date");
818                 options.flags |= REBASE_FORCE;
819         }
820
821         if (options.keep_empty)
822                 imply_interactive(&options, "--keep-empty");
823
824         switch (options.type) {
825         case REBASE_MERGE:
826         case REBASE_INTERACTIVE:
827         case REBASE_PRESERVE_MERGES:
828                 options.state_dir = merge_dir();
829                 break;
830         case REBASE_AM:
831                 options.state_dir = apply_dir();
832                 break;
833         default:
834                 /* the default rebase backend is `--am` */
835                 options.type = REBASE_AM;
836                 options.state_dir = apply_dir();
837                 break;
838         }
839
840         if (options.signoff) {
841                 if (options.type == REBASE_PRESERVE_MERGES)
842                         die("cannot combine '--signoff' with "
843                             "'--preserve-merges'");
844                 strbuf_addstr(&options.git_am_opt, " --signoff");
845                 options.flags |= REBASE_FORCE;
846         }
847
848         if (!options.root) {
849                 if (argc < 1)
850                         die("TODO: handle @{upstream}");
851                 else {
852                         options.upstream_name = argv[0];
853                         argc--;
854                         argv++;
855                         if (!strcmp(options.upstream_name, "-"))
856                                 options.upstream_name = "@{-1}";
857                 }
858                 options.upstream = peel_committish(options.upstream_name);
859                 if (!options.upstream)
860                         die(_("invalid upstream '%s'"), options.upstream_name);
861                 options.upstream_arg = options.upstream_name;
862         } else
863                 die("TODO: upstream for --root");
864
865         /* Make sure the branch to rebase onto is valid. */
866         if (!options.onto_name)
867                 options.onto_name = options.upstream_name;
868         if (strstr(options.onto_name, "...")) {
869                 if (get_oid_mb(options.onto_name, &merge_base) < 0)
870                         die(_("'%s': need exactly one merge base"),
871                             options.onto_name);
872                 options.onto = lookup_commit_or_die(&merge_base,
873                                                     options.onto_name);
874         } else {
875                 options.onto = peel_committish(options.onto_name);
876                 if (!options.onto)
877                         die(_("Does not point to a valid commit '%s'"),
878                                 options.onto_name);
879         }
880
881         /*
882          * If the branch to rebase is given, that is the branch we will rebase
883          * branch_name -- branch/commit being rebased, or
884          *                HEAD (already detached)
885          * orig_head -- commit object name of tip of the branch before rebasing
886          * head_name -- refs/heads/<that-branch> or NULL (detached HEAD)
887          */
888         if (argc == 1) {
889                 /* Is it "rebase other branchname" or "rebase other commit"? */
890                 branch_name = argv[0];
891                 options.switch_to = argv[0];
892
893                 /* Is it a local branch? */
894                 strbuf_reset(&buf);
895                 strbuf_addf(&buf, "refs/heads/%s", branch_name);
896                 if (!read_ref(buf.buf, &options.orig_head))
897                         options.head_name = xstrdup(buf.buf);
898                 /* If not is it a valid ref (branch or commit)? */
899                 else if (!get_oid(branch_name, &options.orig_head))
900                         options.head_name = NULL;
901                 else
902                         die(_("fatal: no such branch/commit '%s'"),
903                             branch_name);
904         } else if (argc == 0) {
905                 /* Do not need to switch branches, we are already on it. */
906                 options.head_name =
907                         xstrdup_or_null(resolve_ref_unsafe("HEAD", 0, NULL,
908                                          &flags));
909                 if (!options.head_name)
910                         die(_("No such ref: %s"), "HEAD");
911                 if (flags & REF_ISSYMREF) {
912                         if (!skip_prefix(options.head_name,
913                                          "refs/heads/", &branch_name))
914                                 branch_name = options.head_name;
915
916                 } else {
917                         free(options.head_name);
918                         options.head_name = NULL;
919                         branch_name = "HEAD";
920                 }
921                 if (get_oid("HEAD", &options.orig_head))
922                         die(_("Could not resolve HEAD to a revision"));
923         } else
924                 BUG("unexpected number of arguments left to parse");
925
926         if (read_index(the_repository->index) < 0)
927                 die(_("could not read index"));
928
929         if (require_clean_work_tree("rebase",
930                                     _("Please commit or stash them."), 1, 1)) {
931                 ret = 1;
932                 goto cleanup;
933         }
934
935         /*
936          * Now we are rebasing commits upstream..orig_head (or with --root,
937          * everything leading up to orig_head) on top of onto.
938          */
939
940         /*
941          * Check if we are already based on onto with linear history,
942          * but this should be done only when upstream and onto are the same
943          * and if this is not an interactive rebase.
944          */
945         if (can_fast_forward(options.onto, &options.orig_head, &merge_base) &&
946             !is_interactive(&options) && !options.restrict_revision &&
947             !oidcmp(&options.upstream->object.oid, &options.onto->object.oid)) {
948                 int flag;
949
950                 if (!(options.flags & REBASE_FORCE)) {
951                         /* Lazily switch to the target branch if needed... */
952                         if (options.switch_to) {
953                                 struct object_id oid;
954
955                                 if (get_oid(options.switch_to, &oid) < 0) {
956                                         ret = !!error(_("could not parse '%s'"),
957                                                       options.switch_to);
958                                         goto cleanup;
959                                 }
960
961                                 strbuf_reset(&buf);
962                                 strbuf_addf(&buf, "rebase: checkout %s",
963                                             options.switch_to);
964                                 if (reset_head(&oid, "checkout",
965                                                options.head_name, 0) < 0) {
966                                         ret = !!error(_("could not switch to "
967                                                         "%s"),
968                                                       options.switch_to);
969                                         goto cleanup;
970                                 }
971                         }
972
973                         if (!(options.flags & REBASE_NO_QUIET))
974                                 ; /* be quiet */
975                         else if (!strcmp(branch_name, "HEAD") &&
976                                  resolve_ref_unsafe("HEAD", 0, NULL, &flag))
977                                 puts(_("HEAD is up to date."));
978                         else
979                                 printf(_("Current branch %s is up to date.\n"),
980                                        branch_name);
981                         ret = !!finish_rebase(&options);
982                         goto cleanup;
983                 } else if (!(options.flags & REBASE_NO_QUIET))
984                         ; /* be quiet */
985                 else if (!strcmp(branch_name, "HEAD") &&
986                          resolve_ref_unsafe("HEAD", 0, NULL, &flag))
987                         puts(_("HEAD is up to date, rebase forced."));
988                 else
989                         printf(_("Current branch %s is up to date, rebase "
990                                  "forced.\n"), branch_name);
991         }
992
993         /* If a hook exists, give it a chance to interrupt*/
994         if (!ok_to_skip_pre_rebase &&
995             run_hook_le(NULL, "pre-rebase", options.upstream_arg,
996                         argc ? argv[0] : NULL, NULL))
997                 die(_("The pre-rebase hook refused to rebase."));
998
999         if (options.flags & REBASE_DIFFSTAT) {
1000                 struct diff_options opts;
1001
1002                 if (options.flags & REBASE_VERBOSE)
1003                         printf(_("Changes from %s to %s:\n"),
1004                                 oid_to_hex(&merge_base),
1005                                 oid_to_hex(&options.onto->object.oid));
1006
1007                 /* We want color (if set), but no pager */
1008                 diff_setup(&opts);
1009                 opts.stat_width = -1; /* use full terminal width */
1010                 opts.stat_graph_width = -1; /* respect statGraphWidth config */
1011                 opts.output_format |=
1012                         DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1013                 opts.detect_rename = DIFF_DETECT_RENAME;
1014                 diff_setup_done(&opts);
1015                 diff_tree_oid(&merge_base, &options.onto->object.oid,
1016                               "", &opts);
1017                 diffcore_std(&opts);
1018                 diff_flush(&opts);
1019         }
1020
1021         if (is_interactive(&options))
1022                 goto run_rebase;
1023
1024         /* Detach HEAD and reset the tree */
1025         if (options.flags & REBASE_NO_QUIET)
1026                 printf(_("First, rewinding head to replay your work on top of "
1027                          "it...\n"));
1028
1029         strbuf_addf(&msg, "rebase: checkout %s", options.onto_name);
1030         if (reset_head(&options.onto->object.oid, "checkout", NULL, 1))
1031                 die(_("Could not detach HEAD"));
1032         strbuf_release(&msg);
1033
1034         strbuf_addf(&revisions, "%s..%s",
1035                     options.root ? oid_to_hex(&options.onto->object.oid) :
1036                     (options.restrict_revision ?
1037                      oid_to_hex(&options.restrict_revision->object.oid) :
1038                      oid_to_hex(&options.upstream->object.oid)),
1039                     oid_to_hex(&options.orig_head));
1040
1041         options.revisions = revisions.buf;
1042
1043 run_rebase:
1044         ret = !!run_specific_rebase(&options);
1045
1046 cleanup:
1047         strbuf_release(&revisions);
1048         free(options.head_name);
1049         return ret;
1050 }