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