Git and GitHub · Part 3 · GitHub and remote repositories

Push, pull and fetch in depth

When two people push

With one person, push and pull just work. With two, their work crosses: a push gets rejected, branches diverge, and someone is tempted to force-push. This lesson covers those everyday situations, using a local “server” like the one in Lesson 16, because it makes two people easy to simulate. Everything works the same with GitHub.

A two-person lab

Terminal
cd ~/Desktop
mkdir sync-lab
cd sync-lab
git init --bare server.git

git clone server.git nithin
git clone server.git teammate

Git warns You appear to have cloned an empty repository, which is fine. Nithin makes the first commit, and the teammate pulls it:

Terminal
cd nithin
echo "line 1" > app.txt
git add app.txt
git commit -m "Add app"
git push -u origin main

cd ../teammate
git pull

git push

A push sends new commits to the remote, moves the remote's branch forward, and updates the local origin/main to match.

Terminal
git push                        # the current branch, to the branch it tracks
git push origin main            # the same, said in full
git push -u origin feature/x    # a new branch's first push, setting up tracking

Typing -u origin branch-name for every new branch gets old. Since Git 2.37, one setting does it on the first push:

Terminal
git config --global push.autoSetupRemote true

After that, plain git push works on a brand-new branch too.

The rejected push

The teammate pushes first:

teammate
echo "teammate line" >> app.txt
git commit -am "Teammate change"
git push

Nithin commits too, without pulling, and pushes:

nithin
echo "nithin line" > notes.txt
git add notes.txt
git commit -m "Add notes"
git push
Output
To /Users/you/Desktop/sync-lab/server.git
 ! [rejected]        main -> main (fetch first)
error: failed to push some refs to '/Users/you/Desktop/sync-lab/server.git'
hint: Updates were rejected because the remote contains work that you do not
hint: have locally. This is usually caused by another repository pushing to
hint: the same ref. If you want to integrate the remote changes, use
hint: 'git pull' before pushing again.

Git is protecting the teammate's work. The server has A then T; the laptop has A then N. Accepting the push would move the server's main to N and throw T away. So a push is only allowed when it's a fast-forward for the server: the new commits build on everything the server already has.

The fix is to bring the teammate's work in first, then push again:

nithin
git pull
git push

How git pull combines the two is the subject of the git pull section.

Force-pushing safely

After rebasing or squashing a branch that's already pushed (Lessons 13 and 14), its history has changed, and a normal push is rejected. Replacing the remote's history takes a force-push, and there are two kinds:

CommandTells the server
git push --forceMatch my laptop, no matter what. Anything a teammate pushed meanwhile is deleted.
git push --force-with-leaseReplace it, but only if it's still where I last saw it. Otherwise, refuse.

1.Both people get a branch

nithin
git pull
git switch -c feature/profile
echo "v1" > profile.txt
git add profile.txt
git commit -m "Add profile"
git push
teammate
git fetch
git switch feature/profile
echo "teammate fix" >> profile.txt
git commit -am "Teammate fix to profile"
git push

There's no local feature/profile in the teammate's copy, so git switch creates one that tracks origin/feature/profile.

2.Rewrite and force-push

Nithin, without fetching, amends his commit and force-pushes:

nithin
git commit --amend -m "Add profile page"
git push --force-with-lease
Output
! [rejected]        feature/profile -> feature/profile (stale info)
error: failed to push some refs to '/Users/you/Desktop/sync-lab/server.git'

Stale info means the server changed since Nithin's last look, so the push was refused and the teammate's fix is safe. Plain --force would have deleted it, so don't run that here.

SituationForce-push?
Your own feature branch after a rebase or squashYes, with --force-with-lease
Your own branch with an open pull requestYes, and tell the reviewers
main, develop or any shared branchNever
A branch other people push toOnly after agreeing it first

An alias makes the safe version the easy one to type:

Terminal
git config --global alias.pushf "push --force-with-lease --force-if-includes"
git pushf

git fetch

git fetch downloads new commits and branches and updates the origin/* bookmarks. It never touches local branches or files, so it's always safe to run. (git fetch --all fetches from every remote, useful with forks.)

Its real use is looking before bringing changes in. The teammate pushes an update:

teammate
git switch main
git pull
echo "important update" >> app.txt
git commit -am "Important update"
git push
nithin
git switch main
git fetch
git status
Output
On branch main
Your branch is behind 'origin/main' by 1 commit, and can be fast-forwarded.
QuestionCommand
What does the remote have that I don't?git log main..origin/main --oneline
What do I have that the remote doesn't?git log origin/main..main --oneline
What changed in the code?git diff main origin/main

A..B means “commits in B that aren't in A”. Here the first command shows cf1e177 Important update and the second shows nothing. Once it looks right, bring it in with git merge origin/main (or git rebase origin/main). That pair is exactly what git pull does in one step.

Cleaning up deleted branches

When a branch is deleted on GitHub, usually after its pull request is merged, the local origin/ bookmark for it stays. Over months, dozens pile up:

nithin
git branch -r
Output
origin/HEAD -> origin/main
  origin/feature/profile
  origin/main

origin/feature/profile was already deleted on the server. --prune removes bookmarks like it:

nithin
git fetch --prune
Output
- [deleted]         (none)     -> origin/feature/profile

To prune on every fetch and pull: git config --global fetch.prune true. Then git branch -vv marks local branches whose remote is gone:

Output
feature/profile 77f98ec [origin/feature/profile: gone] Add profile page
* main            cf1e177 [origin/main] Important update

Delete those with git branch -d feature/profile. If the pull request was squash-merged, Git refuses with not fully merged, because the branch's own commits never reached main. Once GitHub shows it as merged, -D deletes it anyway.

To delete a branch on the server from the terminal: git push origin --delete feature/profile. On GitHub, the Delete branch button after merging a pull request is more common.

git pull

git pull is git fetch followed by a way of combining. If there are no new local commits, there's nothing to combine: Git fast-forwards, the same with every strategy. The decision comes when both sides have new commits:

A
B
NHEAD → main
Torigin/main

Diverged: N is Nithin's new commit, T is the teammate's.

StrategySettingResult
Merge (git pull --no-rebase)pull.rebase falseA merge commit joins N and T. Never rewrites anything, but a busy team gets dozens of “Merge branch 'main' of …” commits a day.
Rebase (git pull --rebase)pull.rebase trueN is replayed on top of T as N′. A straight line, and safe, because only unpushed local commits are rewritten.
Fast-forward only (git pull --ff-only)pull.ff onlyWorks only when simply behind. On a divergence it stops, and the choice is made by hand.
A
B
N
MHEAD → main
T

After git pull --no-rebase: a merge commit M with two parents.

A
B
Torigin/main
N′HEAD → main

After git pull --rebase: one straight line.

With no setting at all, a diverged pull stops and asks for one:

Output
hint: You have divergent branches and need to specify how to reconcile them.
hint:   git config pull.rebase false  # merge
hint:   git config pull.rebase true   # rebase
hint:   git config pull.ff only       # fast-forward only
fatal: Need to specify how to reconcile divergent branches.

Lesson 2 set pull.rebase false to avoid that, and Lesson 13 offered true. The rebase setting, plus one more, is what many developers use:

Terminal
git config --global pull.rebase true
git config --global rebase.autoStash true

Without rebase.autoStash, a pull with uncommitted changes refuses: error: cannot pull with rebase: You have unstaged changes. With it, Git stashes them, rebases and brings them back (Lesson 15). If a team prefers merges, follow the team.

Try the rebase pull

teammate
echo "teammate A" >> app.txt
git commit -am "Teammate A"
git push
nithin
echo "nithin B" > b.txt
git add b.txt
git commit -m "Nithin B"
git pull --rebase
git log --oneline --graph
Output
* 34f1016 (HEAD -> main) Nithin B
* fd13746 (origin/main) Teammate A
* cf1e177 Important update

A straight line, ready for git push.

Conflicts during a pull

A pull that hits a conflict is fixed the same way as any other. Only the last command depends on the strategy:

Rebase pullMerge pull
FixEdit the file, delete the markersEdit the file, delete the markers
Mark as fixedgit add app.txtgit add app.txt
Finishgit rebase --continuegit commit
Back outgit rebase --abortgit merge --abort

During a rebase pull, the sides are swapped (Lesson 13): “current” (HEAD) is what came from the server, and “incoming” is the local commit.

A teammate's branch

The teammate pushed feature/search and asked for a look:

nithin
git fetch
git branch -a
Output
* main
  remotes/origin/HEAD -> origin/main
  remotes/origin/feature/search
  remotes/origin/main
nithin
git switch feature/search
Output
Switched to a new branch 'feature/search'
branch 'feature/search' set up to track 'origin/feature/search'.

Git finds origin/feature/search and makes a local branch that tracks it, so git pull and git push work on it. To link a branch by hand: git branch -u origin/feature/search.

A normal day

Terminal
# Morning: get the latest
git switch main
git pull

# Start a feature, commit often
git switch -c feature/filters
git commit -am "Add price filter"
git commit -am "Add bedroom filter"

# Back it up (fine even when unfinished, on your own branch)
git push

# main moved on: bring the branch up to date
git fetch
git rebase origin/main
git push --force-with-lease

# After the pull request is merged
git switch main
git pull
git branch -d feature/filters

Recommended settings

Terminal
git config --global push.autoSetupRemote true
git config --global pull.rebase true
git config --global rebase.autoStash true
git config --global fetch.prune true
git config --global alias.pushf "push --force-with-lease --force-if-includes"

git config --global --list shows them all.

Quick reference

TaskCommand
Push the current branchgit push
First push of a new branchgit push -u origin branch
Push was rejectedgit pull, then git push
Force-push your own branchgit push --force-with-lease
Delete a remote branchgit push origin --delete branch
Download without changing anythinggit fetch
What's new on the remotegit log main..origin/main --oneline
What isn't pushed yetgit log origin/main..main --oneline
Compare code with the remotegit diff main origin/main
Clean up deleted remote branchesgit fetch --prune
Find branches deleted on the servergit branch -vv
Pull with a straight historygit pull --rebase
Pull only if it fast-forwardsgit pull --ff-only
Work on a teammate's branchgit fetch, then git switch branch