u123
u123

Reputation: 16329

When do I need to pull before I can push in Git?

If A and B are working on the same git repo and A pushes a change on a feature branch: A-feature to the repo BEFORE B, B now needs to do a pull before he can push.

But where are the exact condition for this described? E.g. does it apply to any change on any branch pushed to the repo? Or is it only if A and B are pushing to the same branch? Meaning that B could push to B-feature even though A just pushed on A-feature before him?

Upvotes: 5

Views: 6841

Answers (3)

Philipp
Philipp

Reputation: 69763

Every branch in Git is a chronological sequence of commits.

When you want to push a commit which is not based on the latest commit of that branch, you need to pull the intermediate commits first (which might involve manual merging).

This is only an issue when multiple users push to the same branch. When each user is working separately on a personal branch, they will never have to pull before pushing. Unless, of course, they intentionally want to merge the branch of someone else.

Upvotes: 3

VonC
VonC

Reputation: 1329572

Meaning that B could push to B-feature even though A just pushed on A-feature before him?

Yes. The warning you get is only when you are pushing to a branch updated by someone else:

hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Merge the remote changes (e.g. 'git pull')
hint: before pushing again.

The only alternative to a git pull would be a git push --force (which would overwrite the history published by A with B's, if B were to push on A-feature, and that is bad.).
See "git push --force, behind the scenes".

If nobody but B is working on B-feature, no pull is needed when B wants to push the local B-feature branch to the upstream repo: the push will be a fast-forward one: you are adding new commits on top of the remote branch.

Upvotes: 4

Nic Wortel
Nic Wortel

Reputation: 11423

The reason why B would need to pull in A's changes before he (or she) can push their own changes to that same branch, is that otherwise B would be rewriting history (removing A's commits in favor of their own), and A's commits (which are not part of B's local branch) would be lost.

This is only the case if you push to the same branch, so yes, B could push to another branch without having to pull A's commits first. In that case, the merging of A's and B's commits will take place later, when their branches are merged.

If you do want to push to the remote branch even though it contains commits that are not in your local branch, you can instruct git not to warn you and to continue with the push anyway, using git push --force (or git push -f). However, be careful, as in most cases (especially when you're working together with other people) it is not advisable to do so. The commits that are not in your local branch, will be removed from the remote branch.

Upvotes: 3

Related Questions