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