Search And Replace is a powerful tool in the developer toolbelt that can save you time and effort…
if you can formulate the right regular expression.
Search and Transform is a twist on the same concept
but we use a LLM to perform the transformation instead of a simple string replacement.
👩💻 Understanding the Script Code
The script starts by defining its purpose and parameters using the script function. Here, we define the title, description, and the three parameters the script will need: glob to specify the files, pattern for the text to search for, and transform for the desired transformation.
Extracting and Validating Parameters
Next, we extract the pattern, glob, and transform parameters from the environment variables and validate them. If pattern or transform are missing, the script will cancel execution. We then compile the pattern into a regular expression object for later use.
Searching for Files and Matches
Here, we use the grep function from the workspace API to search for files that match the glob pattern and contain the regex pattern.
Transforming Matches
We initialize an object called patches to store the transformations. Then, we loop through each file, read its content, and skip binary files. For each match found in the file’s content, we check if we’ve already computed a transformation for this match to avoid redundant work.
Generating Prompts for Transformations
For each unique match, we generate a prompt using the runPrompt function. In the prompt, we define the task and context for the transformation, specifying that the transformed text should be returned without enclosing quotes. We also define the matched text and the transformation to apply.
Applying the Transformation
We then extract the transformed text from the prompt result and store it in the patches object. Finally, we apply the transformations to the file content using String.prototype.replace.
Saving the Changes
If the file content has changed after applying the transformations, we save the updated content back to the file.
Running the Script
To run this script, you’ll need the GenAIScript CLI. Check out the installation guide if you need to set it up. Once you have the CLI, run the script by executing: