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