How to move HEAD to another branch in Git without checking files or updating any links?

I usually do this with echo ref: refs/heads/new_branch > .git/HEAD . How to do it right?

Some use cases:

  • You imported the source code from another place, now you want to fix it in Git (but not in the current branch).
  • Your .git is just a symbolic link, and now you are accessing it from another workgroup (I already know about git -new-workdir to do it right)

Therefore, you want to manually select which parent should have the next commit, and which ref should be updated by it.

+4
source share
4 answers

git plumbing team for this

 git symbolic-ref HEAD refs/heads/existing_branch 

You cannot go into the state of an individual head (he needs a link, not a SHA). However, you can switch to a non-existent ref (unknown branch). To prevent this, perhaps use the following git alias :

 git config --global alias.switch '!f() { git show-ref --heads --verify "refs/heads/$1" && git symbolic-ref -m "switch to branch $1 not touching workdir" HEAD "refs/heads/$1"; }; f' 

Then you can use it as a git switch existing_branch . Note that you need the -m option to see the entry in git reflog , this is usually what you want.

Notes:

  • git reflog HEAD shows the ref HEAD log (you will again see the comment specified with the -m option). The full file (which includes before SHA in case you want to find the lost commit) is stored in $(git rev-parse --git-dir)/logs/HEAD (for HEAD )
  • git show-ref --heads lists all the links you can use in RHS. As shown in alias , you can use it with --verify to check if the argument is a valid (existing) ref (aka. Branch).
  • Beware: git symbolic-ref can point to any other symbol, for example refs/tags/ or refs/remotes/ or even inside packed links. This is probably not what you want, so the alias limits this to the value of refs/heads/ .
+4
source

git reset --soft $branch_to_make_HEAD

man git reset docs in the --soft option:

It does not apply to the index file or the working tree in general (but it resets the head to <commit> , like all modes). This leaves all of your modified “Changes Must Be Committed” files, as git status would say.

+2
source
 git checkout -B existing_or_new_branch # HEAD by default git reset existing_branch@ {1} # or anywhere else for a new_branch 
+1
source

No. HEAD is a symbolic link that should always point to the current commit, i.e. what is in your working copy. You do not have to manually manipulate refs manually - and use plumbing commands only if you really know what you are doing.

This may be the case of the XY problem - that is, you think you know how to solve your problem and ask for help in this way, but there may be a better way to do this (only no one can tell you because you did not ask about your real problem ) Maybe I'm wrong: D

0
source

Source: https://habr.com/ru/post/1481185/


All Articles