f7967cdb7c9eca20e40ba5edc2224c79f10f766f
1#define USE_THE_INDEX_COMPATIBILITY_MACROS
2#include "builtin.h"
3#include "advice.h"
4#include "blob.h"
5#include "branch.h"
6#include "cache-tree.h"
7#include "checkout.h"
8#include "commit.h"
9#include "config.h"
10#include "diff.h"
11#include "dir.h"
12#include "ll-merge.h"
13#include "lockfile.h"
14#include "merge-recursive.h"
15#include "object-store.h"
16#include "parse-options.h"
17#include "refs.h"
18#include "remote.h"
19#include "resolve-undo.h"
20#include "revision.h"
21#include "run-command.h"
22#include "submodule.h"
23#include "submodule-config.h"
24#include "tree.h"
25#include "tree-walk.h"
26#include "unpack-trees.h"
27#include "xdiff-interface.h"
28
29static const char * const checkout_usage[] = {
30 N_("git checkout [<options>] <branch>"),
31 N_("git checkout [<options>] [<branch>] -- <file>..."),
32 NULL,
33};
34
35static const char * const switch_branch_usage[] = {
36 N_("git switch [<options>] [<branch>]"),
37 NULL,
38};
39
40struct checkout_opts {
41 int patch_mode;
42 int quiet;
43 int merge;
44 int force;
45 int force_detach;
46 int implicit_detach;
47 int writeout_stage;
48 int overwrite_ignore;
49 int ignore_skipworktree;
50 int ignore_other_worktrees;
51 int show_progress;
52 int count_checkout_paths;
53 int overlay_mode;
54 int dwim_new_local_branch;
55 int discard_changes;
56 int accept_pathspec;
57 int switch_branch_doing_nothing_is_ok;
58 int only_merge_on_switching_branches;
59
60 const char *new_branch;
61 const char *new_branch_force;
62 const char *new_orphan_branch;
63 int new_branch_log;
64 enum branch_track track;
65 struct diff_options diff_options;
66 char *conflict_style;
67
68 int branch_exists;
69 const char *prefix;
70 struct pathspec pathspec;
71 struct tree *source_tree;
72};
73
74static int post_checkout_hook(struct commit *old_commit, struct commit *new_commit,
75 int changed)
76{
77 return run_hook_le(NULL, "post-checkout",
78 oid_to_hex(old_commit ? &old_commit->object.oid : &null_oid),
79 oid_to_hex(new_commit ? &new_commit->object.oid : &null_oid),
80 changed ? "1" : "0", NULL);
81 /* "new_commit" can be NULL when checking out from the index before
82 a commit exists. */
83
84}
85
86static int update_some(const struct object_id *oid, struct strbuf *base,
87 const char *pathname, unsigned mode, int stage, void *context)
88{
89 int len;
90 struct cache_entry *ce;
91 int pos;
92
93 if (S_ISDIR(mode))
94 return READ_TREE_RECURSIVE;
95
96 len = base->len + strlen(pathname);
97 ce = make_empty_cache_entry(&the_index, len);
98 oidcpy(&ce->oid, oid);
99 memcpy(ce->name, base->buf, base->len);
100 memcpy(ce->name + base->len, pathname, len - base->len);
101 ce->ce_flags = create_ce_flags(0) | CE_UPDATE;
102 ce->ce_namelen = len;
103 ce->ce_mode = create_ce_mode(mode);
104
105 /*
106 * If the entry is the same as the current index, we can leave the old
107 * entry in place. Whether it is UPTODATE or not, checkout_entry will
108 * do the right thing.
109 */
110 pos = cache_name_pos(ce->name, ce->ce_namelen);
111 if (pos >= 0) {
112 struct cache_entry *old = active_cache[pos];
113 if (ce->ce_mode == old->ce_mode &&
114 oideq(&ce->oid, &old->oid)) {
115 old->ce_flags |= CE_UPDATE;
116 discard_cache_entry(ce);
117 return 0;
118 }
119 }
120
121 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
122 return 0;
123}
124
125static int read_tree_some(struct tree *tree, const struct pathspec *pathspec)
126{
127 read_tree_recursive(the_repository, tree, "", 0, 0,
128 pathspec, update_some, NULL);
129
130 /* update the index with the given tree's info
131 * for all args, expanding wildcards, and exit
132 * with any non-zero return code.
133 */
134 return 0;
135}
136
137static int skip_same_name(const struct cache_entry *ce, int pos)
138{
139 while (++pos < active_nr &&
140 !strcmp(active_cache[pos]->name, ce->name))
141 ; /* skip */
142 return pos;
143}
144
145static int check_stage(int stage, const struct cache_entry *ce, int pos,
146 int overlay_mode)
147{
148 while (pos < active_nr &&
149 !strcmp(active_cache[pos]->name, ce->name)) {
150 if (ce_stage(active_cache[pos]) == stage)
151 return 0;
152 pos++;
153 }
154 if (!overlay_mode)
155 return 0;
156 if (stage == 2)
157 return error(_("path '%s' does not have our version"), ce->name);
158 else
159 return error(_("path '%s' does not have their version"), ce->name);
160}
161
162static int check_stages(unsigned stages, const struct cache_entry *ce, int pos)
163{
164 unsigned seen = 0;
165 const char *name = ce->name;
166
167 while (pos < active_nr) {
168 ce = active_cache[pos];
169 if (strcmp(name, ce->name))
170 break;
171 seen |= (1 << ce_stage(ce));
172 pos++;
173 }
174 if ((stages & seen) != stages)
175 return error(_("path '%s' does not have all necessary versions"),
176 name);
177 return 0;
178}
179
180static int checkout_stage(int stage, const struct cache_entry *ce, int pos,
181 const struct checkout *state, int *nr_checkouts,
182 int overlay_mode)
183{
184 while (pos < active_nr &&
185 !strcmp(active_cache[pos]->name, ce->name)) {
186 if (ce_stage(active_cache[pos]) == stage)
187 return checkout_entry(active_cache[pos], state,
188 NULL, nr_checkouts);
189 pos++;
190 }
191 if (!overlay_mode) {
192 unlink_entry(ce);
193 return 0;
194 }
195 if (stage == 2)
196 return error(_("path '%s' does not have our version"), ce->name);
197 else
198 return error(_("path '%s' does not have their version"), ce->name);
199}
200
201static int checkout_merged(int pos, const struct checkout *state, int *nr_checkouts)
202{
203 struct cache_entry *ce = active_cache[pos];
204 const char *path = ce->name;
205 mmfile_t ancestor, ours, theirs;
206 int status;
207 struct object_id oid;
208 mmbuffer_t result_buf;
209 struct object_id threeway[3];
210 unsigned mode = 0;
211
212 memset(threeway, 0, sizeof(threeway));
213 while (pos < active_nr) {
214 int stage;
215 stage = ce_stage(ce);
216 if (!stage || strcmp(path, ce->name))
217 break;
218 oidcpy(&threeway[stage - 1], &ce->oid);
219 if (stage == 2)
220 mode = create_ce_mode(ce->ce_mode);
221 pos++;
222 ce = active_cache[pos];
223 }
224 if (is_null_oid(&threeway[1]) || is_null_oid(&threeway[2]))
225 return error(_("path '%s' does not have necessary versions"), path);
226
227 read_mmblob(&ancestor, &threeway[0]);
228 read_mmblob(&ours, &threeway[1]);
229 read_mmblob(&theirs, &threeway[2]);
230
231 /*
232 * NEEDSWORK: re-create conflicts from merges with
233 * merge.renormalize set, too
234 */
235 status = ll_merge(&result_buf, path, &ancestor, "base",
236 &ours, "ours", &theirs, "theirs",
237 state->istate, NULL);
238 free(ancestor.ptr);
239 free(ours.ptr);
240 free(theirs.ptr);
241 if (status < 0 || !result_buf.ptr) {
242 free(result_buf.ptr);
243 return error(_("path '%s': cannot merge"), path);
244 }
245
246 /*
247 * NEEDSWORK:
248 * There is absolutely no reason to write this as a blob object
249 * and create a phony cache entry. This hack is primarily to get
250 * to the write_entry() machinery that massages the contents to
251 * work-tree format and writes out which only allows it for a
252 * cache entry. The code in write_entry() needs to be refactored
253 * to allow us to feed a <buffer, size, mode> instead of a cache
254 * entry. Such a refactoring would help merge_recursive as well
255 * (it also writes the merge result to the object database even
256 * when it may contain conflicts).
257 */
258 if (write_object_file(result_buf.ptr, result_buf.size, blob_type, &oid))
259 die(_("Unable to add merge result for '%s'"), path);
260 free(result_buf.ptr);
261 ce = make_transient_cache_entry(mode, &oid, path, 2);
262 if (!ce)
263 die(_("make_cache_entry failed for path '%s'"), path);
264 status = checkout_entry(ce, state, NULL, nr_checkouts);
265 discard_cache_entry(ce);
266 return status;
267}
268
269static void mark_ce_for_checkout_overlay(struct cache_entry *ce,
270 char *ps_matched,
271 const struct checkout_opts *opts)
272{
273 ce->ce_flags &= ~CE_MATCHED;
274 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
275 return;
276 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
277 /*
278 * "git checkout tree-ish -- path", but this entry
279 * is in the original index but is not in tree-ish
280 * or does not match the pathspec; it will not be
281 * checked out to the working tree. We will not do
282 * anything to this entry at all.
283 */
284 return;
285 /*
286 * Either this entry came from the tree-ish we are
287 * checking the paths out of, or we are checking out
288 * of the index.
289 *
290 * If it comes from the tree-ish, we already know it
291 * matches the pathspec and could just stamp
292 * CE_MATCHED to it from update_some(). But we still
293 * need ps_matched and read_tree_recursive (and
294 * eventually tree_entry_interesting) cannot fill
295 * ps_matched yet. Once it can, we can avoid calling
296 * match_pathspec() for _all_ entries when
297 * opts->source_tree != NULL.
298 */
299 if (ce_path_match(&the_index, ce, &opts->pathspec, ps_matched))
300 ce->ce_flags |= CE_MATCHED;
301}
302
303static void mark_ce_for_checkout_no_overlay(struct cache_entry *ce,
304 char *ps_matched,
305 const struct checkout_opts *opts)
306{
307 ce->ce_flags &= ~CE_MATCHED;
308 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
309 return;
310 if (ce_path_match(&the_index, ce, &opts->pathspec, ps_matched)) {
311 ce->ce_flags |= CE_MATCHED;
312 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
313 /*
314 * In overlay mode, but the path is not in
315 * tree-ish, which means we should remove it
316 * from the index and the working tree.
317 */
318 ce->ce_flags |= CE_REMOVE | CE_WT_REMOVE;
319 }
320}
321
322static int checkout_paths(const struct checkout_opts *opts,
323 const char *revision)
324{
325 int pos;
326 struct checkout state = CHECKOUT_INIT;
327 static char *ps_matched;
328 struct object_id rev;
329 struct commit *head;
330 int errs = 0;
331 struct lock_file lock_file = LOCK_INIT;
332 int nr_checkouts = 0, nr_unmerged = 0;
333
334 trace2_cmd_mode(opts->patch_mode ? "patch" : "path");
335
336 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
337 die(_("'%s' cannot be used with updating paths"), "--track");
338
339 if (opts->new_branch_log)
340 die(_("'%s' cannot be used with updating paths"), "-l");
341
342 if (opts->force && opts->patch_mode)
343 die(_("'%s' cannot be used with updating paths"), "-f");
344
345 if (opts->force_detach)
346 die(_("'%s' cannot be used with updating paths"), "--detach");
347
348 if (opts->merge && opts->patch_mode)
349 die(_("'%s' cannot be used with %s"), "--merge", "--patch");
350
351 if (opts->force && opts->merge)
352 die(_("'%s' cannot be used with %s"), "-f", "-m");
353
354 if (opts->new_branch)
355 die(_("Cannot update paths and switch to branch '%s' at the same time."),
356 opts->new_branch);
357
358 if (opts->patch_mode)
359 return run_add_interactive(revision, "--patch=checkout",
360 &opts->pathspec);
361
362 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
363 if (read_cache_preload(&opts->pathspec) < 0)
364 return error(_("index file corrupt"));
365
366 if (opts->source_tree)
367 read_tree_some(opts->source_tree, &opts->pathspec);
368
369 ps_matched = xcalloc(opts->pathspec.nr, 1);
370
371 /*
372 * Make sure all pathspecs participated in locating the paths
373 * to be checked out.
374 */
375 for (pos = 0; pos < active_nr; pos++)
376 if (opts->overlay_mode)
377 mark_ce_for_checkout_overlay(active_cache[pos],
378 ps_matched,
379 opts);
380 else
381 mark_ce_for_checkout_no_overlay(active_cache[pos],
382 ps_matched,
383 opts);
384
385 if (report_path_error(ps_matched, &opts->pathspec, opts->prefix)) {
386 free(ps_matched);
387 return 1;
388 }
389 free(ps_matched);
390
391 /* "checkout -m path" to recreate conflicted state */
392 if (opts->merge)
393 unmerge_marked_index(&the_index);
394
395 /* Any unmerged paths? */
396 for (pos = 0; pos < active_nr; pos++) {
397 const struct cache_entry *ce = active_cache[pos];
398 if (ce->ce_flags & CE_MATCHED) {
399 if (!ce_stage(ce))
400 continue;
401 if (opts->force) {
402 warning(_("path '%s' is unmerged"), ce->name);
403 } else if (opts->writeout_stage) {
404 errs |= check_stage(opts->writeout_stage, ce, pos, opts->overlay_mode);
405 } else if (opts->merge) {
406 errs |= check_stages((1<<2) | (1<<3), ce, pos);
407 } else {
408 errs = 1;
409 error(_("path '%s' is unmerged"), ce->name);
410 }
411 pos = skip_same_name(ce, pos) - 1;
412 }
413 }
414 if (errs)
415 return 1;
416
417 /* Now we are committed to check them out */
418 state.force = 1;
419 state.refresh_cache = 1;
420 state.istate = &the_index;
421
422 enable_delayed_checkout(&state);
423 for (pos = 0; pos < active_nr; pos++) {
424 struct cache_entry *ce = active_cache[pos];
425 if (ce->ce_flags & CE_MATCHED) {
426 if (!ce_stage(ce)) {
427 errs |= checkout_entry(ce, &state,
428 NULL, &nr_checkouts);
429 continue;
430 }
431 if (opts->writeout_stage)
432 errs |= checkout_stage(opts->writeout_stage,
433 ce, pos,
434 &state,
435 &nr_checkouts, opts->overlay_mode);
436 else if (opts->merge)
437 errs |= checkout_merged(pos, &state,
438 &nr_unmerged);
439 pos = skip_same_name(ce, pos) - 1;
440 }
441 }
442 remove_marked_cache_entries(&the_index, 1);
443 remove_scheduled_dirs();
444 errs |= finish_delayed_checkout(&state, &nr_checkouts);
445
446 if (opts->count_checkout_paths) {
447 if (nr_unmerged)
448 fprintf_ln(stderr, Q_("Recreated %d merge conflict",
449 "Recreated %d merge conflicts",
450 nr_unmerged),
451 nr_unmerged);
452 if (opts->source_tree)
453 fprintf_ln(stderr, Q_("Updated %d path from %s",
454 "Updated %d paths from %s",
455 nr_checkouts),
456 nr_checkouts,
457 find_unique_abbrev(&opts->source_tree->object.oid,
458 DEFAULT_ABBREV));
459 else if (!nr_unmerged || nr_checkouts)
460 fprintf_ln(stderr, Q_("Updated %d path from the index",
461 "Updated %d paths from the index",
462 nr_checkouts),
463 nr_checkouts);
464 }
465
466 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
467 die(_("unable to write new index file"));
468
469 read_ref_full("HEAD", 0, &rev, NULL);
470 head = lookup_commit_reference_gently(the_repository, &rev, 1);
471
472 errs |= post_checkout_hook(head, head, 0);
473 return errs;
474}
475
476static void show_local_changes(struct object *head,
477 const struct diff_options *opts)
478{
479 struct rev_info rev;
480 /* I think we want full paths, even if we're in a subdirectory. */
481 repo_init_revisions(the_repository, &rev, NULL);
482 rev.diffopt.flags = opts->flags;
483 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS;
484 diff_setup_done(&rev.diffopt);
485 add_pending_object(&rev, head, NULL);
486 run_diff_index(&rev, 0);
487}
488
489static void describe_detached_head(const char *msg, struct commit *commit)
490{
491 struct strbuf sb = STRBUF_INIT;
492
493 if (!parse_commit(commit))
494 pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb);
495 if (print_sha1_ellipsis()) {
496 fprintf(stderr, "%s %s... %s\n", msg,
497 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf);
498 } else {
499 fprintf(stderr, "%s %s %s\n", msg,
500 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf);
501 }
502 strbuf_release(&sb);
503}
504
505static int reset_tree(struct tree *tree, const struct checkout_opts *o,
506 int worktree, int *writeout_error)
507{
508 struct unpack_trees_options opts;
509 struct tree_desc tree_desc;
510
511 memset(&opts, 0, sizeof(opts));
512 opts.head_idx = -1;
513 opts.update = worktree;
514 opts.skip_unmerged = !worktree;
515 opts.reset = 1;
516 opts.merge = 1;
517 opts.fn = oneway_merge;
518 opts.verbose_update = o->show_progress;
519 opts.src_index = &the_index;
520 opts.dst_index = &the_index;
521 parse_tree(tree);
522 init_tree_desc(&tree_desc, tree->buffer, tree->size);
523 switch (unpack_trees(1, &tree_desc, &opts)) {
524 case -2:
525 *writeout_error = 1;
526 /*
527 * We return 0 nevertheless, as the index is all right
528 * and more importantly we have made best efforts to
529 * update paths in the work tree, and we cannot revert
530 * them.
531 */
532 /* fallthrough */
533 case 0:
534 return 0;
535 default:
536 return 128;
537 }
538}
539
540struct branch_info {
541 const char *name; /* The short name used */
542 const char *path; /* The full name of a real branch */
543 struct commit *commit; /* The named commit */
544 /*
545 * if not null the branch is detached because it's already
546 * checked out in this checkout
547 */
548 char *checkout;
549};
550
551static void setup_branch_path(struct branch_info *branch)
552{
553 struct strbuf buf = STRBUF_INIT;
554
555 strbuf_branchname(&buf, branch->name, INTERPRET_BRANCH_LOCAL);
556 if (strcmp(buf.buf, branch->name))
557 branch->name = xstrdup(buf.buf);
558 strbuf_splice(&buf, 0, 0, "refs/heads/", 11);
559 branch->path = strbuf_detach(&buf, NULL);
560}
561
562static int merge_working_tree(const struct checkout_opts *opts,
563 struct branch_info *old_branch_info,
564 struct branch_info *new_branch_info,
565 int *writeout_error)
566{
567 int ret;
568 struct lock_file lock_file = LOCK_INIT;
569
570 hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
571 if (read_cache_preload(NULL) < 0)
572 return error(_("index file corrupt"));
573
574 resolve_undo_clear();
575 if (opts->discard_changes) {
576 ret = reset_tree(get_commit_tree(new_branch_info->commit),
577 opts, 1, writeout_error);
578 if (ret)
579 return ret;
580 } else {
581 struct tree_desc trees[2];
582 struct tree *tree;
583 struct unpack_trees_options topts;
584
585 memset(&topts, 0, sizeof(topts));
586 topts.head_idx = -1;
587 topts.src_index = &the_index;
588 topts.dst_index = &the_index;
589
590 setup_unpack_trees_porcelain(&topts, "checkout");
591
592 refresh_cache(REFRESH_QUIET);
593
594 if (unmerged_cache()) {
595 error(_("you need to resolve your current index first"));
596 return 1;
597 }
598
599 /* 2-way merge to the new branch */
600 topts.initial_checkout = is_cache_unborn();
601 topts.update = 1;
602 topts.merge = 1;
603 topts.gently = opts->merge && old_branch_info->commit;
604 topts.verbose_update = opts->show_progress;
605 topts.fn = twoway_merge;
606 if (opts->overwrite_ignore) {
607 topts.dir = xcalloc(1, sizeof(*topts.dir));
608 topts.dir->flags |= DIR_SHOW_IGNORED;
609 setup_standard_excludes(topts.dir);
610 }
611 tree = parse_tree_indirect(old_branch_info->commit ?
612 &old_branch_info->commit->object.oid :
613 the_hash_algo->empty_tree);
614 init_tree_desc(&trees[0], tree->buffer, tree->size);
615 tree = parse_tree_indirect(&new_branch_info->commit->object.oid);
616 init_tree_desc(&trees[1], tree->buffer, tree->size);
617
618 ret = unpack_trees(2, trees, &topts);
619 clear_unpack_trees_porcelain(&topts);
620 if (ret == -1) {
621 /*
622 * Unpack couldn't do a trivial merge; either
623 * give up or do a real merge, depending on
624 * whether the merge flag was used.
625 */
626 struct tree *result;
627 struct tree *work;
628 struct merge_options o;
629 if (!opts->merge)
630 return 1;
631
632 /*
633 * Without old_branch_info->commit, the below is the same as
634 * the two-tree unpack we already tried and failed.
635 */
636 if (!old_branch_info->commit)
637 return 1;
638
639 /* Do more real merge */
640
641 /*
642 * We update the index fully, then write the
643 * tree from the index, then merge the new
644 * branch with the current tree, with the old
645 * branch as the base. Then we reset the index
646 * (but not the working tree) to the new
647 * branch, leaving the working tree as the
648 * merged version, but skipping unmerged
649 * entries in the index.
650 */
651
652 add_files_to_cache(NULL, NULL, 0);
653 /*
654 * NEEDSWORK: carrying over local changes
655 * when branches have different end-of-line
656 * normalization (or clean+smudge rules) is
657 * a pain; plumb in an option to set
658 * o.renormalize?
659 */
660 init_merge_options(&o, the_repository);
661 o.verbosity = 0;
662 work = write_tree_from_memory(&o);
663
664 ret = reset_tree(get_commit_tree(new_branch_info->commit),
665 opts, 1,
666 writeout_error);
667 if (ret)
668 return ret;
669 o.ancestor = old_branch_info->name;
670 o.branch1 = new_branch_info->name;
671 o.branch2 = "local";
672 ret = merge_trees(&o,
673 get_commit_tree(new_branch_info->commit),
674 work,
675 get_commit_tree(old_branch_info->commit),
676 &result);
677 if (ret < 0)
678 exit(128);
679 ret = reset_tree(get_commit_tree(new_branch_info->commit),
680 opts, 0,
681 writeout_error);
682 strbuf_release(&o.obuf);
683 if (ret)
684 return ret;
685 }
686 }
687
688 if (!active_cache_tree)
689 active_cache_tree = cache_tree();
690
691 if (!cache_tree_fully_valid(active_cache_tree))
692 cache_tree_update(&the_index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR);
693
694 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
695 die(_("unable to write new index file"));
696
697 if (!opts->discard_changes && !opts->quiet)
698 show_local_changes(&new_branch_info->commit->object, &opts->diff_options);
699
700 return 0;
701}
702
703static void report_tracking(struct branch_info *new_branch_info)
704{
705 struct strbuf sb = STRBUF_INIT;
706 struct branch *branch = branch_get(new_branch_info->name);
707
708 if (!format_tracking_info(branch, &sb, AHEAD_BEHIND_FULL))
709 return;
710 fputs(sb.buf, stdout);
711 strbuf_release(&sb);
712}
713
714static void update_refs_for_switch(const struct checkout_opts *opts,
715 struct branch_info *old_branch_info,
716 struct branch_info *new_branch_info)
717{
718 struct strbuf msg = STRBUF_INIT;
719 const char *old_desc, *reflog_msg;
720 if (opts->new_branch) {
721 if (opts->new_orphan_branch) {
722 char *refname;
723
724 refname = mkpathdup("refs/heads/%s", opts->new_orphan_branch);
725 if (opts->new_branch_log &&
726 !should_autocreate_reflog(refname)) {
727 int ret;
728 struct strbuf err = STRBUF_INIT;
729
730 ret = safe_create_reflog(refname, 1, &err);
731 if (ret) {
732 fprintf(stderr, _("Can not do reflog for '%s': %s\n"),
733 opts->new_orphan_branch, err.buf);
734 strbuf_release(&err);
735 free(refname);
736 return;
737 }
738 strbuf_release(&err);
739 }
740 free(refname);
741 }
742 else
743 create_branch(the_repository,
744 opts->new_branch, new_branch_info->name,
745 opts->new_branch_force ? 1 : 0,
746 opts->new_branch_force ? 1 : 0,
747 opts->new_branch_log,
748 opts->quiet,
749 opts->track);
750 new_branch_info->name = opts->new_branch;
751 setup_branch_path(new_branch_info);
752 }
753
754 old_desc = old_branch_info->name;
755 if (!old_desc && old_branch_info->commit)
756 old_desc = oid_to_hex(&old_branch_info->commit->object.oid);
757
758 reflog_msg = getenv("GIT_REFLOG_ACTION");
759 if (!reflog_msg)
760 strbuf_addf(&msg, "checkout: moving from %s to %s",
761 old_desc ? old_desc : "(invalid)", new_branch_info->name);
762 else
763 strbuf_insert(&msg, 0, reflog_msg, strlen(reflog_msg));
764
765 if (!strcmp(new_branch_info->name, "HEAD") && !new_branch_info->path && !opts->force_detach) {
766 /* Nothing to do. */
767 } else if (opts->force_detach || !new_branch_info->path) { /* No longer on any branch. */
768 update_ref(msg.buf, "HEAD", &new_branch_info->commit->object.oid, NULL,
769 REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR);
770 if (!opts->quiet) {
771 if (old_branch_info->path &&
772 advice_detached_head && !opts->force_detach)
773 detach_advice(new_branch_info->name);
774 describe_detached_head(_("HEAD is now at"), new_branch_info->commit);
775 }
776 } else if (new_branch_info->path) { /* Switch branches. */
777 if (create_symref("HEAD", new_branch_info->path, msg.buf) < 0)
778 die(_("unable to update HEAD"));
779 if (!opts->quiet) {
780 if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) {
781 if (opts->new_branch_force)
782 fprintf(stderr, _("Reset branch '%s'\n"),
783 new_branch_info->name);
784 else
785 fprintf(stderr, _("Already on '%s'\n"),
786 new_branch_info->name);
787 } else if (opts->new_branch) {
788 if (opts->branch_exists)
789 fprintf(stderr, _("Switched to and reset branch '%s'\n"), new_branch_info->name);
790 else
791 fprintf(stderr, _("Switched to a new branch '%s'\n"), new_branch_info->name);
792 } else {
793 fprintf(stderr, _("Switched to branch '%s'\n"),
794 new_branch_info->name);
795 }
796 }
797 if (old_branch_info->path && old_branch_info->name) {
798 if (!ref_exists(old_branch_info->path) && reflog_exists(old_branch_info->path))
799 delete_reflog(old_branch_info->path);
800 }
801 }
802 remove_branch_state(the_repository, !opts->quiet);
803 strbuf_release(&msg);
804 if (!opts->quiet &&
805 (new_branch_info->path || (!opts->force_detach && !strcmp(new_branch_info->name, "HEAD"))))
806 report_tracking(new_branch_info);
807}
808
809static int add_pending_uninteresting_ref(const char *refname,
810 const struct object_id *oid,
811 int flags, void *cb_data)
812{
813 add_pending_oid(cb_data, refname, oid, UNINTERESTING);
814 return 0;
815}
816
817static void describe_one_orphan(struct strbuf *sb, struct commit *commit)
818{
819 strbuf_addstr(sb, " ");
820 strbuf_add_unique_abbrev(sb, &commit->object.oid, DEFAULT_ABBREV);
821 strbuf_addch(sb, ' ');
822 if (!parse_commit(commit))
823 pp_commit_easy(CMIT_FMT_ONELINE, commit, sb);
824 strbuf_addch(sb, '\n');
825}
826
827#define ORPHAN_CUTOFF 4
828static void suggest_reattach(struct commit *commit, struct rev_info *revs)
829{
830 struct commit *c, *last = NULL;
831 struct strbuf sb = STRBUF_INIT;
832 int lost = 0;
833 while ((c = get_revision(revs)) != NULL) {
834 if (lost < ORPHAN_CUTOFF)
835 describe_one_orphan(&sb, c);
836 last = c;
837 lost++;
838 }
839 if (ORPHAN_CUTOFF < lost) {
840 int more = lost - ORPHAN_CUTOFF;
841 if (more == 1)
842 describe_one_orphan(&sb, last);
843 else
844 strbuf_addf(&sb, _(" ... and %d more.\n"), more);
845 }
846
847 fprintf(stderr,
848 Q_(
849 /* The singular version */
850 "Warning: you are leaving %d commit behind, "
851 "not connected to\n"
852 "any of your branches:\n\n"
853 "%s\n",
854 /* The plural version */
855 "Warning: you are leaving %d commits behind, "
856 "not connected to\n"
857 "any of your branches:\n\n"
858 "%s\n",
859 /* Give ngettext() the count */
860 lost),
861 lost,
862 sb.buf);
863 strbuf_release(&sb);
864
865 if (advice_detached_head)
866 fprintf(stderr,
867 Q_(
868 /* The singular version */
869 "If you want to keep it by creating a new branch, "
870 "this may be a good time\nto do so with:\n\n"
871 " git branch <new-branch-name> %s\n\n",
872 /* The plural version */
873 "If you want to keep them by creating a new branch, "
874 "this may be a good time\nto do so with:\n\n"
875 " git branch <new-branch-name> %s\n\n",
876 /* Give ngettext() the count */
877 lost),
878 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
879}
880
881/*
882 * We are about to leave commit that was at the tip of a detached
883 * HEAD. If it is not reachable from any ref, this is the last chance
884 * for the user to do so without resorting to reflog.
885 */
886static void orphaned_commit_warning(struct commit *old_commit, struct commit *new_commit)
887{
888 struct rev_info revs;
889 struct object *object = &old_commit->object;
890
891 repo_init_revisions(the_repository, &revs, NULL);
892 setup_revisions(0, NULL, &revs, NULL);
893
894 object->flags &= ~UNINTERESTING;
895 add_pending_object(&revs, object, oid_to_hex(&object->oid));
896
897 for_each_ref(add_pending_uninteresting_ref, &revs);
898 add_pending_oid(&revs, "HEAD", &new_commit->object.oid, UNINTERESTING);
899
900 if (prepare_revision_walk(&revs))
901 die(_("internal error in revision walk"));
902 if (!(old_commit->object.flags & UNINTERESTING))
903 suggest_reattach(old_commit, &revs);
904 else
905 describe_detached_head(_("Previous HEAD position was"), old_commit);
906
907 /* Clean up objects used, as they will be reused. */
908 clear_commit_marks_all(ALL_REV_FLAGS);
909}
910
911static int switch_branches(const struct checkout_opts *opts,
912 struct branch_info *new_branch_info)
913{
914 int ret = 0;
915 struct branch_info old_branch_info;
916 void *path_to_free;
917 struct object_id rev;
918 int flag, writeout_error = 0;
919 int do_merge = 1;
920
921 trace2_cmd_mode("branch");
922
923 memset(&old_branch_info, 0, sizeof(old_branch_info));
924 old_branch_info.path = path_to_free = resolve_refdup("HEAD", 0, &rev, &flag);
925 if (old_branch_info.path)
926 old_branch_info.commit = lookup_commit_reference_gently(the_repository, &rev, 1);
927 if (!(flag & REF_ISSYMREF))
928 old_branch_info.path = NULL;
929
930 if (old_branch_info.path)
931 skip_prefix(old_branch_info.path, "refs/heads/", &old_branch_info.name);
932
933 if (!new_branch_info->name) {
934 new_branch_info->name = "HEAD";
935 new_branch_info->commit = old_branch_info.commit;
936 if (!new_branch_info->commit)
937 die(_("You are on a branch yet to be born"));
938 parse_commit_or_die(new_branch_info->commit);
939
940 if (opts->only_merge_on_switching_branches)
941 do_merge = 0;
942 }
943
944 if (do_merge) {
945 ret = merge_working_tree(opts, &old_branch_info, new_branch_info, &writeout_error);
946 if (ret) {
947 free(path_to_free);
948 return ret;
949 }
950 }
951
952 if (!opts->quiet && !old_branch_info.path && old_branch_info.commit && new_branch_info->commit != old_branch_info.commit)
953 orphaned_commit_warning(old_branch_info.commit, new_branch_info->commit);
954
955 update_refs_for_switch(opts, &old_branch_info, new_branch_info);
956
957 ret = post_checkout_hook(old_branch_info.commit, new_branch_info->commit, 1);
958 free(path_to_free);
959 return ret || writeout_error;
960}
961
962static int git_checkout_config(const char *var, const char *value, void *cb)
963{
964 if (!strcmp(var, "diff.ignoresubmodules")) {
965 struct checkout_opts *opts = cb;
966 handle_ignore_submodules_arg(&opts->diff_options, value);
967 return 0;
968 }
969
970 if (starts_with(var, "submodule."))
971 return git_default_submodule_config(var, value, NULL);
972
973 return git_xmerge_config(var, value, NULL);
974}
975
976static void setup_new_branch_info_and_source_tree(
977 struct branch_info *new_branch_info,
978 struct checkout_opts *opts,
979 struct object_id *rev,
980 const char *arg)
981{
982 struct tree **source_tree = &opts->source_tree;
983 struct object_id branch_rev;
984
985 new_branch_info->name = arg;
986 setup_branch_path(new_branch_info);
987
988 if (!check_refname_format(new_branch_info->path, 0) &&
989 !read_ref(new_branch_info->path, &branch_rev))
990 oidcpy(rev, &branch_rev);
991 else
992 new_branch_info->path = NULL; /* not an existing branch */
993
994 new_branch_info->commit = lookup_commit_reference_gently(the_repository, rev, 1);
995 if (!new_branch_info->commit) {
996 /* not a commit */
997 *source_tree = parse_tree_indirect(rev);
998 } else {
999 parse_commit_or_die(new_branch_info->commit);
1000 *source_tree = get_commit_tree(new_branch_info->commit);
1001 }
1002}
1003
1004static int parse_branchname_arg(int argc, const char **argv,
1005 int dwim_new_local_branch_ok,
1006 struct branch_info *new_branch_info,
1007 struct checkout_opts *opts,
1008 struct object_id *rev,
1009 int *dwim_remotes_matched)
1010{
1011 const char **new_branch = &opts->new_branch;
1012 int argcount = 0;
1013 const char *arg;
1014 int dash_dash_pos;
1015 int has_dash_dash = 0;
1016 int i;
1017
1018 /*
1019 * case 1: git checkout <ref> -- [<paths>]
1020 *
1021 * <ref> must be a valid tree, everything after the '--' must be
1022 * a path.
1023 *
1024 * case 2: git checkout -- [<paths>]
1025 *
1026 * everything after the '--' must be paths.
1027 *
1028 * case 3: git checkout <something> [--]
1029 *
1030 * (a) If <something> is a commit, that is to
1031 * switch to the branch or detach HEAD at it. As a special case,
1032 * if <something> is A...B (missing A or B means HEAD but you can
1033 * omit at most one side), and if there is a unique merge base
1034 * between A and B, A...B names that merge base.
1035 *
1036 * (b) If <something> is _not_ a commit, either "--" is present
1037 * or <something> is not a path, no -t or -b was given, and
1038 * and there is a tracking branch whose name is <something>
1039 * in one and only one remote (or if the branch exists on the
1040 * remote named in checkout.defaultRemote), then this is a
1041 * short-hand to fork local <something> from that
1042 * remote-tracking branch.
1043 *
1044 * (c) Otherwise, if "--" is present, treat it like case (1).
1045 *
1046 * (d) Otherwise :
1047 * - if it's a reference, treat it like case (1)
1048 * - else if it's a path, treat it like case (2)
1049 * - else: fail.
1050 *
1051 * case 4: git checkout <something> <paths>
1052 *
1053 * The first argument must not be ambiguous.
1054 * - If it's *only* a reference, treat it like case (1).
1055 * - If it's only a path, treat it like case (2).
1056 * - else: fail.
1057 *
1058 */
1059 if (!argc)
1060 return 0;
1061
1062 if (!opts->accept_pathspec) {
1063 if (argc > 1)
1064 die(_("only one reference expected"));
1065 has_dash_dash = 1; /* helps disambiguate */
1066 }
1067
1068 arg = argv[0];
1069 dash_dash_pos = -1;
1070 for (i = 0; i < argc; i++) {
1071 if (opts->accept_pathspec && !strcmp(argv[i], "--")) {
1072 dash_dash_pos = i;
1073 break;
1074 }
1075 }
1076 if (dash_dash_pos == 0)
1077 return 1; /* case (2) */
1078 else if (dash_dash_pos == 1)
1079 has_dash_dash = 1; /* case (3) or (1) */
1080 else if (dash_dash_pos >= 2)
1081 die(_("only one reference expected, %d given."), dash_dash_pos);
1082 opts->count_checkout_paths = !opts->quiet && !has_dash_dash;
1083
1084 if (!strcmp(arg, "-"))
1085 arg = "@{-1}";
1086
1087 if (get_oid_mb(arg, rev)) {
1088 /*
1089 * Either case (3) or (4), with <something> not being
1090 * a commit, or an attempt to use case (1) with an
1091 * invalid ref.
1092 *
1093 * It's likely an error, but we need to find out if
1094 * we should auto-create the branch, case (3).(b).
1095 */
1096 int recover_with_dwim = dwim_new_local_branch_ok;
1097
1098 int could_be_checkout_paths = !has_dash_dash &&
1099 check_filename(opts->prefix, arg);
1100
1101 if (!has_dash_dash && !no_wildcard(arg))
1102 recover_with_dwim = 0;
1103
1104 /*
1105 * Accept "git checkout foo", "git checkout foo --"
1106 * and "git switch foo" as candidates for dwim.
1107 */
1108 if (!(argc == 1 && !has_dash_dash) &&
1109 !(argc == 2 && has_dash_dash) &&
1110 opts->accept_pathspec)
1111 recover_with_dwim = 0;
1112
1113 if (recover_with_dwim) {
1114 const char *remote = unique_tracking_name(arg, rev,
1115 dwim_remotes_matched);
1116 if (remote) {
1117 if (could_be_checkout_paths)
1118 die(_("'%s' could be both a local file and a tracking branch.\n"
1119 "Please use -- (and optionally --no-guess) to disambiguate"),
1120 arg);
1121 *new_branch = arg;
1122 arg = remote;
1123 /* DWIMmed to create local branch, case (3).(b) */
1124 } else {
1125 recover_with_dwim = 0;
1126 }
1127 }
1128
1129 if (!recover_with_dwim) {
1130 if (has_dash_dash)
1131 die(_("invalid reference: %s"), arg);
1132 return argcount;
1133 }
1134 }
1135
1136 /* we can't end up being in (2) anymore, eat the argument */
1137 argcount++;
1138 argv++;
1139 argc--;
1140
1141 setup_new_branch_info_and_source_tree(new_branch_info, opts, rev, arg);
1142
1143 if (!opts->source_tree) /* case (1): want a tree */
1144 die(_("reference is not a tree: %s"), arg);
1145
1146 if (!has_dash_dash) { /* case (3).(d) -> (1) */
1147 /*
1148 * Do not complain the most common case
1149 * git checkout branch
1150 * even if there happen to be a file called 'branch';
1151 * it would be extremely annoying.
1152 */
1153 if (argc)
1154 verify_non_filename(opts->prefix, arg);
1155 } else if (opts->accept_pathspec) {
1156 argcount++;
1157 argv++;
1158 argc--;
1159 }
1160
1161 return argcount;
1162}
1163
1164static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
1165{
1166 int status;
1167 struct strbuf branch_ref = STRBUF_INIT;
1168
1169 trace2_cmd_mode("unborn");
1170
1171 if (!opts->new_branch)
1172 die(_("You are on a branch yet to be born"));
1173 strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
1174 status = create_symref("HEAD", branch_ref.buf, "checkout -b");
1175 strbuf_release(&branch_ref);
1176 if (!opts->quiet)
1177 fprintf(stderr, _("Switched to a new branch '%s'\n"),
1178 opts->new_branch);
1179 return status;
1180}
1181
1182static void die_expecting_a_branch(const struct branch_info *branch_info)
1183{
1184 struct object_id oid;
1185 char *to_free;
1186
1187 if (dwim_ref(branch_info->name, strlen(branch_info->name), &oid, &to_free) == 1) {
1188 const char *ref = to_free;
1189
1190 if (skip_prefix(ref, "refs/tags/", &ref))
1191 die(_("a branch is expected, got tag '%s'"), ref);
1192 if (skip_prefix(ref, "refs/remotes/", &ref))
1193 die(_("a branch is expected, got remote branch '%s'"), ref);
1194 die(_("a branch is expected, got '%s'"), ref);
1195 }
1196 if (branch_info->commit)
1197 die(_("a branch is expected, got commit '%s'"), branch_info->name);
1198 /*
1199 * This case should never happen because we already die() on
1200 * non-commit, but just in case.
1201 */
1202 die(_("a branch is expected, got '%s'"), branch_info->name);
1203}
1204
1205static int checkout_branch(struct checkout_opts *opts,
1206 struct branch_info *new_branch_info)
1207{
1208 if (opts->pathspec.nr)
1209 die(_("paths cannot be used with switching branches"));
1210
1211 if (opts->patch_mode)
1212 die(_("'%s' cannot be used with switching branches"),
1213 "--patch");
1214
1215 if (!opts->overlay_mode)
1216 die(_("'%s' cannot be used with switching branches"),
1217 "--no-overlay");
1218
1219 if (opts->writeout_stage)
1220 die(_("'%s' cannot be used with switching branches"),
1221 "--ours/--theirs");
1222
1223 if (opts->force && opts->merge)
1224 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1225
1226 if (opts->discard_changes && opts->merge)
1227 die(_("'%s' cannot be used with '%s'"), "--discard-changes", "--merge");
1228
1229 if (opts->force_detach && opts->new_branch)
1230 die(_("'%s' cannot be used with '%s'"),
1231 "--detach", "-b/-B/--orphan");
1232
1233 if (opts->new_orphan_branch) {
1234 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1235 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1236 } else if (opts->force_detach) {
1237 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1238 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1239 } else if (opts->track == BRANCH_TRACK_UNSPECIFIED)
1240 opts->track = git_branch_track;
1241
1242 if (new_branch_info->name && !new_branch_info->commit)
1243 die(_("Cannot switch branch to a non-commit '%s'"),
1244 new_branch_info->name);
1245
1246 if (!opts->switch_branch_doing_nothing_is_ok &&
1247 !new_branch_info->name &&
1248 !opts->new_branch &&
1249 !opts->force_detach)
1250 die(_("missing branch or commit argument"));
1251
1252 if (!opts->implicit_detach &&
1253 !opts->force_detach &&
1254 !opts->new_branch &&
1255 !opts->new_branch_force &&
1256 new_branch_info->name &&
1257 !new_branch_info->path)
1258 die_expecting_a_branch(new_branch_info);
1259
1260 if (new_branch_info->path && !opts->force_detach && !opts->new_branch &&
1261 !opts->ignore_other_worktrees) {
1262 int flag;
1263 char *head_ref = resolve_refdup("HEAD", 0, NULL, &flag);
1264 if (head_ref &&
1265 (!(flag & REF_ISSYMREF) || strcmp(head_ref, new_branch_info->path)))
1266 die_if_checked_out(new_branch_info->path, 1);
1267 free(head_ref);
1268 }
1269
1270 if (!new_branch_info->commit && opts->new_branch) {
1271 struct object_id rev;
1272 int flag;
1273
1274 if (!read_ref_full("HEAD", 0, &rev, &flag) &&
1275 (flag & REF_ISSYMREF) && is_null_oid(&rev))
1276 return switch_unborn_to_new_branch(opts);
1277 }
1278 return switch_branches(opts, new_branch_info);
1279}
1280
1281static struct option *add_common_options(struct checkout_opts *opts,
1282 struct option *prevopts)
1283{
1284 struct option options[] = {
1285 OPT__QUIET(&opts->quiet, N_("suppress progress reporting")),
1286 { OPTION_CALLBACK, 0, "recurse-submodules", NULL,
1287 "checkout", "control recursive updating of submodules",
1288 PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater },
1289 OPT_BOOL(0, "progress", &opts->show_progress, N_("force progress reporting")),
1290 OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
1291 PARSE_OPT_NOCOMPLETE),
1292 OPT_BOOL('m', "merge", &opts->merge, N_("perform a 3-way merge with the new branch")),
1293 OPT_STRING(0, "conflict", &opts->conflict_style, N_("style"),
1294 N_("conflict style (merge or diff3)")),
1295 OPT_END()
1296 };
1297 struct option *newopts = parse_options_concat(prevopts, options);
1298 free(prevopts);
1299 return newopts;
1300}
1301
1302static struct option *add_common_switch_branch_options(
1303 struct checkout_opts *opts, struct option *prevopts)
1304{
1305 struct option options[] = {
1306 OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
1307 OPT_SET_INT('t', "track", &opts->track, N_("set upstream info for new branch"),
1308 BRANCH_TRACK_EXPLICIT),
1309 OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unparented branch")),
1310 OPT_BOOL_F(0, "overwrite-ignore", &opts->overwrite_ignore,
1311 N_("update ignored files (default)"),
1312 PARSE_OPT_NOCOMPLETE),
1313 OPT_BOOL(0, "ignore-other-worktrees", &opts->ignore_other_worktrees,
1314 N_("do not check if another worktree is holding the given ref")),
1315 OPT_END()
1316 };
1317 struct option *newopts = parse_options_concat(prevopts, options);
1318 free(prevopts);
1319 return newopts;
1320}
1321
1322static struct option *add_checkout_path_options(struct checkout_opts *opts,
1323 struct option *prevopts)
1324{
1325 struct option options[] = {
1326 OPT_SET_INT_F('2', "ours", &opts->writeout_stage,
1327 N_("checkout our version for unmerged files"),
1328 2, PARSE_OPT_NONEG),
1329 OPT_SET_INT_F('3', "theirs", &opts->writeout_stage,
1330 N_("checkout their version for unmerged files"),
1331 3, PARSE_OPT_NONEG),
1332 OPT_BOOL('p', "patch", &opts->patch_mode, N_("select hunks interactively")),
1333 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts->ignore_skipworktree,
1334 N_("do not limit pathspecs to sparse entries only")),
1335 OPT_BOOL(0, "overlay", &opts->overlay_mode, N_("use overlay mode (default)")),
1336 OPT_END()
1337 };
1338 struct option *newopts = parse_options_concat(prevopts, options);
1339 free(prevopts);
1340 return newopts;
1341}
1342
1343static int checkout_main(int argc, const char **argv, const char *prefix,
1344 struct checkout_opts *opts, struct option *options,
1345 const char * const usagestr[])
1346{
1347 struct branch_info new_branch_info;
1348 int dwim_remotes_matched = 0;
1349
1350 memset(&new_branch_info, 0, sizeof(new_branch_info));
1351 opts->overwrite_ignore = 1;
1352 opts->prefix = prefix;
1353 opts->show_progress = -1;
1354 opts->overlay_mode = -1;
1355
1356 git_config(git_checkout_config, opts);
1357
1358 opts->track = BRANCH_TRACK_UNSPECIFIED;
1359
1360 argc = parse_options(argc, argv, prefix, options, usagestr,
1361 PARSE_OPT_KEEP_DASHDASH);
1362
1363 if (opts->show_progress < 0) {
1364 if (opts->quiet)
1365 opts->show_progress = 0;
1366 else
1367 opts->show_progress = isatty(2);
1368 }
1369
1370 if (opts->conflict_style) {
1371 opts->merge = 1; /* implied */
1372 git_xmerge_config("merge.conflictstyle", opts->conflict_style, NULL);
1373 }
1374 if (opts->force)
1375 opts->discard_changes = 1;
1376
1377 if ((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) > 1)
1378 die(_("-b, -B and --orphan are mutually exclusive"));
1379
1380 if (opts->overlay_mode == 1 && opts->patch_mode)
1381 die(_("-p and --overlay are mutually exclusive"));
1382
1383 /*
1384 * From here on, new_branch will contain the branch to be checked out,
1385 * and new_branch_force and new_orphan_branch will tell us which one of
1386 * -b/-B/--orphan is being used.
1387 */
1388 if (opts->new_branch_force)
1389 opts->new_branch = opts->new_branch_force;
1390
1391 if (opts->new_orphan_branch)
1392 opts->new_branch = opts->new_orphan_branch;
1393
1394 /* --track without -b/-B/--orphan should DWIM */
1395 if (opts->track != BRANCH_TRACK_UNSPECIFIED && !opts->new_branch) {
1396 const char *argv0 = argv[0];
1397 if (!argc || !strcmp(argv0, "--"))
1398 die(_("--track needs a branch name"));
1399 skip_prefix(argv0, "refs/", &argv0);
1400 skip_prefix(argv0, "remotes/", &argv0);
1401 argv0 = strchr(argv0, '/');
1402 if (!argv0 || !argv0[1])
1403 die(_("missing branch name; try -b"));
1404 opts->new_branch = argv0 + 1;
1405 }
1406
1407 /*
1408 * Extract branch name from command line arguments, so
1409 * all that is left is pathspecs.
1410 *
1411 * Handle
1412 *
1413 * 1) git checkout <tree> -- [<paths>]
1414 * 2) git checkout -- [<paths>]
1415 * 3) git checkout <something> [<paths>]
1416 *
1417 * including "last branch" syntax and DWIM-ery for names of
1418 * remote branches, erroring out for invalid or ambiguous cases.
1419 */
1420 if (argc) {
1421 struct object_id rev;
1422 int dwim_ok =
1423 !opts->patch_mode &&
1424 opts->dwim_new_local_branch &&
1425 opts->track == BRANCH_TRACK_UNSPECIFIED &&
1426 !opts->new_branch;
1427 int n = parse_branchname_arg(argc, argv, dwim_ok,
1428 &new_branch_info, opts, &rev,
1429 &dwim_remotes_matched);
1430 argv += n;
1431 argc -= n;
1432 }
1433
1434 if (argc) {
1435 parse_pathspec(&opts->pathspec, 0,
1436 opts->patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0,
1437 prefix, argv);
1438
1439 if (!opts->pathspec.nr)
1440 die(_("invalid path specification"));
1441
1442 /*
1443 * Try to give more helpful suggestion.
1444 * new_branch && argc > 1 will be caught later.
1445 */
1446 if (opts->new_branch && argc == 1)
1447 die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
1448 argv[0], opts->new_branch);
1449
1450 if (opts->force_detach)
1451 die(_("git checkout: --detach does not take a path argument '%s'"),
1452 argv[0]);
1453
1454 if (1 < !!opts->writeout_stage + !!opts->force + !!opts->merge)
1455 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1456 "checking out of the index."));
1457 }
1458
1459 if (opts->new_branch) {
1460 struct strbuf buf = STRBUF_INIT;
1461
1462 if (opts->new_branch_force)
1463 opts->branch_exists = validate_branchname(opts->new_branch, &buf);
1464 else
1465 opts->branch_exists =
1466 validate_new_branchname(opts->new_branch, &buf, 0);
1467 strbuf_release(&buf);
1468 }
1469
1470 UNLEAK(opts);
1471 if (opts->patch_mode || opts->pathspec.nr) {
1472 int ret = checkout_paths(opts, new_branch_info.name);
1473 if (ret && dwim_remotes_matched > 1 &&
1474 advice_checkout_ambiguous_remote_branch_name)
1475 advise(_("'%s' matched more than one remote tracking branch.\n"
1476 "We found %d remotes with a reference that matched. So we fell back\n"
1477 "on trying to resolve the argument as a path, but failed there too!\n"
1478 "\n"
1479 "If you meant to check out a remote tracking branch on, e.g. 'origin',\n"
1480 "you can do so by fully qualifying the name with the --track option:\n"
1481 "\n"
1482 " git checkout --track origin/<name>\n"
1483 "\n"
1484 "If you'd like to always have checkouts of an ambiguous <name> prefer\n"
1485 "one remote, e.g. the 'origin' remote, consider setting\n"
1486 "checkout.defaultRemote=origin in your config."),
1487 argv[0],
1488 dwim_remotes_matched);
1489 return ret;
1490 } else {
1491 return checkout_branch(opts, &new_branch_info);
1492 }
1493}
1494
1495int cmd_checkout(int argc, const char **argv, const char *prefix)
1496{
1497 struct checkout_opts opts;
1498 struct option *options;
1499 struct option checkout_options[] = {
1500 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
1501 N_("create and checkout a new branch")),
1502 OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
1503 N_("create/reset and checkout a branch")),
1504 OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
1505 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
1506 N_("second guess 'git checkout <no-such-branch>' (default)")),
1507 OPT_END()
1508 };
1509 int ret;
1510
1511 memset(&opts, 0, sizeof(opts));
1512 opts.dwim_new_local_branch = 1;
1513 opts.switch_branch_doing_nothing_is_ok = 1;
1514 opts.only_merge_on_switching_branches = 0;
1515 opts.accept_pathspec = 1;
1516 opts.implicit_detach = 1;
1517
1518 options = parse_options_dup(checkout_options);
1519 options = add_common_options(&opts, options);
1520 options = add_common_switch_branch_options(&opts, options);
1521 options = add_checkout_path_options(&opts, options);
1522
1523 ret = checkout_main(argc, argv, prefix, &opts,
1524 options, checkout_usage);
1525 FREE_AND_NULL(options);
1526 return ret;
1527}
1528
1529int cmd_switch(int argc, const char **argv, const char *prefix)
1530{
1531 struct checkout_opts opts;
1532 struct option *options = NULL;
1533 struct option switch_options[] = {
1534 OPT_STRING('c', "create", &opts.new_branch, N_("branch"),
1535 N_("create and switch to a new branch")),
1536 OPT_STRING('C', "force-create", &opts.new_branch_force, N_("branch"),
1537 N_("create/reset and switch to a branch")),
1538 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
1539 N_("second guess 'git switch <no-such-branch>'")),
1540 OPT_BOOL(0, "discard-changes", &opts.discard_changes,
1541 N_("throw away local modifications")),
1542 OPT_END()
1543 };
1544 int ret;
1545
1546 memset(&opts, 0, sizeof(opts));
1547 opts.dwim_new_local_branch = 1;
1548 opts.accept_pathspec = 0;
1549 opts.switch_branch_doing_nothing_is_ok = 0;
1550 opts.only_merge_on_switching_branches = 1;
1551 opts.implicit_detach = 0;
1552
1553 options = parse_options_dup(switch_options);
1554 options = add_common_options(&opts, options);
1555 options = add_common_switch_branch_options(&opts, options);
1556
1557 ret = checkout_main(argc, argv, prefix, &opts,
1558 options, switch_branch_usage);
1559 FREE_AND_NULL(options);
1560 return ret;
1561}