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