3 #include "parse-options.h"
8 #include "unpack-trees.h"
10 #include "run-command.h"
11 #include "merge-recursive.h"
17 static const char * const checkout_usage[] = {
18 "git checkout [options] <branch>",
19 "git checkout [options] [<branch>] -- <file>...",
23 struct checkout_opts {
30 const char *new_branch;
32 enum branch_track track;
35 static int post_checkout_hook(struct commit *old, struct commit *new,
38 struct child_process proc;
39 const char *name = git_path("hooks/post-checkout");
42 if (access(name, X_OK) < 0)
45 memset(&proc, 0, sizeof(proc));
47 argv[1] = xstrdup(sha1_to_hex(old->object.sha1));
48 argv[2] = xstrdup(sha1_to_hex(new->object.sha1));
49 argv[3] = changed ? "1" : "0";
53 proc.stdout_to_stderr = 1;
54 return run_command(&proc);
57 static int update_some(const unsigned char *sha1, const char *base, int baselen,
58 const char *pathname, unsigned mode, int stage, void *context)
61 struct cache_entry *ce;
63 if (S_ISGITLINK(mode))
67 return READ_TREE_RECURSIVE;
69 len = baselen + strlen(pathname);
70 ce = xcalloc(1, cache_entry_size(len));
71 hashcpy(ce->sha1, sha1);
72 memcpy(ce->name, base, baselen);
73 memcpy(ce->name + baselen, pathname, len - baselen);
74 ce->ce_flags = create_ce_flags(len, 0);
75 ce->ce_mode = create_ce_mode(mode);
76 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
80 static int read_tree_some(struct tree *tree, const char **pathspec)
82 read_tree_recursive(tree, "", 0, 0, pathspec, update_some, NULL);
84 /* update the index with the given tree's info
85 * for all args, expanding wildcards, and exit
86 * with any non-zero return code.
91 static int skip_same_name(struct cache_entry *ce, int pos)
93 while (++pos < active_nr &&
94 !strcmp(active_cache[pos]->name, ce->name))
99 static int check_stage(int stage, struct cache_entry *ce, int pos)
101 while (pos < active_nr &&
102 !strcmp(active_cache[pos]->name, ce->name)) {
103 if (ce_stage(active_cache[pos]) == stage)
107 return error("path '%s' does not have %s version",
109 (stage == 2) ? "our" : "their");
112 static int checkout_stage(int stage, struct cache_entry *ce, int pos,
113 struct checkout *state)
115 while (pos < active_nr &&
116 !strcmp(active_cache[pos]->name, ce->name)) {
117 if (ce_stage(active_cache[pos]) == stage)
118 return checkout_entry(active_cache[pos], state, NULL);
121 return error("path '%s' does not have %s version",
123 (stage == 2) ? "our" : "their");
126 static int checkout_paths(struct tree *source_tree, const char **pathspec,
127 struct checkout_opts *opts)
130 struct checkout state;
131 static char *ps_matched;
132 unsigned char rev[20];
136 int stage = opts->writeout_stage;
138 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
140 newfd = hold_locked_index(lock_file, 1);
144 read_tree_some(source_tree, pathspec);
146 for (pos = 0; pathspec[pos]; pos++)
148 ps_matched = xcalloc(1, pos);
150 for (pos = 0; pos < active_nr; pos++) {
151 struct cache_entry *ce = active_cache[pos];
152 pathspec_match(pathspec, ps_matched, ce->name, 0);
155 if (report_path_error(ps_matched, pathspec, 0))
158 /* Any unmerged paths? */
159 for (pos = 0; pos < active_nr; pos++) {
160 struct cache_entry *ce = active_cache[pos];
161 if (pathspec_match(pathspec, NULL, ce->name, 0)) {
165 warning("path '%s' is unmerged", ce->name);
167 errs |= check_stage(stage, ce, pos);
170 error("path '%s' is unmerged", ce->name);
172 pos = skip_same_name(ce, pos) - 1;
178 /* Now we are committed to check them out */
179 memset(&state, 0, sizeof(state));
181 state.refresh_cache = 1;
182 for (pos = 0; pos < active_nr; pos++) {
183 struct cache_entry *ce = active_cache[pos];
184 if (pathspec_match(pathspec, NULL, ce->name, 0)) {
186 errs |= checkout_entry(ce, &state, NULL);
190 errs |= checkout_stage(stage, ce, pos, &state);
191 pos = skip_same_name(ce, pos) - 1;
195 if (write_cache(newfd, active_cache, active_nr) ||
196 commit_locked_index(lock_file))
197 die("unable to write new index file");
199 resolve_ref("HEAD", rev, 0, &flag);
200 head = lookup_commit_reference_gently(rev, 1);
202 errs |= post_checkout_hook(head, head, 0);
206 static void show_local_changes(struct object *head)
209 /* I think we want full paths, even if we're in a subdirectory. */
210 init_revisions(&rev, NULL);
212 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS;
213 add_pending_object(&rev, head, NULL);
214 run_diff_index(&rev, 0);
217 static void describe_detached_head(char *msg, struct commit *commit)
221 parse_commit(commit);
222 pretty_print_commit(CMIT_FMT_ONELINE, commit, &sb, 0, NULL, NULL, 0, 0);
223 fprintf(stderr, "%s %s... %s\n", msg,
224 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV), sb.buf);
228 static int reset_tree(struct tree *tree, struct checkout_opts *o, int worktree)
230 struct unpack_trees_options opts;
231 struct tree_desc tree_desc;
233 memset(&opts, 0, sizeof(opts));
235 opts.update = worktree;
236 opts.skip_unmerged = !worktree;
239 opts.fn = oneway_merge;
240 opts.verbose_update = !o->quiet;
241 opts.src_index = &the_index;
242 opts.dst_index = &the_index;
244 init_tree_desc(&tree_desc, tree->buffer, tree->size);
245 switch (unpack_trees(1, &tree_desc, &opts)) {
247 o->writeout_error = 1;
249 * We return 0 nevertheless, as the index is all right
250 * and more importantly we have made best efforts to
251 * update paths in the work tree, and we cannot revert
262 const char *name; /* The short name used */
263 const char *path; /* The full name of a real branch */
264 struct commit *commit; /* The named commit */
267 static void setup_branch_path(struct branch_info *branch)
270 strbuf_init(&buf, 0);
271 strbuf_addstr(&buf, "refs/heads/");
272 strbuf_addstr(&buf, branch->name);
273 branch->path = strbuf_detach(&buf, NULL);
276 static int merge_working_tree(struct checkout_opts *opts,
277 struct branch_info *old, struct branch_info *new)
280 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
281 int newfd = hold_locked_index(lock_file, 1);
285 ret = reset_tree(new->commit->tree, opts, 1);
289 struct tree_desc trees[2];
291 struct unpack_trees_options topts;
293 memset(&topts, 0, sizeof(topts));
295 topts.src_index = &the_index;
296 topts.dst_index = &the_index;
298 topts.msgs.not_uptodate_file = "You have local changes to '%s'; cannot switch branches.";
300 refresh_cache(REFRESH_QUIET);
302 if (unmerged_cache()) {
303 error("you need to resolve your current index first");
307 /* 2-way merge to the new branch */
310 topts.gently = opts->merge;
311 topts.verbose_update = !opts->quiet;
312 topts.fn = twoway_merge;
313 topts.dir = xcalloc(1, sizeof(*topts.dir));
314 topts.dir->show_ignored = 1;
315 topts.dir->exclude_per_dir = ".gitignore";
316 tree = parse_tree_indirect(old->commit->object.sha1);
317 init_tree_desc(&trees[0], tree->buffer, tree->size);
318 tree = parse_tree_indirect(new->commit->object.sha1);
319 init_tree_desc(&trees[1], tree->buffer, tree->size);
321 ret = unpack_trees(2, trees, &topts);
324 * Unpack couldn't do a trivial merge; either
325 * give up or do a real merge, depending on
326 * whether the merge flag was used.
332 parse_commit(old->commit);
334 /* Do more real merge */
337 * We update the index fully, then write the
338 * tree from the index, then merge the new
339 * branch with the current tree, with the old
340 * branch as the base. Then we reset the index
341 * (but not the working tree) to the new
342 * branch, leaving the working tree as the
343 * merged version, but skipping unmerged
344 * entries in the index.
347 add_files_to_cache(NULL, NULL, 0);
348 work = write_tree_from_memory();
350 ret = reset_tree(new->commit->tree, opts, 1);
353 merge_trees(new->commit->tree, work, old->commit->tree,
354 new->name, "local", &result);
355 ret = reset_tree(new->commit->tree, opts, 0);
361 if (write_cache(newfd, active_cache, active_nr) ||
362 commit_locked_index(lock_file))
363 die("unable to write new index file");
366 show_local_changes(&new->commit->object);
371 static void report_tracking(struct branch_info *new)
373 struct strbuf sb = STRBUF_INIT;
374 struct branch *branch = branch_get(new->name);
376 if (!format_tracking_info(branch, &sb))
378 fputs(sb.buf, stdout);
382 static void update_refs_for_switch(struct checkout_opts *opts,
383 struct branch_info *old,
384 struct branch_info *new)
387 const char *old_desc;
388 if (opts->new_branch) {
389 create_branch(old->name, opts->new_branch, new->name, 0,
390 opts->new_branch_log, opts->track);
391 new->name = opts->new_branch;
392 setup_branch_path(new);
395 strbuf_init(&msg, 0);
396 old_desc = old->name;
398 old_desc = sha1_to_hex(old->commit->object.sha1);
399 strbuf_addf(&msg, "checkout: moving from %s to %s",
400 old_desc, new->name);
403 create_symref("HEAD", new->path, msg.buf);
405 if (old->path && !strcmp(new->path, old->path))
406 fprintf(stderr, "Already on \"%s\"\n",
409 fprintf(stderr, "Switched to%s branch \"%s\"\n",
410 opts->new_branch ? " a new" : "",
413 } else if (strcmp(new->name, "HEAD")) {
414 update_ref(msg.buf, "HEAD", new->commit->object.sha1, NULL,
415 REF_NODEREF, DIE_ON_ERR);
418 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);
419 describe_detached_head("HEAD is now at", new->commit);
422 remove_branch_state();
423 strbuf_release(&msg);
424 if (!opts->quiet && (new->path || !strcmp(new->name, "HEAD")))
425 report_tracking(new);
428 static int switch_branches(struct checkout_opts *opts, struct branch_info *new)
431 struct branch_info old;
432 unsigned char rev[20];
434 memset(&old, 0, sizeof(old));
435 old.path = resolve_ref("HEAD", rev, 0, &flag);
436 old.commit = lookup_commit_reference_gently(rev, 1);
437 if (!(flag & REF_ISSYMREF))
440 if (old.path && !prefixcmp(old.path, "refs/heads/"))
441 old.name = old.path + strlen("refs/heads/");
445 new->commit = old.commit;
447 die("You are on a branch yet to be born");
448 parse_commit(new->commit);
452 * If the new thing isn't a branch and isn't HEAD and we're
453 * not starting a new branch, and we want messages, and we
454 * weren't on a branch, and we're moving to a new commit,
455 * describe the old commit.
457 if (!new->path && strcmp(new->name, "HEAD") && !opts->new_branch &&
458 !opts->quiet && !old.path && new->commit != old.commit)
459 describe_detached_head("Previous HEAD position was", old.commit);
463 fprintf(stderr, "warning: You appear to be on a branch yet to be born.\n");
464 fprintf(stderr, "warning: Forcing checkout of %s.\n", new->name);
469 ret = merge_working_tree(opts, &old, new);
473 update_refs_for_switch(opts, &old, new);
475 ret = post_checkout_hook(old.commit, new->commit, 1);
476 return ret || opts->writeout_error;
479 int cmd_checkout(int argc, const char **argv, const char *prefix)
481 struct checkout_opts opts;
482 unsigned char rev[20];
484 struct branch_info new;
485 struct tree *source_tree = NULL;
486 struct option options[] = {
487 OPT__QUIET(&opts.quiet),
488 OPT_STRING('b', NULL, &opts.new_branch, "new branch", "branch"),
489 OPT_BOOLEAN('l', NULL, &opts.new_branch_log, "log for new branch"),
490 OPT_SET_INT('t', "track", &opts.track, "track",
491 BRANCH_TRACK_EXPLICIT),
492 OPT_SET_INT('2', "ours", &opts.writeout_stage, "stage",
494 OPT_SET_INT('3', "theirs", &opts.writeout_stage, "stage",
496 OPT_BOOLEAN('f', NULL, &opts.force, "force"),
497 OPT_BOOLEAN('m', NULL, &opts.merge, "merge"),
502 memset(&opts, 0, sizeof(opts));
503 memset(&new, 0, sizeof(new));
505 git_config(git_default_config, NULL);
507 opts.track = git_branch_track;
509 argc = parse_options(argc, argv, options, checkout_usage,
510 PARSE_OPT_KEEP_DASHDASH);
512 if (!opts.new_branch && (opts.track != git_branch_track))
513 die("git checkout: --track and --no-track require -b");
515 if (opts.force && opts.merge)
516 die("git checkout: -f and -m are incompatible");
519 * case 1: git checkout <ref> -- [<paths>]
521 * <ref> must be a valid tree, everything after the '--' must be
524 * case 2: git checkout -- [<paths>]
526 * everything after the '--' must be paths.
528 * case 3: git checkout <something> [<paths>]
530 * With no paths, if <something> is a commit, that is to
531 * switch to the branch or detach HEAD at it.
533 * Otherwise <something> shall not be ambiguous.
534 * - If it's *only* a reference, treat it like case (1).
535 * - If it's only a path, treat it like case (2).
540 if (!strcmp(argv[0], "--")) { /* case (2) */
547 has_dash_dash = (argc > 1) && !strcmp(argv[1], "--");
549 if (get_sha1(arg, rev)) {
550 if (has_dash_dash) /* case (1) */
551 die("invalid reference: %s", arg);
552 goto no_reference; /* case (3 -> 2) */
555 /* we can't end up being in (2) anymore, eat the argument */
559 if ((new.commit = lookup_commit_reference_gently(rev, 1))) {
561 setup_branch_path(&new);
562 if (resolve_ref(new.path, rev, 1, NULL))
563 new.commit = lookup_commit_reference(rev);
566 parse_commit(new.commit);
567 source_tree = new.commit->tree;
569 source_tree = parse_tree_indirect(rev);
571 if (!source_tree) /* case (1): want a tree */
572 die("reference is not a tree: %s", arg);
573 if (!has_dash_dash) {/* case (3 -> 1) */
575 * Do not complain the most common case
576 * git checkout branch
577 * even if there happen to be a file called 'branch';
578 * it would be extremely annoying.
581 verify_non_filename(NULL, arg);
591 const char **pathspec = get_pathspec(prefix, argv);
594 die("invalid path specification");
597 if (opts.new_branch || opts.merge) {
599 die("git checkout: updating paths is incompatible with switching branches.\nDid you intend to checkout '%s' which can not be resolved as commit?", argv[0]);
601 die("git checkout: updating paths is incompatible with switching branches.");
605 return checkout_paths(source_tree, pathspec, &opts);
608 if (new.name && !new.commit) {
609 die("Cannot switch branch to a non-commit.");
611 if (opts.writeout_stage)
612 die("--ours/--theirs is incompatible with switching branches.");
614 return switch_branches(&opts, &new);