# Remotes: push, fetch and pull without surprises

How your repository stays in sync with GitHub: remotes and remote-tracking branches, pushing a new branch, why a push gets rejected, fetching to look before you merge, and pulling with rebase.

Course: [Git & GitHub](https://devops.rajeev.pro/courses/git), lesson 5. About 30 minutes, beginner. Source: https://devops.rajeev.pro/courses/git/05-remotes

## What you will learn

- Explain origin, remote-tracking branches such as origin/main, and upstream branches
- List, add, rename and change the URL of remotes
- Push a new branch and set its upstream, and read ahead/behind counts
- Explain why a push is rejected, and fix it without losing anyone's work
- Fetch to see what changed before merging it
- Choose how git pull combines work, and set a sensible default once

## Three copies of every branch

**Why this matters.** As long as a repository lives only on your laptop, two things can go wrong: the
laptop dies and the history dies with it, and nobody else can build on your work. A remote fixes
both. It's a second full copy of the repository, usually on GitHub, that you send commits to and
collect your teammates' commits from. The confusing part is that your laptop then holds _two_
versions of every branch, and most push and pull surprises come from mixing them up. This section
untangles that.

A **remote** is another copy of the repository, usually on GitHub, with a short name. The one you
cloned from is called `origin`. Once you have a remote, each branch exists in three places, and
knowing which one you're looking at removes most of the confusion around push and pull:

> **Figure.** Three copies of main. On GitHub, main itself. On your laptop, origin/main, a read-only bookmark of where GitHub's main was at your last fetch, and your own local main where you commit. git fetch updates origin/main from GitHub and touches nothing else. git merge or git rebase brings origin/main into your main. git pull does fetch plus merge or rebase. git push sends your main's new commits to GitHub and moves origin/main to match.
>
> fetch updates your bookmark. pull also changes your branch. push changes GitHub.

| Name             | Lives                         | Updated by                          |
| ---------------- | ----------------------------- | ----------------------------------- |
| `main` on GitHub | the server                    | anyone's `git push`                 |
| `origin/main`    | your `.git`, read-only        | `git fetch`, `git pull`, `git push` |
| `main`           | your `.git`, where you commit | you                                 |

`origin/main` is a snapshot from the last time you talked to GitHub. It doesn't update on its own, so
always fetch before deciding you're up to date.

## Managing remotes

```sh
$ git remote -v                                     # names and URLs
origin	https://github.com/rajeev/shop.git (fetch)
origin	https://github.com/rajeev/shop.git (push)
$ git remote add upstream https://github.com/owner/shop.git   # a second remote, e.g. for a fork
$ git remote set-url origin git@github.com:rajeev/shop.git    # switch from HTTPS to SSH
$ git remote rename upstream source
$ git remote remove source
$ git remote show origin                            # branches it has, and what tracks what
```

By convention `origin` is where you push (your repository or your fork) and `upstream` is the original
project you forked from.

Why have two? When you contribute to someone else's project, you can't push to it. So you push to
your fork (`origin`), and you _fetch_ from the original (`upstream`) to keep up with everyone else's
changes. Your own team's repository usually needs only `origin`.

## Push and pull

### Pushing a new branch

```sh
$ git switch -c feature/x
$ git push -u origin feature/x
 * [new branch]      feature/x -> feature/x
branch 'feature/x' set up to track 'origin/feature/x'.
```

`-u` sets the branch's **upstream**. From then on, plain `git push` and `git pull` know where to go,
and `git status` can compare:

```sh
$ git status -sb
## main...origin/main [ahead 1]
$ git branch -vv
* main 99fec5d [origin/main: ahead 1, behind 1] Add Ravi's file
```

| Status              | Means                                      | Do                            |
| ------------------- | ------------------------------------------ | ----------------------------- |
| `ahead 2`           | you have 2 commits GitHub doesn't          | `git push`                    |
| `behind 3`          | GitHub has 3 commits you don't             | `git pull`                    |
| `ahead 1, behind 1` | both moved: the branches have **diverged** | pull (with rebase), then push |

### When a push is rejected

> **Figure.** Animated. Asha commits A and pushes; GitHub's main now has A. Ravi commits R and pushes, but the push is rejected because GitHub has a commit he doesn't. Ravi runs git pull --rebase: A comes down to his laptop and R is replayed on top of it. His push then succeeds, and GitHub's main has A then R.
>
> Asha pushes first. Ravi's push bounces, he pulls with rebase, and his second push lands on top of hers.

Asha and Ravi both cloned the repository. Asha pushed first. Now Ravi's push fails:

```text
 ! [rejected]        main -> main (fetch first)
error: failed to push some refs to 'github.com:rajeev/shop.git'
hint: Updates were rejected because the remote contains work that you do not
hint: have locally.
```

Git refuses because accepting Ravi's push would throw away Asha's commit. The fix is to bring her work
in first, then push:

```sh
$ git pull --rebase                  # fetch, then replay my commits on top of theirs
Successfully rebased and updated refs/heads/main.
$ git log --oneline -2
e0c625c Add Ravi's file
ff897a0 Add Asha's note
$ git push
   ff897a0..e0c625c  main -> main
```

> **Never answer a rejected push with --force.** `git push --force` makes GitHub's branch match yours exactly, deleting the commits you didn't have. On a shared branch that silently erases a teammate's work. The *Rewriting history* lesson covers the rare cases where a forced push is right, and the safer `--force-with-lease`.

### How should pull combine work?

When both sides have new commits, `git pull` must merge or rebase, and recent Git asks you to choose
instead of guessing:

```text
fatal: Need to specify how to reconcile divergent branches.
```

Set your default once:

```sh
$ git config --global pull.rebase true   # replay your local commits on top: straight history
```

| Setting             | Diverged pull does                        | History                                              |
| ------------------- | ----------------------------------------- | ---------------------------------------------------- |
| `pull.rebase true`  | replays your commits after theirs         | a straight line                                      |
| `pull.rebase false` | makes a merge commit                      | a "Merge branch 'main' of github…" bubble every time |
| `pull.ff only`      | refuses unless it's a simple fast-forward | you decide each time                                 |

Rebasing on pull is what most teams want for their own unpushed commits. The _Merge strategies_
lesson explains rebase properly.

## Fetch: look before you merge

`git fetch` downloads everything new and updates `origin/*`, and changes nothing else: not your
branches, not your files. That makes it the safe way to see what your team did:

```sh
$ git fetch
   9c53c90..ff897a0  main       -> origin/main
$ git log --oneline main..origin/main      # commits on GitHub that I don't have
ff897a0 Add Asha's note
$ git log --oneline origin/main..main      # my commits GitHub doesn't have
99fec5d Add Ravi's file
$ git diff main origin/main --stat         # what their commits change
$ git merge origin/main                    # or rebase, when you're ready
```

`A..B` means "commits in B that aren't in A". Read it as _from A to B_.

```sh
$ git fetch --prune                        # also forget branches deleted on GitHub
$ git config --global fetch.prune true     # always do that
```

> **Before you push to a shared branch.** `git fetch`, read what came in, rebase or merge, run the tests, then push. Thirty seconds of this prevents most "who broke main?" mornings. Better still, protect `main` on GitHub so nobody pushes to it directly (the *Collaboration* lesson).

> **Video.** [Git Tutorial #32: What Is Git Fetch and How to Use It | Learn Git](https://www.youtube.com/watch?v=uEEcw1s_wWk) (GitKraken)

## Mission: Two developers, one branch

Simulate two teammates on your own machine: clone one repository into two folders, make a commit in each, push from the first, and get the second one's push accepted without a force push and without losing either commit.

- You need: Git, and a local bare repository standing in for GitHub
- You'll have: Both commits on the shared main, in a straight line

```sh
$ cd ~ && git init --bare team.git              # plays the role of GitHub
$ git clone team.git asha && git clone team.git ravi   # "cloned an empty repository" is expected
$ cd asha && echo "# Team" > README.md && git add . && git commit -m "Add README" && git push -u origin main
$ cd ../ravi && git pull                        # Ravi gets the README
$ cd ../asha && echo "asha" >> README.md && git commit -am "Add Asha's note" && git push
$ cd ../ravi && echo "ravi" > ravi.txt && git add . && git commit -m "Add Ravi's file"
$ git push                                      # rejected: fetch first
$ git fetch && git log --oneline main..origin/main
$ git pull --rebase && git push
$ git log --oneline
```

The last log shows Ravi's commit on top of Asha's, then the README commit, with no merge commit. Both
folders end with the same history after `git pull` in `asha`.

## Try it

- Run `git remote -v` in a cloned repository and name each remote.
- Run `git branch -vv` and read which upstream each branch tracks, and how far ahead or behind it is.
- Run `git fetch`, then `git log --oneline main..origin/main` to see commits you don't have yet.
- Push a new branch with `git push -u origin <branch>`.
- Set `git config --global pull.rebase true` and read what it changes in this lesson.
- Clone one repository twice into two folders, push from one, and pull from the other.

## Quiz

1. What is origin/main?
   - The main branch on GitHub itself
   - **Your local record of where main was on origin the last time you fetched** (answer)
   - A second copy of your main branch
   Why: Remote-tracking branches update only when you fetch, pull or push. They can be out of date until you git fetch.

2. git push is rejected with "fetch first". What happened, and what do you do?
   - GitHub is down; retry later
   - **Someone pushed commits you don't have. Pull them in (git pull --rebase), then push again** (answer)
   - Use git push --force
   Why: Git refuses to overwrite commits on the remote. Integrating them first keeps everyone's work. Forcing would delete your teammate's commits.

3. What is the difference between git fetch and git pull?
   - None
   - **fetch downloads new commits and updates origin/*, changing none of your branches; pull fetches and then merges or rebases into your current branch** (answer)
   - pull only downloads
   Why: fetch is always safe. Use it to look at what changed before you combine it with your work.

4. What does -u do in git push -u origin feature/login?
   - Pushes urgently
   - **Sets origin/feature/login as the branch's upstream, so later git push and git pull need no arguments** (answer)
   - Updates every branch
   Why: The upstream link is also what git status uses to say "ahead 2" or "behind 1".

5. git status says "ahead 1, behind 1". What does that mean?
   - **You have one commit the remote lacks, and the remote has one commit you lack: the branches have diverged** (answer)
   - Everything is in sync
   - One file is staged
   Why: Pull with rebase to replay your commit on top of theirs, then push.

## Resources

- [Pro Git: working with remotes](https://git-scm.com/book/en/v2/Git-Basics-Working-with-Remotes) (Pro Git)
- [Pro Git: remote branches](https://git-scm.com/book/en/v2/Git-Branching-Remote-Branches) (Pro Git)
- [git-pull documentation](https://git-scm.com/docs/git-pull) (Git)
- [GitHub Docs: managing remote repositories](https://docs.github.com/en/get-started/git-basics/managing-remote-repositories) (GitHub Docs)
