Video in progress
`git status` says "Your branch is ahead of 'origin/main' by 2 commits" or "have diverged". What does it mean, and how is upstream set up?
The local branch is compared with its upstream (usually origin/<name>) as of the last fetch: ahead means unpushed commits, behind means server commits you do not have, and diverged means both. Upstream is set with git push -u or --set-upstream-to.
📖 Answer
An important subtlety: Git does not go to the server. It compares with the local copy of origin/main. If you have not run fetch, the "up to date" message may be false.
git fetch
git branch -vv
# * feature/sms 4e1a2b3 [origin/feature/sms: ahead 2, behind 1] SMS shablonlari
git rev-list --left-right --count origin/main...main
# 3 2 → the server has 3 you lack, you have 2 the server lacks
Setting upstream:
git push -u origin feature/sms # with the first push
git branch --set-upstream-to=origin/main main # for an existing branch
git config --global push.autoSetupRemote true # Git 2.37+: sets it itself on the first push
Once there is an upstream, the @{u} shorthand works:
git log --oneline @{u}.. # my commits not pushed yet
git log --oneline ..@{u} # what is new on the server
When diverged, there are two ways: git pull --rebase (put your commits on top) or a merge. But first look at what happened with git log --oneline --graph HEAD @{u}. Often someone has rebased that branch and force pushed, and then a plain pull brings in duplicate commits.
Sign up to mark studied questions and save your progress.