TIL: Dropping commits and search replace

I have been working on a project where my access rights to the original repo have recently changed. Before, I was able to push directly to the repo. Now, I am pushing changes as an OSS Citizen and making pull requests from a fork.

This means that I needed to pull my original WIP branch into my local fork, continue making changes and then push it to a new pull request.

However, as I was trying to keep things up to date, a rebase from trunk polluted my forked PR with ~260 commits which I didn’t need 🙈

Stackoverflow to the rescue! I found a similar question which suggested running git rebase -i HEAD~n.

When I ran git rebase -i HEAD~270, vi opened the file with the listed commits. That’s when reality hit. I would need to make ~260 edits to change each pick to drop. There had to be a better way.

There is! vi has a search and replace function.

To search and replace for a single instance of a string run this: :s/search-key/replace-key. It will replace the first instance in the file.

To search and replace for multiple instances of a string, add in %

The command now becomes :%s/search-key/replace-key

So in my case, I ran :%s/pick/drop

This allowed me to mark all of the commits as dropped and then go back and manually select the 10ish commits I wanted to keep back to pick.

I finished up the process by running git push --force (you could also use --force-with-lease).

Now my PR is cleaned up and ready for review.

Something to consider for the future, if I dropped a commit I actually needed, how would I get it back?

Comments

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.