Merge branch 'jc/maint-checkout-fix' into 'jc/better-conflict-resolution'
[git/git.git] / builtin-checkout.c
CommitLineData
782c2d65
DB
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"
79a1e6b4 15#include "remote.h"
782c2d65
DB
16
17static const char * const checkout_usage[] = {
18 "git checkout [options] <branch>",
19 "git checkout [options] [<branch>] -- <file>...",
20 NULL,
21};
22
db941099
JH
23struct checkout_opts {
24 int quiet;
25 int merge;
26 int force;
38901a48 27 int writeout_stage;
db941099
JH
28 int writeout_error;
29
30 const char *new_branch;
31 int new_branch_log;
32 enum branch_track track;
33};
34
782c2d65
DB
35static int post_checkout_hook(struct commit *old, struct commit *new,
36 int changed)
37{
38 struct child_process proc;
39 const char *name = git_path("hooks/post-checkout");
40 const char *argv[5];
41
42 if (access(name, X_OK) < 0)
43 return 0;
44
45 memset(&proc, 0, sizeof(proc));
46 argv[0] = name;
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";
50 argv[4] = NULL;
51 proc.argv = argv;
52 proc.no_stdin = 1;
53 proc.stdout_to_stderr = 1;
54 return run_command(&proc);
55}
56
57static int update_some(const unsigned char *sha1, const char *base, int baselen,
671f0707 58 const char *pathname, unsigned mode, int stage, void *context)
782c2d65
DB
59{
60 int len;
61 struct cache_entry *ce;
62
63 if (S_ISGITLINK(mode))
64 return 0;
65
66 if (S_ISDIR(mode))
67 return READ_TREE_RECURSIVE;
68
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);
77 return 0;
78}
79
80static int read_tree_some(struct tree *tree, const char **pathspec)
81{
671f0707 82 read_tree_recursive(tree, "", 0, 0, pathspec, update_some, NULL);
782c2d65 83
782c2d65
DB
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.
87 */
88 return 0;
89}
90
8fdcf312
JH
91static int skip_same_name(struct cache_entry *ce, int pos)
92{
93 while (++pos < active_nr &&
94 !strcmp(active_cache[pos]->name, ce->name))
95 ; /* skip */
96 return pos;
97}
98
38901a48
JH
99static int check_stage(int stage, struct cache_entry *ce, int pos)
100{
101 while (pos < active_nr &&
102 !strcmp(active_cache[pos]->name, ce->name)) {
103 if (ce_stage(active_cache[pos]) == stage)
104 return 0;
105 pos++;
106 }
107 return error("path '%s' does not have %s version",
108 ce->name,
109 (stage == 2) ? "our" : "their");
110}
111
112static int checkout_stage(int stage, struct cache_entry *ce, int pos,
113 struct checkout *state)
114{
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);
119 pos++;
120 }
121 return error("path '%s' does not have %s version",
122 ce->name,
123 (stage == 2) ? "our" : "their");
124}
8fdcf312 125
db941099
JH
126static int checkout_paths(struct tree *source_tree, const char **pathspec,
127 struct checkout_opts *opts)
782c2d65
DB
128{
129 int pos;
130 struct checkout state;
131 static char *ps_matched;
132 unsigned char rev[20];
133 int flag;
134 struct commit *head;
d2b3691b 135 int errs = 0;
38901a48 136 int stage = opts->writeout_stage;
75336878
DB
137 int newfd;
138 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
139
140 newfd = hold_locked_index(lock_file, 1);
141 read_cache();
142
143 if (source_tree)
144 read_tree_some(source_tree, pathspec);
145
782c2d65
DB
146 for (pos = 0; pathspec[pos]; pos++)
147 ;
148 ps_matched = xcalloc(1, pos);
149
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);
153 }
154
155 if (report_path_error(ps_matched, pathspec, 0))
156 return 1;
157
8fdcf312
JH
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)) {
162 if (!ce_stage(ce))
163 continue;
db941099
JH
164 if (opts->force) {
165 warning("path '%s' is unmerged", ce->name);
38901a48
JH
166 } else if (stage) {
167 errs |= check_stage(stage, ce, pos);
db941099
JH
168 } else {
169 errs = 1;
170 error("path '%s' is unmerged", ce->name);
171 }
8fdcf312
JH
172 pos = skip_same_name(ce, pos) - 1;
173 }
174 }
175 if (errs)
176 return 1;
177
d2b3691b 178 /* Now we are committed to check them out */
782c2d65
DB
179 memset(&state, 0, sizeof(state));
180 state.force = 1;
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)) {
8fdcf312
JH
185 if (!ce_stage(ce)) {
186 errs |= checkout_entry(ce, &state, NULL);
187 continue;
188 }
38901a48
JH
189 if (stage)
190 errs |= checkout_stage(stage, ce, pos, &state);
8fdcf312 191 pos = skip_same_name(ce, pos) - 1;
782c2d65
DB
192 }
193 }
194
75336878
DB
195 if (write_cache(newfd, active_cache, active_nr) ||
196 commit_locked_index(lock_file))
197 die("unable to write new index file");
198
782c2d65
DB
199 resolve_ref("HEAD", rev, 0, &flag);
200 head = lookup_commit_reference_gently(rev, 1);
201
d2b3691b
JH
202 errs |= post_checkout_hook(head, head, 0);
203 return errs;
782c2d65
DB
204}
205
206static void show_local_changes(struct object *head)
207{
208 struct rev_info rev;
209 /* I think we want full paths, even if we're in a subdirectory. */
210 init_revisions(&rev, NULL);
211 rev.abbrev = 0;
212 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS;
213 add_pending_object(&rev, head, NULL);
214 run_diff_index(&rev, 0);
215}
216
217static void describe_detached_head(char *msg, struct commit *commit)
218{
219 struct strbuf sb;
220 strbuf_init(&sb, 0);
221 parse_commit(commit);
27886318 222 pretty_print_commit(CMIT_FMT_ONELINE, commit, &sb, 0, NULL, NULL, 0, 0);
782c2d65
DB
223 fprintf(stderr, "%s %s... %s\n", msg,
224 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV), sb.buf);
225 strbuf_release(&sb);
226}
227
6286a08d 228static int reset_tree(struct tree *tree, struct checkout_opts *o, int worktree)
782c2d65
DB
229{
230 struct unpack_trees_options opts;
231 struct tree_desc tree_desc;
bc052d7f 232
782c2d65
DB
233 memset(&opts, 0, sizeof(opts));
234 opts.head_idx = -1;
6286a08d
JH
235 opts.update = worktree;
236 opts.skip_unmerged = !worktree;
782c2d65
DB
237 opts.reset = 1;
238 opts.merge = 1;
239 opts.fn = oneway_merge;
6286a08d 240 opts.verbose_update = !o->quiet;
34110cd4
LT
241 opts.src_index = &the_index;
242 opts.dst_index = &the_index;
782c2d65
DB
243 parse_tree(tree);
244 init_tree_desc(&tree_desc, tree->buffer, tree->size);
291d823e
JH
245 switch (unpack_trees(1, &tree_desc, &opts)) {
246 case -2:
247 o->writeout_error = 1;
248 /*
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
252 * them.
253 */
254 case 0:
255 return 0;
256 default:
84a5750b 257 return 128;
291d823e 258 }
782c2d65
DB
259}
260
782c2d65
DB
261struct branch_info {
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 */
265};
266
267static void setup_branch_path(struct branch_info *branch)
268{
269 struct strbuf buf;
270 strbuf_init(&buf, 0);
271 strbuf_addstr(&buf, "refs/heads/");
272 strbuf_addstr(&buf, branch->name);
273 branch->path = strbuf_detach(&buf, NULL);
274}
275
276static int merge_working_tree(struct checkout_opts *opts,
75ea38df 277 struct branch_info *old, struct branch_info *new)
782c2d65
DB
278{
279 int ret;
280 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
281 int newfd = hold_locked_index(lock_file, 1);
282 read_cache();
283
284 if (opts->force) {
6286a08d 285 ret = reset_tree(new->commit->tree, opts, 1);
782c2d65
DB
286 if (ret)
287 return ret;
288 } else {
289 struct tree_desc trees[2];
290 struct tree *tree;
291 struct unpack_trees_options topts;
bc052d7f 292
782c2d65
DB
293 memset(&topts, 0, sizeof(topts));
294 topts.head_idx = -1;
34110cd4
LT
295 topts.src_index = &the_index;
296 topts.dst_index = &the_index;
782c2d65 297
8ccba008
JH
298 topts.msgs.not_uptodate_file = "You have local changes to '%s'; cannot switch branches.";
299
782c2d65
DB
300 refresh_cache(REFRESH_QUIET);
301
302 if (unmerged_cache()) {
04c9e11f
JH
303 error("you need to resolve your current index first");
304 return 1;
782c2d65 305 }
04c9e11f
JH
306
307 /* 2-way merge to the new branch */
308 topts.update = 1;
309 topts.merge = 1;
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);
320
291d823e
JH
321 ret = unpack_trees(2, trees, &topts);
322 if (ret == -1) {
782c2d65
DB
323 /*
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.
327 */
328 struct tree *result;
329 struct tree *work;
330 if (!opts->merge)
331 return 1;
332 parse_commit(old->commit);
333
334 /* Do more real merge */
335
336 /*
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.
345 */
346
7ae02a30 347 add_files_to_cache(NULL, NULL, 0);
782c2d65
DB
348 work = write_tree_from_memory();
349
6286a08d 350 ret = reset_tree(new->commit->tree, opts, 1);
782c2d65
DB
351 if (ret)
352 return ret;
353 merge_trees(new->commit->tree, work, old->commit->tree,
354 new->name, "local", &result);
6286a08d 355 ret = reset_tree(new->commit->tree, opts, 0);
84a5750b
JH
356 if (ret)
357 return ret;
782c2d65
DB
358 }
359 }
360
361 if (write_cache(newfd, active_cache, active_nr) ||
362 commit_locked_index(lock_file))
363 die("unable to write new index file");
364
365 if (!opts->force)
366 show_local_changes(&new->commit->object);
367
368 return 0;
369}
370
6d21bf96 371static void report_tracking(struct branch_info *new)
79a1e6b4 372{
6d21bf96 373 struct strbuf sb = STRBUF_INIT;
b56fca07 374 struct branch *branch = branch_get(new->name);
79a1e6b4 375
6d21bf96 376 if (!format_tracking_info(branch, &sb))
79a1e6b4 377 return;
6d21bf96
JH
378 fputs(sb.buf, stdout);
379 strbuf_release(&sb);
b0030db3 380}
79a1e6b4 381
782c2d65
DB
382static void update_refs_for_switch(struct checkout_opts *opts,
383 struct branch_info *old,
384 struct branch_info *new)
385{
386 struct strbuf msg;
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);
393 }
394
395 strbuf_init(&msg, 0);
396 old_desc = old->name;
397 if (!old_desc)
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);
401
402 if (new->path) {
403 create_symref("HEAD", new->path, msg.buf);
404 if (!opts->quiet) {
405 if (old->path && !strcmp(new->path, old->path))
406 fprintf(stderr, "Already on \"%s\"\n",
407 new->name);
408 else
409 fprintf(stderr, "Switched to%s branch \"%s\"\n",
410 opts->new_branch ? " a new" : "",
411 new->name);
412 }
413 } else if (strcmp(new->name, "HEAD")) {
414 update_ref(msg.buf, "HEAD", new->commit->object.sha1, NULL,
415 REF_NODEREF, DIE_ON_ERR);
416 if (!opts->quiet) {
417 if (old->path)
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);
420 }
421 }
422 remove_branch_state();
423 strbuf_release(&msg);
b0030db3 424 if (!opts->quiet && (new->path || !strcmp(new->name, "HEAD")))
6d21bf96 425 report_tracking(new);
782c2d65
DB
426}
427
75ea38df 428static int switch_branches(struct checkout_opts *opts, struct branch_info *new)
782c2d65
DB
429{
430 int ret = 0;
431 struct branch_info old;
432 unsigned char rev[20];
433 int flag;
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))
438 old.path = NULL;
439
440 if (old.path && !prefixcmp(old.path, "refs/heads/"))
441 old.name = old.path + strlen("refs/heads/");
442
443 if (!new->name) {
444 new->name = "HEAD";
445 new->commit = old.commit;
446 if (!new->commit)
447 die("You are on a branch yet to be born");
448 parse_commit(new->commit);
449 }
450
451 /*
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.
456 */
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);
460
461 if (!old.commit) {
462 if (!opts->quiet) {
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);
465 }
466 opts->force = 1;
467 }
468
75ea38df 469 ret = merge_working_tree(opts, &old, new);
782c2d65
DB
470 if (ret)
471 return ret;
472
473 update_refs_for_switch(opts, &old, new);
474
291d823e
JH
475 ret = post_checkout_hook(old.commit, new->commit, 1);
476 return ret || opts->writeout_error;
782c2d65
DB
477}
478
782c2d65
DB
479int cmd_checkout(int argc, const char **argv, const char *prefix)
480{
481 struct checkout_opts opts;
482 unsigned char rev[20];
483 const char *arg;
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"),
498a6e7e 490 OPT_SET_INT('t', "track", &opts.track, "track",
9ed36cfa 491 BRANCH_TRACK_EXPLICIT),
38901a48
JH
492 OPT_SET_INT('2', "ours", &opts.writeout_stage, "stage",
493 2),
494 OPT_SET_INT('3', "theirs", &opts.writeout_stage, "stage",
495 3),
782c2d65
DB
496 OPT_BOOLEAN('f', NULL, &opts.force, "force"),
497 OPT_BOOLEAN('m', NULL, &opts.merge, "merge"),
b249b552 498 OPT_END(),
782c2d65 499 };
859fdaba 500 int has_dash_dash;
782c2d65
DB
501
502 memset(&opts, 0, sizeof(opts));
503 memset(&new, 0, sizeof(new));
504
ef90d6d4 505 git_config(git_default_config, NULL);
782c2d65 506
9ed36cfa 507 opts.track = git_branch_track;
782c2d65 508
f5242ebf
PH
509 argc = parse_options(argc, argv, options, checkout_usage,
510 PARSE_OPT_KEEP_DASHDASH);
859fdaba
PH
511
512 if (!opts.new_branch && (opts.track != git_branch_track))
513 die("git checkout: --track and --no-track require -b");
514
515 if (opts.force && opts.merge)
516 die("git checkout: -f and -m are incompatible");
517
518 /*
519 * case 1: git checkout <ref> -- [<paths>]
520 *
521 * <ref> must be a valid tree, everything after the '--' must be
522 * a path.
523 *
524 * case 2: git checkout -- [<paths>]
525 *
526 * everything after the '--' must be paths.
527 *
528 * case 3: git checkout <something> [<paths>]
529 *
530 * With no paths, if <something> is a commit, that is to
531 * switch to the branch or detach HEAD at it.
532 *
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).
536 * - else: fail.
537 *
538 */
782c2d65 539 if (argc) {
859fdaba
PH
540 if (!strcmp(argv[0], "--")) { /* case (2) */
541 argv++;
542 argc--;
543 goto no_reference;
544 }
545
782c2d65 546 arg = argv[0];
859fdaba
PH
547 has_dash_dash = (argc > 1) && !strcmp(argv[1], "--");
548
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) */
553 }
554
555 /* we can't end up being in (2) anymore, eat the argument */
556 argv++;
557 argc--;
558
559 if ((new.commit = lookup_commit_reference_gently(rev, 1))) {
782c2d65
DB
560 new.name = arg;
561 setup_branch_path(&new);
562 if (resolve_ref(new.path, rev, 1, NULL))
563 new.commit = lookup_commit_reference(rev);
564 else
565 new.path = NULL;
566 parse_commit(new.commit);
567 source_tree = new.commit->tree;
859fdaba
PH
568 } else
569 source_tree = parse_tree_indirect(rev);
570
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) */
574 /*
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.
579 */
580 if (argc)
581 verify_non_filename(NULL, arg);
582 }
583 else {
782c2d65
DB
584 argv++;
585 argc--;
586 }
587 }
588
859fdaba 589no_reference:
782c2d65
DB
590 if (argc) {
591 const char **pathspec = get_pathspec(prefix, argv);
301e42ed
AR
592
593 if (!pathspec)
594 die("invalid path specification");
595
782c2d65 596 /* Checkout paths */
db941099 597 if (opts.new_branch || opts.merge) {
782c2d65 598 if (argc == 1) {
db941099 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]);
782c2d65 600 } else {
db941099 601 die("git checkout: updating paths is incompatible with switching branches.");
782c2d65
DB
602 }
603 }
604
db941099 605 return checkout_paths(source_tree, pathspec, &opts);
782c2d65
DB
606 }
607
608 if (new.name && !new.commit) {
609 die("Cannot switch branch to a non-commit.");
610 }
38901a48
JH
611 if (opts.writeout_stage)
612 die("--ours/--theirs is incompatible with switching branches.");
782c2d65 613
75ea38df 614 return switch_branches(&opts, &new);
782c2d65 615}