builtin-checkout.c: fix possible usage segfault
[alt-git.git] / builtin-checkout.c
blob0d19835a6b9e8d52574531c0453eff91f47b8e8d
1 #include "cache.h"
2 #include "builtin.h"
3 #include "parse-options.h"
4 #include "refs.h"
5 #include "commit.h"
6 #include "tree.h"
7 #include "tree-walk.h"
8 #include "unpack-trees.h"
9 #include "dir.h"
10 #include "run-command.h"
11 #include "merge-recursive.h"
12 #include "branch.h"
13 #include "diff.h"
14 #include "revision.h"
15 #include "remote.h"
17 static const char * const checkout_usage[] = {
18 "git checkout [options] <branch>",
19 "git checkout [options] [<branch>] -- <file>...",
20 NULL,
23 static int post_checkout_hook(struct commit *old, struct commit *new,
24 int changed)
26 struct child_process proc;
27 const char *name = git_path("hooks/post-checkout");
28 const char *argv[5];
30 if (access(name, X_OK) < 0)
31 return 0;
33 memset(&proc, 0, sizeof(proc));
34 argv[0] = name;
35 argv[1] = xstrdup(sha1_to_hex(old->object.sha1));
36 argv[2] = xstrdup(sha1_to_hex(new->object.sha1));
37 argv[3] = changed ? "1" : "0";
38 argv[4] = NULL;
39 proc.argv = argv;
40 proc.no_stdin = 1;
41 proc.stdout_to_stderr = 1;
42 return run_command(&proc);
45 static int update_some(const unsigned char *sha1, const char *base, int baselen,
46 const char *pathname, unsigned mode, int stage)
48 int len;
49 struct cache_entry *ce;
51 if (S_ISGITLINK(mode))
52 return 0;
54 if (S_ISDIR(mode))
55 return READ_TREE_RECURSIVE;
57 len = baselen + strlen(pathname);
58 ce = xcalloc(1, cache_entry_size(len));
59 hashcpy(ce->sha1, sha1);
60 memcpy(ce->name, base, baselen);
61 memcpy(ce->name + baselen, pathname, len - baselen);
62 ce->ce_flags = create_ce_flags(len, 0);
63 ce->ce_mode = create_ce_mode(mode);
64 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
65 return 0;
68 static int read_tree_some(struct tree *tree, const char **pathspec)
70 int newfd;
71 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
72 newfd = hold_locked_index(lock_file, 1);
73 read_cache();
75 read_tree_recursive(tree, "", 0, 0, pathspec, update_some);
77 if (write_cache(newfd, active_cache, active_nr) ||
78 commit_locked_index(lock_file))
79 die("unable to write new index file");
81 /* update the index with the given tree's info
82 * for all args, expanding wildcards, and exit
83 * with any non-zero return code.
85 return 0;
88 static int checkout_paths(const char **pathspec)
90 int pos;
91 struct checkout state;
92 static char *ps_matched;
93 unsigned char rev[20];
94 int flag;
95 struct commit *head;
97 for (pos = 0; pathspec[pos]; pos++)
99 ps_matched = xcalloc(1, pos);
101 for (pos = 0; pos < active_nr; pos++) {
102 struct cache_entry *ce = active_cache[pos];
103 pathspec_match(pathspec, ps_matched, ce->name, 0);
106 if (report_path_error(ps_matched, pathspec, 0))
107 return 1;
109 memset(&state, 0, sizeof(state));
110 state.force = 1;
111 state.refresh_cache = 1;
112 for (pos = 0; pos < active_nr; pos++) {
113 struct cache_entry *ce = active_cache[pos];
114 if (pathspec_match(pathspec, NULL, ce->name, 0)) {
115 checkout_entry(ce, &state, NULL);
119 resolve_ref("HEAD", rev, 0, &flag);
120 head = lookup_commit_reference_gently(rev, 1);
122 return post_checkout_hook(head, head, 0);
125 static void show_local_changes(struct object *head)
127 struct rev_info rev;
128 /* I think we want full paths, even if we're in a subdirectory. */
129 init_revisions(&rev, NULL);
130 rev.abbrev = 0;
131 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS;
132 add_pending_object(&rev, head, NULL);
133 run_diff_index(&rev, 0);
136 static void describe_detached_head(char *msg, struct commit *commit)
138 struct strbuf sb;
139 strbuf_init(&sb, 0);
140 parse_commit(commit);
141 pretty_print_commit(CMIT_FMT_ONELINE, commit, &sb, 0, "", "", 0, 0);
142 fprintf(stderr, "%s %s... %s\n", msg,
143 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV), sb.buf);
144 strbuf_release(&sb);
147 static int reset_to_new(struct tree *tree, int quiet)
149 struct unpack_trees_options opts;
150 struct tree_desc tree_desc;
151 memset(&opts, 0, sizeof(opts));
152 opts.head_idx = -1;
153 opts.update = 1;
154 opts.reset = 1;
155 opts.merge = 1;
156 opts.fn = oneway_merge;
157 opts.verbose_update = !quiet;
158 parse_tree(tree);
159 init_tree_desc(&tree_desc, tree->buffer, tree->size);
160 if (unpack_trees(1, &tree_desc, &opts))
161 return 128;
162 return 0;
165 static void reset_clean_to_new(struct tree *tree, int quiet)
167 struct unpack_trees_options opts;
168 struct tree_desc tree_desc;
169 memset(&opts, 0, sizeof(opts));
170 opts.head_idx = -1;
171 opts.skip_unmerged = 1;
172 opts.reset = 1;
173 opts.merge = 1;
174 opts.fn = oneway_merge;
175 opts.verbose_update = !quiet;
176 parse_tree(tree);
177 init_tree_desc(&tree_desc, tree->buffer, tree->size);
178 if (unpack_trees(1, &tree_desc, &opts))
179 exit(128);
182 struct checkout_opts {
183 int quiet;
184 int merge;
185 int force;
187 char *new_branch;
188 int new_branch_log;
189 int track;
192 struct branch_info {
193 const char *name; /* The short name used */
194 const char *path; /* The full name of a real branch */
195 struct commit *commit; /* The named commit */
198 static void setup_branch_path(struct branch_info *branch)
200 struct strbuf buf;
201 strbuf_init(&buf, 0);
202 strbuf_addstr(&buf, "refs/heads/");
203 strbuf_addstr(&buf, branch->name);
204 branch->path = strbuf_detach(&buf, NULL);
207 static int merge_working_tree(struct checkout_opts *opts,
208 struct branch_info *old, struct branch_info *new,
209 const char *prefix)
211 int ret;
212 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
213 int newfd = hold_locked_index(lock_file, 1);
214 read_cache();
216 if (opts->force) {
217 ret = reset_to_new(new->commit->tree, opts->quiet);
218 if (ret)
219 return ret;
220 } else {
221 struct tree_desc trees[2];
222 struct tree *tree;
223 struct unpack_trees_options topts;
224 memset(&topts, 0, sizeof(topts));
225 topts.head_idx = -1;
227 refresh_cache(REFRESH_QUIET);
229 if (unmerged_cache()) {
230 ret = opts->merge ? -1 :
231 error("you need to resolve your current index first");
232 } else {
233 topts.update = 1;
234 topts.merge = 1;
235 topts.gently = opts->merge;
236 topts.fn = twoway_merge;
237 topts.dir = xcalloc(1, sizeof(*topts.dir));
238 topts.dir->show_ignored = 1;
239 topts.dir->exclude_per_dir = ".gitignore";
240 topts.prefix = prefix;
241 tree = parse_tree_indirect(old->commit->object.sha1);
242 init_tree_desc(&trees[0], tree->buffer, tree->size);
243 tree = parse_tree_indirect(new->commit->object.sha1);
244 init_tree_desc(&trees[1], tree->buffer, tree->size);
245 ret = unpack_trees(2, trees, &topts);
247 if (ret) {
249 * Unpack couldn't do a trivial merge; either
250 * give up or do a real merge, depending on
251 * whether the merge flag was used.
253 struct tree *result;
254 struct tree *work;
255 if (!opts->merge)
256 return 1;
257 parse_commit(old->commit);
259 /* Do more real merge */
262 * We update the index fully, then write the
263 * tree from the index, then merge the new
264 * branch with the current tree, with the old
265 * branch as the base. Then we reset the index
266 * (but not the working tree) to the new
267 * branch, leaving the working tree as the
268 * merged version, but skipping unmerged
269 * entries in the index.
272 add_files_to_cache(0, NULL, NULL);
273 work = write_tree_from_memory();
275 ret = reset_to_new(new->commit->tree, opts->quiet);
276 if (ret)
277 return ret;
278 merge_trees(new->commit->tree, work, old->commit->tree,
279 new->name, "local", &result);
280 reset_clean_to_new(new->commit->tree, opts->quiet);
284 if (write_cache(newfd, active_cache, active_nr) ||
285 commit_locked_index(lock_file))
286 die("unable to write new index file");
288 if (!opts->force)
289 show_local_changes(&new->commit->object);
291 return 0;
295 * We really should allow cb_data... Yuck
297 static const char *branch_name;
298 static int branch_name_len;
299 static char *found_remote;
300 static char *found_merge;
301 static int read_branch_config(const char *var, const char *value)
303 const char *name;
304 if (prefixcmp(var, "branch."))
305 return 0; /* not ours */
306 name = var + strlen("branch.");
307 if (strncmp(name, branch_name, branch_name_len) ||
308 name[branch_name_len] != '.')
309 return 0; /* not ours either */
310 if (!strcmp(name + branch_name_len, ".remote")) {
312 * Yeah, I know Christian's clean-up should
313 * be used here, but the topic is based on an
314 * older fork point.
316 if (!value)
317 return error("'%s' not string", var);
318 found_remote = xstrdup(value);
319 return 0;
321 if (!strcmp(name + branch_name_len, ".merge")) {
322 if (!value)
323 return error("'%s' not string", var);
324 found_merge = xstrdup(value);
325 return 0;
327 return 0; /* not ours */
330 static int find_build_base(const char *ours, char **base)
332 struct remote *remote;
333 struct refspec spec;
335 *base = NULL;
337 branch_name = ours + strlen("refs/heads/");
338 branch_name_len = strlen(branch_name);
339 found_remote = NULL;
340 found_merge = NULL;
341 git_config(read_branch_config);
343 if (!found_remote || !found_merge) {
344 cleanup:
345 free(found_remote);
346 free(found_merge);
347 return 0;
350 remote = remote_get(found_remote);
351 memset(&spec, 0, sizeof(spec));
352 spec.src = found_merge;
353 if (remote_find_tracking(remote, &spec))
354 goto cleanup;
355 *base = spec.dst;
356 return 1;
359 static void adjust_to_tracking(struct branch_info *new, struct checkout_opts *opts)
362 * We have switched to a new branch; is it building on
363 * top of another branch, and if so does that other branch
364 * have changes we do not have yet?
366 char *base;
367 unsigned char sha1[20];
368 struct commit *ours, *theirs;
369 const char *msgfmt;
370 char symmetric[84];
371 int show_log;
373 if (!resolve_ref(new->path, sha1, 1, NULL))
374 return;
375 ours = lookup_commit(sha1);
377 if (!find_build_base(new->path, &base))
378 return;
380 sprintf(symmetric, "%s", sha1_to_hex(sha1));
383 * Ok, it is tracking base; is it ahead of us?
385 if (!resolve_ref(base, sha1, 1, NULL))
386 return;
387 theirs = lookup_commit(sha1);
389 sprintf(symmetric + 40, "...%s", sha1_to_hex(sha1));
391 if (!hashcmp(sha1, ours->object.sha1))
392 return; /* we are the same */
394 show_log = 1;
395 if (in_merge_bases(theirs, &ours, 1)) {
396 msgfmt = "You are ahead of the tracked branch '%s'\n";
397 show_log = 0;
399 else if (in_merge_bases(ours, &theirs, 1))
400 msgfmt = "Your branch can be fast-forwarded to the tracked branch '%s'\n";
401 else
402 msgfmt = "Both your branch and the tracked branch '%s' have own changes, you would eventually need to merge\n";
404 if (!prefixcmp(base, "refs/remotes/"))
405 base += strlen("refs/remotes/");
406 fprintf(stderr, msgfmt, base);
408 if (show_log) {
409 const char *args[32];
410 int ac;
412 ac = 0;
413 args[ac++] = "log";
414 args[ac++] = "--pretty=oneline";
415 args[ac++] = "--abbrev-commit";
416 args[ac++] = "--left-right";
417 args[ac++] = "--boundary";
418 args[ac++] = symmetric;
419 args[ac++] = "--";
420 args[ac] = NULL;
422 run_command_v_opt(args, RUN_GIT_CMD);
427 static void update_refs_for_switch(struct checkout_opts *opts,
428 struct branch_info *old,
429 struct branch_info *new)
431 struct strbuf msg;
432 const char *old_desc;
433 if (opts->new_branch) {
434 create_branch(old->name, opts->new_branch, new->name, 0,
435 opts->new_branch_log, opts->track);
436 new->name = opts->new_branch;
437 setup_branch_path(new);
440 strbuf_init(&msg, 0);
441 old_desc = old->name;
442 if (!old_desc)
443 old_desc = sha1_to_hex(old->commit->object.sha1);
444 strbuf_addf(&msg, "checkout: moving from %s to %s",
445 old_desc, new->name);
447 if (new->path) {
448 create_symref("HEAD", new->path, msg.buf);
449 if (!opts->quiet) {
450 if (old->path && !strcmp(new->path, old->path))
451 fprintf(stderr, "Already on \"%s\"\n",
452 new->name);
453 else
454 fprintf(stderr, "Switched to%s branch \"%s\"\n",
455 opts->new_branch ? " a new" : "",
456 new->name);
458 } else if (strcmp(new->name, "HEAD")) {
459 update_ref(msg.buf, "HEAD", new->commit->object.sha1, NULL,
460 REF_NODEREF, DIE_ON_ERR);
461 if (!opts->quiet) {
462 if (old->path)
463 fprintf(stderr, "Note: moving to \"%s\" which isn't a local branch\nIf you want to create a new branch from this checkout, you may do so\n(now or later) by using -b with the checkout command again. Example:\n git checkout -b <new_branch_name>\n", new->name);
464 describe_detached_head("HEAD is now at", new->commit);
467 remove_branch_state();
468 strbuf_release(&msg);
469 if (new->path)
470 adjust_to_tracking(new, opts);
473 static int switch_branches(struct checkout_opts *opts,
474 struct branch_info *new, const char *prefix)
476 int ret = 0;
477 struct branch_info old;
478 unsigned char rev[20];
479 int flag;
480 memset(&old, 0, sizeof(old));
481 old.path = resolve_ref("HEAD", rev, 0, &flag);
482 old.commit = lookup_commit_reference_gently(rev, 1);
483 if (!(flag & REF_ISSYMREF))
484 old.path = NULL;
486 if (old.path && !prefixcmp(old.path, "refs/heads/"))
487 old.name = old.path + strlen("refs/heads/");
489 if (!new->name) {
490 new->name = "HEAD";
491 new->commit = old.commit;
492 if (!new->commit)
493 die("You are on a branch yet to be born");
494 parse_commit(new->commit);
498 * If the new thing isn't a branch and isn't HEAD and we're
499 * not starting a new branch, and we want messages, and we
500 * weren't on a branch, and we're moving to a new commit,
501 * describe the old commit.
503 if (!new->path && strcmp(new->name, "HEAD") && !opts->new_branch &&
504 !opts->quiet && !old.path && new->commit != old.commit)
505 describe_detached_head("Previous HEAD position was", old.commit);
507 if (!old.commit) {
508 if (!opts->quiet) {
509 fprintf(stderr, "warning: You appear to be on a branch yet to be born.\n");
510 fprintf(stderr, "warning: Forcing checkout of %s.\n", new->name);
512 opts->force = 1;
515 ret = merge_working_tree(opts, &old, new, prefix);
516 if (ret)
517 return ret;
519 update_refs_for_switch(opts, &old, new);
521 return post_checkout_hook(old.commit, new->commit, 1);
524 static int branch_track = 0;
526 static int git_checkout_config(const char *var, const char *value)
528 if (!strcmp(var, "branch.autosetupmerge"))
529 branch_track = git_config_bool(var, value);
531 return git_default_config(var, value);
534 int cmd_checkout(int argc, const char **argv, const char *prefix)
536 struct checkout_opts opts;
537 unsigned char rev[20];
538 const char *arg;
539 struct branch_info new;
540 struct tree *source_tree = NULL;
541 struct option options[] = {
542 OPT__QUIET(&opts.quiet),
543 OPT_STRING('b', NULL, &opts.new_branch, "new branch", "branch"),
544 OPT_BOOLEAN('l', NULL, &opts.new_branch_log, "log for new branch"),
545 OPT_BOOLEAN( 0 , "track", &opts.track, "track"),
546 OPT_BOOLEAN('f', NULL, &opts.force, "force"),
547 OPT_BOOLEAN('m', NULL, &opts.merge, "merge"),
548 OPT_END(),
551 memset(&opts, 0, sizeof(opts));
552 memset(&new, 0, sizeof(new));
554 git_config(git_checkout_config);
556 opts.track = branch_track;
558 argc = parse_options(argc, argv, options, checkout_usage, 0);
559 if (argc) {
560 arg = argv[0];
561 if (get_sha1(arg, rev))
563 else if ((new.commit = lookup_commit_reference_gently(rev, 1))) {
564 new.name = arg;
565 setup_branch_path(&new);
566 if (resolve_ref(new.path, rev, 1, NULL))
567 new.commit = lookup_commit_reference(rev);
568 else
569 new.path = NULL;
570 parse_commit(new.commit);
571 source_tree = new.commit->tree;
572 argv++;
573 argc--;
574 } else if ((source_tree = parse_tree_indirect(rev))) {
575 argv++;
576 argc--;
580 if (argc && !strcmp(argv[0], "--")) {
581 argv++;
582 argc--;
585 if (!opts.new_branch && (opts.track != branch_track))
586 die("git checkout: --track and --no-track require -b");
588 if (opts.force && opts.merge)
589 die("git checkout: -f and -m are incompatible");
591 if (argc) {
592 const char **pathspec = get_pathspec(prefix, argv);
593 /* Checkout paths */
594 if (opts.new_branch || opts.force || opts.merge) {
595 if (argc == 1) {
596 die("git checkout: updating paths is incompatible with switching branches/forcing\nDid you intend to checkout '%s' which can not be resolved as commit?", argv[0]);
597 } else {
598 die("git checkout: updating paths is incompatible with switching branches/forcing");
602 if (source_tree)
603 read_tree_some(source_tree, pathspec);
604 else
605 read_cache();
606 return checkout_paths(pathspec);
609 if (new.name && !new.commit) {
610 die("Cannot switch branch to a non-commit.");
613 return switch_branches(&opts, &new, prefix);