Today I did a refactoring wich required me to do a change in many JS files. I wanted to change this:

<WebPageWrapper orderStoreData={props.orderStoreData}>

To be this:

<WebPageWrapper showOrderLockedModal={props.orderStoreData.showOrderLockedModal} showInvalidOrderModal={props.orderStoreData.showInvalidOrderModal}>

First I needed a list of all the files containing the line of code. Let’s use grep for this!

$ grep -r "<WebPageWrapper" frontend/

Grep returns the filename in the first column, then the matched text in the second column. Let’s use awk to extract the first column!

$ grep -r "<WebPageWrapper" frontend/ | awk '{print $1}' | sed s/://

I also used sed at the end to remove the trailing colon after each filename.

Now we have a list of all the files we need to edit. Next step is to do the actual refactoring. Let’s use sed again to transform text:

$ sed s/orderStoreData\=\{props.orderStoreData\}/showOrderLockedModal\=\{props.orderStoreData.showOrderLockedModal\}\ showInvalidOrderModal\=\{props.orderStoreData.showInvalidOrderModal\}/ FILENAME

Sed takes a regex and a filename as input. It outputs the transformed text, and keeps the original file. To edit the file we can pass in the -i parameter (i stands for In place edit). A backupfile is created with the file extension that is passed in as a parameter. If empty string is added, no backup is made. We don’t need any backup because we have git:

$ sed -i "" 's/orderStoreData\={props.orderStoreData}/showOrderLockedModal\=\{props.orderStoreData.showOrderLockedModal\}\ showInvalidOrderModal\=\{props.orderStoreData.showInvalidOrderModal\}/' frontend/js/components/AccessoryDetails/AccessoryDetailsPage.jsx

Now lets do the refactoring to every file that has a match. Let’s combine our two lines of code with xargs. xargs is a pretty useful tool. It transform the input on stdin and pass it as arguments to another application. This is how it looks in use:

$ grep -r "<WebPageWrapper" frontend/ | awk '{print $1}' | sed s/:// | xargs -J @ sed -i "" 's/orderStoreData\={props.orderStoreData}/showOrderLockedModal\=\{props.orderStoreData.showOrderLockedModal\}\ showInvalidOrderModal\=\{props.orderStoreData.showInvalidOrderModal\}/' @

These commands most likely took me more time to write than it would have taken to manually refactor the code. But I learned more doing it this way!

Have a nice weekend!