Git branch

A git branch is a mutable reference under refs/heads/ that points to a commit.

Concepts

Branching workflows

  • git-flow
  • github-flow
  • gitlab-flow
  • trunk-based development

Cheatsheet

git branch

The uppercased flags add --force:

  • git branch -a/--all: list both remote-tracking and local branches
  • git branch -m/-M/--move master main: move/rename a branch and its reflog

git checkout

git checkout was split into two commands in 2.23, git switch and git restore.

git restore

I do use git restore --staged sometimes

git switch

git checkout -b is the same of git switch -c

ReferencesLink to other things

Personal Config

I have most of my aliases on nix in the git-aliases file

[alias]
br=branch
branches=branch -a
cd=checkout
[branch]
autosetuprebase = always

autosetupmerge

autosetupmerge controls whether git branch and git checkout -b imply the –track option, i.e. with your setting of always:

  • git checkout branchname, if branchname exists on a remote but not locally will create branchname tracking its remote counterpart

  • git checkout -b newbranch will create a new branch newbranch tracking whichever branch you had checked out before issuing this command

  • StackOverflow

autosetuprebase

autosetuprebase controls whether new branches should be set up to be rebased upon git pull, i.e. your setting of always will result in branches being set up such that git pull always performs a rebase, not a merge. (Be aware that existing branches retain their configuration when you change this option.)

Setup default branch

This sets the main branch as default when creating a new repository (git init) instead of master. Sometimes I create the repository locally and then push it.

Example

~/.config/git/config
[init]
defaultBranch=main

Setup default remote name

I like to use the upstream remote name for projects that I do not have write access.

Example

~/.config/git/config
[includeIf "gitdir:/some/dir"]
path = "~/.config/git/other-config"
~/.config/git/other-config
[clone]
defaultRemoteBranch=upstream

Delete the merged branches

Good to clean feature branches after merging them.

[alias]
brd="!f() {
git branch --merged \
| grep -Ev '^[*]|main|master|staging' \
| xargs -r git branch -d \
; }; f"