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