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