0

I have a PR with 100 commits, which will be submitted as a number of smaller PRs.

At the bottom of the PR stack, I chose a variable name that I now find odd, and would like to change it throughout each commit, but don't want to tediously resolve merge conflicts everywhere.

Is there a way to automate this, using some cli commands to search+replace the variable name?

Devin Rhode
  • 23,026
  • 8
  • 58
  • 72
  • Is this not the same question as https://stackoverflow.com/q/73981158/112968? – knittl Jan 14 '23 at 10:30
  • There are some similarities indeed. That other question is focused on eliminating a string/variable name, where the programmer needs to manually change code. This q/a is focused on doing a fully automated rename. More detail included on other answer. – Devin Rhode Jan 15 '23 at 03:49

1 Answers1

0

Here's one huge, ugly, but magical command:

WARNING: IF YOU HAVE FILE NAMES WITH SPACES IN THEM, THIS WILL ABSOLUTELY WRECK YOUR HISTORY.

git fetch && git rebase --empty=drop --exec "ag -0 -l 'YourOldUndesirableString' | xargs -0 sed -ri.bak -e 's/YourOldUndesirableString/YourShinyNewString/g'; git clean -f '**/*.bak'; git add .; yarn prettier --write \$(git diff HEAD^..HEAD --name-only) && git add . && git commit --amend --no-verify --no-edit" --strategy recursive --strategy-option theirs origin/master

  • The ag command is the_silver_searcher, brew install the_silver_searcher
  • This command is generally suited for osx.
  • Replace YourOldUndesirableString and YourShinyNewString with your actual strings
  • Be sure to replace <your-base-sha> with something like 1a2s3d4f
  • Note 90% of this command is inside a rebase --exec "string", maybe there's a way to avoid passing a huge string to git rebase --exec, allowing for better formatting of this code.
Devin Rhode
  • 23,026
  • 8
  • 58
  • 72
  • --diff-filter=d means "exclude deleted files": stackoverflow.com/a/71190099/565877 – – Devin Rhode Oct 05 '22 at 02:18
  • Related: rebase over mass formatting via prettier without merge conflicts: https://stackoverflow.com/questions/71812872/how-to-rebase-when-prettier-formatting-was-applied-to-whole-project/73955601#73955601 – Devin Rhode Oct 05 '22 at 03:28
  • curious you must have a reason for it but... why not just add 101st commit that does the renaming? – smbl Oct 05 '22 at 03:35
  • Easier to read through commit log if there's consistent names across everything. Alternatively, could also just not rename stuff. – Devin Rhode Oct 05 '22 at 23:10