interplane.Get Omega
Read in your language

git

[Ported from github.com/git/git] Sync with Git 2.56.1

Brought by drakestapleton

branch master Branches Tags History

git / builtin / checkout.c

2290 lines · 70772 bytes Raw Blame History
1#define USE_THE_REPOSITORY_VARIABLE
2#define DISABLE_SIGN_COMPARE_WARNINGS
3
4#include "builtin.h"
5#include "advice.h"
6#include "branch.h"
7#include "cache-tree.h"
8#include "checkout.h"
9#include "commit.h"
10#include "config.h"
11#include "diff.h"
12#include "dir.h"
13#include "environment.h"
14#include "gettext.h"
15#include "hex.h"
16#include "hook.h"
17#include "merge-ll.h"
18#include "merge.h"
19#include "lockfile.h"
20#include "mem-pool.h"
21#include "object-file.h"
22#include "object-name.h"
23#include "odb.h"
24#include "parse-options.h"
25#include "path.h"
26#include "preload-index.h"
27#include "read-cache.h"
28#include "refs.h"
29#include "remote.h"
30#include "repo-settings.h"
31#include "resolve-undo.h"
32#include "revision.h"
33#include "sequencer.h"
34#include "setup.h"
35#include "sparse-index.h"
36#include "strvec.h"
37#include "submodule.h"
38#include "symlinks.h"
39#include "trace2.h"
40#include "tree.h"
41#include "tree-walk.h"
42#include "unpack-trees.h"
43#include "wt-status.h"
44#include "xdiff-interface.h"
45#include "entry.h"
46#include "parallel-checkout.h"
47#include "add-interactive.h"
48
49struct checkout_opts {
50 int patch_mode;
51 int patch_context;
52 int patch_interhunk_context;
53 int auto_advance;
54 int quiet;
55 int merge;
56 int force;
57 int force_detach;
58 int implicit_detach;
59 int writeout_stage;
60 int overwrite_ignore;
61 int ignore_skipworktree;
62 int ignore_other_worktrees;
63 int show_progress;
64 int count_checkout_paths;
65 int overlay_mode;
66 int dwim_new_local_branch;
67 int discard_changes;
68 int accept_ref;
69 int accept_pathspec;
70 int switch_branch_doing_nothing_is_ok;
71 int only_merge_on_switching_branches;
72 int can_switch_when_in_progress;
73 int orphan_from_empty_tree;
74 int empty_pathspec_ok;
75 int checkout_index;
76 int checkout_worktree;
77 const char *ignore_unmerged_opt;
78 int ignore_unmerged;
79 int pathspec_file_nul;
80 char *pathspec_from_file;
81
82 const char *new_branch;
83 const char *new_branch_force;
84 const char *new_orphan_branch;
85 int new_branch_log;
86 enum branch_track track;
87 struct diff_options diff_options;
88 int conflict_style;
89
90 int branch_exists;
91 const char *prefix;
92 struct pathspec pathspec;
93 const char *from_treeish;
94 struct tree *source_tree;
95};
96
97#define CHECKOUT_OPTS_INIT { \
98 .conflict_style = -1, \
99 .merge = -1, \
100 .patch_context = -1, \
101 .patch_interhunk_context = -1, \
102 .auto_advance = 1, \
103}
104
105#define MERGE_WORKING_TREE_UNPACK_FAILED (-2)
106
107struct branch_info {
108 char *name; /* The short name used */
109 char *path; /* The full name of a real branch */
110 struct commit *commit; /* The named commit */
111 char *refname; /* The full name of the ref being checked out. */
112 struct object_id oid; /* The object ID of the commit being checked out. */
113 /*
114 * if not null the branch is detached because it's already
115 * checked out in this checkout
116 */
117 char *checkout;
118};
119
120static void branch_info_release(struct branch_info *info)
121{
122 free(info->name);
123 free(info->path);
124 free(info->refname);
125 free(info->checkout);
126}
127
128static int post_checkout_hook(struct commit *old_commit, struct commit *new_commit,
129 int changed)
130{
131 struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT_FORCE_SERIAL;
132
133 /*
134 * "new_commit" can be NULL when checking out from the index before
135 * a commit exists.
136 */
137 strvec_pushl(&opt.args,
138 oid_to_hex(old_commit ? &old_commit->object.oid : null_oid(the_hash_algo)),
139 oid_to_hex(new_commit ? &new_commit->object.oid : null_oid(the_hash_algo)),
140 changed ? "1" : "0",
141 NULL);
142
143 return run_hooks_opt(the_repository, "post-checkout", &opt);
144}
145
146/*
147 * Handle a tree object and determine if we need to recurse into the
148 * tree (READ_TREE_RECURSIVE) or skip it (0).
149 */
150static int try_update_sparse_directory(const struct object_id *oid,
151 struct strbuf *base,
152 const char *pathname,
153 int overlay_mode)
154{
155 struct strbuf dirpath = STRBUF_INIT;
156 struct cache_entry *old;
157 int pos, result = READ_TREE_RECURSIVE;
158
159 if (!the_repository->index->sparse_index)
160 return result;
161
162 strbuf_addbuf(&dirpath, base);
163 strbuf_addstr(&dirpath, pathname);
164 strbuf_addch(&dirpath, '/');
165
166 pos = index_name_pos_sparse(the_repository->index,
167 dirpath.buf, dirpath.len);
168 if (pos < 0)
169 goto cleanup;
170
171 old = the_repository->index->cache[pos];
172 if (!S_ISSPARSEDIR(old->ce_mode))
173 goto cleanup;
174
175 if (oideq(oid, &old->oid)) {
176 /* Tree content already matches; no need to descend. */
177 result = 0;
178 } else if (!overlay_mode) {
179 /*
180 * In non-overlay mode (e.g., restore --staged), replace the
181 * sparse directory OID directly since files not present in
182 * the source tree should be removed anyway.
183 */
184 oidcpy(&old->oid, oid);
185 old->ce_flags |= CE_UPDATE;
186 result = 0;
187 }
188
189cleanup:
190 strbuf_release(&dirpath);
191 return result;
192}
193
194static int update_some(const struct object_id *oid, struct strbuf *base,
195 const char *pathname, unsigned mode, void *context)
196{
197 size_t len;
198 struct cache_entry *ce;
199 int pos;
200 int overlay_mode = context ? *((int *)context) : 1;
201
202 if (S_ISDIR(mode))
203 return try_update_sparse_directory(oid, base, pathname,
204 overlay_mode);
205
206 len = st_add(base->len, strlen(pathname));
207 ce = make_empty_cache_entry(the_repository->index, len);
208 oidcpy(&ce->oid, oid);
209 memcpy(ce->name, base->buf, base->len);
210 memcpy(ce->name + base->len, pathname, len - base->len);
211 ce->ce_flags = create_ce_flags(0) | CE_UPDATE;
212 ce->ce_namelen = len;
213 ce->ce_mode = create_ce_mode(mode);
214
215 /*
216 * If the entry is the same as the current index, we can leave the old
217 * entry in place. Whether it is UPTODATE or not, checkout_entry will
218 * do the right thing.
219 */
220 pos = index_name_pos_sparse(the_repository->index, ce->name, ce->ce_namelen);
221 if (pos >= 0) {
222 struct cache_entry *old = the_repository->index->cache[pos];
223 if (ce->ce_mode == old->ce_mode &&
224 !ce_intent_to_add(old) &&
225 oideq(&ce->oid, &old->oid)) {
226 old->ce_flags |= CE_UPDATE;
227 discard_cache_entry(ce);
228 return 0;
229 }
230 }
231
232 add_index_entry(the_repository->index, ce,
233 ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
234 return 0;
235}
236
237static int read_tree_some(struct tree *tree, const struct pathspec *pathspec,
238 int overlay_mode)
239{
240 read_tree(the_repository, tree,
241 pathspec, update_some, &overlay_mode);
242
243 /* update the index with the given tree's info
244 * for all args, expanding wildcards, and exit
245 * with any non-zero return code.
246 */
247 return 0;
248}
249
250static int skip_same_name(const struct cache_entry *ce, int pos)
251{
252 while (++pos < the_repository->index->cache_nr &&
253 !strcmp(the_repository->index->cache[pos]->name, ce->name))
254 ; /* skip */
255 return pos;
256}
257
258static int check_stage(int stage, const struct cache_entry *ce, int pos,
259 int overlay_mode)
260{
261 while (pos < the_repository->index->cache_nr &&
262 !strcmp(the_repository->index->cache[pos]->name, ce->name)) {
263 if (ce_stage(the_repository->index->cache[pos]) == stage)
264 return 0;
265 pos++;
266 }
267 if (!overlay_mode)
268 return 0;
269 if (stage == 2)
270 return error(_("path '%s' does not have our version"), ce->name);
271 else
272 return error(_("path '%s' does not have their version"), ce->name);
273}
274
275static int check_stages(unsigned stages, const struct cache_entry *ce, int pos)
276{
277 unsigned seen = 0;
278 const char *name = ce->name;
279
280 while (pos < the_repository->index->cache_nr) {
281 ce = the_repository->index->cache[pos];
282 if (strcmp(name, ce->name))
283 break;
284 seen |= (1 << ce_stage(ce));
285 pos++;
286 }
287 if ((stages & seen) != stages)
288 return error(_("path '%s' does not have all necessary versions"),
289 name);
290 return 0;
291}
292
293static int checkout_stage(int stage, const struct cache_entry *ce, int pos,
294 const struct checkout *state, int *nr_checkouts,
295 int overlay_mode)
296{
297 while (pos < the_repository->index->cache_nr &&
298 !strcmp(the_repository->index->cache[pos]->name, ce->name)) {
299 if (ce_stage(the_repository->index->cache[pos]) == stage)
300 return checkout_entry(the_repository->index->cache[pos], state,
301 NULL, nr_checkouts);
302 pos++;
303 }
304 if (!overlay_mode) {
305 unlink_entry(ce, NULL);
306 return 0;
307 }
308 if (stage == 2)
309 return error(_("path '%s' does not have our version"), ce->name);
310 else
311 return error(_("path '%s' does not have their version"), ce->name);
312}
313
314struct checkout_merged_data {
315 int conflict_style;
316 int renormalize;
317 char *base_label, *ours_label, *theirs_label;
318};
319
320static void checkout_merged_release(struct checkout_merged_data *data)
321{
322 free(data->base_label);
323 free(data->ours_label);
324 free(data->theirs_label);
325}
326
327static void checkout_merged_prepare(struct checkout_merged_data *data)
328{
329 int renormalize = 0;
330
331 repo_config_get_bool(the_repository, "merge.renormalize", &renormalize);
332 data->renormalize = renormalize;
333 if (read_merge_labels(the_repository, &data->base_label, &data->ours_label,
334 &data->theirs_label)) {
335 data->base_label = xstrdup("base");
336 data->ours_label = xstrdup("ours");
337 data->theirs_label = xstrdup("theirs");
338 }
339}
340
341static int checkout_merged(int pos, const struct checkout *state,
342 int *nr_checkouts, struct mem_pool *ce_mem_pool,
343 struct checkout_merged_data *data)
344{
345 struct cache_entry *ce = the_repository->index->cache[pos];
346 const char *path = ce->name;
347 mmfile_t ancestor, ours, theirs;
348 enum ll_merge_result merge_status;
349 int status;
350 struct object_id oid;
351 mmfile_t result_buf;
352 struct object_id threeway[3];
353 unsigned mode = 0;
354 struct ll_merge_options ll_opts = LL_MERGE_OPTIONS_INIT;
355
356 memset(threeway, 0, sizeof(threeway));
357 while (pos < the_repository->index->cache_nr) {
358 int stage;
359 stage = ce_stage(ce);
360 if (!stage || strcmp(path, ce->name))
361 break;
362 oidcpy(&threeway[stage - 1], &ce->oid);
363 if (stage == 2)
364 mode = create_ce_mode(ce->ce_mode);
365 pos++;
366 ce = the_repository->index->cache[pos];
367 }
368 if (is_null_oid(&threeway[1]) || is_null_oid(&threeway[2]))
369 return error(_("path '%s' does not have necessary versions"), path);
370
371 read_mmblob(&ancestor, the_repository->objects, &threeway[0]);
372 read_mmblob(&ours, the_repository->objects, &threeway[1]);
373 read_mmblob(&theirs, the_repository->objects, &threeway[2]);
374
375 ll_opts.renormalize = data->renormalize;
376 ll_opts.conflict_style = data->conflict_style;
377 merge_status = ll_merge(&result_buf, path, &ancestor, data->base_label,
378 &ours, data->ours_label, &theirs, data->theirs_label,
379 state->istate, &ll_opts);
380 free(ancestor.ptr);
381 free(ours.ptr);
382 free(theirs.ptr);
383 if (merge_status == LL_MERGE_BINARY_CONFLICT)
384 warning("Cannot merge binary files: %s (%s vs. %s)",
385 path, "ours", "theirs");
386 if (merge_status < 0 || !result_buf.ptr) {
387 free(result_buf.ptr);
388 return error(_("path '%s': cannot merge"), path);
389 }
390
391 /*
392 * NEEDSWORK:
393 * There is absolutely no reason to write this as a blob object
394 * and create a phony cache entry. This hack is primarily to get
395 * to the write_entry() machinery that massages the contents to
396 * work-tree format and writes out which only allows it for a
397 * cache entry. The code in write_entry() needs to be refactored
398 * to allow us to feed a <buffer, size, mode> instead of a cache
399 * entry. Such a refactoring would help merge_recursive as well
400 * (it also writes the merge result to the object database even
401 * when it may contain conflicts).
402 */
403 if (odb_write_object(the_repository->objects, result_buf.ptr, result_buf.size, OBJ_BLOB, &oid))
404 die(_("Unable to add merge result for '%s'"), path);
405 free(result_buf.ptr);
406 ce = make_transient_cache_entry(mode, &oid, path, 2, ce_mem_pool);
407 if (!ce)
408 die(_("make_cache_entry failed for path '%s'"), path);
409 status = checkout_entry(ce, state, NULL, nr_checkouts);
410 return status;
411}
412
413static void mark_ce_for_checkout_overlay(struct cache_entry *ce,
414 char *ps_matched,
415 const struct checkout_opts *opts)
416{
417 ce->ce_flags &= ~CE_MATCHED;
418 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
419 return;
420 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
421 /*
422 * "git checkout tree-ish -- path", but this entry
423 * is in the original index but is not in tree-ish
424 * or does not match the pathspec; it will not be
425 * checked out to the working tree. We will not do
426 * anything to this entry at all.
427 */
428 return;
429 /*
430 * Either this entry came from the tree-ish we are
431 * checking the paths out of, or we are checking out
432 * of the index.
433 *
434 * If it comes from the tree-ish, we already know it
435 * matches the pathspec and could just stamp
436 * CE_MATCHED to it from update_some(). But we still
437 * need ps_matched and read_tree (and
438 * eventually tree_entry_interesting) cannot fill
439 * ps_matched yet. Once it can, we can avoid calling
440 * match_pathspec() for _all_ entries when
441 * opts->source_tree != NULL.
442 */
443 if (ce_path_match(the_repository->index, ce, &opts->pathspec, ps_matched))
444 ce->ce_flags |= CE_MATCHED;
445}
446
447static void mark_ce_for_checkout_no_overlay(struct cache_entry *ce,
448 char *ps_matched,
449 const struct checkout_opts *opts)
450{
451 ce->ce_flags &= ~CE_MATCHED;
452 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
453 return;
454 if (ce_path_match(the_repository->index, ce, &opts->pathspec, ps_matched)) {
455 ce->ce_flags |= CE_MATCHED;
456 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
457 /*
458 * In overlay mode, but the path is not in
459 * tree-ish, which means we should remove it
460 * from the index and the working tree.
461 */
462 ce->ce_flags |= CE_REMOVE | CE_WT_REMOVE;
463 }
464}
465
466static int checkout_worktree(const struct checkout_opts *opts,
467 const struct branch_info *info)
468{
469 struct checkout state = CHECKOUT_INIT;
470 int nr_checkouts = 0, nr_unmerged = 0;
471 int errs = 0;
472 int pos;
473 int pc_workers, pc_threshold;
474 struct mem_pool ce_mem_pool;
475 struct checkout_merged_data checkout_merged_data = {0};
476
477 state.force = 1;
478 state.refresh_cache = 1;
479 state.istate = the_repository->index;
480
481 mem_pool_init(&ce_mem_pool, 0);
482 get_parallel_checkout_configs(&pc_workers, &pc_threshold);
483 init_checkout_metadata(&state.meta, info->refname,
484 info->commit ? &info->commit->object.oid : &info->oid,
485 NULL);
486
487 enable_delayed_checkout(&state);
488
489 if (pc_workers > 1)
490 init_parallel_checkout();
491
492 if (opts->merge) {
493 checkout_merged_prepare(&checkout_merged_data);
494 checkout_merged_data.conflict_style = opts->conflict_style;
495 }
496 for (pos = 0; pos < the_repository->index->cache_nr; pos++) {
497 struct cache_entry *ce = the_repository->index->cache[pos];
498 if (ce->ce_flags & CE_MATCHED) {
499 if (!ce_stage(ce)) {
500 errs |= checkout_entry(ce, &state,
501 NULL, &nr_checkouts);
502 continue;
503 }
504 if (opts->writeout_stage)
505 errs |= checkout_stage(opts->writeout_stage,
506 ce, pos,
507 &state,
508 &nr_checkouts, opts->overlay_mode);
509 else if (opts->merge)
510 errs |= checkout_merged(pos, &state,
511 &nr_unmerged,
512 &ce_mem_pool,
513 &checkout_merged_data);
514 pos = skip_same_name(ce, pos) - 1;
515 }
516 }
517
518 if (opts->merge)
519 checkout_merged_release(&checkout_merged_data);
520
521 if (pc_workers > 1)
522 errs |= run_parallel_checkout(&state, pc_workers, pc_threshold,
523 NULL, NULL);
524 mem_pool_discard(&ce_mem_pool, should_validate_cache_entries());
525 remove_marked_cache_entries(the_repository->index, 1);
526 remove_scheduled_dirs();
527 errs |= finish_delayed_checkout(&state, opts->show_progress);
528
529 if (opts->count_checkout_paths) {
530 if (nr_unmerged)
531 fprintf_ln(stderr, Q_("Recreated %d merge conflict",
532 "Recreated %d merge conflicts",
533 nr_unmerged),
534 nr_unmerged);
535 if (opts->source_tree)
536 fprintf_ln(stderr, Q_("Updated %d path from %s",
537 "Updated %d paths from %s",
538 nr_checkouts),
539 nr_checkouts,
540 repo_find_unique_abbrev(the_repository, &opts->source_tree->object.oid,
541 DEFAULT_ABBREV));
542 else if (!nr_unmerged || nr_checkouts)
543 fprintf_ln(stderr, Q_("Updated %d path from the index",
544 "Updated %d paths from the index",
545 nr_checkouts),
546 nr_checkouts);
547 }
548
549 return errs;
550}
551
552static int checkout_paths(const struct checkout_opts *opts,
553 const struct branch_info *new_branch_info)
554{
555 int pos;
556 static char *ps_matched;
557 struct object_id rev;
558 struct commit *head;
559 int errs = 0;
560 struct lock_file lock_file = LOCK_INIT;
561 int checkout_index;
562
563 trace2_cmd_mode(opts->patch_mode ? "patch" : "path");
564
565 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
566 die(_("'%s' cannot be used with updating paths"), "--track");
567
568 if (opts->new_branch_log)
569 die(_("'%s' cannot be used with updating paths"), "-l");
570
571 if (opts->ignore_unmerged && opts->patch_mode)
572 die(_("'%s' cannot be used with updating paths"),
573 opts->ignore_unmerged_opt);
574
575 if (opts->force_detach)
576 die(_("'%s' cannot be used with updating paths"), "--detach");
577
578 if (opts->merge && opts->patch_mode)
579 die(_("options '%s' and '%s' cannot be used together"), "--merge", "--patch");
580
581 if (opts->ignore_unmerged && opts->merge)
582 die(_("options '%s' and '%s' cannot be used together"),
583 opts->ignore_unmerged_opt, "-m");
584
585 if (opts->new_branch)
586 die(_("Cannot update paths and switch to branch '%s' at the same time."),
587 opts->new_branch);
588
589 if (!opts->checkout_worktree && !opts->checkout_index)
590 die(_("neither '%s' or '%s' is specified"),
591 "--staged", "--worktree");
592
593 if (!opts->checkout_worktree && !opts->from_treeish)
594 die(_("'%s' must be used when '%s' is not specified"),
595 "--worktree", "--source");
596
597 /*
598 * Reject --staged option to the restore command when combined with
599 * merge-related options. Use the accept_ref flag to distinguish it
600 * from the checkout command, which does not accept --staged anyway.
601 *
602 * `restore --ours|--theirs --worktree --staged` could mean resolving
603 * conflicted paths to one side in both the worktree and the index,
604 * but does not currently.
605 *
606 * `restore --merge|--conflict=<style>` already recreates conflicts
607 * in both the worktree and the index, so adding --staged would be
608 * meaningless.
609 */
610 if (!opts->accept_ref && opts->checkout_index) {
611 if (opts->writeout_stage)
612 die(_("'%s' or '%s' cannot be used with %s"),
613 "--ours", "--theirs", "--staged");
614
615 if (opts->merge)
616 die(_("'%s' or '%s' cannot be used with %s"),
617 "--merge", "--conflict", "--staged");
618 }
619
620 /*
621 * recreating unmerged index entries and writing out data from
622 * unmerged index entries would make no sense when checking out
623 * of a tree-ish.
624 */
625 if ((opts->merge || opts->writeout_stage) && opts->source_tree)
626 die(_("'%s', '%s', or '%s' cannot be used when checking out of a tree"),
627 "--merge", "--ours", "--theirs");
628
629 if (opts->patch_mode) {
630 enum add_p_mode patch_mode;
631 struct interactive_options interactive_opts = {
632 .context = opts->patch_context,
633 .interhunkcontext = opts->patch_interhunk_context,
634 .auto_advance = opts->auto_advance
635 };
636 const char *rev = new_branch_info->name;
637 char rev_oid[GIT_MAX_HEXSZ + 1];
638
639 /*
640 * Since rev can be in the form of `<a>...<b>` (which is not
641 * recognized by diff-index), we will always replace the name
642 * with the hex of the commit (whether it's in `...` form or
643 * not) for the run_add_interactive() machinery to work
644 * properly. However, there is special logic for the HEAD case
645 * so we mustn't replace that. Also, when we were given a
646 * tree-object, new_branch_info->commit would be NULL, but we
647 * do not have to do any replacement, either.
648 */
649 if (rev && new_branch_info->commit && strcmp(rev, "HEAD"))
650 rev = oid_to_hex_r(rev_oid, &new_branch_info->commit->object.oid);
651
652 if (opts->checkout_index && opts->checkout_worktree)
653 patch_mode = ADD_P_CHECKOUT;
654 else if (opts->checkout_index && !opts->checkout_worktree)
655 patch_mode = ADD_P_RESET;
656 else if (!opts->checkout_index && opts->checkout_worktree)
657 patch_mode = ADD_P_WORKTREE;
658 else
659 BUG("either flag must have been set, worktree=%d, index=%d",
660 opts->checkout_worktree, opts->checkout_index);
661 return !!run_add_p(the_repository, patch_mode, &interactive_opts,
662 rev, &opts->pathspec, 0);
663 }
664
665 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
666 if (repo_read_index_preload(the_repository, &opts->pathspec, 0) < 0)
667 return error(_("index file corrupt"));
668
669 if (opts->source_tree)
670 read_tree_some(opts->source_tree, &opts->pathspec,
671 opts->overlay_mode);
672 if (opts->merge)
673 unmerge_index(the_repository->index, &opts->pathspec, CE_MATCHED);
674
675 ps_matched = xcalloc(opts->pathspec.nr, 1);
676
677 /*
678 * Make sure all pathspecs participated in locating the paths
679 * to be checked out.
680 */
681 for (pos = 0; pos < the_repository->index->cache_nr; pos++)
682 if (opts->overlay_mode)
683 mark_ce_for_checkout_overlay(the_repository->index->cache[pos],
684 ps_matched,
685 opts);
686 else
687 mark_ce_for_checkout_no_overlay(the_repository->index->cache[pos],
688 ps_matched,
689 opts);
690
691 if (report_path_error(ps_matched, &opts->pathspec)) {
692 free(ps_matched);
693 return 1;
694 }
695 free(ps_matched);
696
697 /* Any unmerged paths? */
698 for (pos = 0; pos < the_repository->index->cache_nr; pos++) {
699 const struct cache_entry *ce = the_repository->index->cache[pos];
700 if (ce->ce_flags & CE_MATCHED) {
701 if (!ce_stage(ce))
702 continue;
703 if (opts->ignore_unmerged) {
704 if (!opts->quiet)
705 warning(_("path '%s' is unmerged"), ce->name);
706 } else if (opts->writeout_stage) {
707 errs |= check_stage(opts->writeout_stage, ce, pos, opts->overlay_mode);
708 } else if (opts->merge) {
709 errs |= check_stages((1<<2) | (1<<3), ce, pos);
710 } else {
711 errs = 1;
712 error(_("path '%s' is unmerged"), ce->name);
713 }
714 pos = skip_same_name(ce, pos) - 1;
715 }
716 }
717 if (errs)
718 return 1;
719
720 /* Now we are committed to check them out */
721 if (opts->checkout_worktree)
722 errs |= checkout_worktree(opts, new_branch_info);
723 else
724 remove_marked_cache_entries(the_repository->index, 1);
725
726 /*
727 * Allow updating the index when checking out from the index.
728 * This is to save new stat info.
729 */
730 if (opts->checkout_worktree && !opts->checkout_index && !opts->source_tree)
731 checkout_index = 1;
732 else
733 checkout_index = opts->checkout_index;
734
735 if (checkout_index) {
736 if (write_locked_index(the_repository->index, &lock_file, COMMIT_LOCK))
737 die(_("unable to write new index file"));
738 } else {
739 /*
740 * NEEDSWORK: if --worktree is not specified, we
741 * should save stat info of checked out files in the
742 * index to avoid the next (potentially costly)
743 * refresh. But it's a bit tricker to do...
744 */
745 rollback_lock_file(&lock_file);
746 }
747
748 refs_read_ref_full(get_main_ref_store(the_repository), "HEAD", 0,
749 &rev, NULL);
750 head = lookup_commit_reference_gently(the_repository, &rev, 1);
751
752 errs |= post_checkout_hook(head, head, 0);
753 return errs;
754}
755
756static void show_local_changes(struct object *head,
757 const struct diff_options *opts)
758{
759 struct rev_info rev;
760 /* I think we want full paths, even if we're in a subdirectory. */
761 repo_init_revisions(the_repository, &rev, NULL);
762 rev.diffopt.flags = opts->flags;
763 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS;
764 rev.diffopt.flags.recursive = 1;
765 diff_setup_done(&rev.diffopt);
766 add_pending_object(&rev, head, NULL);
767 run_diff_index(&rev, 0);
768 release_revisions(&rev);
769}
770
771static void describe_detached_head(const char *msg, struct commit *commit)
772{
773 struct strbuf sb = STRBUF_INIT;
774
775 if (!repo_parse_commit(the_repository, commit))
776 pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb);
777 if (print_sha1_ellipsis()) {
778 fprintf(stderr, "%s %s... %s\n", msg,
779 repo_find_unique_abbrev(the_repository, &commit->object.oid, DEFAULT_ABBREV),
780 sb.buf);
781 } else {
782 fprintf(stderr, "%s %s %s\n", msg,
783 repo_find_unique_abbrev(the_repository, &commit->object.oid, DEFAULT_ABBREV),
784 sb.buf);
785 }
786 strbuf_release(&sb);
787}
788
789static int reset_tree(struct tree *tree, const struct checkout_opts *o,
790 int worktree, int *writeout_error,
791 struct branch_info *info)
792{
793 struct unpack_trees_options opts;
794 struct tree_desc tree_desc;
795
796 memset(&opts, 0, sizeof(opts));
797 opts.head_idx = -1;
798 opts.update = worktree;
799 opts.skip_unmerged = !worktree;
800 opts.reset = o->force ? UNPACK_RESET_OVERWRITE_UNTRACKED :
801 UNPACK_RESET_PROTECT_UNTRACKED;
802 opts.preserve_ignored = (!o->force && !o->overwrite_ignore);
803 opts.merge = 1;
804 opts.fn = oneway_merge;
805 opts.verbose_update = o->show_progress;
806 opts.src_index = the_repository->index;
807 opts.dst_index = the_repository->index;
808 init_checkout_metadata(&opts.meta, info->refname,
809 info->commit ? &info->commit->object.oid : null_oid(the_hash_algo),
810 NULL);
811 if (repo_parse_tree(the_repository, tree) < 0)
812 return 128;
813 init_tree_desc(&tree_desc, &tree->object.oid, tree->buffer, tree->size);
814 switch (unpack_trees(1, &tree_desc, &opts)) {
815 case -2:
816 *writeout_error = 1;
817 /*
818 * We return 0 nevertheless, as the index is all right
819 * and more importantly we have made best efforts to
820 * update paths in the work tree, and we cannot revert
821 * them.
822 */
823 /* fallthrough */
824 case 0:
825 return 0;
826 default:
827 return 128;
828 }
829}
830
831static void setup_branch_path(struct branch_info *branch)
832{
833 struct strbuf buf = STRBUF_INIT;
834
835 /*
836 * If this is a ref, resolve it; otherwise, look up the OID for our
837 * expression. Failure here is okay.
838 */
839 if (!repo_dwim_ref(the_repository, branch->name, strlen(branch->name),
840 &branch->oid, &branch->refname, 0))
841 repo_get_oid_committish(the_repository, branch->name, &branch->oid);
842
843 copy_branchname(the_repository, &buf, branch->name, INTERPRET_BRANCH_LOCAL);
844 if (strcmp(buf.buf, branch->name)) {
845 free(branch->name);
846 branch->name = xstrdup(buf.buf);
847 }
848 strbuf_splice(&buf, 0, 0, "refs/heads/", 11);
849 free(branch->path);
850 branch->path = strbuf_detach(&buf, NULL);
851}
852
853static void init_topts(struct unpack_trees_options *topts,
854 int show_progress, int overwrite_ignore,
855 bool quiet)
856{
857 memset(topts, 0, sizeof(*topts));
858 topts->head_idx = -1;
859 topts->src_index = the_repository->index;
860 topts->dst_index = the_repository->index;
861
862 setup_unpack_trees_porcelain(topts, "checkout");
863
864 topts->initial_checkout = is_index_unborn(the_repository->index);
865 topts->update = 1;
866 topts->merge = 1;
867 topts->quiet = quiet;
868 topts->verbose_update = show_progress;
869 topts->fn = twoway_merge;
870 topts->preserve_ignored = !overwrite_ignore;
871}
872
873static int merge_working_tree(const struct checkout_opts *opts,
874 struct branch_info *old_branch_info,
875 struct branch_info *new_branch_info,
876 bool quiet,
877 int *writeout_error)
878{
879 int ret;
880 struct lock_file lock_file = LOCK_INIT;
881 struct tree *new_tree;
882
883 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
884 if (repo_read_index_preload(the_repository, NULL, 0) < 0) {
885 rollback_lock_file(&lock_file);
886 return error(_("index file corrupt"));
887 }
888
889 resolve_undo_clear_index(the_repository->index);
890 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
891 if (new_branch_info->commit)
892 BUG("'switch --orphan' should never accept a commit as starting point");
893 new_tree = repo_parse_tree_indirect(the_repository,
894 the_hash_algo->empty_tree);
895 if (!new_tree)
896 BUG("unable to read empty tree");
897 } else {
898 new_tree = repo_get_commit_tree(the_repository,
899 new_branch_info->commit);
900 if (!new_tree) {
901 rollback_lock_file(&lock_file);
902 return error(_("unable to read tree (%s)"),
903 oid_to_hex(&new_branch_info->commit->object.oid));
904 }
905 }
906 if (opts->discard_changes) {
907 ret = reset_tree(new_tree, opts, 1, writeout_error, new_branch_info);
908 if (ret) {
909 rollback_lock_file(&lock_file);
910 return ret;
911 }
912 } else {
913 struct tree_desc trees[2];
914 struct tree *tree;
915 struct unpack_trees_options topts;
916 const struct object_id *old_commit_oid;
917
918 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL, NULL);
919
920 if (unmerged_index(the_repository->index)) {
921 rollback_lock_file(&lock_file);
922 error(_("you need to resolve your current index first"));
923 return 1;
924 }
925
926 /* 2-way merge to the new branch */
927 init_topts(&topts, opts->show_progress,
928 opts->overwrite_ignore, quiet);
929 init_checkout_metadata(&topts.meta, new_branch_info->refname,
930 new_branch_info->commit ?
931 &new_branch_info->commit->object.oid :
932 &new_branch_info->oid, NULL);
933
934 old_commit_oid = old_branch_info->commit ?
935 &old_branch_info->commit->object.oid :
936 the_hash_algo->empty_tree;
937 tree = repo_parse_tree_indirect(the_repository,
938 old_commit_oid);
939 if (!tree)
940 die(_("unable to parse commit %s"),
941 oid_to_hex(old_commit_oid));
942
943 init_tree_desc(&trees[0], &tree->object.oid,
944 tree->buffer, tree->size);
945 if (repo_parse_tree(the_repository, new_tree) < 0)
946 die(NULL);
947 tree = new_tree;
948 init_tree_desc(&trees[1], &tree->object.oid,
949 tree->buffer, tree->size);
950
951 ret = unpack_trees(2, trees, &topts);
952 clear_unpack_trees_porcelain(&topts);
953 if (ret == -1) {
954 rollback_lock_file(&lock_file);
955 return MERGE_WORKING_TREE_UNPACK_FAILED;
956 }
957 }
958
959 if (!cache_tree_fully_valid(the_repository->index))
960 cache_tree_update(the_repository->index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR);
961
962 if (write_locked_index(the_repository->index, &lock_file, COMMIT_LOCK))
963 die(_("unable to write new index file"));
964
965 if (!opts->discard_changes && !opts->quiet && new_branch_info->commit)
966 show_local_changes(&new_branch_info->commit->object, &opts->diff_options);
967
968 return 0;
969}
970
971static void report_tracking(struct branch_info *new_branch_info)
972{
973 struct strbuf sb = STRBUF_INIT;
974 struct branch *branch = branch_get(new_branch_info->name);
975
976 if (!format_tracking_info(branch, &sb, AHEAD_BEHIND_FULL, 1))
977 return;
978 fputs(sb.buf, stdout);
979 strbuf_release(&sb);
980}
981
982static void update_refs_for_switch(const struct checkout_opts *opts,
983 struct branch_info *old_branch_info,
984 struct branch_info *new_branch_info,
985 bool merge_conflicts)
986{
987 struct strbuf msg = STRBUF_INIT;
988 const char *old_desc, *reflog_msg;
989 unsigned flags = 0;
990
991 if (opts->new_branch) {
992 if (opts->new_orphan_branch) {
993 enum log_refs_config log_all_ref_updates = LOG_REFS_UNSET;
994 const char *value;
995 char *refname;
996
997 if (!repo_config_get_string_tmp(the_repository, "core.logallrefupdates", &value))
998 log_all_ref_updates = refs_parse_log_all_ref_updates_config(value);
999
1000 refname = mkpathdup("refs/heads/%s", opts->new_orphan_branch);
1001 if (opts->new_branch_log &&
1002 !should_autocreate_reflog(log_all_ref_updates, refname)) {
1003 int ret;
1004 struct strbuf err = STRBUF_INIT;
1005
1006 ret = refs_create_reflog(get_main_ref_store(the_repository),
1007 refname, &err);
1008 if (ret) {
1009 fprintf(stderr, _("Can not do reflog for '%s': %s\n"),
1010 opts->new_orphan_branch, err.buf);
1011 strbuf_release(&err);
1012 free(refname);
1013 return;
1014 }
1015 strbuf_release(&err);
1016 }
1017 free(refname);
1018 }
1019 else
1020 /*
1021 * Not fatal: the error and hint have already been
1022 * shown, and like "push -u" and "clone" we finish
1023 * the switch instead of leaving HEAD on the old
1024 * branch with the worktree already updated.
1025 */
1026 create_branch(the_repository,
1027 opts->new_branch, new_branch_info->name,
1028 opts->new_branch_force ? 1 : 0,
1029 opts->new_branch_force ? 1 : 0,
1030 opts->new_branch_log,
1031 opts->quiet,
1032 opts->track,
1033 0);
1034 free(new_branch_info->name);
1035 free(new_branch_info->refname);
1036 new_branch_info->name = xstrdup(opts->new_branch);
1037 setup_branch_path(new_branch_info);
1038 }
1039
1040 old_desc = old_branch_info->name;
1041 if (!old_desc && old_branch_info->commit)
1042 old_desc = oid_to_hex(&old_branch_info->commit->object.oid);
1043
1044 reflog_msg = getenv("GIT_REFLOG_ACTION");
1045 if (!reflog_msg)
1046 strbuf_addf(&msg, "checkout: moving from %s to %s",
1047 old_desc ? old_desc : "(invalid)", new_branch_info->name);
1048 else
1049 strbuf_insertstr(&msg, 0, reflog_msg);
1050
1051 if (!strcmp(new_branch_info->name, "HEAD") && !new_branch_info->path && !opts->force_detach) {
1052 /* Nothing to do. */
1053 } else if (opts->force_detach || !new_branch_info->path) { /* No longer on any branch. */
1054 refs_update_ref(get_main_ref_store(the_repository), msg.buf,
1055 "HEAD", &new_branch_info->commit->object.oid,
1056 NULL,
1057 REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR);
1058 if (!opts->quiet) {
1059 if (old_branch_info->path &&
1060 advice_enabled(ADVICE_DETACHED_HEAD) && !opts->force_detach)
1061 detach_advice(new_branch_info->name);
1062 describe_detached_head(_("HEAD is now at"), new_branch_info->commit);
1063 }
1064 } else if (new_branch_info->path) { /* Switch branches. */
1065 if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", new_branch_info->path, msg.buf) < 0)
1066 die(_("unable to update HEAD"));
1067 if (!opts->quiet) {
1068 if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) {
1069 if (opts->new_branch_force)
1070 fprintf(stderr, _("Reset branch '%s'\n"),
1071 new_branch_info->name);
1072 else
1073 fprintf(stderr, _("Already on '%s'\n"),
1074 new_branch_info->name);
1075 } else if (opts->new_branch) {
1076 if (opts->branch_exists)
1077 fprintf(stderr, _("Switched to and reset branch '%s'\n"), new_branch_info->name);
1078 else
1079 fprintf(stderr, _("Switched to a new branch '%s'\n"), new_branch_info->name);
1080 } else {
1081 fprintf(stderr, _("Switched to branch '%s'\n"),
1082 new_branch_info->name);
1083 }
1084 }
1085 if (old_branch_info->path && old_branch_info->name) {
1086 if (!refs_ref_exists(get_main_ref_store(the_repository), old_branch_info->path) && refs_reflog_exists(get_main_ref_store(the_repository), old_branch_info->path))
1087 refs_delete_reflog(get_main_ref_store(the_repository),
1088 old_branch_info->path);
1089 }
1090 }
1091 if (!opts->quiet)
1092 flags |= REMOVE_BRANCH_STATE_VERBOSE;
1093 if (merge_conflicts)
1094 flags |= REMOVE_BRANCH_STATE_PRESERVE_CONFLICT_LABELS;
1095 remove_branch_state(the_repository, flags);
1096 strbuf_release(&msg);
1097 if (!opts->quiet &&
1098 !opts->force_detach &&
1099 (new_branch_info->path || !strcmp(new_branch_info->name, "HEAD")))
1100 report_tracking(new_branch_info);
1101}
1102
1103static int add_pending_uninteresting_ref(const struct reference *ref, void *cb_data)
1104{
1105 add_pending_oid(cb_data, ref->name, ref->oid, UNINTERESTING);
1106 return 0;
1107}
1108
1109static void describe_one_orphan(struct strbuf *sb, struct commit *commit)
1110{
1111 strbuf_addstr(sb, " ");
1112 strbuf_add_unique_abbrev(sb, &commit->object.oid, DEFAULT_ABBREV);
1113 strbuf_addch(sb, ' ');
1114 if (!repo_parse_commit(the_repository, commit))
1115 pp_commit_easy(CMIT_FMT_ONELINE, commit, sb);
1116 strbuf_addch(sb, '\n');
1117}
1118
1119#define ORPHAN_CUTOFF 4
1120static void suggest_reattach(struct commit *commit, struct rev_info *revs)
1121{
1122 struct commit *c, *last = NULL;
1123 struct strbuf sb = STRBUF_INIT;
1124 int lost = 0;
1125 while ((c = get_revision(revs)) != NULL) {
1126 if (lost < ORPHAN_CUTOFF)
1127 describe_one_orphan(&sb, c);
1128 last = c;
1129 lost++;
1130 }
1131 if (ORPHAN_CUTOFF < lost) {
1132 int more = lost - ORPHAN_CUTOFF;
1133 if (more == 1)
1134 describe_one_orphan(&sb, last);
1135 else
1136 strbuf_addf(&sb, Q_(" ... and %d more.\n",
1137 " ... and %d more.\n",
1138 more), more);
1139 }
1140
1141 fprintf(stderr,
1142 Q_(
1143 /* The singular version */
1144 "Warning: you are leaving %d commit behind, "
1145 "not connected to\n"
1146 "any of your branches:\n\n"
1147 "%s\n",
1148 /* The plural version */
1149 "Warning: you are leaving %d commits behind, "
1150 "not connected to\n"
1151 "any of your branches:\n\n"
1152 "%s\n",
1153 /* Give ngettext() the count */
1154 lost),
1155 lost,
1156 sb.buf);
1157 strbuf_release(&sb);
1158
1159 if (advice_enabled(ADVICE_DETACHED_HEAD))
1160 fprintf(stderr,
1161 Q_(
1162 /* The singular version */
1163 "If you want to keep it by creating a new branch, "
1164 "this may be a good time\nto do so with:\n\n"
1165 " git branch <new-branch-name> %s\n\n",
1166 /* The plural version */
1167 "If you want to keep them by creating a new branch, "
1168 "this may be a good time\nto do so with:\n\n"
1169 " git branch <new-branch-name> %s\n\n",
1170 /* Give ngettext() the count */
1171 lost),
1172 repo_find_unique_abbrev(the_repository, &commit->object.oid, DEFAULT_ABBREV));
1173}
1174
1175/*
1176 * We are about to leave commit that was at the tip of a detached
1177 * HEAD. If it is not reachable from any ref, this is the last chance
1178 * for the user to do so without resorting to reflog.
1179 */
1180static void orphaned_commit_warning(struct commit *old_commit, struct commit *new_commit)
1181{
1182 struct rev_info revs;
1183 struct object *object = &old_commit->object;
1184
1185 repo_init_revisions(the_repository, &revs, NULL);
1186 setup_revisions(0, NULL, &revs, NULL);
1187
1188 object->flags &= ~UNINTERESTING;
1189 add_pending_object(&revs, object, oid_to_hex(&object->oid));
1190
1191 refs_for_each_ref(get_main_ref_store(the_repository),
1192 add_pending_uninteresting_ref, &revs);
1193 if (new_commit)
1194 add_pending_oid(&revs, "HEAD",
1195 &new_commit->object.oid,
1196 UNINTERESTING);
1197
1198 if (prepare_revision_walk(&revs))
1199 die(_("internal error in revision walk"));
1200 if (!(old_commit->object.flags & UNINTERESTING))
1201 suggest_reattach(old_commit, &revs);
1202 else
1203 describe_detached_head(_("Previous HEAD position was"), old_commit);
1204
1205 /* Clean up objects used, as they will be reused. */
1206 repo_clear_commit_marks(the_repository, ALL_REV_FLAGS);
1207 release_revisions(&revs);
1208}
1209
1210static int switch_branches(const struct checkout_opts *opts,
1211 struct branch_info *new_branch_info)
1212{
1213 int ret = 0;
1214 struct branch_info old_branch_info = { 0 };
1215 struct object_id rev;
1216 int flag, writeout_error = 0;
1217 int do_merge = 1;
1218 int created_autostash = 0;
1219 enum stash_apply_result autostash_res = STASH_APPLY_CLEAN;
1220 struct strbuf old_commit_shortname = STRBUF_INIT;
1221 struct strbuf autostash_msg = STRBUF_INIT;
1222 const char *stash_label_base = NULL;
1223
1224 trace2_cmd_mode("branch");
1225
1226 memset(&old_branch_info, 0, sizeof(old_branch_info));
1227 old_branch_info.path = refs_resolve_refdup(get_main_ref_store(the_repository),
1228 "HEAD", 0, &rev, &flag);
1229 if (old_branch_info.path)
1230 old_branch_info.commit = lookup_commit_reference_gently(the_repository, &rev, 1);
1231 if (!(flag & REF_ISSYMREF))
1232 FREE_AND_NULL(old_branch_info.path);
1233
1234 if (old_branch_info.path) {
1235 const char *const prefix = "refs/heads/";
1236 const char *p;
1237 if (skip_prefix(old_branch_info.path, prefix, &p))
1238 old_branch_info.name = xstrdup(p);
1239 }
1240
1241 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
1242 if (new_branch_info->name)
1243 BUG("'switch --orphan' should never accept a commit as starting point");
1244 new_branch_info->commit = NULL;
1245 new_branch_info->name = xstrdup("(empty)");
1246 do_merge = 1;
1247 }
1248
1249 if (!new_branch_info->name) {
1250 new_branch_info->name = xstrdup("HEAD");
1251 new_branch_info->commit = old_branch_info.commit;
1252 if (!new_branch_info->commit)
1253 die(_("You are on a branch yet to be born"));
1254 parse_commit_or_die(new_branch_info->commit);
1255
1256 if (opts->only_merge_on_switching_branches)
1257 do_merge = 0;
1258 }
1259
1260 if (old_branch_info.name) {
1261 stash_label_base = old_branch_info.name;
1262 } else if (old_branch_info.commit) {
1263 strbuf_add_unique_abbrev(&old_commit_shortname,
1264 &old_branch_info.commit->object.oid,
1265 DEFAULT_ABBREV);
1266 stash_label_base = old_commit_shortname.buf;
1267 }
1268
1269 if (do_merge) {
1270 ret = merge_working_tree(opts, &old_branch_info, new_branch_info,
1271 opts->merge, &writeout_error);
1272 if (ret == MERGE_WORKING_TREE_UNPACK_FAILED && opts->merge) {
1273 strbuf_addf(&autostash_msg,
1274 "autostash while switching to '%s'",
1275 new_branch_info->name);
1276 create_autostash_ref(the_repository,
1277 "CHECKOUT_AUTOSTASH_HEAD",
1278 autostash_msg.buf, true);
1279 created_autostash = 1;
1280 ret = merge_working_tree(opts, &old_branch_info, new_branch_info,
1281 false, &writeout_error);
1282 }
1283 if (created_autostash) {
1284 if (opts->conflict_style >= 0) {
1285 struct strbuf cfg = STRBUF_INIT;
1286 strbuf_addf(&cfg, "merge.conflictStyle=%s",
1287 conflict_style_name(opts->conflict_style));
1288 git_config_push_parameter(cfg.buf);
1289 strbuf_release(&cfg);
1290 }
1291 autostash_res = apply_autostash_ref(the_repository,
1292 "CHECKOUT_AUTOSTASH_HEAD",
1293 new_branch_info->name,
1294 "local",
1295 stash_label_base,
1296 autostash_msg.buf);
1297 }
1298 if (ret) {
1299 branch_info_release(&old_branch_info);
1300 strbuf_release(&old_commit_shortname);
1301 strbuf_release(&autostash_msg);
1302 return ret < 0 ? 1 : ret;
1303 }
1304 }
1305
1306 if (!opts->quiet && !old_branch_info.path && old_branch_info.commit && new_branch_info->commit != old_branch_info.commit)
1307 orphaned_commit_warning(old_branch_info.commit, new_branch_info->commit);
1308
1309 if (autostash_res == STASH_APPLY_CONFLICT && !opts->quiet)
1310 fputc('\n', stderr);
1311
1312 update_refs_for_switch(opts, &old_branch_info, new_branch_info,
1313 autostash_res == STASH_APPLY_CONFLICT);
1314
1315 if (created_autostash) {
1316 discard_index(the_repository->index);
1317 if (repo_read_index(the_repository) < 0)
1318 die(_("index file corrupt"));
1319
1320 if (!opts->quiet && new_branch_info->commit) {
1321 printf(_("The following paths have local changes:\n"));
1322 show_local_changes(&new_branch_info->commit->object,
1323 &opts->diff_options);
1324 }
1325 }
1326
1327 ret = post_checkout_hook(old_branch_info.commit, new_branch_info->commit, 1);
1328 branch_info_release(&old_branch_info);
1329 strbuf_release(&old_commit_shortname);
1330 strbuf_release(&autostash_msg);
1331
1332 return ret || writeout_error;
1333}
1334
1335static int git_checkout_config(const char *var, const char *value,
1336 const struct config_context *ctx, void *cb)
1337{
1338 struct checkout_opts *opts = cb;
1339
1340 if (!strcmp(var, "diff.ignoresubmodules")) {
1341 if (!value)
1342 return config_error_nonbool(var);
1343 handle_ignore_submodules_arg(&opts->diff_options, value);
1344 return 0;
1345 }
1346 if (!strcmp(var, "checkout.guess")) {
1347 opts->dwim_new_local_branch = git_config_bool(var, value);
1348 return 0;
1349 }
1350
1351 if (starts_with(var, "submodule."))
1352 return git_default_submodule_config(var, value, NULL);
1353
1354 return git_xmerge_config(var, value, ctx, NULL);
1355}
1356
1357static void setup_new_branch_info_and_source_tree(
1358 struct branch_info *new_branch_info,
1359 struct checkout_opts *opts,
1360 struct object_id *rev,
1361 const char *arg)
1362{
1363 struct tree **source_tree = &opts->source_tree;
1364 struct object_id branch_rev;
1365
1366 /* treat '@' as a shortcut for 'HEAD' */
1367 new_branch_info->name = !strcmp(arg, "@") ? xstrdup("HEAD") :
1368 xstrdup(arg);
1369 setup_branch_path(new_branch_info);
1370
1371 if (!check_refname_format(new_branch_info->path, 0) &&
1372 !refs_read_ref(get_main_ref_store(the_repository), new_branch_info->path, &branch_rev))
1373 oidcpy(rev, &branch_rev);
1374 else
1375 /* not an existing branch */
1376 FREE_AND_NULL(new_branch_info->path);
1377
1378 new_branch_info->commit = lookup_commit_reference_gently(the_repository, rev, 1);
1379 if (!new_branch_info->commit) {
1380 /* not a commit */
1381 *source_tree = repo_parse_tree_indirect(the_repository, rev);
1382 if (!*source_tree)
1383 die(_("unable to read tree (%s)"), oid_to_hex(rev));
1384 } else {
1385 parse_commit_or_die(new_branch_info->commit);
1386 *source_tree = repo_get_commit_tree(the_repository,
1387 new_branch_info->commit);
1388 if (!*source_tree)
1389 die(_("unable to read tree (%s)"),
1390 oid_to_hex(&new_branch_info->commit->object.oid));
1391 }
1392}
1393
1394
1395enum checkout_command {
1396 CHECKOUT_CHECKOUT = 1,
1397 CHECKOUT_SWITCH = 2,
1398 CHECKOUT_RESTORE = 3,
1399};
1400
1401static void advise_disambiguating_remotes(enum checkout_command which_command,
1402 const char *branch,
1403 const struct string_list *matched_remote_names)
1404{
1405 const char *cmdname;
1406 struct string_list_item *item;
1407
1408 switch (which_command) {
1409 case CHECKOUT_CHECKOUT:
1410 cmdname = "checkout";
1411 break;
1412 case CHECKOUT_SWITCH:
1413 cmdname = "switch";
1414 break;
1415 default:
1416 BUG("command <%d> should not reach advise_disambiguating_remotes",
1417 which_command);
1418 break;
1419 }
1420
1421 advise(_("Branch name '%s' appears in multiple remotes:"), branch);
1422 for_each_string_list_item(item, matched_remote_names) {
1423 advise(_(" %s"), item->string);
1424 }
1425 advise(_("If you meant to check out a remote tracking branch on <remote>,\n"
1426 "you can do so by fully qualifying the name with the --track option:\n"
1427 "\n"
1428 " git %s --track <remote>/%s\n"
1429 "\n"
1430 "If you'd like to always have checkouts of an ambiguous name prefer\n"
1431 "one remote, e.g. the 'origin' remote, consider setting\n"
1432 "checkout.defaultRemote=origin in your config."),
1433 cmdname, branch);
1434}
1435
1436static char *parse_remote_branch(const char *arg,
1437 struct object_id *rev,
1438 int could_be_checkout_paths,
1439 enum checkout_command which_command)
1440{
1441 int num_matches = 0;
1442 struct string_list matched_remote_names = STRING_LIST_INIT_DUP;
1443
1444 char *remote = unique_tracking_name(arg, rev, &num_matches,
1445 &matched_remote_names);
1446
1447 if (remote && could_be_checkout_paths) {
1448 die(_("'%s' could be both a local file and a tracking branch.\n"
1449 "Please use -- (and optionally --no-guess) to disambiguate"),
1450 arg);
1451 }
1452
1453 if (!remote && num_matches > 1) {
1454 if (advice_enabled(ADVICE_CHECKOUT_AMBIGUOUS_REMOTE_BRANCH_NAME))
1455 advise_disambiguating_remotes(which_command, arg,
1456 &matched_remote_names);
1457 die(_("'%s' matched multiple (%d) remote tracking branches"),
1458 arg, num_matches);
1459 }
1460
1461 string_list_clear(&matched_remote_names, 0);
1462
1463 return remote;
1464}
1465
1466static int parse_branchname_arg(int argc, const char **argv,
1467 int dwim_new_local_branch_ok,
1468 enum checkout_command which_command,
1469 struct branch_info *new_branch_info,
1470 struct checkout_opts *opts,
1471 struct object_id *rev)
1472{
1473 const char **new_branch = &opts->new_branch;
1474 int argcount = 0;
1475 const char *arg;
1476 char *remote = NULL;
1477 int dash_dash_pos;
1478 int has_dash_dash = 0;
1479 int i;
1480
1481 /*
1482 * case 1: git checkout <ref> -- [<paths>]
1483 *
1484 * <ref> must be a valid tree, everything after the '--' must be
1485 * a path.
1486 *
1487 * case 2: git checkout -- [<paths>]
1488 *
1489 * everything after the '--' must be paths.
1490 *
1491 * case 3: git checkout <something> [--]
1492 *
1493 * (a) If <something> is a commit, that is to
1494 * switch to the branch or detach HEAD at it. As a special case,
1495 * if <something> is A...B (missing A or B means HEAD but you can
1496 * omit at most one side), and if there is a unique merge base
1497 * between A and B, A...B names that merge base.
1498 *
1499 * (b) If <something> is _not_ a commit, either "--" is present
1500 * or <something> is not a path, no -t or -b was given,
1501 * and there is a tracking branch whose name is <something>
1502 * in one and only one remote (or if the branch exists on the
1503 * remote named in checkout.defaultRemote), then this is a
1504 * short-hand to fork local <something> from that
1505 * remote-tracking branch.
1506 *
1507 * (c) Otherwise, if "--" is present, treat it like case (1).
1508 *
1509 * (d) Otherwise :
1510 * - if it's a reference, treat it like case (1)
1511 * - else if it's a path, treat it like case (2)
1512 * - else: fail.
1513 *
1514 * case 4: git checkout <something> <paths>
1515 *
1516 * The first argument must not be ambiguous.
1517 * - If it's *only* a reference, treat it like case (1).
1518 * - If it's only a path, treat it like case (2).
1519 * - else: fail.
1520 *
1521 */
1522 if (!argc)
1523 return 0;
1524
1525 if (!opts->accept_pathspec) {
1526 if (argc > 1)
1527 die(_("only one reference expected"));
1528 has_dash_dash = 1; /* helps disambiguate */
1529 }
1530
1531 arg = argv[0];
1532 dash_dash_pos = -1;
1533 for (i = 0; i < argc; i++) {
1534 if (opts->accept_pathspec && !strcmp(argv[i], "--")) {
1535 dash_dash_pos = i;
1536 break;
1537 }
1538 }
1539 if (dash_dash_pos == 0)
1540 return 1; /* case (2) */
1541 else if (dash_dash_pos == 1)
1542 has_dash_dash = 1; /* case (3) or (1) */
1543 else if (dash_dash_pos >= 2)
1544 die(Q_("only one reference expected, %d given.",
1545 "only one reference expected, %d given.",
1546 dash_dash_pos), dash_dash_pos);
1547 opts->count_checkout_paths = !opts->quiet && !has_dash_dash;
1548
1549 if (!strcmp(arg, "-"))
1550 arg = "@{-1}";
1551
1552 if (repo_get_oid_mb(the_repository, arg, rev)) {
1553 /*
1554 * Either case (3) or (4), with <something> not being
1555 * a commit, or an attempt to use case (1) with an
1556 * invalid ref.
1557 *
1558 * It's likely an error, but we need to find out if
1559 * we should auto-create the branch, case (3).(b).
1560 */
1561 int recover_with_dwim = dwim_new_local_branch_ok;
1562
1563 int could_be_checkout_paths = !has_dash_dash &&
1564 check_filename(opts->prefix, arg);
1565
1566 if (!has_dash_dash && !no_wildcard(arg))
1567 recover_with_dwim = 0;
1568
1569 /*
1570 * Accept "git checkout foo", "git checkout foo --"
1571 * and "git switch foo" as candidates for dwim.
1572 */
1573 if (!(argc == 1 && !has_dash_dash) &&
1574 !(argc == 2 && has_dash_dash) &&
1575 opts->accept_pathspec)
1576 recover_with_dwim = 0;
1577
1578 if (recover_with_dwim) {
1579 remote = parse_remote_branch(arg, rev,
1580 could_be_checkout_paths,
1581 which_command);
1582 if (remote) {
1583 *new_branch = arg;
1584 arg = remote;
1585 /* DWIMmed to create local branch, case (3).(b) */
1586 } else {
1587 recover_with_dwim = 0;
1588 }
1589 }
1590
1591 if (!recover_with_dwim) {
1592 if (has_dash_dash)
1593 die(_("invalid reference: %s"), arg);
1594 return argcount;
1595 }
1596 }
1597
1598 /* we can't end up being in (2) anymore, eat the argument */
1599 argcount++;
1600 argv++;
1601 argc--;
1602
1603 setup_new_branch_info_and_source_tree(new_branch_info, opts, rev, arg);
1604
1605 if (!opts->source_tree) /* case (1): want a tree */
1606 die(_("reference is not a tree: %s"), arg);
1607
1608 if (!has_dash_dash) { /* case (3).(d) -> (1) */
1609 /*
1610 * Do not complain the most common case
1611 * git checkout branch
1612 * even if there happen to be a file called 'branch';
1613 * it would be extremely annoying.
1614 */
1615 if (argc)
1616 verify_non_filename(the_repository, opts->prefix, arg);
1617 } else if (opts->accept_pathspec) {
1618 argcount++;
1619 argv++;
1620 argc--;
1621 }
1622
1623 free(remote);
1624 return argcount;
1625}
1626
1627static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
1628{
1629 int status;
1630 struct strbuf branch_ref = STRBUF_INIT;
1631
1632 trace2_cmd_mode("unborn");
1633
1634 if (!opts->new_branch)
1635 die(_("You are on a branch yet to be born"));
1636 strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
1637 status = refs_update_symref(get_main_ref_store(the_repository),
1638 "HEAD", branch_ref.buf, "checkout -b");
1639 strbuf_release(&branch_ref);
1640 if (!opts->quiet)
1641 fprintf(stderr, _("Switched to a new branch '%s'\n"),
1642 opts->new_branch);
1643 return status;
1644}
1645
1646static void die_expecting_a_branch(const struct branch_info *branch_info)
1647{
1648 struct object_id oid;
1649 char *to_free;
1650 int code;
1651
1652 if (repo_dwim_ref(the_repository, branch_info->name,
1653 strlen(branch_info->name), &oid, &to_free, 0) == 1) {
1654 const char *ref = to_free;
1655
1656 if (skip_prefix(ref, "refs/tags/", &ref))
1657 code = die_message(_("a branch is expected, got tag '%s'"), ref);
1658 else if (skip_prefix(ref, "refs/remotes/", &ref))
1659 code = die_message(_("a branch is expected, got remote branch '%s'"), ref);
1660 else
1661 code = die_message(_("a branch is expected, got '%s'"), ref);
1662 }
1663 else if (branch_info->commit)
1664 code = die_message(_("a branch is expected, got commit '%s'"), branch_info->name);
1665 else
1666 /*
1667 * This case should never happen because we already die() on
1668 * non-commit, but just in case.
1669 */
1670 code = die_message(_("a branch is expected, got '%s'"), branch_info->name);
1671
1672 if (advice_enabled(ADVICE_SUGGEST_DETACHING_HEAD))
1673 advise(_("If you want to detach HEAD at the commit, try again with the --detach option."));
1674
1675 exit(code);
1676}
1677
1678static void die_if_some_operation_in_progress(void)
1679{
1680 struct wt_status_state state;
1681
1682 memset(&state, 0, sizeof(state));
1683 wt_status_get_state(the_repository, &state, 0);
1684
1685 if (state.merge_in_progress)
1686 die(_("cannot switch branch while merging\n"
1687 "Consider \"git merge --quit\" "
1688 "or \"git worktree add\"."));
1689 if (state.am_in_progress)
1690 die(_("cannot switch branch in the middle of an am session\n"
1691 "Consider \"git am --quit\" "
1692 "or \"git worktree add\"."));
1693 if (state.rebase_interactive_in_progress || state.rebase_in_progress)
1694 die(_("cannot switch branch while rebasing\n"
1695 "Consider \"git rebase --quit\" "
1696 "or \"git worktree add\"."));
1697 if (state.cherry_pick_in_progress)
1698 die(_("cannot switch branch while cherry-picking\n"
1699 "Consider \"git cherry-pick --quit\" "
1700 "or \"git worktree add\"."));
1701 if (state.revert_in_progress)
1702 die(_("cannot switch branch while reverting\n"
1703 "Consider \"git revert --quit\" "
1704 "or \"git worktree add\"."));
1705 if (state.bisect_in_progress)
1706 warning(_("you are switching branch while bisecting"));
1707
1708 wt_status_state_free_buffers(&state);
1709}
1710
1711/*
1712 * die if attempting to checkout an existing branch that is in use
1713 * in another worktree, unless ignore-other-wortrees option is given.
1714 * The check is bypassed when the branch is already the current one,
1715 * as it will not make things any worse.
1716 */
1717static void die_if_switching_to_a_branch_in_use(struct checkout_opts *opts,
1718 const char *full_ref)
1719{
1720 int flags;
1721 char *head_ref;
1722
1723 if (opts->ignore_other_worktrees)
1724 return;
1725 head_ref = refs_resolve_refdup(get_main_ref_store(the_repository),
1726 "HEAD", 0, NULL, &flags);
1727 if (head_ref && (!(flags & REF_ISSYMREF) || strcmp(head_ref, full_ref)))
1728 die_if_checked_out(full_ref, 1);
1729 free(head_ref);
1730}
1731
1732static int checkout_branch(struct checkout_opts *opts,
1733 struct branch_info *new_branch_info)
1734{
1735 struct repo_config_values *cfg = repo_config_values(the_repository);
1736 int noop_switch = (!new_branch_info->name &&
1737 !opts->new_branch &&
1738 !opts->force_detach);
1739
1740 if (opts->pathspec.nr)
1741 die(_("paths cannot be used with switching branches"));
1742
1743 if (opts->patch_mode)
1744 die(_("'%s' cannot be used with switching branches"),
1745 "--patch");
1746
1747 if (opts->overlay_mode != -1)
1748 die(_("'%s' cannot be used with switching branches"),
1749 "--[no]-overlay");
1750
1751 if (opts->writeout_stage) {
1752 const char *msg;
1753 if (noop_switch)
1754 msg = _("'%s' needs the paths to check out");
1755 else
1756 msg = _("'%s' cannot be used with switching branches");
1757 die(msg, "--ours/--theirs");
1758 }
1759
1760 if (opts->force && opts->merge)
1761 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1762
1763 if (opts->discard_changes && opts->merge)
1764 die(_("'%s' cannot be used with '%s'"), "--discard-changes", "--merge");
1765
1766 if (opts->force_detach && opts->new_branch)
1767 die(_("'%s' cannot be used with '%s'"),
1768 "--detach", "-b/-B/--orphan");
1769
1770 if (opts->new_orphan_branch) {
1771 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1772 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1773 if (opts->orphan_from_empty_tree && new_branch_info->name)
1774 die(_("'%s' cannot take <start-point>"), "--orphan");
1775 } else if (opts->force_detach) {
1776 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1777 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1778 } else if (opts->track == BRANCH_TRACK_UNSPECIFIED)
1779 opts->track = cfg->branch_track;
1780
1781 if (new_branch_info->name && !new_branch_info->commit)
1782 die(_("Cannot switch branch to a non-commit '%s'"),
1783 new_branch_info->name);
1784
1785 if (noop_switch &&
1786 !opts->switch_branch_doing_nothing_is_ok)
1787 die(_("missing branch or commit argument"));
1788
1789 if (!opts->implicit_detach &&
1790 !opts->force_detach &&
1791 !opts->new_branch &&
1792 !opts->new_branch_force &&
1793 new_branch_info->name &&
1794 !new_branch_info->path)
1795 die_expecting_a_branch(new_branch_info);
1796
1797 if (!opts->can_switch_when_in_progress)
1798 die_if_some_operation_in_progress();
1799
1800 /* "git checkout <branch>" */
1801 if (new_branch_info->path && !opts->force_detach && !opts->new_branch)
1802 die_if_switching_to_a_branch_in_use(opts, new_branch_info->path);
1803
1804 /* "git checkout -B <branch>" */
1805 if (opts->new_branch_force) {
1806 char *full_ref = xstrfmt("refs/heads/%s", opts->new_branch);
1807 die_if_switching_to_a_branch_in_use(opts, full_ref);
1808 free(full_ref);
1809 }
1810
1811 if (!new_branch_info->commit && opts->new_branch) {
1812 struct object_id rev;
1813 int flag;
1814
1815 if (!refs_read_ref_full(get_main_ref_store(the_repository), "HEAD", 0, &rev, &flag) &&
1816 (flag & REF_ISSYMREF) && is_null_oid(&rev))
1817 return switch_unborn_to_new_branch(opts);
1818 }
1819 return switch_branches(opts, new_branch_info);
1820}
1821
1822static int parse_opt_conflict(const struct option *o, const char *arg, int unset)
1823{
1824 struct checkout_opts *opts = o->value;
1825
1826 if (unset) {
1827 opts->conflict_style = -1;
1828 return 0;
1829 }
1830 opts->conflict_style = parse_conflict_style_name(arg);
1831 if (opts->conflict_style < 0)
1832 return error(_("unknown conflict style '%s'"), arg);
1833 /* --conflict overrides a previous --no-merge */
1834 if (!opts->merge)
1835 opts->merge = -1;
1836
1837 return 0;
1838}
1839
1840static struct option *add_common_options(struct checkout_opts *opts,
1841 struct option *prevopts)
1842{
1843 struct option options[] = {
1844 OPT__QUIET(&opts->quiet, N_("suppress progress reporting")),
1845 OPT_CALLBACK_F(0, "recurse-submodules", NULL,
1846 "checkout", "control recursive updating of submodules",
1847 PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater),
1848 OPT_BOOL(0, "progress", &opts->show_progress, N_("force progress reporting")),
1849 OPT_BOOL('m', "merge", &opts->merge, N_("perform a 3-way merge with the new branch")),
1850 OPT_CALLBACK(0, "conflict", opts, N_("style"),
1851 N_("conflict style (merge, diff3, or zdiff3)"),
1852 parse_opt_conflict),
1853 OPT_END()
1854 };
1855 struct option *newopts = parse_options_concat(prevopts, options);
1856 free(prevopts);
1857 return newopts;
1858}
1859
1860static struct option *add_common_switch_branch_options(
1861 struct checkout_opts *opts, struct option *prevopts)
1862{
1863 struct option options[] = {
1864 OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
1865 OPT_CALLBACK_F('t', "track", &opts->track, "(direct|inherit)",
1866 N_("set branch tracking configuration"),
1867 PARSE_OPT_OPTARG,
1868 parse_opt_tracking_mode),
1869 OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
1870 PARSE_OPT_NOCOMPLETE),
1871 OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unborn branch")),
1872 OPT_BOOL_F(0, "overwrite-ignore", &opts->overwrite_ignore,
1873 N_("update ignored files (default)"),
1874 PARSE_OPT_NOCOMPLETE),
1875 OPT_BOOL(0, "ignore-other-worktrees", &opts->ignore_other_worktrees,
1876 N_("do not check if another worktree is using this branch")),
1877 OPT_END()
1878 };
1879 struct option *newopts = parse_options_concat(prevopts, options);
1880 free(prevopts);
1881 return newopts;
1882}
1883
1884static struct option *add_checkout_path_options(struct checkout_opts *opts,
1885 struct option *prevopts)
1886{
1887 struct option options[] = {
1888 OPT_SET_INT_F('2', "ours", &opts->writeout_stage,
1889 N_("checkout our version for unmerged files"),
1890 2, PARSE_OPT_NONEG),
1891 OPT_SET_INT_F('3', "theirs", &opts->writeout_stage,
1892 N_("checkout their version for unmerged files"),
1893 3, PARSE_OPT_NONEG),
1894 OPT_BOOL('p', "patch", &opts->patch_mode, N_("select hunks interactively")),
1895 OPT_DIFF_UNIFIED(&opts->patch_context),
1896 OPT_DIFF_INTERHUNK_CONTEXT(&opts->patch_interhunk_context),
1897 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts->ignore_skipworktree,
1898 N_("do not limit pathspecs to sparse entries only")),
1899 OPT_PATHSPEC_FROM_FILE(&opts->pathspec_from_file),
1900 OPT_PATHSPEC_FILE_NUL(&opts->pathspec_file_nul),
1901 OPT_END()
1902 };
1903 struct option *newopts = parse_options_concat(prevopts, options);
1904 free(prevopts);
1905 return newopts;
1906}
1907
1908/* create-branch option (either b or c) */
1909static char cb_option = 'b';
1910
1911static int checkout_main(int argc, const char **argv, const char *prefix,
1912 struct checkout_opts *opts, struct option *options,
1913 enum checkout_command which_command)
1914{
1915 int parseopt_flags = 0;
1916 struct branch_info new_branch_info = { 0 };
1917 int ret;
1918
1919 static const char * const checkout_usage[] = {
1920 N_("git checkout [<options>] <branch>"),
1921 N_("git checkout [<options>] [<branch>] -- <file>..."),
1922 NULL,
1923 };
1924
1925 static const char * const switch_branch_usage[] = {
1926 N_("git switch [<options>] [<branch>]"),
1927 NULL,
1928 };
1929
1930 static const char * const restore_usage[] = {
1931 N_("git restore [<options>] [--source=<branch>] <file>..."),
1932 NULL,
1933 };
1934
1935 const char * const *usagestr;
1936
1937 switch (which_command) {
1938 case CHECKOUT_CHECKOUT:
1939 usagestr = checkout_usage;
1940 break;
1941 case CHECKOUT_SWITCH:
1942 usagestr = switch_branch_usage;
1943 break;
1944 case CHECKOUT_RESTORE:
1945 usagestr = restore_usage;
1946 break;
1947 default:
1948 BUG("no such checkout variant %d", which_command);
1949 }
1950
1951 opts->overwrite_ignore = 1;
1952 opts->prefix = prefix;
1953 opts->show_progress = -1;
1954
1955 repo_config(the_repository, git_checkout_config, opts);
1956 if (the_repository->gitdir) {
1957 prepare_repo_settings(the_repository);
1958 the_repository->settings.command_requires_full_index = 0;
1959 }
1960
1961 opts->track = BRANCH_TRACK_UNSPECIFIED;
1962
1963 if (!opts->accept_pathspec && !opts->accept_ref)
1964 BUG("make up your mind, you need to take _something_");
1965 if (opts->accept_pathspec && opts->accept_ref)
1966 parseopt_flags = PARSE_OPT_KEEP_DASHDASH;
1967
1968 argc = parse_options(argc, argv, prefix, options,
1969 usagestr, parseopt_flags);
1970
1971 if (opts->patch_context < -1)
1972 die(_("'%s' cannot be negative"), "--unified");
1973 if (opts->patch_interhunk_context < -1)
1974 die(_("'%s' cannot be negative"), "--inter-hunk-context");
1975
1976 if (!opts->patch_mode) {
1977 if (opts->patch_context != -1)
1978 die(_("the option '%s' requires '%s'"), "--unified", "--patch");
1979 if (opts->patch_interhunk_context != -1)
1980 die(_("the option '%s' requires '%s'"), "--inter-hunk-context", "--patch");
1981 if (!opts->auto_advance)
1982 die(_("the option '%s' requires '%s'"), "--no-auto-advance", "--patch");
1983 }
1984
1985 if (opts->show_progress < 0) {
1986 if (opts->quiet)
1987 opts->show_progress = 0;
1988 else
1989 opts->show_progress = isatty(2);
1990 }
1991
1992 /* --conflicts implies --merge */
1993 if (opts->merge == -1)
1994 opts->merge = opts->conflict_style >= 0;
1995
1996 if (opts->force) {
1997 opts->discard_changes = 1;
1998 opts->ignore_unmerged_opt = "--force";
1999 opts->ignore_unmerged = 1;
2000 }
2001
2002 if ((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) > 1)
2003 die(_("options '-%c', '-%c', and '%s' cannot be used together"),
2004 cb_option, toupper(cb_option), "--orphan");
2005
2006 if (opts->overlay_mode == 1 && opts->patch_mode)
2007 die(_("options '%s' and '%s' cannot be used together"), "-p", "--overlay");
2008
2009 if (opts->checkout_index >= 0 || opts->checkout_worktree >= 0) {
2010 if (opts->checkout_index < 0)
2011 opts->checkout_index = 0;
2012 if (opts->checkout_worktree < 0)
2013 opts->checkout_worktree = 0;
2014 } else {
2015 if (opts->checkout_index < 0)
2016 opts->checkout_index = -opts->checkout_index - 1;
2017 if (opts->checkout_worktree < 0)
2018 opts->checkout_worktree = -opts->checkout_worktree - 1;
2019 }
2020 if (opts->checkout_index < 0 || opts->checkout_worktree < 0)
2021 BUG("these flags should be non-negative by now");
2022 /*
2023 * convenient shortcut: "git restore --staged [--worktree]" equals
2024 * "git restore --staged [--worktree] --source HEAD"
2025 */
2026 if (!opts->from_treeish && opts->checkout_index)
2027 opts->from_treeish = "HEAD";
2028
2029 /*
2030 * From here on, new_branch will contain the branch to be checked out,
2031 * and new_branch_force and new_orphan_branch will tell us which one of
2032 * -b/-B/-c/-C/--orphan is being used.
2033 */
2034 if (opts->new_branch_force)
2035 opts->new_branch = opts->new_branch_force;
2036
2037 if (opts->new_orphan_branch)
2038 opts->new_branch = opts->new_orphan_branch;
2039
2040 /* --track without -c/-C/-b/-B/--orphan should DWIM */
2041 if (opts->track != BRANCH_TRACK_UNSPECIFIED && !opts->new_branch) {
2042 const char *argv0 = argv[0];
2043 if (!argc || !strcmp(argv0, "--"))
2044 die(_("--track needs a branch name"));
2045 skip_prefix(argv0, "refs/", &argv0);
2046 skip_prefix(argv0, "remotes/", &argv0);
2047 argv0 = strchr(argv0, '/');
2048 if (!argv0 || !argv0[1])
2049 die(_("missing branch name; try -%c"), cb_option);
2050 opts->new_branch = argv0 + 1;
2051 }
2052
2053 /*
2054 * Extract branch name from command line arguments, so
2055 * all that is left is pathspecs.
2056 *
2057 * Handle
2058 *
2059 * 1) git checkout <tree> -- [<paths>]
2060 * 2) git checkout -- [<paths>]
2061 * 3) git checkout <something> [<paths>]
2062 *
2063 * including "last branch" syntax and DWIM-ery for names of
2064 * remote branches, erroring out for invalid or ambiguous cases.
2065 */
2066 if (argc && opts->accept_ref) {
2067 struct object_id rev;
2068 int dwim_ok =
2069 !opts->patch_mode &&
2070 opts->dwim_new_local_branch &&
2071 opts->track == BRANCH_TRACK_UNSPECIFIED &&
2072 !opts->new_branch;
2073 int n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
2074 &new_branch_info, opts, &rev);
2075 argv += n;
2076 argc -= n;
2077 } else if (!opts->accept_ref && opts->from_treeish) {
2078 struct object_id rev;
2079
2080 if (repo_get_oid_mb(the_repository, opts->from_treeish, &rev))
2081 die(_("could not resolve '%s'"), opts->from_treeish);
2082
2083 setup_new_branch_info_and_source_tree(&new_branch_info,
2084 opts, &rev,
2085 opts->from_treeish);
2086
2087 if (!opts->source_tree)
2088 die(_("reference is not a tree: %s"), opts->from_treeish);
2089 }
2090
2091 if (argc) {
2092 parse_pathspec(&opts->pathspec, 0,
2093 opts->patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0,
2094 prefix, argv);
2095
2096 if (!opts->pathspec.nr)
2097 die(_("invalid path specification"));
2098
2099 /*
2100 * Try to give more helpful suggestion.
2101 * new_branch && argc > 1 will be caught later.
2102 */
2103 if (opts->new_branch && argc == 1 && !new_branch_info.commit)
2104 die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
2105 argv[0], opts->new_branch);
2106
2107 if (opts->force_detach)
2108 die(_("git checkout: --detach does not take a path argument '%s'"),
2109 argv[0]);
2110 }
2111
2112 if (opts->pathspec_from_file) {
2113 if (opts->pathspec.nr)
2114 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
2115
2116 if (opts->force_detach)
2117 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--detach");
2118
2119 if (opts->patch_mode)
2120 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
2121
2122 parse_pathspec_file(&opts->pathspec, 0,
2123 0,
2124 prefix, opts->pathspec_from_file, opts->pathspec_file_nul);
2125 } else if (opts->pathspec_file_nul) {
2126 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
2127 }
2128
2129 opts->pathspec.recursive = 1;
2130
2131 if (opts->pathspec.nr) {
2132 if (1 < !!opts->writeout_stage + !!opts->force + !!opts->merge)
2133 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
2134 "checking out of the index."));
2135 } else {
2136 if (opts->accept_pathspec && !opts->empty_pathspec_ok &&
2137 !opts->patch_mode) /* patch mode is special */
2138 die(_("you must specify path(s) to restore"));
2139 }
2140
2141 if (opts->new_branch) {
2142 struct strbuf buf = STRBUF_INIT;
2143
2144 if (opts->new_branch_force)
2145 opts->branch_exists = validate_branchname(opts->new_branch, &buf);
2146 else
2147 opts->branch_exists =
2148 validate_new_branchname(opts->new_branch, &buf, 0);
2149 strbuf_release(&buf);
2150 }
2151
2152 if (opts->patch_mode || opts->pathspec.nr)
2153 ret = checkout_paths(opts, &new_branch_info);
2154 else
2155 ret = checkout_branch(opts, &new_branch_info);
2156
2157 branch_info_release(&new_branch_info);
2158 clear_pathspec(&opts->pathspec);
2159 free(opts->pathspec_from_file);
2160 free(options);
2161
2162 return ret;
2163}
2164
2165int cmd_checkout(int argc,
2166 const char **argv,
2167 const char *prefix,
2168 struct repository *repo UNUSED)
2169{
2170 struct checkout_opts opts = CHECKOUT_OPTS_INIT;
2171 struct option *options;
2172 struct option checkout_options[] = {
2173 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
2174 N_("create and checkout a new branch")),
2175 OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
2176 N_("create/reset and checkout a branch")),
2177 OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
2178 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
2179 N_("second guess 'git checkout <no-such-branch>' (default)")),
2180 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode (default)")),
2181 OPT_BOOL(0, "auto-advance", &opts.auto_advance,
2182 N_("auto advance to the next file when selecting hunks interactively")),
2183 OPT_END()
2184 };
2185
2186 opts.dwim_new_local_branch = 1;
2187 opts.switch_branch_doing_nothing_is_ok = 1;
2188 opts.only_merge_on_switching_branches = 0;
2189 opts.accept_ref = 1;
2190 opts.accept_pathspec = 1;
2191 opts.implicit_detach = 1;
2192 opts.can_switch_when_in_progress = 1;
2193 opts.orphan_from_empty_tree = 0;
2194 opts.empty_pathspec_ok = 1;
2195 opts.overlay_mode = -1;
2196 opts.checkout_index = -2; /* default on */
2197 opts.checkout_worktree = -2; /* default on */
2198
2199 if (argc == 3 && !strcmp(argv[1], "-b")) {
2200 /*
2201 * User ran 'git checkout -b <branch>' and expects
2202 * the same behavior as 'git switch -c <branch>'.
2203 */
2204 opts.switch_branch_doing_nothing_is_ok = 0;
2205 opts.only_merge_on_switching_branches = 1;
2206 }
2207
2208 options = parse_options_dup(checkout_options);
2209 options = add_common_options(&opts, options);
2210 options = add_common_switch_branch_options(&opts, options);
2211 options = add_checkout_path_options(&opts, options);
2212
2213 return checkout_main(argc, argv, prefix, &opts, options,
2214 CHECKOUT_CHECKOUT);
2215}
2216
2217int cmd_switch(int argc,
2218 const char **argv,
2219 const char *prefix,
2220 struct repository *repo UNUSED)
2221{
2222 struct checkout_opts opts = CHECKOUT_OPTS_INIT;
2223 struct option *options = NULL;
2224 struct option switch_options[] = {
2225 OPT_STRING('c', "create", &opts.new_branch, N_("branch"),
2226 N_("create and switch to a new branch")),
2227 OPT_STRING('C', "force-create", &opts.new_branch_force, N_("branch"),
2228 N_("create/reset and switch to a branch")),
2229 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
2230 N_("second guess 'git switch <no-such-branch>'")),
2231 OPT_BOOL(0, "discard-changes", &opts.discard_changes,
2232 N_("throw away local modifications")),
2233 OPT_END()
2234 };
2235
2236 opts.dwim_new_local_branch = 1;
2237 opts.accept_ref = 1;
2238 opts.accept_pathspec = 0;
2239 opts.switch_branch_doing_nothing_is_ok = 0;
2240 opts.only_merge_on_switching_branches = 1;
2241 opts.implicit_detach = 0;
2242 opts.can_switch_when_in_progress = 0;
2243 opts.orphan_from_empty_tree = 1;
2244 opts.overlay_mode = -1;
2245
2246 options = parse_options_dup(switch_options);
2247 options = add_common_options(&opts, options);
2248 options = add_common_switch_branch_options(&opts, options);
2249
2250 cb_option = 'c';
2251
2252 return checkout_main(argc, argv, prefix, &opts, options,
2253 CHECKOUT_SWITCH);
2254}
2255
2256int cmd_restore(int argc,
2257 const char **argv,
2258 const char *prefix,
2259 struct repository *repo UNUSED)
2260{
2261 struct checkout_opts opts = CHECKOUT_OPTS_INIT;
2262 struct option *options;
2263 struct option restore_options[] = {
2264 OPT_STRING('s', "source", &opts.from_treeish, "<tree-ish>",
2265 N_("which tree-ish to checkout from")),
2266 OPT_BOOL('S', "staged", &opts.checkout_index,
2267 N_("restore the index")),
2268 OPT_BOOL('W', "worktree", &opts.checkout_worktree,
2269 N_("restore the working tree (default)")),
2270 OPT_BOOL(0, "ignore-unmerged", &opts.ignore_unmerged,
2271 N_("ignore unmerged entries")),
2272 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode")),
2273 OPT_END()
2274 };
2275
2276 opts.accept_ref = 0;
2277 opts.accept_pathspec = 1;
2278 opts.empty_pathspec_ok = 0;
2279 opts.overlay_mode = 0;
2280 opts.checkout_index = -1; /* default off */
2281 opts.checkout_worktree = -2; /* default on */
2282 opts.ignore_unmerged_opt = "--ignore-unmerged";
2283
2284 options = parse_options_dup(restore_options);
2285 options = add_common_options(&opts, options);
2286 options = add_checkout_path_options(&opts, options);
2287
2288 return checkout_main(argc, argv, prefix, &opts, options,
2289 CHECKOUT_RESTORE);
2290}