Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Passes full file path to the replacement function #67

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 21 additions & 12 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,20 +55,29 @@ module.exports = function(search, replacement, options) {
callback(null, file);
}

if (options && options.skipBinary) {
istextorbinary.isText(file.path, file.contents, function(err, result) {
if (err) {
return callback(err, file);
}
if (options) {
if (options.passFilename && typeof replacement === 'function') {
var userReplacement = replacement;
replacement = function (match) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, this won't work for regex replace. More than one argument is passed to the function, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wanted to deal with this issue by introducing new option passFilename but you're right. The regexp replace mode will be much more useless without passing all original arguments to the replacement callbacks.

userReplacement(match, file.path);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another potential solution would be to call the replacement function in the context of the file object:

userReplacement.apply(file, arguments);
// this.path == the path of the file

Thoughts?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great idea! But maybe it's better and safer to create context object and set its properties explicitly? It will help us with argument immutability.

var context = {
  filepath: file.path
};
userReplacement.apply(context, arguments);

};
}

if (!result) {
callback(null, file);
} else {
doReplace();
}
});
if (options.skipBinary) {
istextorbinary.isText(file.path, file.contents, function(err, result) {
if (err) {
return callback(err, file);
}

return;
if (!result) {
callback(null, file);
} else {
doReplace();
}
});

return;
}
}

doReplace();
Expand Down