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