Skip to content

Git Branching

Kenneth Kasajian edited this page Mar 26, 2021 · 28 revisions

Create a new branch:

git branch experimental

Creating branches just creates a new tag pointing to the currently checked out commit.

List branches (the asterisk marks the branch you are currently on):

git branch

Switch to the experimental branch:

git checkout experimental

Create branch and check it out with a single command:

git checkout -b branchname

Make changes, and edit. Then switch back to master and merge:

git checkout master
git merge experimental

If there's conflicts, markers will be left in the files. type git diff to see.

git merge will create a new commit with two parents. The resulting commit snapshot will have the all of the work that has been done in both branches. If there was no divergence between the two commits, git will do a "fast-forward" method merge.

To delete the experimental branch:

git branch -d experimental

will only delete it if the changes are in the current branch.

To delete a branch just to throw it away without merging it, use:

git branch -D crazy-idea-branch

-D delete a branch irrespective of its merged status.

To rename a local branch

git branch -m <old_name> <new_name>

to rename a branch on remote

git push origin origin/<old_name>:refs/heads/<new_name> :<old_name>

Rebase and Squash commits

See Git---Push

Publish / Unpublish branch

Publish:

git push -u origin <branch_to_publish>

Unpublish

git push origin :<branch_to_publish>

or

git push origin --delete <branch_to_publish>

Example Workflows:

Branch to fix a bug then merge:

git branch bug111
git checkout bug111
git commit
git checkout master
git merge bug111

Branch to fix a bug then rebase:

git branch bug111
git checkout bug111
git commit
git rebase master

To move master to the end (i.e. bug111), use one of the following:

git checkout master
git reset bug111

or

git branch -f master bug111

Branch to fix a bug then rebase:

Hand-pick each line of the files to be merged, bypass Git from getting involved in the merge process:

git checkout master
git difftool local-branch HEAD

Determine the common ancestor of two branches (say, release and master)

git merge-base release master

or

git merge-base master head

Determine what commits are on the current branch by not master

git log head --not master

Determine which branch contains a commit

git branch --contains <commit>

or

git reflow show --all | grep <commit>

To show only commits on master (will give bad results if you have ff merges)

git logs --first-parent master

References