at commit a0189536

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