Skip to content

Commit

Permalink
Added support for passing Regex into CLI (#14)
Browse files Browse the repository at this point in the history
* Added support for passing Regex into CLI

This will allow for passing the `from`/`to` parameters as regex in the format `\match\g` through the CLI. If pattern does not match a Regex it will fall back to passing through as a `String`.

* - Fixed style inconsistencies
- Added -isRegex parameter to explicitly state ‘from’ parameter is a regex
- Removed regex support from ‘to’ parameter

* Replaced -isRegex with —isRegex and moved to the end of the param list

* Added line and sample syntax for CLI in README
  • Loading branch information
ryan-codingintrigue authored and adamreisnz committed Feb 21, 2017
1 parent f176f67 commit fbc7de4
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,14 +95,16 @@ catch (error) {
Via CLI:

```sh
replace-in-file from to some/file.js,some/**/glob.js
replace-in-file from to some/file.js,some/**/glob.js [--isRegex]
```

The options `allowEmptyPaths` and `encoding` are supported in the CLI.
In addition, the CLI supports the `verbose` option to list the changed files.

Multiple files or globs can be replaced by providing a comma separated list.

A regular expression may be used for the `from` parameter by specifying the `--isRegex` option.

## License
(MIT License)

Expand Down
15 changes: 14 additions & 1 deletion bin/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,27 @@ if (argv._.length < 3) {
}

//Collect main arguments
const from = argv._.shift();
let from = argv._.shift();
const to = argv._.shift();

//Single star globs already get expanded in the command line
const files = argv._.reduce((files, file) => {
return files.concat(file.split(','));
}, []);

// If the --isRegex flag is passed, send the 'from' parameter
// to the lib as a RegExp object
if (argv.isRegex) {
const flags = from.replace(/.*\/([gimy]*)$/, '$1');
const pattern = from.replace(new RegExp(`^/(.*?)/${flags}$`), '$1');
try {
from = new RegExp(pattern, flags);
}
catch (error) {
console.error('Could not create RegExp from \'from\' parameter', error);
}
}

//Log
console.log(`Replacing '${from}' with '${to}'`);

Expand Down

0 comments on commit fbc7de4

Please sign in to comment.