adamreisnz / replace-in-file

A simple utility to quickly replace contents in one or more files
580 stars 65 forks source link

Using CLI with RegExp and a config file in version 8 #197

Closed elchininet closed 3 months ago

elchininet commented 3 months ago

Hi there,

I am trying to update to version 8 one of my repos. I have converted the config file to JSON, double escaped the escaped characters and added the --isRegex flag. But I am receiving the next error:

TypeError: from.replace is not a function
    at main (file:///xxx/node_modules/replace-in-file/bin/cli.js:37:24)
error Command failed with exit code 1.

I have prepared a minimum reproducible repo so maybe you can spot what is the issue there.

  1. Just run yarn replace first (it runs without issues and replace the string in the file)
  2. Then try to run yarn replace-regexp

Could you indicate if I am missing something here?

Regards

adamreisnz commented 3 months ago

Thank you, I'll have a look shortly!

adamreisnz commented 3 months ago

I think if you are using a regex in the JSON config now, then you don't need to use the --isRegex flag in addition, as this will automatically be detected if you are using. It should only be necessary when passing the from parameter via CLI argument as well. I will update the readme to clarify that and update the code to handle that better.

Try not using the --isRegex flag and let me know if that works.

I have updated the readme accordingly and released a new version 8.0.2 to better handle this.

elchininet commented 3 months ago

Hi @adamreisnz,

And how is detected that I am writing a regular expression?

The config was a Node.js module before, so it was possible to write the from parameter as a string or as a regular expression, but it is a JSON file now, so it is only possible to write a string. I though that the intention of the --isRegex flag was precissely that, to know that I am not intending to search a string but a regular expression no mattering if it came from the CLI parameters or from the config.

Just check the code in the minimum reproducible repo and remove the --isRegex flag, you will not receive any error but there will not be any changes then because the string is not found in the file:

Replacing '/\/\w{3} \d{3}\/g/' with 'replaced'
No files were changed
✨  Done in 0.15s.

If I try to use only CLI parameters, removing completely the JSON config, it works as expected.

elchininet commented 3 months ago

I am seeing that you are checking if the from parameter from the config matches a regexp, and convert it to a regexp then. I think that you need to do the same that you are doing here, because the resulting regexp will not be right in that case:

// correct
new RegExp('\\w+') // /\w+/

// incorrect
new RegExp('/\\w+/') // /\/\w+\//
adamreisnz commented 3 months ago

Ahh, yes, gotcha, thank you. Have fixed in 8.0.3

elchininet commented 3 months ago

Thanks @adamreisnz, Let me update it 👍