Recently on our team chat: “I removed the remote git branch and pushed again”. “Remove” was not necessary, he could have used “git push –force” or better “git push –force-with-lease” instead.
The normal “git pushed” only works when the remote branch is contained in your local branch or in other words if your local branch is the same or ahead of the remote branch. When you still want to “overwrite” the remote branch with your local branch, use the “–force” option or the “–force-with-lease”.
When you collaborate with other team members on a remote branch, git push with force option may overwrite their work. “–force-with-lease” makes git check that the remote branch is in the state we expect it to be in before pushing the local branch, so you wouldn’t destroy work that you don’t know of.
We need to force push when
- we changed our local branch history by rebasing or amanding
- we need to “reset” the remote branch to our local branch
If you need to “overwrite” a remote branch with your local branch, use the “–force-with-lease” option.
Say your git repo consists of a subdirectory “app” and a subdirectory “database” (or “frontend” and “backend” or “team-a” and “team-b”) and you realize each directories content should be in its own repository. Here is how to split the repo.
To create a repo that consists of the content of the “database” dir and its history, execute
git filter-branch --prune-empty --tag-name-filter cat --subdirectory-filter database -- --all
and then push it to a new remote:
git remote rename origin old-origin
git remote add origin <new-remote>
git push -u origin --all
git push -u origin --tags
This is what Gitlab states on a newly created project page. However in
git push -u origin --all “-all” should be replaced with “–mirror” because “-all” pushes all local branches only so you would need to checkout all branches you want to keep. “–mirror” pushes remote branches, too.
In the same fashion apply “filter-branches” to the “app” directory.
There is a nice article that compares several git workflows:
- Centralized workflow
- Feature branch workflow
- Gitflow workflow
- Forking workflow
I admit I don’t use git on a daily basis. Therefore I value they show the git commands.
At work we use trunk based development.