Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find branch name during git rebase

What?

Is there a way to find the name of the branch-being-rebased during an interactive rebase, that is better than parsing .git/rebase-merge/head-name?

Details

Normally I use git rev-parse --abbrev-ref HEAD to get the branch name. But during a rebase the branch is in a detached head state and rev-parse returns HEAD.

So now I'm parsing the .git/rebase-merge/head-name file if it exists to pull out the branch name. Is there a method (porcelain or otherwise) to get this data?

Usage:

git checkout "the_branch_name_I_want"
git rebase -i "some_other_branch_sha_etc"
# mark commit for edit ...
git magic-command # I'd like to get back "the_branch_name_I_want"
git rebase --continue

Why?

Why do I want to do this?

I store metadata about the branch and fetch it in my commit-msg hook to append to my commit message. I want this to work when rewording or editing my commit messages during interactive rebase.

Code:

branch=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)
if [ "$?" -ne 0 ]; then
    echo "not in a git repo!"
    exit 2
fi
if [ "$branch" = "HEAD" ]; then
    # check if we are in a rebase
    head_name_file="$(git rev-parse --git-dir)/rebase-merge/head-name"
    if [ -f "${head_name_file}" ]; then
        branch=$(cut -f3- -d/ $head_name_file)
    else
        # ignore DETACHED HEAD state.
        exit 1
    fi
fi
## do something with branch
like image 963
spazm Avatar asked Dec 10 '15 22:12

spazm


People also ask

What is rebase current branch?

From a content perspective, rebasing is changing the base of your branch from one commit to another making it appear as if you'd created your branch from a different commit. Internally, Git accomplishes this by creating new commits and applying them to the specified base.

What is git rebase command?

The git rebase command is used to merge the history of two branches on a repository. It is often used to integrate changes from one branch onto another branch. You should only use the git rebase command locally; it should not be used on a public repository.


1 Answers

Although git branch --list shows a branch name (see this answer for the details), it is not useful during the scripting as you need to parse the output.

I use the following function to get a branch name (based on head-name file):

rebasing-branch() {
    for location in rebase-merge rebase-apply; do
        path=$(git rev-parse --git-path ${location})
        if test -d ${path}; then
            revision=$(<${path}/head-name)
            echo ${revision##refs/heads/}
            return 0
        fi
    done
}

It shows the branch name during either regular or interactive rebase.

like image 91
Dmytro Serdiuk Avatar answered Oct 08 '22 20:10

Dmytro Serdiuk