When I have modified my current branch and check out to a different branch, git
warns me that I have not stashed or commited fails only when there is a conflict between the two branches.
How can I make git always warn me that files have not been commited before I checkout?
CodePudding user response:
As Useless says in a comment, you will need to write your own little mini-program (e.g., a few lines of shell script or alias) that does this. Git's "allow switching with modified files" is considered a feature, not a bug, and it specifically enables the creation of a new branch name at any time in case you have started work and decide that this should become a branch of its own.
The git-core
library includes a source
-able shell file named git-sh-setup
that provides a function named require_clean_work_tree
, so your alternate program (which you will use instead of git checkout
or git switch
) will likely begin with:
#! /bin/sh
. git-sh-setup
# adjust my-checkout name as desired
require_clean_work_tree my-checkout "stash or commit your changes before using my-checkout"
Note, however, that a successful git checkout
or git switch
that carries modifications in the index and/or working tree produces git status
style output showing the carried modifications. You can simply git checkout -
or git switch -
to return to the original branch name (or detached HEAD) that you were on just a moment ago. There are a few rare corner cases where you'll lose some information in the process, but you are unlikely to run into these in practice. For the gory details, see Checkout another branch when there are uncommitted changes on the current branch.