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