builtin rebase: require a clean worktree
[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
24 static char const * const builtin_rebase_usage[] = {
25         N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
26                 "[<upstream>] [<branch>]"),
27         N_("git rebase [-i] [options] [--exec <cmd>] [--onto <newbase>] "
28                 "--root [<branch>]"),
29         N_("git rebase --continue | --abort | --skip | --edit-todo"),
30         NULL
31 };
32
33 static GIT_PATH_FUNC(apply_dir, "rebase-apply")
34 static GIT_PATH_FUNC(merge_dir, "rebase-merge")
35
36 enum rebase_type {
37         REBASE_UNSPECIFIED = -1,
38         REBASE_AM,
39         REBASE_MERGE,
40         REBASE_INTERACTIVE,
41         REBASE_PRESERVE_MERGES
42 };
43
44 static int use_builtin_rebase(void)
45 {
46         struct child_process cp = CHILD_PROCESS_INIT;
47         struct strbuf out = STRBUF_INIT;
48         int ret;
49
50         argv_array_pushl(&cp.args,
51                          "config", "--bool", "rebase.usebuiltin", NULL);
52         cp.git_cmd = 1;
53         if (capture_command(&cp, &out, 6)) {
54                 strbuf_release(&out);
55                 return 0;
56         }
57
58         strbuf_trim(&out);
59         ret = !strcmp("true", out.buf);
60         strbuf_release(&out);
61         return ret;
62 }
63
64 static int apply_autostash(void)
65 {
66         warning("TODO");
67         return 0;
68 }
69
70 struct rebase_options {
71         enum rebase_type type;
72         const char *state_dir;
73         struct commit *upstream;
74         const char *upstream_name;
75         const char *upstream_arg;
76         char *head_name;
77         struct object_id orig_head;
78         struct commit *onto;
79         const char *onto_name;
80         const char *revisions;
81         int root;
82         struct commit *restrict_revision;
83         int dont_finish_rebase;
84         enum {
85                 REBASE_NO_QUIET = 1<<0,
86                 REBASE_VERBOSE = 1<<1,
87                 REBASE_DIFFSTAT = 1<<2,
88         } flags;
89         struct strbuf git_am_opt;
90 };
91
92 /* Returns the filename prefixed by the state_dir */
93 static const char *state_dir_path(const char *filename, struct rebase_options *opts)
94 {
95         static struct strbuf path = STRBUF_INIT;
96         static size_t prefix_len;
97
98         if (!prefix_len) {
99                 strbuf_addf(&path, "%s/", opts->state_dir);
100                 prefix_len = path.len;
101         }
102
103         strbuf_setlen(&path, prefix_len);
104         strbuf_addstr(&path, filename);
105         return path.buf;
106 }
107
108 static int finish_rebase(struct rebase_options *opts)
109 {
110         struct strbuf dir = STRBUF_INIT;
111         const char *argv_gc_auto[] = { "gc", "--auto", NULL };
112
113         delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
114         apply_autostash();
115         close_all_packs(the_repository->objects);
116         /*
117          * We ignore errors in 'gc --auto', since the
118          * user should see them.
119          */
120         run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
121         strbuf_addstr(&dir, opts->state_dir);
122         remove_dir_recursively(&dir, 0);
123         strbuf_release(&dir);
124
125         return 0;
126 }
127
128 static struct commit *peel_committish(const char *name)
129 {
130         struct object *obj;
131         struct object_id oid;
132
133         if (get_oid(name, &oid))
134                 return NULL;
135         obj = parse_object(the_repository, &oid);
136         return (struct commit *)peel_to_type(name, 0, obj, OBJ_COMMIT);
137 }
138
139 static void add_var(struct strbuf *buf, const char *name, const char *value)
140 {
141         if (!value)
142                 strbuf_addf(buf, "unset %s; ", name);
143         else {
144                 strbuf_addf(buf, "%s=", name);
145                 sq_quote_buf(buf, value);
146                 strbuf_addstr(buf, "; ");
147         }
148 }
149
150 static int run_specific_rebase(struct rebase_options *opts)
151 {
152         const char *argv[] = { NULL, NULL };
153         struct strbuf script_snippet = STRBUF_INIT;
154         int status;
155         const char *backend, *backend_func;
156
157         add_var(&script_snippet, "GIT_DIR", absolute_path(get_git_dir()));
158         add_var(&script_snippet, "state_dir", opts->state_dir);
159
160         add_var(&script_snippet, "upstream_name", opts->upstream_name);
161         add_var(&script_snippet, "upstream",
162                                  oid_to_hex(&opts->upstream->object.oid));
163         add_var(&script_snippet, "head_name", opts->head_name);
164         add_var(&script_snippet, "orig_head", oid_to_hex(&opts->orig_head));
165         add_var(&script_snippet, "onto", oid_to_hex(&opts->onto->object.oid));
166         add_var(&script_snippet, "onto_name", opts->onto_name);
167         add_var(&script_snippet, "revisions", opts->revisions);
168         add_var(&script_snippet, "restrict_revision", opts->restrict_revision ?
169                 oid_to_hex(&opts->restrict_revision->object.oid) : NULL);
170         add_var(&script_snippet, "GIT_QUIET",
171                 opts->flags & REBASE_NO_QUIET ? "" : "t");
172         add_var(&script_snippet, "git_am_opt", opts->git_am_opt.buf);
173         add_var(&script_snippet, "verbose",
174                 opts->flags & REBASE_VERBOSE ? "t" : "");
175         add_var(&script_snippet, "diffstat",
176                 opts->flags & REBASE_DIFFSTAT ? "t" : "");
177
178         switch (opts->type) {
179         case REBASE_AM:
180                 backend = "git-rebase--am";
181                 backend_func = "git_rebase__am";
182                 break;
183         case REBASE_INTERACTIVE:
184                 backend = "git-rebase--interactive";
185                 backend_func = "git_rebase__interactive";
186                 break;
187         case REBASE_MERGE:
188                 backend = "git-rebase--merge";
189                 backend_func = "git_rebase__merge";
190                 break;
191         case REBASE_PRESERVE_MERGES:
192                 backend = "git-rebase--preserve-merges";
193                 backend_func = "git_rebase__preserve_merges";
194                 break;
195         default:
196                 BUG("Unhandled rebase type %d", opts->type);
197                 break;
198         }
199
200         strbuf_addf(&script_snippet,
201                     ". git-sh-setup && . git-rebase--common &&"
202                     " . %s && %s", backend, backend_func);
203         argv[0] = script_snippet.buf;
204
205         status = run_command_v_opt(argv, RUN_USING_SHELL);
206         if (opts->dont_finish_rebase)
207                 ; /* do nothing */
208         else if (status == 0) {
209                 if (!file_exists(state_dir_path("stopped-sha", opts)))
210                         finish_rebase(opts);
211         } else if (status == 2) {
212                 struct strbuf dir = STRBUF_INIT;
213
214                 apply_autostash();
215                 strbuf_addstr(&dir, opts->state_dir);
216                 remove_dir_recursively(&dir, 0);
217                 strbuf_release(&dir);
218                 die("Nothing to do");
219         }
220
221         strbuf_release(&script_snippet);
222
223         return status ? -1 : 0;
224 }
225
226 #define GIT_REFLOG_ACTION_ENVIRONMENT "GIT_REFLOG_ACTION"
227
228 static int reset_head(struct object_id *oid, const char *action,
229                       const char *switch_to_branch, int detach_head)
230 {
231         struct object_id head_oid;
232         struct tree_desc desc;
233         struct lock_file lock = LOCK_INIT;
234         struct unpack_trees_options unpack_tree_opts;
235         struct tree *tree;
236         const char *reflog_action;
237         struct strbuf msg = STRBUF_INIT;
238         size_t prefix_len;
239         struct object_id *orig = NULL, oid_orig,
240                 *old_orig = NULL, oid_old_orig;
241         int ret = 0;
242
243         if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0)
244                 return -1;
245
246         if (!oid) {
247                 if (get_oid("HEAD", &head_oid)) {
248                         rollback_lock_file(&lock);
249                         return error(_("could not determine HEAD revision"));
250                 }
251                 oid = &head_oid;
252         }
253
254         memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
255         setup_unpack_trees_porcelain(&unpack_tree_opts, action);
256         unpack_tree_opts.head_idx = 1;
257         unpack_tree_opts.src_index = the_repository->index;
258         unpack_tree_opts.dst_index = the_repository->index;
259         unpack_tree_opts.fn = oneway_merge;
260         unpack_tree_opts.update = 1;
261         unpack_tree_opts.merge = 1;
262         if (!detach_head)
263                 unpack_tree_opts.reset = 1;
264
265         if (read_index_unmerged(the_repository->index) < 0) {
266                 rollback_lock_file(&lock);
267                 return error(_("could not read index"));
268         }
269
270         if (!fill_tree_descriptor(&desc, oid)) {
271                 error(_("failed to find tree of %s"), oid_to_hex(oid));
272                 rollback_lock_file(&lock);
273                 free((void *)desc.buffer);
274                 return -1;
275         }
276
277         if (unpack_trees(1, &desc, &unpack_tree_opts)) {
278                 rollback_lock_file(&lock);
279                 free((void *)desc.buffer);
280                 return -1;
281         }
282
283         tree = parse_tree_indirect(oid);
284         prime_cache_tree(the_repository->index, tree);
285
286         if (write_locked_index(the_repository->index, &lock, COMMIT_LOCK) < 0)
287                 ret = error(_("could not write index"));
288         free((void *)desc.buffer);
289
290         if (ret)
291                 return ret;
292
293         reflog_action = getenv(GIT_REFLOG_ACTION_ENVIRONMENT);
294         strbuf_addf(&msg, "%s: ", reflog_action ? reflog_action : "rebase");
295         prefix_len = msg.len;
296
297         if (!get_oid("ORIG_HEAD", &oid_old_orig))
298                 old_orig = &oid_old_orig;
299         if (!get_oid("HEAD", &oid_orig)) {
300                 orig = &oid_orig;
301                 strbuf_addstr(&msg, "updating ORIG_HEAD");
302                 update_ref(msg.buf, "ORIG_HEAD", orig, old_orig, 0,
303                            UPDATE_REFS_MSG_ON_ERR);
304         } else if (old_orig)
305                 delete_ref(NULL, "ORIG_HEAD", old_orig, 0);
306         strbuf_setlen(&msg, prefix_len);
307         strbuf_addstr(&msg, "updating HEAD");
308         if (!switch_to_branch)
309                 ret = update_ref(msg.buf, "HEAD", oid, orig, REF_NO_DEREF,
310                                  UPDATE_REFS_MSG_ON_ERR);
311         else {
312                 ret = create_symref("HEAD", switch_to_branch, msg.buf);
313                 if (!ret)
314                         ret = update_ref(msg.buf, "HEAD", oid, NULL, 0,
315                                          UPDATE_REFS_MSG_ON_ERR);
316         }
317
318         strbuf_release(&msg);
319         return ret;
320 }
321
322 static int rebase_config(const char *var, const char *value, void *data)
323 {
324         struct rebase_options *opts = data;
325
326         if (!strcmp(var, "rebase.stat")) {
327                 if (git_config_bool(var, value))
328                         opts->flags |= REBASE_DIFFSTAT;
329                 else
330                         opts->flags &= !REBASE_DIFFSTAT;
331                 return 0;
332         }
333
334         return git_default_config(var, value, data);
335 }
336
337 int cmd_rebase(int argc, const char **argv, const char *prefix)
338 {
339         struct rebase_options options = {
340                 .type = REBASE_UNSPECIFIED,
341                 .flags = REBASE_NO_QUIET,
342                 .git_am_opt = STRBUF_INIT,
343         };
344         const char *branch_name;
345         int ret, flags;
346         int ok_to_skip_pre_rebase = 0;
347         struct strbuf msg = STRBUF_INIT;
348         struct strbuf revisions = STRBUF_INIT;
349         struct object_id merge_base;
350         struct option builtin_rebase_options[] = {
351                 OPT_STRING(0, "onto", &options.onto_name,
352                            N_("revision"),
353                            N_("rebase onto given branch instead of upstream")),
354                 OPT_BOOL(0, "no-verify", &ok_to_skip_pre_rebase,
355                          N_("allow pre-rebase hook to run")),
356                 OPT_NEGBIT('q', "quiet", &options.flags,
357                            N_("be quiet. implies --no-stat"),
358                            REBASE_NO_QUIET| REBASE_VERBOSE | REBASE_DIFFSTAT),
359                 OPT_BIT('v', "verbose", &options.flags,
360                         N_("display a diffstat of what changed upstream"),
361                         REBASE_NO_QUIET | REBASE_VERBOSE | REBASE_DIFFSTAT),
362                 {OPTION_NEGBIT, 'n', "no-stat", &options.flags, NULL,
363                         N_("do not show diffstat of what changed upstream"),
364                         PARSE_OPT_NOARG, NULL, REBASE_DIFFSTAT },
365                 OPT_END(),
366         };
367
368         /*
369          * NEEDSWORK: Once the builtin rebase has been tested enough
370          * and git-legacy-rebase.sh is retired to contrib/, this preamble
371          * can be removed.
372          */
373
374         if (!use_builtin_rebase()) {
375                 const char *path = mkpath("%s/git-legacy-rebase",
376                                           git_exec_path());
377
378                 if (sane_execvp(path, (char **)argv) < 0)
379                         die_errno(_("could not exec %s"), path);
380                 else
381                         BUG("sane_execvp() returned???");
382         }
383
384         if (argc == 2 && !strcmp(argv[1], "-h"))
385                 usage_with_options(builtin_rebase_usage,
386                                    builtin_rebase_options);
387
388         prefix = setup_git_directory();
389         trace_repo_setup(prefix);
390         setup_work_tree();
391
392         git_config(rebase_config, &options);
393
394         argc = parse_options(argc, argv, prefix,
395                              builtin_rebase_options,
396                              builtin_rebase_usage, 0);
397
398         if (argc > 2)
399                 usage_with_options(builtin_rebase_usage,
400                                    builtin_rebase_options);
401
402         if (!(options.flags & REBASE_NO_QUIET))
403                 strbuf_addstr(&options.git_am_opt, " -q");
404
405         switch (options.type) {
406         case REBASE_MERGE:
407         case REBASE_INTERACTIVE:
408         case REBASE_PRESERVE_MERGES:
409                 options.state_dir = merge_dir();
410                 break;
411         case REBASE_AM:
412                 options.state_dir = apply_dir();
413                 break;
414         default:
415                 /* the default rebase backend is `--am` */
416                 options.type = REBASE_AM;
417                 options.state_dir = apply_dir();
418                 break;
419         }
420
421         if (!options.root) {
422                 if (argc < 1)
423                         die("TODO: handle @{upstream}");
424                 else {
425                         options.upstream_name = argv[0];
426                         argc--;
427                         argv++;
428                         if (!strcmp(options.upstream_name, "-"))
429                                 options.upstream_name = "@{-1}";
430                 }
431                 options.upstream = peel_committish(options.upstream_name);
432                 if (!options.upstream)
433                         die(_("invalid upstream '%s'"), options.upstream_name);
434                 options.upstream_arg = options.upstream_name;
435         } else
436                 die("TODO: upstream for --root");
437
438         /* Make sure the branch to rebase onto is valid. */
439         if (!options.onto_name)
440                 options.onto_name = options.upstream_name;
441         if (strstr(options.onto_name, "...")) {
442                 if (get_oid_mb(options.onto_name, &merge_base) < 0)
443                         die(_("'%s': need exactly one merge base"),
444                             options.onto_name);
445                 options.onto = lookup_commit_or_die(&merge_base,
446                                                     options.onto_name);
447         } else {
448                 options.onto = peel_committish(options.onto_name);
449                 if (!options.onto)
450                         die(_("Does not point to a valid commit '%s'"),
451                                 options.onto_name);
452         }
453
454         /*
455          * If the branch to rebase is given, that is the branch we will rebase
456          * branch_name -- branch/commit being rebased, or
457          *                HEAD (already detached)
458          * orig_head -- commit object name of tip of the branch before rebasing
459          * head_name -- refs/heads/<that-branch> or "detached HEAD"
460          */
461         if (argc > 0)
462                  die("TODO: handle switch_to");
463         else {
464                 /* Do not need to switch branches, we are already on it. */
465                 options.head_name =
466                         xstrdup_or_null(resolve_ref_unsafe("HEAD", 0, NULL,
467                                          &flags));
468                 if (!options.head_name)
469                         die(_("No such ref: %s"), "HEAD");
470                 if (flags & REF_ISSYMREF) {
471                         if (!skip_prefix(options.head_name,
472                                          "refs/heads/", &branch_name))
473                                 branch_name = options.head_name;
474
475                 } else {
476                         options.head_name = xstrdup("detached HEAD");
477                         branch_name = "HEAD";
478                 }
479                 if (get_oid("HEAD", &options.orig_head))
480                         die(_("Could not resolve HEAD to a revision"));
481         }
482
483         if (read_index(the_repository->index) < 0)
484                 die(_("could not read index"));
485
486         if (require_clean_work_tree("rebase",
487                                     _("Please commit or stash them."), 1, 1)) {
488                 ret = 1;
489                 goto cleanup;
490         }
491
492         /* If a hook exists, give it a chance to interrupt*/
493         if (!ok_to_skip_pre_rebase &&
494             run_hook_le(NULL, "pre-rebase", options.upstream_arg,
495                         argc ? argv[0] : NULL, NULL))
496                 die(_("The pre-rebase hook refused to rebase."));
497
498         if (options.flags & REBASE_DIFFSTAT) {
499                 struct diff_options opts;
500
501                 if (options.flags & REBASE_VERBOSE)
502                         printf(_("Changes from %s to %s:\n"),
503                                 oid_to_hex(&merge_base),
504                                 oid_to_hex(&options.onto->object.oid));
505
506                 /* We want color (if set), but no pager */
507                 diff_setup(&opts);
508                 opts.stat_width = -1; /* use full terminal width */
509                 opts.stat_graph_width = -1; /* respect statGraphWidth config */
510                 opts.output_format |=
511                         DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
512                 opts.detect_rename = DIFF_DETECT_RENAME;
513                 diff_setup_done(&opts);
514                 diff_tree_oid(&merge_base, &options.onto->object.oid,
515                               "", &opts);
516                 diffcore_std(&opts);
517                 diff_flush(&opts);
518         }
519
520         /* Detach HEAD and reset the tree */
521         if (options.flags & REBASE_NO_QUIET)
522                 printf(_("First, rewinding head to replay your work on top of "
523                          "it...\n"));
524
525         strbuf_addf(&msg, "rebase: checkout %s", options.onto_name);
526         if (reset_head(&options.onto->object.oid, "checkout", NULL, 1))
527                 die(_("Could not detach HEAD"));
528         strbuf_release(&msg);
529
530         strbuf_addf(&revisions, "%s..%s",
531                     options.root ? oid_to_hex(&options.onto->object.oid) :
532                     (options.restrict_revision ?
533                      oid_to_hex(&options.restrict_revision->object.oid) :
534                      oid_to_hex(&options.upstream->object.oid)),
535                     oid_to_hex(&options.orig_head));
536
537         options.revisions = revisions.buf;
538
539         ret = !!run_specific_rebase(&options);
540
541 cleanup:
542         strbuf_release(&revisions);
543         free(options.head_name);
544         return ret;
545 }