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