ryanmcgrath / wrench-js

Recursive file operations in Node.js
MIT License
435 stars 71 forks source link

Filtering files and directories in copyDirSyncRecursive() #30

Closed donaldpipowitch closed 12 years ago

donaldpipowitch commented 12 years ago

Hi Ryan!

First: Thank you for wrench.

I just wanted to ask if you could enhance the copyDirSyncRecursive function with optional filtering? Currently I hacked something together which looks like this:

Before "var currFile = fs.lstatSync(sourceDir + "/" + files[i]);" in copyDirSyncRecursive I placed the line:

if(opts.filter && files[i].match(opts.filter)) continue;

opts.filter holds a RegExp which could look like this: /^CVS$|.idea$|.DS_Store$/

That's all! Just one line and a new property in the opts object.

I use a helper function to create my RegExp before I pass the RegExp into the opts object. My helper function looks basically like this:

        var filterArray = ['CVS', '*.idea', '*.DS_Store'];
        filterArray.forEach(function(value, index, array) {
            // file extension
            if(value.match(/^\*\./))   // /^\*/ searches for '*.' (\*) in the beginning (^)
                value = value.replace(/^\*/m, '');  // removes leading '*' for file extension
            else
                value = '^' + value;    // add leading ^for directories and files
            value += '$';   // append $ for file extensions, files and directories
            array[index] = value;
        });
        var filterRegExp = new RegExp(config.filter.join('|'));

        wrench.copyDirSyncRecursive(
            inputPath,
            outputPath,
            { filter: filterRegExp }
        );

You could inline the helper function so opts.filter can be a RegExp or an Array.

What do you think?

millermedeiros commented 12 years ago

I have something similar on this Gist, check copyFilesToDeploy() and filterFiles(). Not sure if that is outside the scope of wrench (since the project description only says that it's about recursive file operations).

ryanmcgrath commented 12 years ago

If people find it useful I'm not against having it as an option. Feel free to make a pull request. ;)