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