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 allow_autostash,
967 int *writeout_error)
968 {
969 int ret;
970 bool can_autostash = false;
971 struct lock_file lock_file = LOCK_INIT;
972 struct tree *new_tree;
973
974 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
975 if (repo_read_index_preload(the_repository, NULL, 0) < 0) {
976 rollback_lock_file(&lock_file);
977 return error(_("index file corrupt"));
978 }
979
980 resolve_undo_clear_index(the_repository->index);
981 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
982 if (new_branch_info->commit)
983 BUG("'switch --orphan' should never accept a commit as starting point");
984 new_tree = repo_parse_tree_indirect(the_repository,
985 the_hash_algo->empty_tree);
986 if (!new_tree)
987 BUG("unable to read empty tree");
988 } else {
989 new_tree = repo_get_commit_tree(the_repository,
990 new_branch_info->commit);
991 if (!new_tree) {
992 rollback_lock_file(&lock_file);
993 return error(_("unable to read tree (%s)"),
994 oid_to_hex(&new_branch_info->commit->object.oid));
995 }
996 }
997 if (opts->discard_changes) {
998 ret = reset_tree(new_tree, opts, 1, writeout_error, new_branch_info);
999 if (ret) {
1000 rollback_lock_file(&lock_file);
1001 return ret;
1002 }
1003 } else {
1004 struct tree_desc trees[2];
1005 struct tree *tree;
1006 struct unpack_trees_options topts;
1007 const struct object_id *old_commit_oid;
1008
1009 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL, NULL);
1010
1011 if (unmerged_index(the_repository->index)) {
1012 rollback_lock_file(&lock_file);
1013 error(_("you need to resolve your current index first"));
1014 return 1;
1015 }
1016
1017 if (allow_autostash)
1018 can_autostash = has_unstaged_changes(the_repository, 1) ||
1019 has_uncommitted_changes(the_repository, 1);
1020
1021 /* 2-way merge to the new branch */
1022 init_topts(&topts, opts->show_progress,
1023 opts->overwrite_ignore, can_autostash);
1024 init_checkout_metadata(&topts.meta, new_branch_info->refname,
1025 new_branch_info->commit ?
1026 &new_branch_info->commit->object.oid :
1027 &new_branch_info->oid, NULL);
1028
1029 old_commit_oid = old_branch_info->commit ?
1030 &old_branch_info->commit->object.oid :
1031 the_hash_algo->empty_tree;
1032 tree = repo_parse_tree_indirect(the_repository,
1033 old_commit_oid);
1034 if (!tree)
1035 die(_("unable to parse commit %s"),
1036 oid_to_hex(old_commit_oid));
1037
1038 init_tree_desc(&trees[0], &tree->object.oid,
1039 tree->buffer, tree->size);
1040 if (repo_parse_tree(the_repository, new_tree) < 0)
1041 die(NULL);
1042 tree = new_tree;
1043 init_tree_desc(&trees[1], &tree->object.oid,
1044 tree->buffer, tree->size);
1045
1046 ret = unpack_trees(2, trees, &topts);
1047 clear_unpack_trees_porcelain(&topts);
1048 if (ret == -1) {
1049 rollback_lock_file(&lock_file);
1050 return can_autostash ?
1051 MERGE_WORKING_TREE_UNPACK_FAILED : 1;
1052 }
1053 }
1054
1055 if (!cache_tree_fully_valid(the_repository->index->cache_tree))
1056 cache_tree_update(the_repository->index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR);
1057
1058 if (write_locked_index(the_repository->index, &lock_file, COMMIT_LOCK))
1059 die(_("unable to write new index file"));
1060
1061 if (!opts->discard_changes && !opts->quiet && new_branch_info->commit)
1062 show_local_changes(&new_branch_info->commit->object, &opts->diff_options);
1063
1064 return 0;
1065 }
1066
1067 static void report_tracking(struct branch_info *new_branch_info)
1068 {
1069 struct strbuf sb = STRBUF_INIT;
1070 struct branch *branch = branch_get(new_branch_info->name);
1071
1072 if (!format_tracking_info(branch, &sb, AHEAD_BEHIND_FULL, 1))
1073 return;
1074 fputs(sb.buf, stdout);
1075 strbuf_release(&sb);
1076 }
1077
1078 static void update_refs_for_switch(const struct checkout_opts *opts,
1079 struct branch_info *old_branch_info,
1080 struct branch_info *new_branch_info)
1081 {
1082 struct strbuf msg = STRBUF_INIT;
1083 const char *old_desc, *reflog_msg;
1084 if (opts->new_branch) {
1085 if (opts->new_orphan_branch) {
1086 enum log_refs_config log_all_ref_updates = LOG_REFS_UNSET;
1087 const char *value;
1088 char *refname;
1089
1090 if (!repo_config_get_string_tmp(the_repository, "core.logallrefupdates", &value))
1091 log_all_ref_updates = refs_parse_log_all_ref_updates_config(value);
1092
1093 refname = mkpathdup("refs/heads/%s", opts->new_orphan_branch);
1094 if (opts->new_branch_log &&
1095 !should_autocreate_reflog(log_all_ref_updates, refname)) {
1096 int ret;
1097 struct strbuf err = STRBUF_INIT;
1098
1099 ret = refs_create_reflog(get_main_ref_store(the_repository),
1100 refname, &err);
1101 if (ret) {
1102 fprintf(stderr, _("Can not do reflog for '%s': %s\n"),
1103 opts->new_orphan_branch, err.buf);
1104 strbuf_release(&err);
1105 free(refname);
1106 return;
1107 }
1108 strbuf_release(&err);
1109 }
1110 free(refname);
1111 }
1112 else
1113 create_branch(the_repository,
1114 opts->new_branch, new_branch_info->name,
1115 opts->new_branch_force ? 1 : 0,
1116 opts->new_branch_force ? 1 : 0,
1117 opts->new_branch_log,
1118 opts->quiet,
1119 opts->track,
1120 0);
1121 free(new_branch_info->name);
1122 free(new_branch_info->refname);
1123 new_branch_info->name = xstrdup(opts->new_branch);
1124 setup_branch_path(new_branch_info);
1125 }
1126
1127 old_desc = old_branch_info->name;
1128 if (!old_desc && old_branch_info->commit)
1129 old_desc = oid_to_hex(&old_branch_info->commit->object.oid);
1130
1131 reflog_msg = getenv("GIT_REFLOG_ACTION");
1132 if (!reflog_msg)
1133 strbuf_addf(&msg, "checkout: moving from %s to %s",
1134 old_desc ? old_desc : "(invalid)", new_branch_info->name);
1135 else
1136 strbuf_insertstr(&msg, 0, reflog_msg);
1137
1138 if (!strcmp(new_branch_info->name, "HEAD") && !new_branch_info->path && !opts->force_detach) {
1139 /* Nothing to do. */
1140 } else if (opts->force_detach || !new_branch_info->path) { /* No longer on any branch. */
1141 refs_update_ref(get_main_ref_store(the_repository), msg.buf,
1142 "HEAD", &new_branch_info->commit->object.oid,
1143 NULL,
1144 REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR);
1145 if (!opts->quiet) {
1146 if (old_branch_info->path &&
1147 advice_enabled(ADVICE_DETACHED_HEAD) && !opts->force_detach)
1148 detach_advice(new_branch_info->name);
1149 describe_detached_head(_("HEAD is now at"), new_branch_info->commit);
1150 }
1151 } else if (new_branch_info->path) { /* Switch branches. */
1152 if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", new_branch_info->path, msg.buf) < 0)
1153 die(_("unable to update HEAD"));
1154 if (!opts->quiet) {
1155 if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) {
1156 if (opts->new_branch_force)
1157 fprintf(stderr, _("Reset branch '%s'\n"),
1158 new_branch_info->name);
1159 else
1160 fprintf(stderr, _("Already on '%s'\n"),
1161 new_branch_info->name);
1162 } else if (opts->new_branch) {
1163 if (opts->branch_exists)
1164 fprintf(stderr, _("Switched to and reset branch '%s'\n"), new_branch_info->name);
1165 else
1166 fprintf(stderr, _("Switched to a new branch '%s'\n"), new_branch_info->name);
1167 } else {
1168 fprintf(stderr, _("Switched to branch '%s'\n"),
1169 new_branch_info->name);
1170 }
1171 }
1172 if (old_branch_info->path && old_branch_info->name) {
1173 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))
1174 refs_delete_reflog(get_main_ref_store(the_repository),
1175 old_branch_info->path);
1176 }
1177 }
1178 remove_branch_state(the_repository, !opts->quiet);
1179 strbuf_release(&msg);
1180 if (!opts->quiet &&
1181 !opts->force_detach &&
1182 (new_branch_info->path || !strcmp(new_branch_info->name, "HEAD")))
1183 report_tracking(new_branch_info);
1184 }
1185
1186 static int add_pending_uninteresting_ref(const struct reference *ref, void *cb_data)
1187 {
1188 add_pending_oid(cb_data, ref->name, ref->oid, UNINTERESTING);
1189 return 0;
1190 }
1191
1192 static void describe_one_orphan(struct strbuf *sb, struct commit *commit)
1193 {
1194 strbuf_addstr(sb, " ");
1195 strbuf_add_unique_abbrev(sb, &commit->object.oid, DEFAULT_ABBREV);
1196 strbuf_addch(sb, ' ');
1197 if (!repo_parse_commit(the_repository, commit))
1198 pp_commit_easy(CMIT_FMT_ONELINE, commit, sb);
1199 strbuf_addch(sb, '\n');
1200 }
1201
1202 #define ORPHAN_CUTOFF 4
1203 static void suggest_reattach(struct commit *commit, struct rev_info *revs)
1204 {
1205 struct commit *c, *last = NULL;
1206 struct strbuf sb = STRBUF_INIT;
1207 int lost = 0;
1208 while ((c = get_revision(revs)) != NULL) {
1209 if (lost < ORPHAN_CUTOFF)
1210 describe_one_orphan(&sb, c);
1211 last = c;
1212 lost++;
1213 }
1214 if (ORPHAN_CUTOFF < lost) {
1215 int more = lost - ORPHAN_CUTOFF;
1216 if (more == 1)
1217 describe_one_orphan(&sb, last);
1218 else
1219 strbuf_addf(&sb, _(" ... and %d more.\n"), more);
1220 }
1221
1222 fprintf(stderr,
1223 Q_(
1224 /* The singular version */
1225 "Warning: you are leaving %d commit behind, "
1226 "not connected to\n"
1227 "any of your branches:\n\n"
1228 "%s\n",
1229 /* The plural version */
1230 "Warning: you are leaving %d commits behind, "
1231 "not connected to\n"
1232 "any of your branches:\n\n"
1233 "%s\n",
1234 /* Give ngettext() the count */
1235 lost),
1236 lost,
1237 sb.buf);
1238 strbuf_release(&sb);
1239
1240 if (advice_enabled(ADVICE_DETACHED_HEAD))
1241 fprintf(stderr,
1242 Q_(
1243 /* The singular version */
1244 "If you want to keep it by creating a new branch, "
1245 "this may be a good time\nto do so with:\n\n"
1246 " git branch <new-branch-name> %s\n\n",
1247 /* The plural version */
1248 "If you want to keep them by creating a new branch, "
1249 "this may be a good time\nto do so with:\n\n"
1250 " git branch <new-branch-name> %s\n\n",
1251 /* Give ngettext() the count */
1252 lost),
1253 repo_find_unique_abbrev(the_repository, &commit->object.oid, DEFAULT_ABBREV));
1254 }
1255
1256 /*
1257 * We are about to leave commit that was at the tip of a detached
1258 * HEAD. If it is not reachable from any ref, this is the last chance
1259 * for the user to do so without resorting to reflog.
1260 */
1261 static void orphaned_commit_warning(struct commit *old_commit, struct commit *new_commit)
1262 {
1263 struct rev_info revs;
1264 struct object *object = &old_commit->object;
1265
1266 repo_init_revisions(the_repository, &revs, NULL);
1267 setup_revisions(0, NULL, &revs, NULL);
1268
1269 object->flags &= ~UNINTERESTING;
1270 add_pending_object(&revs, object, oid_to_hex(&object->oid));
1271
1272 refs_for_each_ref(get_main_ref_store(the_repository),
1273 add_pending_uninteresting_ref, &revs);
1274 if (new_commit)
1275 add_pending_oid(&revs, "HEAD",
1276 &new_commit->object.oid,
1277 UNINTERESTING);
1278
1279 if (prepare_revision_walk(&revs))
1280 die(_("internal error in revision walk"));
1281 if (!(old_commit->object.flags & UNINTERESTING))
1282 suggest_reattach(old_commit, &revs);
1283 else
1284 describe_detached_head(_("Previous HEAD position was"), old_commit);
1285
1286 /* Clean up objects used, as they will be reused. */
1287 repo_clear_commit_marks(the_repository, ALL_REV_FLAGS);
1288 release_revisions(&revs);
1289 }
1290
1291 static int switch_branches(const struct checkout_opts *opts,
1292 struct branch_info *new_branch_info)
1293 {
1294 int ret = 0;
1295 struct branch_info old_branch_info = { 0 };
1296 struct object_id rev;
1297 int flag, writeout_error = 0;
1298 int do_merge = 1;
1299 int created_autostash = 0;
1300 bool autostash_conflicted = false;
1301 struct strbuf old_commit_shortname = STRBUF_INIT;
1302 struct strbuf autostash_msg = STRBUF_INIT;
1303 const char *stash_label_base = NULL;
1304
1305 trace2_cmd_mode("branch");
1306
1307 memset(&old_branch_info, 0, sizeof(old_branch_info));
1308 old_branch_info.path = refs_resolve_refdup(get_main_ref_store(the_repository),
1309 "HEAD", 0, &rev, &flag);
1310 if (old_branch_info.path)
1311 old_branch_info.commit = lookup_commit_reference_gently(the_repository, &rev, 1);
1312 if (!(flag & REF_ISSYMREF))
1313 FREE_AND_NULL(old_branch_info.path);
1314
1315 if (old_branch_info.path) {
1316 const char *const prefix = "refs/heads/";
1317 const char *p;
1318 if (skip_prefix(old_branch_info.path, prefix, &p))
1319 old_branch_info.name = xstrdup(p);
1320 }
1321
1322 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
1323 if (new_branch_info->name)
1324 BUG("'switch --orphan' should never accept a commit as starting point");
1325 new_branch_info->commit = NULL;
1326 new_branch_info->name = xstrdup("(empty)");
1327 do_merge = 1;
1328 }
1329
1330 if (!new_branch_info->name) {
1331 new_branch_info->name = xstrdup("HEAD");
1332 new_branch_info->commit = old_branch_info.commit;
1333 if (!new_branch_info->commit)
1334 die(_("You are on a branch yet to be born"));
1335 parse_commit_or_die(new_branch_info->commit);
1336
1337 if (opts->only_merge_on_switching_branches)
1338 do_merge = 0;
1339 }
1340
1341 if (old_branch_info.name) {
1342 stash_label_base = old_branch_info.name;
1343 } else if (old_branch_info.commit) {
1344 strbuf_add_unique_abbrev(&old_commit_shortname,
1345 &old_branch_info.commit->object.oid,
1346 DEFAULT_ABBREV);
1347 stash_label_base = old_commit_shortname.buf;
1348 }
1349
1350 if (do_merge) {
1351 ret = merge_working_tree(opts, &old_branch_info, new_branch_info,
1352 opts->merge, &writeout_error);
1353 if (ret == MERGE_WORKING_TREE_UNPACK_FAILED && opts->merge) {
1354 strbuf_addf(&autostash_msg,
1355 "autostash while switching to '%s'",
1356 new_branch_info->name);
1357 create_autostash_ref(the_repository,
1358 "CHECKOUT_AUTOSTASH_HEAD",
1359 autostash_msg.buf, true);
1360 created_autostash = 1;
1361 ret = merge_working_tree(opts, &old_branch_info, new_branch_info,
1362 false, &writeout_error);
1363 }
1364 if (created_autostash) {
1365 if (opts->conflict_style >= 0) {
1366 struct strbuf cfg = STRBUF_INIT;
1367 strbuf_addf(&cfg, "merge.conflictStyle=%s",
1368 conflict_style_name(opts->conflict_style));
1369 git_config_push_parameter(cfg.buf);
1370 strbuf_release(&cfg);
1371 }
1372 apply_autostash_ref(the_repository,
1373 "CHECKOUT_AUTOSTASH_HEAD",
1374 new_branch_info->name,
1375 "local",
1376 stash_label_base,
1377 autostash_msg.buf,
1378 &autostash_conflicted);
1379 }
1380 if (ret) {
1381 branch_info_release(&old_branch_info);
1382 strbuf_release(&old_commit_shortname);
1383 strbuf_release(&autostash_msg);
1384 return ret < 0 ? 1 : ret;
1385 }
1386 }
1387
1388 if (!opts->quiet && !old_branch_info.path && old_branch_info.commit && new_branch_info->commit != old_branch_info.commit)
1389 orphaned_commit_warning(old_branch_info.commit, new_branch_info->commit);
1390
1391 if (autostash_conflicted && !opts->quiet)
1392 fputc('\n', stderr);
1393 update_refs_for_switch(opts, &old_branch_info, new_branch_info);
1394
1395 if (created_autostash) {
1396 discard_index(the_repository->index);
1397 if (repo_read_index(the_repository) < 0)
1398 die(_("index file corrupt"));
1399
1400 if (!opts->quiet && new_branch_info->commit) {
1401 printf(_("The following paths have local changes:\n"));
1402 show_local_changes(&new_branch_info->commit->object,
1403 &opts->diff_options);
1404 }
1405 }
1406
1407 ret = post_checkout_hook(old_branch_info.commit, new_branch_info->commit, 1);
1408 branch_info_release(&old_branch_info);
1409 strbuf_release(&old_commit_shortname);
1410 strbuf_release(&autostash_msg);
1411
1412 return ret || writeout_error;
1413 }
1414
1415 static int git_checkout_config(const char *var, const char *value,
1416 const struct config_context *ctx, void *cb)
1417 {
1418 struct checkout_opts *opts = cb;
1419
1420 if (!strcmp(var, "diff.ignoresubmodules")) {
1421 if (!value)
1422 return config_error_nonbool(var);
1423 handle_ignore_submodules_arg(&opts->diff_options, value);
1424 return 0;
1425 }
1426 if (!strcmp(var, "checkout.guess")) {
1427 opts->dwim_new_local_branch = git_config_bool(var, value);
1428 return 0;
1429 }
1430
1431 if (starts_with(var, "submodule."))
1432 return git_default_submodule_config(var, value, NULL);
1433
1434 return git_xmerge_config(var, value, ctx, NULL);
1435 }
1436
1437 static void setup_new_branch_info_and_source_tree(
1438 struct branch_info *new_branch_info,
1439 struct checkout_opts *opts,
1440 struct object_id *rev,
1441 const char *arg)
1442 {
1443 struct tree **source_tree = &opts->source_tree;
1444 struct object_id branch_rev;
1445
1446 /* treat '@' as a shortcut for 'HEAD' */
1447 new_branch_info->name = !strcmp(arg, "@") ? xstrdup("HEAD") :
1448 xstrdup(arg);
1449 setup_branch_path(new_branch_info);
1450
1451 if (!check_refname_format(new_branch_info->path, 0) &&
1452 !refs_read_ref(get_main_ref_store(the_repository), new_branch_info->path, &branch_rev))
1453 oidcpy(rev, &branch_rev);
1454 else
1455 /* not an existing branch */
1456 FREE_AND_NULL(new_branch_info->path);
1457
1458 new_branch_info->commit = lookup_commit_reference_gently(the_repository, rev, 1);
1459 if (!new_branch_info->commit) {
1460 /* not a commit */
1461 *source_tree = repo_parse_tree_indirect(the_repository, rev);
1462 if (!*source_tree)
1463 die(_("unable to read tree (%s)"), oid_to_hex(rev));
1464 } else {
1465 parse_commit_or_die(new_branch_info->commit);
1466 *source_tree = repo_get_commit_tree(the_repository,
1467 new_branch_info->commit);
1468 if (!*source_tree)
1469 die(_("unable to read tree (%s)"),
1470 oid_to_hex(&new_branch_info->commit->object.oid));
1471 }
1472 }
1473
1474
1475 enum checkout_command {
1476 CHECKOUT_CHECKOUT = 1,
1477 CHECKOUT_SWITCH = 2,
1478 CHECKOUT_RESTORE = 3,
1479 };
1480
1481 static char *parse_remote_branch(const char *arg,
1482 struct object_id *rev,
1483 int could_be_checkout_paths,
1484 enum checkout_command which_command)
1485 {
1486 int num_matches = 0;
1487 char *remote = unique_tracking_name(arg, rev, &num_matches);
1488
1489 if (remote && could_be_checkout_paths) {
1490 die(_("'%s' could be both a local file and a tracking branch.\n"
1491 "Please use -- (and optionally --no-guess) to disambiguate"),
1492 arg);
1493 }
1494
1495 if (!remote && num_matches > 1) {
1496 if (advice_enabled(ADVICE_CHECKOUT_AMBIGUOUS_REMOTE_BRANCH_NAME)) {
1497 const char *cmdname;
1498
1499 switch (which_command) {
1500 case CHECKOUT_CHECKOUT:
1501 cmdname = "checkout";
1502 break;
1503 case CHECKOUT_SWITCH:
1504 cmdname = "switch";
1505 break;
1506 default:
1507 BUG("command <%d> should not reach parse_remote_branch",
1508 which_command);
1509 break;
1510 }
1511
1512 advise(_("If you meant to check out a remote tracking branch on, e.g. 'origin',\n"
1513 "you can do so by fully qualifying the name with the --track option:\n"
1514 "\n"
1515 " git %s --track origin/<name>\n"
1516 "\n"
1517 "If you'd like to always have checkouts of an ambiguous <name> prefer\n"
1518 "one remote, e.g. the 'origin' remote, consider setting\n"
1519 "checkout.defaultRemote=origin in your config."),
1520 cmdname);
1521 }
1522
1523 die(_("'%s' matched multiple (%d) remote tracking branches"),
1524 arg, num_matches);
1525 }
1526
1527 return remote;
1528 }
1529
1530 static int parse_branchname_arg(int argc, const char **argv,
1531 int dwim_new_local_branch_ok,
1532 enum checkout_command which_command,
1533 struct branch_info *new_branch_info,
1534 struct checkout_opts *opts,
1535 struct object_id *rev)
1536 {
1537 const char **new_branch = &opts->new_branch;
1538 int argcount = 0;
1539 const char *arg;
1540 char *remote = NULL;
1541 int dash_dash_pos;
1542 int has_dash_dash = 0;
1543 int i;
1544
1545 /*
1546 * case 1: git checkout <ref> -- [<paths>]
1547 *
1548 * <ref> must be a valid tree, everything after the '--' must be
1549 * a path.
1550 *
1551 * case 2: git checkout -- [<paths>]
1552 *
1553 * everything after the '--' must be paths.
1554 *
1555 * case 3: git checkout <something> [--]
1556 *
1557 * (a) If <something> is a commit, that is to
1558 * switch to the branch or detach HEAD at it. As a special case,
1559 * if <something> is A...B (missing A or B means HEAD but you can
1560 * omit at most one side), and if there is a unique merge base
1561 * between A and B, A...B names that merge base.
1562 *
1563 * (b) If <something> is _not_ a commit, either "--" is present
1564 * or <something> is not a path, no -t or -b was given,
1565 * and there is a tracking branch whose name is <something>
1566 * in one and only one remote (or if the branch exists on the
1567 * remote named in checkout.defaultRemote), then this is a
1568 * short-hand to fork local <something> from that
1569 * remote-tracking branch.
1570 *
1571 * (c) Otherwise, if "--" is present, treat it like case (1).
1572 *
1573 * (d) Otherwise :
1574 * - if it's a reference, treat it like case (1)
1575 * - else if it's a path, treat it like case (2)
1576 * - else: fail.
1577 *
1578 * case 4: git checkout <something> <paths>
1579 *
1580 * The first argument must not be ambiguous.
1581 * - If it's *only* a reference, treat it like case (1).
1582 * - If it's only a path, treat it like case (2).
1583 * - else: fail.
1584 *
1585 */
1586 if (!argc)
1587 return 0;
1588
1589 if (!opts->accept_pathspec) {
1590 if (argc > 1)
1591 die(_("only one reference expected"));
1592 has_dash_dash = 1; /* helps disambiguate */
1593 }
1594
1595 arg = argv[0];
1596 dash_dash_pos = -1;
1597 for (i = 0; i < argc; i++) {
1598 if (opts->accept_pathspec && !strcmp(argv[i], "--")) {
1599 dash_dash_pos = i;
1600 break;
1601 }
1602 }
1603 if (dash_dash_pos == 0)
1604 return 1; /* case (2) */
1605 else if (dash_dash_pos == 1)
1606 has_dash_dash = 1; /* case (3) or (1) */
1607 else if (dash_dash_pos >= 2)
1608 die(_("only one reference expected, %d given."), dash_dash_pos);
1609 opts->count_checkout_paths = !opts->quiet && !has_dash_dash;
1610
1611 if (!strcmp(arg, "-"))
1612 arg = "@{-1}";
1613
1614 if (repo_get_oid_mb(the_repository, arg, rev)) {
1615 /*
1616 * Either case (3) or (4), with <something> not being
1617 * a commit, or an attempt to use case (1) with an
1618 * invalid ref.
1619 *
1620 * It's likely an error, but we need to find out if
1621 * we should auto-create the branch, case (3).(b).
1622 */
1623 int recover_with_dwim = dwim_new_local_branch_ok;
1624
1625 int could_be_checkout_paths = !has_dash_dash &&
1626 check_filename(opts->prefix, arg);
1627
1628 if (!has_dash_dash && !no_wildcard(arg))
1629 recover_with_dwim = 0;
1630
1631 /*
1632 * Accept "git checkout foo", "git checkout foo --"
1633 * and "git switch foo" as candidates for dwim.
1634 */
1635 if (!(argc == 1 && !has_dash_dash) &&
1636 !(argc == 2 && has_dash_dash) &&
1637 opts->accept_pathspec)
1638 recover_with_dwim = 0;
1639
1640 if (recover_with_dwim) {
1641 remote = parse_remote_branch(arg, rev,
1642 could_be_checkout_paths,
1643 which_command);
1644 if (remote) {
1645 *new_branch = arg;
1646 arg = remote;
1647 /* DWIMmed to create local branch, case (3).(b) */
1648 } else {
1649 recover_with_dwim = 0;
1650 }
1651 }
1652
1653 if (!recover_with_dwim) {
1654 if (has_dash_dash)
1655 die(_("invalid reference: %s"), arg);
1656 return argcount;
1657 }
1658 }
1659
1660 /* we can't end up being in (2) anymore, eat the argument */
1661 argcount++;
1662 argv++;
1663 argc--;
1664
1665 setup_new_branch_info_and_source_tree(new_branch_info, opts, rev, arg);
1666
1667 if (!opts->source_tree) /* case (1): want a tree */
1668 die(_("reference is not a tree: %s"), arg);
1669
1670 if (!has_dash_dash) { /* case (3).(d) -> (1) */
1671 /*
1672 * Do not complain the most common case
1673 * git checkout branch
1674 * even if there happen to be a file called 'branch';
1675 * it would be extremely annoying.
1676 */
1677 if (argc)
1678 verify_non_filename(the_repository, opts->prefix, arg);
1679 } else if (opts->accept_pathspec) {
1680 argcount++;
1681 argv++;
1682 argc--;
1683 }
1684
1685 free(remote);
1686 return argcount;
1687 }
1688
1689 static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
1690 {
1691 int status;
1692 struct strbuf branch_ref = STRBUF_INIT;
1693
1694 trace2_cmd_mode("unborn");
1695
1696 if (!opts->new_branch)
1697 die(_("You are on a branch yet to be born"));
1698 strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
1699 status = refs_update_symref(get_main_ref_store(the_repository),
1700 "HEAD", branch_ref.buf, "checkout -b");
1701 strbuf_release(&branch_ref);
1702 if (!opts->quiet)
1703 fprintf(stderr, _("Switched to a new branch '%s'\n"),
1704 opts->new_branch);
1705 return status;
1706 }
1707
1708 static void die_expecting_a_branch(const struct branch_info *branch_info)
1709 {
1710 struct object_id oid;
1711 char *to_free;
1712 int code;
1713
1714 if (repo_dwim_ref(the_repository, branch_info->name,
1715 strlen(branch_info->name), &oid, &to_free, 0) == 1) {
1716 const char *ref = to_free;
1717
1718 if (skip_prefix(ref, "refs/tags/", &ref))
1719 code = die_message(_("a branch is expected, got tag '%s'"), ref);
1720 else if (skip_prefix(ref, "refs/remotes/", &ref))
1721 code = die_message(_("a branch is expected, got remote branch '%s'"), ref);
1722 else
1723 code = die_message(_("a branch is expected, got '%s'"), ref);
1724 }
1725 else if (branch_info->commit)
1726 code = die_message(_("a branch is expected, got commit '%s'"), branch_info->name);
1727 else
1728 /*
1729 * This case should never happen because we already die() on
1730 * non-commit, but just in case.
1731 */
1732 code = die_message(_("a branch is expected, got '%s'"), branch_info->name);
1733
1734 if (advice_enabled(ADVICE_SUGGEST_DETACHING_HEAD))
1735 advise(_("If you want to detach HEAD at the commit, try again with the --detach option."));
1736
1737 exit(code);
1738 }
1739
1740 static void die_if_some_operation_in_progress(void)
1741 {
1742 struct wt_status_state state;
1743
1744 memset(&state, 0, sizeof(state));
1745 wt_status_get_state(the_repository, &state, 0);
1746
1747 if (state.merge_in_progress)
1748 die(_("cannot switch branch while merging\n"
1749 "Consider \"git merge --quit\" "
1750 "or \"git worktree add\"."));
1751 if (state.am_in_progress)
1752 die(_("cannot switch branch in the middle of an am session\n"
1753 "Consider \"git am --quit\" "
1754 "or \"git worktree add\"."));
1755 if (state.rebase_interactive_in_progress || state.rebase_in_progress)
1756 die(_("cannot switch branch while rebasing\n"
1757 "Consider \"git rebase --quit\" "
1758 "or \"git worktree add\"."));
1759 if (state.cherry_pick_in_progress)
1760 die(_("cannot switch branch while cherry-picking\n"
1761 "Consider \"git cherry-pick --quit\" "
1762 "or \"git worktree add\"."));
1763 if (state.revert_in_progress)
1764 die(_("cannot switch branch while reverting\n"
1765 "Consider \"git revert --quit\" "
1766 "or \"git worktree add\"."));
1767 if (state.bisect_in_progress)
1768 warning(_("you are switching branch while bisecting"));
1769
1770 wt_status_state_free_buffers(&state);
1771 }
1772
1773 /*
1774 * die if attempting to checkout an existing branch that is in use
1775 * in another worktree, unless ignore-other-wortrees option is given.
1776 * The check is bypassed when the branch is already the current one,
1777 * as it will not make things any worse.
1778 */
1779 static void die_if_switching_to_a_branch_in_use(struct checkout_opts *opts,
1780 const char *full_ref)
1781 {
1782 int flags;
1783 char *head_ref;
1784
1785 if (opts->ignore_other_worktrees)
1786 return;
1787 head_ref = refs_resolve_refdup(get_main_ref_store(the_repository),
1788 "HEAD", 0, NULL, &flags);
1789 if (head_ref && (!(flags & REF_ISSYMREF) || strcmp(head_ref, full_ref)))
1790 die_if_checked_out(full_ref, 1);
1791 free(head_ref);
1792 }
1793
1794 static int checkout_branch(struct checkout_opts *opts,
1795 struct branch_info *new_branch_info)
1796 {
1797 struct repo_config_values *cfg = repo_config_values(the_repository);
1798 int noop_switch = (!new_branch_info->name &&
1799 !opts->new_branch &&
1800 !opts->force_detach);
1801
1802 if (opts->pathspec.nr)
1803 die(_("paths cannot be used with switching branches"));
1804
1805 if (opts->patch_mode)
1806 die(_("'%s' cannot be used with switching branches"),
1807 "--patch");
1808
1809 if (opts->overlay_mode != -1)
1810 die(_("'%s' cannot be used with switching branches"),
1811 "--[no]-overlay");
1812
1813 if (opts->writeout_stage) {
1814 const char *msg;
1815 if (noop_switch)
1816 msg = _("'%s' needs the paths to check out");
1817 else
1818 msg = _("'%s' cannot be used with switching branches");
1819 die(msg, "--ours/--theirs");
1820 }
1821
1822 if (opts->force && opts->merge)
1823 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1824
1825 if (opts->discard_changes && opts->merge)
1826 die(_("'%s' cannot be used with '%s'"), "--discard-changes", "--merge");
1827
1828 if (opts->force_detach && opts->new_branch)
1829 die(_("'%s' cannot be used with '%s'"),
1830 "--detach", "-b/-B/--orphan");
1831
1832 if (opts->new_orphan_branch) {
1833 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1834 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1835 if (opts->orphan_from_empty_tree && new_branch_info->name)
1836 die(_("'%s' cannot take <start-point>"), "--orphan");
1837 } else if (opts->force_detach) {
1838 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1839 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1840 } else if (opts->track == BRANCH_TRACK_UNSPECIFIED)
1841 opts->track = cfg->branch_track;
1842
1843 if (new_branch_info->name && !new_branch_info->commit)
1844 die(_("Cannot switch branch to a non-commit '%s'"),
1845 new_branch_info->name);
1846
1847 if (noop_switch &&
1848 !opts->switch_branch_doing_nothing_is_ok)
1849 die(_("missing branch or commit argument"));
1850
1851 if (!opts->implicit_detach &&
1852 !opts->force_detach &&
1853 !opts->new_branch &&
1854 !opts->new_branch_force &&
1855 new_branch_info->name &&
1856 !new_branch_info->path)
1857 die_expecting_a_branch(new_branch_info);
1858
1859 if (!opts->can_switch_when_in_progress)
1860 die_if_some_operation_in_progress();
1861
1862 /* "git checkout <branch>" */
1863 if (new_branch_info->path && !opts->force_detach && !opts->new_branch)
1864 die_if_switching_to_a_branch_in_use(opts, new_branch_info->path);
1865
1866 /* "git checkout -B <branch>" */
1867 if (opts->new_branch_force) {
1868 char *full_ref = xstrfmt("refs/heads/%s", opts->new_branch);
1869 die_if_switching_to_a_branch_in_use(opts, full_ref);
1870 free(full_ref);
1871 }
1872
1873 if (!new_branch_info->commit && opts->new_branch) {
1874 struct object_id rev;
1875 int flag;
1876
1877 if (!refs_read_ref_full(get_main_ref_store(the_repository), "HEAD", 0, &rev, &flag) &&
1878 (flag & REF_ISSYMREF) && is_null_oid(&rev))
1879 return switch_unborn_to_new_branch(opts);
1880 }
1881 return switch_branches(opts, new_branch_info);
1882 }
1883
1884 static int parse_opt_conflict(const struct option *o, const char *arg, int unset)
1885 {
1886 struct checkout_opts *opts = o->value;
1887
1888 if (unset) {
1889 opts->conflict_style = -1;
1890 return 0;
1891 }
1892 opts->conflict_style = parse_conflict_style_name(arg);
1893 if (opts->conflict_style < 0)
1894 return error(_("unknown conflict style '%s'"), arg);
1895 /* --conflict overrides a previous --no-merge */
1896 if (!opts->merge)
1897 opts->merge = -1;
1898
1899 return 0;
1900 }
1901
1902 static struct option *add_common_options(struct checkout_opts *opts,
1903 struct option *prevopts)
1904 {
1905 struct option options[] = {
1906 OPT__QUIET(&opts->quiet, N_("suppress progress reporting")),
1907 OPT_CALLBACK_F(0, "recurse-submodules", NULL,
1908 "checkout", "control recursive updating of submodules",
1909 PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater),
1910 OPT_BOOL(0, "progress", &opts->show_progress, N_("force progress reporting")),
1911 OPT_BOOL('m', "merge", &opts->merge, N_("perform a 3-way merge with the new branch")),
1912 OPT_CALLBACK(0, "conflict", opts, N_("style"),
1913 N_("conflict style (merge, diff3, or zdiff3)"),
1914 parse_opt_conflict),
1915 OPT_END()
1916 };
1917 struct option *newopts = parse_options_concat(prevopts, options);
1918 free(prevopts);
1919 return newopts;
1920 }
1921
1922 static struct option *add_common_switch_branch_options(
1923 struct checkout_opts *opts, struct option *prevopts)
1924 {
1925 struct option options[] = {
1926 OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
1927 OPT_CALLBACK_F('t', "track", opts, "(direct|inherit|fetch)[,...]",
1928 N_("set branch tracking configuration"),
1929 PARSE_OPT_OPTARG,
1930 parse_opt_checkout_track),
1931 OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
1932 PARSE_OPT_NOCOMPLETE),
1933 OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unborn branch")),
1934 OPT_BOOL_F(0, "overwrite-ignore", &opts->overwrite_ignore,
1935 N_("update ignored files (default)"),
1936 PARSE_OPT_NOCOMPLETE),
1937 OPT_BOOL(0, "ignore-other-worktrees", &opts->ignore_other_worktrees,
1938 N_("do not check if another worktree is using this branch")),
1939 OPT_END()
1940 };
1941 struct option *newopts = parse_options_concat(prevopts, options);
1942 free(prevopts);
1943 return newopts;
1944 }
1945
1946 static struct option *add_checkout_path_options(struct checkout_opts *opts,
1947 struct option *prevopts)
1948 {
1949 struct option options[] = {
1950 OPT_SET_INT_F('2', "ours", &opts->writeout_stage,
1951 N_("checkout our version for unmerged files"),
1952 2, PARSE_OPT_NONEG),
1953 OPT_SET_INT_F('3', "theirs", &opts->writeout_stage,
1954 N_("checkout their version for unmerged files"),
1955 3, PARSE_OPT_NONEG),
1956 OPT_BOOL('p', "patch", &opts->patch_mode, N_("select hunks interactively")),
1957 OPT_DIFF_UNIFIED(&opts->patch_context),
1958 OPT_DIFF_INTERHUNK_CONTEXT(&opts->patch_interhunk_context),
1959 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts->ignore_skipworktree,
1960 N_("do not limit pathspecs to sparse entries only")),
1961 OPT_PATHSPEC_FROM_FILE(&opts->pathspec_from_file),
1962 OPT_PATHSPEC_FILE_NUL(&opts->pathspec_file_nul),
1963 OPT_END()
1964 };
1965 struct option *newopts = parse_options_concat(prevopts, options);
1966 free(prevopts);
1967 return newopts;
1968 }
1969
1970 /* create-branch option (either b or c) */
1971 static char cb_option = 'b';
1972
1973 static int checkout_main(int argc, const char **argv, const char *prefix,
1974 struct checkout_opts *opts, struct option *options,
1975 enum checkout_command which_command)
1976 {
1977 int parseopt_flags = 0;
1978 struct branch_info new_branch_info = { 0 };
1979 int ret;
1980
1981 static const char * const checkout_usage[] = {
1982 N_("git checkout [<options>] <branch>"),
1983 N_("git checkout [<options>] [<branch>] -- <file>..."),
1984 NULL,
1985 };
1986
1987 static const char * const switch_branch_usage[] = {
1988 N_("git switch [<options>] [<branch>]"),
1989 NULL,
1990 };
1991
1992 static const char * const restore_usage[] = {
1993 N_("git restore [<options>] [--source=<branch>] <file>..."),
1994 NULL,
1995 };
1996
1997 const char * const *usagestr;
1998
1999 switch (which_command) {
2000 case CHECKOUT_CHECKOUT:
2001 usagestr = checkout_usage;
2002 break;
2003 case CHECKOUT_SWITCH:
2004 usagestr = switch_branch_usage;
2005 break;
2006 case CHECKOUT_RESTORE:
2007 usagestr = restore_usage;
2008 break;
2009 default:
2010 BUG("no such checkout variant %d", which_command);
2011 }
2012
2013 opts->overwrite_ignore = 1;
2014 opts->prefix = prefix;
2015 opts->show_progress = -1;
2016
2017 repo_config(the_repository, git_checkout_config, opts);
2018 if (the_repository->gitdir) {
2019 prepare_repo_settings(the_repository);
2020 the_repository->settings.command_requires_full_index = 0;
2021 }
2022
2023 opts->track = BRANCH_TRACK_UNSPECIFIED;
2024
2025 if (!opts->accept_pathspec && !opts->accept_ref)
2026 BUG("make up your mind, you need to take _something_");
2027 if (opts->accept_pathspec && opts->accept_ref)
2028 parseopt_flags = PARSE_OPT_KEEP_DASHDASH;
2029
2030 argc = parse_options(argc, argv, prefix, options,
2031 usagestr, parseopt_flags);
2032
2033 if (opts->patch_context < -1)
2034 die(_("'%s' cannot be negative"), "--unified");
2035 if (opts->patch_interhunk_context < -1)
2036 die(_("'%s' cannot be negative"), "--inter-hunk-context");
2037
2038 if (!opts->patch_mode) {
2039 if (opts->patch_context != -1)
2040 die(_("the option '%s' requires '%s'"), "--unified", "--patch");
2041 if (opts->patch_interhunk_context != -1)
2042 die(_("the option '%s' requires '%s'"), "--inter-hunk-context", "--patch");
2043 if (!opts->auto_advance)
2044 die(_("the option '%s' requires '%s'"), "--no-auto-advance", "--patch");
2045 }
2046
2047 if (opts->show_progress < 0) {
2048 if (opts->quiet)
2049 opts->show_progress = 0;
2050 else
2051 opts->show_progress = isatty(2);
2052 }
2053
2054 /* --conflicts implies --merge */
2055 if (opts->merge == -1)
2056 opts->merge = opts->conflict_style >= 0;
2057
2058 if (opts->force) {
2059 opts->discard_changes = 1;
2060 opts->ignore_unmerged_opt = "--force";
2061 opts->ignore_unmerged = 1;
2062 }
2063
2064 if ((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) > 1)
2065 die(_("options '-%c', '-%c', and '%s' cannot be used together"),
2066 cb_option, toupper(cb_option), "--orphan");
2067
2068 if (opts->overlay_mode == 1 && opts->patch_mode)
2069 die(_("options '%s' and '%s' cannot be used together"), "-p", "--overlay");
2070
2071 if (opts->checkout_index >= 0 || opts->checkout_worktree >= 0) {
2072 if (opts->checkout_index < 0)
2073 opts->checkout_index = 0;
2074 if (opts->checkout_worktree < 0)
2075 opts->checkout_worktree = 0;
2076 } else {
2077 if (opts->checkout_index < 0)
2078 opts->checkout_index = -opts->checkout_index - 1;
2079 if (opts->checkout_worktree < 0)
2080 opts->checkout_worktree = -opts->checkout_worktree - 1;
2081 }
2082 if (opts->checkout_index < 0 || opts->checkout_worktree < 0)
2083 BUG("these flags should be non-negative by now");
2084 /*
2085 * convenient shortcut: "git restore --staged [--worktree]" equals
2086 * "git restore --staged [--worktree] --source HEAD"
2087 */
2088 if (!opts->from_treeish && opts->checkout_index)
2089 opts->from_treeish = "HEAD";
2090
2091 /*
2092 * From here on, new_branch will contain the branch to be checked out,
2093 * and new_branch_force and new_orphan_branch will tell us which one of
2094 * -b/-B/-c/-C/--orphan is being used.
2095 */
2096 if (opts->new_branch_force)
2097 opts->new_branch = opts->new_branch_force;
2098
2099 if (opts->new_orphan_branch)
2100 opts->new_branch = opts->new_orphan_branch;
2101
2102 /* --track without -c/-C/-b/-B/--orphan should DWIM */
2103 if (opts->track != BRANCH_TRACK_UNSPECIFIED && !opts->new_branch) {
2104 const char *argv0 = argv[0];
2105 if (!argc || !strcmp(argv0, "--"))
2106 die(_("--track needs a branch name"));
2107 skip_prefix(argv0, "refs/", &argv0);
2108 skip_prefix(argv0, "remotes/", &argv0);
2109 argv0 = strchr(argv0, '/');
2110 if (!argv0 || !argv0[1])
2111 die(_("missing branch name; try -%c"), cb_option);
2112 opts->new_branch = argv0 + 1;
2113 }
2114
2115 /*
2116 * Extract branch name from command line arguments, so
2117 * all that is left is pathspecs.
2118 *
2119 * Handle
2120 *
2121 * 1) git checkout <tree> -- [<paths>]
2122 * 2) git checkout -- [<paths>]
2123 * 3) git checkout <something> [<paths>]
2124 *
2125 * including "last branch" syntax and DWIM-ery for names of
2126 * remote branches, erroring out for invalid or ambiguous cases.
2127 */
2128 if (argc && opts->accept_ref) {
2129 struct object_id rev;
2130 int dwim_ok =
2131 !opts->patch_mode &&
2132 opts->dwim_new_local_branch &&
2133 opts->track == BRANCH_TRACK_UNSPECIFIED &&
2134 !opts->new_branch;
2135 int n;
2136
2137 if (opts->fetch)
2138 fetch_remote_for_start_point(argv[0], opts->quiet);
2139
2140 n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
2141 &new_branch_info, opts, &rev);
2142 argv += n;
2143 argc -= n;
2144 } else if (!opts->accept_ref && opts->from_treeish) {
2145 struct object_id rev;
2146
2147 if (repo_get_oid_mb(the_repository, opts->from_treeish, &rev))
2148 die(_("could not resolve '%s'"), opts->from_treeish);
2149
2150 setup_new_branch_info_and_source_tree(&new_branch_info,
2151 opts, &rev,
2152 opts->from_treeish);
2153
2154 if (!opts->source_tree)
2155 die(_("reference is not a tree: %s"), opts->from_treeish);
2156 }
2157
2158 if (argc) {
2159 parse_pathspec(&opts->pathspec, 0,
2160 opts->patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0,
2161 prefix, argv);
2162
2163 if (!opts->pathspec.nr)
2164 die(_("invalid path specification"));
2165
2166 /*
2167 * Try to give more helpful suggestion.
2168 * new_branch && argc > 1 will be caught later.
2169 */
2170 if (opts->new_branch && argc == 1 && !new_branch_info.commit)
2171 die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
2172 argv[0], opts->new_branch);
2173
2174 if (opts->force_detach)
2175 die(_("git checkout: --detach does not take a path argument '%s'"),
2176 argv[0]);
2177 }
2178
2179 if (opts->pathspec_from_file) {
2180 if (opts->pathspec.nr)
2181 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
2182
2183 if (opts->force_detach)
2184 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--detach");
2185
2186 if (opts->patch_mode)
2187 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
2188
2189 parse_pathspec_file(&opts->pathspec, 0,
2190 0,
2191 prefix, opts->pathspec_from_file, opts->pathspec_file_nul);
2192 } else if (opts->pathspec_file_nul) {
2193 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
2194 }
2195
2196 opts->pathspec.recursive = 1;
2197
2198 if (opts->pathspec.nr) {
2199 if (1 < !!opts->writeout_stage + !!opts->force + !!opts->merge)
2200 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
2201 "checking out of the index."));
2202 } else {
2203 if (opts->accept_pathspec && !opts->empty_pathspec_ok &&
2204 !opts->patch_mode) /* patch mode is special */
2205 die(_("you must specify path(s) to restore"));
2206 }
2207
2208 if (opts->new_branch) {
2209 struct strbuf buf = STRBUF_INIT;
2210
2211 if (opts->new_branch_force)
2212 opts->branch_exists = validate_branchname(opts->new_branch, &buf);
2213 else
2214 opts->branch_exists =
2215 validate_new_branchname(opts->new_branch, &buf, 0);
2216 strbuf_release(&buf);
2217 }
2218
2219 if (opts->patch_mode || opts->pathspec.nr)
2220 ret = checkout_paths(opts, &new_branch_info);
2221 else
2222 ret = checkout_branch(opts, &new_branch_info);
2223
2224 branch_info_release(&new_branch_info);
2225 clear_pathspec(&opts->pathspec);
2226 free(opts->pathspec_from_file);
2227 free(options);
2228
2229 return ret;
2230 }
2231
2232 int cmd_checkout(int argc,
2233 const char **argv,
2234 const char *prefix,
2235 struct repository *repo UNUSED)
2236 {
2237 struct checkout_opts opts = CHECKOUT_OPTS_INIT;
2238 struct option *options;
2239 struct option checkout_options[] = {
2240 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
2241 N_("create and checkout a new branch")),
2242 OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
2243 N_("create/reset and checkout a branch")),
2244 OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
2245 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
2246 N_("second guess 'git checkout <no-such-branch>' (default)")),
2247 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode (default)")),
2248 OPT_BOOL(0, "auto-advance", &opts.auto_advance,
2249 N_("auto advance to the next file when selecting hunks interactively")),
2250 OPT_END()
2251 };
2252
2253 opts.dwim_new_local_branch = 1;
2254 opts.switch_branch_doing_nothing_is_ok = 1;
2255 opts.only_merge_on_switching_branches = 0;
2256 opts.accept_ref = 1;
2257 opts.accept_pathspec = 1;
2258 opts.implicit_detach = 1;
2259 opts.can_switch_when_in_progress = 1;
2260 opts.orphan_from_empty_tree = 0;
2261 opts.empty_pathspec_ok = 1;
2262 opts.overlay_mode = -1;
2263 opts.checkout_index = -2; /* default on */
2264 opts.checkout_worktree = -2; /* default on */
2265
2266 if (argc == 3 && !strcmp(argv[1], "-b")) {
2267 /*
2268 * User ran 'git checkout -b <branch>' and expects
2269 * the same behavior as 'git switch -c <branch>'.
2270 */
2271 opts.switch_branch_doing_nothing_is_ok = 0;
2272 opts.only_merge_on_switching_branches = 1;
2273 }
2274
2275 options = parse_options_dup(checkout_options);
2276 options = add_common_options(&opts, options);
2277 options = add_common_switch_branch_options(&opts, options);
2278 options = add_checkout_path_options(&opts, options);
2279
2280 return checkout_main(argc, argv, prefix, &opts, options,
2281 CHECKOUT_CHECKOUT);
2282 }
2283
2284 int cmd_switch(int argc,
2285 const char **argv,
2286 const char *prefix,
2287 struct repository *repo UNUSED)
2288 {
2289 struct checkout_opts opts = CHECKOUT_OPTS_INIT;
2290 struct option *options = NULL;
2291 struct option switch_options[] = {
2292 OPT_STRING('c', "create", &opts.new_branch, N_("branch"),
2293 N_("create and switch to a new branch")),
2294 OPT_STRING('C', "force-create", &opts.new_branch_force, N_("branch"),
2295 N_("create/reset and switch to a branch")),
2296 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
2297 N_("second guess 'git switch <no-such-branch>'")),
2298 OPT_BOOL(0, "discard-changes", &opts.discard_changes,
2299 N_("throw away local modifications")),
2300 OPT_END()
2301 };
2302
2303 opts.dwim_new_local_branch = 1;
2304 opts.accept_ref = 1;
2305 opts.accept_pathspec = 0;
2306 opts.switch_branch_doing_nothing_is_ok = 0;
2307 opts.only_merge_on_switching_branches = 1;
2308 opts.implicit_detach = 0;
2309 opts.can_switch_when_in_progress = 0;
2310 opts.orphan_from_empty_tree = 1;
2311 opts.overlay_mode = -1;
2312
2313 options = parse_options_dup(switch_options);
2314 options = add_common_options(&opts, options);
2315 options = add_common_switch_branch_options(&opts, options);
2316
2317 cb_option = 'c';
2318
2319 return checkout_main(argc, argv, prefix, &opts, options,
2320 CHECKOUT_SWITCH);
2321 }
2322
2323 int cmd_restore(int argc,
2324 const char **argv,
2325 const char *prefix,
2326 struct repository *repo UNUSED)
2327 {
2328 struct checkout_opts opts = CHECKOUT_OPTS_INIT;
2329 struct option *options;
2330 struct option restore_options[] = {
2331 OPT_STRING('s', "source", &opts.from_treeish, "<tree-ish>",
2332 N_("which tree-ish to checkout from")),
2333 OPT_BOOL('S', "staged", &opts.checkout_index,
2334 N_("restore the index")),
2335 OPT_BOOL('W', "worktree", &opts.checkout_worktree,
2336 N_("restore the working tree (default)")),
2337 OPT_BOOL(0, "ignore-unmerged", &opts.ignore_unmerged,
2338 N_("ignore unmerged entries")),
2339 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode")),
2340 OPT_END()
2341 };
2342
2343 opts.accept_ref = 0;
2344 opts.accept_pathspec = 1;
2345 opts.empty_pathspec_ok = 0;
2346 opts.overlay_mode = 0;
2347 opts.checkout_index = -1; /* default off */
2348 opts.checkout_worktree = -2; /* default on */
2349 opts.ignore_unmerged_opt = "--ignore-unmerged";
2350
2351 options = parse_options_dup(restore_options);
2352 options = add_common_options(&opts, options);
2353 options = add_checkout_path_options(&opts, options);
2354
2355 return checkout_main(argc, argv, prefix, &opts, options,
2356 CHECKOUT_RESTORE);
2357 }