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