Skip to contentSkip to conversation

Add new command "switch"

PATCH Superseded Nguyễn Thái Ngọc Duy 11 participants 289 messages Jan 30, 2019 – Jul 4, 2019 Page 2 of 3

Subsystems (2)
lore
Share & tools
lore
#142 lore raw

Re: [PATCH v3 10/21] checkout: split part of it to new command 'switch'

In reply to Nguyễn Thái Ngọc Duy

A few other comments that I thought of while responding elsewhere in the thread that didn't make sense to include elsewhere...

Quoted 5 lines · Nguyễn Thái Ngọc Duy

"git checkout" doing too many things is a source of confusion for many users (and it even bites old timers sometimes). To remedy that, the command will be split into two new ones: switch and something-to-checkout-paths. The good old "git checkout" command is

s/something-to-checkout-paths/restore/ ?

Documentation/git-switch.txt line 86

Quoted 9 lines
+-g::
+--guess::
Documentation/git-switch.txt new file +7 -0
+       If `<branch>` is not found but there does exist a tracking
+       branch in exactly one remote (call it `<remote>`) with a
+       matching name, treat as equivalent to
++
+------------
+$ git switch -c <branch> --track <remote>/<branch>
+------------

I'm not sure if it'd be better or worse to simplify this to
git switch --track <remote>/<branch>
Thoughts?

Documentation/git-switch.txt line 98

Quoted 12 lines

++

Documentation/git-switch.txt new file +11 -0
+If the branch exists in multiple remotes and one of them is named by
+the `checkout.defaultRemote` configuration variable, we'll use that
+one for the purposes of disambiguation, even if the `<branch>` isn't
+unique across all remotes. Set it to e.g. `checkout.defaultRemote=origin`
+to always checkout remote branches from there if `<branch>` is
+ambiguous but exists on the 'origin' remote. See also
+`checkout.defaultRemote` in linkgit:git-config[1].
+
+-q::
+--quiet::
+       Quiet, suppress feedback messages.

--quiet and --progress should be adjacent in the man-page since they are touching upon the same concept. It'd be nice if we had a way to group similar items like this besides simply putting them together, but we can at least do that.

Documentation/git-switch.txt line 105

Quoted 7 lines
Documentation/git-switch.txt new file +7 -0
+
+-f::
+--force::
+       Proceed even if the index or the working tree differs from
+       HEAD. Both the index and working tree are restored to match
+       the switching target. This is used to throw away local
+       changes.

--force (or --discard-changes as mentioned elsewhere in this thread), -m/--merge, and --conflict are also similar options and should be adjacent in the man-page; they all reflect on how to handle switching when local changes affect the same paths that different between HEAD and the other branch.

Documentation/git-switch.txt line 112

Quoted 6 lines
+--progress::
+--no-progress::
Documentation/git-switch.txt new file +4 -0
+       Progress status is reported on the standard error stream
+       by default when it is attached to a terminal, unless `--quiet`
+       is specified. This flag enables progress reporting even if not
+       attached to a terminal, regardless of `--quiet`.

This again makes me curious what --quiet actually supresses; in the case of branch switching, are there any non-warning informational messages other than progress reports that are printed? If not, the extra sentence at the end of the description for --progress can (and probably should) be stripped.

Quoted 6 lines
Documentation/git-switch.txt new file +6 -0
+
+-t::
+--track::
+       When creating a new branch, set up "upstream" configuration.
+       `-c` is implied. See "--track" in linkgit:git-branch[1] for
+       details.

Documentation/git-switch.txt line 128

Quoted 10 lines
Documentation/git-switch.txt new file +10 -0
++
+If no `-c` option is given, the name of the new branch will be derived
+from the remote-tracking branch, by looking at the local part of the
+refspec configured for the corresponding remote, and then stripping
+the initial part up to the "*".  This would tell us to use "hack" as
+the local branch when branching off of "origin/hack" (or
+"remotes/origin/hack", or even "refs/remotes/origin/hack").  If the
+given name has no slash, or the above guessing results in an empty
+name, the guessing is aborted.  You can explicitly give a name with
+`-c` in such a case.

Slightly disappointed that we couldn't remove --track; it has always seemed a bit complicated. But I don't see how to do so, since people do want upstream branches to be tracked with their new branches.

Quoted 9 lines
Documentation/git-switch.txt new file +9 -0
+
+--no-track::
+       Do not set up "upstream" configuration, even if the
+       branch.autoSetupMerge configuration variable is true.
+
+-m::
+--merge::
+       If you have local modifications to one or more files that are
+       different between the current branch and the branch to which

Documentation/git-switch.txt line 147

Quoted 10 lines
Documentation/git-switch.txt new file +10 -0
+       you are switching, the command refuses to switch branches in
+       order to preserve your modifications in context.  However,
+       with this option, a three-way merge between the current
+       branch, your working tree contents, and the new branch is
+       done, and you will be on the new branch.
++
+When a merge conflict happens, the index entries for conflicting
+paths are left unmerged, and you need to resolve the conflicts
+and mark the resolved paths with `git add` (or `git rm` if the merge
+should result in deletion of the path).

Now that Phillip highlighted issues with -m and -f, it's hard not to wonder about other corner cases. For example, what if the user made some changes, staged them, then made more changes, then tried to 'git checkout -m <other branch>'? That's no longer a three-way merge, but four way. How does that work? Does it just rely on merge-recursive's (poorly defined) choice of when to bail out and when to permit such craziness?

Documentation/git-switch.txt line 159

Quoted 11 lines

+--conflict=<style>::

Documentation/git-switch.txt new file +10 -0
+       The same as --merge option above, but changes the way the
+       conflicting hunks are presented, overriding the
+       merge.conflictStyle configuration variable.  Possible values are
+       "merge" (default) and "diff3" (in addition to what is shown by
+       "merge" style, shows the original contents).
+
+--orphan <new-branch>::
+       Create a new 'orphan' branch, named `<new-branch>`, started from
+       `<start-point>` and switch to it. See explanation of the same
+       option in linkgit:git-checkout[1] for details.

Sigh...does this mean --orphan will remain broken? It has always driven me crazy that it leaves you with a fully populated rather than an empty index. It seemed broken to me before I figured out the special usecase, though it still seemed like the wrong default (an empty index wouldn't surprise due to the "orphan" name, but a full one does to those without the special usecase in mind). Oh well, that's a much smaller battle than the big picture of getting switch and restore in place, and I don't want to derail the bigger picture; anything using --orphan is a somewhat special case anyway.

Documentation/git-switch.txt line 212

Quoted 11 lines
Documentation/git-switch.txt new file +11 -0
+You can give the `-m` flag to the command, which would try a three-way
+merge:
+
+------------
+$ git switch -m mytopic
+Auto-merging frotz
+------------
+
+After this three-way merge, the local modifications are _not_
+registered in your index file, so `git diff` would show you what
+changes you made since the tip of the new branch.

...even if the local modifications were registered in the index file before? Is this why Phillip's "x" was missing and how it avoided doing a four-way merge? I guess it kinda makes sense, view from this angle, but I'm not so sure I like it. Hmm....

#143 lore raw

Re: [PATCH v3 10/21] checkout: split part of it to new command 'switch'

Hi Elijah

Quoted 20 lines · Elijah Newren

A few other comments that I thought of while responding elsewhere in the thread that didn't make sense to include elsewhere...

Quoted 5 lines · Nguyễn Thái Ngọc Duy
+-m::
+--merge::
Documentation/git-switch.txt new file +2 -0
+       If you have local modifications to one or more files that are
+       different between the current branch and the branch to which

Documentation/git-switch.txt line 147

Quoted 10 lines
Documentation/git-switch.txt new file +10 -0
+       you are switching, the command refuses to switch branches in
+       order to preserve your modifications in context.  However,
+       with this option, a three-way merge between the current
+       branch, your working tree contents, and the new branch is
+       done, and you will be on the new branch.
++
+When a merge conflict happens, the index entries for conflicting
+paths are left unmerged, and you need to resolve the conflicts
+and mark the resolved paths with `git add` (or `git rm` if the merge
+should result in deletion of the path).
Quoted 7 lines

Now that Phillip highlighted issues with -m and -f, it's hard not to wonder about other corner cases. For example, what if the user made some changes, staged them, then made more changes, then tried to 'git checkout -m <other branch>'? That's no longer a three-way merge, but four way. How does that work? Does it just rely on merge-recursive's (poorly defined) choice of when to bail out and when to permit such craziness?

If the two-way merge fails then it does 'git add -u' before calling merge_recursive(), then any merged paths are reset to the new HEAD (which throws away newly added files, it should keep anything that is not in HEAD or HEAD@{1}). So any staged changes are lost.

Quoted 8 lines

Documentation/git-switch.txt line 159

Quoted 4 lines

+--orphan <new-branch>::

Documentation/git-switch.txt new file +3 -0
+       Create a new 'orphan' branch, named `<new-branch>`, started from
+       `<start-point>` and switch to it. See explanation of the same
+       option in linkgit:git-checkout[1] for details.

Sigh...does this mean --orphan will remain broken? It has always driven me crazy that it leaves you with a fully populated rather than an empty index.

I've always thought that was weird.

Quoted 2 lines

It seemed broken to me before I figured out the
special usecase,

I haven't figured it out yet - what is it?

Best Wishes

Phillip

Quoted 24 lines

though it still seemed like the wrong default (an
empty index wouldn't surprise due to the "orphan" name, but a full one does to those without the special usecase in mind). Oh well, that's a much smaller battle than the big picture of getting switch and restore in place, and I don't want to derail the bigger picture; anything using --orphan is a somewhat special case anyway.

Documentation/git-switch.txt line 212

Quoted 11 lines
Documentation/git-switch.txt new file +11 -0
+You can give the `-m` flag to the command, which would try a three-way
+merge:
+
+------------
+$ git switch -m mytopic
+Auto-merging frotz
+------------
+
+After this three-way merge, the local modifications are _not_
+registered in your index file, so `git diff` would show you what
+changes you made since the tip of the new branch.

...even if the local modifications were registered in the index file before? Is this why Phillip's "x" was missing and how it avoided doing a four-way merge? I guess it kinda makes sense, view from this angle, but I'm not so sure I like it. Hmm....

#144 lore raw

Re: [PATCH v3 10/21] checkout: split part of it to new command 'switch'

Quoted 32 lines · Phillip Wood

Hi Elijah

Quoted 20 lines · Elijah Newren

A few other comments that I thought of while responding elsewhere in the thread that didn't make sense to include elsewhere...

Quoted 5 lines · Nguyễn Thái Ngọc Duy
+-m::
+--merge::
Documentation/git-switch.txt new file +2 -0
+       If you have local modifications to one or more files that are
+       different between the current branch and the branch to which

Documentation/git-switch.txt line 147

Quoted 10 lines
Documentation/git-switch.txt new file +10 -0
+       you are switching, the command refuses to switch branches in
+       order to preserve your modifications in context.  However,
+       with this option, a three-way merge between the current
+       branch, your working tree contents, and the new branch is
+       done, and you will be on the new branch.
++
+When a merge conflict happens, the index entries for conflicting
+paths are left unmerged, and you need to resolve the conflicts
+and mark the resolved paths with `git add` (or `git rm` if the merge
+should result in deletion of the path).
Quoted 7 lines

Now that Phillip highlighted issues with -m and -f, it's hard not to wonder about other corner cases. For example, what if the user made some changes, staged them, then made more changes, then tried to 'git checkout -m <other branch>'? That's no longer a three-way merge, but four way. How does that work? Does it just rely on merge-recursive's (poorly defined) choice of when to bail out and when to permit such craziness?

Quoted 4 lines

If the two-way merge fails then it does 'git add -u' before calling merge_recursive(), then any merged paths are reset to the new HEAD (which throws away newly added files, it should keep anything that is not in HEAD or HEAD@{1}). So any staged changes are lost.

Ah, so roughly
* git add -u
* uncommitted_tree=$(git write-tree)
* git reset --hard
* git checkout $other_branch
* git merge-recursive $old_branch -- $other_branch $uncommitted_tree
* git reset --mixed HEAD

This at least gives well defined behavior, even if somewhat suboptimal in relation to losing staged changes (especially when those staged changes were new files).

I wonder if it'd be nicer, after I get my don't-touch-the-working-tree merge rewrite done, to instead do something like:
* Write the beginning index to a tree; call it $tree_0
* Note whether any working tree files differ from the index, add
these all to a temporary index and write to to a tree; call it $tree_1.
* Do a three way in-memory merge of $old_branch with $other_branch
and $tree_0; call it $merged_tree if there are no conflicts
* If $tree_0 == $tree_1, checkout the new branch and update the
index and working tree to reflect the merge result.
* If $tree_0 != $tree_1 and there were any conflicts, abort telling
the user they need to either unstage or stage changes first (we don't want to confuse users with a merge of a merge).
* Switch to the new branch, and update the index to match $merged_tree
* Do a three way in-memory merge of $old_branch with $merged_tree
and $tree_1, writing the results (including any conflicts) to the working tree afterward.

Pros of this method:
* We don't lose newly staged files
* We don't lose user's carefully staged entries for existing files either
Cons of this method:
* It may abort with an error if the user has a mix of both staged
and unstaged changes (in particular, it will do so if the user's staged changes conflict with some difference in the new branch)

Thoughts?

Quoted 10 lines
Quoted 9 lines

Documentation/git-switch.txt line 159

Quoted 5 lines

+--orphan <new-branch>::

Documentation/git-switch.txt new file +3 -0
+       Create a new 'orphan' branch, named `<new-branch>`, started from
+       `<start-point>` and switch to it. See explanation of the same
+       option in linkgit:git-checkout[1] for details.

Sigh...does this mean --orphan will remain broken? It has always driven me crazy that it leaves you with a fully populated rather than an empty index.

Quoted 6 lines

I've always thought that was weird.

Quoted 2 lines

It seemed broken to me before I figured out the
special usecase,

I haven't figured it out yet - what is it?

It's a presumption that despite the fact that you want a new branch, and one with no history to boot, that for some reason you want all the previous branch's current contents. In particular, you can think of it as a way to squash all the history of an existing branch into a single commit in a new branch.

Knowing of this usecase doesn't make it bother me any less when I want to create a new unrelated empty branch; it seems like it took the esoteric usecase over the common one to me, but I'm biased. It makes me feel better than neither you nor Eric could understand this behavior of --orphan either.

#145 lore raw

Re: [PATCH v3 10/21] checkout: split part of it to new command 'switch'

Quoted 38 lines · Elijah Newren
Quoted 32 lines · Phillip Wood

Hi Elijah

Quoted 20 lines · Elijah Newren

A few other comments that I thought of while responding elsewhere in the thread that didn't make sense to include elsewhere...

Quoted 5 lines · Nguyễn Thái Ngọc Duy
+-m::
+--merge::
Documentation/git-switch.txt new file +2 -0
+       If you have local modifications to one or more files that are
+       different between the current branch and the branch to which

Documentation/git-switch.txt line 147

Quoted 10 lines
Documentation/git-switch.txt new file +10 -0
+       you are switching, the command refuses to switch branches in
+       order to preserve your modifications in context.  However,
+       with this option, a three-way merge between the current
+       branch, your working tree contents, and the new branch is
+       done, and you will be on the new branch.
++
+When a merge conflict happens, the index entries for conflicting
+paths are left unmerged, and you need to resolve the conflicts
+and mark the resolved paths with `git add` (or `git rm` if the merge
+should result in deletion of the path).
Quoted 7 lines

Now that Phillip highlighted issues with -m and -f, it's hard not to wonder about other corner cases. For example, what if the user made some changes, staged them, then made more changes, then tried to 'git checkout -m <other branch>'? That's no longer a three-way merge, but four way. How does that work? Does it just rely on merge-recursive's (poorly defined) choice of when to bail out and when to permit such craziness?

Quoted 4 lines

If the two-way merge fails then it does 'git add -u' before calling merge_recursive(), then any merged paths are reset to the new HEAD (which throws away newly added files, it should keep anything that is not in HEAD or HEAD@{1}). So any staged changes are lost.

Quoted 7 lines

Ah, so roughly
* git add -u
* uncommitted_tree=$(git write-tree)
* git reset --hard
* git checkout $other_branch
* git merge-recursive $old_branch -- $other_branch $uncommitted_tree
* git reset --mixed HEAD

Something like that (I think it skips the reset and checkout and does git merge-recursive $old_branch -- $uncommitted_tree $other_branch and then updating HEAD)

Quoted 13 lines

This at least gives well defined behavior, even if somewhat suboptimal in relation to losing staged changes (especially when those staged changes were new files).

I wonder if it'd be nicer, after I get my don't-touch-the-working-tree merge rewrite done, to instead do something like:
* Write the beginning index to a tree; call it $tree_0
* Note whether any working tree files differ from the index, add
these all to a temporary index and write to to a tree; call it $tree_1.
* Do a three way in-memory merge of $old_branch with $other_branch
and $tree_0; call it $merged_tree if there are no conflicts
* If $tree_0 == $tree_1, checkout the new branch and update the

Quoted 8 lines

index and working tree to reflect the merge result.
* If $tree_0 != $tree_1 and there were any conflicts, abort telling
the user they need to either unstage or stage changes first (we don't want to confuse users with a merge of a merge).
* Switch to the new branch, and update the index to match $merged_tree
* Do a three way in-memory merge of $old_branch with $merged_tree
and $tree_1, writing the results (including any conflicts) to the working tree afterward.

As much as it annoys me to have to clear conflicts from the index after a checkout or stash pop I'm wary of updating the working tree with conflicts without marking those paths as unmerged in the index. Marking them prevents the user from accidentally committing files with unresolved conflicts. It is also easier for the user to find the conflicts if they're marked as unmerged in the index, they can use diff --cc and recreate them if they need to start over with the resolution.

Quoted 8 lines

Pros of this method:
* We don't lose newly staged files
* We don't lose user's carefully staged entries for existing files either
Cons of this method:
* It may abort with an error if the user has a mix of both staged
and unstaged changes (in particular, it will do so if the user's staged changes conflict with some difference in the new branch)

I think it's a good way of preserving any unstaged changes, it is probably good that the user is warned ahead of time that their staged changes would be lost.

Quoted 25 lines

Thoughts?

Quoted 10 lines
Quoted 9 lines

Documentation/git-switch.txt line 159

Quoted 5 lines

+--orphan <new-branch>::

Documentation/git-switch.txt new file +3 -0
+       Create a new 'orphan' branch, named `<new-branch>`, started from
+       `<start-point>` and switch to it. See explanation of the same
+       option in linkgit:git-checkout[1] for details.

Sigh...does this mean --orphan will remain broken? It has always driven me crazy that it leaves you with a fully populated rather than an empty index.

Quoted 6 lines

I've always thought that was weird.

Quoted 2 lines

It seemed broken to me before I figured out the
special usecase,

I haven't figured it out yet - what is it?

It's a presumption that despite the fact that you want a new branch, and one with no history to boot, that for some reason you want all the previous branch's current contents. In particular, you can think of it as a way to squash all the history of an existing branch into a single commit in a new branch.

Quoted 5 lines

Knowing of this usecase doesn't make it bother me any less when I want to create a new unrelated empty branch; it seems like it took the esoteric usecase over the common one to me, but I'm biased. It makes me feel better than neither you nor Eric could understand this behavior of --orphan either.

Thanks for the explanation, I agree it seems like a more esoteric use case.

Best Wishes

Phillip

#146 lore raw

PATCH 1/1 checkout.txt: note about losing staged changes with --merge

If you have staged changes in path A and perform 'checkout --merge' (which could result in conflicts in a totally unrelated path B), changes in A will be gone. Which is unexpected. We are supposed to keep all changes, or kick and scream otherwise.

This is the result of how --merge is implemented, from the very first day in 1be0659efc (checkout: merge local modifications while switching branches., 2006-01-12):

1. a merge is done, unmerged entries are collected
2. a hard switch to a new branch is done, then unmerged entries added back

There is no trivial fix for this. Going with 3-way merge one file at a time loses rename detection. Going with 3-way merge by trees requires teaching the algorithm to pick up staged changes. And even if we detect staged changes with --merge and abort for safety, an option to continue --merge is very weird. Such an option would keep worktree changes, but drop staged changes.

Because the problem has been with us since the introduction of --merge and everybody has been pretty happy (except Phillip, who found this problem), I'll just take a note here to acknowledge it and wait for merge wizards to come in and work their magic. There may be a way forward [1].

[1] CABPp-BFoL_U=bzON4SEMaQSKU2TKwnOgNqjt5MUaOejTKGUJxw@mail.gmail.com

---
This is my "fix" for Phillip's second problem. I chose to reply here because this is where an actual fix was discussed. The test script to demonstate it is here

https://public-inbox.org/git/[email protected]/

 Documentation/git-checkout.txt | 2 ++
 builtin/checkout.c             | 9 +++++++++
 2 files changed, 11 insertions(+)
Documentation/git-checkout.txt +2 -0
index f179b43732..877e5f503a 100644
@@ -242,6 +242,8 @@ should result in deletion of the path).
 +
 When checking out paths from the index, this option lets you recreate
 the conflicted merge in the specified paths.
++
+When switching branches with `--merge`, staged changes may be lost.
 
 --conflict=<style>::
 	The same as --merge option above, but changes the way the
builtin/checkout.c +9 -0
index 0e6037b296..f95e7975f7 100644
@@ -726,6 +726,8 @@ static int merge_working_tree(const struct checkout_opts *opts,
 			struct tree *result;
 			struct tree *work;
 			struct merge_options o;
+			struct strbuf sb = STRBUF_INIT;
+
 			if (!opts->merge)
 				return 1;
 
@@ -736,6 +738,13 @@ static int merge_working_tree(const struct checkout_opts *opts,
 			if (!old_branch_info->commit)
 				return 1;
 
+			if (repo_index_has_changes(the_repository,
+						   get_commit_tree(old_branch_info->commit),
+						   &sb))
+				warning(_("staged changes in the following files may be lost: %s"),
+					sb.buf);
+			strbuf_release(&sb);
+
 			/* Do more real merge */
 
 			/*
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#147 lore raw

Re: [PATCH] checkout.txt: note about losing staged changes with --merge

Hi Duy

Quoted 26 lines · Nguyễn Thái Ngọc Duy

If you have staged changes in path A and perform 'checkout --merge' (which could result in conflicts in a totally unrelated path B), changes in A will be gone. Which is unexpected. We are supposed to keep all changes, or kick and scream otherwise.

This is the result of how --merge is implemented, from the very first day in 1be0659efc (checkout: merge local modifications while switching branches., 2006-01-12):

1. a merge is done, unmerged entries are collected
2. a hard switch to a new branch is done, then unmerged entries added back

There is no trivial fix for this. Going with 3-way merge one file at a time loses rename detection. Going with 3-way merge by trees requires teaching the algorithm to pick up staged changes. And even if we detect staged changes with --merge and abort for safety, an option to continue --merge is very weird. Such an option would keep worktree changes, but drop staged changes.

Because the problem has been with us since the introduction of --merge and everybody has been pretty happy (except Phillip, who found this problem), I'll just take a note here to acknowledge it and wait for merge wizards to come in and work their magic. There may be a way forward [1].

Quoted 3 lines

[1] CABPp-BFoL_U=bzON4SEMaQSKU2TKwnOgNqjt5MUaOejTKGUJxw@mail.gmail.com

I try to use [email protected] for git stuff as it shouldn't change in the future.

Quoted 39 lines

---
This is my "fix" for Phillip's second problem. I chose to reply here because this is where an actual fix was discussed. The test script to demonstate it is here

https://public-inbox.org/git/[email protected]/

  Documentation/git-checkout.txt | 2 ++
  builtin/checkout.c             | 9 +++++++++
  2 files changed, 11 insertions(+)
Documentation/git-checkout.txt +2 -0
index f179b43732..877e5f503a 100644
@@ -242,6 +242,8 @@ should result in deletion of the path).
  +
  When checking out paths from the index, this option lets you recreate
  the conflicted merge in the specified paths.
++
+When switching branches with `--merge`, staged changes may be lost.
 
  --conflict=<style>::
  	The same as --merge option above, but changes the way the
builtin/checkout.c +2 -0
index 0e6037b296..f95e7975f7 100644
@@ -726,6 +726,8 @@ static int merge_working_tree(const struct checkout_opts *opts,
  			struct tree *result;
  			struct tree *work;
  			struct merge_options o;
+			struct strbuf sb = STRBUF_INIT;
+
  			if (!opts->merge)
  				return 1;
 

builtin/checkout.c static int merge_working_tree(const struct checkout_opts *opts, · line 746

Quoted 9 lines
builtin/checkout.c +6 -0
@@ -736,6 +738,13 @@ static int merge_working_tree(const struct checkout_opts *opts,
  			if (!old_branch_info->commit)
  				return 1;
 
+			if (repo_index_has_changes(the_repository,
+						   get_commit_tree(old_branch_info->commit),
+						   &sb))
+				warning(_("staged changes in the following files may be lost: %s"),
+					sb.buf);
+			strbuf_release(&sb);

Thanks for doing this, I think having some sort of warning is a good idea, I wonder if this could be quite noisy though. I guess it depends on how many staged changes people have that don't match the new index. If we diff against the new tree and only print names that are in both lists does that give a definitive list of what will be lost? If it does then if there are a lot of files affected then it will still be noisy (using columns may help) but at least it will not contain false positives. It is more work though, maybe we should just say "staged changes may be lost" and leave it at that.

Best Wishes

Phillip

Quoted 5 lines
builtin/checkout.c +1 -0
+
  			/* Do more real merge */
 
  			/*
#148 lore raw

Re: [PATCH] checkout.txt: note about losing staged changes with --merge

In reply to Nguyễn Thái Ngọc Duy
Quoted 13 lines · Nguyễn Thái Ngọc Duy

If you have staged changes in path A and perform 'checkout --merge' (which could result in conflicts in a totally unrelated path B), changes in A will be gone. Which is unexpected. We are supposed to keep all changes, or kick and scream otherwise.

This is the result of how --merge is implemented, from the very first day in 1be0659efc (checkout: merge local modifications while switching branches., 2006-01-12):

1. a merge is done, unmerged entries are collected
2. a hard switch to a new branch is done, then unmerged entries added back

Quoted 6 lines

There is no trivial fix for this. Going with 3-way merge one file at a time loses rename detection. Going with 3-way merge by trees requires teaching the algorithm to pick up staged changes. And even if we detect staged changes with --merge and abort for safety, an option to continue --merge is very weird. Such an option would keep worktree changes, but drop staged changes.

I think "checkout -m <otherbranch>" with a dirty index should refuse to run; there is nothing to "continue" after such a failure, so I am not sure what you mean by "an option to continue" (iow, I do not see a need for such an option, and if that option makes the whole notion strange, we can just decide not to have it, can't we?).

author
#149 lore raw

Re: [PATCH] checkout.txt: note about losing staged changes with --merge

Quoted 23 lines · Junio C Hamano
Quoted 13 lines · Nguyễn Thái Ngọc Duy

If you have staged changes in path A and perform 'checkout --merge' (which could result in conflicts in a totally unrelated path B), changes in A will be gone. Which is unexpected. We are supposed to keep all changes, or kick and scream otherwise.

This is the result of how --merge is implemented, from the very first day in 1be0659efc (checkout: merge local modifications while switching branches., 2006-01-12):

1. a merge is done, unmerged entries are collected
2. a hard switch to a new branch is done, then unmerged entries added back

Quoted 6 lines

There is no trivial fix for this. Going with 3-way merge one file at a time loses rename detection. Going with 3-way merge by trees requires teaching the algorithm to pick up staged changes. And even if we detect staged changes with --merge and abort for safety, an option to continue --merge is very weird. Such an option would keep worktree changes, but drop staged changes.

Quoted 5 lines

I think "checkout -m <otherbranch>" with a dirty index should refuse to run; there is nothing to "continue" after such a failure, so I am not sure what you mean by "an option to continue" (iow, I do not see a need for such an option, and if that option makes the whole notion strange, we can just decide not to have it, can't we?).

We have --force to continue even when we have local changes, which will be overwritten. I was thinking a similar option which gives us permission to destroy staged changes.

Refusing to run fails the test suite though (I tried that even before this patch), in t7201.10, "switch to another branch while carrying a deletion", because of this line

git rm two

Signature · 1 line
Duy
#150 lore raw

Re: [PATCH] checkout.txt: note about losing staged changes with --merge

Quoted 9 lines · Duy Nguyen
Quoted 5 lines

I think "checkout -m <otherbranch>" with a dirty index should refuse to run; there is nothing to "continue" after such a failure, so I am not sure what you mean by "an option to continue" (iow, I do not see a need for such an option, and if that option makes the whole notion strange, we can just decide not to have it, can't we?).

We have --force to continue even when we have local changes, which will be overwritten. I was thinking a similar option which gives us permission to destroy staged changes.

Ah, then that is not "checkout --continue", but "checkout --force -m"? That sounds sensible, and should behave as if "checkout -f HEAD && checkout -m <otherbranch>" was done, with respect to local changes, I would think.

author
#151 lore raw

Re: [PATCH] checkout.txt: note about losing staged changes with --merge

Quoted 9 lines · Junio C Hamano
Quoted 6 lines · Duy Nguyen
Quoted 5 lines

I think "checkout -m <otherbranch>" with a dirty index should refuse to run; there is nothing to "continue" after such a failure, so I am not sure what you mean by "an option to continue" (iow, I do not see a need for such an option, and if that option makes the whole notion strange, we can just decide not to have it, can't we?).

Quoted 8 lines
Quoted 3 lines

We have --force to continue even when we have local changes, which will be overwritten. I was thinking a similar option which gives us permission to destroy staged changes.

Ah, then that is not "checkout --continue", but "checkout --force -m"? That sounds sensible, and should behave as if "checkout -f HEAD && checkout -m <otherbranch>" was done, with respect to local changes, I would think.

Kinda. But "--force --merge" makes no sense. --force discards all local changes by definition, which means you can't have conflicts and will not need --merge. I think this is the reason why we die() out when both are specified. So we need something like --discard-staged-changes-only...

Signature · 1 line
Duy
#152 lore raw

Re: [PATCH] checkout.txt: note about losing staged changes with --merge

Quoted 5 lines · Duy Nguyen

Kinda. But "--force --merge" makes no sense. --force discards all local changes by definition, which means you can't have conflicts and will not need --merge. I think this is the reason why we die() out when both are specified. So we need something like --discard-staged-changes-only...

At that point, I would have to say that we do not need anything. The use case is already covered with "git reset && git checkout -m", isn't it?

Thanks.

#153 lore raw

Re: [PATCH] checkout.txt: note about losing staged changes with --merge

Quoted 9 lines · Junio C Hamano
Quoted 5 lines · Duy Nguyen

Kinda. But "--force --merge" makes no sense. --force discards all local changes by definition, which means you can't have conflicts and will not need --merge. I think this is the reason why we die() out when both are specified. So we need something like --discard-staged-changes-only...

Quoted 3 lines

At that point, I would have to say that we do not need anything. The use case is already covered with "git reset && git checkout -m", isn't it?

I guess the problem is just that 'git checkout -m' has not refused to run with either a dirty index or a dirty working tree, and if both are dirty (making us require more of a four-way merge), then our three-way merge has to have some kind of casualty in the implementation for at least some case. The current casualty as highlighted by Philip is that newly staged files before the 'checkout -m' become untracked and any carefully staged pieces before that command are lost amongst the unstaged changes again even if there weren't any conflicts.

One solution is to just accept and document or warn about this shortcoming for now as Duy did in his patch. Another is to do as you mentioned earlier in this thread when you stated 'I think "checkout -m <otherbranch>" with a dirty index should refuse to run'. Duy linked to a third option that I outlined in his commit message, though it'd require a bit more capability from merge-recursive than we have today.

So, I think we do need something (eventually at least). Would you prefer we dropped this patch from Duy and instead made 'checkout -m' abort when the index is dirty?

author
#154 lore raw

Re: [PATCH] checkout.txt: note about losing staged changes with --merge

Quoted 3 lines · Elijah Newren

So, I think we do need something (eventually at least). Would you prefer we dropped this patch from Duy and instead made 'checkout -m' abort when the index is dirty?

I have no problem with this. Still scratching my head wondering if t7201-co.sh has a slightly incorrect setup, or aborting is actually wrong. You're probably a better person to understand that test case ;-)

Signature · 1 line
Duy
#155 lore raw

Re: [PATCH] checkout.txt: note about losing staged changes with --merge

Quoted 10 lines · Duy Nguyen
Quoted 3 lines · Elijah Newren

So, I think we do need something (eventually at least). Would you prefer we dropped this patch from Duy and instead made 'checkout -m' abort when the index is dirty?

I have no problem with this. Still scratching my head wondering if t7201-co.sh has a slightly incorrect setup, or aborting is actually wrong. You're probably a better person to understand that test case ;-)

It doesn't surprise me at all that some testcases would fail with this change; it's a change of behavior from the previous implementation. However, taking a look at that testcase, it looks like it's not a simple change to make it do something similar because there's at least one other bug that we need to fix first. I'll dig in...though I really want to get my directory-rename-detection-defaults-to-reporting-conflict series updated and sent out first. Since Junio seems to be okay with just taking your doc update for now, hopefully that's not a problem. :-)

#156 lore raw

Re: [PATCH] checkout.txt: note about losing staged changes with --merge

In reply to Elijah Newren
Quoted 10 lines · Elijah Newren
Quoted 9 lines · Junio C Hamano
Quoted 5 lines · Duy Nguyen

Kinda. But "--force --merge" makes no sense. --force discards all local changes by definition, which means you can't have conflicts and will not need --merge. I think this is the reason why we die() out when both are specified. So we need something like --discard-staged-changes-only...

Quoted 8 lines
Quoted 3 lines

At that point, I would have to say that we do not need anything. The use case is already covered with "git reset && git checkout -m", isn't it?

I guess the problem is just that 'git checkout -m' has not refused to run with either a dirty index or a dirty working tree, and if both are dirty (making us require more of a four-way merge), then our three-way merge has to ...

I didn't actually mean "nothing to do here" relative to the current code; instead, I meant "nothing more than just stop when the index has updates" (which is hard to read from the above quoted part, as "Kinda." is a response in a discussion started with my "checkout -m should probably refuse to do anything when the index is dirty").

Quoted 3 lines

So, I think we do need something (eventually at least). Would you prefer we dropped this patch from Duy and instead made 'checkout -m' abort when the index is dirty?

Let's go with the doc update first, as the patch has already written. I think in the longer term, just aborting when the index is dirty would be a vast improvement over the status quo + a doc update and is a good place to stop.

Thanks.

author
#157 lore raw

Re: [PATCH v3 10/21] checkout: split part of it to new command 'switch'

In reply to Elijah Newren
Quoted 10 lines · Elijah Newren

Documentation/git-switch.txt line 112

Quoted 6 lines
+--progress::
+--no-progress::
Documentation/git-switch.txt new file +4 -0
+       Progress status is reported on the standard error stream
+       by default when it is attached to a terminal, unless `--quiet`
+       is specified. This flag enables progress reporting even if not
+       attached to a terminal, regardless of `--quiet`.

This again makes me curious what --quiet actually supresses; in the case of branch switching, are there any non-warning informational messages other than progress reports that are printed?

One big thing git-checkout and git-switch will print when not --quiet is "git diff --name-status" to highlight local changes since we allow switching branches when the worktree is not clean. Should it be mentioned in --quiet description?

We could also occasionally print advice, branch tracking info, and one-liner summary like "Switched to (new) branch 'master'".

Signature · 1 line
Duy
#158 lore raw

Re: [PATCH v3 10/21] checkout: split part of it to new command 'switch'

Quoted 9 lines · Duy Nguyen
Quoted 7 lines · Elijah Newren
Quoted 6 lines
+--progress::
+--no-progress::
Documentation/git-switch.txt new file +4 -0
+       Progress status is reported on the standard error stream
+       by default when it is attached to a terminal, unless `--quiet`
+       is specified. This flag enables progress reporting even if not
+       attached to a terminal, regardless of `--quiet`.
Quoted 8 lines
Quoted 3 lines

This again makes me curious what --quiet actually supresses; in the case of branch switching, are there any non-warning informational messages other than progress reports that are printed?

One big thing git-checkout and git-switch will print when not --quiet is "git diff --name-status" to highlight local changes since we allow switching branches when the worktree is not clean. Should it be mentioned in --quiet description?

Nah, that all makes sense. It was more a curiosity (I tend to have a clean working tree most the time when switching branches, I guess; maybe I also filtered out messages I was used to seeing and couldn't remember seeing them) and also I had a small concern that perhaps this bit of documentation was relevant for one part of git-checkout and not the other, and thus shouldn't appear in both git-switch and git-restore.

Quoted 2 lines

We could also occasionally print advice, branch tracking info, and one-liner summary like "Switched to (new) branch 'master'".

Thanks for the explanations. This all makes sense. However, all these answers are specific to git-switch; perhaps the detailed explanation of --progress can be shorted for git-restore? Or does it too have reasons to print non-progress informational messages?

#159 lore raw

PATCH v3 11/21 switch: better names for -b and -B

In reply to Nguyễn Thái Ngọc Duy

The shortcut of these options do not make much sense when used with switch. And their descriptions are also tied to checkout. Move -b/-B to cmd_checkout() and new -c/-C with the same functionality in cmd_switch_branch()

---
 builtin/checkout.c | 32 +++++++++++++++++++++-----------
 1 file changed, 21 insertions(+), 11 deletions(-)
builtin/checkout.c +21 -11
index 1eff10dbef..4c3f0f6ac7 100644
@@ -1368,14 +1368,10 @@ static struct option *add_common_options(struct checkout_opts *opts,
 	return newopts;
 }
 
-static struct option *add_switch_branch_options(struct checkout_opts *opts,
-						struct option *prevopts)
+static struct option *add_common_switch_branch_options(
+	struct checkout_opts *opts, struct option *prevopts)
 {
 	struct option options[] = {
-		OPT_STRING('b', NULL, &opts->new_branch, N_("branch"),
-			   N_("create and checkout a new branch")),
-		OPT_STRING('B', NULL, &opts->new_branch_force, N_("branch"),
-			   N_("create/reset and checkout a branch")),
 		OPT_BOOL('l', NULL, &opts->new_branch_log, N_("create reflog for new branch")),
 		OPT_BOOL(0, "detach", &opts->force_detach, N_("detach HEAD at named commit")),
 		OPT_SET_INT('t', "track",  &opts->track, N_("set upstream info for new branch"),
@@ -1571,15 +1567,22 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
 int cmd_checkout(int argc, const char **argv, const char *prefix)
 {
 	struct checkout_opts opts;
-	struct option *options = NULL;
+	struct option *options;
+	struct option checkout_options[] = {
+		OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
+			   N_("create and checkout a new branch")),
+		OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
+			   N_("create/reset and checkout a branch")),
+		OPT_END()
+	};
 	int ret;
 
 	memset(&opts, 0, sizeof(opts));
 	opts.no_dwim_new_local_branch = 0;
 
-	options = parse_options_dup(options);
+	options = parse_options_dup(checkout_options);
 	options = add_common_options(&opts, options);
-	options = add_switch_branch_options(&opts, options);
+	options = add_common_switch_branch_options(&opts, options);
 	options = add_checkout_path_options(&opts, options);
 
 	ret = checkout_main(argc, argv, prefix, &opts,
@@ -1592,14 +1595,21 @@ int cmd_switch(int argc, const char **argv, const char *prefix)
 {
 	struct checkout_opts opts;
 	struct option *options = NULL;
+	struct option switch_options[] = {
+		OPT_STRING('c', "create", &opts.new_branch, N_("branch"),
+			   N_("create and switch to a new branch")),
+		OPT_STRING('C', "force-create", &opts.new_branch_force, N_("branch"),
+			   N_("create/reset and switch to a branch")),
+		OPT_END()
+	};
 	int ret;
 
 	memset(&opts, 0, sizeof(opts));
 	opts.no_dwim_new_local_branch = 0;
 
-	options = parse_options_dup(options);
+	options = parse_options_dup(switch_options);
 	options = add_common_options(&opts, options);
-	options = add_switch_branch_options(&opts, options);
+	options = add_common_switch_branch_options(&opts, options);
 
 	ret = checkout_main(argc, argv, prefix, &opts,
 			    options, switch_branch_usage);
Signature · 1 line
2.21.0.rc1.337.gdf7f8d0522
#160 lore raw

PATCH v3 12/21 switch: remove -l

In reply to Nguyễn Thái Ngọc Duy

This option is ancient. Nowadays reflog is enabled by default and automatically created for new branches. Keep it in git-checkout only.

---
 builtin/checkout.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
builtin/checkout.c +1 -1
index 4c3f0f6ac7..a731f983c4 100644
@@ -1372,7 +1372,6 @@ static struct option *add_common_switch_branch_options(
 	struct checkout_opts *opts, struct option *prevopts)
 {
 	struct option options[] = {
-		OPT_BOOL('l', NULL, &opts->new_branch_log, N_("create reflog for new branch")),
 		OPT_BOOL(0, "detach", &opts->force_detach, N_("detach HEAD at named commit")),
 		OPT_SET_INT('t', "track",  &opts->track, N_("set upstream info for new branch"),
 			BRANCH_TRACK_EXPLICIT),
@@ -1573,6 +1572,7 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 			   N_("create and checkout a new branch")),
 		OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
 			   N_("create/reset and checkout a branch")),
+		OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
 		OPT_END()
 	};
 	int ret;
Signature · 1 line
2.21.0.rc1.337.gdf7f8d0522
#161 lore raw

PATCH v3 13/21 switch: stop accepting pathspec

In reply to Nguyễn Thái Ngọc Duy

This command is about switching branch (or creating a new one) and should not accept pathspec. This helps simplify ambiguation handling. The other two ("git checkout" and "git restore") of course do accept pathspec as before.

---
 builtin/checkout.c | 20 +++++++++++++++-----
 1 file changed, 15 insertions(+), 5 deletions(-)
builtin/checkout.c +15 -5
index a731f983c4..1b1181b220 100644
@@ -53,6 +53,7 @@ struct checkout_opts {
 	int count_checkout_paths;
 	int overlay_mode;
 	int no_dwim_new_local_branch;
+	int accept_pathspec;
 
 	/*
 	 * If new checkout options are added, skip_merge_working_tree
@@ -1175,10 +1176,16 @@ static int parse_branchname_arg(int argc, const char **argv,
 	if (!argc)
 		return 0;
 
+	if (!opts->accept_pathspec) {
+		if (argc > 1)
+			die(_("only one reference expected"));
+		has_dash_dash = 1; /* helps disambiguate */
+	}
+
 	arg = argv[0];
 	dash_dash_pos = -1;
 	for (i = 0; i < argc; i++) {
-		if (!strcmp(argv[i], "--")) {
+		if (opts->accept_pathspec && !strcmp(argv[i], "--")) {
 			dash_dash_pos = i;
 			break;
 		}
@@ -1212,11 +1219,12 @@ static int parse_branchname_arg(int argc, const char **argv,
 			recover_with_dwim = 0;
 
 		/*
-		 * Accept "git checkout foo" and "git checkout foo --"
-		 * as candidates for dwim.
+		 * Accept "git checkout foo", "git checkout foo --"
+		 * and "git switch foo" as candidates for dwim.
 		 */
 		if (!(argc == 1 && !has_dash_dash) &&
-		    !(argc == 2 && has_dash_dash))
+		    !(argc == 2 && has_dash_dash) &&
+		    opts->accept_pathspec)
 			recover_with_dwim = 0;
 
 		if (recover_with_dwim) {
@@ -1261,7 +1269,7 @@ static int parse_branchname_arg(int argc, const char **argv,
 		 */
 		if (argc)
 			verify_non_filename(opts->prefix, arg);
-	} else {
+	} else if (opts->accept_pathspec) {
 		argcount++;
 		argv++;
 		argc--;
@@ -1579,6 +1587,7 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 
 	memset(&opts, 0, sizeof(opts));
 	opts.no_dwim_new_local_branch = 0;
+	opts.accept_pathspec = 1;
 
 	options = parse_options_dup(checkout_options);
 	options = add_common_options(&opts, options);
@@ -1606,6 +1615,7 @@ int cmd_switch(int argc, const char **argv, const char *prefix)
 
 	memset(&opts, 0, sizeof(opts));
 	opts.no_dwim_new_local_branch = 0;
+	opts.accept_pathspec = 0;
 
 	options = parse_options_dup(switch_options);
 	options = add_common_options(&opts, options);
Signature · 1 line
2.21.0.rc1.337.gdf7f8d0522
#162 lore raw

PATCH v3 14/21 switch: reject "do nothing" case

In reply to Nguyễn Thái Ngọc Duy

"git checkout" can be executed without any arguments. What it does is not exactly great: it switches from HEAD to HEAD and shows worktree modification as a side effect.

Make switch reject this case. Just use "git status" if you want that side effect. For switch, you have to either

- really switch a branch
- (explicitly) detach from the current branch
- create a new branch

---
 builtin/checkout.c | 9 +++++++++
 1 file changed, 9 insertions(+)
builtin/checkout.c +9 -0
index 1b1181b220..f9f7ee2936 100644
@@ -54,6 +54,7 @@ struct checkout_opts {
 	int overlay_mode;
 	int no_dwim_new_local_branch;
 	int accept_pathspec;
+	int switch_branch_doing_nothing_is_ok;
 
 	/*
 	 * If new checkout options are added, skip_merge_working_tree
@@ -1334,6 +1335,12 @@ static int checkout_branch(struct checkout_opts *opts,
 		die(_("Cannot switch branch to a non-commit '%s'"),
 		    new_branch_info->name);
 
+	if (!opts->switch_branch_doing_nothing_is_ok &&
+	    !new_branch_info->name &&
+	    !opts->new_branch &&
+	    !opts->force_detach)
+		die(_("missing branch or commit argument"));
+
 	if (new_branch_info->path && !opts->force_detach && !opts->new_branch &&
 	    !opts->ignore_other_worktrees) {
 		int flag;
@@ -1587,6 +1594,7 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 
 	memset(&opts, 0, sizeof(opts));
 	opts.no_dwim_new_local_branch = 0;
+	opts.switch_branch_doing_nothing_is_ok = 1;
 	opts.accept_pathspec = 1;
 
 	options = parse_options_dup(checkout_options);
@@ -1616,6 +1624,7 @@ int cmd_switch(int argc, const char **argv, const char *prefix)
 	memset(&opts, 0, sizeof(opts));
 	opts.no_dwim_new_local_branch = 0;
 	opts.accept_pathspec = 0;
+	opts.switch_branch_doing_nothing_is_ok = 0;
 
 	options = parse_options_dup(switch_options);
 	options = add_common_options(&opts, options);
Signature · 1 line
2.21.0.rc1.337.gdf7f8d0522
#163 lore raw

PATCH v3 15/21 switch: only allow explicit detached HEAD

In reply to Nguyễn Thái Ngọc Duy

"git checkout <commit>" will checkout the commit in question and detach HEAD from the current branch. It is naturally a right thing to do once you get git references. But detached HEAD is a scary concept to new users because we show a lot of warnings and stuff, and it could be hard to get out of (until you know better).

To keep switch a bit more friendly to new users, we only allow entering detached HEAD mode when --detach is given. "git switch" must take a branch (unless you create a new branch, then of course switch can take any commit-ish)

---
 builtin/checkout.c | 11 +++++++++++
 1 file changed, 11 insertions(+)
builtin/checkout.c +11 -0
index f9f7ee2936..2e150f0175 100644
@@ -45,6 +45,7 @@ struct checkout_opts {
 	int merge;
 	int force;
 	int force_detach;
+	int implicit_detach;
 	int writeout_stage;
 	int overwrite_ignore;
 	int ignore_skipworktree;
@@ -1341,6 +1342,14 @@ static int checkout_branch(struct checkout_opts *opts,
 	    !opts->force_detach)
 		die(_("missing branch or commit argument"));
 
+	if (!opts->implicit_detach &&
+	    !opts->force_detach &&
+	    !opts->new_branch &&
+	    !opts->new_branch_force &&
+	    new_branch_info->name &&
+	    !new_branch_info->path)
+		die(_("a branch is expected, got %s"), new_branch_info->name);
+
 	if (new_branch_info->path && !opts->force_detach && !opts->new_branch &&
 	    !opts->ignore_other_worktrees) {
 		int flag;
@@ -1596,6 +1605,7 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 	opts.no_dwim_new_local_branch = 0;
 	opts.switch_branch_doing_nothing_is_ok = 1;
 	opts.accept_pathspec = 1;
+	opts.implicit_detach = 1;
 
 	options = parse_options_dup(checkout_options);
 	options = add_common_options(&opts, options);
@@ -1625,6 +1635,7 @@ int cmd_switch(int argc, const char **argv, const char *prefix)
 	opts.no_dwim_new_local_branch = 0;
 	opts.accept_pathspec = 0;
 	opts.switch_branch_doing_nothing_is_ok = 0;
+	opts.implicit_detach = 0;
 
 	options = parse_options_dup(switch_options);
 	options = add_common_options(&opts, options);
Signature · 1 line
2.21.0.rc1.337.gdf7f8d0522
#164 lore raw

PATCH v3 16/21 switch: add short option for --detach

In reply to Nguyễn Thái Ngọc Duy

"git checkout" automatically detaches branches and --detach is not that useful (--no-detach is more likely). But for "switch", you may want to use it more often once you're used to detached HEAD. This of course adds -d to git-checkout but it does not harm (yet?) to do it.

---
 builtin/checkout.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
builtin/checkout.c +1 -1
index 2e150f0175..0866aeba83 100644
@@ -1396,7 +1396,7 @@ static struct option *add_common_switch_branch_options(
 	struct checkout_opts *opts, struct option *prevopts)
 {
 	struct option options[] = {
-		OPT_BOOL(0, "detach", &opts->force_detach, N_("detach HEAD at named commit")),
+		OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
 		OPT_SET_INT('t', "track",  &opts->track, N_("set upstream info for new branch"),
 			BRANCH_TRACK_EXPLICIT),
 		OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unparented branch")),
Signature · 1 line
2.21.0.rc1.337.gdf7f8d0522
#165 lore raw

PATCH v3 17/21 switch: no implicit dwim, use --guess to dwim

In reply to Nguyễn Thái Ngọc Duy

Similar to automatic detach, this behavior could be confusing because it can sometimes create a new branch without a user asking it to, especially when the user is still not aware about this feature.

In the future, perhaps we could have a config key to disable these safety nets and let 'switch' do automatic detach or dwim again. But that will be opt-in after the user knows what is what. For now give a short option if you want to use it often.

---
 Documentation/git-checkout.txt | 38 ++++++++++++++++++++--------------
 builtin/checkout.c             | 16 +++++++-------
 2 files changed, 31 insertions(+), 23 deletions(-)
Documentation/git-checkout.txt +23 -15
index ac355dc3f3..2b776c1269 100644
@@ -31,22 +31,13 @@ branch.
 	`<branch>`.
 +
 If `<branch>` is not found but there does exist a tracking branch in
-exactly one remote (call it `<remote>`) with a matching name, treat as
-equivalent to
+exactly one remote (call it `<remote>`) with a matching name and
+`--no-guess` is not specified, treat as equivalent to
 +
 ------------
 $ git checkout -b <branch> --track <remote>/<branch>
 ------------
 +
-If the branch exists in multiple remotes and one of them is named by
-the `checkout.defaultRemote` configuration variable, we'll use that
-one for the purposes of disambiguation, even if the `<branch>` isn't
-unique across all remotes. Set it to
-e.g. `checkout.defaultRemote=origin` to always checkout remote
-branches from there if `<branch>` is ambiguous but exists on the
-'origin' remote. See also `checkout.defaultRemote` in
-linkgit:git-config[1].
-+
 You could omit `<branch>`, in which case the command degenerates to
 "check out the current branch", which is a glorified no-op with
 rather expensive side-effects to show only the tracking information,
@@ -183,6 +174,27 @@ explicitly give a name with `-b` in such a case.
 	Do not set up "upstream" configuration, even if the
 	branch.autoSetupMerge configuration variable is true.
 
+--guess::
+--no-guess::
+	If `<branch>` is not found but there does exist a tracking
+	branch in exactly one remote (call it `<remote>`) with a
+	matching name, treat as equivalent to
++
+------------
+$ git checkout -b <branch> --track <remote>/<branch>
+------------
++
+If the branch exists in multiple remotes and one of them is named by
+the `checkout.defaultRemote` configuration variable, we'll use that
+one for the purposes of disambiguation, even if the `<branch>` isn't
+unique across all remotes. Set it to
+e.g. `checkout.defaultRemote=origin` to always checkout remote
+branches from there if `<branch>` is ambiguous but exists on the
+'origin' remote. See also `checkout.defaultRemote` in
+linkgit:git-config[1].
++
+Use `--no-guess` to disable this.
+
 -l::
 	Create the new branch's reflog; see linkgit:git-branch[1] for
 	details.
@@ -287,10 +299,6 @@ Note that this option uses the no overlay mode by default (see also
 	Just like linkgit:git-submodule[1], this will detach the
 	submodules HEAD.
 
---no-guess::
-	Do not attempt to create a branch if a remote tracking branch
-	of the same name exists.
-
 --overlay::
 --no-overlay::
 	In the default overlay mode, `git checkout` never
builtin/checkout.c +8 -8
index 0866aeba83..8a89df4f36 100644
@@ -53,7 +53,7 @@ struct checkout_opts {
 	int show_progress;
 	int count_checkout_paths;
 	int overlay_mode;
-	int no_dwim_new_local_branch;
+	int dwim_new_local_branch;
 	int accept_pathspec;
 	int switch_branch_doing_nothing_is_ok;
 
@@ -1403,8 +1403,6 @@ static struct option *add_common_switch_branch_options(
 		OPT_BOOL_F(0, "overwrite-ignore", &opts->overwrite_ignore,
 			   N_("update ignored files (default)"),
 			   PARSE_OPT_NOCOMPLETE),
-		OPT_BOOL(0, "no-guess", &opts->no_dwim_new_local_branch,
-			 N_("second guess 'git checkout <no-such-branch>'")),
 		OPT_BOOL(0, "ignore-other-worktrees", &opts->ignore_other_worktrees,
 			 N_("do not check if another worktree is holding the given ref")),
 		OPT_END()
@@ -1441,7 +1439,6 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
 {
 	struct branch_info new_branch_info;
 	int dwim_remotes_matched = 0;
-	int dwim_new_local_branch;
 
 	memset(&new_branch_info, 0, sizeof(new_branch_info));
 	opts->overwrite_ignore = 1;
@@ -1456,7 +1453,6 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
 	argc = parse_options(argc, argv, prefix, options, usagestr,
 			     PARSE_OPT_KEEP_DASHDASH);
 
-	dwim_new_local_branch = !opts->no_dwim_new_local_branch;
 	if (opts->show_progress < 0) {
 		if (opts->quiet)
 			opts->show_progress = 0;
@@ -1516,7 +1512,7 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
 		struct object_id rev;
 		int dwim_ok =
 			!opts->patch_mode &&
-			dwim_new_local_branch &&
+			opts->dwim_new_local_branch &&
 			opts->track == BRANCH_TRACK_UNSPECIFIED &&
 			!opts->new_branch;
 		int n = parse_branchname_arg(argc, argv, dwim_ok,
@@ -1597,12 +1593,14 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 		OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
 			   N_("create/reset and checkout a branch")),
 		OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
+		OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
+			 N_("second guess 'git checkout <no-such-branch>' (default)")),
 		OPT_END()
 	};
 	int ret;
 
 	memset(&opts, 0, sizeof(opts));
-	opts.no_dwim_new_local_branch = 0;
+	opts.dwim_new_local_branch = 1;
 	opts.switch_branch_doing_nothing_is_ok = 1;
 	opts.accept_pathspec = 1;
 	opts.implicit_detach = 1;
@@ -1627,12 +1625,14 @@ int cmd_switch(int argc, const char **argv, const char *prefix)
 			   N_("create and switch to a new branch")),
 		OPT_STRING('C', "force-create", &opts.new_branch_force, N_("branch"),
 			   N_("create/reset and switch to a branch")),
+		OPT_BOOL('g', "guess", &opts.dwim_new_local_branch,
+			 N_("second guess 'git switch <no-such-branch>'")),
 		OPT_END()
 	};
 	int ret;
 
 	memset(&opts, 0, sizeof(opts));
-	opts.no_dwim_new_local_branch = 0;
+	opts.dwim_new_local_branch = 0;
 	opts.accept_pathspec = 0;
 	opts.switch_branch_doing_nothing_is_ok = 0;
 	opts.implicit_detach = 0;
Signature · 1 line
2.21.0.rc1.337.gdf7f8d0522
#166 lore raw

Re: [PATCH v3 17/21] switch: no implicit dwim, use --guess to dwim

Quoted 8 lines · Nguyễn Thái Ngọc Duy

Similar to automatic detach, this behavior could be confusing because it can sometimes create a new branch without a user asking it to, especially when the user is still not aware about this feature.

In the future, perhaps we could have a config key to disable these safety nets and let 'switch' do automatic detach or dwim again. But that will be opt-in after the user knows what is what. For now give a short option if you want to use it often.

As I am late to the patch series (sorry!), has there been already any discussion on that? In my experience, people get confused with detached HEAD state quite often, whereas the automatic creation of a local branch is no problem. So if it is deemed to be too confusing to dwim in this case, could we add a hint suggesting the command? Something like:
"No suitable branch <foo> found, however there is a remote tracking branch <origin/foo> that you can siwtch and create with git switch --guess foo" (or maybe the one without guess)?

And while at it - what should happen, if:

- there is a tag named example
- no local branch example
- a branch at origin/example

... and we switch then? Right now it just gives "cannot find branch", should there be more information? Should it even create a branch example? With switch, switching a branch is unambiguous, even though there is a tag with that name. If I really want to --guess - should I be given more information?

Greetings,
Eckhard

#167 lore raw

Re: [PATCH v3 17/21] switch: no implicit dwim, use --guess to dwim

Quoted 10 lines · Eckhard Maaß
Quoted 8 lines · Nguyễn Thái Ngọc Duy

Similar to automatic detach, this behavior could be confusing because it can sometimes create a new branch without a user asking it to, especially when the user is still not aware about this feature.

In the future, perhaps we could have a config key to disable these safety nets and let 'switch' do automatic detach or dwim again. But that will be opt-in after the user knows what is what. For now give a short option if you want to use it often.

Quoted 4 lines

As I am late to the patch series (sorry!), has there been already any discussion on that? In my experience, people get confused with detached HEAD state quite often, whereas the automatic creation of a local branch is no problem.

This statement does a good job of articulating my (unspoken) response to this patch. Whereas a detached HEAD might be scary and confusing to newcomers, and difficult for them to recover from, automatic creation of a DWIM'd local branch doesn't seem so problematic (if at all).

With git-checkout, it's very easy to accidentally get into a detached HEAD state, so it makes some sense to protect newcomers, by default, from that accident in git-switch. However, auto-creation of a new local branch is not, for a couple reasons, nearly so weighty a matter. First, in many cases it may be less likely to happen since it requires presence of a corresponding remote tracking branch. Second, it's intuitively easy to recover from it: when git-switch reports that it created a new branch, though perhaps surprising, the user would naturally know to look for a command to "delete a branch".

And, unlike a detached HEAD, which newcomers may mistakenly believe lead to irretrievable loss of work, an unexpected branch creation carries no such penalty, perceived or real.

Quoted 5 lines

So if it is deemed to be too confusing to dwim in this case, could we add a hint suggesting the command? Something like:
"No suitable branch <foo> found, however there is a remote tracking branch <origin/foo> that you can siwtch and create with git switch --guess foo" (or maybe the one without guess)?

That could be helpful if git-switch continues to make --no-guess the default, but making --guess the default (as it is in git-checkout) would likely be even better (for the reasons enumerated above).

author
#168 lore raw

Re: [PATCH v3 17/21] switch: no implicit dwim, use --guess to dwim

Quoted 33 lines · Eric Sunshine
Quoted 10 lines · Eckhard Maaß
Quoted 8 lines · Nguyễn Thái Ngọc Duy

Similar to automatic detach, this behavior could be confusing because it can sometimes create a new branch without a user asking it to, especially when the user is still not aware about this feature.

In the future, perhaps we could have a config key to disable these safety nets and let 'switch' do automatic detach or dwim again. But that will be opt-in after the user knows what is what. For now give a short option if you want to use it often.

Quoted 4 lines

As I am late to the patch series (sorry!), has there been already any discussion on that? In my experience, people get confused with detached HEAD state quite often, whereas the automatic creation of a local branch is no problem.

This statement does a good job of articulating my (unspoken) response to this patch. Whereas a detached HEAD might be scary and confusing to newcomers, and difficult for them to recover from, automatic creation of a DWIM'd local branch doesn't seem so problematic (if at all).

With git-checkout, it's very easy to accidentally get into a detached HEAD state, so it makes some sense to protect newcomers, by default, from that accident in git-switch. However, auto-creation of a new local branch is not, for a couple reasons, nearly so weighty a matter. First, in many cases it may be less likely to happen since it requires presence of a corresponding remote tracking branch. Second, it's intuitively easy to recover from it: when git-switch reports that it created a new branch, though perhaps surprising, the user would naturally know to look for a command to "delete a branch".

Quoted 3 lines

And, unlike a detached HEAD, which newcomers may mistakenly believe lead to irretrievable loss of work, an unexpected branch creation carries no such penalty, perceived or real.

I can't remember the last time it was discussed, but part of the reasons I chose to default --no-guess is because completion will be a lot less noisy.

But that's a very personal preference. I will switch to --guess as default no problem (unless someone jumps in and screams NOOO of course).

Please don't hold back when you find something not quite right. At least now I can fix it. Either that or by the time it's released, the Internet will blame me for adding yet another confusing git command :P

Signature · 1 line
Duy
#169 lore raw

Re: [PATCH v3 17/21] switch: no implicit dwim, use --guess to dwim

In reply to Eric Sunshine
Quoted 10 lines · Eric Sunshine

With git-checkout, it's very easy to accidentally get into a detached HEAD state, so it makes some sense to protect newcomers, by default, from that accident in git-switch. However, auto-creation of a new local branch is not, for a couple reasons, nearly so weighty a matter. First, in many cases it may be less likely to happen since it requires presence of a corresponding remote tracking branch. Second, it's intuitively easy to recover from it: when git-switch reports that it created a new branch, though perhaps surprising, the user would naturally know to look for a command to "delete a branch".

Quoted 3 lines

And, unlike a detached HEAD, which newcomers may mistakenly believe lead to irretrievable loss of work, an unexpected branch creation carries no such penalty, perceived or real.

I suspect that it actually cuts both ways. An auto-vivified local branch 'foo' that happens to have the same name as 'origin/foo' is still a different line of history UNLESS the user makes sure the divergence is reconciled with "push" and "pull" (possibly configured to "pull --rebase", but that is a secondary detail that depends on the workflow). Even when 'switch' reports that it created a new branch, a newcomer would probably not realize that it is "new", and different from the branch that the remote has.

Quoted 9 lines
Quoted 5 lines

So if it is deemed to be too confusing to dwim in this case, could we add a hint suggesting the command? Something like:
"No suitable branch <foo> found, however there is a remote tracking branch <origin/foo> that you can siwtch and create with git switch --guess foo" (or maybe the one without guess)?

That could be helpful if git-switch continues to make --no-guess the default, but making --guess the default (as it is in git-checkout) would likely be even better (for the reasons enumerated above).

I do not have a huge issue with making "--guess" the default, but then the user may be entitled to help with an advice message when the command, especially with the implicit "--guess", auto-vivifies a new local branch based on a remote-tracking branch to stress that this is a new branch and different from the history the remote side has.

author
#170 lore raw

Re: [PATCH v3 17/21] switch: no implicit dwim, use --guess to dwim

In reply to Eckhard Maaß
Quoted 11 lines · Eckhard Maaß

And while at it - what should happen, if:

- there is a tag named example
- no local branch example
- a branch at origin/example

... and we switch then? Right now it just gives "cannot find branch", should there be more information? Should it even create a branch example? With switch, switching a branch is unambiguous, even though there is a tag with that name. If I really want to --guess - should I be given more information?

There's checkout.defaultRemote that changes this behavior and it affects git-switch as well.

I like the idea of giving more information than just the terse (and technically correct) "cannot find branch". But I may have to delay implementing this a bit. There's a been a lot of updates in git-switch (which is great, don't get me wrong, I appreciate the feedback). I need to get v4 out for review soon then maybe handle the rest in v5 (and finally take a real hard look at git-restore comments).

Signature · 1 line
Duy
#171 lore raw

PATCH v3 18/21 switch: no worktree status unless real branch switch happens

In reply to Nguyễn Thái Ngọc Duy

When we switch from one branch to another, it makes sense to show a summary of local changes since there could be conflicts, or some files left modified.... When switch is used solely for creating a new branch (and "switch" to the same commit) or detaching, we don't really need to show anything.

"git checkout" does it anyway for historical reasons. But we can start with a clean slate with switch and don't have to.

This essentially reverts fa655d8411 (checkout: optimize "git checkout -b <new_branch>" - 2018-08-16) and make it default for switch, but also for -B and --detach. Users of big repos are encouraged to move to switch.

---
 Documentation/config/checkout.txt |   8 --
 builtin/checkout.c                | 134 ++----------------------------
 t/t1090-sparse-checkout-scope.sh  |  14 ----
 3 files changed, 8 insertions(+), 148 deletions(-)
Documentation/config/checkout.txt +0 -8
index d6872ffa83..6b646813ab 100644
@@ -16,11 +16,3 @@ will checkout the '<something>' branch on another remote,
 and by linkgit:git-worktree[1] when 'git worktree add' refers to a
 remote branch. This setting might be used for other checkout-like
 commands or functionality in the future.
-
-checkout.optimizeNewBranch::
-	Optimizes the performance of "git checkout -b <new_branch>" when
-	using sparse-checkout.  When set to true, git will not update the
-	repo based on the current sparse-checkout settings.  This means it
-	will not update the skip-worktree bit in the index nor add/remove
-	files in the working directory to reflect the current sparse checkout
-	settings nor will it show the local changes.
builtin/checkout.c +8 -126

184 lines not on this page · raw message

t/t1090-sparse-checkout-scope.sh +0 -14
index 090b7fc3d3..40cc004326 100755
@@ -31,20 +31,6 @@ test_expect_success 'perform sparse checkout of master' '
 	test_path_is_file c
 '
 
-test_expect_success 'checkout -b checkout.optimizeNewBranch interaction' '
-	cp .git/info/sparse-checkout .git/info/sparse-checkout.bak &&
-	test_when_finished "
-		mv -f .git/info/sparse-checkout.bak .git/info/sparse-checkout
-		git checkout master
-	" &&
-	echo "/b" >>.git/info/sparse-checkout &&
-	test "$(git ls-files -t b)" = "S b" &&
-	git -c checkout.optimizeNewBranch=true checkout -b fast &&
-	test "$(git ls-files -t b)" = "S b" &&
-	git checkout -b slow &&
-	test "$(git ls-files -t b)" = "H b"
-'
-
 test_expect_success 'merge feature branch into sparse checkout of master' '
 	git merge feature &&
 	test_path_is_file a &&
Signature · 1 line
2.21.0.rc1.337.gdf7f8d0522
#172 lore raw

Re: [PATCH v3 18/21] switch: no worktree status unless real branch switch happens

Quoted 6 lines · Nguyễn Thái Ngọc Duy

When we switch from one branch to another, it makes sense to show a summary of local changes since there could be conflicts, or some files left modified.... When switch is used solely for creating a new branch (and "switch" to the same commit) or detaching, we don't really need to show anything.

Quoted 7 lines

"git checkout" does it anyway for historical reasons. But we can start with a clean slate with switch and don't have to.

This essentially reverts fa655d8411 (checkout: optimize "git checkout -b <new_branch>" - 2018-08-16) and make it default for switch, but also for -B and --detach. Users of big repos are encouraged to move to switch.

I like this last bit. The skip_merge_working_tree() function which this removes was ugly, difficult to maintain, and difficult to get just right (and easy to break -- even by changing parts of the system which one might not expect to impact it).

#173 lore raw

PATCH v3 19/21 t: add tests for switch

In reply to Nguyễn Thái Ngọc Duy
---
 t/t2060-switch.sh | 87 +++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 87 insertions(+)
 create mode 100755 t/t2060-switch.sh
t/t2060-switch.sh new file +87 -0
new file mode 100755
index 0000000000..1e1e834c1b
@@ -0,0 +1,87 @@
+#!/bin/sh
+
+test_description='switch basic functionality'
+
+. ./test-lib.sh
+
+test_expect_success 'setup' '
+	test_commit first &&
+	git branch first-branch &&
+	test_commit second &&
+	test_commit third &&
+	git remote add origin nohost:/nopath &&
+	git update-ref refs/remotes/origin/foo first-branch
+'
+
+test_expect_success 'switch branch no arguments' '
+	test_must_fail git switch
+'
+
+test_expect_success 'switch branch' '
+	git switch first-branch &&
+	test_path_is_missing second.t
+'
+
+test_expect_success 'switch to a commit' '
+	test_must_fail git switch master^{commit}
+'
+
+test_expect_success 'switch and detach' '
+	test_when_finished git switch master &&
+	git switch --detach master^{commit} &&
+	test_must_fail git symbolic-ref HEAD
+'
+
+test_expect_success 'switch and detach current branch' '
+	test_when_finished git switch master &&
+	git switch master &&
+	git switch --detach &&
+	test_must_fail git symbolic-ref HEAD
+'
+
+test_expect_success 'switch and create branch' '
+	test_when_finished git switch master &&
+	git switch -c temp master^ &&
+	test_cmp_rev master^ refs/heads/temp &&
+	echo refs/heads/temp >expected-branch &&
+	git symbolic-ref HEAD >actual-branch &&
+	test_cmp expected-branch actual-branch
+'
+
+test_expect_success 'force create branch from HEAD' '
+	test_when_finished git switch master &&
+	git switch --detach master &&
+	git switch -C temp &&
+	test_cmp_rev master refs/heads/temp &&
+	echo refs/heads/temp >expected-branch &&
+	git symbolic-ref HEAD >actual-branch &&
+	test_cmp expected-branch actual-branch
+'
+
+test_expect_success 'new orphan branch' '
+	test_when_finished git switch master &&
+	git switch --orphan new-orphan master^ &&
+	test_commit orphan &&
+	git cat-file commit refs/heads/new-orphan >commit &&
+	! grep ^parent commit
+'
+
+test_expect_success 'switching ignores file of same branch name' '
+	test_when_finished git switch master &&
+	: >first-branch &&
+	git switch first-branch &&
+	echo refs/heads/first-branch >expected &&
+	git symbolic-ref HEAD >actual &&
+	test_commit expected actual
+'
+
+test_expect_success 'guess and create branch ' '
+	test_when_finished git switch master &&
+	test_must_fail git switch foo &&
+	git switch --guess foo &&
+	echo refs/heads/foo >expected &&
+	git symbolic-ref HEAD >actual &&
+	test_cmp expected actual
+'
+
+test_done
Signature · 1 line
2.21.0.rc1.337.gdf7f8d0522
#174 lore raw

Re: [PATCH v3 19/21] t: add tests for switch

t/t2060-switch.sh line 3

Quoted 5 lines · Nguyễn Thái Ngọc Duy
t/t2060-switch.sh +3 -0
@@ -0,0 +1,87 @@
+test_expect_success 'switch to a commit' '
+       test_must_fail git switch master^{commit}
+'

The title of this test was a bit misleading for me; I would have found it easier to understand what's being tested had it said "switch without --detach" or something.

t/t2060-switch.sh line 33

Quoted 5 lines
t/t2060-switch.sh +5 -0
+test_expect_success 'switch and detach' '
+       test_when_finished git switch master &&
+       git switch --detach master^{commit} &&
+       test_must_fail git symbolic-ref HEAD
+'

In fact, if the two tests were combined, it would have been even clearer (for me):

    test_expect_success 'switch and detach' '
        test_when_finished git switch master &&
        test_must_fail git switch master^{commit} &&
        git switch --detach master^{commit} &&
        test_must_fail git symbolic-ref HEAD
    '

Not worth a re-roll.

Quoted 8 lines
t/t2060-switch.sh +8 -0
+test_expect_success 'switch and create branch' '
+       test_when_finished git switch master &&
+       git switch -c temp master^ &&
+       test_cmp_rev master^ refs/heads/temp &&
+       echo refs/heads/temp >expected-branch &&
+       git symbolic-ref HEAD >actual-branch &&
+       test_cmp expected-branch actual-branch
+'

t/t2060-switch.sh line 59

Quoted 10 lines
t/t2060-switch.sh +10 -0
+
+test_expect_success 'force create branch from HEAD' '
+       test_when_finished git switch master &&
+       git switch --detach master &&
+       git switch -C temp &&
+       test_cmp_rev master refs/heads/temp &&
+       echo refs/heads/temp >expected-branch &&
+       git symbolic-ref HEAD >actual-branch &&
+       test_cmp expected-branch actual-branch
+'

Maybe also demonstrate that -C is actually needed here by leading in with a failing -c:

    ...
    git switch --detach master &&
    test_must_fail git switch -c temp &&
    git switch -C temp &&
    ...

Not worth a re-roll.

t/t2060-switch.sh line 85

Quoted 8 lines
t/t2060-switch.sh +8 -0
+test_expect_success 'guess and create branch ' '
+       test_when_finished git switch master &&
+       test_must_fail git switch foo &&
+       git switch --guess foo &&
+       echo refs/heads/foo >expected &&
+       git symbolic-ref HEAD >actual &&
+       test_cmp expected actual
+'

The above suggestions about --detach/-C reflect how you did it in this test, in which you first try "git switch foo" without the --guess option, expecting it to fail, and then repeat with the option, expecting it to succeed.

#175 lore raw

Re: [PATCH v3 19/21] t: add tests for switch

In reply to Nguyễn Thái Ngọc Duy
Quoted 13 lines · Nguyễn Thái Ngọc Duy
---
 t/t2060-switch.sh | 87 +++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 87 insertions(+)
 create mode 100755 t/t2060-switch.sh
t/t2060-switch.sh new file +2 -0
new file mode 100755
index 0000000000..1e1e834c1b
@@ -0,0 +1,87 @@
+#!/bin/sh
+

[snip]

t/t2060-switch.sh line 75

Quoted 8 lines
t/t2060-switch.sh new file +8 -0
+
+test_expect_success 'switching ignores file of same branch name' '
+	test_when_finished git switch master &&
+	: >first-branch &&
+	git switch first-branch &&
+	echo refs/heads/first-branch >expected &&
+	git symbolic-ref HEAD >actual &&
+	test_commit expected actual

s/commit/cmp/

Quoted 13 lines

+'

t/t2060-switch.sh new file +11 -0
+
+test_expect_success 'guess and create branch ' '
+	test_when_finished git switch master &&
+	test_must_fail git switch foo &&
+	git switch --guess foo &&
+	echo refs/heads/foo >expected &&
+	git symbolic-ref HEAD >actual &&
+	test_cmp expected actual
+'
+
+test_done
#176 lore raw

PATCH v3 20/21 completion: support switch

In reply to Nguyễn Thái Ngọc Duy

Completion support for --guess could be made better. If no --detach is given, we should only provide a list of refs/heads/* and dwim ones, not the entire ref space. But I still can't penetrate that __git_refs() function yet.

---
 contrib/completion/git-completion.bash | 27 ++++++++++++++++++++++++++
 1 file changed, 27 insertions(+)
contrib/completion/git-completion.bash +27 -0
index 976e4a6548..7fcf28d437 100644
@@ -2158,6 +2158,33 @@ _git_status ()
 	__git_complete_index_file "$complete_opt"
 }
 
+_git_switch ()
+{
+	case "$cur" in
+	--conflict=*)
+		__gitcomp "diff3 merge" "" "${cur##--conflict=}"
+		;;
+	--*)
+		__gitcomp_builtin switch
+		;;
+	*)
+		# check if ---guess was specified to enable DWIM mode
+		local track_opt= only_local_ref=n
+		if [ -n "$(__git_find_on_cmdline "-g --guess")" ]; then
+			track_opt='--track'
+		fi
+		if [ -z "$(__git_find_on_cmdline "-d --detach")" ]; then
+			only_local_ref=y
+		fi
+		if [ $only_local_ref = y -a -n "$track_opt"]; then
+			__gitcomp_direct "$(__git_heads "" "$cur" " ")"
+		else
+			__git_complete_refs $track_opt
+		fi
+		;;
+	esac
+}
+
 __git_config_get_set_variables ()
 {
 	local prevword word config_file= c=$cword
Signature · 1 line
2.21.0.rc1.337.gdf7f8d0522
#177 lore raw

PATCH v3 21/21 doc: promote "git switch"

In reply to Nguyễn Thái Ngọc Duy

The new command "git switch" is added to avoid the confusion of one-command-do-all "git checkout" for new users. They are also helpful to avoid ambiguation context.

For these reasons, promote it everywhere possible. This includes documentation, suggestions/advice from other commands...

---
 Documentation/git-branch.txt           | 12 +++---
 Documentation/git-check-ref-format.txt |  3 +-
 Documentation/git-format-patch.txt     |  2 +-
 Documentation/git-merge-base.txt       |  2 +-
 Documentation/git-rebase.txt           |  2 +-
 Documentation/git-remote.txt           |  2 +-
 Documentation/git-rerere.txt           | 10 ++---
 Documentation/git-reset.txt            | 20 ++++-----
 Documentation/git-stash.txt            |  9 +++--
 Documentation/gitcore-tutorial.txt     | 19 +++++----
 Documentation/giteveryday.txt          | 24 +++++------
 Documentation/gittutorial.txt          |  4 +-
 Documentation/gitworkflows.txt         |  3 +-
 Documentation/revisions.txt            |  2 +-
 Documentation/user-manual.txt          | 56 +++++++++++++-------------
 advice.c                               | 11 +++--
 sha1-name.c                            |  2 +-
 t/t2020-checkout-detach.sh             | 16 ++++----
 18 files changed, 101 insertions(+), 98 deletions(-)
Documentation/git-branch.txt +6 -6
index 0cd87ddeff..1e2d89b174 100644
@@ -48,7 +48,7 @@ The command's second form creates a new branch head named <branchname>
 which points to the current `HEAD`, or <start-point> if given.
 
 Note that this will create the new branch, but it will not switch the
-working tree to it; use "git checkout <newbranch>" to switch to the
+working tree to it; use "git switch <newbranch>" to switch to the
 new branch.
 
 When a local branch is started off a remote-tracking branch, Git sets up the
@@ -198,7 +198,7 @@ This option is only applicable in non-verbose mode.
 +
 This behavior is the default when the start point is a remote-tracking branch.
 Set the branch.autoSetupMerge configuration variable to `false` if you
-want `git checkout` and `git branch` to always behave as if `--no-track`
+want `git switch`, `git checkout` and `git branch` to always behave as if `--no-track`
 were given. Set it to `always` if you want this behavior when the
 start-point is either a local or remote-tracking branch.
 
@@ -297,7 +297,7 @@ Start development from a known tag::
 $ git clone git://git.kernel.org/pub/scm/.../linux-2.6 my2.6
 $ cd my2.6
 $ git branch my2.6.14 v2.6.14   <1>
-$ git checkout my2.6.14
+$ git switch my2.6.14
 ------------
 +
 <1> This step and the next one could be combined into a single step with
@@ -322,9 +322,9 @@ $ git branch -D test                                    <2>
 NOTES
 -----
 
-If you are creating a branch that you want to checkout immediately, it is
-easier to use the git checkout command with its `-b` option to create
-a branch and check it out with a single command.
+If you are creating a branch that you want to switch to immediately,
+it is easier to use the "git switch" command with its `-c` option to
+do the same thing with a single command.
 
 The options `--contains`, `--no-contains`, `--merged` and `--no-merged`
 serve four related but different purposes:
Documentation/git-check-ref-format.txt +2 -1
index d9de992585..ee6a4144fb 100644
@@ -88,7 +88,8 @@ but it is explicitly forbidden at the beginning of a branch name).
 When run with `--branch` option in a repository, the input is first
 expanded for the ``previous checkout syntax''
 `@{-n}`.  For example, `@{-1}` is a way to refer the last thing that
-was checked out using "git checkout" operation. This option should be
+was checked out using "git switch" or "git checkout" operation.
+This option should be
 used by porcelains to accept this syntax anywhere a branch name is
 expected, so they can act as if you typed the branch name. As an
 exception note that, the ``previous checkout operation'' might result
Documentation/git-format-patch.txt +1 -1
index 1af85d404f..0a24a5679e 100644
@@ -421,7 +421,7 @@ One way to test if your MUA is set up correctly is:
 * Apply it:
 
     $ git fetch <project> master:test-apply
-    $ git checkout test-apply
+    $ git switch test-apply
     $ git reset --hard
     $ git am a.patch
 
Documentation/git-merge-base.txt +1 -1
index 9f07f4f6ed..261d5c1164 100644
@@ -149,7 +149,7 @@ instead.
 Discussion on fork-point mode
 -----------------------------
 
-After working on the `topic` branch created with `git checkout -b
+After working on the `topic` branch created with `git switch -c
 topic origin/master`, the history of remote-tracking branch
 `origin/master` may have been rewound and rebuilt, leading to a
 history of this shape:
Documentation/git-rebase.txt +1 -1
index 5629ba4c5d..cb6fc166e2 100644
@@ -17,7 +17,7 @@ SYNOPSIS
 DESCRIPTION
 -----------
 If <branch> is specified, 'git rebase' will perform an automatic
-`git checkout <branch>` before doing anything else.  Otherwise
+`git switch <branch>` before doing anything else.  Otherwise
 it remains on the current branch.
 
 If <upstream> is not specified, the upstream configured in
Documentation/git-remote.txt +1 -1
index 0cad37fb81..9659abbf8e 100644
@@ -230,7 +230,7 @@ $ git branch -r
   staging/master
   staging/staging-linus
   staging/staging-next
-$ git checkout -b staging staging/master
+$ git switch -c staging staging/master
 ...
 ------------
 
Documentation/git-rerere.txt +5 -5
index df310d2a58..fe4434ad9d 100644
@@ -91,7 +91,7 @@ For such a test, you need to merge master and topic somehow.
 One way to do it is to pull master into the topic branch:
 
 ------------
-	$ git checkout topic
+	$ git switch topic
 	$ git merge master
 
               o---*---o---+ topic
@@ -113,10 +113,10 @@ the upstream might have been advanced since the test merge `+`,
 in which case the final commit graph would look like this:
 
 ------------
-	$ git checkout topic
+	$ git switch topic
 	$ git merge master
 	$ ... work on both topic and master branches
-	$ git checkout master
+	$ git switch master
 	$ git merge topic
 
               o---*---o---+---o---o topic
@@ -136,11 +136,11 @@ merges, you could blow away the test merge, and keep building on
 top of the tip before the test merge:
 
 ------------
-	$ git checkout topic
+	$ git switch topic
 	$ git merge master
 	$ git reset --hard HEAD^ ;# rewind the test merge
 	$ ... work on both topic and master branches
-	$ git checkout master
+	$ git switch master
 	$ git merge topic
 
               o---*---o-------o---o topic
Documentation/git-reset.txt +10 -10
index 132f8e55f6..cbf901efb4 100644
@@ -149,9 +149,9 @@ See also the `--amend` option to linkgit:git-commit[1].
 Undo a commit, making it a topic branch::
 +
 ------------
-$ git branch topic/wip     <1>
-$ git reset --hard HEAD~3  <2>
-$ git checkout topic/wip   <3>
+$ git branch topic/wip          <1>
+$ git reset --hard HEAD~3       <2>
+$ git switch topic/wip          <3>
 ------------
 +
 <1> You have made some commits, but realize they were premature
@@ -232,13 +232,13 @@ working tree are not in any shape to be committed yet, but you
 need to get to the other branch for a quick bugfix.
 +
 ------------
-$ git checkout feature ;# you were working in "feature" branch and
-$ work work work       ;# got interrupted
+$ git switch feature  ;# you were working in "feature" branch and
+$ work work work      ;# got interrupted
 $ git commit -a -m "snapshot WIP"                 <1>
-$ git checkout master
+$ git switch master
 $ fix fix fix
 $ git commit ;# commit with real log
-$ git checkout feature
+$ git switch feature
 $ git reset --soft HEAD^ ;# go back to WIP state  <2>
 $ git reset                                       <3>
 ------------
@@ -279,18 +279,18 @@ reset it while keeping the changes in your working tree.
 +
 ------------
 $ git tag start
-$ git checkout -b branch1
+$ git switch -c branch1
 $ edit
 $ git commit ...                            <1>
 $ edit
-$ git checkout -b branch2                   <2>
+$ git switch -c branch2                     <2>
 $ git reset --keep start                    <3>
 ------------
 +
 <1> This commits your first edits in `branch1`.
 <2> In the ideal world, you could have realized that the earlier
     commit did not belong to the new topic when you created and switched
-    to `branch2` (i.e. `git checkout -b branch2 start`), but nobody is
+    to `branch2` (i.e. `git switch -c branch2 start`), but nobody is
     perfect.
 <3> But you can use `reset --keep` to remove the unwanted commit after
     you switched to `branch2`.
Documentation/git-stash.txt +5 -4
index 7ef8c47911..ebb6282db3 100644
@@ -235,12 +235,12 @@ return to your original branch to make the emergency fix, like this:
 +
 ----------------------------------------------------------------
 # ... hack hack hack ...
-$ git checkout -b my_wip
+$ git switch -c my_wip
 $ git commit -a -m "WIP"
-$ git checkout master
+$ git switch master
 $ edit emergency fix
 $ git commit -a -m "Fix in a hurry"
-$ git checkout my_wip
+$ git switch my_wip
 $ git reset --soft HEAD^
 # ... continue hacking ...
 ----------------------------------------------------------------
@@ -293,7 +293,8 @@ SEE ALSO
 linkgit:git-checkout[1],
 linkgit:git-commit[1],
 linkgit:git-reflog[1],
-linkgit:git-reset[1]
+linkgit:git-reset[1],
+linkgit:git-switch[1]
 
 GIT
 ---
Documentation/gitcore-tutorial.txt +9 -10
index e29a9effcc..f880d21dfb 100644
@@ -741,7 +741,7 @@ used earlier, and create a branch in it. You do that by simply just
 saying that you want to check out a new branch:
 
 ------------
-$ git checkout -b mybranch
+$ git switch -c mybranch
 ------------
 
 will create a new branch based at the current `HEAD` position, and switch
@@ -755,7 +755,7 @@ just telling 'git checkout' what the base of the checkout would be.
 In other words, if you have an earlier tag or branch, you'd just do
 
 ------------
-$ git checkout -b mybranch earlier-commit
+$ git switch -c mybranch earlier-commit
 ------------
 
 and it would create the new branch `mybranch` at the earlier commit,
@@ -765,7 +765,7 @@ and check out the state at that time.
 You can always just jump back to your original `master` branch by doing
 
 ------------
-$ git checkout master
+$ git switch master
 ------------
 
 (or any other branch-name, for that matter) and if you forget which
@@ -794,7 +794,7 @@ $ git branch <branchname> [startingpoint]
 
 which will simply _create_ the branch, but will not do anything further.
 You can then later -- once you decide that you want to actually develop
-on that branch -- switch to that branch with a regular 'git checkout'
+on that branch -- switch to that branch with a regular 'git switch'
 with the branchname as the argument.
 
 
@@ -808,7 +808,7 @@ being the same as the original `master` branch, let's make sure we're in
 that branch, and do some work there.
 
 ------------------------------------------------
-$ git checkout mybranch
+$ git switch mybranch
 $ echo "Work, work, work" >>hello
 $ git commit -m "Some work." -i hello
 ------------------------------------------------
@@ -825,7 +825,7 @@ does some work in the original branch, and simulate that by going back
 to the master branch, and editing the same file differently there:
 
 ------------
-$ git checkout master
+$ git switch master
 ------------
 
 Here, take a moment to look at the contents of `hello`, and notice how they
@@ -958,7 +958,7 @@ to the `master` branch. Let's go back to `mybranch`, and run
 'git merge' to get the "upstream changes" back to your branch.
 
 ------------
-$ git checkout mybranch
+$ git switch mybranch
 $ git merge -m "Merge upstream changes." master
 ------------
 
@@ -1133,9 +1133,8 @@ Remember, before running 'git merge', our `master` head was at
 work." commit.
 
 ------------
-$ git checkout mybranch
-$ git reset --hard master^2
-$ git checkout master
+$ git switch -C mybranch master^2
+$ git switch master
 $ git reset --hard master^
 ------------
 
Documentation/giteveryday.txt +12 -12
index 9f2528fc8c..ad455f3e39 100644
@@ -41,7 +41,7 @@ following commands.
 
   * linkgit:git-log[1] to see what happened.
 
-  * linkgit:git-checkout[1] and linkgit:git-branch[1] to switch
+  * linkgit:git-switch[1] and linkgit:git-branch[1] to switch
     branches.
 
   * linkgit:git-add[1] to manage the index file.
@@ -80,7 +80,7 @@ $ git tag v2.43 <2>
 Create a topic branch and develop.::
 +
 ------------
-$ git checkout -b alsa-audio <1>
+$ git switch -c alsa-audio <1>
 $ edit/compile/test
 $ git checkout -- curses/ux_audio_oss.c <2>
 $ git add curses/ux_audio_alsa.c <3>
@@ -90,7 +90,7 @@ $ git commit -a -s <5>
 $ edit/compile/test
 $ git diff HEAD^ <6>
 $ git commit -a --amend <7>
-$ git checkout master <8>
+$ git switch master <8>
 $ git merge alsa-audio <9>
 $ git log --since='3 days ago' <10>
 $ git log v2.43.. curses/ <11>
@@ -148,11 +148,11 @@ Clone the upstream and work on it.  Feed changes to upstream.::
 ------------
 $ git clone git://git.kernel.org/pub/scm/.../torvalds/linux-2.6 my2.6
 $ cd my2.6
-$ git checkout -b mine master <1>
+$ git switch -c mine master <1>
 $ edit/compile/test; git commit -a -s <2>
 $ git format-patch master <3>
 $ git send-email --to="person <[email protected]>" 00*.patch <4>
-$ git checkout master <5>
+$ git switch master <5>
 $ git pull <6>
 $ git log -p ORIG_HEAD.. arch/i386 include/asm-i386 <7>
 $ git ls-remote --heads http://git.kernel.org/.../jgarzik/libata-dev.git <8>
@@ -194,7 +194,7 @@ satellite$ edit/compile/test/commit
 satellite$ git push origin <4>
 
 mothership$ cd frotz
-mothership$ git checkout master
+mothership$ git switch master
 mothership$ git merge satellite/master <5>
 ------------
 +
@@ -216,7 +216,7 @@ machine into the master branch.
 Branch off of a specific tag.::
 +
 ------------
-$ git checkout -b private2.6.14 v2.6.14 <1>
+$ git switch -c private2.6.14 v2.6.14 <1>
 $ edit/compile/test; git commit -a
 $ git checkout master
 $ git cherry-pick v2.6.14..private2.6.14 <2>
@@ -274,14 +274,14 @@ $ mailx <3>
 & s 2 3 4 5 ./+to-apply
 & s 7 8 ./+hold-linus
 & q
-$ git checkout -b topic/one master
+$ git switch -c topic/one master
 $ git am -3 -i -s ./+to-apply <4>
 $ compile/test
-$ git checkout -b hold/linus && git am -3 -i -s ./+hold-linus <5>
-$ git checkout topic/one && git rebase master <6>
-$ git checkout pu && git reset --hard next <7>
+$ git switch -c hold/linus && git am -3 -i -s ./+hold-linus <5>
+$ git switch topic/one && git rebase master <6>
+$ git switch -C pu next <7>
 $ git merge topic/one topic/two && git merge hold/linus <8>
-$ git checkout maint
+$ git switch maint
 $ git cherry-pick master~4 <9>
 $ compile/test
 $ git tag -s -m "GIT 0.99.9x" v0.99.9x <10>
Documentation/gittutorial.txt +2 -2
index 242de31cb6..e6ad6b5f8d 100644
@@ -207,7 +207,7 @@ automatically.  The asterisk marks the branch you are currently on;
 type
 
 ------------------------------------------------
-$ git checkout experimental
+$ git switch experimental
 ------------------------------------------------
 
 to switch to the experimental branch.  Now edit a file, commit the
@@ -216,7 +216,7 @@ change, and switch back to the master branch:
 ------------------------------------------------
 (edit file)
 $ git commit -a
-$ git checkout master
+$ git switch master
 ------------------------------------------------
 
 Check that the change you made is no longer visible, since it was
Documentation/gitworkflows.txt +1 -2
index ca11c7bdaf..abc0dc6bc7 100644
@@ -301,8 +301,7 @@ topics on 'next':
 .Rewind and rebuild next
 [caption="Recipe: "]
 =====================================
-* `git checkout next`
-* `git reset --hard master`
+* `git switch -C next master`
 * `git merge ai/topic_in_next1`
 * `git merge ai/topic_in_next2`
 * ...
Documentation/revisions.txt +1 -1
index 72daa20e76..a1c7a65da6 100644
@@ -115,7 +115,7 @@ Here's an example to make it more clear:
 ------------------------------
 $ git config push.default current
 $ git config remote.pushdefault myfork
-$ git checkout -b mybranch origin/master
+$ git switch -c mybranch origin/master
 
 $ git rev-parse --symbolic-full-name @{upstream}
 refs/remotes/origin/master
Documentation/user-manual.txt +28 -28

164 lines not on this page · raw message

advice.c +7 -4
index 567209aa79..457c1a255e 100644
@@ -191,13 +191,16 @@ void NORETURN die_conclude_merge(void)
 void detach_advice(const char *new_name)
 {
 	const char *fmt =
-	_("Note: checking out '%s'.\n\n"
+	_("Note: switching to '%s'.\n"
+	"\n"
 	"You are in 'detached HEAD' state. You can look around, make experimental\n"
 	"changes and commit them, and you can discard any commits you make in this\n"
-	"state without impacting any branches by performing another checkout.\n\n"
+	"state without impacting any branches by switching back to a branch.\n"
+	"\n"
 	"If you want to create a new branch to retain commits you create, you may\n"
-	"do so (now or later) by using -b with the checkout command again. Example:\n\n"
-	"  git checkout -b <new-branch-name>\n\n");
+	"do so (now or later) by using -c with the switch command. Example:\n"
+	"\n"
+	"  git switch -c <new-branch-name>\n\n");
 
 	fprintf(stderr, fmt, new_name);
 }
sha1-name.c +1 -1
index 6dda2c16df..da0518c8e3 100644
@@ -743,7 +743,7 @@ static int get_oid_basic(const char *str, int len, struct object_id *oid,
 	"because it will be ignored when you just specify 40-hex. These refs\n"
 	"may be created by mistake. For example,\n"
 	"\n"
-	"  git checkout -b $br $(git rev-parse ...)\n"
+	"  git switch -c $br $(git rev-parse ...)\n"
 	"\n"
 	"where \"$br\" is somehow empty and a 40-hex ref is created. Please\n"
 	"examine these refs and maybe delete them. Turn this message off by\n"
t/t2020-checkout-detach.sh +8 -8
index 1fa670625c..f85dbd6740 100755
@@ -195,16 +195,16 @@ test_expect_success 'describe_detached_head prints no SHA-1 ellipsis when not as
 
 	# The first detach operation is more chatty than the following ones.
 	cat >1st_detach <<-EOF &&
-	Note: checking out 'HEAD^'.
+	Note: switching to 'HEAD^'.
 
 	You are in 'detached HEAD' state. You can look around, make experimental
 	changes and commit them, and you can discard any commits you make in this
-	state without impacting any branches by performing another checkout.
+	state without impacting any branches by switching back to a branch.
 
 	If you want to create a new branch to retain commits you create, you may
-	do so (now or later) by using -b with the checkout command again. Example:
+	do so (now or later) by using -c with the switch command. Example:
 
-	  git checkout -b <new-branch-name>
+	  git switch -c <new-branch-name>
 
 	HEAD is now at \$commit three
 	EOF
@@ -271,16 +271,16 @@ test_expect_success 'describe_detached_head does print SHA-1 ellipsis when asked
 
 	# The first detach operation is more chatty than the following ones.
 	cat >1st_detach <<-EOF &&
-	Note: checking out 'HEAD^'.
+	Note: switching to 'HEAD^'.
 
 	You are in 'detached HEAD' state. You can look around, make experimental
 	changes and commit them, and you can discard any commits you make in this
-	state without impacting any branches by performing another checkout.
+	state without impacting any branches by switching back to a branch.
 
 	If you want to create a new branch to retain commits you create, you may
-	do so (now or later) by using -b with the checkout command again. Example:
+	do so (now or later) by using -c with the switch command. Example:
 
-	  git checkout -b <new-branch-name>
+	  git switch -c <new-branch-name>
 
 	HEAD is now at \$commit... three
 	EOF
Signature · 1 line
2.21.0.rc1.337.gdf7f8d0522
#178 lore raw
In reply to Nguyễn Thái Ngọc Duy

On 08/03/2019 09:57, Nguyễn Thái Ngọc Duy wrote:
[snip]

Quoted 11 lines

Range-diff dựa trên v2:

 -:  ---------- >  1:  949f3dd4fd git-checkout.txt: spell out --no-option
 1:  8358b9ca36 =  2:  1ddbbae3e2 git-checkout.txt: fix one syntax line
 2:  1686ccbf8d !  3:  b0cb2372db doc: document --overwrite-ignore
    @@ -14,14 +14,15 @@
      	out anyway. In other words, the ref can be held by more than one
      	worktree.
      
    -+--[no-]overwrite-ignore::
    ++--overwrite-ignore::
    ++--no-overwrite-ignore::

Just curious, but why? Is '--[no-]overwrite-ignore' thought to be harder to read? What about the rest of the man-pages?

ATB,
Ramsay Jones

author
#179 lore raw
Quoted 13 lines · Ramsay Jones

On 08/03/2019 09:57, Nguyễn Thái Ngọc Duy wrote:
[snip]

Quoted 8 lines

Range-diff dựa trên v2:

 -:  ---------- >  1:  949f3dd4fd git-checkout.txt: spell out --no-option
 1:  8358b9ca36 =  2:  1ddbbae3e2 git-checkout.txt: fix one syntax line
 2:  1686ccbf8d !  3:  b0cb2372db doc: document --overwrite-ignore

@@ -14,14 +14,15 @@
out anyway. In other words, the ref can be held by more than one worktree.

Quoted 6 lines
Quoted 3 lines
    -+--[no-]overwrite-ignore::
    ++--overwrite-ignore::
    ++--no-overwrite-ignore::

Just curious, but why? Is '--[no-]overwrite-ignore' thought to be harder to read? What about the rest of the man-pages?

It's also easier to search. If I remember correctly I did search for the rest of man pages and the --no- wins over --[no-]

Signature · 1 line
Duy
#180 lore raw

v4 cover Add new command 'switch'

In reply to Nguyễn Thái Ngọc Duy

Thanks for all the comments from v3 (and before), I didn't expect feedback from so many people. v4 fixes most of them, but still leaves a couple for v5.

- -C remains because people seem to need it

- --recreate vs --force-create: there was no strong preference for either, so I stick with --force-create

- --guess (dwim mode) is now made default

- --orphan by default switches to an empty tree instead of current HEAD (this is Elijah's alternative approach). This allows you to start fresh, but you can still keep "HEAD" content or even switch to another tree.

- advice.detachedHead text is updated to suggest a way out (currently it only suggests a way forward with 'checkout -b')

- --force has a new alias --discard-changes

- the error message when we expect a branch is improved to help point out why the given argument is not a branch

- more docs update and reorganization, and other silly bugs I made in v3

The two things I'm aware of but have not done:

- the bug in 'git checkout -m' and 'git switch -m' that could lead to loss of staged changes.

- better suggestion when dwim fails (e.g. when there are multiple dwim candidates, we could show them all).

There have been lots of discussions back and forth. If I miss anything else, please let me know.

Nguyễn Thái Ngọc Duy (26):
git-checkout.txt: spell out --no-option git-checkout.txt: fix one syntax line
doc: document --overwrite-ignore
git-checkout.txt: fix monospace typeset
t: rename t2014-switch.sh to t2014-checkout-switch.sh
checkout: advice how to get out of detached HEAD mode
checkout: keep most #include sorted
checkout: factor out some code in parse_branchname_arg()
checkout: make "opts" in cmd_checkout() a pointer
checkout: move 'confict_style' and 'dwim_..' to checkout_opts
checkout: split options[] array in three pieces
checkout: split part of it to new command 'switch'
switch: better names for -b and -B
switch: add --discard-changes
switch: remove -l
switch: stop accepting pathspec
switch: reject "do nothing" case
switch: only allow explicit detached HEAD
switch: add short option for --detach
switch: implicit dwim, use --no-guess to disable it
switch: no worktree status unless real branch switch happens
switch: reject if some operation is in progress
switch: --orphan defaults to empty tree as HEAD
t: add tests for switch
completion: support switch
doc: promote "git switch"

 .gitignore                                    |   1 +
 Documentation/config/advice.txt               |  13 +-
 Documentation/config/branch.txt               |   4 +-
 Documentation/config/checkout.txt             |  17 +-
 Documentation/config/diff.txt                 |   3 +-
 Documentation/git-branch.txt                  |  12 +-
 Documentation/git-check-ref-format.txt        |   3 +-
 Documentation/git-checkout.txt                | 221 ++++---
 Documentation/git-format-patch.txt            |   2 +-
 Documentation/git-merge-base.txt              |   2 +-
 Documentation/git-merge.txt                   |   5 +
 Documentation/git-rebase.txt                  |   2 +-
 Documentation/git-remote.txt                  |   2 +-
 Documentation/git-rerere.txt                  |  10 +-
 Documentation/git-reset.txt                   |  20 +-
 Documentation/git-stash.txt                   |   9 +-
 Documentation/git-switch.txt (new)            | 277 ++++++++
 Documentation/gitattributes.txt               |   3 +-
 Documentation/gitcore-tutorial.txt            |  19 +-
 Documentation/giteveryday.txt                 |  24 +-
 Documentation/githooks.txt                    |   8 +-
 Documentation/gittutorial.txt                 |   4 +-
 Documentation/gitworkflows.txt                |   3 +-
 Documentation/revisions.txt                   |   2 +-
 Documentation/user-manual.txt                 |  56 +-
 Makefile                                      |   1 +
 advice.c                                      |  17 +-
 builtin.h                                     |   1 +
 builtin/checkout.c                            | 597 ++++++++++--------
 command-list.txt                              |   1 +
 contrib/completion/git-completion.bash        |  37 +-
 git.c                                         |   1 +
 parse-options-cb.c                            |  17 +
 parse-options.h                               |   1 +
 sha1-name.c                                   |   2 +-
 t/t1090-sparse-checkout-scope.sh              |  14 -
 ...014-switch.sh => t2014-checkout-switch.sh} |   0
 t/t2020-checkout-detach.sh                    |  28 +-
 t/t2060-switch.sh (new +x)                    |  97 +++
 39 files changed, 1043 insertions(+), 493 deletions(-)
 create mode 100644 Documentation/git-switch.txt
 rename t/{t2014-switch.sh => t2014-checkout-switch.sh} (100%)
 create mode 100755 t/t2060-switch.sh

Range-diff dựa trên v3:
1: b0cb2372db ! 1: 535dc1f310 doc: document --overwrite-ignore
@@ -22,7 +22,20 @@
+
--recurse-submodules::
--no-recurse-submodules::
- Using --recurse-submodules will update the content of all initialized
+- Using --recurse-submodules will update the content of all initialized
++ Using --recurse-submodules will update the content of all initialized
+ submodules according to the commit recorded in the superproject. If
+ local modifications in a submodule would be overwritten the checkout
+- will fail unless -f is used. If nothing (or --no-recurse-submodules)
++ will fail unless -f is used. If nothing (or --no-recurse-submodules)
+ is used, the work trees of submodules will not be updated.
+- Just like linkgit:git-submodule[1], this will detach the
+- submodules HEAD.
++ Just like linkgit:git-submodule[1], this will detach HEAD of the
++ submodule.
+
+ --no-guess::
+ Do not attempt to create a branch if a remote tracking branch

diff --git a/Documentation/git-merge.txt b/Documentation/git-merge.txt --- a/Documentation/git-merge.txt

 2:  5b165524d1 <  -:  ---------- git-checkout.txt: fix monospace typeset
 -:  ---------- >  2:  b6305d2871 git-checkout.txt: fix monospace typeset
 3:  a4240a888e =  3:  bb56e45457 t: rename t2014-switch.sh to t2014-checkout-switch.sh
 -:  ---------- >  4:  123392757a checkout: advice how to get out of detached HEAD mode
 -:  ---------- >  5:  d1ec6b4ce0 checkout: keep most #include sorted
 4:  dc4a8e8933 =  6:  4b1742672b checkout: factor out some code in parse_branchname_arg()
 5:  f0d933c2ac =  7:  e0bcc3a4dd checkout: make "opts" in cmd_checkout() a pointer
 6:  0aa541689c =  8:  ca5b4d7db0 checkout: move 'confict_style' and 'dwim_..' to checkout_opts
 7:  84ca42bb26 =  9:  13c03997f0 checkout: split options[] array in three pieces
 8:  e983c8bb2c ! 10:  24d532b276 checkout: split part of it to new command 'switch'

@@ -4,9 +4,9 @@

"git checkout" doing too many things is a source of confusion for many users (and it even bites old timers sometimes). To remedy that, the
- command will be split into two new ones: switch and
- something-to-checkout-paths. The good old "git checkout" command is
- still here and will be until all (or most of users) are sick of it.
+ command will be split into two new ones: switch and restore. The good
+ old "git checkout" command is still here and will be until all (or most
+ of users) are sick of it.

See the new man page for the final design of switch. The actual implementation though is still pretty much the same as "git checkout"
@@ -157,12 +157,13 @@
+updated to match the branch. All new commits will be added to the tip +of this branch.
+
-+Optionally a new branch could be created with either -c or -C, or ++Optionally a new branch could be created with either -c, -C, ++automatically from a remote branch of same name (see --guess), or
+detach the working tree from any branch with --detach, along with +switching.
+
+Switching branches does not require a clean index and working tree
-+(i.e. no differences compared to 'HEAD'). The operation is aborted ++(i.e. no differences compared to HEAD). The operation is aborted
+however if the switch leads to loss of local changes, unless told +otherwise.
+
@@ -175,14 +176,19 @@
+ Name for the new branch.
+
+<start-point>::
-+ The name of a commit at which to switch to before creating a
-+ new branch or detach from.
++ The starting point for the new branch. Specifying a
++ <start-point> allows you to create a branch based on some
++ other point in history than where HEAD currently points. (Or,
++ in the case of --detach, allows you to inspect and detach
++ from some other point.)
++
-+You can use the "@{-N}" syntax to refer to the N-th last ++You can use the @{-N} syntax to refer to the N-th last
+branch/commit switched to "git switch" or "git checkout"
-+operation. You may also specify - which is synonymous to "@{-1}". ++operation. You may also specify - which is synonymous to @{-1}. ++This is often used to switch quickly between two branches, or to undo ++a branch switch by mistake.
++
-+As a special case, you may use "A...B" as a shortcut for the merge ++As a special case, you may use A...B as a shortcut for the merge
+base of A and B if there is exactly one merge base. You can leave +out at most one of A and B, in which case it defaults to HEAD. +
@@ -214,8 +220,8 @@
+ experiments. See the "DETACHED HEAD" section in
+ linkgit:git-checkout[1] for details.
+
-+-g::
+--guess::
++--no-guess::
+ If <branch> is not found but there does exist a tracking
+ branch in exactly one remote (call it <remote>) with a
+ matching name, treat as equivalent to
@@ -231,18 +237,45 @@
+to always checkout remote branches from there if <branch> is +ambiguous but exists on the 'origin' remote. See also +checkout.defaultRemote in linkgit:git-config[1].
-+
-+-q::
-+--quiet::
-+ Quiet, suppress feedback messages.
+++
++--guess is the default behavior. Use --no-guess to disable it.
+
+-f::
+--force::
++ An alias for --discard-changes.
++
++--discard-changes::
+ Proceed even if the index or the working tree differs from
-+ HEAD. Both the index and working tree are restored to match
++ HEAD. Both the index and working tree are restored to match
+ the switching target. This is used to throw away local
+ changes.
+
++-m::
++--merge::
++ If you have local modifications to one or more files that are
++ different between the current branch and the branch to which
++ you are switching, the command refuses to switch branches in
++ order to preserve your modifications in context. However,
++ with this option, a three-way merge between the current
++ branch, your working tree contents, and the new branch is
++ done, and you will be on the new branch.
+++
++When a merge conflict happens, the index entries for conflicting ++paths are left unmerged, and you need to resolve the conflicts ++and mark the resolved paths with git add (or git rm if the merge ++should result in deletion of the path).
++
++--conflict=<style>::
++ The same as --merge option above, but changes the way the
++ conflicting hunks are presented, overriding the
++ merge.conflictStyle configuration variable. Possible values are
++ "merge" (default) and "diff3" (in addition to what is shown by
++ "merge" style, shows the original contents).
++
++-q::
++--quiet::
++ Quiet, suppress feedback messages.
++
+--progress::
+--no-progress::
+ Progress status is reported on the standard error stream
@@ -253,49 +286,28 @@
+-t::
+--track::
+ When creating a new branch, set up "upstream" configuration.
-+ -c is implied. See "--track" in linkgit:git-branch[1] for
++ -c is implied. See --track in linkgit:git-branch[1] for
+ details.
++
+If no -c option is given, the name of the new branch will be derived +from the remote-tracking branch, by looking at the local part of the +refspec configured for the corresponding remote, and then stripping
-+the initial part up to the "*". This would tell us to use "hack" as -+the local branch when branching off of "origin/hack" (or -+"remotes/origin/hack", or even "refs/remotes/origin/hack"). If the ++the initial part up to the "*". This would tell us to use hack as ++the local branch when branching off of origin/hack (or ++remotes/origin/hack, or even refs/remotes/origin/hack). If the
+given name has no slash, or the above guessing results in an empty +name, the guessing is aborted. You can explicitly give a name with +-c in such a case.
+
+--no-track::
+ Do not set up "upstream" configuration, even if the
-+ branch.autoSetupMerge configuration variable is true.
-+
-+-m::
-+--merge::
-+ If you have local modifications to one or more files that are
-+ different between the current branch and the branch to which
-+ you are switching, the command refuses to switch branches in
-+ order to preserve your modifications in context. However,
-+ with this option, a three-way merge between the current
-+ branch, your working tree contents, and the new branch is
-+ done, and you will be on the new branch.
-++
-+When a merge conflict happens, the index entries for conflicting -+paths are left unmerged, and you need to resolve the conflicts -+and mark the resolved paths with git add (or git rm if the merge -+should result in deletion of the path).
-+
-+--conflict=<style>::
-+ The same as --merge option above, but changes the way the
-+ conflicting hunks are presented, overriding the
-+ merge.conflictStyle configuration variable. Possible values are
-+ "merge" (default) and "diff3" (in addition to what is shown by
-+ "merge" style, shows the original contents).
++ branch.autoSetupMerge configuration variable is true.
+
+--orphan <new-branch>::
-+ Create a new 'orphan' branch, named <new-branch>, started from
-+ <start-point> and switch to it. See explanation of the same
-+ option in linkgit:git-checkout[1] for details.
++ Create a new 'orphan' branch, named <new-branch>. If
++ <start-point> is specified, the index and working tree are
++ adjusted to match it. Otherwise both are adjusted to contain no
++ tracked files.
+
+--ignore-other-worktrees::
+ git switch refuses when the wanted ref is already
@@ -303,15 +315,20 @@
+ the ref out anyway. In other words, the ref can be held by
+ more than one worktree.
+
++--ignore-in-progress::
++ git switch by default refuses when some operation is in
++ progress (e.g. "git rebase", "git am" ...). This option
++ overrides this safety check and allows switching.
++
+--recurse-submodules::
+--no-recurse-submodules::
-+ Using --recurse-submodules will update the content of all initialized
++ Using --recurse-submodules will update the content of all initialized
+ submodules according to the commit recorded in the superproject. If
+ local modifications in a submodule would be overwritten the checkout
-+ will fail unless -f is used. If nothing (or --no-recurse-submodules)
++ will fail unless -f is used. If nothing (or --no-recurse-submodules)
+ is used, the work trees of submodules will not be updated.
-+ Just like linkgit:git-submodule[1], this will detach the
-+ submodules HEAD.
++ Just like linkgit:git-submodule[1], this will detach HEAD of the
++ submodule.
+
+EXAMPLES
+--------
@@ -366,7 +383,7 @@
+------------
+
+If you want to start a new branch from a remote branch of the same
-+name, use -g:
++name:
+
+------------
+$ git switch -g new-topic
@@ -374,7 +391,7 @@
+Switched to a new branch 'new-topic'
+------------
+
-+To check out commit "HEAD~3" for temporary inspection or experiment ++To check out commit HEAD~3 for temporary inspection or experiment
+without creating a new branch:
+
+------------
@@ -391,7 +408,8 @@
+
+SEE ALSO
+--------
-+linkgit:git-checkout[1]
++linkgit:git-checkout[1],
++linkgit:git-branch[1]
+
+GIT
+---

 9:  5491932cc8 = 11:  c966bacfcc switch: better names for -b and -B
 -:  ---------- > 12:  bdb88bf9a9 switch: add --discard-changes
10:  e0f1247b09 = 13:  d5fe7f4bd0 switch: remove -l
11:  f7ff1a7df6 ! 14:  3bce4c521e switch: stop accepting pathspec
    @@ -11,9 +11,9 @@
      --- a/builtin/checkout.c
      +++ b/builtin/checkout.c
     @@
    - 	int count_checkout_paths;
      	int overlay_mode;
      	int no_dwim_new_local_branch;
    + 	int discard_changes;
     +	int accept_pathspec;
      
      	/*
12:  0750d63d38 ! 15:  dad0063fc4 switch: reject "do nothing" case
    @@ -17,8 +17,8 @@
      --- a/builtin/checkout.c
      +++ b/builtin/checkout.c
     @@
    - 	int overlay_mode;
      	int no_dwim_new_local_branch;
    + 	int discard_changes;
      	int accept_pathspec;
     +	int switch_branch_doing_nothing_is_ok;

13: bcd843146d ! 16: 41ca042917 switch: only allow explicit detached HEAD

    @@ -24,6 +24,36 @@
      	int writeout_stage;
      	int overwrite_ignore;
      	int ignore_skipworktree;
    +@@
    + 	return status;
    + }
    + 
    ++static void die_expecting_a_branch(const struct branch_info *branch_info)
    ++{
    ++	struct object_id oid;
    ++	char *to_free;
    ++
    ++	if (dwim_ref(branch_info->name, strlen(branch_info->name), &oid, &to_free) == 1) {
    ++		const char *ref = to_free;
    ++
    ++		if (skip_prefix(ref, "refs/tags/", &ref))
    ++			die(_("a branch is expected, got tag '%s'"), ref);
    ++		if (skip_prefix(ref, "refs/remotes/", &ref))
    ++			die(_("a branch is expected, got remote branch '%s'"), ref);
    ++		die(_("a branch is expected, got '%s'"), ref);
    ++	}
    ++	if (branch_info->commit)
    ++		die(_("a branch is expected, got commit '%s'"), branch_info->name);
    ++	/*
    ++	 * This case should never happen because we already die() on
    ++	 * non-commit, but just in case.
    ++	 */
    ++	die(_("a branch is expected, got '%s'"), branch_info->name);
    ++}
    ++
    + static int checkout_branch(struct checkout_opts *opts,
    + 			   struct branch_info *new_branch_info)
    + {
     @@
      	    !opts->force_detach)
      		die(_("missing branch or commit argument"));
    @@ -34,7 +64,7 @@
     +	    !opts->new_branch_force &&
     +	    new_branch_info->name &&
     +	    !new_branch_info->path)
    -+		die(_("a branch is expected, got %s"), new_branch_info->name);
    ++		die_expecting_a_branch(new_branch_info);
     +
      	if (new_branch_info->path && !opts->force_detach && !opts->new_branch &&
      	    !opts->ignore_other_worktrees) {
14:  d5cc55525d = 17:  a0b9f1b285 switch: add short option for --detach
15:  4a27400a58 ! 18:  3d254df104 switch: no implicit dwim, use --guess to dwim

@@ -1,15 +1,15 @@
Author: Nguyễn Thái Ngọc Duy <[email protected]>

- switch: no implicit dwim, use --guess to dwim
+ switch: implicit dwim, use --no-guess to disable it

- Similar to automatic detach, this behavior could be confusing because
- it can sometimes create a new branch without a user asking it to,
- especially when the user is still not aware about this feature.
+ This is already the default in git-checkout. The real change in here is
+ just minor cleanup. The main excuse is to explain why dwim is kept default.

- In the future, perhaps we could have a config key to disable these
- safety nets and let 'switch' do automatic detach or dwim
- again. But that will be opt-in after the user knows what is what. For
- now give a short option if you want to use it often.
+ Contrary to detach mode that is easy to get into and confusing to get
+ back out. Automatically creating a tracking branch often does not kick
+ in as often (you would need a branch of the same name on a remote). And
+ since the branch creation is reported clearly, the user should be able
+ to undo/delete it if it's unwanted.

diff --git a/Documentation/git-checkout.txt b/Documentation/git-checkout.txt --- a/Documentation/git-checkout.txt
@@ -41,7 +41,7 @@
rather expensive side-effects to show only the tracking information,
@@
Do not set up "upstream" configuration, even if the
- branch.autoSetupMerge configuration variable is true.
+ branch.autoSetupMerge configuration variable is true.

+--guess::
+--no-guess::
@@ -68,8 +68,8 @@
Create the new branch's reflog; see linkgit:git-branch[1] for details.
@@
- Just like linkgit:git-submodule[1], this will detach the
- submodules HEAD.
+ Just like linkgit:git-submodule[1], this will detach HEAD of the
+ submodule.

---no-guess::
- Do not attempt to create a branch if a remote tracking branch
@@ -88,9 +88,9 @@
int overlay_mode;
- int no_dwim_new_local_branch;
+ int dwim_new_local_branch;
+ int discard_changes;
int accept_pathspec;
int switch_branch_doing_nothing_is_ok;
-
@@
OPT_BOOL_F(0, "overwrite-ignore", &opts->overwrite_ignore,
N_("update ignored files (default)"),
@@ -145,15 +145,17 @@
N_("create and switch to a new branch")),
OPT_STRING('C', "force-create", &opts.new_branch_force, N_("branch"),
N_("create/reset and switch to a branch")),
-+ OPT_BOOL('g', "guess", &opts.dwim_new_local_branch,
++ OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
+ N_("second guess 'git switch <no-such-branch>'")),
+ OPT_BOOL(0, "discard-changes", &opts.discard_changes,
+ N_("throw away local modifications")),
OPT_END()
- };
+@@
int ret;

memset(&opts, 0, sizeof(opts));
- opts.no_dwim_new_local_branch = 0;
-+ opts.dwim_new_local_branch = 0;
++ opts.dwim_new_local_branch = 1;
opts.accept_pathspec = 0;
opts.switch_branch_doing_nothing_is_ok = 0;
opts.implicit_detach = 0;
16: f7dd33abe6 ! 19: c6ea203f36 switch: no worktree status unless real branch switch happens

    @@ -36,8 +36,8 @@
      --- a/builtin/checkout.c
      +++ b/builtin/checkout.c
     @@
    - #include "submodule.h"
    - #include "advice.h"
    + #include "unpack-trees.h"
    + #include "xdiff-interface.h"
      
     -static int checkout_optimize_new_branch;
     -
    @@ -45,7 +45,7 @@
      	N_("git checkout [<options>] <branch>"),
      	N_("git checkout [<options>] [<branch>] -- <file>..."),
     @@
    - 	int dwim_new_local_branch;
    + 	int discard_changes;
      	int accept_pathspec;
      	int switch_branch_doing_nothing_is_ok;
     -
    @@ -220,7 +220,7 @@
      	opts.implicit_detach = 1;
      
     @@
    - 	opts.dwim_new_local_branch = 0;
    + 	opts.dwim_new_local_branch = 1;
      	opts.accept_pathspec = 0;
      	opts.switch_branch_doing_nothing_is_ok = 0;
     +	opts.only_merge_on_switching_branches = 1;
 -:  ---------- > 20:  5c4effc7fd switch: reject if some operation is in progress
 -:  ---------- > 21:  a4afe6a999 switch: --orphan defaults to empty tree as HEAD
17:  5b182abea8 ! 22:  6cca78f835 t: add tests for switch
    @@ -31,12 +31,9 @@
     +	test_path_is_missing second.t
     +'
     +
    -+test_expect_success 'switch to a commit' '
    -+	test_must_fail git switch master^{commit}
    -+'
    -+
     +test_expect_success 'switch and detach' '
     +	test_when_finished git switch master &&
    ++	test_must_fail git switch master^{commit} &&
     +	git switch --detach master^{commit} &&
     +	test_must_fail git symbolic-ref HEAD
     +'
    @@ -60,6 +57,7 @@
     +test_expect_success 'force create branch from HEAD' '
     +	test_when_finished git switch master &&
     +	git switch --detach master &&
    ++	test_must_fail git switch -c temp &&
     +	git switch -C temp &&
     +	test_cmp_rev master refs/heads/temp &&
     +	echo refs/heads/temp >expected-branch &&
    @@ -67,12 +65,15 @@
     +	test_cmp expected-branch actual-branch
     +'
     +
    -+test_expect_success 'new orphan branch' '
    ++test_expect_success 'new orphan branch from empty' '
     +	test_when_finished git switch master &&
    -+	git switch --orphan new-orphan master^ &&
    ++	git switch --orphan new-orphan &&
     +	test_commit orphan &&
     +	git cat-file commit refs/heads/new-orphan >commit &&
    -+	! grep ^parent commit
    ++	! grep ^parent commit &&
    ++	git ls-files >tracked-files &&
    ++	echo orphan.t >expected &&
    ++	test_cmp expected tracked-files
     +'
     +
     +test_expect_success 'switching ignores file of same branch name' '
    @@ -81,16 +82,25 @@
     +	git switch first-branch &&
     +	echo refs/heads/first-branch >expected &&
     +	git symbolic-ref HEAD >actual &&
    -+	test_commit expected actual
    ++	test_cmp expected actual
     +'
     +
     +test_expect_success 'guess and create branch ' '
     +	test_when_finished git switch master &&
    -+	test_must_fail git switch foo &&
    -+	git switch --guess foo &&
    ++	test_must_fail git switch --no-guess foo &&
    ++	git switch foo &&
     +	echo refs/heads/foo >expected &&
     +	git symbolic-ref HEAD >actual &&
     +	test_cmp expected actual
     +'
     +
    ++test_expect_success 'switching when something is in progress' '
    ++	test_when_finished rm -f .git/MERGE_HEAD &&
    ++	# fake a merge-in-progress
    ++	cp .git/HEAD .git/MERGE_HEAD &&
    ++	test_must_fail git switch -d @^ &&
    ++	git switch --ignore-in-progress -d @^ &&
    ++	git switch -
    ++'
    ++
     +test_done
18:  1575064fe6 ! 23:  e5e6f9d6f1 completion: support switch
    @@ -10,6 +10,16 @@
      diff --git a/contrib/completion/git-completion.bash b/contrib/completion/git-completion.bash
      --- a/contrib/completion/git-completion.bash
      +++ b/contrib/completion/git-completion.bash
    +@@
    + #   GIT_COMPLETION_CHECKOUT_NO_GUESS
    + #
    + #     When set to "1", do not include "DWIM" suggestions in git-checkout
    +-#     completion (e.g., completing "foo" when "origin/foo" exists).
    ++#     and git-switch completion (e.g., completing "foo" when "origin/foo"
    ++#     exists).
    + 
    + case "$COMP_WORDBREAKS" in
    + *:*) : great ;;
     @@
      	__git_complete_index_file "$complete_opt"
      }
    @@ -24,15 +34,22 @@
     +		__gitcomp_builtin switch
     +		;;
     +	*)
    -+		# check if ---guess was specified to enable DWIM mode
    -+		local track_opt= only_local_ref=n
    -+		if [ -n "$(__git_find_on_cmdline "-g --guess")" ]; then
    ++		# check if --track, --no-track, or --no-guess was specified
    ++		# if so, disable DWIM mode
    ++		local track_opt="--track" only_local_ref=n
    ++		if [ "$GIT_COMPLETION_CHECKOUT_NO_GUESS" = "1" ] ||
    ++		   [ -n "$(__git_find_on_cmdline "--track --no-track --no-guess")" ]; then
    ++			track_opt=''
    ++		fi
    ++		# explicit --guess enables DWIM mode regardless of
    ++		# $GIT_COMPLETION_CHECKOUT_NO_GUESS
    ++		if [ -n "$(__git_find_on_cmdline "--guess")" ]; then
     +			track_opt='--track'
     +		fi
     +		if [ -z "$(__git_find_on_cmdline "-d --detach")" ]; then
     +			only_local_ref=y
     +		fi
    -+		if [ $only_local_ref = y -a -n "$track_opt"]; then
    ++		if [ $only_local_ref = y -a -z "$track_opt" ]; then
     +			__gitcomp_direct "$(__git_heads "" "$cur" " ")"
     +		else
     +			__git_complete_refs $track_opt

19: 8ed01ad0c5 ! 24: 807e8bc50b doc: promote "git switch"
@@ -647,23 +647,28 @@
void detach_advice(const char *new_name)
{
const char *fmt =
-- _("Note: checking out '%s'.\n\n"
+- _("Note: checking out '%s'.\n"
+ _("Note: switching to '%s'.\n"
-+ "\n"
+ "\n"
"You are in 'detached HEAD' state. You can look around, make experimental\n" "changes and commit them, and you can discard any commits you make in this\n"
-- "state without impacting any branches by performing another checkout.\n\n"
+- "state without impacting any branches by performing another checkout.\n"
+ "state without impacting any branches by switching back to a branch.\n"
-+ "\n"
+ "\n"
"If you want to create a new branch to retain commits you create, you may\n"
-- "do so (now or later) by using -b with the checkout command again. Example:\n\n"
-- " git checkout -b <new-branch-name>\n\n");
+- "do so (now or later) by using -b with the checkout command again. Example:\n"
+ "do so (now or later) by using -c with the switch command. Example:\n"
-+ "\n"
-+ " git switch -c <new-branch-name>\n\n");
+ "\n"
+- " git checkout -b <new-branch-name>\n"
++ " git switch -c <new-branch-name>\n"
+ "\n"
+ "Or undo this checkout with:\n"
+ "\n"
+- " git checkout -\n"
++ " git switch -\n"
+ "\n"
+ "Turn off this advice by setting config variable advice.detachedHead to false\n\n");

- fprintf(stderr, fmt, new_name);
- }

diff --git a/sha1-name.c b/sha1-name.c
--- a/sha1-name.c
@@ -700,8 +705,13 @@
- git checkout -b <new-branch-name>
+ git switch -c <new-branch-name>

- HEAD is now at \$commit three
- EOF
+ Or undo this checkout with:
+
+- git checkout -
++ git switch -
+
+ Turn off this advice by setting config variable advice.detachedHead to false
+
@@

# The first detach operation is more chatty than the following ones.
@@ -721,5 +731,10 @@
- git checkout -b <new-branch-name>
+ git switch -c <new-branch-name>

- HEAD is now at \$commit... three
- EOF
+ Or undo this checkout with:
+
+- git checkout -
++ git switch -
+
+ Turn off this advice by setting config variable advice.detachedHead to false
+

Signature · 1 line
2.21.0.548.gd3c7d92dc2
#181 lore raw

PATCH v4 1/26 git-checkout.txt: spell out --no-option

It's easier to search for and also less cryptic.

---
 Documentation/git-checkout.txt | 11 +++++++----
 1 file changed, 7 insertions(+), 4 deletions(-)
Documentation/git-checkout.txt +7 -4
index f179b43732..99c8c0dc0f 100644
@@ -118,7 +118,8 @@ OPTIONS
 --quiet::
 	Quiet, suppress feedback messages.
 
---[no-]progress::
+--progress::
+--no-progress::
 	Progress status is reported on the standard error stream
 	by default when it is attached to a terminal, unless `--quiet`
 	is specified. This flag enables progress reporting even if not
@@ -262,7 +263,7 @@ edits from your current working tree. See the ``Interactive Mode''
 section of linkgit:git-add[1] to learn how to operate the `--patch` mode.
 +
 Note that this option uses the no overlay mode by default (see also
-`--[no-]overlay`), and currently doesn't support overlay mode.
+`--overlay`), and currently doesn't support overlay mode.
 
 --ignore-other-worktrees::
 	`git checkout` refuses when the wanted ref is already checked
@@ -270,7 +271,8 @@ Note that this option uses the no overlay mode by default (see also
 	out anyway. In other words, the ref can be held by more than one
 	worktree.
 
---[no-]recurse-submodules::
+--recurse-submodules::
+--no-recurse-submodules::
 	Using --recurse-submodules will update the content of all initialized
 	submodules according to the commit recorded in the superproject. If
 	local modifications in a submodule would be overwritten the checkout
@@ -283,7 +285,8 @@ Note that this option uses the no overlay mode by default (see also
 	Do not attempt to create a branch if a remote tracking branch
 	of the same name exists.
 
---[no-]overlay::
+--overlay::
+--no-overlay::
 	In the default overlay mode, `git checkout` never
 	removes files from the index or the working tree.  When
 	specifying `--no-overlay`, files that appear in the index and
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#182 lore raw

PATCH v4 2/26 git-checkout.txt: fix one syntax line

In reply to Nguyễn Thái Ngọc Duy

<branch> can be omitted in this syntax, and it's actually documented a few paragraphs down:

You could omit <branch>, in which case the command degenerates to "check out the current branch", which is a glorified no-op with rather expensive side-effects to show only the tracking information, if exists, for the current branch.

---
 Documentation/git-checkout.txt | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
Documentation/git-checkout.txt +1 -1
index 99c8c0dc0f..28817cfa41 100644
@@ -23,7 +23,7 @@ or the specified tree.  If no paths are given, 'git checkout' will
 also update `HEAD` to set the specified branch as the current
 branch.
 
-'git checkout' <branch>::
+'git checkout' [<branch>]::
 	To prepare for working on <branch>, switch to it by updating
 	the index and the files in the working tree, and by pointing
 	HEAD at the branch. Local modifications to the files in the
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#183 lore raw

PATCH v4 3/26 doc: document --overwrite-ignore

In reply to Nguyễn Thái Ngọc Duy

I added this option in git-checkout and git-merge in c1d7036b6b (checkout,merge: disallow overwriting ignored files with --no-overwrite-ignore - 2011-11-27) but did not remember to update documentation. This completes that commit.

---
 Documentation/git-checkout.txt | 14 ++++++++++----
 Documentation/git-merge.txt    |  5 +++++
 2 files changed, 15 insertions(+), 4 deletions(-)
Documentation/git-checkout.txt +10 -4
index 28817cfa41..82e0f81869 100644
@@ -271,15 +271,21 @@ Note that this option uses the no overlay mode by default (see also
 	out anyway. In other words, the ref can be held by more than one
 	worktree.
 
+--overwrite-ignore::
+--no-overwrite-ignore::
+	Silently overwrite ignored files when switching branches. This
+	is the default behavior. Use `--no-overwrite-ignore` to abort
+	the operation when the new branch contains ignored files.
+
 --recurse-submodules::
 --no-recurse-submodules::
-	Using --recurse-submodules will update the content of all initialized
+	Using `--recurse-submodules` will update the content of all initialized
 	submodules according to the commit recorded in the superproject. If
 	local modifications in a submodule would be overwritten the checkout
-	will fail unless `-f` is used. If nothing (or --no-recurse-submodules)
+	will fail unless `-f` is used. If nothing (or `--no-recurse-submodules`)
 	is used, the work trees of submodules will not be updated.
-	Just like linkgit:git-submodule[1], this will detach the
-	submodules HEAD.
+	Just like linkgit:git-submodule[1], this will detach `HEAD` of the
+	submodule.
 
 --no-guess::
 	Do not attempt to create a branch if a remote tracking branch
Documentation/git-merge.txt +5 -0
index 4cc86469f3..6a9163d8fe 100644
@@ -87,6 +87,11 @@ will be appended to the specified message.
 	Allow the rerere mechanism to update the index with the
 	result of auto-conflict resolution if possible.
 
+--overwrite-ignore::
+--no-overwrite-ignore::
+	Silently overwrite ignored files from the merge result. This
+	is the default behavior. Use `--no-overwrite-ignore` to abort.
+
 --abort::
 	Abort the current conflict resolution process, and
 	try to reconstruct the pre-merge state.
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#184 lore raw

Re: [PATCH v4 03/26] doc: document --overwrite-ignore

Quoted 15 lines · Nguyễn Thái Ngọc Duy

I added this option in git-checkout and git-merge in c1d7036b6b (checkout,merge: disallow overwriting ignored files with --no-overwrite-ignore - 2011-11-27) but did not remember to update documentation. This completes that commit.

+--overwrite-ignore::
+--no-overwrite-ignore::
Documentation/git-checkout.txt +4 -1
+       Silently overwrite ignored files when switching branches. This
+       is the default behavior. Use `--no-overwrite-ignore` to abort
+       the operation when the new branch contains ignored files.
+
 --recurse-submodules::
 --no-recurse-submodules::
-       Using --recurse-submodules will update the content of all initialized

Documentation/git-checkout.txt Note that this option uses the no overlay mode by default (see also · line 288

Quoted 10 lines
Documentation/git-checkout.txt +4 -3
+       Using `--recurse-submodules` will update the content of all initialized
        submodules according to the commit recorded in the superproject. If
        local modifications in a submodule would be overwritten the checkout
-       will fail unless `-f` is used. If nothing (or --no-recurse-submodules)
+       will fail unless `-f` is used. If nothing (or `--no-recurse-submodules`)
        is used, the work trees of submodules will not be updated.
-       Just like linkgit:git-submodule[1], this will detach the
-       submodules HEAD.
+       Just like linkgit:git-submodule[1], this will detach `HEAD` of the
+       submodule.

All of this --recurse-submodules stuff seems to have have ended up in the wrong commit.

Martin

#185 lore raw

PATCH v4 4/26 git-checkout.txt: fix monospace typeset

In reply to Nguyễn Thái Ngọc Duy

Add backticks where we have none, replace single quotes with backticks and replace double-quotes. Drop double-quotes from nested constructions such as "@{-1}". Add a missing possessive apostrophe after the word "submodules" while at it.

---
 Documentation/git-checkout.txt | 154 ++++++++++++++++-----------------
 1 file changed, 77 insertions(+), 77 deletions(-)
Documentation/git-checkout.txt +77 -77
index 82e0f81869..bf90966c95 100644
@@ -24,14 +24,14 @@ also update `HEAD` to set the specified branch as the current
 branch.
 
 'git checkout' [<branch>]::
-	To prepare for working on <branch>, switch to it by updating
+	To prepare for working on `<branch>`, switch to it by updating
 	the index and the files in the working tree, and by pointing
-	HEAD at the branch. Local modifications to the files in the
+	`HEAD` at the branch. Local modifications to the files in the
 	working tree are kept, so that they can be committed to the
-	<branch>.
+	`<branch>`.
 +
-If <branch> is not found but there does exist a tracking branch in
-exactly one remote (call it <remote>) with a matching name, treat as
+If `<branch>` is not found but there does exist a tracking branch in
+exactly one remote (call it `<remote>`) with a matching name, treat as
 equivalent to
 +
 ------------
@@ -47,7 +47,7 @@ branches from there if `<branch>` is ambiguous but exists on the
 'origin' remote. See also `checkout.defaultRemote` in
 linkgit:git-config[1].
 +
-You could omit <branch>, in which case the command degenerates to
+You could omit `<branch>`, in which case the command degenerates to
 "check out the current branch", which is a glorified no-op with
 rather expensive side-effects to show only the tracking information,
 if exists, for the current branch.
@@ -61,7 +61,7 @@ if exists, for the current branch.
 	`--track` without `-b` implies branch creation; see the
 	description of `--track` below.
 +
-If `-B` is given, <new_branch> is created if it doesn't exist; otherwise, it
+If `-B` is given, `<new_branch>` is created if it doesn't exist; otherwise, it
 is reset. This is the transactional equivalent of
 +
 ------------
@@ -75,25 +75,25 @@ successful.
 'git checkout' --detach [<branch>]::
 'git checkout' [--detach] <commit>::
 
-	Prepare to work on top of <commit>, by detaching HEAD at it
+	Prepare to work on top of `<commit>`, by detaching `HEAD` at it
 	(see "DETACHED HEAD" section), and updating the index and the
 	files in the working tree.  Local modifications to the files
 	in the working tree are kept, so that the resulting working
 	tree will be the state recorded in the commit plus the local
 	modifications.
 +
-When the <commit> argument is a branch name, the `--detach` option can
-be used to detach HEAD at the tip of the branch (`git checkout
-<branch>` would check out that branch without detaching HEAD).
+When the `<commit>` argument is a branch name, the `--detach` option can
+be used to detach `HEAD` at the tip of the branch (`git checkout
+<branch>` would check out that branch without detaching `HEAD`).
 +
-Omitting <branch> detaches HEAD at the tip of the current branch.
+Omitting `<branch>` detaches `HEAD` at the tip of the current branch.
 
 'git checkout' [<tree-ish>] [--] <pathspec>...::
 
 	Overwrite paths in the working tree by replacing with the
-	contents in the index or in the <tree-ish> (most often a
-	commit).  When a <tree-ish> is given, the paths that
-	match the <pathspec> are updated both in the index and in
+	contents in the index or in the `<tree-ish>` (most often a
+	commit).  When a `<tree-ish>` is given, the paths that
+	match the `<pathspec>` are updated both in the index and in
 	the working tree.
 +
 The index may contain unmerged entries because of a previous failed merge.
@@ -128,7 +128,7 @@ OPTIONS
 -f::
 --force::
 	When switching branches, proceed even if the index or the
-	working tree differs from HEAD.  This is used to throw away
+	working tree differs from `HEAD`.  This is used to throw away
 	local changes.
 +
 When checking out paths from the index, do not fail upon unmerged
@@ -155,12 +155,12 @@ on your side branch as `theirs` (i.e. "one contributor's work on top
 of it").
 
 -b <new_branch>::
-	Create a new branch named <new_branch> and start it at
-	<start_point>; see linkgit:git-branch[1] for details.
+	Create a new branch named `<new_branch>` and start it at
+	`<start_point>`; see linkgit:git-branch[1] for details.
 
 -B <new_branch>::
-	Creates the branch <new_branch> and start it at <start_point>;
-	if it already exists, then reset it to <start_point>. This is
+	Creates the branch `<new_branch>` and start it at `<start_point>`;
+	if it already exists, then reset it to `<start_point>`. This is
 	equivalent to running "git branch" with "-f"; see
 	linkgit:git-branch[1] for details.
 
@@ -173,15 +173,15 @@ If no `-b` option is given, the name of the new branch will be
 derived from the remote-tracking branch, by looking at the local part of
 the refspec configured for the corresponding remote, and then stripping
 the initial part up to the "*".
-This would tell us to use "hack" as the local branch when branching
-off of "origin/hack" (or "remotes/origin/hack", or even
-"refs/remotes/origin/hack").  If the given name has no slash, or the above
+This would tell us to use `hack` as the local branch when branching
+off of `origin/hack` (or `remotes/origin/hack`, or even
+`refs/remotes/origin/hack`).  If the given name has no slash, or the above
 guessing results in an empty name, the guessing is aborted.  You can
 explicitly give a name with `-b` in such a case.
 
 --no-track::
 	Do not set up "upstream" configuration, even if the
-	branch.autoSetupMerge configuration variable is true.
+	`branch.autoSetupMerge` configuration variable is true.
 
 -l::
 	Create the new branch's reflog; see linkgit:git-branch[1] for
@@ -190,21 +190,21 @@ explicitly give a name with `-b` in such a case.
 --detach::
 	Rather than checking out a branch to work on it, check out a
 	commit for inspection and discardable experiments.
-	This is the default behavior of "git checkout <commit>" when
-	<commit> is not a branch name.  See the "DETACHED HEAD" section
+	This is the default behavior of `git checkout <commit>` when
+	`<commit>` is not a branch name.  See the "DETACHED HEAD" section
 	below for details.
 
 --orphan <new_branch>::
-	Create a new 'orphan' branch, named <new_branch>, started from
-	<start_point> and switch to it.  The first commit made on this
+	Create a new 'orphan' branch, named `<new_branch>`, started from
+	`<start_point>` and switch to it.  The first commit made on this
 	new branch will have no parents and it will be the root of a new
 	history totally disconnected from all the other branches and
 	commits.
 +
 The index and the working tree are adjusted as if you had previously run
-"git checkout <start_point>".  This allows you to start a new history
-that records a set of paths similar to <start_point> by easily running
-"git commit -a" to make the root commit.
+`git checkout <start_point>`.  This allows you to start a new history
+that records a set of paths similar to `<start_point>` by easily running
+`git commit -a` to make the root commit.
 +
 This can be useful when you want to publish the tree from a commit
 without exposing its full history. You might want to do this to publish
@@ -213,17 +213,17 @@ whose full history contains proprietary or otherwise encumbered bits of
 code.
 +
 If you want to start a disconnected history that records a set of paths
-that is totally different from the one of <start_point>, then you should
+that is totally different from the one of `<start_point>`, then you should
 clear the index and the working tree right after creating the orphan
-branch by running "git rm -rf ." from the top level of the working tree.
+branch by running `git rm -rf .` from the top level of the working tree.
 Afterwards you will be ready to prepare your new files, repopulating the
 working tree, by copying them from elsewhere, extracting a tarball, etc.
 
 --ignore-skip-worktree-bits::
 	In sparse checkout mode, `git checkout -- <paths>` would
-	update only entries matched by <paths> and sparse patterns
-	in $GIT_DIR/info/sparse-checkout. This option ignores
-	the sparse patterns and adds back any files in <paths>.
+	update only entries matched by `<paths>` and sparse patterns
+	in `$GIT_DIR/info/sparse-checkout`. This option ignores
+	the sparse patterns and adds back any files in `<paths>`.
 
 -m::
 --merge::
@@ -245,18 +245,18 @@ When checking out paths from the index, this option lets you recreate
 the conflicted merge in the specified paths.
 
 --conflict=<style>::
-	The same as --merge option above, but changes the way the
+	The same as `--merge` option above, but changes the way the
 	conflicting hunks are presented, overriding the
-	merge.conflictStyle configuration variable.  Possible values are
+	`merge.conflictStyle` configuration variable.  Possible values are
 	"merge" (default) and "diff3" (in addition to what is shown by
 	"merge" style, shows the original contents).
 
 -p::
 --patch::
 	Interactively select hunks in the difference between the
-	<tree-ish> (or the index, if unspecified) and the working
+	`<tree-ish>` (or the index, if unspecified) and the working
 	tree.  The chosen hunks are then applied in reverse to the
-	working tree (and if a <tree-ish> was specified, the index).
+	working tree (and if a `<tree-ish>` was specified, the index).
 +
 This means that you can use `git checkout -p` to selectively discard
 edits from your current working tree. See the ``Interactive Mode''
@@ -296,21 +296,21 @@ Note that this option uses the no overlay mode by default (see also
 	In the default overlay mode, `git checkout` never
 	removes files from the index or the working tree.  When
 	specifying `--no-overlay`, files that appear in the index and
-	working tree, but not in <tree-ish> are removed, to make them
-	match <tree-ish> exactly.
+	working tree, but not in `<tree-ish>` are removed, to make them
+	match `<tree-ish>` exactly.
 
 <branch>::
 	Branch to checkout; if it refers to a branch (i.e., a name that,
 	when prepended with "refs/heads/", is a valid ref), then that
 	branch is checked out. Otherwise, if it refers to a valid
-	commit, your HEAD becomes "detached" and you are no longer on
+	commit, your `HEAD` becomes "detached" and you are no longer on
 	any branch (see below for details).
 +
-You can use the `"@{-N}"` syntax to refer to the N-th last
+You can use the `@{-N}` syntax to refer to the N-th last
 branch/commit checked out using "git checkout" operation. You may
-also specify `-` which is synonymous to `"@{-1}"`.
+also specify `-` which is synonymous to `@{-1}`.
 +
-As a special case, you may use `"A...B"` as a shortcut for the
+As a special case, you may use `A...B` as a shortcut for the
 merge base of `A` and `B` if there is exactly one merge base. You can
 leave out at most one of `A` and `B`, in which case it defaults to `HEAD`.
 
@@ -319,7 +319,7 @@ leave out at most one of `A` and `B`, in which case it defaults to `HEAD`.
 
 <start_point>::
 	The name of a commit at which to start the new branch; see
-	linkgit:git-branch[1] for details. Defaults to HEAD.
+	linkgit:git-branch[1] for details. Defaults to `HEAD`.
 
 <tree-ish>::
 	Tree to checkout from (when paths are given). If not specified,
@@ -329,9 +329,9 @@ leave out at most one of `A` and `B`, in which case it defaults to `HEAD`.
 
 DETACHED HEAD
 -------------
-HEAD normally refers to a named branch (e.g. 'master'). Meanwhile, each
+`HEAD` normally refers to a named branch (e.g. `master`). Meanwhile, each
 branch refers to a specific commit. Let's look at a repo with three
-commits, one of them tagged, and with branch 'master' checked out:
+commits, one of them tagged, and with branch `master` checked out:
 
 ------------
            HEAD (refers to branch 'master')
@@ -344,10 +344,10 @@ a---b---c  branch 'master' (refers to commit 'c')
 ------------
 
 When a commit is created in this state, the branch is updated to refer to
-the new commit. Specifically, 'git commit' creates a new commit 'd', whose
-parent is commit 'c', and then updates branch 'master' to refer to new
-commit 'd'. HEAD still refers to branch 'master' and so indirectly now refers
-to commit 'd':
+the new commit. Specifically, 'git commit' creates a new commit `d`, whose
+parent is commit `c`, and then updates branch `master` to refer to new
+commit `d`. `HEAD` still refers to branch `master` and so indirectly now refers
+to commit `d`:
 
 ------------
 $ edit; git add; git commit
@@ -364,7 +364,7 @@ a---b---c---d  branch 'master' (refers to commit 'd')
 It is sometimes useful to be able to checkout a commit that is not at
 the tip of any named branch, or even to create a new commit that is not
 referenced by a named branch. Let's look at what happens when we
-checkout commit 'b' (here we show two ways this may be done):
+checkout commit `b` (here we show two ways this may be done):
 
 ------------
 $ git checkout v2.0  # or
@@ -379,9 +379,9 @@ a---b---c---d  branch 'master' (refers to commit 'd')
   tag 'v2.0' (refers to commit 'b')
 ------------
 
-Notice that regardless of which checkout command we use, HEAD now refers
-directly to commit 'b'. This is known as being in detached HEAD state.
-It means simply that HEAD refers to a specific commit, as opposed to
+Notice that regardless of which checkout command we use, `HEAD` now refers
+directly to commit `b`. This is known as being in detached `HEAD` state.
+It means simply that `HEAD` refers to a specific commit, as opposed to
 referring to a named branch. Let's see what happens when we create a commit:
 
 ------------
@@ -398,7 +398,7 @@ a---b---c---d  branch 'master' (refers to commit 'd')
   tag 'v2.0' (refers to commit 'b')
 ------------
 
-There is now a new commit 'e', but it is referenced only by HEAD. We can
+There is now a new commit `e`, but it is referenced only by `HEAD`. We can
 of course add yet another commit in this state:
 
 ------------
@@ -416,7 +416,7 @@ a---b---c---d  branch 'master' (refers to commit 'd')
 ------------
 
 In fact, we can perform all the normal Git operations. But, let's look
-at what happens when we then checkout master:
+at what happens when we then checkout `master`:
 
 ------------
 $ git checkout master
@@ -431,9 +431,9 @@ a---b---c---d  branch 'master' (refers to commit 'd')
 ------------
 
 It is important to realize that at this point nothing refers to commit
-'f'. Eventually commit 'f' (and by extension commit 'e') will be deleted
+`f`. Eventually commit `f` (and by extension commit `e`) will be deleted
 by the routine Git garbage collection process, unless we create a reference
-before that happens. If we have not yet moved away from commit 'f',
+before that happens. If we have not yet moved away from commit `f`,
 any of these will create a reference to it:
 
 ------------
@@ -442,19 +442,19 @@ $ git branch foo        <2>
 $ git tag foo           <3>
 ------------
 
-<1> creates a new branch 'foo', which refers to commit 'f', and then
-    updates HEAD to refer to branch 'foo'. In other words, we'll no longer
-    be in detached HEAD state after this command.
+<1> creates a new branch `foo`, which refers to commit `f`, and then
+    updates `HEAD` to refer to branch `foo`. In other words, we'll no longer
+    be in detached `HEAD` state after this command.
 
-<2> similarly creates a new branch 'foo', which refers to commit 'f',
-    but leaves HEAD detached.
+<2> similarly creates a new branch `foo`, which refers to commit `f`,
+    but leaves `HEAD` detached.
 
-<3> creates a new tag 'foo', which refers to commit 'f',
-    leaving HEAD detached.
+<3> creates a new tag `foo`, which refers to commit `f`,
+    leaving `HEAD` detached.
 
-If we have moved away from commit 'f', then we must first recover its object
+If we have moved away from commit `f`, then we must first recover its object
 name (typically by using git reflog), and then we can create a reference to
-it. For example, to see the last two commits to which HEAD referred, we
+it. For example, to see the last two commits to which `HEAD` referred, we
 can use either of these commands:
 
 ------------
@@ -465,12 +465,12 @@ $ git log -g -2 HEAD
 ARGUMENT DISAMBIGUATION
 -----------------------
 
-When there is only one argument given and it is not `--` (e.g. "git
-checkout abc"), and when the argument is both a valid `<tree-ish>`
-(e.g. a branch "abc" exists) and a valid `<pathspec>` (e.g. a file
+When there is only one argument given and it is not `--` (e.g. `git
+checkout abc`), and when the argument is both a valid `<tree-ish>`
+(e.g. a branch `abc` exists) and a valid `<pathspec>` (e.g. a file
 or a directory whose name is "abc" exists), Git would usually ask
 you to disambiguate.  Because checking out a branch is so common an
-operation, however, "git checkout abc" takes "abc" as a `<tree-ish>`
+operation, however, `git checkout abc` takes "abc" as a `<tree-ish>`
 in such a situation.  Use `git checkout -- <pathspec>` if you want
 to checkout these paths out of the index.
 
@@ -478,7 +478,7 @@ EXAMPLES
 --------
 
 . The following sequence checks out the `master` branch, reverts
-  the `Makefile` to two revisions back, deletes hello.c by
+  the `Makefile` to two revisions back, deletes `hello.c` by
   mistake, and gets it back from the index.
 +
 ------------
@@ -490,7 +490,7 @@ $ git checkout hello.c            <3>
 +
 <1> switch branch
 <2> take a file out of another commit
-<3> restore hello.c from the index
+<3> restore `hello.c` from the index
 +
 If you want to check out _all_ C source files out of the index,
 you can say
@@ -519,7 +519,7 @@ $ git checkout -- hello.c
 $ git checkout mytopic
 ------------
 +
-However, your "wrong" branch and correct "mytopic" branch may
+However, your "wrong" branch and correct `mytopic` branch may
 differ in files that you have modified locally, in which case
 the above checkout would fail like this:
 +
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#186 lore raw

Re: [PATCH v4 04/26] git-checkout.txt: fix monospace typeset

Quoted 5 lines · Nguyễn Thái Ngọc Duy

Add backticks where we have none, replace single quotes with backticks and replace double-quotes. Drop double-quotes from nested constructions such as "@{-1}". Add a missing possessive apostrophe after the word "submodules" while at it.

Assuming you move those "submodules" hunks from an earlier commit, this last part needs some tweaking since you're not adding a "'", but you actually rephrase the docs to avoid a buggy AsciiDoc rendering. (And if a while-at-it needs too much explaining, maybe just skip it altogether? I dunno.)

Other than some things appearing in the wrong commit(?), this matches the "how about this?" I sent for v3 and our discussion of that.

Martin

#187 lore raw

PATCH v4 5/26 t: rename t2014-switch.sh to t2014-checkout-switch.sh

In reply to Nguyễn Thái Ngọc Duy

The old name does not really say that this is about 'checkout -b'. See 49d833dc07 (Revert "checkout branch: prime cache-tree fully" - 2009-05-12) for more information

---
 t/{t2014-switch.sh => t2014-checkout-switch.sh} | 0
 1 file changed, 0 insertions(+), 0 deletions(-)
t/t2014-checkout-switch.sh renamed from t/t2014-switch.sh +0 -0
similarity index 100%
rename from t/t2014-switch.sh
rename to t/t2014-checkout-switch.sh
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#188 lore raw

PATCH v4 6/26 checkout: advice how to get out of detached HEAD mode

In reply to Nguyễn Thái Ngọc Duy

Detached HEAD mode is considered dangerous and confusing for newcomers and we print a big block of warning how to move forward. But we should also suggest the user the way to get out of it if they get into detached HEAD by mistake.

While at there, I also suggest how to turn the advice off. This is another thing I find annoying with advices and should be dealt with in a more generic way. But that may require some refactoring in advice.c first.

---
 advice.c                   | 17 +++++++++++++----
 t/t2020-checkout-detach.sh | 12 ++++++++++++
 2 files changed, 25 insertions(+), 4 deletions(-)
advice.c +13 -4
index 567209aa79..b224825637 100644
@@ -191,13 +191,22 @@ void NORETURN die_conclude_merge(void)
 void detach_advice(const char *new_name)
 {
 	const char *fmt =
-	_("Note: checking out '%s'.\n\n"
+	_("Note: checking out '%s'.\n"
+	"\n"
 	"You are in 'detached HEAD' state. You can look around, make experimental\n"
 	"changes and commit them, and you can discard any commits you make in this\n"
-	"state without impacting any branches by performing another checkout.\n\n"
+	"state without impacting any branches by performing another checkout.\n"
+	"\n"
 	"If you want to create a new branch to retain commits you create, you may\n"
-	"do so (now or later) by using -b with the checkout command again. Example:\n\n"
-	"  git checkout -b <new-branch-name>\n\n");
+	"do so (now or later) by using -b with the checkout command again. Example:\n"
+	"\n"
+	"  git checkout -b <new-branch-name>\n"
+	"\n"
+	"Or undo this checkout with:\n"
+	"\n"
+	"  git checkout -\n"
+	"\n"
+	"Turn off this advice by setting config variable advice.detachedHead to false\n\n");
 
 	fprintf(stderr, fmt, new_name);
 }
t/t2020-checkout-detach.sh +12 -0
index 1fa670625c..743c7248a2 100755
@@ -206,6 +206,12 @@ test_expect_success 'describe_detached_head prints no SHA-1 ellipsis when not as
 
 	  git checkout -b <new-branch-name>
 
+	Or undo this checkout with:
+
+	  git checkout -
+
+	Turn off this advice by setting config variable advice.detachedHead to false
+
 	HEAD is now at \$commit three
 	EOF
 
@@ -282,6 +288,12 @@ test_expect_success 'describe_detached_head does print SHA-1 ellipsis when asked
 
 	  git checkout -b <new-branch-name>
 
+	Or undo this checkout with:
+
+	  git checkout -
+
+	Turn off this advice by setting config variable advice.detachedHead to false
+
 	HEAD is now at \$commit... three
 	EOF
 
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#189 lore raw

PATCH v4 7/26 checkout: keep most #include sorted

In reply to Nguyễn Thái Ngọc Duy

The include list becomes very long and frankly a bit unorganized. With the exception of builtin.h, cache.h or git-compat-util.h which have to come first, keep the rest sorted.

---
 builtin/checkout.c | 34 +++++++++++++++++-----------------
 1 file changed, 17 insertions(+), 17 deletions(-)
builtin/checkout.c +17 -17
index 0e6037b296..f7801db2fb 100644
@@ -1,30 +1,30 @@
 #define USE_THE_INDEX_COMPATIBILITY_MACROS
 #include "builtin.h"
-#include "config.h"
+#include "advice.h"
+#include "blob.h"
+#include "branch.h"
+#include "cache-tree.h"
 #include "checkout.h"
+#include "commit.h"
+#include "config.h"
+#include "diff.h"
+#include "dir.h"
+#include "ll-merge.h"
 #include "lockfile.h"
+#include "merge-recursive.h"
+#include "object-store.h"
 #include "parse-options.h"
 #include "refs.h"
-#include "object-store.h"
-#include "commit.h"
+#include "remote.h"
+#include "resolve-undo.h"
+#include "revision.h"
+#include "run-command.h"
+#include "submodule.h"
+#include "submodule-config.h"
 #include "tree.h"
 #include "tree-walk.h"
-#include "cache-tree.h"
 #include "unpack-trees.h"
-#include "dir.h"
-#include "run-command.h"
-#include "merge-recursive.h"
-#include "branch.h"
-#include "diff.h"
-#include "revision.h"
-#include "remote.h"
-#include "blob.h"
 #include "xdiff-interface.h"
-#include "ll-merge.h"
-#include "resolve-undo.h"
-#include "submodule-config.h"
-#include "submodule.h"
-#include "advice.h"
 
 static int checkout_optimize_new_branch;
 
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#190 lore raw

PATCH v4 8/26 checkout: factor out some code in parse_branchname_arg()

In reply to Nguyễn Thái Ngọc Duy

This is in preparation for the new command restore, which also needs to parse opts->source_tree but does not need all the disambiguation logic.

---
 builtin/checkout.c | 51 ++++++++++++++++++++++++++++------------------
 1 file changed, 31 insertions(+), 20 deletions(-)
builtin/checkout.c +31 -20
index f7801db2fb..1ce0446bc6 100644
@@ -1081,6 +1081,34 @@ static int git_checkout_config(const char *var, const char *value, void *cb)
 	return git_xmerge_config(var, value, NULL);
 }
 
+static void setup_new_branch_info_and_source_tree(
+	struct branch_info *new_branch_info,
+	struct checkout_opts *opts,
+	struct object_id *rev,
+	const char *arg)
+{
+	struct tree **source_tree = &opts->source_tree;
+	struct object_id branch_rev;
+
+	new_branch_info->name = arg;
+	setup_branch_path(new_branch_info);
+
+	if (!check_refname_format(new_branch_info->path, 0) &&
+	    !read_ref(new_branch_info->path, &branch_rev))
+		oidcpy(rev, &branch_rev);
+	else
+		new_branch_info->path = NULL; /* not an existing branch */
+
+	new_branch_info->commit = lookup_commit_reference_gently(the_repository, rev, 1);
+	if (!new_branch_info->commit) {
+		/* not a commit */
+		*source_tree = parse_tree_indirect(rev);
+	} else {
+		parse_commit_or_die(new_branch_info->commit);
+		*source_tree = get_commit_tree(new_branch_info->commit);
+	}
+}
+
 static int parse_branchname_arg(int argc, const char **argv,
 				int dwim_new_local_branch_ok,
 				struct branch_info *new_branch_info,
@@ -1088,10 +1116,8 @@ static int parse_branchname_arg(int argc, const char **argv,
 				struct object_id *rev,
 				int *dwim_remotes_matched)
 {
-	struct tree **source_tree = &opts->source_tree;
 	const char **new_branch = &opts->new_branch;
 	int argcount = 0;
-	struct object_id branch_rev;
 	const char *arg;
 	int dash_dash_pos;
 	int has_dash_dash = 0;
@@ -1213,26 +1239,11 @@ static int parse_branchname_arg(int argc, const char **argv,
 	argv++;
 	argc--;
 
-	new_branch_info->name = arg;
-	setup_branch_path(new_branch_info);
-
-	if (!check_refname_format(new_branch_info->path, 0) &&
-	    !read_ref(new_branch_info->path, &branch_rev))
-		oidcpy(rev, &branch_rev);
-	else
-		new_branch_info->path = NULL; /* not an existing branch */
+	setup_new_branch_info_and_source_tree(new_branch_info, opts, rev, arg);
 
-	new_branch_info->commit = lookup_commit_reference_gently(the_repository, rev, 1);
-	if (!new_branch_info->commit) {
-		/* not a commit */
-		*source_tree = parse_tree_indirect(rev);
-	} else {
-		parse_commit_or_die(new_branch_info->commit);
-		*source_tree = get_commit_tree(new_branch_info->commit);
-	}
-
-	if (!*source_tree)                   /* case (1): want a tree */
+	if (!opts->source_tree)                   /* case (1): want a tree */
 		die(_("reference is not a tree: %s"), arg);
+
 	if (!has_dash_dash) {	/* case (3).(d) -> (1) */
 		/*
 		 * Do not complain the most common case
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#191 lore raw

PATCH v4 9/26 checkout: make "opts" in cmd_checkout() a pointer

In reply to Nguyễn Thái Ngọc Duy

"opts" will soon be moved out of cmd_checkout(). To keep changes in that patch smaller, convert "opts" to a pointer and keep the real thing behind "real_opts".

---
 builtin/checkout.c | 115 +++++++++++++++++++++++----------------------
 1 file changed, 58 insertions(+), 57 deletions(-)
builtin/checkout.c +58 -57
index 1ce0446bc6..963f10b05b 100644
@@ -1341,82 +1341,83 @@ static int checkout_branch(struct checkout_opts *opts,
 
 int cmd_checkout(int argc, const char **argv, const char *prefix)
 {
-	struct checkout_opts opts;
+	struct checkout_opts real_opts;
+	struct checkout_opts *opts = &real_opts;
 	struct branch_info new_branch_info;
 	char *conflict_style = NULL;
 	int dwim_new_local_branch, no_dwim_new_local_branch = 0;
 	int dwim_remotes_matched = 0;
 	struct option options[] = {
-		OPT__QUIET(&opts.quiet, N_("suppress progress reporting")),
-		OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
+		OPT__QUIET(&opts->quiet, N_("suppress progress reporting")),
+		OPT_STRING('b', NULL, &opts->new_branch, N_("branch"),
 			   N_("create and checkout a new branch")),
-		OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
+		OPT_STRING('B', NULL, &opts->new_branch_force, N_("branch"),
 			   N_("create/reset and checkout a branch")),
-		OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
-		OPT_BOOL(0, "detach", &opts.force_detach, N_("detach HEAD at named commit")),
-		OPT_SET_INT('t', "track",  &opts.track, N_("set upstream info for new branch"),
+		OPT_BOOL('l', NULL, &opts->new_branch_log, N_("create reflog for new branch")),
+		OPT_BOOL(0, "detach", &opts->force_detach, N_("detach HEAD at named commit")),
+		OPT_SET_INT('t', "track",  &opts->track, N_("set upstream info for new branch"),
 			BRANCH_TRACK_EXPLICIT),
-		OPT_STRING(0, "orphan", &opts.new_orphan_branch, N_("new-branch"), N_("new unparented branch")),
-		OPT_SET_INT_F('2', "ours", &opts.writeout_stage,
+		OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unparented branch")),
+		OPT_SET_INT_F('2', "ours", &opts->writeout_stage,
 			      N_("checkout our version for unmerged files"),
 			      2, PARSE_OPT_NONEG),
-		OPT_SET_INT_F('3', "theirs", &opts.writeout_stage,
+		OPT_SET_INT_F('3', "theirs", &opts->writeout_stage,
 			      N_("checkout their version for unmerged files"),
 			      3, PARSE_OPT_NONEG),
-		OPT__FORCE(&opts.force, N_("force checkout (throw away local modifications)"),
+		OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
 			   PARSE_OPT_NOCOMPLETE),
-		OPT_BOOL('m', "merge", &opts.merge, N_("perform a 3-way merge with the new branch")),
-		OPT_BOOL_F(0, "overwrite-ignore", &opts.overwrite_ignore,
+		OPT_BOOL('m', "merge", &opts->merge, N_("perform a 3-way merge with the new branch")),
+		OPT_BOOL_F(0, "overwrite-ignore", &opts->overwrite_ignore,
 			   N_("update ignored files (default)"),
 			   PARSE_OPT_NOCOMPLETE),
 		OPT_STRING(0, "conflict", &conflict_style, N_("style"),
 			   N_("conflict style (merge or diff3)")),
-		OPT_BOOL('p', "patch", &opts.patch_mode, N_("select hunks interactively")),
-		OPT_BOOL(0, "ignore-skip-worktree-bits", &opts.ignore_skipworktree,
+		OPT_BOOL('p', "patch", &opts->patch_mode, N_("select hunks interactively")),
+		OPT_BOOL(0, "ignore-skip-worktree-bits", &opts->ignore_skipworktree,
 			 N_("do not limit pathspecs to sparse entries only")),
 		OPT_BOOL(0, "no-guess", &no_dwim_new_local_branch,
 			 N_("do not second guess 'git checkout <no-such-branch>'")),
-		OPT_BOOL(0, "ignore-other-worktrees", &opts.ignore_other_worktrees,
+		OPT_BOOL(0, "ignore-other-worktrees", &opts->ignore_other_worktrees,
 			 N_("do not check if another worktree is holding the given ref")),
 		{ OPTION_CALLBACK, 0, "recurse-submodules", NULL,
 			    "checkout", "control recursive updating of submodules",
 			    PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater },
-		OPT_BOOL(0, "progress", &opts.show_progress, N_("force progress reporting")),
-		OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode (default)")),
+		OPT_BOOL(0, "progress", &opts->show_progress, N_("force progress reporting")),
+		OPT_BOOL(0, "overlay", &opts->overlay_mode, N_("use overlay mode (default)")),
 		OPT_END(),
 	};
 
-	memset(&opts, 0, sizeof(opts));
+	memset(opts, 0, sizeof(*opts));
 	memset(&new_branch_info, 0, sizeof(new_branch_info));
-	opts.overwrite_ignore = 1;
-	opts.prefix = prefix;
-	opts.show_progress = -1;
-	opts.overlay_mode = -1;
+	opts->overwrite_ignore = 1;
+	opts->prefix = prefix;
+	opts->show_progress = -1;
+	opts->overlay_mode = -1;
 
-	git_config(git_checkout_config, &opts);
+	git_config(git_checkout_config, opts);
 
-	opts.track = BRANCH_TRACK_UNSPECIFIED;
+	opts->track = BRANCH_TRACK_UNSPECIFIED;
 
 	argc = parse_options(argc, argv, prefix, options, checkout_usage,
 			     PARSE_OPT_KEEP_DASHDASH);
 
 	dwim_new_local_branch = !no_dwim_new_local_branch;
-	if (opts.show_progress < 0) {
-		if (opts.quiet)
-			opts.show_progress = 0;
+	if (opts->show_progress < 0) {
+		if (opts->quiet)
+			opts->show_progress = 0;
 		else
-			opts.show_progress = isatty(2);
+			opts->show_progress = isatty(2);
 	}
 
 	if (conflict_style) {
-		opts.merge = 1; /* implied */
+		opts->merge = 1; /* implied */
 		git_xmerge_config("merge.conflictstyle", conflict_style, NULL);
 	}
 
-	if ((!!opts.new_branch + !!opts.new_branch_force + !!opts.new_orphan_branch) > 1)
+	if ((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) > 1)
 		die(_("-b, -B and --orphan are mutually exclusive"));
 
-	if (opts.overlay_mode == 1 && opts.patch_mode)
+	if (opts->overlay_mode == 1 && opts->patch_mode)
 		die(_("-p and --overlay are mutually exclusive"));
 
 	/*
@@ -1424,14 +1425,14 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 	 * and new_branch_force and new_orphan_branch will tell us which one of
 	 * -b/-B/--orphan is being used.
 	 */
-	if (opts.new_branch_force)
-		opts.new_branch = opts.new_branch_force;
+	if (opts->new_branch_force)
+		opts->new_branch = opts->new_branch_force;
 
-	if (opts.new_orphan_branch)
-		opts.new_branch = opts.new_orphan_branch;
+	if (opts->new_orphan_branch)
+		opts->new_branch = opts->new_orphan_branch;
 
 	/* --track without -b/-B/--orphan should DWIM */
-	if (opts.track != BRANCH_TRACK_UNSPECIFIED && !opts.new_branch) {
+	if (opts->track != BRANCH_TRACK_UNSPECIFIED && !opts->new_branch) {
 		const char *argv0 = argv[0];
 		if (!argc || !strcmp(argv0, "--"))
 			die(_("--track needs a branch name"));
@@ -1440,7 +1441,7 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 		argv0 = strchr(argv0, '/');
 		if (!argv0 || !argv0[1])
 			die(_("missing branch name; try -b"));
-		opts.new_branch = argv0 + 1;
+		opts->new_branch = argv0 + 1;
 	}
 
 	/*
@@ -1459,56 +1460,56 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 	if (argc) {
 		struct object_id rev;
 		int dwim_ok =
-			!opts.patch_mode &&
+			!opts->patch_mode &&
 			dwim_new_local_branch &&
-			opts.track == BRANCH_TRACK_UNSPECIFIED &&
-			!opts.new_branch;
+			opts->track == BRANCH_TRACK_UNSPECIFIED &&
+			!opts->new_branch;
 		int n = parse_branchname_arg(argc, argv, dwim_ok,
-					     &new_branch_info, &opts, &rev,
+					     &new_branch_info, opts, &rev,
 					     &dwim_remotes_matched);
 		argv += n;
 		argc -= n;
 	}
 
 	if (argc) {
-		parse_pathspec(&opts.pathspec, 0,
-			       opts.patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0,
+		parse_pathspec(&opts->pathspec, 0,
+			       opts->patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0,
 			       prefix, argv);
 
-		if (!opts.pathspec.nr)
+		if (!opts->pathspec.nr)
 			die(_("invalid path specification"));
 
 		/*
 		 * Try to give more helpful suggestion.
 		 * new_branch && argc > 1 will be caught later.
 		 */
-		if (opts.new_branch && argc == 1)
+		if (opts->new_branch && argc == 1)
 			die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
-				argv[0], opts.new_branch);
+				argv[0], opts->new_branch);
 
-		if (opts.force_detach)
+		if (opts->force_detach)
 			die(_("git checkout: --detach does not take a path argument '%s'"),
 			    argv[0]);
 
-		if (1 < !!opts.writeout_stage + !!opts.force + !!opts.merge)
+		if (1 < !!opts->writeout_stage + !!opts->force + !!opts->merge)
 			die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
 			      "checking out of the index."));
 	}
 
-	if (opts.new_branch) {
+	if (opts->new_branch) {
 		struct strbuf buf = STRBUF_INIT;
 
-		if (opts.new_branch_force)
-			opts.branch_exists = validate_branchname(opts.new_branch, &buf);
+		if (opts->new_branch_force)
+			opts->branch_exists = validate_branchname(opts->new_branch, &buf);
 		else
-			opts.branch_exists =
-				validate_new_branchname(opts.new_branch, &buf, 0);
+			opts->branch_exists =
+				validate_new_branchname(opts->new_branch, &buf, 0);
 		strbuf_release(&buf);
 	}
 
 	UNLEAK(opts);
-	if (opts.patch_mode || opts.pathspec.nr) {
-		int ret = checkout_paths(&opts, new_branch_info.name);
+	if (opts->patch_mode || opts->pathspec.nr) {
+		int ret = checkout_paths(opts, new_branch_info.name);
 		if (ret && dwim_remotes_matched > 1 &&
 		    advice_checkout_ambiguous_remote_branch_name)
 			advise(_("'%s' matched more than one remote tracking branch.\n"
@@ -1527,6 +1528,6 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 			       dwim_remotes_matched);
 		return ret;
 	} else {
-		return checkout_branch(&opts, &new_branch_info);
+		return checkout_branch(opts, &new_branch_info);
 	}
 }
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#192 lore raw

PATCH v4 10/26 checkout: move 'confict_style' and 'dwim_..' to checkout_opts

In reply to Nguyễn Thái Ngọc Duy

These local variables are referenced by struct option[]. This struct will soon be broken down, moved away and we can't rely on local variables anymore. Move these two to struct checkout_opts in preparation for that.

---
 builtin/checkout.c | 17 ++++++++++-------
 1 file changed, 10 insertions(+), 7 deletions(-)
builtin/checkout.c +10 -7
index 963f10b05b..b6fc1fc69f 100644
@@ -47,6 +47,8 @@ struct checkout_opts {
 	int show_progress;
 	int count_checkout_paths;
 	int overlay_mode;
+	int no_dwim_new_local_branch;
+
 	/*
 	 * If new checkout options are added, skip_merge_working_tree
 	 * should be updated accordingly.
@@ -58,6 +60,7 @@ struct checkout_opts {
 	int new_branch_log;
 	enum branch_track track;
 	struct diff_options diff_options;
+	char *conflict_style;
 
 	int branch_exists;
 	const char *prefix;
@@ -1344,8 +1347,7 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 	struct checkout_opts real_opts;
 	struct checkout_opts *opts = &real_opts;
 	struct branch_info new_branch_info;
-	char *conflict_style = NULL;
-	int dwim_new_local_branch, no_dwim_new_local_branch = 0;
+	int dwim_new_local_branch;
 	int dwim_remotes_matched = 0;
 	struct option options[] = {
 		OPT__QUIET(&opts->quiet, N_("suppress progress reporting")),
@@ -1370,12 +1372,12 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 		OPT_BOOL_F(0, "overwrite-ignore", &opts->overwrite_ignore,
 			   N_("update ignored files (default)"),
 			   PARSE_OPT_NOCOMPLETE),
-		OPT_STRING(0, "conflict", &conflict_style, N_("style"),
+		OPT_STRING(0, "conflict", &opts->conflict_style, N_("style"),
 			   N_("conflict style (merge or diff3)")),
 		OPT_BOOL('p', "patch", &opts->patch_mode, N_("select hunks interactively")),
 		OPT_BOOL(0, "ignore-skip-worktree-bits", &opts->ignore_skipworktree,
 			 N_("do not limit pathspecs to sparse entries only")),
-		OPT_BOOL(0, "no-guess", &no_dwim_new_local_branch,
+		OPT_BOOL(0, "no-guess", &opts->no_dwim_new_local_branch,
 			 N_("do not second guess 'git checkout <no-such-branch>'")),
 		OPT_BOOL(0, "ignore-other-worktrees", &opts->ignore_other_worktrees,
 			 N_("do not check if another worktree is holding the given ref")),
@@ -1393,6 +1395,7 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 	opts->prefix = prefix;
 	opts->show_progress = -1;
 	opts->overlay_mode = -1;
+	opts->no_dwim_new_local_branch = 0;
 
 	git_config(git_checkout_config, opts);
 
@@ -1401,7 +1404,7 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 	argc = parse_options(argc, argv, prefix, options, checkout_usage,
 			     PARSE_OPT_KEEP_DASHDASH);
 
-	dwim_new_local_branch = !no_dwim_new_local_branch;
+	dwim_new_local_branch = !opts->no_dwim_new_local_branch;
 	if (opts->show_progress < 0) {
 		if (opts->quiet)
 			opts->show_progress = 0;
@@ -1409,9 +1412,9 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 			opts->show_progress = isatty(2);
 	}
 
-	if (conflict_style) {
+	if (opts->conflict_style) {
 		opts->merge = 1; /* implied */
-		git_xmerge_config("merge.conflictstyle", conflict_style, NULL);
+		git_xmerge_config("merge.conflictstyle", opts->conflict_style, NULL);
 	}
 
 	if ((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) > 1)
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#193 lore raw

PATCH v4 11/26 checkout: split options[] array in three pieces

In reply to Nguyễn Thái Ngọc Duy

This is a preparation step for introducing new commands that do parts of what checkout does. There will be two new commands, one is about switching branches, detaching HEAD... one about checking out paths. These share the a subset of command line options. The rest of command line options are separate.

---
 builtin/checkout.c | 82 +++++++++++++++++++++++++++++++++-------------
 parse-options-cb.c | 17 ++++++++++
 parse-options.h    |  1 +
 3 files changed, 77 insertions(+), 23 deletions(-)
builtin/checkout.c +59 -23
index b6fc1fc69f..cf1d70511e 100644
@@ -1342,15 +1342,31 @@ static int checkout_branch(struct checkout_opts *opts,
 	return switch_branches(opts, new_branch_info);
 }
 
-int cmd_checkout(int argc, const char **argv, const char *prefix)
+static struct option *add_common_options(struct checkout_opts *opts,
+					 struct option *prevopts)
 {
-	struct checkout_opts real_opts;
-	struct checkout_opts *opts = &real_opts;
-	struct branch_info new_branch_info;
-	int dwim_new_local_branch;
-	int dwim_remotes_matched = 0;
 	struct option options[] = {
 		OPT__QUIET(&opts->quiet, N_("suppress progress reporting")),
+		{ OPTION_CALLBACK, 0, "recurse-submodules", NULL,
+			    "checkout", "control recursive updating of submodules",
+			    PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater },
+		OPT_BOOL(0, "progress", &opts->show_progress, N_("force progress reporting")),
+		OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
+			   PARSE_OPT_NOCOMPLETE),
+		OPT_BOOL('m', "merge", &opts->merge, N_("perform a 3-way merge with the new branch")),
+		OPT_STRING(0, "conflict", &opts->conflict_style, N_("style"),
+			   N_("conflict style (merge or diff3)")),
+		OPT_END()
+	};
+	struct option *newopts = parse_options_concat(prevopts, options);
+	free(prevopts);
+	return newopts;
+}
+
+static struct option *add_switch_branch_options(struct checkout_opts *opts,
+						struct option *prevopts)
+{
+	struct option options[] = {
 		OPT_STRING('b', NULL, &opts->new_branch, N_("branch"),
 			   N_("create and checkout a new branch")),
 		OPT_STRING('B', NULL, &opts->new_branch_force, N_("branch"),
@@ -1360,34 +1376,49 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 		OPT_SET_INT('t', "track",  &opts->track, N_("set upstream info for new branch"),
 			BRANCH_TRACK_EXPLICIT),
 		OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unparented branch")),
+		OPT_BOOL_F(0, "overwrite-ignore", &opts->overwrite_ignore,
+			   N_("update ignored files (default)"),
+			   PARSE_OPT_NOCOMPLETE),
+		OPT_BOOL(0, "no-guess", &opts->no_dwim_new_local_branch,
+			 N_("second guess 'git checkout <no-such-branch>'")),
+		OPT_BOOL(0, "ignore-other-worktrees", &opts->ignore_other_worktrees,
+			 N_("do not check if another worktree is holding the given ref")),
+		OPT_END()
+	};
+	struct option *newopts = parse_options_concat(prevopts, options);
+	free(prevopts);
+	return newopts;
+}
+
+static struct option *add_checkout_path_options(struct checkout_opts *opts,
+						struct option *prevopts)
+{
+	struct option options[] = {
 		OPT_SET_INT_F('2', "ours", &opts->writeout_stage,
 			      N_("checkout our version for unmerged files"),
 			      2, PARSE_OPT_NONEG),
 		OPT_SET_INT_F('3', "theirs", &opts->writeout_stage,
 			      N_("checkout their version for unmerged files"),
 			      3, PARSE_OPT_NONEG),
-		OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
-			   PARSE_OPT_NOCOMPLETE),
-		OPT_BOOL('m', "merge", &opts->merge, N_("perform a 3-way merge with the new branch")),
-		OPT_BOOL_F(0, "overwrite-ignore", &opts->overwrite_ignore,
-			   N_("update ignored files (default)"),
-			   PARSE_OPT_NOCOMPLETE),
-		OPT_STRING(0, "conflict", &opts->conflict_style, N_("style"),
-			   N_("conflict style (merge or diff3)")),
 		OPT_BOOL('p', "patch", &opts->patch_mode, N_("select hunks interactively")),
 		OPT_BOOL(0, "ignore-skip-worktree-bits", &opts->ignore_skipworktree,
 			 N_("do not limit pathspecs to sparse entries only")),
-		OPT_BOOL(0, "no-guess", &opts->no_dwim_new_local_branch,
-			 N_("do not second guess 'git checkout <no-such-branch>'")),
-		OPT_BOOL(0, "ignore-other-worktrees", &opts->ignore_other_worktrees,
-			 N_("do not check if another worktree is holding the given ref")),
-		{ OPTION_CALLBACK, 0, "recurse-submodules", NULL,
-			    "checkout", "control recursive updating of submodules",
-			    PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater },
-		OPT_BOOL(0, "progress", &opts->show_progress, N_("force progress reporting")),
 		OPT_BOOL(0, "overlay", &opts->overlay_mode, N_("use overlay mode (default)")),
-		OPT_END(),
+		OPT_END()
 	};
+	struct option *newopts = parse_options_concat(prevopts, options);
+	free(prevopts);
+	return newopts;
+}
+
+int cmd_checkout(int argc, const char **argv, const char *prefix)
+{
+	struct checkout_opts real_opts;
+	struct checkout_opts *opts = &real_opts;
+	struct branch_info new_branch_info;
+	int dwim_remotes_matched = 0;
+	int dwim_new_local_branch;
+	struct option *options = NULL;
 
 	memset(opts, 0, sizeof(*opts));
 	memset(&new_branch_info, 0, sizeof(new_branch_info));
@@ -1401,6 +1432,11 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 
 	opts->track = BRANCH_TRACK_UNSPECIFIED;
 
+	options = parse_options_dup(options);
+	options = add_common_options(opts, options);
+	options = add_switch_branch_options(opts, options);
+	options = add_checkout_path_options(opts, options);
+
 	argc = parse_options(argc, argv, prefix, options, checkout_usage,
 			     PARSE_OPT_KEEP_DASHDASH);
 
parse-options-cb.c +17 -0
index 2733393546..caaeed896f 100644
@@ -122,6 +122,23 @@ int parse_opt_tertiary(const struct option *opt, const char *arg, int unset)
 	return 0;
 }
 
+struct option *parse_options_dup(const struct option *o)
+{
+	struct option *opts;
+	int nr = 0;
+
+	while (o && o->type != OPTION_END) {
+		nr++;
+		o++;
+	}
+
+	ALLOC_ARRAY(opts, nr + 1);
+	memcpy(opts, o - nr, sizeof(*o) * nr);
+	memset(opts + nr, 0, sizeof(*opts));
+	opts[nr].type = OPTION_END;
+	return opts;
+}
+
 struct option *parse_options_concat(struct option *a, struct option *b)
 {
 	struct option *ret;
parse-options.h +1 -0
index 7d83e2971d..9a90c332a5 100644
@@ -257,6 +257,7 @@ int parse_options_step(struct parse_opt_ctx_t *ctx,
 
 int parse_options_end(struct parse_opt_ctx_t *ctx);
 
+struct option *parse_options_dup(const struct option *a);
 struct option *parse_options_concat(struct option *a, struct option *b);
 
 /*----- some often used options -----*/
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#194 lore raw

PATCH v4 12/26 checkout: split part of it to new command 'switch'

In reply to Nguyễn Thái Ngọc Duy

"git checkout" doing too many things is a source of confusion for many users (and it even bites old timers sometimes). To remedy that, the command will be split into two new ones: switch and restore. The good old "git checkout" command is still here and will be until all (or most of users) are sick of it.

See the new man page for the final design of switch. The actual implementation though is still pretty much the same as "git checkout" and not completely aligned with the man page. Following patches will adjust their behavior to match the man page.

---
 .gitignore                         |   1 +
 Documentation/config/advice.txt    |  13 +-
 Documentation/config/branch.txt    |   4 +-
 Documentation/config/checkout.txt  |   9 +-
 Documentation/config/diff.txt      |   3 +-
 Documentation/git-checkout.txt     |   4 +
 Documentation/git-switch.txt (new) | 277 +++++++++++++++++++++++++++++
 Documentation/gitattributes.txt    |   3 +-
 Documentation/githooks.txt         |   8 +-
 Makefile                           |   1 +
 builtin.h                          |   1 +
 builtin/checkout.c                 |  60 +++++--
 command-list.txt                   |   1 +
 git.c                              |   1 +
 14 files changed, 359 insertions(+), 27 deletions(-)
.gitignore +1 -0
index 7374587f9d..c687b92b1c 100644
@@ -167,6 +167,7 @@
 /git-submodule
 /git-submodule--helper
 /git-svn
+/git-switch
 /git-symbolic-ref
 /git-tag
 /git-unpack-file
Documentation/config/advice.txt +8 -5
index 88620429ea..239d479506 100644
@@ -42,7 +42,8 @@ advice.*::
 		state in the output of linkgit:git-status[1], in
 		the template shown when writing commit messages in
 		linkgit:git-commit[1], and in the help message shown
-		by linkgit:git-checkout[1] when switching branch.
+		by linkgit:git-switch[1] or
+		linkgit:git-checkout[1] when switching branch.
 	statusUoption::
 		Advise to consider using the `-u` option to linkgit:git-status[1]
 		when the command takes more than 2 seconds to enumerate untracked
@@ -62,12 +63,14 @@ advice.*::
 		your information is guessed from the system username and
 		domain name.
 	detachedHead::
-		Advice shown when you used linkgit:git-checkout[1] to
-		move to the detach HEAD state, to instruct how to create
-		a local branch after the fact.
+		Advice shown when you used
+		linkgit:git-switch[1] or linkgit:git-checkout[1]
+		to move to the detach HEAD state, to instruct how to
+		create a local branch after the fact.
 	checkoutAmbiguousRemoteBranchName::
 		Advice shown when the argument to
-		linkgit:git-checkout[1] ambiguously resolves to a
+		linkgit:git-checkout[1] and linkgit:git-switch[1]
+		ambiguously resolves to a
 		remote tracking branch on more than one remote in
 		situations where an unambiguous argument would have
 		otherwise caused a remote-tracking branch to be
Documentation/config/branch.txt +2 -2
index 019d60ede2..8050466159 100644
@@ -1,5 +1,5 @@
 branch.autoSetupMerge::
-	Tells 'git branch' and 'git checkout' to set up new branches
+	Tells 'git branch', 'git switch' and 'git checkout' to set up new branches
 	so that linkgit:git-pull[1] will appropriately merge from the
 	starting point branch. Note that even if this option is not set,
 	this behavior can be chosen per-branch using the `--track`
@@ -11,7 +11,7 @@ branch.autoSetupMerge::
 	branch. This option defaults to true.
 
 branch.autoSetupRebase::
-	When a new branch is created with 'git branch' or 'git checkout'
+	When a new branch is created with 'git branch', 'git switch' or 'git checkout'
 	that tracks another branch, this variable tells Git to set
 	up pull to rebase instead of merge (see "branch.<name>.rebase").
 	When `never`, rebase is never automatically set to true.
Documentation/config/checkout.txt +6 -3
index c4118fa196..d6872ffa83 100644
@@ -1,5 +1,6 @@
 checkout.defaultRemote::
-	When you run 'git checkout <something>' and only have one
+	When you run 'git checkout <something>'
+	or 'git switch <something>' and only have one
 	remote, it may implicitly fall back on checking out and
 	tracking e.g. 'origin/<something>'. This stops working as soon
 	as you have more than one remote with a '<something>'
@@ -8,8 +9,10 @@ checkout.defaultRemote::
 	disambiguation. The typical use-case is to set this to
 	`origin`.
 +
-Currently this is used by linkgit:git-checkout[1] when 'git checkout
-<something>' will checkout the '<something>' branch on another remote,
+Currently this is used by linkgit:git-switch[1] and
+linkgit:git-checkout[1] when 'git checkout <something>'
+or 'git switch <something>'
+will checkout the '<something>' branch on another remote,
 and by linkgit:git-worktree[1] when 'git worktree add' refers to a
 remote branch. This setting might be used for other checkout-like
 commands or functionality in the future.
Documentation/config/diff.txt +2 -1
index e48bb987d7..b3b304ee12 100644
@@ -78,7 +78,8 @@ diff.external::
 diff.ignoreSubmodules::
 	Sets the default value of --ignore-submodules. Note that this
 	affects only 'git diff' Porcelain, and not lower level 'diff'
-	commands such as 'git diff-files'. 'git checkout' also honors
+	commands such as 'git diff-files'. 'git checkout'
+	and 'git switch' also honor
 	this setting when reporting uncommitted changes. Setting it to
 	'all' disables the submodule summary normally shown by 'git commit'
 	and 'git status' when `status.submoduleSummary` is set unless it is
Documentation/git-checkout.txt +4 -0
index bf90966c95..c7192bdefe 100644
@@ -560,6 +560,10 @@ $ edit frotz
 $ git add frotz
 ------------
 
+SEE ALSO
+--------
+linkgit:git-switch[1]
+
 GIT
 ---
 Part of the linkgit:git[1] suite
Documentation/git-switch.txt new file +277 -0

277 lines not on this page · raw message

Documentation/gitattributes.txt +2 -1
index 9b41f81c06..cd0f9fa507 100644
@@ -112,7 +112,8 @@ Checking-out and checking-in
 
 These attributes affect how the contents stored in the
 repository are copied to the working tree files when commands
-such as 'git checkout' and 'git merge' run.  They also affect how
+such as 'git switch', 'git checkout'  and 'git merge' run.
+They also affect how
 Git stores the contents you prepare in the working tree in the
 repository upon 'git add' and 'git commit'.
 
Documentation/githooks.txt +5 -3
index 5bf653c111..8ff72f0613 100644
@@ -165,12 +165,13 @@ rebased, and is not set when rebasing the current branch.
 post-checkout
 ~~~~~~~~~~~~~
 
-This hook is invoked when a linkgit:git-checkout[1] is run after having updated the
+This hook is invoked when a linkgit:git-checkout[1] or
+linkgit:git-switch[1] is run after having updated the
 worktree.  The hook is given three parameters: the ref of the previous HEAD,
 the ref of the new HEAD (which may or may not have changed), and a flag
 indicating whether the checkout was a branch checkout (changing branches,
 flag=1) or a file checkout (retrieving a file from the index, flag=0).
-This hook cannot affect the outcome of `git checkout`.
+This hook cannot affect the outcome of `git switch` or `git checkout`.
 
 It is also run after linkgit:git-clone[1], unless the `--no-checkout` (`-n`) option is
 used. The first parameter given to the hook is the null-ref, the second the
@@ -406,7 +407,8 @@ exit with a zero status.
 For example, the hook can simply run `git read-tree -u -m HEAD "$1"`
 in order to emulate `git fetch` that is run in the reverse direction
 with `git push`, as the two-tree form of `git read-tree -u -m` is
-essentially the same as `git checkout` that switches branches while
+essentially the same as `git switch` or `git checkout`
+that switches branches while
 keeping the local changes in the working tree that do not interfere
 with the difference between the branches.
 
Makefile +1 -0
index 148668368b..8e91db73ad 100644
@@ -802,6 +802,7 @@ BUILT_INS += git-merge-subtree$X
 BUILT_INS += git-show$X
 BUILT_INS += git-stage$X
 BUILT_INS += git-status$X
+BUILT_INS += git-switch$X
 BUILT_INS += git-whatchanged$X
 
 # what 'all' will build and 'install' will install in gitexecdir,
builtin.h +1 -0
index 6538932e99..c64e44450e 100644
@@ -227,6 +227,7 @@ extern int cmd_show_index(int argc, const char **argv, const char *prefix);
 extern int cmd_status(int argc, const char **argv, const char *prefix);
 extern int cmd_stripspace(int argc, const char **argv, const char *prefix);
 extern int cmd_submodule__helper(int argc, const char **argv, const char *prefix);
+extern int cmd_switch(int argc, const char **argv, const char *prefix);
 extern int cmd_symbolic_ref(int argc, const char **argv, const char *prefix);
 extern int cmd_tag(int argc, const char **argv, const char *prefix);
 extern int cmd_tar_tree(int argc, const char **argv, const char *prefix);
builtin/checkout.c +48 -12

90 lines not on this page · raw message

command-list.txt +1 -0
index 3a9af104b5..13317f47d4 100644
@@ -171,6 +171,7 @@ git-status                              mainporcelain           info
 git-stripspace                          purehelpers
 git-submodule                           mainporcelain
 git-svn                                 foreignscminterface
+git-switch                              mainporcelain           history
 git-symbolic-ref                        plumbingmanipulators
 git-tag                                 mainporcelain           history
 git-unpack-file                         plumbinginterrogators
git.c +1 -0
index 2014aab6b8..39582cf511 100644
@@ -573,6 +573,7 @@ static struct cmd_struct commands[] = {
 	{ "status", cmd_status, RUN_SETUP | NEED_WORK_TREE },
 	{ "stripspace", cmd_stripspace },
 	{ "submodule--helper", cmd_submodule__helper, RUN_SETUP | SUPPORT_SUPER_PREFIX | NO_PARSEOPT },
+	{ "switch", cmd_switch, RUN_SETUP | NEED_WORK_TREE },
 	{ "symbolic-ref", cmd_symbolic_ref, RUN_SETUP },
 	{ "tag", cmd_tag, RUN_SETUP | DELAY_PAGER_CONFIG },
 	{ "unpack-file", cmd_unpack_file, RUN_SETUP | NO_PARSEOPT },
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#195 lore raw

Re: [PATCH v4 12/26] checkout: split part of it to new command 'switch'

Quoted 7 lines · Nguyễn Thái Ngọc Duy

"git checkout" doing too many things is a source of confusion for many users (and it even bites old timers sometimes). To remedy that, the command will be split into two new ones: switch and restore. The good old "git checkout" command is still here and will be until all (or most of users) are sick of it.

Quoted 7 lines

See the new man page for the final design of switch. The actual implementation though is still pretty much the same as "git checkout" and not completely aligned with the man page. Following patches will adjust their behavior to match the man page.

---

Looking really good. Just some minor comments...

Documentation/git-switch.txt line 11

Quoted 11 lines
Documentation/git-switch.txt new file +11 -0
+git-switch(1)
+=============
+
+NAME
+----
+git-switch - Switch branches
+
+SYNOPSIS
+--------
+[verse]
+'git switch' [<options>] [--guess] <branch>

Should this now use [--no-guess] since --guess is the default?

Quoted 8 lines

+'git switch' [<options>] --detach [<start-point>]
+'git switch' [<options>] (-c|-C|--orphan) <new-branch> [<start-point>]

Documentation/git-switch.txt new file +6 -0
+
+DESCRIPTION
+-----------
+Switch to a specified branch. The working tree and the index are
+updated to match the branch. All new commits will be added to the tip
+of this branch.

Documentation/git-switch.txt line 29

Quoted 10 lines
Documentation/git-switch.txt new file +10 -0
+
+Optionally a new branch could be created with either `-c`, `-C`,
+automatically from a remote branch of same name (see `--guess`), or
+detach the working tree from any branch with `--detach`, along with
+switching.
+
+Switching branches does not require a clean index and working tree
+(i.e. no differences compared to `HEAD`). The operation is aborted
+however if the switch leads to loss of local changes, unless told
+otherwise.

Maybe s/otherwise./otherwise with --discard-changes or --merge./, just for a little extra clarity?

Documentation/git-switch.txt line 112

Quoted 9 lines
+-f::
+--force::
Documentation/git-switch.txt new file +7 -0
+       An alias for `--discard-changes`.
+
+--discard-changes::
+       Proceed even if the index or the working tree differs from
+       `HEAD`. Both the index and working tree are restored to match
+       the switching target. This is used to throw away local
+       changes.

It looks like elsewhere you and Junio discussed making --force also imply --ignore-in-progress. That option should be moved close to --force, so that similar options are adjacent, but it also brings up a question for me:

Is --force an alias for both --discard-changes and --ignore-in-progress, or is --discard-changes really just another name for --force (i.e. does it too imply --ignore-in-progress)? I'd be tempted to say the former, but I'm curious on others' thoughts.

Documentation/git-switch.txt line 171

Quoted 5 lines

+--orphan <new-branch>::

Documentation/git-switch.txt new file +4 -0
+       Create a new 'orphan' branch, named `<new-branch>`. If
+       `<start-point>` is specified, the index and working tree are
+       adjusted to match it. Otherwise both are adjusted to contain no
+       tracked files.

Thanks. I'm still slightly hesitant about whether <start-point> should be allowed with --orphan; it seems equivalent to me to letting people have a flag for switching to existing branch A while forcing the index and working tree to match branch B (defaulting B to HEAD from before the switch). Having <start-point> and --orphan together is just a special case of this idea, and thus allowing those together seems like it'll cause the more general request to be filed at some point, and we will already have the precedent of supporting it somewhere. This usecase seems to be somewhat esoteric and infrequent, and could be easily obtained by combining other commands. I'm worried that trying to explain this usecase may make the documentation for the common everyday commands even more complex, and these manpages are already kind of long. However, as I said above, that's just a slight hesitation and maybe I'm just excessively worried about the length of our manpages for the most common commands. This new description of --orphan at least gets the default behavior right.

Great work so far; thanks for working on this.

Elijah

#196 lore raw

PATCH v4 13/26 switch: better names for -b and -B

In reply to Nguyễn Thái Ngọc Duy

The shortcut of these options do not make much sense when used with switch. And their descriptions are also tied to checkout. Move -b/-B to cmd_checkout() and new -c/-C with the same functionality in cmd_switch_branch()

---
 builtin/checkout.c | 32 +++++++++++++++++++++-----------
 1 file changed, 21 insertions(+), 11 deletions(-)
builtin/checkout.c +21 -11
index dd3c200cb5..400a0d5620 100644
@@ -1368,14 +1368,10 @@ static struct option *add_common_options(struct checkout_opts *opts,
 	return newopts;
 }
 
-static struct option *add_switch_branch_options(struct checkout_opts *opts,
-						struct option *prevopts)
+static struct option *add_common_switch_branch_options(
+	struct checkout_opts *opts, struct option *prevopts)
 {
 	struct option options[] = {
-		OPT_STRING('b', NULL, &opts->new_branch, N_("branch"),
-			   N_("create and checkout a new branch")),
-		OPT_STRING('B', NULL, &opts->new_branch_force, N_("branch"),
-			   N_("create/reset and checkout a branch")),
 		OPT_BOOL('l', NULL, &opts->new_branch_log, N_("create reflog for new branch")),
 		OPT_BOOL(0, "detach", &opts->force_detach, N_("detach HEAD at named commit")),
 		OPT_SET_INT('t', "track",  &opts->track, N_("set upstream info for new branch"),
@@ -1571,15 +1567,22 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
 int cmd_checkout(int argc, const char **argv, const char *prefix)
 {
 	struct checkout_opts opts;
-	struct option *options = NULL;
+	struct option *options;
+	struct option checkout_options[] = {
+		OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
+			   N_("create and checkout a new branch")),
+		OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
+			   N_("create/reset and checkout a branch")),
+		OPT_END()
+	};
 	int ret;
 
 	memset(&opts, 0, sizeof(opts));
 	opts.no_dwim_new_local_branch = 0;
 
-	options = parse_options_dup(options);
+	options = parse_options_dup(checkout_options);
 	options = add_common_options(&opts, options);
-	options = add_switch_branch_options(&opts, options);
+	options = add_common_switch_branch_options(&opts, options);
 	options = add_checkout_path_options(&opts, options);
 
 	ret = checkout_main(argc, argv, prefix, &opts,
@@ -1592,14 +1595,21 @@ int cmd_switch(int argc, const char **argv, const char *prefix)
 {
 	struct checkout_opts opts;
 	struct option *options = NULL;
+	struct option switch_options[] = {
+		OPT_STRING('c', "create", &opts.new_branch, N_("branch"),
+			   N_("create and switch to a new branch")),
+		OPT_STRING('C', "force-create", &opts.new_branch_force, N_("branch"),
+			   N_("create/reset and switch to a branch")),
+		OPT_END()
+	};
 	int ret;
 
 	memset(&opts, 0, sizeof(opts));
 	opts.no_dwim_new_local_branch = 0;
 
-	options = parse_options_dup(options);
+	options = parse_options_dup(switch_options);
 	options = add_common_options(&opts, options);
-	options = add_switch_branch_options(&opts, options);
+	options = add_common_switch_branch_options(&opts, options);
 
 	ret = checkout_main(argc, argv, prefix, &opts,
 			    options, switch_branch_usage);
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#197 lore raw

PATCH v4 14/26 switch: add --discard-changes

In reply to Nguyễn Thái Ngọc Duy

--discard-changes is a better name than --force for this option since it's what really happens. --force is turned to an alias for --discard-changes. But it's meant to an alias for potentially more force options in the future.

---
 builtin/checkout.c | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)
builtin/checkout.c +10 -2
index 400a0d5620..bd94b04303 100644
@@ -53,6 +53,7 @@ struct checkout_opts {
 	int count_checkout_paths;
 	int overlay_mode;
 	int no_dwim_new_local_branch;
+	int discard_changes;
 
 	/*
 	 * If new checkout options are added, skip_merge_working_tree
@@ -680,7 +681,7 @@ static int merge_working_tree(const struct checkout_opts *opts,
 		return error(_("index file corrupt"));
 
 	resolve_undo_clear();
-	if (opts->force) {
+	if (opts->discard_changes) {
 		ret = reset_tree(get_commit_tree(new_branch_info->commit),
 				 opts, 1, writeout_error);
 		if (ret)
@@ -802,7 +803,7 @@ static int merge_working_tree(const struct checkout_opts *opts,
 	if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
 		die(_("unable to write new index file"));
 
-	if (!opts->force && !opts->quiet)
+	if (!opts->discard_changes && !opts->quiet)
 		show_local_changes(&new_branch_info->commit->object, &opts->diff_options);
 
 	return 0;
@@ -1309,6 +1310,9 @@ static int checkout_branch(struct checkout_opts *opts,
 	if (opts->force && opts->merge)
 		die(_("'%s' cannot be used with '%s'"), "-f", "-m");
 
+	if (opts->discard_changes && opts->merge)
+		die(_("'%s' cannot be used with '%s'"), "--discard-changes", "--merge");
+
 	if (opts->force_detach && opts->new_branch)
 		die(_("'%s' cannot be used with '%s'"),
 		    "--detach", "-b/-B/--orphan");
@@ -1445,6 +1449,8 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
 		opts->merge = 1; /* implied */
 		git_xmerge_config("merge.conflictstyle", opts->conflict_style, NULL);
 	}
+	if (opts->force)
+		opts->discard_changes = 1;
 
 	if ((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) > 1)
 		die(_("-b, -B and --orphan are mutually exclusive"));
@@ -1600,6 +1606,8 @@ int cmd_switch(int argc, const char **argv, const char *prefix)
 			   N_("create and switch to a new branch")),
 		OPT_STRING('C', "force-create", &opts.new_branch_force, N_("branch"),
 			   N_("create/reset and switch to a branch")),
+		OPT_BOOL(0, "discard-changes", &opts.discard_changes,
+			 N_("throw away local modifications")),
 		OPT_END()
 	};
 	int ret;
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#198 lore raw

Re: [PATCH v4 14/26] switch: add --discard-changes

Quoted 3 lines · Nguyễn Thái Ngọc Duy

--discard-changes is a better name than --force for this option since it's what really happens. --force is turned to an alias for --discard-changes. But it's meant to an alias for potentially more force

s/to an/to be an/

Quoted 3 lines

options in the future.

#199 lore raw

PATCH v4 15/26 switch: remove -l

In reply to Nguyễn Thái Ngọc Duy

This option is ancient. Nowadays reflog is enabled by default and automatically created for new branches. Keep it in git-checkout only.

---
 builtin/checkout.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
builtin/checkout.c +1 -1
index bd94b04303..85fc60f5f2 100644
@@ -1376,7 +1376,6 @@ static struct option *add_common_switch_branch_options(
 	struct checkout_opts *opts, struct option *prevopts)
 {
 	struct option options[] = {
-		OPT_BOOL('l', NULL, &opts->new_branch_log, N_("create reflog for new branch")),
 		OPT_BOOL(0, "detach", &opts->force_detach, N_("detach HEAD at named commit")),
 		OPT_SET_INT('t', "track",  &opts->track, N_("set upstream info for new branch"),
 			BRANCH_TRACK_EXPLICIT),
@@ -1579,6 +1578,7 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 			   N_("create and checkout a new branch")),
 		OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
 			   N_("create/reset and checkout a branch")),
+		OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
 		OPT_END()
 	};
 	int ret;
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#200 lore raw

PATCH v4 16/26 switch: stop accepting pathspec

In reply to Nguyễn Thái Ngọc Duy

This command is about switching branch (or creating a new one) and should not accept pathspec. This helps simplify ambiguation handling. The other two ("git checkout" and "git restore") of course do accept pathspec as before.

---
 builtin/checkout.c | 20 +++++++++++++++-----
 1 file changed, 15 insertions(+), 5 deletions(-)
builtin/checkout.c +15 -5
index 85fc60f5f2..2c4cab6406 100644
@@ -54,6 +54,7 @@ struct checkout_opts {
 	int overlay_mode;
 	int no_dwim_new_local_branch;
 	int discard_changes;
+	int accept_pathspec;
 
 	/*
 	 * If new checkout options are added, skip_merge_working_tree
@@ -1176,10 +1177,16 @@ static int parse_branchname_arg(int argc, const char **argv,
 	if (!argc)
 		return 0;
 
+	if (!opts->accept_pathspec) {
+		if (argc > 1)
+			die(_("only one reference expected"));
+		has_dash_dash = 1; /* helps disambiguate */
+	}
+
 	arg = argv[0];
 	dash_dash_pos = -1;
 	for (i = 0; i < argc; i++) {
-		if (!strcmp(argv[i], "--")) {
+		if (opts->accept_pathspec && !strcmp(argv[i], "--")) {
 			dash_dash_pos = i;
 			break;
 		}
@@ -1213,11 +1220,12 @@ static int parse_branchname_arg(int argc, const char **argv,
 			recover_with_dwim = 0;
 
 		/*
-		 * Accept "git checkout foo" and "git checkout foo --"
-		 * as candidates for dwim.
+		 * Accept "git checkout foo", "git checkout foo --"
+		 * and "git switch foo" as candidates for dwim.
 		 */
 		if (!(argc == 1 && !has_dash_dash) &&
-		    !(argc == 2 && has_dash_dash))
+		    !(argc == 2 && has_dash_dash) &&
+		    opts->accept_pathspec)
 			recover_with_dwim = 0;
 
 		if (recover_with_dwim) {
@@ -1262,7 +1270,7 @@ static int parse_branchname_arg(int argc, const char **argv,
 		 */
 		if (argc)
 			verify_non_filename(opts->prefix, arg);
-	} else {
+	} else if (opts->accept_pathspec) {
 		argcount++;
 		argv++;
 		argc--;
@@ -1585,6 +1593,7 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 
 	memset(&opts, 0, sizeof(opts));
 	opts.no_dwim_new_local_branch = 0;
+	opts.accept_pathspec = 1;
 
 	options = parse_options_dup(checkout_options);
 	options = add_common_options(&opts, options);
@@ -1614,6 +1623,7 @@ int cmd_switch(int argc, const char **argv, const char *prefix)
 
 	memset(&opts, 0, sizeof(opts));
 	opts.no_dwim_new_local_branch = 0;
+	opts.accept_pathspec = 0;
 
 	options = parse_options_dup(switch_options);
 	options = add_common_options(&opts, options);
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#201 lore raw

PATCH v4 17/26 switch: reject "do nothing" case

In reply to Nguyễn Thái Ngọc Duy

"git checkout" can be executed without any arguments. What it does is not exactly great: it switches from HEAD to HEAD and shows worktree modification as a side effect.

Make switch reject this case. Just use "git status" if you want that side effect. For switch, you have to either

- really switch a branch
- (explicitly) detach from the current branch
- create a new branch

---
 builtin/checkout.c | 9 +++++++++
 1 file changed, 9 insertions(+)
builtin/checkout.c +9 -0
index 2c4cab6406..73b7373414 100644
@@ -55,6 +55,7 @@ struct checkout_opts {
 	int no_dwim_new_local_branch;
 	int discard_changes;
 	int accept_pathspec;
+	int switch_branch_doing_nothing_is_ok;
 
 	/*
 	 * If new checkout options are added, skip_merge_working_tree
@@ -1338,6 +1339,12 @@ static int checkout_branch(struct checkout_opts *opts,
 		die(_("Cannot switch branch to a non-commit '%s'"),
 		    new_branch_info->name);
 
+	if (!opts->switch_branch_doing_nothing_is_ok &&
+	    !new_branch_info->name &&
+	    !opts->new_branch &&
+	    !opts->force_detach)
+		die(_("missing branch or commit argument"));
+
 	if (new_branch_info->path && !opts->force_detach && !opts->new_branch &&
 	    !opts->ignore_other_worktrees) {
 		int flag;
@@ -1593,6 +1600,7 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 
 	memset(&opts, 0, sizeof(opts));
 	opts.no_dwim_new_local_branch = 0;
+	opts.switch_branch_doing_nothing_is_ok = 1;
 	opts.accept_pathspec = 1;
 
 	options = parse_options_dup(checkout_options);
@@ -1624,6 +1632,7 @@ int cmd_switch(int argc, const char **argv, const char *prefix)
 	memset(&opts, 0, sizeof(opts));
 	opts.no_dwim_new_local_branch = 0;
 	opts.accept_pathspec = 0;
+	opts.switch_branch_doing_nothing_is_ok = 0;
 
 	options = parse_options_dup(switch_options);
 	options = add_common_options(&opts, options);
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#202 lore raw

PATCH v4 18/26 switch: only allow explicit detached HEAD

In reply to Nguyễn Thái Ngọc Duy

"git checkout <commit>" will checkout the commit in question and detach HEAD from the current branch. It is naturally a right thing to do once you get git references. But detached HEAD is a scary concept to new users because we show a lot of warnings and stuff, and it could be hard to get out of (until you know better).

To keep switch a bit more friendly to new users, we only allow entering detached HEAD mode when --detach is given. "git switch" must take a branch (unless you create a new branch, then of course switch can take any commit-ish)

---
 builtin/checkout.c | 34 ++++++++++++++++++++++++++++++++++
 1 file changed, 34 insertions(+)
builtin/checkout.c +34 -0
index 73b7373414..d72e28aabb 100644
@@ -45,6 +45,7 @@ struct checkout_opts {
 	int merge;
 	int force;
 	int force_detach;
+	int implicit_detach;
 	int writeout_stage;
 	int overwrite_ignore;
 	int ignore_skipworktree;
@@ -1298,6 +1299,29 @@ static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
 	return status;
 }
 
+static void die_expecting_a_branch(const struct branch_info *branch_info)
+{
+	struct object_id oid;
+	char *to_free;
+
+	if (dwim_ref(branch_info->name, strlen(branch_info->name), &oid, &to_free) == 1) {
+		const char *ref = to_free;
+
+		if (skip_prefix(ref, "refs/tags/", &ref))
+			die(_("a branch is expected, got tag '%s'"), ref);
+		if (skip_prefix(ref, "refs/remotes/", &ref))
+			die(_("a branch is expected, got remote branch '%s'"), ref);
+		die(_("a branch is expected, got '%s'"), ref);
+	}
+	if (branch_info->commit)
+		die(_("a branch is expected, got commit '%s'"), branch_info->name);
+	/*
+	 * This case should never happen because we already die() on
+	 * non-commit, but just in case.
+	 */
+	die(_("a branch is expected, got '%s'"), branch_info->name);
+}
+
 static int checkout_branch(struct checkout_opts *opts,
 			   struct branch_info *new_branch_info)
 {
@@ -1345,6 +1369,14 @@ static int checkout_branch(struct checkout_opts *opts,
 	    !opts->force_detach)
 		die(_("missing branch or commit argument"));
 
+	if (!opts->implicit_detach &&
+	    !opts->force_detach &&
+	    !opts->new_branch &&
+	    !opts->new_branch_force &&
+	    new_branch_info->name &&
+	    !new_branch_info->path)
+		die_expecting_a_branch(new_branch_info);
+
 	if (new_branch_info->path && !opts->force_detach && !opts->new_branch &&
 	    !opts->ignore_other_worktrees) {
 		int flag;
@@ -1602,6 +1634,7 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 	opts.no_dwim_new_local_branch = 0;
 	opts.switch_branch_doing_nothing_is_ok = 1;
 	opts.accept_pathspec = 1;
+	opts.implicit_detach = 1;
 
 	options = parse_options_dup(checkout_options);
 	options = add_common_options(&opts, options);
@@ -1633,6 +1666,7 @@ int cmd_switch(int argc, const char **argv, const char *prefix)
 	opts.no_dwim_new_local_branch = 0;
 	opts.accept_pathspec = 0;
 	opts.switch_branch_doing_nothing_is_ok = 0;
+	opts.implicit_detach = 0;
 
 	options = parse_options_dup(switch_options);
 	options = add_common_options(&opts, options);
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#203 lore raw

PATCH v4 19/26 switch: add short option for --detach

In reply to Nguyễn Thái Ngọc Duy

"git checkout" automatically detaches branches and --detach is not that useful (--no-detach is more likely). But for "switch", you may want to use it more often once you're used to detached HEAD. This of course adds -d to git-checkout but it does not harm (yet?) to do it.

---
 builtin/checkout.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
builtin/checkout.c +1 -1
index d72e28aabb..a14133b474 100644
@@ -1423,7 +1423,7 @@ static struct option *add_common_switch_branch_options(
 	struct checkout_opts *opts, struct option *prevopts)
 {
 	struct option options[] = {
-		OPT_BOOL(0, "detach", &opts->force_detach, N_("detach HEAD at named commit")),
+		OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
 		OPT_SET_INT('t', "track",  &opts->track, N_("set upstream info for new branch"),
 			BRANCH_TRACK_EXPLICIT),
 		OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unparented branch")),
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#204 lore raw

PATCH v4 20/26 switch: implicit dwim, use --no-guess to disable it

In reply to Nguyễn Thái Ngọc Duy

This is already the default in git-checkout. The real change in here is just minor cleanup. The main excuse is to explain why dwim is kept default.

Contrary to detach mode that is easy to get into and confusing to get back out. Automatically creating a tracking branch often does not kick in as often (you would need a branch of the same name on a remote). And since the branch creation is reported clearly, the user should be able to undo/delete it if it's unwanted.

---
 Documentation/git-checkout.txt | 38 ++++++++++++++++++++--------------
 builtin/checkout.c             | 16 +++++++-------
 2 files changed, 31 insertions(+), 23 deletions(-)
Documentation/git-checkout.txt +23 -15
index c7192bdefe..58f18a0842 100644
@@ -31,22 +31,13 @@ branch.
 	`<branch>`.
 +
 If `<branch>` is not found but there does exist a tracking branch in
-exactly one remote (call it `<remote>`) with a matching name, treat as
-equivalent to
+exactly one remote (call it `<remote>`) with a matching name and
+`--no-guess` is not specified, treat as equivalent to
 +
 ------------
 $ git checkout -b <branch> --track <remote>/<branch>
 ------------
 +
-If the branch exists in multiple remotes and one of them is named by
-the `checkout.defaultRemote` configuration variable, we'll use that
-one for the purposes of disambiguation, even if the `<branch>` isn't
-unique across all remotes. Set it to
-e.g. `checkout.defaultRemote=origin` to always checkout remote
-branches from there if `<branch>` is ambiguous but exists on the
-'origin' remote. See also `checkout.defaultRemote` in
-linkgit:git-config[1].
-+
 You could omit `<branch>`, in which case the command degenerates to
 "check out the current branch", which is a glorified no-op with
 rather expensive side-effects to show only the tracking information,
@@ -183,6 +174,27 @@ explicitly give a name with `-b` in such a case.
 	Do not set up "upstream" configuration, even if the
 	`branch.autoSetupMerge` configuration variable is true.
 
+--guess::
+--no-guess::
+	If `<branch>` is not found but there does exist a tracking
+	branch in exactly one remote (call it `<remote>`) with a
+	matching name, treat as equivalent to
++
+------------
+$ git checkout -b <branch> --track <remote>/<branch>
+------------
++
+If the branch exists in multiple remotes and one of them is named by
+the `checkout.defaultRemote` configuration variable, we'll use that
+one for the purposes of disambiguation, even if the `<branch>` isn't
+unique across all remotes. Set it to
+e.g. `checkout.defaultRemote=origin` to always checkout remote
+branches from there if `<branch>` is ambiguous but exists on the
+'origin' remote. See also `checkout.defaultRemote` in
+linkgit:git-config[1].
++
+Use `--no-guess` to disable this.
+
 -l::
 	Create the new branch's reflog; see linkgit:git-branch[1] for
 	details.
@@ -287,10 +299,6 @@ Note that this option uses the no overlay mode by default (see also
 	Just like linkgit:git-submodule[1], this will detach `HEAD` of the
 	submodule.
 
---no-guess::
-	Do not attempt to create a branch if a remote tracking branch
-	of the same name exists.
-
 --overlay::
 --no-overlay::
 	In the default overlay mode, `git checkout` never
builtin/checkout.c +8 -8
index a14133b474..ee74379038 100644
@@ -53,7 +53,7 @@ struct checkout_opts {
 	int show_progress;
 	int count_checkout_paths;
 	int overlay_mode;
-	int no_dwim_new_local_branch;
+	int dwim_new_local_branch;
 	int discard_changes;
 	int accept_pathspec;
 	int switch_branch_doing_nothing_is_ok;
@@ -1430,8 +1430,6 @@ static struct option *add_common_switch_branch_options(
 		OPT_BOOL_F(0, "overwrite-ignore", &opts->overwrite_ignore,
 			   N_("update ignored files (default)"),
 			   PARSE_OPT_NOCOMPLETE),
-		OPT_BOOL(0, "no-guess", &opts->no_dwim_new_local_branch,
-			 N_("second guess 'git checkout <no-such-branch>'")),
 		OPT_BOOL(0, "ignore-other-worktrees", &opts->ignore_other_worktrees,
 			 N_("do not check if another worktree is holding the given ref")),
 		OPT_END()
@@ -1468,7 +1466,6 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
 {
 	struct branch_info new_branch_info;
 	int dwim_remotes_matched = 0;
-	int dwim_new_local_branch;
 
 	memset(&new_branch_info, 0, sizeof(new_branch_info));
 	opts->overwrite_ignore = 1;
@@ -1483,7 +1480,6 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
 	argc = parse_options(argc, argv, prefix, options, usagestr,
 			     PARSE_OPT_KEEP_DASHDASH);
 
-	dwim_new_local_branch = !opts->no_dwim_new_local_branch;
 	if (opts->show_progress < 0) {
 		if (opts->quiet)
 			opts->show_progress = 0;
@@ -1545,7 +1541,7 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
 		struct object_id rev;
 		int dwim_ok =
 			!opts->patch_mode &&
-			dwim_new_local_branch &&
+			opts->dwim_new_local_branch &&
 			opts->track == BRANCH_TRACK_UNSPECIFIED &&
 			!opts->new_branch;
 		int n = parse_branchname_arg(argc, argv, dwim_ok,
@@ -1626,12 +1622,14 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 		OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
 			   N_("create/reset and checkout a branch")),
 		OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
+		OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
+			 N_("second guess 'git checkout <no-such-branch>' (default)")),
 		OPT_END()
 	};
 	int ret;
 
 	memset(&opts, 0, sizeof(opts));
-	opts.no_dwim_new_local_branch = 0;
+	opts.dwim_new_local_branch = 1;
 	opts.switch_branch_doing_nothing_is_ok = 1;
 	opts.accept_pathspec = 1;
 	opts.implicit_detach = 1;
@@ -1656,6 +1654,8 @@ int cmd_switch(int argc, const char **argv, const char *prefix)
 			   N_("create and switch to a new branch")),
 		OPT_STRING('C', "force-create", &opts.new_branch_force, N_("branch"),
 			   N_("create/reset and switch to a branch")),
+		OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
+			 N_("second guess 'git switch <no-such-branch>'")),
 		OPT_BOOL(0, "discard-changes", &opts.discard_changes,
 			 N_("throw away local modifications")),
 		OPT_END()
@@ -1663,7 +1663,7 @@ int cmd_switch(int argc, const char **argv, const char *prefix)
 	int ret;
 
 	memset(&opts, 0, sizeof(opts));
-	opts.no_dwim_new_local_branch = 0;
+	opts.dwim_new_local_branch = 1;
 	opts.accept_pathspec = 0;
 	opts.switch_branch_doing_nothing_is_ok = 0;
 	opts.implicit_detach = 0;
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#205 lore raw

PATCH v4 21/26 switch: no worktree status unless real branch switch happens

In reply to Nguyễn Thái Ngọc Duy

When we switch from one branch to another, it makes sense to show a summary of local changes since there could be conflicts, or some files left modified.... When switch is used solely for creating a new branch (and "switch" to the same commit) or detaching, we don't really need to show anything.

"git checkout" does it anyway for historical reasons. But we can start with a clean slate with switch and don't have to.

This essentially reverts fa655d8411 (checkout: optimize "git checkout -b <new_branch>" - 2018-08-16) and make it default for switch, but also for -B and --detach. Users of big repos are encouraged to move to switch.

---
 Documentation/config/checkout.txt |   8 --
 builtin/checkout.c                | 134 ++----------------------------
 t/t1090-sparse-checkout-scope.sh  |  14 ----
 3 files changed, 8 insertions(+), 148 deletions(-)
Documentation/config/checkout.txt +0 -8
index d6872ffa83..6b646813ab 100644
@@ -16,11 +16,3 @@ will checkout the '<something>' branch on another remote,
 and by linkgit:git-worktree[1] when 'git worktree add' refers to a
 remote branch. This setting might be used for other checkout-like
 commands or functionality in the future.
-
-checkout.optimizeNewBranch::
-	Optimizes the performance of "git checkout -b <new_branch>" when
-	using sparse-checkout.  When set to true, git will not update the
-	repo based on the current sparse-checkout settings.  This means it
-	will not update the skip-worktree bit in the index nor add/remove
-	files in the working directory to reflect the current sparse checkout
-	settings nor will it show the local changes.
builtin/checkout.c +8 -126

184 lines not on this page · raw message

t/t1090-sparse-checkout-scope.sh +0 -14
index 090b7fc3d3..40cc004326 100755
@@ -31,20 +31,6 @@ test_expect_success 'perform sparse checkout of master' '
 	test_path_is_file c
 '
 
-test_expect_success 'checkout -b checkout.optimizeNewBranch interaction' '
-	cp .git/info/sparse-checkout .git/info/sparse-checkout.bak &&
-	test_when_finished "
-		mv -f .git/info/sparse-checkout.bak .git/info/sparse-checkout
-		git checkout master
-	" &&
-	echo "/b" >>.git/info/sparse-checkout &&
-	test "$(git ls-files -t b)" = "S b" &&
-	git -c checkout.optimizeNewBranch=true checkout -b fast &&
-	test "$(git ls-files -t b)" = "S b" &&
-	git checkout -b slow &&
-	test "$(git ls-files -t b)" = "H b"
-'
-
 test_expect_success 'merge feature branch into sparse checkout of master' '
 	git merge feature &&
 	test_path_is_file a &&
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#206 lore raw

PATCH v4 22/26 switch: reject if some operation is in progress

In reply to Nguyễn Thái Ngọc Duy

Unless you know what you're doing, switching to another branch to do something then switching back could be confusing. Worse, you may even forget that you're in the middle of something. By the time you realize, you may have done a ton of work and it gets harder to go back.

The new option --ignore-in-progress is added to override this check. However it's probably just safer to create a separate worktree for that separate thing you want to work on and leave this worktree alone (unless of course creating or preparing worktrees are not cheap).

---
 builtin/checkout.c | 26 ++++++++++++++++++++++++++
 1 file changed, 26 insertions(+)
builtin/checkout.c +26 -0
index 2aeaac092d..21a585eaa9 100644
@@ -24,6 +24,7 @@
 #include "tree.h"
 #include "tree-walk.h"
 #include "unpack-trees.h"
+#include "wt-status.h"
 #include "xdiff-interface.h"
 
 static const char * const checkout_usage[] = {
@@ -56,6 +57,7 @@ struct checkout_opts {
 	int accept_pathspec;
 	int switch_branch_doing_nothing_is_ok;
 	int only_merge_on_switching_branches;
+	int can_switch_when_in_progress;
 
 	const char *new_branch;
 	const char *new_branch_force;
@@ -1257,6 +1259,26 @@ static int checkout_branch(struct checkout_opts *opts,
 	    !new_branch_info->path)
 		die_expecting_a_branch(new_branch_info);
 
+	if (!opts->can_switch_when_in_progress) {
+		struct wt_status_state state;
+
+		memset(&state, 0, sizeof(state));
+		wt_status_get_state(the_repository, &state, 0);
+
+		if (state.merge_in_progress)
+			die(_("cannot switch branch while merging"));
+		if (state.am_in_progress)
+			die(_("cannot switch branch in the middle of an am session"));
+		if (state.rebase_in_progress || state.rebase_in_progress)
+			die(_("cannot switch branch while rebasing"));
+		if (state.cherry_pick_in_progress)
+			die(_("cannot switch branch while cherry-picking"));
+		if (state.revert_in_progress)
+			die(_("cannot switch branch while reverting"));
+		if (state.bisect_in_progress)
+			die(_("cannot switch branch while bisecting"));
+	}
+
 	if (new_branch_info->path && !opts->force_detach && !opts->new_branch &&
 	    !opts->ignore_other_worktrees) {
 		int flag;
@@ -1514,6 +1536,7 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 	opts.only_merge_on_switching_branches = 0;
 	opts.accept_pathspec = 1;
 	opts.implicit_detach = 1;
+	opts.can_switch_when_in_progress = 1;
 
 	options = parse_options_dup(checkout_options);
 	options = add_common_options(&opts, options);
@@ -1539,6 +1562,8 @@ int cmd_switch(int argc, const char **argv, const char *prefix)
 			 N_("second guess 'git switch <no-such-branch>'")),
 		OPT_BOOL(0, "discard-changes", &opts.discard_changes,
 			 N_("throw away local modifications")),
+		OPT_BOOL(0, "ignore-in-progress", &opts.can_switch_when_in_progress,
+			 N_("allow to switch branch when some operation is still in progress")),
 		OPT_END()
 	};
 	int ret;
@@ -1549,6 +1574,7 @@ int cmd_switch(int argc, const char **argv, const char *prefix)
 	opts.switch_branch_doing_nothing_is_ok = 0;
 	opts.only_merge_on_switching_branches = 1;
 	opts.implicit_detach = 0;
+	opts.can_switch_when_in_progress = 0;
 
 	options = parse_options_dup(switch_options);
 	options = add_common_options(&opts, options);
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#207 lore raw

Re: [PATCH v4 22/26] switch: reject if some operation is in progress

Hi Duy

The new switch command is shaping up nicely

Quoted 40 lines · Nguyễn Thái Ngọc Duy

Unless you know what you're doing, switching to another branch to do something then switching back could be confusing. Worse, you may even forget that you're in the middle of something. By the time you realize, you may have done a ton of work and it gets harder to go back.

The new option --ignore-in-progress is added to override this check. However it's probably just safer to create a separate worktree for that separate thing you want to work on and leave this worktree alone (unless of course creating or preparing worktrees are not cheap).

---
 builtin/checkout.c | 26 ++++++++++++++++++++++++++
 1 file changed, 26 insertions(+)
builtin/checkout.c +3 -0
index 2aeaac092d..21a585eaa9 100644
@@ -24,6 +24,7 @@
 #include "tree.h"
 #include "tree-walk.h"
 #include "unpack-trees.h"
+#include "wt-status.h"
 #include "xdiff-interface.h"
 
 static const char * const checkout_usage[] = {
@@ -56,6 +57,7 @@ struct checkout_opts {
 	int accept_pathspec;
 	int switch_branch_doing_nothing_is_ok;
 	int only_merge_on_switching_branches;
+	int can_switch_when_in_progress;
 
 	const char *new_branch;
 	const char *new_branch_force;
@@ -1257,6 +1259,26 @@ static int checkout_branch(struct checkout_opts *opts,
 	    !new_branch_info->path)
 		die_expecting_a_branch(new_branch_info);
 
+	if (!opts->can_switch_when_in_progress) {

builtin/checkout.c static int checkout_branch(struct checkout_opts *opts, · line 1272

Quoted 10 lines
builtin/checkout.c +10 -0
+		struct wt_status_state state;
+
+		memset(&state, 0, sizeof(state));
+		wt_status_get_state(the_repository, &state, 0);
+
+		if (state.merge_in_progress)
+			die(_("cannot switch branch while merging"));
+		if (state.am_in_progress)
+			die(_("cannot switch branch in the middle of an am session"));
+		if (state.rebase_in_progress || state.rebase_in_progress)

I think one of those should be state.rebase_interactive_in_progress

Best Wishes

Phillip

Quoted 38 lines
builtin/checkout.c +13 -0
+			die(_("cannot switch branch while rebasing"));
+		if (state.cherry_pick_in_progress)
+			die(_("cannot switch branch while cherry-picking"));
+		if (state.revert_in_progress)
+			die(_("cannot switch branch while reverting"));
+		if (state.bisect_in_progress)
+			die(_("cannot switch branch while bisecting"));
+	}
+
 	if (new_branch_info->path && !opts->force_detach && !opts->new_branch &&
 	    !opts->ignore_other_worktrees) {
 		int flag;
@@ -1514,6 +1536,7 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 	opts.only_merge_on_switching_branches = 0;
 	opts.accept_pathspec = 1;
 	opts.implicit_detach = 1;
+	opts.can_switch_when_in_progress = 1;
 
 	options = parse_options_dup(checkout_options);
 	options = add_common_options(&opts, options);
@@ -1539,6 +1562,8 @@ int cmd_switch(int argc, const char **argv, const char *prefix)
 			 N_("second guess 'git switch <no-such-branch>'")),
 		OPT_BOOL(0, "discard-changes", &opts.discard_changes,
 			 N_("throw away local modifications")),
+		OPT_BOOL(0, "ignore-in-progress", &opts.can_switch_when_in_progress,
+			 N_("allow to switch branch when some operation is still in progress")),
 		OPT_END()
 	};
 	int ret;
@@ -1549,6 +1574,7 @@ int cmd_switch(int argc, const char **argv, const char *prefix)
 	opts.switch_branch_doing_nothing_is_ok = 0;
 	opts.only_merge_on_switching_branches = 1;
 	opts.implicit_detach = 0;
+	opts.can_switch_when_in_progress = 0;
 
 	options = parse_options_dup(switch_options);
 	options = add_common_options(&opts, options);
#208 lore raw

PATCH v4 23/26 switch: --orphan defaults to empty tree as HEAD

In reply to Nguyễn Thái Ngọc Duy

Switching and creating branches always involves knowing the <start-point> to begin the new branch from. Sometimes, people want to create a new branch that does not have any commits yet; --orphan is a flag to allow that.

If <start-point> is not specified, instead of leaving index/worktree unchanged, default to "empty tree" starting point, allowing a clean start.

A note on the implementation. An alternative is just create a dummy commit in-core with empty tree and switch to it. But there's a chance the commit's SHA-1 may end up somewhere permanent like reflog. It's best to make sure "commit" pointer is NULL to avoid it.

---
 builtin/checkout.c | 33 +++++++++++++++++++++++++--------
 1 file changed, 25 insertions(+), 8 deletions(-)
builtin/checkout.c +25 -8
index 21a585eaa9..f0d6207236 100644
@@ -58,6 +58,7 @@ struct checkout_opts {
 	int switch_branch_doing_nothing_is_ok;
 	int only_merge_on_switching_branches;
 	int can_switch_when_in_progress;
+	int orphan_default_empty_tree;
 
 	const char *new_branch;
 	const char *new_branch_force;
@@ -568,15 +569,19 @@ static int merge_working_tree(const struct checkout_opts *opts,
 {
 	int ret;
 	struct lock_file lock_file = LOCK_INIT;
+	struct tree *new_tree;
 
 	hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
 	if (read_cache_preload(NULL) < 0)
 		return error(_("index file corrupt"));
 
 	resolve_undo_clear();
+	if (opts->orphan_default_empty_tree && !new_branch_info->commit)
+		new_tree = parse_tree_indirect(the_hash_algo->empty_tree);
+	else
+		new_tree = get_commit_tree(new_branch_info->commit);
 	if (opts->discard_changes) {
-		ret = reset_tree(get_commit_tree(new_branch_info->commit),
-				 opts, 1, writeout_error);
+		ret = reset_tree(new_tree, opts, 1, writeout_error);
 		if (ret)
 			return ret;
 	} else {
@@ -614,7 +619,8 @@ static int merge_working_tree(const struct checkout_opts *opts,
 					   &old_branch_info->commit->object.oid :
 					   the_hash_algo->empty_tree);
 		init_tree_desc(&trees[0], tree->buffer, tree->size);
-		tree = parse_tree_indirect(&new_branch_info->commit->object.oid);
+		parse_tree(new_tree);
+		tree = new_tree;
 		init_tree_desc(&trees[1], tree->buffer, tree->size);
 
 		ret = unpack_trees(2, trees, &topts);
@@ -663,7 +669,7 @@ static int merge_working_tree(const struct checkout_opts *opts,
 			o.verbosity = 0;
 			work = write_tree_from_memory(&o);
 
-			ret = reset_tree(get_commit_tree(new_branch_info->commit),
+			ret = reset_tree(new_tree,
 					 opts, 1,
 					 writeout_error);
 			if (ret)
@@ -672,13 +678,13 @@ static int merge_working_tree(const struct checkout_opts *opts,
 			o.branch1 = new_branch_info->name;
 			o.branch2 = "local";
 			ret = merge_trees(&o,
-					  get_commit_tree(new_branch_info->commit),
+					  new_tree,
 					  work,
 					  get_commit_tree(old_branch_info->commit),
 					  &result);
 			if (ret < 0)
 				exit(128);
-			ret = reset_tree(get_commit_tree(new_branch_info->commit),
+			ret = reset_tree(new_tree,
 					 opts, 0,
 					 writeout_error);
 			strbuf_release(&o.obuf);
@@ -696,7 +702,7 @@ static int merge_working_tree(const struct checkout_opts *opts,
 	if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
 		die(_("unable to write new index file"));
 
-	if (!opts->discard_changes && !opts->quiet)
+	if (!opts->discard_changes && !opts->quiet && new_branch_info->commit)
 		show_local_changes(&new_branch_info->commit->object, &opts->diff_options);
 
 	return 0;
@@ -897,7 +903,10 @@ static void orphaned_commit_warning(struct commit *old_commit, struct commit *ne
 	add_pending_object(&revs, object, oid_to_hex(&object->oid));
 
 	for_each_ref(add_pending_uninteresting_ref, &revs);
-	add_pending_oid(&revs, "HEAD", &new_commit->object.oid, UNINTERESTING);
+	if (new_commit)
+		add_pending_oid(&revs, "HEAD",
+				&new_commit->object.oid,
+				UNINTERESTING);
 
 	if (prepare_revision_walk(&revs))
 		die(_("internal error in revision walk"));
@@ -941,6 +950,12 @@ static int switch_branches(const struct checkout_opts *opts,
 
 		if (opts->only_merge_on_switching_branches)
 			do_merge = 0;
+
+		if (opts->new_orphan_branch && opts->orphan_default_empty_tree) {
+			new_branch_info->commit = NULL;
+			new_branch_info->name = "(empty)";
+			do_merge = 1;
+		}
 	}
 
 	if (do_merge) {
@@ -1537,6 +1552,7 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 	opts.accept_pathspec = 1;
 	opts.implicit_detach = 1;
 	opts.can_switch_when_in_progress = 1;
+	opts.orphan_default_empty_tree = 0;
 
 	options = parse_options_dup(checkout_options);
 	options = add_common_options(&opts, options);
@@ -1575,6 +1591,7 @@ int cmd_switch(int argc, const char **argv, const char *prefix)
 	opts.only_merge_on_switching_branches = 1;
 	opts.implicit_detach = 0;
 	opts.can_switch_when_in_progress = 0;
+	opts.orphan_default_empty_tree = 1;
 
 	options = parse_options_dup(switch_options);
 	options = add_common_options(&opts, options);
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#209 lore raw

PATCH v4 24/26 t: add tests for switch

In reply to Nguyễn Thái Ngọc Duy
---
 t/t2060-switch.sh (new +x) | 97 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 97 insertions(+)
t/t2060-switch.sh new file +97 -0
new file mode 100755
index 0000000000..62ec1bb924
@@ -0,0 +1,97 @@
+#!/bin/sh
+
+test_description='switch basic functionality'
+
+. ./test-lib.sh
+
+test_expect_success 'setup' '
+	test_commit first &&
+	git branch first-branch &&
+	test_commit second &&
+	test_commit third &&
+	git remote add origin nohost:/nopath &&
+	git update-ref refs/remotes/origin/foo first-branch
+'
+
+test_expect_success 'switch branch no arguments' '
+	test_must_fail git switch
+'
+
+test_expect_success 'switch branch' '
+	git switch first-branch &&
+	test_path_is_missing second.t
+'
+
+test_expect_success 'switch and detach' '
+	test_when_finished git switch master &&
+	test_must_fail git switch master^{commit} &&
+	git switch --detach master^{commit} &&
+	test_must_fail git symbolic-ref HEAD
+'
+
+test_expect_success 'switch and detach current branch' '
+	test_when_finished git switch master &&
+	git switch master &&
+	git switch --detach &&
+	test_must_fail git symbolic-ref HEAD
+'
+
+test_expect_success 'switch and create branch' '
+	test_when_finished git switch master &&
+	git switch -c temp master^ &&
+	test_cmp_rev master^ refs/heads/temp &&
+	echo refs/heads/temp >expected-branch &&
+	git symbolic-ref HEAD >actual-branch &&
+	test_cmp expected-branch actual-branch
+'
+
+test_expect_success 'force create branch from HEAD' '
+	test_when_finished git switch master &&
+	git switch --detach master &&
+	test_must_fail git switch -c temp &&
+	git switch -C temp &&
+	test_cmp_rev master refs/heads/temp &&
+	echo refs/heads/temp >expected-branch &&
+	git symbolic-ref HEAD >actual-branch &&
+	test_cmp expected-branch actual-branch
+'
+
+test_expect_success 'new orphan branch from empty' '
+	test_when_finished git switch master &&
+	git switch --orphan new-orphan &&
+	test_commit orphan &&
+	git cat-file commit refs/heads/new-orphan >commit &&
+	! grep ^parent commit &&
+	git ls-files >tracked-files &&
+	echo orphan.t >expected &&
+	test_cmp expected tracked-files
+'
+
+test_expect_success 'switching ignores file of same branch name' '
+	test_when_finished git switch master &&
+	: >first-branch &&
+	git switch first-branch &&
+	echo refs/heads/first-branch >expected &&
+	git symbolic-ref HEAD >actual &&
+	test_cmp expected actual
+'
+
+test_expect_success 'guess and create branch ' '
+	test_when_finished git switch master &&
+	test_must_fail git switch --no-guess foo &&
+	git switch foo &&
+	echo refs/heads/foo >expected &&
+	git symbolic-ref HEAD >actual &&
+	test_cmp expected actual
+'
+
+test_expect_success 'switching when something is in progress' '
+	test_when_finished rm -f .git/MERGE_HEAD &&
+	# fake a merge-in-progress
+	cp .git/HEAD .git/MERGE_HEAD &&
+	test_must_fail git switch -d @^ &&
+	git switch --ignore-in-progress -d @^ &&
+	git switch -
+'
+
+test_done
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#210 lore raw

PATCH v4 25/26 completion: support switch

In reply to Nguyễn Thái Ngọc Duy

Completion support for --guess could be made better. If no --detach is given, we should only provide a list of refs/heads/* and dwim ones, not the entire ref space. But I still can't penetrate that __git_refs() function yet.

---
 contrib/completion/git-completion.bash | 37 +++++++++++++++++++++++++-
 1 file changed, 36 insertions(+), 1 deletion(-)
contrib/completion/git-completion.bash +36 -1
index 976e4a6548..b24bc48276 100644
@@ -37,7 +37,8 @@
 #   GIT_COMPLETION_CHECKOUT_NO_GUESS
 #
 #     When set to "1", do not include "DWIM" suggestions in git-checkout
-#     completion (e.g., completing "foo" when "origin/foo" exists).
+#     and git-switch completion (e.g., completing "foo" when "origin/foo"
+#     exists).
 
 case "$COMP_WORDBREAKS" in
 *:*) : great ;;
@@ -2158,6 +2159,40 @@ _git_status ()
 	__git_complete_index_file "$complete_opt"
 }
 
+_git_switch ()
+{
+	case "$cur" in
+	--conflict=*)
+		__gitcomp "diff3 merge" "" "${cur##--conflict=}"
+		;;
+	--*)
+		__gitcomp_builtin switch
+		;;
+	*)
+		# check if --track, --no-track, or --no-guess was specified
+		# if so, disable DWIM mode
+		local track_opt="--track" only_local_ref=n
+		if [ "$GIT_COMPLETION_CHECKOUT_NO_GUESS" = "1" ] ||
+		   [ -n "$(__git_find_on_cmdline "--track --no-track --no-guess")" ]; then
+			track_opt=''
+		fi
+		# explicit --guess enables DWIM mode regardless of
+		# $GIT_COMPLETION_CHECKOUT_NO_GUESS
+		if [ -n "$(__git_find_on_cmdline "--guess")" ]; then
+			track_opt='--track'
+		fi
+		if [ -z "$(__git_find_on_cmdline "-d --detach")" ]; then
+			only_local_ref=y
+		fi
+		if [ $only_local_ref = y -a -z "$track_opt" ]; then
+			__gitcomp_direct "$(__git_heads "" "$cur" " ")"
+		else
+			__git_complete_refs $track_opt
+		fi
+		;;
+	esac
+}
+
 __git_config_get_set_variables ()
 {
 	local prevword word config_file= c=$cword
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#211 lore raw

PATCH v4 26/26 doc: promote "git switch"

In reply to Nguyễn Thái Ngọc Duy

The new command "git switch" is added to avoid the confusion of one-command-do-all "git checkout" for new users. They are also helpful to avoid ambiguation context.

For these reasons, promote it everywhere possible. This includes documentation, suggestions/advice from other commands...

---
 Documentation/git-branch.txt           | 12 +++---
 Documentation/git-check-ref-format.txt |  3 +-
 Documentation/git-format-patch.txt     |  2 +-
 Documentation/git-merge-base.txt       |  2 +-
 Documentation/git-rebase.txt           |  2 +-
 Documentation/git-remote.txt           |  2 +-
 Documentation/git-rerere.txt           | 10 ++---
 Documentation/git-reset.txt            | 20 ++++-----
 Documentation/git-stash.txt            |  9 +++--
 Documentation/gitcore-tutorial.txt     | 19 +++++----
 Documentation/giteveryday.txt          | 24 +++++------
 Documentation/gittutorial.txt          |  4 +-
 Documentation/gitworkflows.txt         |  3 +-
 Documentation/revisions.txt            |  2 +-
 Documentation/user-manual.txt          | 56 +++++++++++++-------------
 advice.c                               | 10 ++---
 sha1-name.c                            |  2 +-
 t/t2020-checkout-detach.sh             | 20 ++++-----
 18 files changed, 101 insertions(+), 101 deletions(-)
Documentation/git-branch.txt +6 -6
index 0cd87ddeff..1e2d89b174 100644
@@ -48,7 +48,7 @@ The command's second form creates a new branch head named <branchname>
 which points to the current `HEAD`, or <start-point> if given.
 
 Note that this will create the new branch, but it will not switch the
-working tree to it; use "git checkout <newbranch>" to switch to the
+working tree to it; use "git switch <newbranch>" to switch to the
 new branch.
 
 When a local branch is started off a remote-tracking branch, Git sets up the
@@ -198,7 +198,7 @@ This option is only applicable in non-verbose mode.
 +
 This behavior is the default when the start point is a remote-tracking branch.
 Set the branch.autoSetupMerge configuration variable to `false` if you
-want `git checkout` and `git branch` to always behave as if `--no-track`
+want `git switch`, `git checkout` and `git branch` to always behave as if `--no-track`
 were given. Set it to `always` if you want this behavior when the
 start-point is either a local or remote-tracking branch.
 
@@ -297,7 +297,7 @@ Start development from a known tag::
 $ git clone git://git.kernel.org/pub/scm/.../linux-2.6 my2.6
 $ cd my2.6
 $ git branch my2.6.14 v2.6.14   <1>
-$ git checkout my2.6.14
+$ git switch my2.6.14
 ------------
 +
 <1> This step and the next one could be combined into a single step with
@@ -322,9 +322,9 @@ $ git branch -D test                                    <2>
 NOTES
 -----
 
-If you are creating a branch that you want to checkout immediately, it is
-easier to use the git checkout command with its `-b` option to create
-a branch and check it out with a single command.
+If you are creating a branch that you want to switch to immediately,
+it is easier to use the "git switch" command with its `-c` option to
+do the same thing with a single command.
 
 The options `--contains`, `--no-contains`, `--merged` and `--no-merged`
 serve four related but different purposes:
Documentation/git-check-ref-format.txt +2 -1
index d9de992585..ee6a4144fb 100644
@@ -88,7 +88,8 @@ but it is explicitly forbidden at the beginning of a branch name).
 When run with `--branch` option in a repository, the input is first
 expanded for the ``previous checkout syntax''
 `@{-n}`.  For example, `@{-1}` is a way to refer the last thing that
-was checked out using "git checkout" operation. This option should be
+was checked out using "git switch" or "git checkout" operation.
+This option should be
 used by porcelains to accept this syntax anywhere a branch name is
 expected, so they can act as if you typed the branch name. As an
 exception note that, the ``previous checkout operation'' might result
Documentation/git-format-patch.txt +1 -1
index 1af85d404f..0a24a5679e 100644
@@ -421,7 +421,7 @@ One way to test if your MUA is set up correctly is:
 * Apply it:
 
     $ git fetch <project> master:test-apply
-    $ git checkout test-apply
+    $ git switch test-apply
     $ git reset --hard
     $ git am a.patch
 
Documentation/git-merge-base.txt +1 -1
index 9f07f4f6ed..261d5c1164 100644
@@ -149,7 +149,7 @@ instead.
 Discussion on fork-point mode
 -----------------------------
 
-After working on the `topic` branch created with `git checkout -b
+After working on the `topic` branch created with `git switch -c
 topic origin/master`, the history of remote-tracking branch
 `origin/master` may have been rewound and rebuilt, leading to a
 history of this shape:
Documentation/git-rebase.txt +1 -1
index 5629ba4c5d..cb6fc166e2 100644
@@ -17,7 +17,7 @@ SYNOPSIS
 DESCRIPTION
 -----------
 If <branch> is specified, 'git rebase' will perform an automatic
-`git checkout <branch>` before doing anything else.  Otherwise
+`git switch <branch>` before doing anything else.  Otherwise
 it remains on the current branch.
 
 If <upstream> is not specified, the upstream configured in
Documentation/git-remote.txt +1 -1
index 0cad37fb81..9659abbf8e 100644
@@ -230,7 +230,7 @@ $ git branch -r
   staging/master
   staging/staging-linus
   staging/staging-next
-$ git checkout -b staging staging/master
+$ git switch -c staging staging/master
 ...
 ------------
 
Documentation/git-rerere.txt +5 -5
index df310d2a58..fe4434ad9d 100644
@@ -91,7 +91,7 @@ For such a test, you need to merge master and topic somehow.
 One way to do it is to pull master into the topic branch:
 
 ------------
-	$ git checkout topic
+	$ git switch topic
 	$ git merge master
 
               o---*---o---+ topic
@@ -113,10 +113,10 @@ the upstream might have been advanced since the test merge `+`,
 in which case the final commit graph would look like this:
 
 ------------
-	$ git checkout topic
+	$ git switch topic
 	$ git merge master
 	$ ... work on both topic and master branches
-	$ git checkout master
+	$ git switch master
 	$ git merge topic
 
               o---*---o---+---o---o topic
@@ -136,11 +136,11 @@ merges, you could blow away the test merge, and keep building on
 top of the tip before the test merge:
 
 ------------
-	$ git checkout topic
+	$ git switch topic
 	$ git merge master
 	$ git reset --hard HEAD^ ;# rewind the test merge
 	$ ... work on both topic and master branches
-	$ git checkout master
+	$ git switch master
 	$ git merge topic
 
               o---*---o-------o---o topic
Documentation/git-reset.txt +10 -10
index 132f8e55f6..cbf901efb4 100644
@@ -149,9 +149,9 @@ See also the `--amend` option to linkgit:git-commit[1].
 Undo a commit, making it a topic branch::
 +
 ------------
-$ git branch topic/wip     <1>
-$ git reset --hard HEAD~3  <2>
-$ git checkout topic/wip   <3>
+$ git branch topic/wip          <1>
+$ git reset --hard HEAD~3       <2>
+$ git switch topic/wip          <3>
 ------------
 +
 <1> You have made some commits, but realize they were premature
@@ -232,13 +232,13 @@ working tree are not in any shape to be committed yet, but you
 need to get to the other branch for a quick bugfix.
 +
 ------------
-$ git checkout feature ;# you were working in "feature" branch and
-$ work work work       ;# got interrupted
+$ git switch feature  ;# you were working in "feature" branch and
+$ work work work      ;# got interrupted
 $ git commit -a -m "snapshot WIP"                 <1>
-$ git checkout master
+$ git switch master
 $ fix fix fix
 $ git commit ;# commit with real log
-$ git checkout feature
+$ git switch feature
 $ git reset --soft HEAD^ ;# go back to WIP state  <2>
 $ git reset                                       <3>
 ------------
@@ -279,18 +279,18 @@ reset it while keeping the changes in your working tree.
 +
 ------------
 $ git tag start
-$ git checkout -b branch1
+$ git switch -c branch1
 $ edit
 $ git commit ...                            <1>
 $ edit
-$ git checkout -b branch2                   <2>
+$ git switch -c branch2                     <2>
 $ git reset --keep start                    <3>
 ------------
 +
 <1> This commits your first edits in `branch1`.
 <2> In the ideal world, you could have realized that the earlier
     commit did not belong to the new topic when you created and switched
-    to `branch2` (i.e. `git checkout -b branch2 start`), but nobody is
+    to `branch2` (i.e. `git switch -c branch2 start`), but nobody is
     perfect.
 <3> But you can use `reset --keep` to remove the unwanted commit after
     you switched to `branch2`.
Documentation/git-stash.txt +5 -4
index 7ef8c47911..ebb6282db3 100644
@@ -235,12 +235,12 @@ return to your original branch to make the emergency fix, like this:
 +
 ----------------------------------------------------------------
 # ... hack hack hack ...
-$ git checkout -b my_wip
+$ git switch -c my_wip
 $ git commit -a -m "WIP"
-$ git checkout master
+$ git switch master
 $ edit emergency fix
 $ git commit -a -m "Fix in a hurry"
-$ git checkout my_wip
+$ git switch my_wip
 $ git reset --soft HEAD^
 # ... continue hacking ...
 ----------------------------------------------------------------
@@ -293,7 +293,8 @@ SEE ALSO
 linkgit:git-checkout[1],
 linkgit:git-commit[1],
 linkgit:git-reflog[1],
-linkgit:git-reset[1]
+linkgit:git-reset[1],
+linkgit:git-switch[1]
 
 GIT
 ---
Documentation/gitcore-tutorial.txt +9 -10
index e29a9effcc..f880d21dfb 100644
@@ -741,7 +741,7 @@ used earlier, and create a branch in it. You do that by simply just
 saying that you want to check out a new branch:
 
 ------------
-$ git checkout -b mybranch
+$ git switch -c mybranch
 ------------
 
 will create a new branch based at the current `HEAD` position, and switch
@@ -755,7 +755,7 @@ just telling 'git checkout' what the base of the checkout would be.
 In other words, if you have an earlier tag or branch, you'd just do
 
 ------------
-$ git checkout -b mybranch earlier-commit
+$ git switch -c mybranch earlier-commit
 ------------
 
 and it would create the new branch `mybranch` at the earlier commit,
@@ -765,7 +765,7 @@ and check out the state at that time.
 You can always just jump back to your original `master` branch by doing
 
 ------------
-$ git checkout master
+$ git switch master
 ------------
 
 (or any other branch-name, for that matter) and if you forget which
@@ -794,7 +794,7 @@ $ git branch <branchname> [startingpoint]
 
 which will simply _create_ the branch, but will not do anything further.
 You can then later -- once you decide that you want to actually develop
-on that branch -- switch to that branch with a regular 'git checkout'
+on that branch -- switch to that branch with a regular 'git switch'
 with the branchname as the argument.
 
 
@@ -808,7 +808,7 @@ being the same as the original `master` branch, let's make sure we're in
 that branch, and do some work there.
 
 ------------------------------------------------
-$ git checkout mybranch
+$ git switch mybranch
 $ echo "Work, work, work" >>hello
 $ git commit -m "Some work." -i hello
 ------------------------------------------------
@@ -825,7 +825,7 @@ does some work in the original branch, and simulate that by going back
 to the master branch, and editing the same file differently there:
 
 ------------
-$ git checkout master
+$ git switch master
 ------------
 
 Here, take a moment to look at the contents of `hello`, and notice how they
@@ -958,7 +958,7 @@ to the `master` branch. Let's go back to `mybranch`, and run
 'git merge' to get the "upstream changes" back to your branch.
 
 ------------
-$ git checkout mybranch
+$ git switch mybranch
 $ git merge -m "Merge upstream changes." master
 ------------
 
@@ -1133,9 +1133,8 @@ Remember, before running 'git merge', our `master` head was at
 work." commit.
 
 ------------
-$ git checkout mybranch
-$ git reset --hard master^2
-$ git checkout master
+$ git switch -C mybranch master^2
+$ git switch master
 $ git reset --hard master^
 ------------
 
Documentation/giteveryday.txt +12 -12
index 9f2528fc8c..ad455f3e39 100644
@@ -41,7 +41,7 @@ following commands.
 
   * linkgit:git-log[1] to see what happened.
 
-  * linkgit:git-checkout[1] and linkgit:git-branch[1] to switch
+  * linkgit:git-switch[1] and linkgit:git-branch[1] to switch
     branches.
 
   * linkgit:git-add[1] to manage the index file.
@@ -80,7 +80,7 @@ $ git tag v2.43 <2>
 Create a topic branch and develop.::
 +
 ------------
-$ git checkout -b alsa-audio <1>
+$ git switch -c alsa-audio <1>
 $ edit/compile/test
 $ git checkout -- curses/ux_audio_oss.c <2>
 $ git add curses/ux_audio_alsa.c <3>
@@ -90,7 +90,7 @@ $ git commit -a -s <5>
 $ edit/compile/test
 $ git diff HEAD^ <6>
 $ git commit -a --amend <7>
-$ git checkout master <8>
+$ git switch master <8>
 $ git merge alsa-audio <9>
 $ git log --since='3 days ago' <10>
 $ git log v2.43.. curses/ <11>
@@ -148,11 +148,11 @@ Clone the upstream and work on it.  Feed changes to upstream.::
 ------------
 $ git clone git://git.kernel.org/pub/scm/.../torvalds/linux-2.6 my2.6
 $ cd my2.6
-$ git checkout -b mine master <1>
+$ git switch -c mine master <1>
 $ edit/compile/test; git commit -a -s <2>
 $ git format-patch master <3>
 $ git send-email --to="person <[email protected]>" 00*.patch <4>
-$ git checkout master <5>
+$ git switch master <5>
 $ git pull <6>
 $ git log -p ORIG_HEAD.. arch/i386 include/asm-i386 <7>
 $ git ls-remote --heads http://git.kernel.org/.../jgarzik/libata-dev.git <8>
@@ -194,7 +194,7 @@ satellite$ edit/compile/test/commit
 satellite$ git push origin <4>
 
 mothership$ cd frotz
-mothership$ git checkout master
+mothership$ git switch master
 mothership$ git merge satellite/master <5>
 ------------
 +
@@ -216,7 +216,7 @@ machine into the master branch.
 Branch off of a specific tag.::
 +
 ------------
-$ git checkout -b private2.6.14 v2.6.14 <1>
+$ git switch -c private2.6.14 v2.6.14 <1>
 $ edit/compile/test; git commit -a
 $ git checkout master
 $ git cherry-pick v2.6.14..private2.6.14 <2>
@@ -274,14 +274,14 @@ $ mailx <3>
 & s 2 3 4 5 ./+to-apply
 & s 7 8 ./+hold-linus
 & q
-$ git checkout -b topic/one master
+$ git switch -c topic/one master
 $ git am -3 -i -s ./+to-apply <4>
 $ compile/test
-$ git checkout -b hold/linus && git am -3 -i -s ./+hold-linus <5>
-$ git checkout topic/one && git rebase master <6>
-$ git checkout pu && git reset --hard next <7>
+$ git switch -c hold/linus && git am -3 -i -s ./+hold-linus <5>
+$ git switch topic/one && git rebase master <6>
+$ git switch -C pu next <7>
 $ git merge topic/one topic/two && git merge hold/linus <8>
-$ git checkout maint
+$ git switch maint
 $ git cherry-pick master~4 <9>
 $ compile/test
 $ git tag -s -m "GIT 0.99.9x" v0.99.9x <10>
Documentation/gittutorial.txt +2 -2
index 242de31cb6..e6ad6b5f8d 100644
@@ -207,7 +207,7 @@ automatically.  The asterisk marks the branch you are currently on;
 type
 
 ------------------------------------------------
-$ git checkout experimental
+$ git switch experimental
 ------------------------------------------------
 
 to switch to the experimental branch.  Now edit a file, commit the
@@ -216,7 +216,7 @@ change, and switch back to the master branch:
 ------------------------------------------------
 (edit file)
 $ git commit -a
-$ git checkout master
+$ git switch master
 ------------------------------------------------
 
 Check that the change you made is no longer visible, since it was
Documentation/gitworkflows.txt +1 -2
index ca11c7bdaf..abc0dc6bc7 100644
@@ -301,8 +301,7 @@ topics on 'next':
 .Rewind and rebuild next
 [caption="Recipe: "]
 =====================================
-* `git checkout next`
-* `git reset --hard master`
+* `git switch -C next master`
 * `git merge ai/topic_in_next1`
 * `git merge ai/topic_in_next2`
 * ...
Documentation/revisions.txt +1 -1
index 72daa20e76..a1c7a65da6 100644
@@ -115,7 +115,7 @@ Here's an example to make it more clear:
 ------------------------------
 $ git config push.default current
 $ git config remote.pushdefault myfork
-$ git checkout -b mybranch origin/master
+$ git switch -c mybranch origin/master
 
 $ git rev-parse --symbolic-full-name @{upstream}
 refs/remotes/origin/master
Documentation/user-manual.txt +28 -28

164 lines not on this page · raw message

advice.c +5 -5
index b224825637..27e39e6514 100644
@@ -191,20 +191,20 @@ void NORETURN die_conclude_merge(void)
 void detach_advice(const char *new_name)
 {
 	const char *fmt =
-	_("Note: checking out '%s'.\n"
+	_("Note: switching to '%s'.\n"
 	"\n"
 	"You are in 'detached HEAD' state. You can look around, make experimental\n"
 	"changes and commit them, and you can discard any commits you make in this\n"
-	"state without impacting any branches by performing another checkout.\n"
+	"state without impacting any branches by switching back to a branch.\n"
 	"\n"
 	"If you want to create a new branch to retain commits you create, you may\n"
-	"do so (now or later) by using -b with the checkout command again. Example:\n"
+	"do so (now or later) by using -c with the switch command. Example:\n"
 	"\n"
-	"  git checkout -b <new-branch-name>\n"
+	"  git switch -c <new-branch-name>\n"
 	"\n"
 	"Or undo this checkout with:\n"
 	"\n"
-	"  git checkout -\n"
+	"  git switch -\n"
 	"\n"
 	"Turn off this advice by setting config variable advice.detachedHead to false\n\n");
 
sha1-name.c +1 -1
index 6dda2c16df..da0518c8e3 100644
@@ -743,7 +743,7 @@ static int get_oid_basic(const char *str, int len, struct object_id *oid,
 	"because it will be ignored when you just specify 40-hex. These refs\n"
 	"may be created by mistake. For example,\n"
 	"\n"
-	"  git checkout -b $br $(git rev-parse ...)\n"
+	"  git switch -c $br $(git rev-parse ...)\n"
 	"\n"
 	"where \"$br\" is somehow empty and a 40-hex ref is created. Please\n"
 	"examine these refs and maybe delete them. Turn this message off by\n"
t/t2020-checkout-detach.sh +10 -10
index 743c7248a2..da6809b48f 100755
@@ -195,20 +195,20 @@ test_expect_success 'describe_detached_head prints no SHA-1 ellipsis when not as
 
 	# The first detach operation is more chatty than the following ones.
 	cat >1st_detach <<-EOF &&
-	Note: checking out 'HEAD^'.
+	Note: switching to 'HEAD^'.
 
 	You are in 'detached HEAD' state. You can look around, make experimental
 	changes and commit them, and you can discard any commits you make in this
-	state without impacting any branches by performing another checkout.
+	state without impacting any branches by switching back to a branch.
 
 	If you want to create a new branch to retain commits you create, you may
-	do so (now or later) by using -b with the checkout command again. Example:
+	do so (now or later) by using -c with the switch command. Example:
 
-	  git checkout -b <new-branch-name>
+	  git switch -c <new-branch-name>
 
 	Or undo this checkout with:
 
-	  git checkout -
+	  git switch -
 
 	Turn off this advice by setting config variable advice.detachedHead to false
 
@@ -277,20 +277,20 @@ test_expect_success 'describe_detached_head does print SHA-1 ellipsis when asked
 
 	# The first detach operation is more chatty than the following ones.
 	cat >1st_detach <<-EOF &&
-	Note: checking out 'HEAD^'.
+	Note: switching to 'HEAD^'.
 
 	You are in 'detached HEAD' state. You can look around, make experimental
 	changes and commit them, and you can discard any commits you make in this
-	state without impacting any branches by performing another checkout.
+	state without impacting any branches by switching back to a branch.
 
 	If you want to create a new branch to retain commits you create, you may
-	do so (now or later) by using -b with the checkout command again. Example:
+	do so (now or later) by using -c with the switch command. Example:
 
-	  git checkout -b <new-branch-name>
+	  git switch -c <new-branch-name>
 
 	Or undo this checkout with:
 
-	  git checkout -
+	  git switch -
 
 	Turn off this advice by setting config variable advice.detachedHead to false
 
Signature · 1 line
2.21.0.548.gd3c7d92dc2
author
#212 lore raw

Re: [PATCH v4 00/26] Add new command 'switch'

In reply to Nguyễn Thái Ngọc Duy
Quoted 20 lines · Nguyễn Thái Ngọc Duy

Thanks for all the comments from v3 (and before), I didn't expect feedback from so many people. v4 fixes most of them, but still leaves a couple for v5.

- -C remains because people seem to need it

- --recreate vs --force-create: there was no strong preference for either, so I stick with --force-create

- --guess (dwim mode) is now made default

- --orphan by default switches to an empty tree instead of current HEAD (this is Elijah's alternative approach). This allows you to start fresh, but you can still keep "HEAD" content or even switch to another tree.

- advice.detachedHead text is updated to suggest a way out (currently it only suggests a way forward with 'checkout -b')

Quoted 7 lines

- --force has a new alias --discard-changes

- the error message when we expect a branch is improved to help point out why the given argument is not a branch

- more docs update and reorganization, and other silly bugs I made in v3

I did forget one thing:

- 'git switch' refuses to switch in the middle of rebase/bisect/cherry-pick/... session. Add --ignore-in-progress to override this

Now that I mention this, --ignore-in-progress should probably be part of --force too. Hmm...

Signature · 1 line
Duy
#213 lore raw

Re: [PATCH v4 00/26] Add new command 'switch'

Quoted 5 lines · Duy Nguyen

I did forget one thing:

- 'git switch' refuses to switch in the middle of rebase/bisect/cherry-pick/... session. Add --ignore-in-progress to override this

I think that is a sensible thing to do. Once I did not realize that a "checkout" from a failed cherry-pick with the state files left in the .git/ directory took me to a strange state, causing some later operation to act on these state files as if a cherry-pick were in progress (and somehow the shell prompt support did not report it, perhaps because the copy I use was out of sync with the binary).

Making sure that during a stateful operation the working tree won't get switched to a different branch is probably a good idea.

I often find "git reset --hard <some other starting point>" after a failed "git checkout -b new <starting point> && git am -s3c", so I'd be opposed to a change to refuse a "reset --hard" during the middle of such a stateful operation, but I do not think of a reason why I would want to "switch" in the middle.

Quoted 2 lines

Now that I mention this, --ignore-in-progress should probably be part of --force too. Hmm...

Probably. You may want to decline other parts of what --force allows but when you say --force, --ignore-in-progress should be implied.

author
#214 lore raw

Re: [PATCH v4 00/26] Add new command 'switch'

Quoted 1 line · Junio C Hamano

I often find "git reset --hard <some other starting point>" after a

It still bugs me that I need to use this to abort some in-progress operation. There's "git X --abort" but I would need to find out what X is first. I would like "git abort" or something (and "git continue") but haven't really thought that through yet. That direction may also lead to "git undo" which is another can of worms.

Quoted 4 lines

failed "git checkout -b new <starting point> && git am -s3c", so I'd be opposed to a change to refuse a "reset --hard" during the middle of such a stateful operation, but I do not think of a reason why I would want to "switch" in the middle.

Signature · 1 line
Duy
#215 lore raw

Re: [PATCH v4 00/26] Add new command 'switch'

Quoted 5 lines · Duy Nguyen
Quoted 1 line · Junio C Hamano

I often find "git reset --hard <some other starting point>" after a

It still bugs me that I need to use this to abort some in-progress operation.

Note that my comment was *NOT* about aborting the in-progress "am". What happens in that "I often find" situation is that I identify the problem's origin, prepare a branch to apply a fix forking from an old release point that includes the origin, and "am" tells me the code diverged too much and it cannot be applied, or "am -3" tells me that the author sent the patch based on some unknown base. At that point, I "git reset --hard" to some plausible place the author would have based the patch (e.g. "master" pushed out last night) and then say "am" or ("am --no-3") to retry.

So your response is unrelated to what I said, but having said that, it still deserves a comment.

Quoted 4 lines

... There's "git X --abort" but I would need to find out what X is first. I would like "git abort" or something (and "git continue") but haven't really thought that through yet. That direction may also lead to "git undo" which is another can of worms.

I rarely had "what was I doing" problem; doesn't the command line prompt tell you? It is debatable (and I am pessimistic) if a general blanket "git abort" makes sense, but the info on the current status (i.e. "what was the user doing?") it must gather should be a strict superset as what is needed to give useful info in the command line prompt, so a good place to start may be to think about what's missing (not shown) in the prompt and if that is deliberate omission (avoiding overly verbose prompt) or is coming from lack of enough information. Then we may need to do something about the latter by teaching these commands with state to leave more clue of what we were in the middle of and what the next step would be.

After thinking about that, the answer might turn out to be to unify the backend of these commands with state to a single one, or at least fewer ones, so that we can have better grasp and control over how these backend engines record state when they give control back to the user.

#216 lore raw

v5 cover Add new command 'switch'

In reply to Nguyễn Thái Ngọc Duy

This adds a new command 'git-switch' as the half-replacement for 'git-checkout'. Jump to 12/26 as the starting point. The other half is git-restore, which is dealt with separately.

The diff delta is shrinking nicely. The two main changes are

- '--orphan <new-branch> <initial-tree>' is no longer accepted
- --force implies --ignore-in-progress

The rest is the usual typo and bug fixes.

The two "todo" items from v4 will be handled separately and will not be mentioned again in v6 (if there is one):

- The 'checkout -m' losing staged changes problem has already been
discussed elsewhere and I'm still trying to see if I can improve it.

- I have some work in progress for improving tracking branch error
message, but it's unlikely to conflict badly with this series.

Nguyễn Thái Ngọc Duy (26):
git-checkout.txt: spell out --no-option git-checkout.txt: fix one syntax line
doc: document --overwrite-ignore
git-checkout.txt: fix monospace typeset
t: rename t2014-switch.sh to t2014-checkout-switch.sh
checkout: advice how to get out of detached HEAD mode
checkout: keep most #include sorted
checkout: factor out some code in parse_branchname_arg()
checkout: make "opts" in cmd_checkout() a pointer
checkout: move 'confict_style' and 'dwim_..' to checkout_opts
checkout: split options[] array in three pieces
checkout: split part of it to new command 'switch'
switch: better names for -b and -B
switch: add --discard-changes
switch: remove -l
switch: stop accepting pathspec
switch: reject "do nothing" case
switch: only allow explicit detached HEAD
switch: add short option for --detach
switch: implicit dwim, use --no-guess to disable it
switch: no worktree status unless real branch switch happens
switch: reject if some operation is in progress
switch: make --orphan switch to an empty tree
t: add tests for switch
completion: support switch
doc: promote "git switch"

 .gitignore                                    |   1 +
 Documentation/config/advice.txt               |  13 +-
 Documentation/config/branch.txt               |   4 +-
 Documentation/config/checkout.txt             |  17 +-
 Documentation/config/diff.txt                 |   3 +-
 Documentation/git-branch.txt                  |  12 +-
 Documentation/git-check-ref-format.txt        |   3 +-
 Documentation/git-checkout.txt                | 221 ++++---
 Documentation/git-format-patch.txt            |   2 +-
 Documentation/git-merge-base.txt              |   2 +-
 Documentation/git-merge.txt                   |   5 +
 Documentation/git-rebase.txt                  |   2 +-
 Documentation/git-remote.txt                  |   2 +-
 Documentation/git-rerere.txt                  |  10 +-
 Documentation/git-reset.txt                   |  20 +-
 Documentation/git-stash.txt                   |   9 +-
 Documentation/git-switch.txt (new)            | 276 ++++++++
 Documentation/gitattributes.txt               |   3 +-
 Documentation/gitcore-tutorial.txt            |  19 +-
 Documentation/giteveryday.txt                 |  24 +-
 Documentation/githooks.txt                    |   8 +-
 Documentation/gittutorial.txt                 |   4 +-
 Documentation/gitworkflows.txt                |   3 +-
 Documentation/revisions.txt                   |   2 +-
 Documentation/user-manual.txt                 |  56 +-
 Makefile                                      |   1 +
 advice.c                                      |  17 +-
 builtin.h                                     |   1 +
 builtin/checkout.c                            | 605 ++++++++++--------
 command-list.txt                              |   1 +
 contrib/completion/git-completion.bash        |  37 +-
 git.c                                         |   1 +
 parse-options-cb.c                            |  17 +
 parse-options.h                               |   1 +
 sha1-name.c                                   |   2 +-
 t/t1090-sparse-checkout-scope.sh              |  14 -
 ...014-switch.sh => t2014-checkout-switch.sh} |   0
 t/t2020-checkout-detach.sh                    |  28 +-
 t/t2060-switch.sh (new +x)                    |  98 +++
 39 files changed, 1051 insertions(+), 493 deletions(-)
 create mode 100644 Documentation/git-switch.txt
 rename t/{t2014-switch.sh => t2014-checkout-switch.sh} (100%)
 create mode 100755 t/t2060-switch.sh

Range-diff dựa trên v4:
1: 535dc1f310 ! 1: 7bcb4b0ff8 doc: document --overwrite-ignore
@@ -22,20 +22,7 @@
+
--recurse-submodules::
--no-recurse-submodules::
-- Using --recurse-submodules will update the content of all initialized
-+ Using --recurse-submodules will update the content of all initialized
- submodules according to the commit recorded in the superproject. If
- local modifications in a submodule would be overwritten the checkout
-- will fail unless -f is used. If nothing (or --no-recurse-submodules)
-+ will fail unless -f is used. If nothing (or --no-recurse-submodules)
- is used, the work trees of submodules will not be updated.
-- Just like linkgit:git-submodule[1], this will detach the
-- submodules HEAD.
-+ Just like linkgit:git-submodule[1], this will detach HEAD of the
-+ submodule.
-
- --no-guess::
- Do not attempt to create a branch if a remote tracking branch
+ Using --recurse-submodules will update the content of all initialized

diff --git a/Documentation/git-merge.txt b/Documentation/git-merge.txt --- a/Documentation/git-merge.txt
2: b6305d2871 ! 2: f2d77152eb git-checkout.txt: fix monospace typeset
@@ -4,8 +4,7 @@

Add backticks where we have none, replace single quotes with backticks and replace double-quotes. Drop double-quotes from nested constructions
- such as "@{-1}". Add a missing possessive apostrophe after the word
- "submodules" while at it.
+ such as "@{-1}".

@@ -207,6 +206,24 @@
This means that you can use git checkout -p to selectively discard edits from your current working tree. See the ``Interactive Mode''
@@
+
+ --recurse-submodules::
+ --no-recurse-submodules::
+- Using --recurse-submodules will update the content of all initialized
++ Using --recurse-submodules will update the content of all initialized
+ submodules according to the commit recorded in the superproject. If
+ local modifications in a submodule would be overwritten the checkout
+- will fail unless -f is used. If nothing (or --no-recurse-submodules)
++ will fail unless -f is used. If nothing (or --no-recurse-submodules)
+ is used, the work trees of submodules will not be updated.
+- Just like linkgit:git-submodule[1], this will detach the
+- submodules HEAD.
++ Just like linkgit:git-submodule[1], this will detach HEAD of the
++ submodule.
+
+ --no-guess::
+ Do not attempt to create a branch if a remote tracking branch
+@@
In the default overlay mode, git checkout never removes files from the index or the working tree. When specifying --no-overlay, files that appear in the index and

 3:  bb56e45457 =  3:  cbe630fb4a t: rename t2014-switch.sh to t2014-checkout-switch.sh
 4:  123392757a =  4:  6bc8a1052f checkout: advice how to get out of detached HEAD mode
 5:  d1ec6b4ce0 =  5:  0bb2aefb85 checkout: keep most #include sorted
 6:  4b1742672b =  6:  ace82aa26f checkout: factor out some code in parse_branchname_arg()
 7:  e0bcc3a4dd =  7:  6e13efcba8 checkout: make "opts" in cmd_checkout() a pointer
 8:  ca5b4d7db0 =  8:  f61a042eb8 checkout: move 'confict_style' and 'dwim_..' to checkout_opts
 9:  13c03997f0 =  9:  972cebc568 checkout: split options[] array in three pieces
10:  24d532b276 ! 10:  970c727b24 checkout: split part of it to new command 'switch'
    @@ -147,9 +147,10 @@
     +SYNOPSIS
     +--------
     +[verse]
    -+'git switch' [<options>] [--guess] <branch>
    ++'git switch' [<options>] [--no-guess] <branch>
     +'git switch' [<options>] --detach [<start-point>]
    -+'git switch' [<options>] (-c|-C|--orphan) <new-branch> [<start-point>]
    ++'git switch' [<options>] (-c|-C) <new-branch> [<start-point>]
    ++'git switch' [<options>] --orphan <new-branch>
     +
     +DESCRIPTION
     +-----------
    @@ -164,8 +165,8 @@
     +
     +Switching branches does not require a clean index and working tree
     +(i.e. no differences compared to `HEAD`). The operation is aborted
    -+however if the switch leads to loss of local changes, unless told
    -+otherwise.
    ++however if the operation leads to loss of local changes, unless told
    ++otherwise with `--discard-changes` or `--merge`.
     +
     +OPTIONS
     +-------
    @@ -183,7 +184,7 @@
     +	from some other point.)
     ++
     +You can use the `@{-N}` syntax to refer to the N-th last
    -+branch/commit switched to "git switch" or "git checkout"
    ++branch/commit switched to using "git switch" or "git checkout"
     +operation. You may also specify `-` which is synonymous to `@{-1}`.
     +This is often used to switch quickly between two branches, or to undo
     +a branch switch by mistake.
    @@ -242,7 +243,7 @@
     +
     +-f::
     +--force::
    -+	An alias for `--discard-changes`.
    ++	An alias for `--discard-changes` and `--ignore-in-progress`.
     +
     +--discard-changes::
     +	Proceed even if the index or the working tree differs from
    @@ -250,6 +251,11 @@
     +	the switching target. This is used to throw away local
     +	changes.
     +
    ++--ignore-in-progress::
    ++	`git switch` by default refuses when some operation is in
    ++	progress (e.g. "git rebase", "git am" ...). This option
    ++	overrides this safety check and allows switching.
    ++
     +-m::
     +--merge::
     +	If you have local modifications to one or more files that are
    @@ -304,10 +310,8 @@
     +	`branch.autoSetupMerge` configuration variable is true.
     +
     +--orphan <new-branch>::
    -+	Create a new 'orphan' branch, named `<new-branch>`. If
    -+	`<start-point>` is specified, the index and working tree are
    -+	adjusted to match it. Otherwise both are adjusted to contain no
    -+	tracked files.
    ++	Create a new 'orphan' branch, named `<new-branch>`. All
    ++	tracked files are removed.
     +
     +--ignore-other-worktrees::
     +	`git switch` refuses when the wanted ref is already
    @@ -315,11 +319,6 @@
     +	the ref out anyway. In other words, the ref can be held by
     +	more than one worktree.
     +
    -+--ignore-in-progress::
    -+	`git switch` by default refuses when some operation is in
    -+	progress (e.g. "git rebase", "git am" ...). This option
    -+	overrides this safety check and allows switching.
    -+
     +--recurse-submodules::
     +--no-recurse-submodules::
     +	Using `--recurse-submodules` will update the content of all initialized
11:  c966bacfcc = 11:  676f5df0fd switch: better names for -b and -B
12:  bdb88bf9a9 ! 12:  4e37c0659e switch: add --discard-changes

@@ -4,8 +4,8 @@

--discard-changes is a better name than --force for this option since it's what really happens. --force is turned to an alias for
- --discard-changes. But it's meant to an alias for potentially more force
- options in the future.
+ --discard-changes. But it's meant to be an alias for potentially more
+ force options in the future.

diff --git a/builtin/checkout.c b/builtin/checkout.c --- a/builtin/checkout.c

13:  d5fe7f4bd0 = 13:  a57208d137 switch: remove -l
14:  3bce4c521e = 14:  3de6f95bf2 switch: stop accepting pathspec
15:  dad0063fc4 = 15:  ad225517cd switch: reject "do nothing" case
16:  41ca042917 = 16:  583cfd5cc4 switch: only allow explicit detached HEAD
17:  a0b9f1b285 = 17:  1c5aee658d switch: add short option for --detach
18:  3d254df104 = 18:  d942ac52e2 switch: implicit dwim, use --no-guess to disable it
19:  c6ea203f36 = 19:  37eb152c0d switch: no worktree status unless real branch switch happens
20:  5c4effc7fd ! 20:  50d6768afd switch: reject if some operation is in progress
    @@ -12,6 +12,9 @@
         that separate thing you want to work on and leave this worktree
         alone (unless of course creating or preparing worktrees are not cheap).
     
    +    --force is updated to also imply --ignore-in-progress because it is
    +    supposed to be the "just do your things and don't bother me" option.
    +
      diff --git a/builtin/checkout.c b/builtin/checkout.c
      --- a/builtin/checkout.c
      +++ b/builtin/checkout.c
    @@ -45,7 +48,7 @@
     +			die(_("cannot switch branch while merging"));
     +		if (state.am_in_progress)
     +			die(_("cannot switch branch in the middle of an am session"));
    -+		if (state.rebase_in_progress || state.rebase_in_progress)
    ++		if (state.rebase_interactive_in_progress || state.rebase_in_progress)
     +			die(_("cannot switch branch while rebasing"));
     +		if (state.cherry_pick_in_progress)
     +			die(_("cannot switch branch while cherry-picking"));
    @@ -58,6 +61,18 @@
      	if (new_branch_info->path && !opts->force_detach && !opts->new_branch &&
      	    !opts->ignore_other_worktrees) {
      		int flag;
    +@@
    + 		opts->merge = 1; /* implied */
    + 		git_xmerge_config("merge.conflictstyle", opts->conflict_style, NULL);
    + 	}
    +-	if (opts->force)
    ++	if (opts->force) {
    + 		opts->discard_changes = 1;
    ++		opts->can_switch_when_in_progress = 1;
    ++	}
    + 
    + 	if ((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) > 1)
    + 		die(_("-b, -B and --orphan are mutually exclusive"));
     @@
      	opts.only_merge_on_switching_branches = 0;
      	opts.accept_pathspec = 1;
21:  a4afe6a999 ! 21:  af8bb710c8 switch: --orphan defaults to empty tree as HEAD
    @@ -1,15 +1,16 @@
     Author: Nguyễn Thái Ngọc Duy <[email protected]>
     
    -    switch: --orphan defaults to empty tree as HEAD
    +    switch: make --orphan switch to an empty tree
     
         Switching and creating branches always involves knowing the
         <start-point> to begin the new branch from. Sometimes, people want to
         create a new branch that does not have any commits yet; --orphan is a
         flag to allow that.
     
    -    If <start-point> is not specified, instead of leaving index/worktree
    -    unchanged, default to "empty tree" starting point, allowing a clean
    -    start.
    +    --orphan overrides the default of HEAD for <start-point> instead causing
    +    us to start from an empty history with all tracked files removed from
    +    the index and working tree. The use of --orphan is incompatible with
    +    specifying a <start-point>.
     
         A note on the implementation. An alternative is just create a dummy
         commit in-core with empty tree and switch to it. But there's a chance
    @@ -23,7 +24,7 @@
      	int switch_branch_doing_nothing_is_ok;
      	int only_merge_on_switching_branches;
      	int can_switch_when_in_progress;
    -+	int orphan_default_empty_tree;
    ++	int orphan_from_empty_tree;
      
      	const char *new_branch;
      	const char *new_branch_force;
    @@ -38,9 +39,11 @@
      		return error(_("index file corrupt"));
      
      	resolve_undo_clear();
    -+	if (opts->orphan_default_empty_tree && !new_branch_info->commit)
    ++	if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
    ++		if (new_branch_info->commit)
    ++			BUG("'switch --orphan' should never accept a commit as starting point");
     +		new_tree = parse_tree_indirect(the_hash_algo->empty_tree);
    -+	else
    ++	} else
     +		new_tree = get_commit_tree(new_branch_info->commit);
      	if (opts->discard_changes) {
     -		ret = reset_tree(get_commit_tree(new_branch_info->commit),
    @@ -106,23 +109,34 @@
      	if (prepare_revision_walk(&revs))
      		die(_("internal error in revision walk"));
     @@
    + 	if (old_branch_info.path)
    + 		skip_prefix(old_branch_info.path, "refs/heads/", &old_branch_info.name);
      
    - 		if (opts->only_merge_on_switching_branches)
    - 			do_merge = 0;
    ++	if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
    ++		if (new_branch_info->name)
    ++			BUG("'switch --orphan' should never accept a commit as starting point");
    ++		new_branch_info->commit = NULL;
    ++		new_branch_info->name = "(empty)";
    ++		do_merge = 1;
    ++	}
     +
    -+		if (opts->new_orphan_branch && opts->orphan_default_empty_tree) {
    -+			new_branch_info->commit = NULL;
    -+			new_branch_info->name = "(empty)";
    -+			do_merge = 1;
    -+		}
    - 	}
    - 
    - 	if (do_merge) {
    + 	if (!new_branch_info->name) {
    + 		new_branch_info->name = "HEAD";
    + 		new_branch_info->commit = old_branch_info.commit;
    +@@
    + 	if (opts->new_orphan_branch) {
    + 		if (opts->track != BRANCH_TRACK_UNSPECIFIED)
    + 			die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
    ++		if (opts->orphan_from_empty_tree && new_branch_info->name)
    ++			die(_("'%s' cannot take <start-point>"), "--orphan");
    + 	} else if (opts->force_detach) {
    + 		if (opts->track != BRANCH_TRACK_UNSPECIFIED)
    + 			die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
     @@
      	opts.accept_pathspec = 1;
      	opts.implicit_detach = 1;
      	opts.can_switch_when_in_progress = 1;
    -+	opts.orphan_default_empty_tree = 0;
    ++	opts.orphan_from_empty_tree = 0;
      
      	options = parse_options_dup(checkout_options);
      	options = add_common_options(&opts, options);
    @@ -130,7 +144,7 @@
      	opts.only_merge_on_switching_branches = 1;
      	opts.implicit_detach = 0;
      	opts.can_switch_when_in_progress = 0;
    -+	opts.orphan_default_empty_tree = 1;
    ++	opts.orphan_from_empty_tree = 1;
      
      	options = parse_options_dup(switch_options);
      	options = add_common_options(&opts, options);
22:  6cca78f835 ! 22:  4a293a3d53 t: add tests for switch
    @@ -67,6 +67,7 @@
     +
     +test_expect_success 'new orphan branch from empty' '
     +	test_when_finished git switch master &&
    ++	test_must_fail git switch --orphan new-orphan HEAD &&
     +	git switch --orphan new-orphan &&
     +	test_commit orphan &&
     +	git cat-file commit refs/heads/new-orphan >commit &&
23:  e5e6f9d6f1 = 23:  b10290b378 completion: support switch
24:  807e8bc50b = 24:  67c5175e5f doc: promote "git switch"
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#217 lore raw

PATCH v5 1/26 git-checkout.txt: spell out --no-option

It's easier to search for and also less cryptic.

---
 Documentation/git-checkout.txt | 11 +++++++----
 1 file changed, 7 insertions(+), 4 deletions(-)
Documentation/git-checkout.txt +7 -4
index f179b43732..99c8c0dc0f 100644
@@ -118,7 +118,8 @@ OPTIONS
 --quiet::
 	Quiet, suppress feedback messages.
 
---[no-]progress::
+--progress::
+--no-progress::
 	Progress status is reported on the standard error stream
 	by default when it is attached to a terminal, unless `--quiet`
 	is specified. This flag enables progress reporting even if not
@@ -262,7 +263,7 @@ edits from your current working tree. See the ``Interactive Mode''
 section of linkgit:git-add[1] to learn how to operate the `--patch` mode.
 +
 Note that this option uses the no overlay mode by default (see also
-`--[no-]overlay`), and currently doesn't support overlay mode.
+`--overlay`), and currently doesn't support overlay mode.
 
 --ignore-other-worktrees::
 	`git checkout` refuses when the wanted ref is already checked
@@ -270,7 +271,8 @@ Note that this option uses the no overlay mode by default (see also
 	out anyway. In other words, the ref can be held by more than one
 	worktree.
 
---[no-]recurse-submodules::
+--recurse-submodules::
+--no-recurse-submodules::
 	Using --recurse-submodules will update the content of all initialized
 	submodules according to the commit recorded in the superproject. If
 	local modifications in a submodule would be overwritten the checkout
@@ -283,7 +285,8 @@ Note that this option uses the no overlay mode by default (see also
 	Do not attempt to create a branch if a remote tracking branch
 	of the same name exists.
 
---[no-]overlay::
+--overlay::
+--no-overlay::
 	In the default overlay mode, `git checkout` never
 	removes files from the index or the working tree.  When
 	specifying `--no-overlay`, files that appear in the index and
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#218 lore raw

PATCH v5 2/26 git-checkout.txt: fix one syntax line

In reply to Nguyễn Thái Ngọc Duy

<branch> can be omitted in this syntax, and it's actually documented a few paragraphs down:

You could omit <branch>, in which case the command degenerates to "check out the current branch", which is a glorified no-op with rather expensive side-effects to show only the tracking information, if exists, for the current branch.

---
 Documentation/git-checkout.txt | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
Documentation/git-checkout.txt +1 -1
index 99c8c0dc0f..28817cfa41 100644
@@ -23,7 +23,7 @@ or the specified tree.  If no paths are given, 'git checkout' will
 also update `HEAD` to set the specified branch as the current
 branch.
 
-'git checkout' <branch>::
+'git checkout' [<branch>]::
 	To prepare for working on <branch>, switch to it by updating
 	the index and the files in the working tree, and by pointing
 	HEAD at the branch. Local modifications to the files in the
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#219 lore raw

PATCH v5 3/26 doc: document --overwrite-ignore

In reply to Nguyễn Thái Ngọc Duy

I added this option in git-checkout and git-merge in c1d7036b6b (checkout,merge: disallow overwriting ignored files with --no-overwrite-ignore - 2011-11-27) but did not remember to update documentation. This completes that commit.

---
 Documentation/git-checkout.txt | 6 ++++++
 Documentation/git-merge.txt    | 5 +++++
 2 files changed, 11 insertions(+)
Documentation/git-checkout.txt +6 -0
index 28817cfa41..5280d1f9ed 100644
@@ -271,6 +271,12 @@ Note that this option uses the no overlay mode by default (see also
 	out anyway. In other words, the ref can be held by more than one
 	worktree.
 
+--overwrite-ignore::
+--no-overwrite-ignore::
+	Silently overwrite ignored files when switching branches. This
+	is the default behavior. Use `--no-overwrite-ignore` to abort
+	the operation when the new branch contains ignored files.
+
 --recurse-submodules::
 --no-recurse-submodules::
 	Using --recurse-submodules will update the content of all initialized
Documentation/git-merge.txt +5 -0
index 4cc86469f3..6a9163d8fe 100644
@@ -87,6 +87,11 @@ will be appended to the specified message.
 	Allow the rerere mechanism to update the index with the
 	result of auto-conflict resolution if possible.
 
+--overwrite-ignore::
+--no-overwrite-ignore::
+	Silently overwrite ignored files from the merge result. This
+	is the default behavior. Use `--no-overwrite-ignore` to abort.
+
 --abort::
 	Abort the current conflict resolution process, and
 	try to reconstruct the pre-merge state.
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#220 lore raw

PATCH v5 4/26 git-checkout.txt: fix monospace typeset

In reply to Nguyễn Thái Ngọc Duy

Add backticks where we have none, replace single quotes with backticks and replace double-quotes. Drop double-quotes from nested constructions such as "@{-1}".

---
 Documentation/git-checkout.txt | 162 ++++++++++++++++-----------------
 1 file changed, 81 insertions(+), 81 deletions(-)
Documentation/git-checkout.txt +81 -81
index 5280d1f9ed..bf90966c95 100644
@@ -24,14 +24,14 @@ also update `HEAD` to set the specified branch as the current
 branch.
 
 'git checkout' [<branch>]::
-	To prepare for working on <branch>, switch to it by updating
+	To prepare for working on `<branch>`, switch to it by updating
 	the index and the files in the working tree, and by pointing
-	HEAD at the branch. Local modifications to the files in the
+	`HEAD` at the branch. Local modifications to the files in the
 	working tree are kept, so that they can be committed to the
-	<branch>.
+	`<branch>`.
 +
-If <branch> is not found but there does exist a tracking branch in
-exactly one remote (call it <remote>) with a matching name, treat as
+If `<branch>` is not found but there does exist a tracking branch in
+exactly one remote (call it `<remote>`) with a matching name, treat as
 equivalent to
 +
 ------------
@@ -47,7 +47,7 @@ branches from there if `<branch>` is ambiguous but exists on the
 'origin' remote. See also `checkout.defaultRemote` in
 linkgit:git-config[1].
 +
-You could omit <branch>, in which case the command degenerates to
+You could omit `<branch>`, in which case the command degenerates to
 "check out the current branch", which is a glorified no-op with
 rather expensive side-effects to show only the tracking information,
 if exists, for the current branch.
@@ -61,7 +61,7 @@ if exists, for the current branch.
 	`--track` without `-b` implies branch creation; see the
 	description of `--track` below.
 +
-If `-B` is given, <new_branch> is created if it doesn't exist; otherwise, it
+If `-B` is given, `<new_branch>` is created if it doesn't exist; otherwise, it
 is reset. This is the transactional equivalent of
 +
 ------------
@@ -75,25 +75,25 @@ successful.
 'git checkout' --detach [<branch>]::
 'git checkout' [--detach] <commit>::
 
-	Prepare to work on top of <commit>, by detaching HEAD at it
+	Prepare to work on top of `<commit>`, by detaching `HEAD` at it
 	(see "DETACHED HEAD" section), and updating the index and the
 	files in the working tree.  Local modifications to the files
 	in the working tree are kept, so that the resulting working
 	tree will be the state recorded in the commit plus the local
 	modifications.
 +
-When the <commit> argument is a branch name, the `--detach` option can
-be used to detach HEAD at the tip of the branch (`git checkout
-<branch>` would check out that branch without detaching HEAD).
+When the `<commit>` argument is a branch name, the `--detach` option can
+be used to detach `HEAD` at the tip of the branch (`git checkout
+<branch>` would check out that branch without detaching `HEAD`).
 +
-Omitting <branch> detaches HEAD at the tip of the current branch.
+Omitting `<branch>` detaches `HEAD` at the tip of the current branch.
 
 'git checkout' [<tree-ish>] [--] <pathspec>...::
 
 	Overwrite paths in the working tree by replacing with the
-	contents in the index or in the <tree-ish> (most often a
-	commit).  When a <tree-ish> is given, the paths that
-	match the <pathspec> are updated both in the index and in
+	contents in the index or in the `<tree-ish>` (most often a
+	commit).  When a `<tree-ish>` is given, the paths that
+	match the `<pathspec>` are updated both in the index and in
 	the working tree.
 +
 The index may contain unmerged entries because of a previous failed merge.
@@ -128,7 +128,7 @@ OPTIONS
 -f::
 --force::
 	When switching branches, proceed even if the index or the
-	working tree differs from HEAD.  This is used to throw away
+	working tree differs from `HEAD`.  This is used to throw away
 	local changes.
 +
 When checking out paths from the index, do not fail upon unmerged
@@ -155,12 +155,12 @@ on your side branch as `theirs` (i.e. "one contributor's work on top
 of it").
 
 -b <new_branch>::
-	Create a new branch named <new_branch> and start it at
-	<start_point>; see linkgit:git-branch[1] for details.
+	Create a new branch named `<new_branch>` and start it at
+	`<start_point>`; see linkgit:git-branch[1] for details.
 
 -B <new_branch>::
-	Creates the branch <new_branch> and start it at <start_point>;
-	if it already exists, then reset it to <start_point>. This is
+	Creates the branch `<new_branch>` and start it at `<start_point>`;
+	if it already exists, then reset it to `<start_point>`. This is
 	equivalent to running "git branch" with "-f"; see
 	linkgit:git-branch[1] for details.
 
@@ -173,15 +173,15 @@ If no `-b` option is given, the name of the new branch will be
 derived from the remote-tracking branch, by looking at the local part of
 the refspec configured for the corresponding remote, and then stripping
 the initial part up to the "*".
-This would tell us to use "hack" as the local branch when branching
-off of "origin/hack" (or "remotes/origin/hack", or even
-"refs/remotes/origin/hack").  If the given name has no slash, or the above
+This would tell us to use `hack` as the local branch when branching
+off of `origin/hack` (or `remotes/origin/hack`, or even
+`refs/remotes/origin/hack`).  If the given name has no slash, or the above
 guessing results in an empty name, the guessing is aborted.  You can
 explicitly give a name with `-b` in such a case.
 
 --no-track::
 	Do not set up "upstream" configuration, even if the
-	branch.autoSetupMerge configuration variable is true.
+	`branch.autoSetupMerge` configuration variable is true.
 
 -l::
 	Create the new branch's reflog; see linkgit:git-branch[1] for
@@ -190,21 +190,21 @@ explicitly give a name with `-b` in such a case.
 --detach::
 	Rather than checking out a branch to work on it, check out a
 	commit for inspection and discardable experiments.
-	This is the default behavior of "git checkout <commit>" when
-	<commit> is not a branch name.  See the "DETACHED HEAD" section
+	This is the default behavior of `git checkout <commit>` when
+	`<commit>` is not a branch name.  See the "DETACHED HEAD" section
 	below for details.
 
 --orphan <new_branch>::
-	Create a new 'orphan' branch, named <new_branch>, started from
-	<start_point> and switch to it.  The first commit made on this
+	Create a new 'orphan' branch, named `<new_branch>`, started from
+	`<start_point>` and switch to it.  The first commit made on this
 	new branch will have no parents and it will be the root of a new
 	history totally disconnected from all the other branches and
 	commits.
 +
 The index and the working tree are adjusted as if you had previously run
-"git checkout <start_point>".  This allows you to start a new history
-that records a set of paths similar to <start_point> by easily running
-"git commit -a" to make the root commit.
+`git checkout <start_point>`.  This allows you to start a new history
+that records a set of paths similar to `<start_point>` by easily running
+`git commit -a` to make the root commit.
 +
 This can be useful when you want to publish the tree from a commit
 without exposing its full history. You might want to do this to publish
@@ -213,17 +213,17 @@ whose full history contains proprietary or otherwise encumbered bits of
 code.
 +
 If you want to start a disconnected history that records a set of paths
-that is totally different from the one of <start_point>, then you should
+that is totally different from the one of `<start_point>`, then you should
 clear the index and the working tree right after creating the orphan
-branch by running "git rm -rf ." from the top level of the working tree.
+branch by running `git rm -rf .` from the top level of the working tree.
 Afterwards you will be ready to prepare your new files, repopulating the
 working tree, by copying them from elsewhere, extracting a tarball, etc.
 
 --ignore-skip-worktree-bits::
 	In sparse checkout mode, `git checkout -- <paths>` would
-	update only entries matched by <paths> and sparse patterns
-	in $GIT_DIR/info/sparse-checkout. This option ignores
-	the sparse patterns and adds back any files in <paths>.
+	update only entries matched by `<paths>` and sparse patterns
+	in `$GIT_DIR/info/sparse-checkout`. This option ignores
+	the sparse patterns and adds back any files in `<paths>`.
 
 -m::
 --merge::
@@ -245,18 +245,18 @@ When checking out paths from the index, this option lets you recreate
 the conflicted merge in the specified paths.
 
 --conflict=<style>::
-	The same as --merge option above, but changes the way the
+	The same as `--merge` option above, but changes the way the
 	conflicting hunks are presented, overriding the
-	merge.conflictStyle configuration variable.  Possible values are
+	`merge.conflictStyle` configuration variable.  Possible values are
 	"merge" (default) and "diff3" (in addition to what is shown by
 	"merge" style, shows the original contents).
 
 -p::
 --patch::
 	Interactively select hunks in the difference between the
-	<tree-ish> (or the index, if unspecified) and the working
+	`<tree-ish>` (or the index, if unspecified) and the working
 	tree.  The chosen hunks are then applied in reverse to the
-	working tree (and if a <tree-ish> was specified, the index).
+	working tree (and if a `<tree-ish>` was specified, the index).
 +
 This means that you can use `git checkout -p` to selectively discard
 edits from your current working tree. See the ``Interactive Mode''
@@ -279,13 +279,13 @@ Note that this option uses the no overlay mode by default (see also
 
 --recurse-submodules::
 --no-recurse-submodules::
-	Using --recurse-submodules will update the content of all initialized
+	Using `--recurse-submodules` will update the content of all initialized
 	submodules according to the commit recorded in the superproject. If
 	local modifications in a submodule would be overwritten the checkout
-	will fail unless `-f` is used. If nothing (or --no-recurse-submodules)
+	will fail unless `-f` is used. If nothing (or `--no-recurse-submodules`)
 	is used, the work trees of submodules will not be updated.
-	Just like linkgit:git-submodule[1], this will detach the
-	submodules HEAD.
+	Just like linkgit:git-submodule[1], this will detach `HEAD` of the
+	submodule.
 
 --no-guess::
 	Do not attempt to create a branch if a remote tracking branch
@@ -296,21 +296,21 @@ Note that this option uses the no overlay mode by default (see also
 	In the default overlay mode, `git checkout` never
 	removes files from the index or the working tree.  When
 	specifying `--no-overlay`, files that appear in the index and
-	working tree, but not in <tree-ish> are removed, to make them
-	match <tree-ish> exactly.
+	working tree, but not in `<tree-ish>` are removed, to make them
+	match `<tree-ish>` exactly.
 
 <branch>::
 	Branch to checkout; if it refers to a branch (i.e., a name that,
 	when prepended with "refs/heads/", is a valid ref), then that
 	branch is checked out. Otherwise, if it refers to a valid
-	commit, your HEAD becomes "detached" and you are no longer on
+	commit, your `HEAD` becomes "detached" and you are no longer on
 	any branch (see below for details).
 +
-You can use the `"@{-N}"` syntax to refer to the N-th last
+You can use the `@{-N}` syntax to refer to the N-th last
 branch/commit checked out using "git checkout" operation. You may
-also specify `-` which is synonymous to `"@{-1}"`.
+also specify `-` which is synonymous to `@{-1}`.
 +
-As a special case, you may use `"A...B"` as a shortcut for the
+As a special case, you may use `A...B` as a shortcut for the
 merge base of `A` and `B` if there is exactly one merge base. You can
 leave out at most one of `A` and `B`, in which case it defaults to `HEAD`.
 
@@ -319,7 +319,7 @@ leave out at most one of `A` and `B`, in which case it defaults to `HEAD`.
 
 <start_point>::
 	The name of a commit at which to start the new branch; see
-	linkgit:git-branch[1] for details. Defaults to HEAD.
+	linkgit:git-branch[1] for details. Defaults to `HEAD`.
 
 <tree-ish>::
 	Tree to checkout from (when paths are given). If not specified,
@@ -329,9 +329,9 @@ leave out at most one of `A` and `B`, in which case it defaults to `HEAD`.
 
 DETACHED HEAD
 -------------
-HEAD normally refers to a named branch (e.g. 'master'). Meanwhile, each
+`HEAD` normally refers to a named branch (e.g. `master`). Meanwhile, each
 branch refers to a specific commit. Let's look at a repo with three
-commits, one of them tagged, and with branch 'master' checked out:
+commits, one of them tagged, and with branch `master` checked out:
 
 ------------
            HEAD (refers to branch 'master')
@@ -344,10 +344,10 @@ a---b---c  branch 'master' (refers to commit 'c')
 ------------
 
 When a commit is created in this state, the branch is updated to refer to
-the new commit. Specifically, 'git commit' creates a new commit 'd', whose
-parent is commit 'c', and then updates branch 'master' to refer to new
-commit 'd'. HEAD still refers to branch 'master' and so indirectly now refers
-to commit 'd':
+the new commit. Specifically, 'git commit' creates a new commit `d`, whose
+parent is commit `c`, and then updates branch `master` to refer to new
+commit `d`. `HEAD` still refers to branch `master` and so indirectly now refers
+to commit `d`:
 
 ------------
 $ edit; git add; git commit
@@ -364,7 +364,7 @@ a---b---c---d  branch 'master' (refers to commit 'd')
 It is sometimes useful to be able to checkout a commit that is not at
 the tip of any named branch, or even to create a new commit that is not
 referenced by a named branch. Let's look at what happens when we
-checkout commit 'b' (here we show two ways this may be done):
+checkout commit `b` (here we show two ways this may be done):
 
 ------------
 $ git checkout v2.0  # or
@@ -379,9 +379,9 @@ a---b---c---d  branch 'master' (refers to commit 'd')
   tag 'v2.0' (refers to commit 'b')
 ------------
 
-Notice that regardless of which checkout command we use, HEAD now refers
-directly to commit 'b'. This is known as being in detached HEAD state.
-It means simply that HEAD refers to a specific commit, as opposed to
+Notice that regardless of which checkout command we use, `HEAD` now refers
+directly to commit `b`. This is known as being in detached `HEAD` state.
+It means simply that `HEAD` refers to a specific commit, as opposed to
 referring to a named branch. Let's see what happens when we create a commit:
 
 ------------
@@ -398,7 +398,7 @@ a---b---c---d  branch 'master' (refers to commit 'd')
   tag 'v2.0' (refers to commit 'b')
 ------------
 
-There is now a new commit 'e', but it is referenced only by HEAD. We can
+There is now a new commit `e`, but it is referenced only by `HEAD`. We can
 of course add yet another commit in this state:
 
 ------------
@@ -416,7 +416,7 @@ a---b---c---d  branch 'master' (refers to commit 'd')
 ------------
 
 In fact, we can perform all the normal Git operations. But, let's look
-at what happens when we then checkout master:
+at what happens when we then checkout `master`:
 
 ------------
 $ git checkout master
@@ -431,9 +431,9 @@ a---b---c---d  branch 'master' (refers to commit 'd')
 ------------
 
 It is important to realize that at this point nothing refers to commit
-'f'. Eventually commit 'f' (and by extension commit 'e') will be deleted
+`f`. Eventually commit `f` (and by extension commit `e`) will be deleted
 by the routine Git garbage collection process, unless we create a reference
-before that happens. If we have not yet moved away from commit 'f',
+before that happens. If we have not yet moved away from commit `f`,
 any of these will create a reference to it:
 
 ------------
@@ -442,19 +442,19 @@ $ git branch foo        <2>
 $ git tag foo           <3>
 ------------
 
-<1> creates a new branch 'foo', which refers to commit 'f', and then
-    updates HEAD to refer to branch 'foo'. In other words, we'll no longer
-    be in detached HEAD state after this command.
+<1> creates a new branch `foo`, which refers to commit `f`, and then
+    updates `HEAD` to refer to branch `foo`. In other words, we'll no longer
+    be in detached `HEAD` state after this command.
 
-<2> similarly creates a new branch 'foo', which refers to commit 'f',
-    but leaves HEAD detached.
+<2> similarly creates a new branch `foo`, which refers to commit `f`,
+    but leaves `HEAD` detached.
 
-<3> creates a new tag 'foo', which refers to commit 'f',
-    leaving HEAD detached.
+<3> creates a new tag `foo`, which refers to commit `f`,
+    leaving `HEAD` detached.
 
-If we have moved away from commit 'f', then we must first recover its object
+If we have moved away from commit `f`, then we must first recover its object
 name (typically by using git reflog), and then we can create a reference to
-it. For example, to see the last two commits to which HEAD referred, we
+it. For example, to see the last two commits to which `HEAD` referred, we
 can use either of these commands:
 
 ------------
@@ -465,12 +465,12 @@ $ git log -g -2 HEAD
 ARGUMENT DISAMBIGUATION
 -----------------------
 
-When there is only one argument given and it is not `--` (e.g. "git
-checkout abc"), and when the argument is both a valid `<tree-ish>`
-(e.g. a branch "abc" exists) and a valid `<pathspec>` (e.g. a file
+When there is only one argument given and it is not `--` (e.g. `git
+checkout abc`), and when the argument is both a valid `<tree-ish>`
+(e.g. a branch `abc` exists) and a valid `<pathspec>` (e.g. a file
 or a directory whose name is "abc" exists), Git would usually ask
 you to disambiguate.  Because checking out a branch is so common an
-operation, however, "git checkout abc" takes "abc" as a `<tree-ish>`
+operation, however, `git checkout abc` takes "abc" as a `<tree-ish>`
 in such a situation.  Use `git checkout -- <pathspec>` if you want
 to checkout these paths out of the index.
 
@@ -478,7 +478,7 @@ EXAMPLES
 --------
 
 . The following sequence checks out the `master` branch, reverts
-  the `Makefile` to two revisions back, deletes hello.c by
+  the `Makefile` to two revisions back, deletes `hello.c` by
   mistake, and gets it back from the index.
 +
 ------------
@@ -490,7 +490,7 @@ $ git checkout hello.c            <3>
 +
 <1> switch branch
 <2> take a file out of another commit
-<3> restore hello.c from the index
+<3> restore `hello.c` from the index
 +
 If you want to check out _all_ C source files out of the index,
 you can say
@@ -519,7 +519,7 @@ $ git checkout -- hello.c
 $ git checkout mytopic
 ------------
 +
-However, your "wrong" branch and correct "mytopic" branch may
+However, your "wrong" branch and correct `mytopic` branch may
 differ in files that you have modified locally, in which case
 the above checkout would fail like this:
 +
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#221 lore raw

PATCH v5 5/26 t: rename t2014-switch.sh to t2014-checkout-switch.sh

In reply to Nguyễn Thái Ngọc Duy

The old name does not really say that this is about 'checkout -b'. See 49d833dc07 (Revert "checkout branch: prime cache-tree fully" - 2009-05-12) for more information

---
 t/{t2014-switch.sh => t2014-checkout-switch.sh} | 0
 1 file changed, 0 insertions(+), 0 deletions(-)
t/t2014-checkout-switch.sh renamed from t/t2014-switch.sh +0 -0
similarity index 100%
rename from t/t2014-switch.sh
rename to t/t2014-checkout-switch.sh
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#222 lore raw

PATCH v5 6/26 checkout: advice how to get out of detached HEAD mode

In reply to Nguyễn Thái Ngọc Duy

Detached HEAD mode is considered dangerous and confusing for newcomers and we print a big block of warning how to move forward. But we should also suggest the user the way to get out of it if they get into detached HEAD by mistake.

While at there, I also suggest how to turn the advice off. This is another thing I find annoying with advices and should be dealt with in a more generic way. But that may require some refactoring in advice.c first.

---
 advice.c                   | 17 +++++++++++++----
 t/t2020-checkout-detach.sh | 12 ++++++++++++
 2 files changed, 25 insertions(+), 4 deletions(-)
advice.c +13 -4
index 567209aa79..b224825637 100644
@@ -191,13 +191,22 @@ void NORETURN die_conclude_merge(void)
 void detach_advice(const char *new_name)
 {
 	const char *fmt =
-	_("Note: checking out '%s'.\n\n"
+	_("Note: checking out '%s'.\n"
+	"\n"
 	"You are in 'detached HEAD' state. You can look around, make experimental\n"
 	"changes and commit them, and you can discard any commits you make in this\n"
-	"state without impacting any branches by performing another checkout.\n\n"
+	"state without impacting any branches by performing another checkout.\n"
+	"\n"
 	"If you want to create a new branch to retain commits you create, you may\n"
-	"do so (now or later) by using -b with the checkout command again. Example:\n\n"
-	"  git checkout -b <new-branch-name>\n\n");
+	"do so (now or later) by using -b with the checkout command again. Example:\n"
+	"\n"
+	"  git checkout -b <new-branch-name>\n"
+	"\n"
+	"Or undo this checkout with:\n"
+	"\n"
+	"  git checkout -\n"
+	"\n"
+	"Turn off this advice by setting config variable advice.detachedHead to false\n\n");
 
 	fprintf(stderr, fmt, new_name);
 }
t/t2020-checkout-detach.sh +12 -0
index 1fa670625c..743c7248a2 100755
@@ -206,6 +206,12 @@ test_expect_success 'describe_detached_head prints no SHA-1 ellipsis when not as
 
 	  git checkout -b <new-branch-name>
 
+	Or undo this checkout with:
+
+	  git checkout -
+
+	Turn off this advice by setting config variable advice.detachedHead to false
+
 	HEAD is now at \$commit three
 	EOF
 
@@ -282,6 +288,12 @@ test_expect_success 'describe_detached_head does print SHA-1 ellipsis when asked
 
 	  git checkout -b <new-branch-name>
 
+	Or undo this checkout with:
+
+	  git checkout -
+
+	Turn off this advice by setting config variable advice.detachedHead to false
+
 	HEAD is now at \$commit... three
 	EOF
 
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#223 lore raw

PATCH v5 7/26 checkout: keep most #include sorted

In reply to Nguyễn Thái Ngọc Duy

The include list becomes very long and frankly a bit unorganized. With the exception of builtin.h, cache.h or git-compat-util.h which have to come first, keep the rest sorted.

---
 builtin/checkout.c | 34 +++++++++++++++++-----------------
 1 file changed, 17 insertions(+), 17 deletions(-)
builtin/checkout.c +17 -17
index 0e6037b296..f7801db2fb 100644
@@ -1,30 +1,30 @@
 #define USE_THE_INDEX_COMPATIBILITY_MACROS
 #include "builtin.h"
-#include "config.h"
+#include "advice.h"
+#include "blob.h"
+#include "branch.h"
+#include "cache-tree.h"
 #include "checkout.h"
+#include "commit.h"
+#include "config.h"
+#include "diff.h"
+#include "dir.h"
+#include "ll-merge.h"
 #include "lockfile.h"
+#include "merge-recursive.h"
+#include "object-store.h"
 #include "parse-options.h"
 #include "refs.h"
-#include "object-store.h"
-#include "commit.h"
+#include "remote.h"
+#include "resolve-undo.h"
+#include "revision.h"
+#include "run-command.h"
+#include "submodule.h"
+#include "submodule-config.h"
 #include "tree.h"
 #include "tree-walk.h"
-#include "cache-tree.h"
 #include "unpack-trees.h"
-#include "dir.h"
-#include "run-command.h"
-#include "merge-recursive.h"
-#include "branch.h"
-#include "diff.h"
-#include "revision.h"
-#include "remote.h"
-#include "blob.h"
 #include "xdiff-interface.h"
-#include "ll-merge.h"
-#include "resolve-undo.h"
-#include "submodule-config.h"
-#include "submodule.h"
-#include "advice.h"
 
 static int checkout_optimize_new_branch;
 
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#224 lore raw

PATCH v5 8/26 checkout: factor out some code in parse_branchname_arg()

In reply to Nguyễn Thái Ngọc Duy

This is in preparation for the new command restore, which also needs to parse opts->source_tree but does not need all the disambiguation logic.

---
 builtin/checkout.c | 51 ++++++++++++++++++++++++++++------------------
 1 file changed, 31 insertions(+), 20 deletions(-)
builtin/checkout.c +31 -20
index f7801db2fb..1ce0446bc6 100644
@@ -1081,6 +1081,34 @@ static int git_checkout_config(const char *var, const char *value, void *cb)
 	return git_xmerge_config(var, value, NULL);
 }
 
+static void setup_new_branch_info_and_source_tree(
+	struct branch_info *new_branch_info,
+	struct checkout_opts *opts,
+	struct object_id *rev,
+	const char *arg)
+{
+	struct tree **source_tree = &opts->source_tree;
+	struct object_id branch_rev;
+
+	new_branch_info->name = arg;
+	setup_branch_path(new_branch_info);
+
+	if (!check_refname_format(new_branch_info->path, 0) &&
+	    !read_ref(new_branch_info->path, &branch_rev))
+		oidcpy(rev, &branch_rev);
+	else
+		new_branch_info->path = NULL; /* not an existing branch */
+
+	new_branch_info->commit = lookup_commit_reference_gently(the_repository, rev, 1);
+	if (!new_branch_info->commit) {
+		/* not a commit */
+		*source_tree = parse_tree_indirect(rev);
+	} else {
+		parse_commit_or_die(new_branch_info->commit);
+		*source_tree = get_commit_tree(new_branch_info->commit);
+	}
+}
+
 static int parse_branchname_arg(int argc, const char **argv,
 				int dwim_new_local_branch_ok,
 				struct branch_info *new_branch_info,
@@ -1088,10 +1116,8 @@ static int parse_branchname_arg(int argc, const char **argv,
 				struct object_id *rev,
 				int *dwim_remotes_matched)
 {
-	struct tree **source_tree = &opts->source_tree;
 	const char **new_branch = &opts->new_branch;
 	int argcount = 0;
-	struct object_id branch_rev;
 	const char *arg;
 	int dash_dash_pos;
 	int has_dash_dash = 0;
@@ -1213,26 +1239,11 @@ static int parse_branchname_arg(int argc, const char **argv,
 	argv++;
 	argc--;
 
-	new_branch_info->name = arg;
-	setup_branch_path(new_branch_info);
-
-	if (!check_refname_format(new_branch_info->path, 0) &&
-	    !read_ref(new_branch_info->path, &branch_rev))
-		oidcpy(rev, &branch_rev);
-	else
-		new_branch_info->path = NULL; /* not an existing branch */
+	setup_new_branch_info_and_source_tree(new_branch_info, opts, rev, arg);
 
-	new_branch_info->commit = lookup_commit_reference_gently(the_repository, rev, 1);
-	if (!new_branch_info->commit) {
-		/* not a commit */
-		*source_tree = parse_tree_indirect(rev);
-	} else {
-		parse_commit_or_die(new_branch_info->commit);
-		*source_tree = get_commit_tree(new_branch_info->commit);
-	}
-
-	if (!*source_tree)                   /* case (1): want a tree */
+	if (!opts->source_tree)                   /* case (1): want a tree */
 		die(_("reference is not a tree: %s"), arg);
+
 	if (!has_dash_dash) {	/* case (3).(d) -> (1) */
 		/*
 		 * Do not complain the most common case
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#225 lore raw

PATCH v5 9/26 checkout: make "opts" in cmd_checkout() a pointer

In reply to Nguyễn Thái Ngọc Duy

"opts" will soon be moved out of cmd_checkout(). To keep changes in that patch smaller, convert "opts" to a pointer and keep the real thing behind "real_opts".

---
 builtin/checkout.c | 115 +++++++++++++++++++++++----------------------
 1 file changed, 58 insertions(+), 57 deletions(-)
builtin/checkout.c +58 -57
index 1ce0446bc6..963f10b05b 100644
@@ -1341,82 +1341,83 @@ static int checkout_branch(struct checkout_opts *opts,
 
 int cmd_checkout(int argc, const char **argv, const char *prefix)
 {
-	struct checkout_opts opts;
+	struct checkout_opts real_opts;
+	struct checkout_opts *opts = &real_opts;
 	struct branch_info new_branch_info;
 	char *conflict_style = NULL;
 	int dwim_new_local_branch, no_dwim_new_local_branch = 0;
 	int dwim_remotes_matched = 0;
 	struct option options[] = {
-		OPT__QUIET(&opts.quiet, N_("suppress progress reporting")),
-		OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
+		OPT__QUIET(&opts->quiet, N_("suppress progress reporting")),
+		OPT_STRING('b', NULL, &opts->new_branch, N_("branch"),
 			   N_("create and checkout a new branch")),
-		OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
+		OPT_STRING('B', NULL, &opts->new_branch_force, N_("branch"),
 			   N_("create/reset and checkout a branch")),
-		OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
-		OPT_BOOL(0, "detach", &opts.force_detach, N_("detach HEAD at named commit")),
-		OPT_SET_INT('t', "track",  &opts.track, N_("set upstream info for new branch"),
+		OPT_BOOL('l', NULL, &opts->new_branch_log, N_("create reflog for new branch")),
+		OPT_BOOL(0, "detach", &opts->force_detach, N_("detach HEAD at named commit")),
+		OPT_SET_INT('t', "track",  &opts->track, N_("set upstream info for new branch"),
 			BRANCH_TRACK_EXPLICIT),
-		OPT_STRING(0, "orphan", &opts.new_orphan_branch, N_("new-branch"), N_("new unparented branch")),
-		OPT_SET_INT_F('2', "ours", &opts.writeout_stage,
+		OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unparented branch")),
+		OPT_SET_INT_F('2', "ours", &opts->writeout_stage,
 			      N_("checkout our version for unmerged files"),
 			      2, PARSE_OPT_NONEG),
-		OPT_SET_INT_F('3', "theirs", &opts.writeout_stage,
+		OPT_SET_INT_F('3', "theirs", &opts->writeout_stage,
 			      N_("checkout their version for unmerged files"),
 			      3, PARSE_OPT_NONEG),
-		OPT__FORCE(&opts.force, N_("force checkout (throw away local modifications)"),
+		OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
 			   PARSE_OPT_NOCOMPLETE),
-		OPT_BOOL('m', "merge", &opts.merge, N_("perform a 3-way merge with the new branch")),
-		OPT_BOOL_F(0, "overwrite-ignore", &opts.overwrite_ignore,
+		OPT_BOOL('m', "merge", &opts->merge, N_("perform a 3-way merge with the new branch")),
+		OPT_BOOL_F(0, "overwrite-ignore", &opts->overwrite_ignore,
 			   N_("update ignored files (default)"),
 			   PARSE_OPT_NOCOMPLETE),
 		OPT_STRING(0, "conflict", &conflict_style, N_("style"),
 			   N_("conflict style (merge or diff3)")),
-		OPT_BOOL('p', "patch", &opts.patch_mode, N_("select hunks interactively")),
-		OPT_BOOL(0, "ignore-skip-worktree-bits", &opts.ignore_skipworktree,
+		OPT_BOOL('p', "patch", &opts->patch_mode, N_("select hunks interactively")),
+		OPT_BOOL(0, "ignore-skip-worktree-bits", &opts->ignore_skipworktree,
 			 N_("do not limit pathspecs to sparse entries only")),
 		OPT_BOOL(0, "no-guess", &no_dwim_new_local_branch,
 			 N_("do not second guess 'git checkout <no-such-branch>'")),
-		OPT_BOOL(0, "ignore-other-worktrees", &opts.ignore_other_worktrees,
+		OPT_BOOL(0, "ignore-other-worktrees", &opts->ignore_other_worktrees,
 			 N_("do not check if another worktree is holding the given ref")),
 		{ OPTION_CALLBACK, 0, "recurse-submodules", NULL,
 			    "checkout", "control recursive updating of submodules",
 			    PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater },
-		OPT_BOOL(0, "progress", &opts.show_progress, N_("force progress reporting")),
-		OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode (default)")),
+		OPT_BOOL(0, "progress", &opts->show_progress, N_("force progress reporting")),
+		OPT_BOOL(0, "overlay", &opts->overlay_mode, N_("use overlay mode (default)")),
 		OPT_END(),
 	};
 
-	memset(&opts, 0, sizeof(opts));
+	memset(opts, 0, sizeof(*opts));
 	memset(&new_branch_info, 0, sizeof(new_branch_info));
-	opts.overwrite_ignore = 1;
-	opts.prefix = prefix;
-	opts.show_progress = -1;
-	opts.overlay_mode = -1;
+	opts->overwrite_ignore = 1;
+	opts->prefix = prefix;
+	opts->show_progress = -1;
+	opts->overlay_mode = -1;
 
-	git_config(git_checkout_config, &opts);
+	git_config(git_checkout_config, opts);
 
-	opts.track = BRANCH_TRACK_UNSPECIFIED;
+	opts->track = BRANCH_TRACK_UNSPECIFIED;
 
 	argc = parse_options(argc, argv, prefix, options, checkout_usage,
 			     PARSE_OPT_KEEP_DASHDASH);
 
 	dwim_new_local_branch = !no_dwim_new_local_branch;
-	if (opts.show_progress < 0) {
-		if (opts.quiet)
-			opts.show_progress = 0;
+	if (opts->show_progress < 0) {
+		if (opts->quiet)
+			opts->show_progress = 0;
 		else
-			opts.show_progress = isatty(2);
+			opts->show_progress = isatty(2);
 	}
 
 	if (conflict_style) {
-		opts.merge = 1; /* implied */
+		opts->merge = 1; /* implied */
 		git_xmerge_config("merge.conflictstyle", conflict_style, NULL);
 	}
 
-	if ((!!opts.new_branch + !!opts.new_branch_force + !!opts.new_orphan_branch) > 1)
+	if ((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) > 1)
 		die(_("-b, -B and --orphan are mutually exclusive"));
 
-	if (opts.overlay_mode == 1 && opts.patch_mode)
+	if (opts->overlay_mode == 1 && opts->patch_mode)
 		die(_("-p and --overlay are mutually exclusive"));
 
 	/*
@@ -1424,14 +1425,14 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 	 * and new_branch_force and new_orphan_branch will tell us which one of
 	 * -b/-B/--orphan is being used.
 	 */
-	if (opts.new_branch_force)
-		opts.new_branch = opts.new_branch_force;
+	if (opts->new_branch_force)
+		opts->new_branch = opts->new_branch_force;
 
-	if (opts.new_orphan_branch)
-		opts.new_branch = opts.new_orphan_branch;
+	if (opts->new_orphan_branch)
+		opts->new_branch = opts->new_orphan_branch;
 
 	/* --track without -b/-B/--orphan should DWIM */
-	if (opts.track != BRANCH_TRACK_UNSPECIFIED && !opts.new_branch) {
+	if (opts->track != BRANCH_TRACK_UNSPECIFIED && !opts->new_branch) {
 		const char *argv0 = argv[0];
 		if (!argc || !strcmp(argv0, "--"))
 			die(_("--track needs a branch name"));
@@ -1440,7 +1441,7 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 		argv0 = strchr(argv0, '/');
 		if (!argv0 || !argv0[1])
 			die(_("missing branch name; try -b"));
-		opts.new_branch = argv0 + 1;
+		opts->new_branch = argv0 + 1;
 	}
 
 	/*
@@ -1459,56 +1460,56 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 	if (argc) {
 		struct object_id rev;
 		int dwim_ok =
-			!opts.patch_mode &&
+			!opts->patch_mode &&
 			dwim_new_local_branch &&
-			opts.track == BRANCH_TRACK_UNSPECIFIED &&
-			!opts.new_branch;
+			opts->track == BRANCH_TRACK_UNSPECIFIED &&
+			!opts->new_branch;
 		int n = parse_branchname_arg(argc, argv, dwim_ok,
-					     &new_branch_info, &opts, &rev,
+					     &new_branch_info, opts, &rev,
 					     &dwim_remotes_matched);
 		argv += n;
 		argc -= n;
 	}
 
 	if (argc) {
-		parse_pathspec(&opts.pathspec, 0,
-			       opts.patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0,
+		parse_pathspec(&opts->pathspec, 0,
+			       opts->patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0,
 			       prefix, argv);
 
-		if (!opts.pathspec.nr)
+		if (!opts->pathspec.nr)
 			die(_("invalid path specification"));
 
 		/*
 		 * Try to give more helpful suggestion.
 		 * new_branch && argc > 1 will be caught later.
 		 */
-		if (opts.new_branch && argc == 1)
+		if (opts->new_branch && argc == 1)
 			die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
-				argv[0], opts.new_branch);
+				argv[0], opts->new_branch);
 
-		if (opts.force_detach)
+		if (opts->force_detach)
 			die(_("git checkout: --detach does not take a path argument '%s'"),
 			    argv[0]);
 
-		if (1 < !!opts.writeout_stage + !!opts.force + !!opts.merge)
+		if (1 < !!opts->writeout_stage + !!opts->force + !!opts->merge)
 			die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
 			      "checking out of the index."));
 	}
 
-	if (opts.new_branch) {
+	if (opts->new_branch) {
 		struct strbuf buf = STRBUF_INIT;
 
-		if (opts.new_branch_force)
-			opts.branch_exists = validate_branchname(opts.new_branch, &buf);
+		if (opts->new_branch_force)
+			opts->branch_exists = validate_branchname(opts->new_branch, &buf);
 		else
-			opts.branch_exists =
-				validate_new_branchname(opts.new_branch, &buf, 0);
+			opts->branch_exists =
+				validate_new_branchname(opts->new_branch, &buf, 0);
 		strbuf_release(&buf);
 	}
 
 	UNLEAK(opts);
-	if (opts.patch_mode || opts.pathspec.nr) {
-		int ret = checkout_paths(&opts, new_branch_info.name);
+	if (opts->patch_mode || opts->pathspec.nr) {
+		int ret = checkout_paths(opts, new_branch_info.name);
 		if (ret && dwim_remotes_matched > 1 &&
 		    advice_checkout_ambiguous_remote_branch_name)
 			advise(_("'%s' matched more than one remote tracking branch.\n"
@@ -1527,6 +1528,6 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 			       dwim_remotes_matched);
 		return ret;
 	} else {
-		return checkout_branch(&opts, &new_branch_info);
+		return checkout_branch(opts, &new_branch_info);
 	}
 }
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#226 lore raw

PATCH v5 10/26 checkout: move 'confict_style' and 'dwim_..' to checkout_opts

In reply to Nguyễn Thái Ngọc Duy

These local variables are referenced by struct option[]. This struct will soon be broken down, moved away and we can't rely on local variables anymore. Move these two to struct checkout_opts in preparation for that.

---
 builtin/checkout.c | 17 ++++++++++-------
 1 file changed, 10 insertions(+), 7 deletions(-)
builtin/checkout.c +10 -7
index 963f10b05b..b6fc1fc69f 100644
@@ -47,6 +47,8 @@ struct checkout_opts {
 	int show_progress;
 	int count_checkout_paths;
 	int overlay_mode;
+	int no_dwim_new_local_branch;
+
 	/*
 	 * If new checkout options are added, skip_merge_working_tree
 	 * should be updated accordingly.
@@ -58,6 +60,7 @@ struct checkout_opts {
 	int new_branch_log;
 	enum branch_track track;
 	struct diff_options diff_options;
+	char *conflict_style;
 
 	int branch_exists;
 	const char *prefix;
@@ -1344,8 +1347,7 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 	struct checkout_opts real_opts;
 	struct checkout_opts *opts = &real_opts;
 	struct branch_info new_branch_info;
-	char *conflict_style = NULL;
-	int dwim_new_local_branch, no_dwim_new_local_branch = 0;
+	int dwim_new_local_branch;
 	int dwim_remotes_matched = 0;
 	struct option options[] = {
 		OPT__QUIET(&opts->quiet, N_("suppress progress reporting")),
@@ -1370,12 +1372,12 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 		OPT_BOOL_F(0, "overwrite-ignore", &opts->overwrite_ignore,
 			   N_("update ignored files (default)"),
 			   PARSE_OPT_NOCOMPLETE),
-		OPT_STRING(0, "conflict", &conflict_style, N_("style"),
+		OPT_STRING(0, "conflict", &opts->conflict_style, N_("style"),
 			   N_("conflict style (merge or diff3)")),
 		OPT_BOOL('p', "patch", &opts->patch_mode, N_("select hunks interactively")),
 		OPT_BOOL(0, "ignore-skip-worktree-bits", &opts->ignore_skipworktree,
 			 N_("do not limit pathspecs to sparse entries only")),
-		OPT_BOOL(0, "no-guess", &no_dwim_new_local_branch,
+		OPT_BOOL(0, "no-guess", &opts->no_dwim_new_local_branch,
 			 N_("do not second guess 'git checkout <no-such-branch>'")),
 		OPT_BOOL(0, "ignore-other-worktrees", &opts->ignore_other_worktrees,
 			 N_("do not check if another worktree is holding the given ref")),
@@ -1393,6 +1395,7 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 	opts->prefix = prefix;
 	opts->show_progress = -1;
 	opts->overlay_mode = -1;
+	opts->no_dwim_new_local_branch = 0;
 
 	git_config(git_checkout_config, opts);
 
@@ -1401,7 +1404,7 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 	argc = parse_options(argc, argv, prefix, options, checkout_usage,
 			     PARSE_OPT_KEEP_DASHDASH);
 
-	dwim_new_local_branch = !no_dwim_new_local_branch;
+	dwim_new_local_branch = !opts->no_dwim_new_local_branch;
 	if (opts->show_progress < 0) {
 		if (opts->quiet)
 			opts->show_progress = 0;
@@ -1409,9 +1412,9 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 			opts->show_progress = isatty(2);
 	}
 
-	if (conflict_style) {
+	if (opts->conflict_style) {
 		opts->merge = 1; /* implied */
-		git_xmerge_config("merge.conflictstyle", conflict_style, NULL);
+		git_xmerge_config("merge.conflictstyle", opts->conflict_style, NULL);
 	}
 
 	if ((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) > 1)
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#227 lore raw

PATCH v5 11/26 checkout: split options[] array in three pieces

In reply to Nguyễn Thái Ngọc Duy

This is a preparation step for introducing new commands that do parts of what checkout does. There will be two new commands, one is about switching branches, detaching HEAD... one about checking out paths. These share the a subset of command line options. The rest of command line options are separate.

---
 builtin/checkout.c | 82 +++++++++++++++++++++++++++++++++-------------
 parse-options-cb.c | 17 ++++++++++
 parse-options.h    |  1 +
 3 files changed, 77 insertions(+), 23 deletions(-)
builtin/checkout.c +59 -23
index b6fc1fc69f..cf1d70511e 100644
@@ -1342,15 +1342,31 @@ static int checkout_branch(struct checkout_opts *opts,
 	return switch_branches(opts, new_branch_info);
 }
 
-int cmd_checkout(int argc, const char **argv, const char *prefix)
+static struct option *add_common_options(struct checkout_opts *opts,
+					 struct option *prevopts)
 {
-	struct checkout_opts real_opts;
-	struct checkout_opts *opts = &real_opts;
-	struct branch_info new_branch_info;
-	int dwim_new_local_branch;
-	int dwim_remotes_matched = 0;
 	struct option options[] = {
 		OPT__QUIET(&opts->quiet, N_("suppress progress reporting")),
+		{ OPTION_CALLBACK, 0, "recurse-submodules", NULL,
+			    "checkout", "control recursive updating of submodules",
+			    PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater },
+		OPT_BOOL(0, "progress", &opts->show_progress, N_("force progress reporting")),
+		OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
+			   PARSE_OPT_NOCOMPLETE),
+		OPT_BOOL('m', "merge", &opts->merge, N_("perform a 3-way merge with the new branch")),
+		OPT_STRING(0, "conflict", &opts->conflict_style, N_("style"),
+			   N_("conflict style (merge or diff3)")),
+		OPT_END()
+	};
+	struct option *newopts = parse_options_concat(prevopts, options);
+	free(prevopts);
+	return newopts;
+}
+
+static struct option *add_switch_branch_options(struct checkout_opts *opts,
+						struct option *prevopts)
+{
+	struct option options[] = {
 		OPT_STRING('b', NULL, &opts->new_branch, N_("branch"),
 			   N_("create and checkout a new branch")),
 		OPT_STRING('B', NULL, &opts->new_branch_force, N_("branch"),
@@ -1360,34 +1376,49 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 		OPT_SET_INT('t', "track",  &opts->track, N_("set upstream info for new branch"),
 			BRANCH_TRACK_EXPLICIT),
 		OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unparented branch")),
+		OPT_BOOL_F(0, "overwrite-ignore", &opts->overwrite_ignore,
+			   N_("update ignored files (default)"),
+			   PARSE_OPT_NOCOMPLETE),
+		OPT_BOOL(0, "no-guess", &opts->no_dwim_new_local_branch,
+			 N_("second guess 'git checkout <no-such-branch>'")),
+		OPT_BOOL(0, "ignore-other-worktrees", &opts->ignore_other_worktrees,
+			 N_("do not check if another worktree is holding the given ref")),
+		OPT_END()
+	};
+	struct option *newopts = parse_options_concat(prevopts, options);
+	free(prevopts);
+	return newopts;
+}
+
+static struct option *add_checkout_path_options(struct checkout_opts *opts,
+						struct option *prevopts)
+{
+	struct option options[] = {
 		OPT_SET_INT_F('2', "ours", &opts->writeout_stage,
 			      N_("checkout our version for unmerged files"),
 			      2, PARSE_OPT_NONEG),
 		OPT_SET_INT_F('3', "theirs", &opts->writeout_stage,
 			      N_("checkout their version for unmerged files"),
 			      3, PARSE_OPT_NONEG),
-		OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
-			   PARSE_OPT_NOCOMPLETE),
-		OPT_BOOL('m', "merge", &opts->merge, N_("perform a 3-way merge with the new branch")),
-		OPT_BOOL_F(0, "overwrite-ignore", &opts->overwrite_ignore,
-			   N_("update ignored files (default)"),
-			   PARSE_OPT_NOCOMPLETE),
-		OPT_STRING(0, "conflict", &opts->conflict_style, N_("style"),
-			   N_("conflict style (merge or diff3)")),
 		OPT_BOOL('p', "patch", &opts->patch_mode, N_("select hunks interactively")),
 		OPT_BOOL(0, "ignore-skip-worktree-bits", &opts->ignore_skipworktree,
 			 N_("do not limit pathspecs to sparse entries only")),
-		OPT_BOOL(0, "no-guess", &opts->no_dwim_new_local_branch,
-			 N_("do not second guess 'git checkout <no-such-branch>'")),
-		OPT_BOOL(0, "ignore-other-worktrees", &opts->ignore_other_worktrees,
-			 N_("do not check if another worktree is holding the given ref")),
-		{ OPTION_CALLBACK, 0, "recurse-submodules", NULL,
-			    "checkout", "control recursive updating of submodules",
-			    PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater },
-		OPT_BOOL(0, "progress", &opts->show_progress, N_("force progress reporting")),
 		OPT_BOOL(0, "overlay", &opts->overlay_mode, N_("use overlay mode (default)")),
-		OPT_END(),
+		OPT_END()
 	};
+	struct option *newopts = parse_options_concat(prevopts, options);
+	free(prevopts);
+	return newopts;
+}
+
+int cmd_checkout(int argc, const char **argv, const char *prefix)
+{
+	struct checkout_opts real_opts;
+	struct checkout_opts *opts = &real_opts;
+	struct branch_info new_branch_info;
+	int dwim_remotes_matched = 0;
+	int dwim_new_local_branch;
+	struct option *options = NULL;
 
 	memset(opts, 0, sizeof(*opts));
 	memset(&new_branch_info, 0, sizeof(new_branch_info));
@@ -1401,6 +1432,11 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 
 	opts->track = BRANCH_TRACK_UNSPECIFIED;
 
+	options = parse_options_dup(options);
+	options = add_common_options(opts, options);
+	options = add_switch_branch_options(opts, options);
+	options = add_checkout_path_options(opts, options);
+
 	argc = parse_options(argc, argv, prefix, options, checkout_usage,
 			     PARSE_OPT_KEEP_DASHDASH);
 
parse-options-cb.c +17 -0
index 2733393546..caaeed896f 100644
@@ -122,6 +122,23 @@ int parse_opt_tertiary(const struct option *opt, const char *arg, int unset)
 	return 0;
 }
 
+struct option *parse_options_dup(const struct option *o)
+{
+	struct option *opts;
+	int nr = 0;
+
+	while (o && o->type != OPTION_END) {
+		nr++;
+		o++;
+	}
+
+	ALLOC_ARRAY(opts, nr + 1);
+	memcpy(opts, o - nr, sizeof(*o) * nr);
+	memset(opts + nr, 0, sizeof(*opts));
+	opts[nr].type = OPTION_END;
+	return opts;
+}
+
 struct option *parse_options_concat(struct option *a, struct option *b)
 {
 	struct option *ret;
parse-options.h +1 -0
index 7d83e2971d..9a90c332a5 100644
@@ -257,6 +257,7 @@ int parse_options_step(struct parse_opt_ctx_t *ctx,
 
 int parse_options_end(struct parse_opt_ctx_t *ctx);
 
+struct option *parse_options_dup(const struct option *a);
 struct option *parse_options_concat(struct option *a, struct option *b);
 
 /*----- some often used options -----*/
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#228 lore raw

PATCH v5 12/26 checkout: split part of it to new command 'switch'

In reply to Nguyễn Thái Ngọc Duy

"git checkout" doing too many things is a source of confusion for many users (and it even bites old timers sometimes). To remedy that, the command will be split into two new ones: switch and restore. The good old "git checkout" command is still here and will be until all (or most of users) are sick of it.

See the new man page for the final design of switch. The actual implementation though is still pretty much the same as "git checkout" and not completely aligned with the man page. Following patches will adjust their behavior to match the man page.

---
 .gitignore                         |   1 +
 Documentation/config/advice.txt    |  13 +-
 Documentation/config/branch.txt    |   4 +-
 Documentation/config/checkout.txt  |   9 +-
 Documentation/config/diff.txt      |   3 +-
 Documentation/git-checkout.txt     |   4 +
 Documentation/git-switch.txt (new) | 276 +++++++++++++++++++++++++++++
 Documentation/gitattributes.txt    |   3 +-
 Documentation/githooks.txt         |   8 +-
 Makefile                           |   1 +
 builtin.h                          |   1 +
 builtin/checkout.c                 |  60 +++++--
 command-list.txt                   |   1 +
 git.c                              |   1 +
 14 files changed, 358 insertions(+), 27 deletions(-)
.gitignore +1 -0
index 7374587f9d..c687b92b1c 100644
@@ -167,6 +167,7 @@
 /git-submodule
 /git-submodule--helper
 /git-svn
+/git-switch
 /git-symbolic-ref
 /git-tag
 /git-unpack-file
Documentation/config/advice.txt +8 -5
index 88620429ea..239d479506 100644
@@ -42,7 +42,8 @@ advice.*::
 		state in the output of linkgit:git-status[1], in
 		the template shown when writing commit messages in
 		linkgit:git-commit[1], and in the help message shown
-		by linkgit:git-checkout[1] when switching branch.
+		by linkgit:git-switch[1] or
+		linkgit:git-checkout[1] when switching branch.
 	statusUoption::
 		Advise to consider using the `-u` option to linkgit:git-status[1]
 		when the command takes more than 2 seconds to enumerate untracked
@@ -62,12 +63,14 @@ advice.*::
 		your information is guessed from the system username and
 		domain name.
 	detachedHead::
-		Advice shown when you used linkgit:git-checkout[1] to
-		move to the detach HEAD state, to instruct how to create
-		a local branch after the fact.
+		Advice shown when you used
+		linkgit:git-switch[1] or linkgit:git-checkout[1]
+		to move to the detach HEAD state, to instruct how to
+		create a local branch after the fact.
 	checkoutAmbiguousRemoteBranchName::
 		Advice shown when the argument to
-		linkgit:git-checkout[1] ambiguously resolves to a
+		linkgit:git-checkout[1] and linkgit:git-switch[1]
+		ambiguously resolves to a
 		remote tracking branch on more than one remote in
 		situations where an unambiguous argument would have
 		otherwise caused a remote-tracking branch to be
Documentation/config/branch.txt +2 -2
index 019d60ede2..8050466159 100644
@@ -1,5 +1,5 @@
 branch.autoSetupMerge::
-	Tells 'git branch' and 'git checkout' to set up new branches
+	Tells 'git branch', 'git switch' and 'git checkout' to set up new branches
 	so that linkgit:git-pull[1] will appropriately merge from the
 	starting point branch. Note that even if this option is not set,
 	this behavior can be chosen per-branch using the `--track`
@@ -11,7 +11,7 @@ branch.autoSetupMerge::
 	branch. This option defaults to true.
 
 branch.autoSetupRebase::
-	When a new branch is created with 'git branch' or 'git checkout'
+	When a new branch is created with 'git branch', 'git switch' or 'git checkout'
 	that tracks another branch, this variable tells Git to set
 	up pull to rebase instead of merge (see "branch.<name>.rebase").
 	When `never`, rebase is never automatically set to true.
Documentation/config/checkout.txt +6 -3
index c4118fa196..d6872ffa83 100644
@@ -1,5 +1,6 @@
 checkout.defaultRemote::
-	When you run 'git checkout <something>' and only have one
+	When you run 'git checkout <something>'
+	or 'git switch <something>' and only have one
 	remote, it may implicitly fall back on checking out and
 	tracking e.g. 'origin/<something>'. This stops working as soon
 	as you have more than one remote with a '<something>'
@@ -8,8 +9,10 @@ checkout.defaultRemote::
 	disambiguation. The typical use-case is to set this to
 	`origin`.
 +
-Currently this is used by linkgit:git-checkout[1] when 'git checkout
-<something>' will checkout the '<something>' branch on another remote,
+Currently this is used by linkgit:git-switch[1] and
+linkgit:git-checkout[1] when 'git checkout <something>'
+or 'git switch <something>'
+will checkout the '<something>' branch on another remote,
 and by linkgit:git-worktree[1] when 'git worktree add' refers to a
 remote branch. This setting might be used for other checkout-like
 commands or functionality in the future.
Documentation/config/diff.txt +2 -1
index e48bb987d7..b3b304ee12 100644
@@ -78,7 +78,8 @@ diff.external::
 diff.ignoreSubmodules::
 	Sets the default value of --ignore-submodules. Note that this
 	affects only 'git diff' Porcelain, and not lower level 'diff'
-	commands such as 'git diff-files'. 'git checkout' also honors
+	commands such as 'git diff-files'. 'git checkout'
+	and 'git switch' also honor
 	this setting when reporting uncommitted changes. Setting it to
 	'all' disables the submodule summary normally shown by 'git commit'
 	and 'git status' when `status.submoduleSummary` is set unless it is
Documentation/git-checkout.txt +4 -0
index bf90966c95..c7192bdefe 100644
@@ -560,6 +560,10 @@ $ edit frotz
 $ git add frotz
 ------------
 
+SEE ALSO
+--------
+linkgit:git-switch[1]
+
 GIT
 ---
 Part of the linkgit:git[1] suite
Documentation/git-switch.txt new file +276 -0

276 lines not on this page · raw message

Documentation/gitattributes.txt +2 -1
index 9b41f81c06..cd0f9fa507 100644
@@ -112,7 +112,8 @@ Checking-out and checking-in
 
 These attributes affect how the contents stored in the
 repository are copied to the working tree files when commands
-such as 'git checkout' and 'git merge' run.  They also affect how
+such as 'git switch', 'git checkout'  and 'git merge' run.
+They also affect how
 Git stores the contents you prepare in the working tree in the
 repository upon 'git add' and 'git commit'.
 
Documentation/githooks.txt +5 -3
index 5bf653c111..8ff72f0613 100644
@@ -165,12 +165,13 @@ rebased, and is not set when rebasing the current branch.
 post-checkout
 ~~~~~~~~~~~~~
 
-This hook is invoked when a linkgit:git-checkout[1] is run after having updated the
+This hook is invoked when a linkgit:git-checkout[1] or
+linkgit:git-switch[1] is run after having updated the
 worktree.  The hook is given three parameters: the ref of the previous HEAD,
 the ref of the new HEAD (which may or may not have changed), and a flag
 indicating whether the checkout was a branch checkout (changing branches,
 flag=1) or a file checkout (retrieving a file from the index, flag=0).
-This hook cannot affect the outcome of `git checkout`.
+This hook cannot affect the outcome of `git switch` or `git checkout`.
 
 It is also run after linkgit:git-clone[1], unless the `--no-checkout` (`-n`) option is
 used. The first parameter given to the hook is the null-ref, the second the
@@ -406,7 +407,8 @@ exit with a zero status.
 For example, the hook can simply run `git read-tree -u -m HEAD "$1"`
 in order to emulate `git fetch` that is run in the reverse direction
 with `git push`, as the two-tree form of `git read-tree -u -m` is
-essentially the same as `git checkout` that switches branches while
+essentially the same as `git switch` or `git checkout`
+that switches branches while
 keeping the local changes in the working tree that do not interfere
 with the difference between the branches.
 
Makefile +1 -0
index 148668368b..8e91db73ad 100644
@@ -802,6 +802,7 @@ BUILT_INS += git-merge-subtree$X
 BUILT_INS += git-show$X
 BUILT_INS += git-stage$X
 BUILT_INS += git-status$X
+BUILT_INS += git-switch$X
 BUILT_INS += git-whatchanged$X
 
 # what 'all' will build and 'install' will install in gitexecdir,
builtin.h +1 -0
index 6538932e99..c64e44450e 100644
@@ -227,6 +227,7 @@ extern int cmd_show_index(int argc, const char **argv, const char *prefix);
 extern int cmd_status(int argc, const char **argv, const char *prefix);
 extern int cmd_stripspace(int argc, const char **argv, const char *prefix);
 extern int cmd_submodule__helper(int argc, const char **argv, const char *prefix);
+extern int cmd_switch(int argc, const char **argv, const char *prefix);
 extern int cmd_symbolic_ref(int argc, const char **argv, const char *prefix);
 extern int cmd_tag(int argc, const char **argv, const char *prefix);
 extern int cmd_tar_tree(int argc, const char **argv, const char *prefix);
builtin/checkout.c +48 -12

90 lines not on this page · raw message

command-list.txt +1 -0
index 3a9af104b5..13317f47d4 100644
@@ -171,6 +171,7 @@ git-status                              mainporcelain           info
 git-stripspace                          purehelpers
 git-submodule                           mainporcelain
 git-svn                                 foreignscminterface
+git-switch                              mainporcelain           history
 git-symbolic-ref                        plumbingmanipulators
 git-tag                                 mainporcelain           history
 git-unpack-file                         plumbinginterrogators
git.c +1 -0
index 2014aab6b8..39582cf511 100644
@@ -573,6 +573,7 @@ static struct cmd_struct commands[] = {
 	{ "status", cmd_status, RUN_SETUP | NEED_WORK_TREE },
 	{ "stripspace", cmd_stripspace },
 	{ "submodule--helper", cmd_submodule__helper, RUN_SETUP | SUPPORT_SUPER_PREFIX | NO_PARSEOPT },
+	{ "switch", cmd_switch, RUN_SETUP | NEED_WORK_TREE },
 	{ "symbolic-ref", cmd_symbolic_ref, RUN_SETUP },
 	{ "tag", cmd_tag, RUN_SETUP | DELAY_PAGER_CONFIG },
 	{ "unpack-file", cmd_unpack_file, RUN_SETUP | NO_PARSEOPT },
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#229 lore raw

PATCH v5 13/26 switch: better names for -b and -B

In reply to Nguyễn Thái Ngọc Duy

The shortcut of these options do not make much sense when used with switch. And their descriptions are also tied to checkout. Move -b/-B to cmd_checkout() and new -c/-C with the same functionality in cmd_switch_branch()

---
 builtin/checkout.c | 32 +++++++++++++++++++++-----------
 1 file changed, 21 insertions(+), 11 deletions(-)
builtin/checkout.c +21 -11
index dd3c200cb5..400a0d5620 100644
@@ -1368,14 +1368,10 @@ static struct option *add_common_options(struct checkout_opts *opts,
 	return newopts;
 }
 
-static struct option *add_switch_branch_options(struct checkout_opts *opts,
-						struct option *prevopts)
+static struct option *add_common_switch_branch_options(
+	struct checkout_opts *opts, struct option *prevopts)
 {
 	struct option options[] = {
-		OPT_STRING('b', NULL, &opts->new_branch, N_("branch"),
-			   N_("create and checkout a new branch")),
-		OPT_STRING('B', NULL, &opts->new_branch_force, N_("branch"),
-			   N_("create/reset and checkout a branch")),
 		OPT_BOOL('l', NULL, &opts->new_branch_log, N_("create reflog for new branch")),
 		OPT_BOOL(0, "detach", &opts->force_detach, N_("detach HEAD at named commit")),
 		OPT_SET_INT('t', "track",  &opts->track, N_("set upstream info for new branch"),
@@ -1571,15 +1567,22 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
 int cmd_checkout(int argc, const char **argv, const char *prefix)
 {
 	struct checkout_opts opts;
-	struct option *options = NULL;
+	struct option *options;
+	struct option checkout_options[] = {
+		OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
+			   N_("create and checkout a new branch")),
+		OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
+			   N_("create/reset and checkout a branch")),
+		OPT_END()
+	};
 	int ret;
 
 	memset(&opts, 0, sizeof(opts));
 	opts.no_dwim_new_local_branch = 0;
 
-	options = parse_options_dup(options);
+	options = parse_options_dup(checkout_options);
 	options = add_common_options(&opts, options);
-	options = add_switch_branch_options(&opts, options);
+	options = add_common_switch_branch_options(&opts, options);
 	options = add_checkout_path_options(&opts, options);
 
 	ret = checkout_main(argc, argv, prefix, &opts,
@@ -1592,14 +1595,21 @@ int cmd_switch(int argc, const char **argv, const char *prefix)
 {
 	struct checkout_opts opts;
 	struct option *options = NULL;
+	struct option switch_options[] = {
+		OPT_STRING('c', "create", &opts.new_branch, N_("branch"),
+			   N_("create and switch to a new branch")),
+		OPT_STRING('C', "force-create", &opts.new_branch_force, N_("branch"),
+			   N_("create/reset and switch to a branch")),
+		OPT_END()
+	};
 	int ret;
 
 	memset(&opts, 0, sizeof(opts));
 	opts.no_dwim_new_local_branch = 0;
 
-	options = parse_options_dup(options);
+	options = parse_options_dup(switch_options);
 	options = add_common_options(&opts, options);
-	options = add_switch_branch_options(&opts, options);
+	options = add_common_switch_branch_options(&opts, options);
 
 	ret = checkout_main(argc, argv, prefix, &opts,
 			    options, switch_branch_usage);
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#230 lore raw

PATCH v5 14/26 switch: add --discard-changes

In reply to Nguyễn Thái Ngọc Duy

--discard-changes is a better name than --force for this option since it's what really happens. --force is turned to an alias for --discard-changes. But it's meant to be an alias for potentially more force options in the future.

---
 builtin/checkout.c | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)
builtin/checkout.c +10 -2
index 400a0d5620..bd94b04303 100644
@@ -53,6 +53,7 @@ struct checkout_opts {
 	int count_checkout_paths;
 	int overlay_mode;
 	int no_dwim_new_local_branch;
+	int discard_changes;
 
 	/*
 	 * If new checkout options are added, skip_merge_working_tree
@@ -680,7 +681,7 @@ static int merge_working_tree(const struct checkout_opts *opts,
 		return error(_("index file corrupt"));
 
 	resolve_undo_clear();
-	if (opts->force) {
+	if (opts->discard_changes) {
 		ret = reset_tree(get_commit_tree(new_branch_info->commit),
 				 opts, 1, writeout_error);
 		if (ret)
@@ -802,7 +803,7 @@ static int merge_working_tree(const struct checkout_opts *opts,
 	if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
 		die(_("unable to write new index file"));
 
-	if (!opts->force && !opts->quiet)
+	if (!opts->discard_changes && !opts->quiet)
 		show_local_changes(&new_branch_info->commit->object, &opts->diff_options);
 
 	return 0;
@@ -1309,6 +1310,9 @@ static int checkout_branch(struct checkout_opts *opts,
 	if (opts->force && opts->merge)
 		die(_("'%s' cannot be used with '%s'"), "-f", "-m");
 
+	if (opts->discard_changes && opts->merge)
+		die(_("'%s' cannot be used with '%s'"), "--discard-changes", "--merge");
+
 	if (opts->force_detach && opts->new_branch)
 		die(_("'%s' cannot be used with '%s'"),
 		    "--detach", "-b/-B/--orphan");
@@ -1445,6 +1449,8 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
 		opts->merge = 1; /* implied */
 		git_xmerge_config("merge.conflictstyle", opts->conflict_style, NULL);
 	}
+	if (opts->force)
+		opts->discard_changes = 1;
 
 	if ((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) > 1)
 		die(_("-b, -B and --orphan are mutually exclusive"));
@@ -1600,6 +1606,8 @@ int cmd_switch(int argc, const char **argv, const char *prefix)
 			   N_("create and switch to a new branch")),
 		OPT_STRING('C', "force-create", &opts.new_branch_force, N_("branch"),
 			   N_("create/reset and switch to a branch")),
+		OPT_BOOL(0, "discard-changes", &opts.discard_changes,
+			 N_("throw away local modifications")),
 		OPT_END()
 	};
 	int ret;
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#231 lore raw

PATCH v5 15/26 switch: remove -l

In reply to Nguyễn Thái Ngọc Duy

This option is ancient. Nowadays reflog is enabled by default and automatically created for new branches. Keep it in git-checkout only.

---
 builtin/checkout.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
builtin/checkout.c +1 -1
index bd94b04303..85fc60f5f2 100644
@@ -1376,7 +1376,6 @@ static struct option *add_common_switch_branch_options(
 	struct checkout_opts *opts, struct option *prevopts)
 {
 	struct option options[] = {
-		OPT_BOOL('l', NULL, &opts->new_branch_log, N_("create reflog for new branch")),
 		OPT_BOOL(0, "detach", &opts->force_detach, N_("detach HEAD at named commit")),
 		OPT_SET_INT('t', "track",  &opts->track, N_("set upstream info for new branch"),
 			BRANCH_TRACK_EXPLICIT),
@@ -1579,6 +1578,7 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 			   N_("create and checkout a new branch")),
 		OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
 			   N_("create/reset and checkout a branch")),
+		OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
 		OPT_END()
 	};
 	int ret;
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#232 lore raw

PATCH v5 16/26 switch: stop accepting pathspec

In reply to Nguyễn Thái Ngọc Duy

This command is about switching branch (or creating a new one) and should not accept pathspec. This helps simplify ambiguation handling. The other two ("git checkout" and "git restore") of course do accept pathspec as before.

---
 builtin/checkout.c | 20 +++++++++++++++-----
 1 file changed, 15 insertions(+), 5 deletions(-)
builtin/checkout.c +15 -5
index 85fc60f5f2..2c4cab6406 100644
@@ -54,6 +54,7 @@ struct checkout_opts {
 	int overlay_mode;
 	int no_dwim_new_local_branch;
 	int discard_changes;
+	int accept_pathspec;
 
 	/*
 	 * If new checkout options are added, skip_merge_working_tree
@@ -1176,10 +1177,16 @@ static int parse_branchname_arg(int argc, const char **argv,
 	if (!argc)
 		return 0;
 
+	if (!opts->accept_pathspec) {
+		if (argc > 1)
+			die(_("only one reference expected"));
+		has_dash_dash = 1; /* helps disambiguate */
+	}
+
 	arg = argv[0];
 	dash_dash_pos = -1;
 	for (i = 0; i < argc; i++) {
-		if (!strcmp(argv[i], "--")) {
+		if (opts->accept_pathspec && !strcmp(argv[i], "--")) {
 			dash_dash_pos = i;
 			break;
 		}
@@ -1213,11 +1220,12 @@ static int parse_branchname_arg(int argc, const char **argv,
 			recover_with_dwim = 0;
 
 		/*
-		 * Accept "git checkout foo" and "git checkout foo --"
-		 * as candidates for dwim.
+		 * Accept "git checkout foo", "git checkout foo --"
+		 * and "git switch foo" as candidates for dwim.
 		 */
 		if (!(argc == 1 && !has_dash_dash) &&
-		    !(argc == 2 && has_dash_dash))
+		    !(argc == 2 && has_dash_dash) &&
+		    opts->accept_pathspec)
 			recover_with_dwim = 0;
 
 		if (recover_with_dwim) {
@@ -1262,7 +1270,7 @@ static int parse_branchname_arg(int argc, const char **argv,
 		 */
 		if (argc)
 			verify_non_filename(opts->prefix, arg);
-	} else {
+	} else if (opts->accept_pathspec) {
 		argcount++;
 		argv++;
 		argc--;
@@ -1585,6 +1593,7 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 
 	memset(&opts, 0, sizeof(opts));
 	opts.no_dwim_new_local_branch = 0;
+	opts.accept_pathspec = 1;
 
 	options = parse_options_dup(checkout_options);
 	options = add_common_options(&opts, options);
@@ -1614,6 +1623,7 @@ int cmd_switch(int argc, const char **argv, const char *prefix)
 
 	memset(&opts, 0, sizeof(opts));
 	opts.no_dwim_new_local_branch = 0;
+	opts.accept_pathspec = 0;
 
 	options = parse_options_dup(switch_options);
 	options = add_common_options(&opts, options);
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#233 lore raw

PATCH v5 17/26 switch: reject "do nothing" case

In reply to Nguyễn Thái Ngọc Duy

"git checkout" can be executed without any arguments. What it does is not exactly great: it switches from HEAD to HEAD and shows worktree modification as a side effect.

Make switch reject this case. Just use "git status" if you want that side effect. For switch, you have to either

- really switch a branch
- (explicitly) detach from the current branch
- create a new branch

---
 builtin/checkout.c | 9 +++++++++
 1 file changed, 9 insertions(+)
builtin/checkout.c +9 -0
index 2c4cab6406..73b7373414 100644
@@ -55,6 +55,7 @@ struct checkout_opts {
 	int no_dwim_new_local_branch;
 	int discard_changes;
 	int accept_pathspec;
+	int switch_branch_doing_nothing_is_ok;
 
 	/*
 	 * If new checkout options are added, skip_merge_working_tree
@@ -1338,6 +1339,12 @@ static int checkout_branch(struct checkout_opts *opts,
 		die(_("Cannot switch branch to a non-commit '%s'"),
 		    new_branch_info->name);
 
+	if (!opts->switch_branch_doing_nothing_is_ok &&
+	    !new_branch_info->name &&
+	    !opts->new_branch &&
+	    !opts->force_detach)
+		die(_("missing branch or commit argument"));
+
 	if (new_branch_info->path && !opts->force_detach && !opts->new_branch &&
 	    !opts->ignore_other_worktrees) {
 		int flag;
@@ -1593,6 +1600,7 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 
 	memset(&opts, 0, sizeof(opts));
 	opts.no_dwim_new_local_branch = 0;
+	opts.switch_branch_doing_nothing_is_ok = 1;
 	opts.accept_pathspec = 1;
 
 	options = parse_options_dup(checkout_options);
@@ -1624,6 +1632,7 @@ int cmd_switch(int argc, const char **argv, const char *prefix)
 	memset(&opts, 0, sizeof(opts));
 	opts.no_dwim_new_local_branch = 0;
 	opts.accept_pathspec = 0;
+	opts.switch_branch_doing_nothing_is_ok = 0;
 
 	options = parse_options_dup(switch_options);
 	options = add_common_options(&opts, options);
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#234 lore raw

PATCH v5 18/26 switch: only allow explicit detached HEAD

In reply to Nguyễn Thái Ngọc Duy

"git checkout <commit>" will checkout the commit in question and detach HEAD from the current branch. It is naturally a right thing to do once you get git references. But detached HEAD is a scary concept to new users because we show a lot of warnings and stuff, and it could be hard to get out of (until you know better).

To keep switch a bit more friendly to new users, we only allow entering detached HEAD mode when --detach is given. "git switch" must take a branch (unless you create a new branch, then of course switch can take any commit-ish)

---
 builtin/checkout.c | 34 ++++++++++++++++++++++++++++++++++
 1 file changed, 34 insertions(+)
builtin/checkout.c +34 -0
index 73b7373414..d72e28aabb 100644
@@ -45,6 +45,7 @@ struct checkout_opts {
 	int merge;
 	int force;
 	int force_detach;
+	int implicit_detach;
 	int writeout_stage;
 	int overwrite_ignore;
 	int ignore_skipworktree;
@@ -1298,6 +1299,29 @@ static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
 	return status;
 }
 
+static void die_expecting_a_branch(const struct branch_info *branch_info)
+{
+	struct object_id oid;
+	char *to_free;
+
+	if (dwim_ref(branch_info->name, strlen(branch_info->name), &oid, &to_free) == 1) {
+		const char *ref = to_free;
+
+		if (skip_prefix(ref, "refs/tags/", &ref))
+			die(_("a branch is expected, got tag '%s'"), ref);
+		if (skip_prefix(ref, "refs/remotes/", &ref))
+			die(_("a branch is expected, got remote branch '%s'"), ref);
+		die(_("a branch is expected, got '%s'"), ref);
+	}
+	if (branch_info->commit)
+		die(_("a branch is expected, got commit '%s'"), branch_info->name);
+	/*
+	 * This case should never happen because we already die() on
+	 * non-commit, but just in case.
+	 */
+	die(_("a branch is expected, got '%s'"), branch_info->name);
+}
+
 static int checkout_branch(struct checkout_opts *opts,
 			   struct branch_info *new_branch_info)
 {
@@ -1345,6 +1369,14 @@ static int checkout_branch(struct checkout_opts *opts,
 	    !opts->force_detach)
 		die(_("missing branch or commit argument"));
 
+	if (!opts->implicit_detach &&
+	    !opts->force_detach &&
+	    !opts->new_branch &&
+	    !opts->new_branch_force &&
+	    new_branch_info->name &&
+	    !new_branch_info->path)
+		die_expecting_a_branch(new_branch_info);
+
 	if (new_branch_info->path && !opts->force_detach && !opts->new_branch &&
 	    !opts->ignore_other_worktrees) {
 		int flag;
@@ -1602,6 +1634,7 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 	opts.no_dwim_new_local_branch = 0;
 	opts.switch_branch_doing_nothing_is_ok = 1;
 	opts.accept_pathspec = 1;
+	opts.implicit_detach = 1;
 
 	options = parse_options_dup(checkout_options);
 	options = add_common_options(&opts, options);
@@ -1633,6 +1666,7 @@ int cmd_switch(int argc, const char **argv, const char *prefix)
 	opts.no_dwim_new_local_branch = 0;
 	opts.accept_pathspec = 0;
 	opts.switch_branch_doing_nothing_is_ok = 0;
+	opts.implicit_detach = 0;
 
 	options = parse_options_dup(switch_options);
 	options = add_common_options(&opts, options);
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#235 lore raw

PATCH v5 19/26 switch: add short option for --detach

In reply to Nguyễn Thái Ngọc Duy

"git checkout" automatically detaches branches and --detach is not that useful (--no-detach is more likely). But for "switch", you may want to use it more often once you're used to detached HEAD. This of course adds -d to git-checkout but it does not harm (yet?) to do it.

---
 builtin/checkout.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
builtin/checkout.c +1 -1
index d72e28aabb..a14133b474 100644
@@ -1423,7 +1423,7 @@ static struct option *add_common_switch_branch_options(
 	struct checkout_opts *opts, struct option *prevopts)
 {
 	struct option options[] = {
-		OPT_BOOL(0, "detach", &opts->force_detach, N_("detach HEAD at named commit")),
+		OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
 		OPT_SET_INT('t', "track",  &opts->track, N_("set upstream info for new branch"),
 			BRANCH_TRACK_EXPLICIT),
 		OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unparented branch")),
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#236 lore raw

PATCH v5 20/26 switch: implicit dwim, use --no-guess to disable it

In reply to Nguyễn Thái Ngọc Duy

This is already the default in git-checkout. The real change in here is just minor cleanup. The main excuse is to explain why dwim is kept default.

Contrary to detach mode that is easy to get into and confusing to get back out. Automatically creating a tracking branch often does not kick in as often (you would need a branch of the same name on a remote). And since the branch creation is reported clearly, the user should be able to undo/delete it if it's unwanted.

---
 Documentation/git-checkout.txt | 38 ++++++++++++++++++++--------------
 builtin/checkout.c             | 16 +++++++-------
 2 files changed, 31 insertions(+), 23 deletions(-)
Documentation/git-checkout.txt +23 -15
index c7192bdefe..58f18a0842 100644
@@ -31,22 +31,13 @@ branch.
 	`<branch>`.
 +
 If `<branch>` is not found but there does exist a tracking branch in
-exactly one remote (call it `<remote>`) with a matching name, treat as
-equivalent to
+exactly one remote (call it `<remote>`) with a matching name and
+`--no-guess` is not specified, treat as equivalent to
 +
 ------------
 $ git checkout -b <branch> --track <remote>/<branch>
 ------------
 +
-If the branch exists in multiple remotes and one of them is named by
-the `checkout.defaultRemote` configuration variable, we'll use that
-one for the purposes of disambiguation, even if the `<branch>` isn't
-unique across all remotes. Set it to
-e.g. `checkout.defaultRemote=origin` to always checkout remote
-branches from there if `<branch>` is ambiguous but exists on the
-'origin' remote. See also `checkout.defaultRemote` in
-linkgit:git-config[1].
-+
 You could omit `<branch>`, in which case the command degenerates to
 "check out the current branch", which is a glorified no-op with
 rather expensive side-effects to show only the tracking information,
@@ -183,6 +174,27 @@ explicitly give a name with `-b` in such a case.
 	Do not set up "upstream" configuration, even if the
 	`branch.autoSetupMerge` configuration variable is true.
 
+--guess::
+--no-guess::
+	If `<branch>` is not found but there does exist a tracking
+	branch in exactly one remote (call it `<remote>`) with a
+	matching name, treat as equivalent to
++
+------------
+$ git checkout -b <branch> --track <remote>/<branch>
+------------
++
+If the branch exists in multiple remotes and one of them is named by
+the `checkout.defaultRemote` configuration variable, we'll use that
+one for the purposes of disambiguation, even if the `<branch>` isn't
+unique across all remotes. Set it to
+e.g. `checkout.defaultRemote=origin` to always checkout remote
+branches from there if `<branch>` is ambiguous but exists on the
+'origin' remote. See also `checkout.defaultRemote` in
+linkgit:git-config[1].
++
+Use `--no-guess` to disable this.
+
 -l::
 	Create the new branch's reflog; see linkgit:git-branch[1] for
 	details.
@@ -287,10 +299,6 @@ Note that this option uses the no overlay mode by default (see also
 	Just like linkgit:git-submodule[1], this will detach `HEAD` of the
 	submodule.
 
---no-guess::
-	Do not attempt to create a branch if a remote tracking branch
-	of the same name exists.
-
 --overlay::
 --no-overlay::
 	In the default overlay mode, `git checkout` never
builtin/checkout.c +8 -8
index a14133b474..ee74379038 100644
@@ -53,7 +53,7 @@ struct checkout_opts {
 	int show_progress;
 	int count_checkout_paths;
 	int overlay_mode;
-	int no_dwim_new_local_branch;
+	int dwim_new_local_branch;
 	int discard_changes;
 	int accept_pathspec;
 	int switch_branch_doing_nothing_is_ok;
@@ -1430,8 +1430,6 @@ static struct option *add_common_switch_branch_options(
 		OPT_BOOL_F(0, "overwrite-ignore", &opts->overwrite_ignore,
 			   N_("update ignored files (default)"),
 			   PARSE_OPT_NOCOMPLETE),
-		OPT_BOOL(0, "no-guess", &opts->no_dwim_new_local_branch,
-			 N_("second guess 'git checkout <no-such-branch>'")),
 		OPT_BOOL(0, "ignore-other-worktrees", &opts->ignore_other_worktrees,
 			 N_("do not check if another worktree is holding the given ref")),
 		OPT_END()
@@ -1468,7 +1466,6 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
 {
 	struct branch_info new_branch_info;
 	int dwim_remotes_matched = 0;
-	int dwim_new_local_branch;
 
 	memset(&new_branch_info, 0, sizeof(new_branch_info));
 	opts->overwrite_ignore = 1;
@@ -1483,7 +1480,6 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
 	argc = parse_options(argc, argv, prefix, options, usagestr,
 			     PARSE_OPT_KEEP_DASHDASH);
 
-	dwim_new_local_branch = !opts->no_dwim_new_local_branch;
 	if (opts->show_progress < 0) {
 		if (opts->quiet)
 			opts->show_progress = 0;
@@ -1545,7 +1541,7 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
 		struct object_id rev;
 		int dwim_ok =
 			!opts->patch_mode &&
-			dwim_new_local_branch &&
+			opts->dwim_new_local_branch &&
 			opts->track == BRANCH_TRACK_UNSPECIFIED &&
 			!opts->new_branch;
 		int n = parse_branchname_arg(argc, argv, dwim_ok,
@@ -1626,12 +1622,14 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 		OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
 			   N_("create/reset and checkout a branch")),
 		OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
+		OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
+			 N_("second guess 'git checkout <no-such-branch>' (default)")),
 		OPT_END()
 	};
 	int ret;
 
 	memset(&opts, 0, sizeof(opts));
-	opts.no_dwim_new_local_branch = 0;
+	opts.dwim_new_local_branch = 1;
 	opts.switch_branch_doing_nothing_is_ok = 1;
 	opts.accept_pathspec = 1;
 	opts.implicit_detach = 1;
@@ -1656,6 +1654,8 @@ int cmd_switch(int argc, const char **argv, const char *prefix)
 			   N_("create and switch to a new branch")),
 		OPT_STRING('C', "force-create", &opts.new_branch_force, N_("branch"),
 			   N_("create/reset and switch to a branch")),
+		OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
+			 N_("second guess 'git switch <no-such-branch>'")),
 		OPT_BOOL(0, "discard-changes", &opts.discard_changes,
 			 N_("throw away local modifications")),
 		OPT_END()
@@ -1663,7 +1663,7 @@ int cmd_switch(int argc, const char **argv, const char *prefix)
 	int ret;
 
 	memset(&opts, 0, sizeof(opts));
-	opts.no_dwim_new_local_branch = 0;
+	opts.dwim_new_local_branch = 1;
 	opts.accept_pathspec = 0;
 	opts.switch_branch_doing_nothing_is_ok = 0;
 	opts.implicit_detach = 0;
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#237 lore raw

PATCH v5 21/26 switch: no worktree status unless real branch switch happens

In reply to Nguyễn Thái Ngọc Duy

When we switch from one branch to another, it makes sense to show a summary of local changes since there could be conflicts, or some files left modified.... When switch is used solely for creating a new branch (and "switch" to the same commit) or detaching, we don't really need to show anything.

"git checkout" does it anyway for historical reasons. But we can start with a clean slate with switch and don't have to.

This essentially reverts fa655d8411 (checkout: optimize "git checkout -b <new_branch>" - 2018-08-16) and make it default for switch, but also for -B and --detach. Users of big repos are encouraged to move to switch.

---
 Documentation/config/checkout.txt |   8 --
 builtin/checkout.c                | 134 ++----------------------------
 t/t1090-sparse-checkout-scope.sh  |  14 ----
 3 files changed, 8 insertions(+), 148 deletions(-)
Documentation/config/checkout.txt +0 -8
index d6872ffa83..6b646813ab 100644
@@ -16,11 +16,3 @@ will checkout the '<something>' branch on another remote,
 and by linkgit:git-worktree[1] when 'git worktree add' refers to a
 remote branch. This setting might be used for other checkout-like
 commands or functionality in the future.
-
-checkout.optimizeNewBranch::
-	Optimizes the performance of "git checkout -b <new_branch>" when
-	using sparse-checkout.  When set to true, git will not update the
-	repo based on the current sparse-checkout settings.  This means it
-	will not update the skip-worktree bit in the index nor add/remove
-	files in the working directory to reflect the current sparse checkout
-	settings nor will it show the local changes.
builtin/checkout.c +8 -126

184 lines not on this page · raw message

t/t1090-sparse-checkout-scope.sh +0 -14
index 090b7fc3d3..40cc004326 100755
@@ -31,20 +31,6 @@ test_expect_success 'perform sparse checkout of master' '
 	test_path_is_file c
 '
 
-test_expect_success 'checkout -b checkout.optimizeNewBranch interaction' '
-	cp .git/info/sparse-checkout .git/info/sparse-checkout.bak &&
-	test_when_finished "
-		mv -f .git/info/sparse-checkout.bak .git/info/sparse-checkout
-		git checkout master
-	" &&
-	echo "/b" >>.git/info/sparse-checkout &&
-	test "$(git ls-files -t b)" = "S b" &&
-	git -c checkout.optimizeNewBranch=true checkout -b fast &&
-	test "$(git ls-files -t b)" = "S b" &&
-	git checkout -b slow &&
-	test "$(git ls-files -t b)" = "H b"
-'
-
 test_expect_success 'merge feature branch into sparse checkout of master' '
 	git merge feature &&
 	test_path_is_file a &&
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#238 lore raw

PATCH v5 22/26 switch: reject if some operation is in progress

In reply to Nguyễn Thái Ngọc Duy

Unless you know what you're doing, switching to another branch to do something then switching back could be confusing. Worse, you may even forget that you're in the middle of something. By the time you realize, you may have done a ton of work and it gets harder to go back.

The new option --ignore-in-progress is added to override this check. However it's probably just safer to create a separate worktree for that separate thing you want to work on and leave this worktree alone (unless of course creating or preparing worktrees are not cheap).

--force is updated to also imply --ignore-in-progress because it is supposed to be the "just do your things and don't bother me" option.

---
 builtin/checkout.c | 30 +++++++++++++++++++++++++++++-
 1 file changed, 29 insertions(+), 1 deletion(-)
builtin/checkout.c +29 -1
index 2aeaac092d..407ed8be94 100644
@@ -24,6 +24,7 @@
 #include "tree.h"
 #include "tree-walk.h"
 #include "unpack-trees.h"
+#include "wt-status.h"
 #include "xdiff-interface.h"
 
 static const char * const checkout_usage[] = {
@@ -56,6 +57,7 @@ struct checkout_opts {
 	int accept_pathspec;
 	int switch_branch_doing_nothing_is_ok;
 	int only_merge_on_switching_branches;
+	int can_switch_when_in_progress;
 
 	const char *new_branch;
 	const char *new_branch_force;
@@ -1257,6 +1259,26 @@ static int checkout_branch(struct checkout_opts *opts,
 	    !new_branch_info->path)
 		die_expecting_a_branch(new_branch_info);
 
+	if (!opts->can_switch_when_in_progress) {
+		struct wt_status_state state;
+
+		memset(&state, 0, sizeof(state));
+		wt_status_get_state(the_repository, &state, 0);
+
+		if (state.merge_in_progress)
+			die(_("cannot switch branch while merging"));
+		if (state.am_in_progress)
+			die(_("cannot switch branch in the middle of an am session"));
+		if (state.rebase_interactive_in_progress || state.rebase_in_progress)
+			die(_("cannot switch branch while rebasing"));
+		if (state.cherry_pick_in_progress)
+			die(_("cannot switch branch while cherry-picking"));
+		if (state.revert_in_progress)
+			die(_("cannot switch branch while reverting"));
+		if (state.bisect_in_progress)
+			die(_("cannot switch branch while bisecting"));
+	}
+
 	if (new_branch_info->path && !opts->force_detach && !opts->new_branch &&
 	    !opts->ignore_other_worktrees) {
 		int flag;
@@ -1371,8 +1393,10 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
 		opts->merge = 1; /* implied */
 		git_xmerge_config("merge.conflictstyle", opts->conflict_style, NULL);
 	}
-	if (opts->force)
+	if (opts->force) {
 		opts->discard_changes = 1;
+		opts->can_switch_when_in_progress = 1;
+	}
 
 	if ((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) > 1)
 		die(_("-b, -B and --orphan are mutually exclusive"));
@@ -1514,6 +1538,7 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 	opts.only_merge_on_switching_branches = 0;
 	opts.accept_pathspec = 1;
 	opts.implicit_detach = 1;
+	opts.can_switch_when_in_progress = 1;
 
 	options = parse_options_dup(checkout_options);
 	options = add_common_options(&opts, options);
@@ -1539,6 +1564,8 @@ int cmd_switch(int argc, const char **argv, const char *prefix)
 			 N_("second guess 'git switch <no-such-branch>'")),
 		OPT_BOOL(0, "discard-changes", &opts.discard_changes,
 			 N_("throw away local modifications")),
+		OPT_BOOL(0, "ignore-in-progress", &opts.can_switch_when_in_progress,
+			 N_("allow to switch branch when some operation is still in progress")),
 		OPT_END()
 	};
 	int ret;
@@ -1549,6 +1576,7 @@ int cmd_switch(int argc, const char **argv, const char *prefix)
 	opts.switch_branch_doing_nothing_is_ok = 0;
 	opts.only_merge_on_switching_branches = 1;
 	opts.implicit_detach = 0;
+	opts.can_switch_when_in_progress = 0;
 
 	options = parse_options_dup(switch_options);
 	options = add_common_options(&opts, options);
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#239 lore raw

PATCH v5 23/26 switch: make --orphan switch to an empty tree

In reply to Nguyễn Thái Ngọc Duy

Switching and creating branches always involves knowing the <start-point> to begin the new branch from. Sometimes, people want to create a new branch that does not have any commits yet; --orphan is a flag to allow that.

--orphan overrides the default of HEAD for <start-point> instead causing us to start from an empty history with all tracked files removed from the index and working tree. The use of --orphan is incompatible with specifying a <start-point>.

A note on the implementation. An alternative is just create a dummy commit in-core with empty tree and switch to it. But there's a chance the commit's SHA-1 may end up somewhere permanent like reflog. It's best to make sure "commit" pointer is NULL to avoid it.

---
 builtin/checkout.c | 39 +++++++++++++++++++++++++++++++--------
 1 file changed, 31 insertions(+), 8 deletions(-)
builtin/checkout.c +31 -8
index 407ed8be94..c7f4b5e3c0 100644
@@ -58,6 +58,7 @@ struct checkout_opts {
 	int switch_branch_doing_nothing_is_ok;
 	int only_merge_on_switching_branches;
 	int can_switch_when_in_progress;
+	int orphan_from_empty_tree;
 
 	const char *new_branch;
 	const char *new_branch_force;
@@ -568,15 +569,21 @@ static int merge_working_tree(const struct checkout_opts *opts,
 {
 	int ret;
 	struct lock_file lock_file = LOCK_INIT;
+	struct tree *new_tree;
 
 	hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
 	if (read_cache_preload(NULL) < 0)
 		return error(_("index file corrupt"));
 
 	resolve_undo_clear();
+	if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
+		if (new_branch_info->commit)
+			BUG("'switch --orphan' should never accept a commit as starting point");
+		new_tree = parse_tree_indirect(the_hash_algo->empty_tree);
+	} else
+		new_tree = get_commit_tree(new_branch_info->commit);
 	if (opts->discard_changes) {
-		ret = reset_tree(get_commit_tree(new_branch_info->commit),
-				 opts, 1, writeout_error);
+		ret = reset_tree(new_tree, opts, 1, writeout_error);
 		if (ret)
 			return ret;
 	} else {
@@ -614,7 +621,8 @@ static int merge_working_tree(const struct checkout_opts *opts,
 					   &old_branch_info->commit->object.oid :
 					   the_hash_algo->empty_tree);
 		init_tree_desc(&trees[0], tree->buffer, tree->size);
-		tree = parse_tree_indirect(&new_branch_info->commit->object.oid);
+		parse_tree(new_tree);
+		tree = new_tree;
 		init_tree_desc(&trees[1], tree->buffer, tree->size);
 
 		ret = unpack_trees(2, trees, &topts);
@@ -663,7 +671,7 @@ static int merge_working_tree(const struct checkout_opts *opts,
 			o.verbosity = 0;
 			work = write_tree_from_memory(&o);
 
-			ret = reset_tree(get_commit_tree(new_branch_info->commit),
+			ret = reset_tree(new_tree,
 					 opts, 1,
 					 writeout_error);
 			if (ret)
@@ -672,13 +680,13 @@ static int merge_working_tree(const struct checkout_opts *opts,
 			o.branch1 = new_branch_info->name;
 			o.branch2 = "local";
 			ret = merge_trees(&o,
-					  get_commit_tree(new_branch_info->commit),
+					  new_tree,
 					  work,
 					  get_commit_tree(old_branch_info->commit),
 					  &result);
 			if (ret < 0)
 				exit(128);
-			ret = reset_tree(get_commit_tree(new_branch_info->commit),
+			ret = reset_tree(new_tree,
 					 opts, 0,
 					 writeout_error);
 			strbuf_release(&o.obuf);
@@ -696,7 +704,7 @@ static int merge_working_tree(const struct checkout_opts *opts,
 	if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
 		die(_("unable to write new index file"));
 
-	if (!opts->discard_changes && !opts->quiet)
+	if (!opts->discard_changes && !opts->quiet && new_branch_info->commit)
 		show_local_changes(&new_branch_info->commit->object, &opts->diff_options);
 
 	return 0;
@@ -897,7 +905,10 @@ static void orphaned_commit_warning(struct commit *old_commit, struct commit *ne
 	add_pending_object(&revs, object, oid_to_hex(&object->oid));
 
 	for_each_ref(add_pending_uninteresting_ref, &revs);
-	add_pending_oid(&revs, "HEAD", &new_commit->object.oid, UNINTERESTING);
+	if (new_commit)
+		add_pending_oid(&revs, "HEAD",
+				&new_commit->object.oid,
+				UNINTERESTING);
 
 	if (prepare_revision_walk(&revs))
 		die(_("internal error in revision walk"));
@@ -932,6 +943,14 @@ static int switch_branches(const struct checkout_opts *opts,
 	if (old_branch_info.path)
 		skip_prefix(old_branch_info.path, "refs/heads/", &old_branch_info.name);
 
+	if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
+		if (new_branch_info->name)
+			BUG("'switch --orphan' should never accept a commit as starting point");
+		new_branch_info->commit = NULL;
+		new_branch_info->name = "(empty)";
+		do_merge = 1;
+	}
+
 	if (!new_branch_info->name) {
 		new_branch_info->name = "HEAD";
 		new_branch_info->commit = old_branch_info.commit;
@@ -1235,6 +1254,8 @@ static int checkout_branch(struct checkout_opts *opts,
 	if (opts->new_orphan_branch) {
 		if (opts->track != BRANCH_TRACK_UNSPECIFIED)
 			die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
+		if (opts->orphan_from_empty_tree && new_branch_info->name)
+			die(_("'%s' cannot take <start-point>"), "--orphan");
 	} else if (opts->force_detach) {
 		if (opts->track != BRANCH_TRACK_UNSPECIFIED)
 			die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
@@ -1539,6 +1560,7 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
 	opts.accept_pathspec = 1;
 	opts.implicit_detach = 1;
 	opts.can_switch_when_in_progress = 1;
+	opts.orphan_from_empty_tree = 0;
 
 	options = parse_options_dup(checkout_options);
 	options = add_common_options(&opts, options);
@@ -1577,6 +1599,7 @@ int cmd_switch(int argc, const char **argv, const char *prefix)
 	opts.only_merge_on_switching_branches = 1;
 	opts.implicit_detach = 0;
 	opts.can_switch_when_in_progress = 0;
+	opts.orphan_from_empty_tree = 1;
 
 	options = parse_options_dup(switch_options);
 	options = add_common_options(&opts, options);
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#240 lore raw

PATCH v5 24/26 t: add tests for switch

In reply to Nguyễn Thái Ngọc Duy
---
 t/t2060-switch.sh (new +x) | 98 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 98 insertions(+)
t/t2060-switch.sh new file +98 -0
new file mode 100755
index 0000000000..81e13cf7f0
@@ -0,0 +1,98 @@
+#!/bin/sh
+
+test_description='switch basic functionality'
+
+. ./test-lib.sh
+
+test_expect_success 'setup' '
+	test_commit first &&
+	git branch first-branch &&
+	test_commit second &&
+	test_commit third &&
+	git remote add origin nohost:/nopath &&
+	git update-ref refs/remotes/origin/foo first-branch
+'
+
+test_expect_success 'switch branch no arguments' '
+	test_must_fail git switch
+'
+
+test_expect_success 'switch branch' '
+	git switch first-branch &&
+	test_path_is_missing second.t
+'
+
+test_expect_success 'switch and detach' '
+	test_when_finished git switch master &&
+	test_must_fail git switch master^{commit} &&
+	git switch --detach master^{commit} &&
+	test_must_fail git symbolic-ref HEAD
+'
+
+test_expect_success 'switch and detach current branch' '
+	test_when_finished git switch master &&
+	git switch master &&
+	git switch --detach &&
+	test_must_fail git symbolic-ref HEAD
+'
+
+test_expect_success 'switch and create branch' '
+	test_when_finished git switch master &&
+	git switch -c temp master^ &&
+	test_cmp_rev master^ refs/heads/temp &&
+	echo refs/heads/temp >expected-branch &&
+	git symbolic-ref HEAD >actual-branch &&
+	test_cmp expected-branch actual-branch
+'
+
+test_expect_success 'force create branch from HEAD' '
+	test_when_finished git switch master &&
+	git switch --detach master &&
+	test_must_fail git switch -c temp &&
+	git switch -C temp &&
+	test_cmp_rev master refs/heads/temp &&
+	echo refs/heads/temp >expected-branch &&
+	git symbolic-ref HEAD >actual-branch &&
+	test_cmp expected-branch actual-branch
+'
+
+test_expect_success 'new orphan branch from empty' '
+	test_when_finished git switch master &&
+	test_must_fail git switch --orphan new-orphan HEAD &&
+	git switch --orphan new-orphan &&
+	test_commit orphan &&
+	git cat-file commit refs/heads/new-orphan >commit &&
+	! grep ^parent commit &&
+	git ls-files >tracked-files &&
+	echo orphan.t >expected &&
+	test_cmp expected tracked-files
+'
+
+test_expect_success 'switching ignores file of same branch name' '
+	test_when_finished git switch master &&
+	: >first-branch &&
+	git switch first-branch &&
+	echo refs/heads/first-branch >expected &&
+	git symbolic-ref HEAD >actual &&
+	test_cmp expected actual
+'
+
+test_expect_success 'guess and create branch ' '
+	test_when_finished git switch master &&
+	test_must_fail git switch --no-guess foo &&
+	git switch foo &&
+	echo refs/heads/foo >expected &&
+	git symbolic-ref HEAD >actual &&
+	test_cmp expected actual
+'
+
+test_expect_success 'switching when something is in progress' '
+	test_when_finished rm -f .git/MERGE_HEAD &&
+	# fake a merge-in-progress
+	cp .git/HEAD .git/MERGE_HEAD &&
+	test_must_fail git switch -d @^ &&
+	git switch --ignore-in-progress -d @^ &&
+	git switch -
+'
+
+test_done
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#241 lore raw

PATCH v5 25/26 completion: support switch

In reply to Nguyễn Thái Ngọc Duy

Completion support for --guess could be made better. If no --detach is given, we should only provide a list of refs/heads/* and dwim ones, not the entire ref space. But I still can't penetrate that __git_refs() function yet.

---
 contrib/completion/git-completion.bash | 37 +++++++++++++++++++++++++-
 1 file changed, 36 insertions(+), 1 deletion(-)
contrib/completion/git-completion.bash +36 -1
index 976e4a6548..b24bc48276 100644
@@ -37,7 +37,8 @@
 #   GIT_COMPLETION_CHECKOUT_NO_GUESS
 #
 #     When set to "1", do not include "DWIM" suggestions in git-checkout
-#     completion (e.g., completing "foo" when "origin/foo" exists).
+#     and git-switch completion (e.g., completing "foo" when "origin/foo"
+#     exists).
 
 case "$COMP_WORDBREAKS" in
 *:*) : great ;;
@@ -2158,6 +2159,40 @@ _git_status ()
 	__git_complete_index_file "$complete_opt"
 }
 
+_git_switch ()
+{
+	case "$cur" in
+	--conflict=*)
+		__gitcomp "diff3 merge" "" "${cur##--conflict=}"
+		;;
+	--*)
+		__gitcomp_builtin switch
+		;;
+	*)
+		# check if --track, --no-track, or --no-guess was specified
+		# if so, disable DWIM mode
+		local track_opt="--track" only_local_ref=n
+		if [ "$GIT_COMPLETION_CHECKOUT_NO_GUESS" = "1" ] ||
+		   [ -n "$(__git_find_on_cmdline "--track --no-track --no-guess")" ]; then
+			track_opt=''
+		fi
+		# explicit --guess enables DWIM mode regardless of
+		# $GIT_COMPLETION_CHECKOUT_NO_GUESS
+		if [ -n "$(__git_find_on_cmdline "--guess")" ]; then
+			track_opt='--track'
+		fi
+		if [ -z "$(__git_find_on_cmdline "-d --detach")" ]; then
+			only_local_ref=y
+		fi
+		if [ $only_local_ref = y -a -z "$track_opt" ]; then
+			__gitcomp_direct "$(__git_heads "" "$cur" " ")"
+		else
+			__git_complete_refs $track_opt
+		fi
+		;;
+	esac
+}
+
 __git_config_get_set_variables ()
 {
 	local prevword word config_file= c=$cword
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#242 lore raw

PATCH v5 26/26 doc: promote "git switch"

In reply to Nguyễn Thái Ngọc Duy

The new command "git switch" is added to avoid the confusion of one-command-do-all "git checkout" for new users. They are also helpful to avoid ambiguation context.

For these reasons, promote it everywhere possible. This includes documentation, suggestions/advice from other commands...

---
 Documentation/git-branch.txt           | 12 +++---
 Documentation/git-check-ref-format.txt |  3 +-
 Documentation/git-format-patch.txt     |  2 +-
 Documentation/git-merge-base.txt       |  2 +-
 Documentation/git-rebase.txt           |  2 +-
 Documentation/git-remote.txt           |  2 +-
 Documentation/git-rerere.txt           | 10 ++---
 Documentation/git-reset.txt            | 20 ++++-----
 Documentation/git-stash.txt            |  9 +++--
 Documentation/gitcore-tutorial.txt     | 19 +++++----
 Documentation/giteveryday.txt          | 24 +++++------
 Documentation/gittutorial.txt          |  4 +-
 Documentation/gitworkflows.txt         |  3 +-
 Documentation/revisions.txt            |  2 +-
 Documentation/user-manual.txt          | 56 +++++++++++++-------------
 advice.c                               | 10 ++---
 sha1-name.c                            |  2 +-
 t/t2020-checkout-detach.sh             | 20 ++++-----
 18 files changed, 101 insertions(+), 101 deletions(-)
Documentation/git-branch.txt +6 -6
index 0cd87ddeff..1e2d89b174 100644
@@ -48,7 +48,7 @@ The command's second form creates a new branch head named <branchname>
 which points to the current `HEAD`, or <start-point> if given.
 
 Note that this will create the new branch, but it will not switch the
-working tree to it; use "git checkout <newbranch>" to switch to the
+working tree to it; use "git switch <newbranch>" to switch to the
 new branch.
 
 When a local branch is started off a remote-tracking branch, Git sets up the
@@ -198,7 +198,7 @@ This option is only applicable in non-verbose mode.
 +
 This behavior is the default when the start point is a remote-tracking branch.
 Set the branch.autoSetupMerge configuration variable to `false` if you
-want `git checkout` and `git branch` to always behave as if `--no-track`
+want `git switch`, `git checkout` and `git branch` to always behave as if `--no-track`
 were given. Set it to `always` if you want this behavior when the
 start-point is either a local or remote-tracking branch.
 
@@ -297,7 +297,7 @@ Start development from a known tag::
 $ git clone git://git.kernel.org/pub/scm/.../linux-2.6 my2.6
 $ cd my2.6
 $ git branch my2.6.14 v2.6.14   <1>
-$ git checkout my2.6.14
+$ git switch my2.6.14
 ------------
 +
 <1> This step and the next one could be combined into a single step with
@@ -322,9 +322,9 @@ $ git branch -D test                                    <2>
 NOTES
 -----
 
-If you are creating a branch that you want to checkout immediately, it is
-easier to use the git checkout command with its `-b` option to create
-a branch and check it out with a single command.
+If you are creating a branch that you want to switch to immediately,
+it is easier to use the "git switch" command with its `-c` option to
+do the same thing with a single command.
 
 The options `--contains`, `--no-contains`, `--merged` and `--no-merged`
 serve four related but different purposes:
Documentation/git-check-ref-format.txt +2 -1
index d9de992585..ee6a4144fb 100644
@@ -88,7 +88,8 @@ but it is explicitly forbidden at the beginning of a branch name).
 When run with `--branch` option in a repository, the input is first
 expanded for the ``previous checkout syntax''
 `@{-n}`.  For example, `@{-1}` is a way to refer the last thing that
-was checked out using "git checkout" operation. This option should be
+was checked out using "git switch" or "git checkout" operation.
+This option should be
 used by porcelains to accept this syntax anywhere a branch name is
 expected, so they can act as if you typed the branch name. As an
 exception note that, the ``previous checkout operation'' might result
Documentation/git-format-patch.txt +1 -1
index 1af85d404f..0a24a5679e 100644
@@ -421,7 +421,7 @@ One way to test if your MUA is set up correctly is:
 * Apply it:
 
     $ git fetch <project> master:test-apply
-    $ git checkout test-apply
+    $ git switch test-apply
     $ git reset --hard
     $ git am a.patch
 
Documentation/git-merge-base.txt +1 -1
index 9f07f4f6ed..261d5c1164 100644
@@ -149,7 +149,7 @@ instead.
 Discussion on fork-point mode
 -----------------------------
 
-After working on the `topic` branch created with `git checkout -b
+After working on the `topic` branch created with `git switch -c
 topic origin/master`, the history of remote-tracking branch
 `origin/master` may have been rewound and rebuilt, leading to a
 history of this shape:
Documentation/git-rebase.txt +1 -1
index 5629ba4c5d..cb6fc166e2 100644
@@ -17,7 +17,7 @@ SYNOPSIS
 DESCRIPTION
 -----------
 If <branch> is specified, 'git rebase' will perform an automatic
-`git checkout <branch>` before doing anything else.  Otherwise
+`git switch <branch>` before doing anything else.  Otherwise
 it remains on the current branch.
 
 If <upstream> is not specified, the upstream configured in
Documentation/git-remote.txt +1 -1
index 0cad37fb81..9659abbf8e 100644
@@ -230,7 +230,7 @@ $ git branch -r
   staging/master
   staging/staging-linus
   staging/staging-next
-$ git checkout -b staging staging/master
+$ git switch -c staging staging/master
 ...
 ------------
 
Documentation/git-rerere.txt +5 -5
index df310d2a58..fe4434ad9d 100644
@@ -91,7 +91,7 @@ For such a test, you need to merge master and topic somehow.
 One way to do it is to pull master into the topic branch:
 
 ------------
-	$ git checkout topic
+	$ git switch topic
 	$ git merge master
 
               o---*---o---+ topic
@@ -113,10 +113,10 @@ the upstream might have been advanced since the test merge `+`,
 in which case the final commit graph would look like this:
 
 ------------
-	$ git checkout topic
+	$ git switch topic
 	$ git merge master
 	$ ... work on both topic and master branches
-	$ git checkout master
+	$ git switch master
 	$ git merge topic
 
               o---*---o---+---o---o topic
@@ -136,11 +136,11 @@ merges, you could blow away the test merge, and keep building on
 top of the tip before the test merge:
 
 ------------
-	$ git checkout topic
+	$ git switch topic
 	$ git merge master
 	$ git reset --hard HEAD^ ;# rewind the test merge
 	$ ... work on both topic and master branches
-	$ git checkout master
+	$ git switch master
 	$ git merge topic
 
               o---*---o-------o---o topic
Documentation/git-reset.txt +10 -10
index 132f8e55f6..cbf901efb4 100644
@@ -149,9 +149,9 @@ See also the `--amend` option to linkgit:git-commit[1].
 Undo a commit, making it a topic branch::
 +
 ------------
-$ git branch topic/wip     <1>
-$ git reset --hard HEAD~3  <2>
-$ git checkout topic/wip   <3>
+$ git branch topic/wip          <1>
+$ git reset --hard HEAD~3       <2>
+$ git switch topic/wip          <3>
 ------------
 +
 <1> You have made some commits, but realize they were premature
@@ -232,13 +232,13 @@ working tree are not in any shape to be committed yet, but you
 need to get to the other branch for a quick bugfix.
 +
 ------------
-$ git checkout feature ;# you were working in "feature" branch and
-$ work work work       ;# got interrupted
+$ git switch feature  ;# you were working in "feature" branch and
+$ work work work      ;# got interrupted
 $ git commit -a -m "snapshot WIP"                 <1>
-$ git checkout master
+$ git switch master
 $ fix fix fix
 $ git commit ;# commit with real log
-$ git checkout feature
+$ git switch feature
 $ git reset --soft HEAD^ ;# go back to WIP state  <2>
 $ git reset                                       <3>
 ------------
@@ -279,18 +279,18 @@ reset it while keeping the changes in your working tree.
 +
 ------------
 $ git tag start
-$ git checkout -b branch1
+$ git switch -c branch1
 $ edit
 $ git commit ...                            <1>
 $ edit
-$ git checkout -b branch2                   <2>
+$ git switch -c branch2                     <2>
 $ git reset --keep start                    <3>
 ------------
 +
 <1> This commits your first edits in `branch1`.
 <2> In the ideal world, you could have realized that the earlier
     commit did not belong to the new topic when you created and switched
-    to `branch2` (i.e. `git checkout -b branch2 start`), but nobody is
+    to `branch2` (i.e. `git switch -c branch2 start`), but nobody is
     perfect.
 <3> But you can use `reset --keep` to remove the unwanted commit after
     you switched to `branch2`.
Documentation/git-stash.txt +5 -4
index 7ef8c47911..ebb6282db3 100644
@@ -235,12 +235,12 @@ return to your original branch to make the emergency fix, like this:
 +
 ----------------------------------------------------------------
 # ... hack hack hack ...
-$ git checkout -b my_wip
+$ git switch -c my_wip
 $ git commit -a -m "WIP"
-$ git checkout master
+$ git switch master
 $ edit emergency fix
 $ git commit -a -m "Fix in a hurry"
-$ git checkout my_wip
+$ git switch my_wip
 $ git reset --soft HEAD^
 # ... continue hacking ...
 ----------------------------------------------------------------
@@ -293,7 +293,8 @@ SEE ALSO
 linkgit:git-checkout[1],
 linkgit:git-commit[1],
 linkgit:git-reflog[1],
-linkgit:git-reset[1]
+linkgit:git-reset[1],
+linkgit:git-switch[1]
 
 GIT
 ---
Documentation/gitcore-tutorial.txt +9 -10
index e29a9effcc..f880d21dfb 100644
@@ -741,7 +741,7 @@ used earlier, and create a branch in it. You do that by simply just
 saying that you want to check out a new branch:
 
 ------------
-$ git checkout -b mybranch
+$ git switch -c mybranch
 ------------
 
 will create a new branch based at the current `HEAD` position, and switch
@@ -755,7 +755,7 @@ just telling 'git checkout' what the base of the checkout would be.
 In other words, if you have an earlier tag or branch, you'd just do
 
 ------------
-$ git checkout -b mybranch earlier-commit
+$ git switch -c mybranch earlier-commit
 ------------
 
 and it would create the new branch `mybranch` at the earlier commit,
@@ -765,7 +765,7 @@ and check out the state at that time.
 You can always just jump back to your original `master` branch by doing
 
 ------------
-$ git checkout master
+$ git switch master
 ------------
 
 (or any other branch-name, for that matter) and if you forget which
@@ -794,7 +794,7 @@ $ git branch <branchname> [startingpoint]
 
 which will simply _create_ the branch, but will not do anything further.
 You can then later -- once you decide that you want to actually develop
-on that branch -- switch to that branch with a regular 'git checkout'
+on that branch -- switch to that branch with a regular 'git switch'
 with the branchname as the argument.
 
 
@@ -808,7 +808,7 @@ being the same as the original `master` branch, let's make sure we're in
 that branch, and do some work there.
 
 ------------------------------------------------
-$ git checkout mybranch
+$ git switch mybranch
 $ echo "Work, work, work" >>hello
 $ git commit -m "Some work." -i hello
 ------------------------------------------------
@@ -825,7 +825,7 @@ does some work in the original branch, and simulate that by going back
 to the master branch, and editing the same file differently there:
 
 ------------
-$ git checkout master
+$ git switch master
 ------------
 
 Here, take a moment to look at the contents of `hello`, and notice how they
@@ -958,7 +958,7 @@ to the `master` branch. Let's go back to `mybranch`, and run
 'git merge' to get the "upstream changes" back to your branch.
 
 ------------
-$ git checkout mybranch
+$ git switch mybranch
 $ git merge -m "Merge upstream changes." master
 ------------
 
@@ -1133,9 +1133,8 @@ Remember, before running 'git merge', our `master` head was at
 work." commit.
 
 ------------
-$ git checkout mybranch
-$ git reset --hard master^2
-$ git checkout master
+$ git switch -C mybranch master^2
+$ git switch master
 $ git reset --hard master^
 ------------
 
Documentation/giteveryday.txt +12 -12
index 9f2528fc8c..ad455f3e39 100644
@@ -41,7 +41,7 @@ following commands.
 
   * linkgit:git-log[1] to see what happened.
 
-  * linkgit:git-checkout[1] and linkgit:git-branch[1] to switch
+  * linkgit:git-switch[1] and linkgit:git-branch[1] to switch
     branches.
 
   * linkgit:git-add[1] to manage the index file.
@@ -80,7 +80,7 @@ $ git tag v2.43 <2>
 Create a topic branch and develop.::
 +
 ------------
-$ git checkout -b alsa-audio <1>
+$ git switch -c alsa-audio <1>
 $ edit/compile/test
 $ git checkout -- curses/ux_audio_oss.c <2>
 $ git add curses/ux_audio_alsa.c <3>
@@ -90,7 +90,7 @@ $ git commit -a -s <5>
 $ edit/compile/test
 $ git diff HEAD^ <6>
 $ git commit -a --amend <7>
-$ git checkout master <8>
+$ git switch master <8>
 $ git merge alsa-audio <9>
 $ git log --since='3 days ago' <10>
 $ git log v2.43.. curses/ <11>
@@ -148,11 +148,11 @@ Clone the upstream and work on it.  Feed changes to upstream.::
 ------------
 $ git clone git://git.kernel.org/pub/scm/.../torvalds/linux-2.6 my2.6
 $ cd my2.6
-$ git checkout -b mine master <1>
+$ git switch -c mine master <1>
 $ edit/compile/test; git commit -a -s <2>
 $ git format-patch master <3>
 $ git send-email --to="person <[email protected]>" 00*.patch <4>
-$ git checkout master <5>
+$ git switch master <5>
 $ git pull <6>
 $ git log -p ORIG_HEAD.. arch/i386 include/asm-i386 <7>
 $ git ls-remote --heads http://git.kernel.org/.../jgarzik/libata-dev.git <8>
@@ -194,7 +194,7 @@ satellite$ edit/compile/test/commit
 satellite$ git push origin <4>
 
 mothership$ cd frotz
-mothership$ git checkout master
+mothership$ git switch master
 mothership$ git merge satellite/master <5>
 ------------
 +
@@ -216,7 +216,7 @@ machine into the master branch.
 Branch off of a specific tag.::
 +
 ------------
-$ git checkout -b private2.6.14 v2.6.14 <1>
+$ git switch -c private2.6.14 v2.6.14 <1>
 $ edit/compile/test; git commit -a
 $ git checkout master
 $ git cherry-pick v2.6.14..private2.6.14 <2>
@@ -274,14 +274,14 @@ $ mailx <3>
 & s 2 3 4 5 ./+to-apply
 & s 7 8 ./+hold-linus
 & q
-$ git checkout -b topic/one master
+$ git switch -c topic/one master
 $ git am -3 -i -s ./+to-apply <4>
 $ compile/test
-$ git checkout -b hold/linus && git am -3 -i -s ./+hold-linus <5>
-$ git checkout topic/one && git rebase master <6>
-$ git checkout pu && git reset --hard next <7>
+$ git switch -c hold/linus && git am -3 -i -s ./+hold-linus <5>
+$ git switch topic/one && git rebase master <6>
+$ git switch -C pu next <7>
 $ git merge topic/one topic/two && git merge hold/linus <8>
-$ git checkout maint
+$ git switch maint
 $ git cherry-pick master~4 <9>
 $ compile/test
 $ git tag -s -m "GIT 0.99.9x" v0.99.9x <10>
Documentation/gittutorial.txt +2 -2
index 242de31cb6..e6ad6b5f8d 100644
@@ -207,7 +207,7 @@ automatically.  The asterisk marks the branch you are currently on;
 type
 
 ------------------------------------------------
-$ git checkout experimental
+$ git switch experimental
 ------------------------------------------------
 
 to switch to the experimental branch.  Now edit a file, commit the
@@ -216,7 +216,7 @@ change, and switch back to the master branch:
 ------------------------------------------------
 (edit file)
 $ git commit -a
-$ git checkout master
+$ git switch master
 ------------------------------------------------
 
 Check that the change you made is no longer visible, since it was
Documentation/gitworkflows.txt +1 -2
index ca11c7bdaf..abc0dc6bc7 100644
@@ -301,8 +301,7 @@ topics on 'next':
 .Rewind and rebuild next
 [caption="Recipe: "]
 =====================================
-* `git checkout next`
-* `git reset --hard master`
+* `git switch -C next master`
 * `git merge ai/topic_in_next1`
 * `git merge ai/topic_in_next2`
 * ...
Documentation/revisions.txt +1 -1
index 72daa20e76..a1c7a65da6 100644
@@ -115,7 +115,7 @@ Here's an example to make it more clear:
 ------------------------------
 $ git config push.default current
 $ git config remote.pushdefault myfork
-$ git checkout -b mybranch origin/master
+$ git switch -c mybranch origin/master
 
 $ git rev-parse --symbolic-full-name @{upstream}
 refs/remotes/origin/master
Documentation/user-manual.txt +28 -28

164 lines not on this page · raw message

advice.c +5 -5
index b224825637..27e39e6514 100644
@@ -191,20 +191,20 @@ void NORETURN die_conclude_merge(void)
 void detach_advice(const char *new_name)
 {
 	const char *fmt =
-	_("Note: checking out '%s'.\n"
+	_("Note: switching to '%s'.\n"
 	"\n"
 	"You are in 'detached HEAD' state. You can look around, make experimental\n"
 	"changes and commit them, and you can discard any commits you make in this\n"
-	"state without impacting any branches by performing another checkout.\n"
+	"state without impacting any branches by switching back to a branch.\n"
 	"\n"
 	"If you want to create a new branch to retain commits you create, you may\n"
-	"do so (now or later) by using -b with the checkout command again. Example:\n"
+	"do so (now or later) by using -c with the switch command. Example:\n"
 	"\n"
-	"  git checkout -b <new-branch-name>\n"
+	"  git switch -c <new-branch-name>\n"
 	"\n"
 	"Or undo this checkout with:\n"
 	"\n"
-	"  git checkout -\n"
+	"  git switch -\n"
 	"\n"
 	"Turn off this advice by setting config variable advice.detachedHead to false\n\n");
 
sha1-name.c +1 -1
index 6dda2c16df..da0518c8e3 100644
@@ -743,7 +743,7 @@ static int get_oid_basic(const char *str, int len, struct object_id *oid,
 	"because it will be ignored when you just specify 40-hex. These refs\n"
 	"may be created by mistake. For example,\n"
 	"\n"
-	"  git checkout -b $br $(git rev-parse ...)\n"
+	"  git switch -c $br $(git rev-parse ...)\n"
 	"\n"
 	"where \"$br\" is somehow empty and a 40-hex ref is created. Please\n"
 	"examine these refs and maybe delete them. Turn this message off by\n"
t/t2020-checkout-detach.sh +10 -10
index 743c7248a2..da6809b48f 100755
@@ -195,20 +195,20 @@ test_expect_success 'describe_detached_head prints no SHA-1 ellipsis when not as
 
 	# The first detach operation is more chatty than the following ones.
 	cat >1st_detach <<-EOF &&
-	Note: checking out 'HEAD^'.
+	Note: switching to 'HEAD^'.
 
 	You are in 'detached HEAD' state. You can look around, make experimental
 	changes and commit them, and you can discard any commits you make in this
-	state without impacting any branches by performing another checkout.
+	state without impacting any branches by switching back to a branch.
 
 	If you want to create a new branch to retain commits you create, you may
-	do so (now or later) by using -b with the checkout command again. Example:
+	do so (now or later) by using -c with the switch command. Example:
 
-	  git checkout -b <new-branch-name>
+	  git switch -c <new-branch-name>
 
 	Or undo this checkout with:
 
-	  git checkout -
+	  git switch -
 
 	Turn off this advice by setting config variable advice.detachedHead to false
 
@@ -277,20 +277,20 @@ test_expect_success 'describe_detached_head does print SHA-1 ellipsis when asked
 
 	# The first detach operation is more chatty than the following ones.
 	cat >1st_detach <<-EOF &&
-	Note: checking out 'HEAD^'.
+	Note: switching to 'HEAD^'.
 
 	You are in 'detached HEAD' state. You can look around, make experimental
 	changes and commit them, and you can discard any commits you make in this
-	state without impacting any branches by performing another checkout.
+	state without impacting any branches by switching back to a branch.
 
 	If you want to create a new branch to retain commits you create, you may
-	do so (now or later) by using -b with the checkout command again. Example:
+	do so (now or later) by using -c with the switch command. Example:
 
-	  git checkout -b <new-branch-name>
+	  git switch -c <new-branch-name>
 
 	Or undo this checkout with:
 
-	  git checkout -
+	  git switch -
 
 	Turn off this advice by setting config variable advice.detachedHead to false
 
Signature · 1 line
2.21.0.548.gd3c7d92dc2
#243 lore raw

Re: [PATCH v5 26/26] doc: promote "git switch"

Quoted 16 lines · Nguyễn Thái Ngọc Duy

...

advice.c +1 -2
index b224825637..27e39e6514 100644
@@ -191,20 +191,20 @@ void NORETURN die_conclude_merge(void)
 void detach_advice(const char *new_name)
 {
 	const char *fmt =
-	_("Note: checking out '%s'.\n"
+	_("Note: switching to '%s'.\n"
 	"\n"
 	"You are in 'detached HEAD' state. You can look around, make experimental\n"
 	"changes and commit them, and you can discard any commits you make in this\n"
-	"state without impacting any branches by performing another checkout.\n"

advice.c void NORETURN die_conclude_merge(void) · line 205

Quoted 10 lines
advice.c +3 -2
+	"state without impacting any branches by switching back to a branch.\n"
 	"\n"
 	"If you want to create a new branch to retain commits you create, you may\n"
-	"do so (now or later) by using -b with the checkout command again. Example:\n"
+	"do so (now or later) by using -c with the switch command. Example:\n"
 	"\n"
-	"  git checkout -b <new-branch-name>\n"
+	"  git switch -c <new-branch-name>\n"
 	"\n"
 	"Or undo this checkout with:\n"

With the start of the message being "switching to ..." this part could probably be also updated to something like "Or undo this switch with" or "Or undo this switch or checkout with".

Quoted 6 lines
advice.c +1 -1
 	"\n"
-	"  git checkout -\n"
+	"  git switch -\n"
 	"\n"
 	"Turn off this advice by setting config variable advice.detachedHead to false\n\n");
 
author
#244 lore raw

Re: [PATCH v5 26/26] doc: promote "git switch"

Quoted 24 lines · Andrei Rybak
Quoted 22 lines · Nguyễn Thái Ngọc Duy

...

advice.c +3 -3
index b224825637..27e39e6514 100644
@@ -191,20 +191,20 @@ void NORETURN die_conclude_merge(void)
 void detach_advice(const char *new_name)
 {
      const char *fmt =
-     _("Note: checking out '%s'.\n"
+     _("Note: switching to '%s'.\n"
      "\n"
      "You are in 'detached HEAD' state. You can look around, make experimental\n"
      "changes and commit them, and you can discard any commits you make in this\n"
-     "state without impacting any branches by performing another checkout.\n"
+     "state without impacting any branches by switching back to a branch.\n"
      "\n"
      "If you want to create a new branch to retain commits you create, you may\n"
-     "do so (now or later) by using -b with the checkout command again. Example:\n"
+     "do so (now or later) by using -c with the switch command. Example:\n"
      "\n"
Quoted 8 lines

advice.c void NORETURN die_conclude_merge(void) · line 205

Quoted 4 lines
advice.c +1 -1
-     "  git checkout -b <new-branch-name>\n"
+     "  git switch -c <new-branch-name>\n"
      "\n"
      "Or undo this checkout with:\n"

With the start of the message being "switching to ..." this part could probably be also updated to something like "Or undo this switch with" or "Or undo this switch or checkout with".

Maybe the neutral "operation"? E.g. "Or undo this operation with:"

Quoted 8 lines
Quoted 7 lines
advice.c +1 -1
      "\n"
-     "  git checkout -\n"
+     "  git switch -\n"
      "\n"
      "Turn off this advice by setting config variable advice.detachedHead to false\n\n");
 
Signature · 1 line
Duy
#245 lore raw

Re: [PATCH v5 00/26] Add new command 'switch'

In reply to Nguyễn Thái Ngọc Duy
Quoted 6 lines · Nguyễn Thái Ngọc Duy

This adds a new command 'git-switch' as the half-replacement for 'git-checkout'. Jump to 12/26 as the starting point. The other half is git-restore, which is dealt with separately.

The diff delta is shrinking nicely. The two main changes are

I only looked over the range-diff this time, but this round looks good to me. Thanks for working on this.

#246 lore raw

Re: [PATCH v5 00/26] Add new command 'switch'

In reply to Nguyễn Thái Ngọc Duy
Quoted 10 lines · Nguyễn Thái Ngọc Duy

This adds a new command 'git-switch' as the half-replacement for 'git-checkout'. Jump to 12/26 as the starting point. The other half is git-restore, which is dealt with separately.

The diff delta is shrinking nicely. The two main changes are

- '--orphan <new-branch> <initial-tree>' is no longer accepted
- --force implies --ignore-in-progress

The rest is the usual typo and bug fixes.

And droppage of sign-off?

Other than that, the changes relative to the previous round looked all reasonable.

author
#247 lore raw

Re: [PATCH v5 00/26] Add new command 'switch'

Quoted 7 lines · Junio C Hamano
Quoted 4 lines · Nguyễn Thái Ngọc Duy

This adds a new command 'git-switch' as the half-replacement for 'git-checkout'. Jump to 12/26 as the starting point. The other half is git-restore, which is dealt with separately.

Quoted 8 lines
Quoted 6 lines

The diff delta is shrinking nicely. The two main changes are

- '--orphan <new-branch> <initial-tree>' is no longer accepted
- --force implies --ignore-in-progress

The rest is the usual typo and bug fixes.

And droppage of sign-off?

I think the amount of options I have to give to format-patch starts to overwhelm me. Can you forge my sign-off? I'll resend otherwise.

Signature · 1 line
Duy
#248 lore raw

v6 cover Add new command 'switch'

In reply to Nguyễn Thái Ngọc Duy

This adds a new command 'git-switch' as the half-replacement for 'git-checkout'. Jump to 13/27 as the starting point. The other half is git-restore, which is dealt with separately.

The sixth time must be the charm, because the seventh time may be the curse!

The last big change since v5 is from the discussion about remove_branch_state() and its relation with --ignore-in-progress. By popular demand, --ignore-in-progress is gone. The discussion is linked in 23/27, which is also improved to suggest a way out.

That discussion also leads to a new patch, 07/27, which improves 'git checkout' and tells the user when merge/revert/cherry-pick is canceled.

The rest is just minor updates here and there. And I made sure the sign-off is back this time :D

Nguyễn Thái Ngọc Duy (27):
git-checkout.txt: spell out --no-option git-checkout.txt: fix one syntax line
doc: document --overwrite-ignore
git-checkout.txt: fix monospace typeset
t: rename t2014-switch.sh to t2014-checkout-switch.sh
checkout: advice how to get out of detached HEAD mode
checkout: inform the user when removing branch state
checkout: keep most #include sorted
checkout: factor out some code in parse_branchname_arg()
checkout: make "opts" in cmd_checkout() a pointer
checkout: move 'confict_style' and 'dwim_..' to checkout_opts
checkout: split options[] array in three pieces
checkout: split part of it to new command 'switch'
switch: better names for -b and -B
switch: add --discard-changes
switch: remove -l
switch: stop accepting pathspec
switch: reject "do nothing" case
switch: only allow explicit detached HEAD
switch: add short option for --detach
switch: implicit dwim, use --no-guess to disable it
switch: no worktree status unless real branch switch happens
switch: reject if some operation is in progress
switch: make --orphan switch to an empty tree
t: add tests for switch
completion: support switch
doc: promote "git switch"

 .gitignore                                    |   1 +
 Documentation/config/advice.txt               |  13 +-
 Documentation/config/branch.txt               |   4 +-
 Documentation/config/checkout.txt             |  17 +-
 Documentation/config/diff.txt                 |   3 +-
 Documentation/git-branch.txt                  |  12 +-
 Documentation/git-check-ref-format.txt        |   3 +-
 Documentation/git-checkout.txt                | 221 ++++---
 Documentation/git-format-patch.txt            |   2 +-
 Documentation/git-merge-base.txt              |   2 +-
 Documentation/git-merge.txt                   |   5 +
 Documentation/git-rebase.txt                  |   2 +-
 Documentation/git-remote.txt                  |   2 +-
 Documentation/git-rerere.txt                  |  10 +-
 Documentation/git-reset.txt                   |  20 +-
 Documentation/git-stash.txt                   |   9 +-
 Documentation/git-switch.txt (new)            | 271 ++++++++
 Documentation/gitattributes.txt               |   3 +-
 Documentation/gitcore-tutorial.txt            |  19 +-
 Documentation/giteveryday.txt                 |  24 +-
 Documentation/githooks.txt                    |   8 +-
 Documentation/gittutorial.txt                 |   4 +-
 Documentation/gitworkflows.txt                |   3 +-
 Documentation/revisions.txt                   |   2 +-
 Documentation/user-manual.txt                 |  56 +-
 Makefile                                      |   1 +
 advice.c                                      |  17 +-
 branch.c                                      |  11 +-
 branch.h                                      |   2 +-
 builtin.h                                     |   1 +
 builtin/am.c                                  |   2 +-
 builtin/checkout.c                            | 619 ++++++++++--------
 builtin/rebase.c                              |   4 +-
 builtin/reset.c                               |   2 +-
 builtin/revert.c                              |   2 +-
 command-list.txt                              |   1 +
 contrib/completion/git-completion.bash        |  37 +-
 git.c                                         |   1 +
 parse-options-cb.c                            |  17 +
 parse-options.h                               |   1 +
 sha1-name.c                                   |   2 +-
 t/t1090-sparse-checkout-scope.sh              |  14 -
 ...014-switch.sh => t2014-checkout-switch.sh} |   0
 t/t2020-checkout-detach.sh                    |  28 +-
 t/t2060-switch.sh (new +x)                    |  96 +++
 unpack-trees.c                                |   2 +-
 46 files changed, 1071 insertions(+), 505 deletions(-)
 create mode 100644 Documentation/git-switch.txt
 rename t/{t2014-switch.sh => t2014-checkout-switch.sh} (100%)
 create mode 100755 t/t2060-switch.sh

Range-diff dựa trên v5:

 -:  ---------- >  1:  ddcc6f7684 checkout: inform the user when removing branch state
 1:  0bb2aefb85 =  2:  1d91c3ed35 checkout: keep most #include sorted
 2:  ace82aa26f =  3:  1705d50f4e checkout: factor out some code in parse_branchname_arg()
 3:  6e13efcba8 =  4:  dc07f2fd92 checkout: make "opts" in cmd_checkout() a pointer
 4:  f61a042eb8 =  5:  a8292a7173 checkout: move 'confict_style' and 'dwim_..' to checkout_opts
 5:  972cebc568 =  6:  89b7d4baea checkout: split options[] array in three pieces
 6:  970c727b24 !  7:  0862b680c3 checkout: split part of it to new command 'switch'
    @@ -243,18 +243,14 @@
     +
     +-f::
     +--force::
    -+	An alias for `--discard-changes` and `--ignore-in-progress`.
    ++	An alias for `--discard-changes`.
     +
     +--discard-changes::
     +	Proceed even if the index or the working tree differs from
     +	`HEAD`. Both the index and working tree are restored to match
    -+	the switching target. This is used to throw away local
    -+	changes.
    -+
    -+--ignore-in-progress::
    -+	`git switch` by default refuses when some operation is in
    -+	progress (e.g. "git rebase", "git am" ...). This option
    -+	overrides this safety check and allows switching.
    ++	the switching target. If `--recurse-submodules` is specified,
    ++	submodule content is also restored to match the switching
    ++	target. This is used to throw away local changes.
     +
     +-m::
     +--merge::
    @@ -321,13 +317,12 @@
     +
     +--recurse-submodules::
     +--no-recurse-submodules::
    -+	Using `--recurse-submodules` will update the content of all initialized
    -+	submodules according to the commit recorded in the superproject. If
    -+	local modifications in a submodule would be overwritten the checkout
    -+	will fail unless `-f` is used. If nothing (or `--no-recurse-submodules`)
    -+	is used, the work trees of submodules will not be updated.
    -+	Just like linkgit:git-submodule[1], this will detach `HEAD` of the
    -+	submodule.
    ++	Using `--recurse-submodules` will update the content of all
    ++	initialized submodules according to the commit recorded in the
    ++	superproject. If nothing (or `--no-recurse-submodules`) is
    ++	used, the work trees of submodules will not be updated. Just
    ++	like linkgit:git-submodule[1], this will detach `HEAD` of the
    ++	submodules.
     +
     +EXAMPLES
     +--------
    @@ -385,7 +380,7 @@
     +name:
     +
     +------------
    -+$ git switch -g new-topic
    ++$ git switch new-topic
     +Branch 'new-topic' set up to track remote branch 'new-topic' from 'origin'
     +Switched to a new branch 'new-topic'
     +------------
 7:  676f5df0fd =  8:  52da28d384 switch: better names for -b and -B
 8:  4e37c0659e !  9:  471b0c47ac switch: add --discard-changes

@@ -7,6 +7,10 @@
--discard-changes. But it's meant to be an alias for potentially more force options in the future.

+ Side note. It's not obvious from the patch but --discard-changes also
+ affects submodules if --recurse-submodules is used. The knob to force
+ updating submodules is hidden behind unpack-trees.c
+
diff --git a/builtin/checkout.c b/builtin/checkout.c --- a/builtin/checkout.c
+++ b/builtin/checkout.c

 9:  a57208d137 = 10:  bf6d12272c switch: remove -l
10:  3de6f95bf2 = 11:  bec2fb8884 switch: stop accepting pathspec
11:  ad225517cd = 12:  ed0dfccf89 switch: reject "do nothing" case
12:  583cfd5cc4 = 13:  d17eabfb01 switch: only allow explicit detached HEAD
13:  1c5aee658d = 14:  59623757ee switch: add short option for --detach
14:  d942ac52e2 = 15:  04dca884f8 switch: implicit dwim, use --no-guess to disable it
15:  37eb152c0d = 16:  c8ff76def6 switch: no worktree status unless real branch switch happens
16:  50d6768afd ! 17:  34727e7d46 switch: reject if some operation is in progress
    @@ -7,13 +7,20 @@
         forget that you're in the middle of something. By the time you realize,
         you may have done a ton of work and it gets harder to go back.
     
    -    The new option --ignore-in-progress is added to override this check.
    -    However it's probably just safer to create a separate worktree for
    -    that separate thing you want to work on and leave this worktree
    -    alone (unless of course creating or preparing worktrees are not cheap).
    +    A new option --ignore-in-progress was considered but dropped because it
    +    was not exactly clear what should happen. Sometimes you can switch away
    +    and get back safely and resume the operation. Sometimes not. And the
    +    git-checkout behavior is automatically clear merge/revert/cherry-pick,
    +    which makes it a bit even more confusing [1].
     
    -    --force is updated to also imply --ignore-in-progress because it is
    -    supposed to be the "just do your things and don't bother me" option.
    +    We may revisit and add this option in the future. But for now play it
    +    safe and not allow it (you can't even skip this check with --force). The
    +    user is suggested to cancel the operation by themselves (and hopefully
    +    they do consider the consequences, not blindly type the command), or to
    +    create a separate worktree instead of switching. The third option is
    +    the good old "git checkout", but it's not mentioned.
    +
    +    [1] CACsJy8Axa5WsLSjiscjnxVK6jQHkfs-gH959=YtUvQkWriAk5w@mail.gmail.com
     
      diff --git a/builtin/checkout.c b/builtin/checkout.c
      --- a/builtin/checkout.c
    @@ -35,44 +42,55 @@
      	const char *new_branch;
      	const char *new_branch_force;
     @@
    - 	    !new_branch_info->path)
    - 		die_expecting_a_branch(new_branch_info);
    + 	die(_("a branch is expected, got '%s'"), branch_info->name);
    + }
      
    -+	if (!opts->can_switch_when_in_progress) {
    -+		struct wt_status_state state;
    ++static void die_if_some_operation_in_progress(void)
    ++{
    ++	struct wt_status_state state;
     +
    -+		memset(&state, 0, sizeof(state));
    -+		wt_status_get_state(the_repository, &state, 0);
    ++	memset(&state, 0, sizeof(state));
    ++	wt_status_get_state(the_repository, &state, 0);
     +
    -+		if (state.merge_in_progress)
    -+			die(_("cannot switch branch while merging"));
    -+		if (state.am_in_progress)
    -+			die(_("cannot switch branch in the middle of an am session"));
    -+		if (state.rebase_interactive_in_progress || state.rebase_in_progress)
    -+			die(_("cannot switch branch while rebasing"));
    -+		if (state.cherry_pick_in_progress)
    -+			die(_("cannot switch branch while cherry-picking"));
    -+		if (state.revert_in_progress)
    -+			die(_("cannot switch branch while reverting"));
    -+		if (state.bisect_in_progress)
    -+			die(_("cannot switch branch while bisecting"));
    -+	}
    ++	if (state.merge_in_progress)
    ++		die(_("cannot switch branch while merging\n"
    ++		      "Consider \"git merge --quit\" "
    ++		      "or \"git worktree add\"."));
    ++	if (state.am_in_progress)
    ++		die(_("cannot switch branch in the middle of an am session\n"
    ++		      "Consider \"git am --quit\" "
    ++		      "or \"git worktree add\"."));
    ++	if (state.rebase_interactive_in_progress || state.rebase_in_progress)
    ++		die(_("cannot switch branch while rebasing\n"
    ++		      "Consider \"git rebase --quit\" "
    ++		      "or \"git worktree add\"."));
    ++	if (state.cherry_pick_in_progress)
    ++		die(_("cannot switch branch while cherry-picking\n"
    ++		      "Consider \"git cherry-pick --quit\" "
    ++		      "or \"git worktree add\"."));
    ++	if (state.revert_in_progress)
    ++		die(_("cannot switch branch while reverting\n"
    ++		      "Consider \"git revert --quit\" "
    ++		      "or \"git worktree add\"."));
    ++	if (state.bisect_in_progress)
    ++		die(_("cannot switch branch while bisecting\n"
    ++		      "Consider \"git bisect reset HEAD\" "
    ++		      "or \"git worktree add\"."));
    ++}
    ++
    + static int checkout_branch(struct checkout_opts *opts,
    + 			   struct branch_info *new_branch_info)
    + {
    +@@
    + 	    !new_branch_info->path)
    + 		die_expecting_a_branch(new_branch_info);
    + 
    ++	if (!opts->can_switch_when_in_progress)
    ++		die_if_some_operation_in_progress();
     +
      	if (new_branch_info->path && !opts->force_detach && !opts->new_branch &&
      	    !opts->ignore_other_worktrees) {
      		int flag;
    -@@
    - 		opts->merge = 1; /* implied */
    - 		git_xmerge_config("merge.conflictstyle", opts->conflict_style, NULL);
    - 	}
    --	if (opts->force)
    -+	if (opts->force) {
    - 		opts->discard_changes = 1;
    -+		opts->can_switch_when_in_progress = 1;
    -+	}
    - 
    - 	if ((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) > 1)
    - 		die(_("-b, -B and --orphan are mutually exclusive"));
     @@
      	opts.only_merge_on_switching_branches = 0;
      	opts.accept_pathspec = 1;
    @@ -81,15 +99,6 @@
      
      	options = parse_options_dup(checkout_options);
      	options = add_common_options(&opts, options);
    -@@
    - 			 N_("second guess 'git switch <no-such-branch>'")),
    - 		OPT_BOOL(0, "discard-changes", &opts.discard_changes,
    - 			 N_("throw away local modifications")),
    -+		OPT_BOOL(0, "ignore-in-progress", &opts.can_switch_when_in_progress,
    -+			 N_("allow to switch branch when some operation is still in progress")),
    - 		OPT_END()
    - 	};
    - 	int ret;
     @@
      	opts.switch_branch_doing_nothing_is_ok = 0;
      	opts.only_merge_on_switching_branches = 1;
17:  af8bb710c8 = 18:  6e1986f0d4 switch: make --orphan switch to an empty tree
18:  4a293a3d53 ! 19:  414a1783fb t: add tests for switch
    @@ -95,13 +95,11 @@
     +	test_cmp expected actual
     +'
     +
    -+test_expect_success 'switching when something is in progress' '
    ++test_expect_success 'not switching when something is in progress' '
     +	test_when_finished rm -f .git/MERGE_HEAD &&
     +	# fake a merge-in-progress
     +	cp .git/HEAD .git/MERGE_HEAD &&
    -+	test_must_fail git switch -d @^ &&
    -+	git switch --ignore-in-progress -d @^ &&
    -+	git switch -
    ++	test_must_fail git switch -d @^
     +'
     +
     +test_done
19:  b10290b378 = 20:  ac6f5fa9f9 completion: support switch
20:  67c5175e5f ! 21:  5a921aa0a1 doc: promote "git switch"

@@ -9,6 +9,9 @@
For these reasons, promote it everywhere possible. This includes documentation, suggestions/advice from other commands...

+ The "Checking out files" progress line in unpack-trees.c is also updated
+ to "Updating files" to be neutral to both git-checkout and git-switch.
+
diff --git a/Documentation/git-branch.txt b/Documentation/git-branch.txt --- a/Documentation/git-branch.txt
+++ b/Documentation/git-branch.txt
@@ -662,7 +665,8 @@
- " git checkout -b <new-branch-name>\n"
+ " git switch -c <new-branch-name>\n"
"\n"
- "Or undo this checkout with:\n"
+- "Or undo this checkout with:\n"
++ "Or undo this operation with:\n"
"\n"
- " git checkout -\n"
+ " git switch -\n"
@@ -705,7 +709,8 @@
- git checkout -b <new-branch-name>
+ git switch -c <new-branch-name>

- Or undo this checkout with:
+- Or undo this checkout with:
++ Or undo this operation with:

- git checkout -
+ git switch -
@@ -731,10 +736,24 @@
- git checkout -b <new-branch-name>
+ git switch -c <new-branch-name>

- Or undo this checkout with:
+- Or undo this checkout with:
++ Or undo this operation with:

- git checkout -
+ git switch -

Turn off this advice by setting config variable advice.detachedHead to false

+
+ diff --git a/unpack-trees.c b/unpack-trees.c
+ --- a/unpack-trees.c
+ +++ b/unpack-trees.c
+@@
+ total++;
+ }
+
+- return start_delayed_progress(_("Checking out files"), total);
++ return start_delayed_progress(_("Updating files"), total);
+ }
+
+ static void setup_collided_checkout_detection(struct checkout *state,

Signature · 1 line
2.21.0.479.g47ac719cd3
#249 lore raw

PATCH v6 1/27 git-checkout.txt: spell out --no-option

It's easier to search for and also less cryptic.

---
 Documentation/git-checkout.txt | 11 +++++++----
 1 file changed, 7 insertions(+), 4 deletions(-)
Documentation/git-checkout.txt +7 -4
index f179b43732..99c8c0dc0f 100644
@@ -118,7 +118,8 @@ OPTIONS
 --quiet::
 	Quiet, suppress feedback messages.
 
---[no-]progress::
+--progress::
+--no-progress::
 	Progress status is reported on the standard error stream
 	by default when it is attached to a terminal, unless `--quiet`
 	is specified. This flag enables progress reporting even if not
@@ -262,7 +263,7 @@ edits from your current working tree. See the ``Interactive Mode''
 section of linkgit:git-add[1] to learn how to operate the `--patch` mode.
 +
 Note that this option uses the no overlay mode by default (see also
-`--[no-]overlay`), and currently doesn't support overlay mode.
+`--overlay`), and currently doesn't support overlay mode.
 
 --ignore-other-worktrees::
 	`git checkout` refuses when the wanted ref is already checked
@@ -270,7 +271,8 @@ Note that this option uses the no overlay mode by default (see also
 	out anyway. In other words, the ref can be held by more than one
 	worktree.
 
---[no-]recurse-submodules::
+--recurse-submodules::
+--no-recurse-submodules::
 	Using --recurse-submodules will update the content of all initialized
 	submodules according to the commit recorded in the superproject. If
 	local modifications in a submodule would be overwritten the checkout
@@ -283,7 +285,8 @@ Note that this option uses the no overlay mode by default (see also
 	Do not attempt to create a branch if a remote tracking branch
 	of the same name exists.
 
---[no-]overlay::
+--overlay::
+--no-overlay::
 	In the default overlay mode, `git checkout` never
 	removes files from the index or the working tree.  When
 	specifying `--no-overlay`, files that appear in the index and
Signature · 1 line
2.21.0.479.g47ac719cd3
#250 lore raw

PATCH v6 2/27 git-checkout.txt: fix one syntax line

In reply to Nguyễn Thái Ngọc Duy

<branch> can be omitted in this syntax, and it's actually documented a few paragraphs down:

You could omit <branch>, in which case the command degenerates to "check out the current branch", which is a glorified no-op with rather expensive side-effects to show only the tracking information, if exists, for the current branch.

---
 Documentation/git-checkout.txt | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
Documentation/git-checkout.txt +1 -1
index 99c8c0dc0f..28817cfa41 100644
@@ -23,7 +23,7 @@ or the specified tree.  If no paths are given, 'git checkout' will
 also update `HEAD` to set the specified branch as the current
 branch.
 
-'git checkout' <branch>::
+'git checkout' [<branch>]::
 	To prepare for working on <branch>, switch to it by updating
 	the index and the files in the working tree, and by pointing
 	HEAD at the branch. Local modifications to the files in the
Signature · 1 line
2.21.0.479.g47ac719cd3
#251 lore raw

PATCH v6 3/27 doc: document --overwrite-ignore

In reply to Nguyễn Thái Ngọc Duy

I added this option in git-checkout and git-merge in c1d7036b6b (checkout,merge: disallow overwriting ignored files with --no-overwrite-ignore - 2011-11-27) but did not remember to update documentation. This completes that commit.

---
 Documentation/git-checkout.txt | 6 ++++++
 Documentation/git-merge.txt    | 5 +++++
 2 files changed, 11 insertions(+)
Documentation/git-checkout.txt +6 -0
index 28817cfa41..5280d1f9ed 100644
@@ -271,6 +271,12 @@ Note that this option uses the no overlay mode by default (see also
 	out anyway. In other words, the ref can be held by more than one
 	worktree.
 
+--overwrite-ignore::
+--no-overwrite-ignore::
+	Silently overwrite ignored files when switching branches. This
+	is the default behavior. Use `--no-overwrite-ignore` to abort
+	the operation when the new branch contains ignored files.
+
 --recurse-submodules::
 --no-recurse-submodules::
 	Using --recurse-submodules will update the content of all initialized
Documentation/git-merge.txt +5 -0
index 4cc86469f3..6a9163d8fe 100644
@@ -87,6 +87,11 @@ will be appended to the specified message.
 	Allow the rerere mechanism to update the index with the
 	result of auto-conflict resolution if possible.
 
+--overwrite-ignore::
+--no-overwrite-ignore::
+	Silently overwrite ignored files from the merge result. This
+	is the default behavior. Use `--no-overwrite-ignore` to abort.
+
 --abort::
 	Abort the current conflict resolution process, and
 	try to reconstruct the pre-merge state.
Signature · 1 line
2.21.0.479.g47ac719cd3
#252 lore raw

PATCH v6 4/27 git-checkout.txt: fix monospace typeset

In reply to Nguyễn Thái Ngọc Duy

Add backticks where we have none, replace single quotes with backticks and replace double-quotes. Drop double-quotes from nested constructions such as "@{-1}".

---
 Documentation/git-checkout.txt | 162 ++++++++++++++++-----------------
 1 file changed, 81 insertions(+), 81 deletions(-)
Documentation/git-checkout.txt +81 -81
index 5280d1f9ed..bf90966c95 100644
@@ -24,14 +24,14 @@ also update `HEAD` to set the specified branch as the current
 branch.
 
 'git checkout' [<branch>]::
-	To prepare for working on <branch>, switch to it by updating
+	To prepare for working on `<branch>`, switch to it by updating
 	the index and the files in the working tree, and by pointing
-	HEAD at the branch. Local modifications to the files in the
+	`HEAD` at the branch. Local modifications to the files in the
 	working tree are kept, so that they can be committed to the
-	<branch>.
+	`<branch>`.
 +
-If <branch> is not found but there does exist a tracking branch in
-exactly one remote (call it <remote>) with a matching name, treat as
+If `<branch>` is not found but there does exist a tracking branch in
+exactly one remote (call it `<remote>`) with a matching name, treat as
 equivalent to
 +
 ------------
@@ -47,7 +47,7 @@ branches from there if `<branch>` is ambiguous but exists on the
 'origin' remote. See also `checkout.defaultRemote` in
 linkgit:git-config[1].
 +
-You could omit <branch>, in which case the command degenerates to
+You could omit `<branch>`, in which case the command degenerates to
 "check out the current branch", which is a glorified no-op with
 rather expensive side-effects to show only the tracking information,
 if exists, for the current branch.
@@ -61,7 +61,7 @@ if exists, for the current branch.
 	`--track` without `-b` implies branch creation; see the
 	description of `--track` below.
 +
-If `-B` is given, <new_branch> is created if it doesn't exist; otherwise, it
+If `-B` is given, `<new_branch>` is created if it doesn't exist; otherwise, it
 is reset. This is the transactional equivalent of
 +
 ------------
@@ -75,25 +75,25 @@ successful.
 'git checkout' --detach [<branch>]::
 'git checkout' [--detach] <commit>::
 
-	Prepare to work on top of <commit>, by detaching HEAD at it
+	Prepare to work on top of `<commit>`, by detaching `HEAD` at it
 	(see "DETACHED HEAD" section), and updating the index and the
 	files in the working tree.  Local modifications to the files
 	in the working tree are kept, so that the resulting working
 	tree will be the state recorded in the commit plus the local
 	modifications.
 +
-When the <commit> argument is a branch name, the `--detach` option can
-be used to detach HEAD at the tip of the branch (`git checkout
-<branch>` would check out that branch without detaching HEAD).
+When the `<commit>` argument is a branch name, the `--detach` option can
+be used to detach `HEAD` at the tip of the branch (`git checkout
+<branch>` would check out that branch without detaching `HEAD`).
 +
-Omitting <branch> detaches HEAD at the tip of the current branch.
+Omitting `<branch>` detaches `HEAD` at the tip of the current branch.
 
 'git checkout' [<tree-ish>] [--] <pathspec>...::
 
 	Overwrite paths in the working tree by replacing with the
-	contents in the index or in the <tree-ish> (most often a
-	commit).  When a <tree-ish> is given, the paths that
-	match the <pathspec> are updated both in the index and in
+	contents in the index or in the `<tree-ish>` (most often a
+	commit).  When a `<tree-ish>` is given, the paths that
+	match the `<pathspec>` are updated both in the index and in
 	the working tree.
 +
 The index may contain unmerged entries because of a previous failed merge.
@@ -128,7 +128,7 @@ OPTIONS
 -f::
 --force::
 	When switching branches, proceed even if the index or the
-	working tree differs from HEAD.  This is used to throw away
+	working tree differs from `HEAD`.  This is used to throw away
 	local changes.
 +
 When checking out paths from the index, do not fail upon unmerged
@@ -155,12 +155,12 @@ on your side branch as `theirs` (i.e. "one contributor's work on top
 of it").
 
 -b <new_branch>::
-	Create a new branch named <new_branch> and start it at
-	<start_point>; see linkgit:git-branch[1] for details.
+	Create a new branch named `<new_branch>` and start it at
+	`<start_point>`; see linkgit:git-branch[1] for details.
 
 -B <new_branch>::
-	Creates the branch <new_branch> and start it at <start_point>;
-	if it already exists, then reset it to <start_point>. This is
+	Creates the branch `<new_branch>` and start it at `<start_point>`;
+	if it already exists, then reset it to `<start_point>`. This is
 	equivalent to running "git branch" with "-f"; see
 	linkgit:git-branch[1] for details.
 
@@ -173,15 +173,15 @@ If no `-b` option is given, the name of the new branch will be
 derived from the remote-tracking branch, by looking at the local part of
 the refspec configured for the corresponding remote, and then stripping
 the initial part up to the "*".
-This would tell us to use "hack" as the local branch when branching
-off of "origin/hack" (or "remotes/origin/hack", or even
-"refs/remotes/origin/hack").  If the given name has no slash, or the above
+This would tell us to use `hack` as the local branch when branching
+off of `origin/hack` (or `remotes/origin/hack`, or even
+`refs/remotes/origin/hack`).  If the given name has no slash, or the above
 guessing results in an empty name, the guessing is aborted.  You can
 explicitly give a name with `-b` in such a case.
 
 --no-track::
 	Do not set up "upstream" configuration, even if the
-	branch.autoSetupMerge configuration variable is true.
+	`branch.autoSetupMerge` configuration variable is true.
 
 -l::
 	Create the new branch's reflog; see linkgit:git-branch[1] for
@@ -190,21 +190,21 @@ explicitly give a name with `-b` in such a case.
 --detach::
 	Rather than checking out a branch to work on it, check out a
 	commit for inspection and discardable experiments.
-	This is the default behavior of "git checkout <commit>" when
-	<commit> is not a branch name.  See the "DETACHED HEAD" section
+	This is the default behavior of `git checkout <commit>` when
+	`<commit>` is not a branch name.  See the "DETACHED HEAD" section
 	below for details.
 
 --orphan <new_branch>::
-	Create a new 'orphan' branch, named <new_branch>, started from
-	<start_point> and switch to it.  The first commit made on this
+	Create a new 'orphan' branch, named `<new_branch>`, started from
+	`<start_point>` and switch to it.  The first commit made on this
 	new branch will have no parents and it will be the root of a new
 	history totally disconnected from all the other branches and
 	commits.
 +
 The index and the working tree are adjusted as if you had previously run
-"git checkout <start_point>".  This allows you to start a new history
-that records a set of paths similar to <start_point> by easily running
-"git commit -a" to make the root commit.
+`git checkout <start_point>`.  This allows you to start a new history
+that records a set of paths similar to `<start_point>` by easily running
+`git commit -a` to make the root commit.
 +
 This can be useful when you want to publish the tree from a commit
 without exposing its full history. You might want to do this to publish
@@ -213,17 +213,17 @@ whose full history contains proprietary or otherwise encumbered bits of
 code.
 +
 If you want to start a disconnected history that records a set of paths
-that is totally different from the one of <start_point>, then you should
+that is totally different from the one of `<start_point>`, then you should
 clear the index and the working tree right after creating the orphan
-branch by running "git rm -rf ." from the top level of the working tree.
+branch by running `git rm -rf .` from the top level of the working tree.
 Afterwards you will be ready to prepare your new files, repopulating the
 working tree, by copying them from elsewhere, extracting a tarball, etc.
 
 --ignore-skip-worktree-bits::
 	In sparse checkout mode, `git checkout -- <paths>` would
-	update only entries matched by <paths> and sparse patterns
-	in $GIT_DIR/info/sparse-checkout. This option ignores
-	the sparse patterns and adds back any files in <paths>.
+	update only entries matched by `<paths>` and sparse patterns
+	in `$GIT_DIR/info/sparse-checkout`. This option ignores
+	the sparse patterns and adds back any files in `<paths>`.
 
 -m::
 --merge::
@@ -245,18 +245,18 @@ When checking out paths from the index, this option lets you recreate
 the conflicted merge in the specified paths.
 
 --conflict=<style>::
-	The same as --merge option above, but changes the way the
+	The same as `--merge` option above, but changes the way the
 	conflicting hunks are presented, overriding the
-	merge.conflictStyle configuration variable.  Possible values are
+	`merge.conflictStyle` configuration variable.  Possible values are
 	"merge" (default) and "diff3" (in addition to what is shown by
 	"merge" style, shows the original contents).
 
 -p::
 --patch::
 	Interactively select hunks in the difference between the
-	<tree-ish> (or the index, if unspecified) and the working
+	`<tree-ish>` (or the index, if unspecified) and the working
 	tree.  The chosen hunks are then applied in reverse to the
-	working tree (and if a <tree-ish> was specified, the index).
+	working tree (and if a `<tree-ish>` was specified, the index).
 +
 This means that you can use `git checkout -p` to selectively discard
 edits from your current working tree. See the ``Interactive Mode''
@@ -279,13 +279,13 @@ Note that this option uses the no overlay mode by default (see also
 
 --recurse-submodules::
 --no-recurse-submodules::
-	Using --recurse-submodules will update the content of all initialized
+	Using `--recurse-submodules` will update the content of all initialized
 	submodules according to the commit recorded in the superproject. If
 	local modifications in a submodule would be overwritten the checkout
-	will fail unless `-f` is used. If nothing (or --no-recurse-submodules)
+	will fail unless `-f` is used. If nothing (or `--no-recurse-submodules`)
 	is used, the work trees of submodules will not be updated.
-	Just like linkgit:git-submodule[1], this will detach the
-	submodules HEAD.
+	Just like linkgit:git-submodule[1], this will detach `HEAD` of the
+	submodule.
 
 --no-guess::
 	Do not attempt to create a branch if a remote tracking branch
@@ -296,21 +296,21 @@ Note that this option uses the no overlay mode by default (see also
 	In the default overlay mode, `git checkout` never
 	removes files from the index or the working tree.  When
 	specifying `--no-overlay`, files that appear in the index and
-	working tree, but not in <tree-ish> are removed, to make them
-	match <tree-ish> exactly.
+	working tree, but not in `<tree-ish>` are removed, to make them
+	match `<tree-ish>` exactly.
 
 <branch>::
 	Branch to checkout; if it refers to a branch (i.e., a name that,
 	when prepended with "refs/heads/", is a valid ref), then that
 	branch is checked out. Otherwise, if it refers to a valid
-	commit, your HEAD becomes "detached" and you are no longer on
+	commit, your `HEAD` becomes "detached" and you are no longer on
 	any branch (see below for details).
 +
-You can use the `"@{-N}"` syntax to refer to the N-th last
+You can use the `@{-N}` syntax to refer to the N-th last
 branch/commit checked out using "git checkout" operation. You may
-also specify `-` which is synonymous to `"@{-1}"`.
+also specify `-` which is synonymous to `@{-1}`.
 +
-As a special case, you may use `"A...B"` as a shortcut for the
+As a special case, you may use `A...B` as a shortcut for the
 merge base of `A` and `B` if there is exactly one merge base. You can
 leave out at most one of `A` and `B`, in which case it defaults to `HEAD`.
 
@@ -319,7 +319,7 @@ leave out at most one of `A` and `B`, in which case it defaults to `HEAD`.
 
 <start_point>::
 	The name of a commit at which to start the new branch; see
-	linkgit:git-branch[1] for details. Defaults to HEAD.
+	linkgit:git-branch[1] for details. Defaults to `HEAD`.
 
 <tree-ish>::
 	Tree to checkout from (when paths are given). If not specified,
@@ -329,9 +329,9 @@ leave out at most one of `A` and `B`, in which case it defaults to `HEAD`.
 
 DETACHED HEAD
 -------------
-HEAD normally refers to a named branch (e.g. 'master'). Meanwhile, each
+`HEAD` normally refers to a named branch (e.g. `master`). Meanwhile, each
 branch refers to a specific commit. Let's look at a repo with three
-commits, one of them tagged, and with branch 'master' checked out:
+commits, one of them tagged, and with branch `master` checked out:
 
 ------------
            HEAD (refers to branch 'master')
@@ -344,10 +344,10 @@ a---b---c  branch 'master' (refers to commit 'c')
 ------------
 
 When a commit is created in this state, the branch is updated to refer to
-the new commit. Specifically, 'git commit' creates a new commit 'd', whose
-parent is commit 'c', and then updates branch 'master' to refer to new
-commit 'd'. HEAD still refers to branch 'master' and so indirectly now refers
-to commit 'd':
+the new commit. Specifically, 'git commit' creates a new commit `d`, whose
+parent is commit `c`, and then updates branch `master` to refer to new
+commit `d`. `HEAD` still refers to branch `master` and so indirectly now refers
+to commit `d`:
 
 ------------
 $ edit; git add; git commit
@@ -364,7 +364,7 @@ a---b---c---d  branch 'master' (refers to commit 'd')
 It is sometimes useful to be able to checkout a commit that is not at
 the tip of any named branch, or even to create a new commit that is not
 referenced by a named branch. Let's look at what happens when we
-checkout commit 'b' (here we show two ways this may be done):
+checkout commit `b` (here we show two ways this may be done):
 
 ------------
 $ git checkout v2.0  # or
@@ -379,9 +379,9 @@ a---b---c---d  branch 'master' (refers to commit 'd')
   tag 'v2.0' (refers to commit 'b')
 ------------
 
-Notice that regardless of which checkout command we use, HEAD now refers
-directly to commit 'b'. This is known as being in detached HEAD state.
-It means simply that HEAD refers to a specific commit, as opposed to
+Notice that regardless of which checkout command we use, `HEAD` now refers
+directly to commit `b`. This is known as being in detached `HEAD` state.
+It means simply that `HEAD` refers to a specific commit, as opposed to
 referring to a named branch. Let's see what happens when we create a commit:
 
 ------------
@@ -398,7 +398,7 @@ a---b---c---d  branch 'master' (refers to commit 'd')
   tag 'v2.0' (refers to commit 'b')
 ------------
 
-There is now a new commit 'e', but it is referenced only by HEAD. We can
+There is now a new commit `e`, but it is referenced only by `HEAD`. We can
 of course add yet another commit in this state:
 
 ------------
@@ -416,7 +416,7 @@ a---b---c---d  branch 'master' (refers to commit 'd')
 ------------
 
 In fact, we can perform all the normal Git operations. But, let's look
-at what happens when we then checkout master:
+at what happens when we then checkout `master`:
 
 ------------
 $ git checkout master
@@ -431,9 +431,9 @@ a---b---c---d  branch 'master' (refers to commit 'd')
 ------------
 
 It is important to realize that at this point nothing refers to commit
-'f'. Eventually commit 'f' (and by extension commit 'e') will be deleted
+`f`. Eventually commit `f` (and by extension commit `e`) will be deleted
 by the routine Git garbage collection process, unless we create a reference
-before that happens. If we have not yet moved away from commit 'f',
+before that happens. If we have not yet moved away from commit `f`,
 any of these will create a reference to it:
 
 ------------
@@ -442,19 +442,19 @@ $ git branch foo        <2>
 $ git tag foo           <3>
 ------------
 
-<1> creates a new branch 'foo', which refers to commit 'f', and then
-    updates HEAD to refer to branch 'foo'. In other words, we'll no longer
-    be in detached HEAD state after this command.
+<1> creates a new branch `foo`, which refers to commit `f`, and then
+    updates `HEAD` to refer to branch `foo`. In other words, we'll no longer
+    be in detached `HEAD` state after this command.
 
-<2> similarly creates a new branch 'foo', which refers to commit 'f',
-    but leaves HEAD detached.
+<2> similarly creates a new branch `foo`, which refers to commit `f`,
+    but leaves `HEAD` detached.
 
-<3> creates a new tag 'foo', which refers to commit 'f',
-    leaving HEAD detached.
+<3> creates a new tag `foo`, which refers to commit `f`,
+    leaving `HEAD` detached.
 
-If we have moved away from commit 'f', then we must first recover its object
+If we have moved away from commit `f`, then we must first recover its object
 name (typically by using git reflog), and then we can create a reference to
-it. For example, to see the last two commits to which HEAD referred, we
+it. For example, to see the last two commits to which `HEAD` referred, we
 can use either of these commands:
 
 ------------
@@ -465,12 +465,12 @@ $ git log -g -2 HEAD
 ARGUMENT DISAMBIGUATION
 -----------------------
 
-When there is only one argument given and it is not `--` (e.g. "git
-checkout abc"), and when the argument is both a valid `<tree-ish>`
-(e.g. a branch "abc" exists) and a valid `<pathspec>` (e.g. a file
+When there is only one argument given and it is not `--` (e.g. `git
+checkout abc`), and when the argument is both a valid `<tree-ish>`
+(e.g. a branch `abc` exists) and a valid `<pathspec>` (e.g. a file
 or a directory whose name is "abc" exists), Git would usually ask
 you to disambiguate.  Because checking out a branch is so common an
-operation, however, "git checkout abc" takes "abc" as a `<tree-ish>`
+operation, however, `git checkout abc` takes "abc" as a `<tree-ish>`
 in such a situation.  Use `git checkout -- <pathspec>` if you want
 to checkout these paths out of the index.
 
@@ -478,7 +478,7 @@ EXAMPLES
 --------
 
 . The following sequence checks out the `master` branch, reverts
-  the `Makefile` to two revisions back, deletes hello.c by
+  the `Makefile` to two revisions back, deletes `hello.c` by
   mistake, and gets it back from the index.
 +
 ------------
@@ -490,7 +490,7 @@ $ git checkout hello.c            <3>
 +
 <1> switch branch
 <2> take a file out of another commit
-<3> restore hello.c from the index
+<3> restore `hello.c` from the index
 +
 If you want to check out _all_ C source files out of the index,
 you can say
@@ -519,7 +519,7 @@ $ git checkout -- hello.c
 $ git checkout mytopic
 ------------
 +
-However, your "wrong" branch and correct "mytopic" branch may
+However, your "wrong" branch and correct `mytopic` branch may
 differ in files that you have modified locally, in which case
 the above checkout would fail like this:
 +
Signature · 1 line
2.21.0.479.g47ac719cd3
#253 lore raw

PATCH v6 5/27 t: rename t2014-switch.sh to t2014-checkout-switch.sh

In reply to Nguyễn Thái Ngọc Duy

The old name does not really say that this is about 'checkout -b'. See 49d833dc07 (Revert "checkout branch: prime cache-tree fully" - 2009-05-12) for more information

---
 t/{t2014-switch.sh => t2014-checkout-switch.sh} | 0
 1 file changed, 0 insertions(+), 0 deletions(-)
t/t2014-checkout-switch.sh renamed from t/t2014-switch.sh +0 -0
similarity index 100%
rename from t/t2014-switch.sh
rename to t/t2014-checkout-switch.sh
Signature · 1 line
2.21.0.479.g47ac719cd3
#254 lore raw

PATCH v6 6/27 checkout: advice how to get out of detached HEAD mode

In reply to Nguyễn Thái Ngọc Duy

Detached HEAD mode is considered dangerous and confusing for newcomers and we print a big block of warning how to move forward. But we should also suggest the user the way to get out of it if they get into detached HEAD by mistake.

While at there, I also suggest how to turn the advice off. This is another thing I find annoying with advices and should be dealt with in a more generic way. But that may require some refactoring in advice.c first.

---
 advice.c                   | 17 +++++++++++++----
 t/t2020-checkout-detach.sh | 12 ++++++++++++
 2 files changed, 25 insertions(+), 4 deletions(-)
advice.c +13 -4
index 567209aa79..b224825637 100644
@@ -191,13 +191,22 @@ void NORETURN die_conclude_merge(void)
 void detach_advice(const char *new_name)
 {
 	const char *fmt =
-	_("Note: checking out '%s'.\n\n"
+	_("Note: checking out '%s'.\n"
+	"\n"
 	"You are in 'detached HEAD' state. You can look around, make experimental\n"
 	"changes and commit them, and you can discard any commits you make in this\n"
-	"state without impacting any branches by performing another checkout.\n\n"
+	"state without impacting any branches by performing another checkout.\n"
+	"\n"
 	"If you want to create a new branch to retain commits you create, you may\n"
-	"do so (now or later) by using -b with the checkout command again. Example:\n\n"
-	"  git checkout -b <new-branch-name>\n\n");
+	"do so (now or later) by using -b with the checkout command again. Example:\n"
+	"\n"
+	"  git checkout -b <new-branch-name>\n"
+	"\n"
+	"Or undo this checkout with:\n"
+	"\n"
+	"  git checkout -\n"
+	"\n"
+	"Turn off this advice by setting config variable advice.detachedHead to false\n\n");
 
 	fprintf(stderr, fmt, new_name);
 }
t/t2020-checkout-detach.sh +12 -0
index 1fa670625c..743c7248a2 100755
@@ -206,6 +206,12 @@ test_expect_success 'describe_detached_head prints no SHA-1 ellipsis when not as
 
 	  git checkout -b <new-branch-name>
 
+	Or undo this checkout with:
+
+	  git checkout -
+
+	Turn off this advice by setting config variable advice.detachedHead to false
+
 	HEAD is now at \$commit three
 	EOF
 
@@ -282,6 +288,12 @@ test_expect_success 'describe_detached_head does print SHA-1 ellipsis when asked
 
 	  git checkout -b <new-branch-name>
 
+	Or undo this checkout with:
+
+	  git checkout -
+
+	Turn off this advice by setting config variable advice.detachedHead to false
+
 	HEAD is now at \$commit... three
 	EOF
 
Signature · 1 line
2.21.0.479.g47ac719cd3
#255 lore raw

PATCH v6 7/27 checkout: inform the user when removing branch state

In reply to Nguyễn Thái Ngọc Duy

After a successful switch, if a merge, cherry-pick or revert is ongoing, it is canceled. This behavior has been with us from the very early beginning, soon after git-merge was created but never actually documented [1]. It may be a good idea to be transparent and tell the user if some operation is canceled.

I consider this a better way of telling the user than just adding a sentence or two in git-checkout.txt, which will be mostly ignored anyway.

PS. Originally I wanted to print more details like

warning: cancelling an in-progress merge from <SHA-1>

which may allow some level of undo if the user wants to. But that seems a lot more work. Perhaps it can be improved later if people still want that.

[1] ... and I will try not to argue whether it is a sensible behavior. There is some more discussion here if people are interested:
CACsJy8Axa5WsLSjiscjnxVK6jQHkfs-gH959=YtUvQkWriAk5w@mail.gmail.com

---
 branch.c           | 11 +++++++----
 branch.h           |  2 +-
 builtin/am.c       |  2 +-
 builtin/checkout.c |  2 +-
 builtin/rebase.c   |  4 ++--
 builtin/reset.c    |  2 +-
 builtin/revert.c   |  2 +-
 7 files changed, 14 insertions(+), 11 deletions(-)
branch.c +7 -4
index 28b81a7e02..8dd5bb9f1c 100644
@@ -337,11 +337,14 @@ void create_branch(struct repository *r,
 	free(real_ref);
 }
 
-void remove_branch_state(struct repository *r)
+void remove_branch_state(struct repository *r, int verbose)
 {
-	unlink(git_path_cherry_pick_head(r));
-	unlink(git_path_revert_head(r));
-	unlink(git_path_merge_head(r));
+	if (!unlink(git_path_cherry_pick_head(r)) && verbose)
+		warning(_("cancelling a cherry picking in progress"));
+	if (!unlink(git_path_revert_head(r)) && verbose)
+		warning(_("cancelling a revert in progress"));
+	if (!unlink(git_path_merge_head(r)) && verbose)
+		warning(_("cancelling a merge in progress"));
 	unlink(git_path_merge_rr(r));
 	unlink(git_path_merge_msg(r));
 	unlink(git_path_merge_mode(r));
branch.h +1 -1
index 29c1afa4d0..aed045901e 100644
@@ -64,7 +64,7 @@ extern int validate_new_branchname(const char *name, struct strbuf *ref, int for
  * Remove information about the state of working on the current
  * branch. (E.g., MERGE_HEAD)
  */
-void remove_branch_state(struct repository *r);
+void remove_branch_state(struct repository *r, int verbose);
 
 /*
  * Configure local branch "local" as downstream to branch "remote"
builtin/am.c +1 -1
index 4fb107a9d1..99b66508fd 100644
@@ -1957,7 +1957,7 @@ static int clean_index(const struct object_id *head, const struct object_id *rem
 	if (merge_tree(remote_tree))
 		return -1;
 
-	remove_branch_state(the_repository);
+	remove_branch_state(the_repository, 0);
 
 	return 0;
 }
builtin/checkout.c +1 -1
index 0e6037b296..f66bd2f56d 100644
@@ -899,7 +899,7 @@ static void update_refs_for_switch(const struct checkout_opts *opts,
 				delete_reflog(old_branch_info->path);
 		}
 	}
-	remove_branch_state(the_repository);
+	remove_branch_state(the_repository, !opts->quiet);
 	strbuf_release(&msg);
 	if (!opts->quiet &&
 	    (new_branch_info->path || (!opts->force_detach && !strcmp(new_branch_info->name, "HEAD"))))
builtin/rebase.c +2 -2
index 52114cbf0d..646d0f9fb1 100644
@@ -1272,7 +1272,7 @@ int cmd_rebase(int argc, const char **argv, const char *prefix)
 		if (reset_head(NULL, "reset", NULL, RESET_HEAD_HARD,
 			       NULL, NULL) < 0)
 			die(_("could not discard worktree changes"));
-		remove_branch_state(the_repository);
+		remove_branch_state(the_repository, 0);
 		if (read_basic_state(&options))
 			exit(1);
 		goto run_rebase;
@@ -1292,7 +1292,7 @@ int cmd_rebase(int argc, const char **argv, const char *prefix)
 			       NULL, NULL) < 0)
 			die(_("could not move back to %s"),
 			    oid_to_hex(&options.orig_head));
-		remove_branch_state(the_repository);
+		remove_branch_state(the_repository, 0);
 		ret = finish_rebase(&options);
 		goto cleanup;
 	}
builtin/reset.c +1 -1
index 7882829a95..6d9397c844 100644
@@ -420,7 +420,7 @@ int cmd_reset(int argc, const char **argv, const char *prefix)
 			print_new_head_line(lookup_commit_reference(the_repository, &oid));
 	}
 	if (!pathspec.nr)
-		remove_branch_state(the_repository);
+		remove_branch_state(the_repository, 0);
 
 	return update_ref_status;
 }
builtin/revert.c +1 -1
index a47b53ceaf..ebf2789225 100644
@@ -196,7 +196,7 @@ static int run_sequencer(int argc, const char **argv, struct replay_opts *opts)
 	if (cmd == 'q') {
 		int ret = sequencer_remove_state(opts);
 		if (!ret)
-			remove_branch_state(the_repository);
+			remove_branch_state(the_repository, 0);
 		return ret;
 	}
 	if (cmd == 'c')
Signature · 1 line
2.21.0.479.g47ac719cd3
#256 lore raw

Re: [PATCH v6 07/27] checkout: inform the user when removing branch state

Quoted 5 lines · Nguyễn Thái Ngọc Duy

After a successful switch, if a merge, cherry-pick or revert is ongoing, it is canceled. This behavior has been with us from the very early beginning, soon after git-merge was created but never actually documented [1]. It may be a good idea to be transparent and tell the user if some operation is canceled.

After this entered 'next' last week, today it greeted me with 167(!) of these warnings... before I even had my breakfast.

Now, my script does a lot of repeated cherry-picks and expects that rerere is able to deal with most of the conflicts, i.e. it does approximately this:

if ! git cherry-pick $oid >/dev/null 2>&1
then

      if was_the_conflict_resolved
      then
          echo "using previous conflict resolution"
          git commit --no-edit --cleanup=strip --quiet
      else
          die "uh-oh"
      fi

fi

That 'git commit' in there always prints:

warning: cancelling a cherry picking in progress

I don't understand why committing after a cherry-pick is considered "cancelling"... in my view it's finishing it and there should be no warning whatsoever.

Quoted 140 lines

I consider this a better way of telling the user than just adding a sentence or two in git-checkout.txt, which will be mostly ignored anyway.

PS. Originally I wanted to print more details like

warning: cancelling an in-progress merge from <SHA-1>

which may allow some level of undo if the user wants to. But that seems a lot more work. Perhaps it can be improved later if people still want that.

[1] ... and I will try not to argue whether it is a sensible behavior. There is some more discussion here if people are interested:
CACsJy8Axa5WsLSjiscjnxVK6jQHkfs-gH959=YtUvQkWriAk5w@mail.gmail.com

---
 branch.c           | 11 +++++++----
 branch.h           |  2 +-
 builtin/am.c       |  2 +-
 builtin/checkout.c |  2 +-
 builtin/rebase.c   |  4 ++--
 builtin/reset.c    |  2 +-
 builtin/revert.c   |  2 +-
 7 files changed, 14 insertions(+), 11 deletions(-)
branch.c +7 -4
index 28b81a7e02..8dd5bb9f1c 100644
@@ -337,11 +337,14 @@ void create_branch(struct repository *r,
 	free(real_ref);
 }
 
-void remove_branch_state(struct repository *r)
+void remove_branch_state(struct repository *r, int verbose)
 {
-	unlink(git_path_cherry_pick_head(r));
-	unlink(git_path_revert_head(r));
-	unlink(git_path_merge_head(r));
+	if (!unlink(git_path_cherry_pick_head(r)) && verbose)
+		warning(_("cancelling a cherry picking in progress"));
+	if (!unlink(git_path_revert_head(r)) && verbose)
+		warning(_("cancelling a revert in progress"));
+	if (!unlink(git_path_merge_head(r)) && verbose)
+		warning(_("cancelling a merge in progress"));
 	unlink(git_path_merge_rr(r));
 	unlink(git_path_merge_msg(r));
 	unlink(git_path_merge_mode(r));
branch.h +1 -1
index 29c1afa4d0..aed045901e 100644
@@ -64,7 +64,7 @@ extern int validate_new_branchname(const char *name, struct strbuf *ref, int for
  * Remove information about the state of working on the current
  * branch. (E.g., MERGE_HEAD)
  */
-void remove_branch_state(struct repository *r);
+void remove_branch_state(struct repository *r, int verbose);
 
 /*
  * Configure local branch "local" as downstream to branch "remote"
builtin/am.c +1 -1
index 4fb107a9d1..99b66508fd 100644
@@ -1957,7 +1957,7 @@ static int clean_index(const struct object_id *head, const struct object_id *rem
 	if (merge_tree(remote_tree))
 		return -1;
 
-	remove_branch_state(the_repository);
+	remove_branch_state(the_repository, 0);
 
 	return 0;
 }
builtin/checkout.c +1 -1
index 0e6037b296..f66bd2f56d 100644
@@ -899,7 +899,7 @@ static void update_refs_for_switch(const struct checkout_opts *opts,
 				delete_reflog(old_branch_info->path);
 		}
 	}
-	remove_branch_state(the_repository);
+	remove_branch_state(the_repository, !opts->quiet);
 	strbuf_release(&msg);
 	if (!opts->quiet &&
 	    (new_branch_info->path || (!opts->force_detach && !strcmp(new_branch_info->name, "HEAD"))))
builtin/rebase.c +2 -2
index 52114cbf0d..646d0f9fb1 100644
@@ -1272,7 +1272,7 @@ int cmd_rebase(int argc, const char **argv, const char *prefix)
 		if (reset_head(NULL, "reset", NULL, RESET_HEAD_HARD,
 			       NULL, NULL) < 0)
 			die(_("could not discard worktree changes"));
-		remove_branch_state(the_repository);
+		remove_branch_state(the_repository, 0);
 		if (read_basic_state(&options))
 			exit(1);
 		goto run_rebase;
@@ -1292,7 +1292,7 @@ int cmd_rebase(int argc, const char **argv, const char *prefix)
 			       NULL, NULL) < 0)
 			die(_("could not move back to %s"),
 			    oid_to_hex(&options.orig_head));
-		remove_branch_state(the_repository);
+		remove_branch_state(the_repository, 0);
 		ret = finish_rebase(&options);
 		goto cleanup;
 	}
builtin/reset.c +1 -1
index 7882829a95..6d9397c844 100644
@@ -420,7 +420,7 @@ int cmd_reset(int argc, const char **argv, const char *prefix)
 			print_new_head_line(lookup_commit_reference(the_repository, &oid));
 	}
 	if (!pathspec.nr)
-		remove_branch_state(the_repository);
+		remove_branch_state(the_repository, 0);
 
 	return update_ref_status;
 }
builtin/revert.c +1 -1
index a47b53ceaf..ebf2789225 100644
@@ -196,7 +196,7 @@ static int run_sequencer(int argc, const char **argv, struct replay_opts *opts)
 	if (cmd == 'q') {
 		int ret = sequencer_remove_state(opts);
 		if (!ret)
-			remove_branch_state(the_repository);
+			remove_branch_state(the_repository, 0);
 		return ret;
 	}
 	if (cmd == 'c')
Signature · 1 line
2.21.0.479.g47ac719cd3
author
#257 lore raw

Re: [PATCH v6 07/27] checkout: inform the user when removing branch state

Quoted 25 lines · SZEDER Gábor
Quoted 5 lines · Nguyễn Thái Ngọc Duy

After a successful switch, if a merge, cherry-pick or revert is ongoing, it is canceled. This behavior has been with us from the very early beginning, soon after git-merge was created but never actually documented [1]. It may be a good idea to be transparent and tell the user if some operation is canceled.

After this entered 'next' last week, today it greeted me with 167(!) of these warnings... before I even had my breakfast.

Now, my script does a lot of repeated cherry-picks and expects that rerere is able to deal with most of the conflicts, i.e. it does approximately this:

if ! git cherry-pick $oid >/dev/null 2>&1
then

      if was_the_conflict_resolved
      then
          echo "using previous conflict resolution"
          git commit --no-edit --cleanup=strip --quiet
      else
          die "uh-oh"
      fi

fi

Quoted 8 lines

That 'git commit' in there always prints:

warning: cancelling a cherry picking in progress

I don't understand why committing after a cherry-pick is considered "cancelling"... in my view it's finishing it and there should be no warning whatsoever.

I agree, this is not "canceling". I think this series causes conflicts with pw/clean-sequencer-state-upon-final-commit and the warning is accidentally enabled (partly my fault since I named the argument "verbose").

Junio, in this conflict resolution (merging nd/switch-and-restore to next), we should pass '0' instead of 'verbose' to sequencer_post_commit_cleanup().

builtin/commit.c +0 -0
diff --cc builtin/commit.c
index 1921401117,fa5982cc86..145d50caf0
@@@ -1658,7 -1666,8 +1658,7 @@@ int cmd_commit(int argc, const char **a
  		die("%s", err.buf);
  	}
  
- 	sequencer_post_commit_cleanup(the_repository);
 -	unlink(git_path_cherry_pick_head(the_repository));
 -	unlink(git_path_revert_head(the_repository));
++	sequencer_post_commit_cleanup(the_repository, verbose);
  	unlink(git_path_merge_head(the_repository));
  	unlink(git_path_merge_msg(the_repository));
  	unlink(git_path_merge_mode(the_repository));
--

Duy

#258 lore raw

Re: [PATCH v6 07/27] checkout: inform the user when removing branch state

Quoted 49 lines · Duy Nguyen
Quoted 25 lines · SZEDER Gábor
Quoted 5 lines · Nguyễn Thái Ngọc Duy

After a successful switch, if a merge, cherry-pick or revert is ongoing, it is canceled. This behavior has been with us from the very early beginning, soon after git-merge was created but never actually documented [1]. It may be a good idea to be transparent and tell the user if some operation is canceled.

After this entered 'next' last week, today it greeted me with 167(!) of these warnings... before I even had my breakfast.

Now, my script does a lot of repeated cherry-picks and expects that rerere is able to deal with most of the conflicts, i.e. it does approximately this:

if ! git cherry-pick $oid >/dev/null 2>&1
then

      if was_the_conflict_resolved
      then
          echo "using previous conflict resolution"
          git commit --no-edit --cleanup=strip --quiet
      else
          die "uh-oh"
      fi

fi

Quoted 8 lines

That 'git commit' in there always prints:

warning: cancelling a cherry picking in progress

I don't understand why committing after a cherry-pick is considered "cancelling"... in my view it's finishing it and there should be no warning whatsoever.

I agree, this is not "canceling". I think this series causes conflicts with pw/clean-sequencer-state-upon-final-commit and the warning is accidentally enabled (partly my fault since I named the argument "verbose").

Junio, in this conflict resolution (merging nd/switch-and-restore to next), we should pass '0' instead of 'verbose' to sequencer_post_commit_cleanup().

builtin/commit.c +0 -0
diff --cc builtin/commit.c
index 1921401117,fa5982cc86..145d50caf0

builtin/commit.c

Quoted 10 lines
builtin/commit.c +1 -1
@@@ -1658,7 -1666,8 +1658,7 @@@ int cmd_commit(int argc, const char **a
  		die("%s", err.buf);
  	}
 
- 	sequencer_post_commit_cleanup(the_repository);
 -	unlink(git_path_cherry_pick_head(the_repository));
 -	unlink(git_path_revert_head(the_repository));
++	sequencer_post_commit_cleanup(the_repository, verbose);
  	unlink(git_path_merge_head(the_repository));
  	unlink(git_path_merge_msg(the_repository));
  	unlink(git_path_merge_mode(the_repository));

Thanks, this indeed takes care of it.

#259 lore raw

Re: [PATCH v6 07/27] checkout: inform the user when removing branch state

In reply to Duy Nguyen
Quoted 8 lines · Duy Nguyen

I agree, this is not "canceling". I think this series causes conflicts with pw/clean-sequencer-state-upon-final-commit and the warning is accidentally enabled (partly my fault since I named the argument "verbose").

Junio, in this conflict resolution (merging nd/switch-and-restore to next), we should pass '0' instead of 'verbose' to sequencer_post_commit_cleanup().

Thanks for an update to the merge-fix. What should the name of the parameter to the sequencer_post_commit_cleanup() funcion be then, though? Perhaps we'd want an update after the topic graduates to the 'master' branch.

Quoted 18 lines
builtin/commit.c +1 -2
diff --cc builtin/commit.c
index 1921401117,fa5982cc86..145d50caf0
@@@ -1658,7 -1666,8 +1658,7 @@@ int cmd_commit(int argc, const char **a
  		die("%s", err.buf);
  	}
 
- 	sequencer_post_commit_cleanup(the_repository);
 -	unlink(git_path_cherry_pick_head(the_repository));
 -	unlink(git_path_revert_head(the_repository));
++	sequencer_post_commit_cleanup(the_repository, verbose);
  	unlink(git_path_merge_head(the_repository));
  	unlink(git_path_merge_msg(the_repository));
  	unlink(git_path_merge_mode(the_repository));
--

Duy

author
#260 lore raw

Re: [PATCH v6 07/27] checkout: inform the user when removing branch state

Quoted 8 lines · Junio C Hamano
Quoted 5 lines · Duy Nguyen

I agree, this is not "canceling". I think this series causes conflicts with pw/clean-sequencer-state-upon-final-commit and the warning is accidentally enabled (partly my fault since I named the argument "verbose").

Quoted 8 lines
Quoted 3 lines

Junio, in this conflict resolution (merging nd/switch-and-restore to next), we should pass '0' instead of 'verbose' to sequencer_post_commit_cleanup().

Thanks for an update to the merge-fix. What should the name of the parameter to the sequencer_post_commit_cleanup() funcion be then, though? Perhaps we'd want an update after the topic graduates to the 'master' branch.

Definitely. I was thinking something with "warn" and "cancel", which is more the the point. Probably warn_cancel_in_progress, or something.

Signature · 1 line
Duy
#261 lore raw

PATCH v6 8/27 checkout: keep most #include sorted

In reply to Nguyễn Thái Ngọc Duy

The include list becomes very long and frankly a bit unorganized. With the exception of builtin.h, cache.h or git-compat-util.h which have to come first, keep the rest sorted.

---
 builtin/checkout.c | 34 +++++++++++++++++-----------------
 1 file changed, 17 insertions(+), 17 deletions(-)
builtin/checkout.c +17 -17
index f66bd2f56d..15ee5181eb 100644
@@ -1,30 +1,30 @@
 #define USE_THE_INDEX_COMPATIBILITY_MACROS
 #include "builtin.h"
-#include "config.h"
+#include "advice.h"
+#include "blob.h"
+#include "branch.h"
+#include "cache-tree.h"
 #include "checkout.h"
+#include "commit.h"
+#include "config.h"
+#include "diff.h"
+#include "dir.h"
+#include "ll-merge.h"
 #include "lockfile.h"
+#include "merge-recursive.h"
+#include "object-store.h"
 #include "parse-options.h"
 #include "refs.h"
-#include "object-store.h"
-#include "commit.h"
+#include "remote.h"
+#include "resolve-undo.h"
+#include "revision.h"
+#include "run-command.h"
+#include "submodule.h"
+#include "submodule-config.h"
 #include "tree.h"
 #include "tree-walk.h"
-#include "cache-tree.h"
 #include "unpack-trees.h"
-#include "dir.h"
-#include "run-command.h"
-#include "merge-recursive.h"
-#include "branch.h"
-#include "diff.h"
-#include "revision.h"
-#include "remote.h"
-#include "blob.h"
 #include "xdiff-interface.h"
-#include "ll-merge.h"
-#include "resolve-undo.h"
-#include "submodule-config.h"
-#include "submodule.h"
-#include "advice.h"
 
 static int checkout_optimize_new_branch;
 
Signature · 1 line
2.21.0.479.g47ac719cd3