Fix gitdir detection when in subdir of gitdir
[git/vmiklos.git] / builtin-checkout.c
blobc107fd643a452edb016f7ad867d4b2a555d9abaf
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 ? old->object.sha1 : null_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, void *context)
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 read_tree_recursive(tree, "", 0, 0, pathspec, update_some, NULL);
72 /* update the index with the given tree's info
73 * for all args, expanding wildcards, and exit
74 * with any non-zero return code.
76 return 0;
79 static int skip_same_name(struct cache_entry *ce, int pos)
81 while (++pos < active_nr &&
82 !strcmp(active_cache[pos]->name, ce->name))
83 ; /* skip */
84 return pos;
88 static int checkout_paths(struct tree *source_tree, 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;
96 int errs = 0;
98 int newfd;
99 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
101 newfd = hold_locked_index(lock_file, 1);
102 read_cache();
104 if (source_tree)
105 read_tree_some(source_tree, pathspec);
107 for (pos = 0; pathspec[pos]; pos++)
109 ps_matched = xcalloc(1, pos);
111 for (pos = 0; pos < active_nr; pos++) {
112 struct cache_entry *ce = active_cache[pos];
113 pathspec_match(pathspec, ps_matched, ce->name, 0);
116 if (report_path_error(ps_matched, pathspec, 0))
117 return 1;
119 /* Any unmerged paths? */
120 for (pos = 0; pos < active_nr; pos++) {
121 struct cache_entry *ce = active_cache[pos];
122 if (pathspec_match(pathspec, NULL, ce->name, 0)) {
123 if (!ce_stage(ce))
124 continue;
125 errs = 1;
126 error("path '%s' is unmerged", ce->name);
127 pos = skip_same_name(ce, pos) - 1;
130 if (errs)
131 return 1;
133 /* Now we are committed to check them out */
134 memset(&state, 0, sizeof(state));
135 state.force = 1;
136 state.refresh_cache = 1;
137 for (pos = 0; pos < active_nr; pos++) {
138 struct cache_entry *ce = active_cache[pos];
139 if (pathspec_match(pathspec, NULL, ce->name, 0)) {
140 if (!ce_stage(ce)) {
141 errs |= checkout_entry(ce, &state, NULL);
142 continue;
144 pos = skip_same_name(ce, pos) - 1;
148 if (write_cache(newfd, active_cache, active_nr) ||
149 commit_locked_index(lock_file))
150 die("unable to write new index file");
152 resolve_ref("HEAD", rev, 0, &flag);
153 head = lookup_commit_reference_gently(rev, 1);
155 errs |= post_checkout_hook(head, head, 0);
156 return errs;
159 static void show_local_changes(struct object *head)
161 struct rev_info rev;
162 /* I think we want full paths, even if we're in a subdirectory. */
163 init_revisions(&rev, NULL);
164 rev.abbrev = 0;
165 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS;
166 add_pending_object(&rev, head, NULL);
167 run_diff_index(&rev, 0);
170 static void describe_detached_head(char *msg, struct commit *commit)
172 struct strbuf sb;
173 strbuf_init(&sb, 0);
174 parse_commit(commit);
175 pretty_print_commit(CMIT_FMT_ONELINE, commit, &sb, 0, NULL, NULL, 0, 0);
176 fprintf(stderr, "%s %s... %s\n", msg,
177 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV), sb.buf);
178 strbuf_release(&sb);
181 struct checkout_opts {
182 int quiet;
183 int merge;
184 int force;
185 int writeout_error;
187 char *new_branch;
188 int new_branch_log;
189 enum branch_track track;
192 static int reset_tree(struct tree *tree, struct checkout_opts *o, int worktree)
194 struct unpack_trees_options opts;
195 struct tree_desc tree_desc;
197 memset(&opts, 0, sizeof(opts));
198 opts.head_idx = -1;
199 opts.update = worktree;
200 opts.skip_unmerged = !worktree;
201 opts.reset = 1;
202 opts.merge = 1;
203 opts.fn = oneway_merge;
204 opts.verbose_update = !o->quiet;
205 opts.src_index = &the_index;
206 opts.dst_index = &the_index;
207 parse_tree(tree);
208 init_tree_desc(&tree_desc, tree->buffer, tree->size);
209 switch (unpack_trees(1, &tree_desc, &opts)) {
210 case -2:
211 o->writeout_error = 1;
213 * We return 0 nevertheless, as the index is all right
214 * and more importantly we have made best efforts to
215 * update paths in the work tree, and we cannot revert
216 * them.
218 case 0:
219 return 0;
220 default:
221 return 128;
225 struct branch_info {
226 const char *name; /* The short name used */
227 const char *path; /* The full name of a real branch */
228 struct commit *commit; /* The named commit */
231 static void setup_branch_path(struct branch_info *branch)
233 struct strbuf buf;
234 strbuf_init(&buf, 0);
235 strbuf_addstr(&buf, "refs/heads/");
236 strbuf_addstr(&buf, branch->name);
237 branch->path = strbuf_detach(&buf, NULL);
240 static int merge_working_tree(struct checkout_opts *opts,
241 struct branch_info *old, struct branch_info *new)
243 int ret;
244 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
245 int newfd = hold_locked_index(lock_file, 1);
246 read_cache();
248 if (opts->force) {
249 ret = reset_tree(new->commit->tree, opts, 1);
250 if (ret)
251 return ret;
252 } else {
253 struct tree_desc trees[2];
254 struct tree *tree;
255 struct unpack_trees_options topts;
257 memset(&topts, 0, sizeof(topts));
258 topts.head_idx = -1;
259 topts.src_index = &the_index;
260 topts.dst_index = &the_index;
262 topts.msgs.not_uptodate_file = "You have local changes to '%s'; cannot switch branches.";
264 refresh_cache(REFRESH_QUIET);
266 if (unmerged_cache()) {
267 error("you need to resolve your current index first");
268 return 1;
271 /* 2-way merge to the new branch */
272 topts.initial_checkout = is_cache_unborn();
273 topts.update = 1;
274 topts.merge = 1;
275 topts.gently = opts->merge;
276 topts.verbose_update = !opts->quiet;
277 topts.fn = twoway_merge;
278 topts.dir = xcalloc(1, sizeof(*topts.dir));
279 topts.dir->show_ignored = 1;
280 topts.dir->exclude_per_dir = ".gitignore";
281 tree = parse_tree_indirect(old->commit->object.sha1);
282 init_tree_desc(&trees[0], tree->buffer, tree->size);
283 tree = parse_tree_indirect(new->commit->object.sha1);
284 init_tree_desc(&trees[1], tree->buffer, tree->size);
286 ret = unpack_trees(2, trees, &topts);
287 if (ret == -1) {
289 * Unpack couldn't do a trivial merge; either
290 * give up or do a real merge, depending on
291 * whether the merge flag was used.
293 struct tree *result;
294 struct tree *work;
295 if (!opts->merge)
296 return 1;
297 parse_commit(old->commit);
299 /* Do more real merge */
302 * We update the index fully, then write the
303 * tree from the index, then merge the new
304 * branch with the current tree, with the old
305 * branch as the base. Then we reset the index
306 * (but not the working tree) to the new
307 * branch, leaving the working tree as the
308 * merged version, but skipping unmerged
309 * entries in the index.
312 add_files_to_cache(NULL, NULL, 0);
313 work = write_tree_from_memory();
315 ret = reset_tree(new->commit->tree, opts, 1);
316 if (ret)
317 return ret;
318 merge_trees(new->commit->tree, work, old->commit->tree,
319 new->name, "local", &result);
320 ret = reset_tree(new->commit->tree, opts, 0);
321 if (ret)
322 return ret;
326 if (write_cache(newfd, active_cache, active_nr) ||
327 commit_locked_index(lock_file))
328 die("unable to write new index file");
330 if (!opts->force && !opts->quiet)
331 show_local_changes(&new->commit->object);
333 return 0;
336 static void report_tracking(struct branch_info *new)
338 struct strbuf sb = STRBUF_INIT;
339 struct branch *branch = branch_get(new->name);
341 if (!format_tracking_info(branch, &sb))
342 return;
343 fputs(sb.buf, stdout);
344 strbuf_release(&sb);
347 static void update_refs_for_switch(struct checkout_opts *opts,
348 struct branch_info *old,
349 struct branch_info *new)
351 struct strbuf msg;
352 const char *old_desc;
353 if (opts->new_branch) {
354 create_branch(old->name, opts->new_branch, new->name, 0,
355 opts->new_branch_log, opts->track);
356 new->name = opts->new_branch;
357 setup_branch_path(new);
360 strbuf_init(&msg, 0);
361 old_desc = old->name;
362 if (!old_desc && old->commit)
363 old_desc = sha1_to_hex(old->commit->object.sha1);
364 strbuf_addf(&msg, "checkout: moving from %s to %s",
365 old_desc ? old_desc : "(invalid)", new->name);
367 if (new->path) {
368 create_symref("HEAD", new->path, msg.buf);
369 if (!opts->quiet) {
370 if (old->path && !strcmp(new->path, old->path))
371 fprintf(stderr, "Already on \"%s\"\n",
372 new->name);
373 else
374 fprintf(stderr, "Switched to%s branch \"%s\"\n",
375 opts->new_branch ? " a new" : "",
376 new->name);
378 } else if (strcmp(new->name, "HEAD")) {
379 update_ref(msg.buf, "HEAD", new->commit->object.sha1, NULL,
380 REF_NODEREF, DIE_ON_ERR);
381 if (!opts->quiet) {
382 if (old->path)
383 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);
384 describe_detached_head("HEAD is now at", new->commit);
387 remove_branch_state();
388 strbuf_release(&msg);
389 if (!opts->quiet && (new->path || !strcmp(new->name, "HEAD")))
390 report_tracking(new);
393 static int switch_branches(struct checkout_opts *opts, struct branch_info *new)
395 int ret = 0;
396 struct branch_info old;
397 unsigned char rev[20];
398 int flag;
399 memset(&old, 0, sizeof(old));
400 old.path = resolve_ref("HEAD", rev, 0, &flag);
401 old.commit = lookup_commit_reference_gently(rev, 1);
402 if (!(flag & REF_ISSYMREF))
403 old.path = NULL;
405 if (old.path && !prefixcmp(old.path, "refs/heads/"))
406 old.name = old.path + strlen("refs/heads/");
408 if (!new->name) {
409 new->name = "HEAD";
410 new->commit = old.commit;
411 if (!new->commit)
412 die("You are on a branch yet to be born");
413 parse_commit(new->commit);
417 * If we were on a detached HEAD, but we are now moving to
418 * a new commit, we want to mention the old commit once more
419 * to remind the user that it might be lost.
421 if (!opts->quiet && !old.path && old.commit && new->commit != old.commit)
422 describe_detached_head("Previous HEAD position was", old.commit);
424 if (!old.commit && !opts->force) {
425 if (!opts->quiet) {
426 fprintf(stderr, "warning: You appear to be on a branch yet to be born.\n");
427 fprintf(stderr, "warning: Forcing checkout of %s.\n", new->name);
429 opts->force = 1;
432 ret = merge_working_tree(opts, &old, new);
433 if (ret)
434 return ret;
436 update_refs_for_switch(opts, &old, new);
438 ret = post_checkout_hook(old.commit, new->commit, 1);
439 return ret || opts->writeout_error;
442 int cmd_checkout(int argc, const char **argv, const char *prefix)
444 struct checkout_opts opts;
445 unsigned char rev[20];
446 const char *arg;
447 struct branch_info new;
448 struct tree *source_tree = NULL;
449 struct option options[] = {
450 OPT__QUIET(&opts.quiet),
451 OPT_STRING('b', NULL, &opts.new_branch, "new branch", "branch"),
452 OPT_BOOLEAN('l', NULL, &opts.new_branch_log, "log for new branch"),
453 OPT_SET_INT('t', "track", &opts.track, "track",
454 BRANCH_TRACK_EXPLICIT),
455 OPT_BOOLEAN('f', NULL, &opts.force, "force"),
456 OPT_BOOLEAN('m', NULL, &opts.merge, "merge"),
457 OPT_END(),
459 int has_dash_dash;
461 memset(&opts, 0, sizeof(opts));
462 memset(&new, 0, sizeof(new));
464 git_config(git_default_config, NULL);
466 opts.track = git_branch_track;
468 argc = parse_options(argc, argv, options, checkout_usage,
469 PARSE_OPT_KEEP_DASHDASH);
471 if (!opts.new_branch && (opts.track != git_branch_track))
472 die("git checkout: --track and --no-track require -b");
474 if (opts.force && opts.merge)
475 die("git checkout: -f and -m are incompatible");
478 * case 1: git checkout <ref> -- [<paths>]
480 * <ref> must be a valid tree, everything after the '--' must be
481 * a path.
483 * case 2: git checkout -- [<paths>]
485 * everything after the '--' must be paths.
487 * case 3: git checkout <something> [<paths>]
489 * With no paths, if <something> is a commit, that is to
490 * switch to the branch or detach HEAD at it.
492 * Otherwise <something> shall not be ambiguous.
493 * - If it's *only* a reference, treat it like case (1).
494 * - If it's only a path, treat it like case (2).
495 * - else: fail.
498 if (argc) {
499 if (!strcmp(argv[0], "--")) { /* case (2) */
500 argv++;
501 argc--;
502 goto no_reference;
505 arg = argv[0];
506 has_dash_dash = (argc > 1) && !strcmp(argv[1], "--");
508 if (get_sha1(arg, rev)) {
509 if (has_dash_dash) /* case (1) */
510 die("invalid reference: %s", arg);
511 goto no_reference; /* case (3 -> 2) */
514 /* we can't end up being in (2) anymore, eat the argument */
515 argv++;
516 argc--;
518 if ((new.commit = lookup_commit_reference_gently(rev, 1))) {
519 new.name = arg;
520 setup_branch_path(&new);
521 if (resolve_ref(new.path, rev, 1, NULL))
522 new.commit = lookup_commit_reference(rev);
523 else
524 new.path = NULL;
525 parse_commit(new.commit);
526 source_tree = new.commit->tree;
527 } else
528 source_tree = parse_tree_indirect(rev);
530 if (!source_tree) /* case (1): want a tree */
531 die("reference is not a tree: %s", arg);
532 if (!has_dash_dash) {/* case (3 -> 1) */
534 * Do not complain the most common case
535 * git checkout branch
536 * even if there happen to be a file called 'branch';
537 * it would be extremely annoying.
539 if (argc)
540 verify_non_filename(NULL, arg);
542 else {
543 argv++;
544 argc--;
548 no_reference:
549 if (argc) {
550 const char **pathspec = get_pathspec(prefix, argv);
552 if (!pathspec)
553 die("invalid path specification");
555 /* Checkout paths */
556 if (opts.new_branch || opts.force || opts.merge) {
557 if (argc == 1) {
558 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]);
559 } else {
560 die("git checkout: updating paths is incompatible with switching branches/forcing");
564 return checkout_paths(source_tree, pathspec);
567 if (opts.new_branch) {
568 struct strbuf buf;
569 strbuf_init(&buf, 0);
570 strbuf_addstr(&buf, "refs/heads/");
571 strbuf_addstr(&buf, opts.new_branch);
572 if (!get_sha1(buf.buf, rev))
573 die("git checkout: branch %s already exists", opts.new_branch);
574 if (check_ref_format(buf.buf))
575 die("git checkout: we do not like '%s' as a branch name.", opts.new_branch);
576 strbuf_release(&buf);
579 if (new.name && !new.commit) {
580 die("Cannot switch branch to a non-commit.");
583 return switch_branches(&opts, &new);