KyleL
KyleL

Reputation: 1455

git branch restoration after merge

If I merge a git feature branch back onto master, is it best to then delete the branch?

Let's say 6 months later, I want to resurrect that deleted branch (assume a freshly cloned repo). Is there a way to easily re-create it or find its history assuming it was merged back onto master? What is the best way to do this?

From reading other questions, I see that if I can find the head of that branch I can re-create it easily, but how do I go about doing that? Some other Q&A responses reference the "reflog" command, but this doesn't return anything useful if I have freshly cloned the repo.

Upvotes: 3

Views: 4447

Answers (1)

Ash Wilson
Ash Wilson

Reputation: 24498

Whether or not it's best to delete a branch once merged depends on what the branch means to your workflow. If it's a branch that's being used to prepare a new release, which gets merged into master once the release is ready, then you'll want to keep it around. If it's a throwaway branch for developing a single feature, then it's usually preferable to delete it so you don't clutter your git branch output with dozens of completed branches.

If you want to re-create a deleted branch later, all you'll need to do is find the SHA that corresponds to its last commit. If you don't have the reflog handy, you'll have to try to find this with git log. The easiest way to do this would be to search for the merge commit with something like:

# This should match the message of the merge commit, if you kept the default.
git log --grep=branch-name

Once you find the merge commit, you'll see two parents listed:

commit 38bf1d168e73f9fa708c334e50f256578d5c2d8f
Merge: a08b280 d7725b0

The first parent is the state of master before the merge; the second is the state of the branch that was merged in, which is what you want. Recreate your branch there and check it out with:

git checkout -b branch-name d7725b0

As a sidenote, this will only work if the merge wasn't a fast-forward merge. A fast-forward merge just zips HEAD up to the ref that's being merged, so it doesn't create a merge commit. You can force git to always make a new commit when you merge by using:

git merge --no-ff branch-name

And if you always want this to be the case you can set it in your config:

git config branch.master.mergeoptions  "--no-ff"

Upvotes: 5

Related Questions