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