Working as a software engineer and a team member can be stressful. There are many changes occurring to a repository and you probably don’t have the time to check all the changes that your teammates have made.
What happens when a file that was merged to master (main if you prefer) has to be removed in order for your branch to be merged? This is the problem I’ve had to solve this week. The file in question existed on my repo but not the prod one since my branch was behind.
TIP: This is a beginner-friendly exercise
Let's get to the terminal and cd in the working directory for the repository. Don't forget to check out the relevant branch.
We first need to search for the commit that first introduced the file
git log --diff-filter=A -- src/unwantedfile.php
The response will be a hash such as this 0833b644fc5765d630c1ddfee07ca2527b727575. We now need to do a reset. What this does is take our git history back in time to the moment before we created the commit.
The response will be a hash such as this 0833b644fc5765d630c1ddfee07ca2527b727575. We now need to do a reset. What this does is take our git history back in time to the moment before we created the commit.
git reset --soft 0833b644fc5765d630c1ddfee07ca2527b727575
We now remove it, this is where it gets interesting.
We now remove it, this is where it gets interesting.
git rm --cached src/unwantedfile.php
The next step is to make a commit but we need to tell git that we've amended something.
The next step is to make a commit but we need to tell git that we've amended something.
git commit --amend
If you see a vim window pop up, don't freak out. Simply type this in :wq
That's it. We can now rejoice and probably get another cup of hot tea. If you're a skeptic like me, run this command to check if the file still exists in the branch.
If you see a vim window pop up, don't freak out. Simply type this in :wq
That's it. We can now rejoice and probably get another cup of hot tea. If you're a skeptic like me, run this command to check if the file still exists in the branch.
git ls-files | grep src/unwantedfile.php
You should have an empty output on the terminal. It now time to push. Doing a git push right here will result in an error that your local branch is behind on a commit.
This is what you should do instead:
You should have an empty output on the terminal. It now time to push. Doing a git push right here will result in an error that your local branch is behind on a commit.
This is what you should do instead:
git push --set-upstream origin myawesomebranch --force
You can now relax. Changes have been committed and pushed to the remote repo.
You can now relax. Changes have been committed and pushed to the remote repo.