Skip to content

Commit

Permalink
Allow copy's filter to return a Promise
Browse files Browse the repository at this point in the history
  • Loading branch information
RyanZim committed Nov 9, 2017
1 parent b72ba64 commit f2c043d
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 4 deletions.
2 changes: 1 addition & 1 deletion docs/copy.md
Expand Up @@ -9,7 +9,7 @@ Copy a file or directory. The directory can have contents. Like `cp -r`.
- `errorOnExist` `<boolean>`: when `overwrite` is `false` and the destination exists, throw an error. Default is `false`.
- `dereference` `<boolean>`: dereference symlinks, default is `false`.
- `preserveTimestamps` `<boolean>`: will set last modification and access times to the ones of the original source files, default is `false`.
- `filter` `<Function>`: Function to filter copied files. Return `true` to include, `false` to exclude.
- `filter` `<Function>`: Function to filter copied files. Return `true` to include, `false` to exclude. Can also return a `Promise` that resolves to `true` or `false` (or pass in an `async` function).
- `callback` `<Function>`

## Example:
Expand Down
13 changes: 13 additions & 0 deletions lib/copy/__tests__/copy.test.js
Expand Up @@ -234,6 +234,19 @@ describe('fs-extra', () => {
})
})

it('allows filter fn to return a promise', done => {
const srcFile1 = path.join(TEST_DIR, '1.css')
fs.writeFileSync(srcFile1, '')
const destFile1 = path.join(TEST_DIR, 'dest1.css')
const filter = s => Promise.resolve(s.split('.').pop() !== 'css')

fse.copy(srcFile1, destFile1, filter, err => {
assert(!err)
assert(!fs.existsSync(destFile1))
done()
})
})

it('should should apply filter recursively', done => {
const FILES = 2
// Don't match anything that ends with a digit higher than 0:
Expand Down
10 changes: 7 additions & 3 deletions lib/copy/copy.js
Expand Up @@ -13,7 +13,7 @@ function copy (src, dest, opts, cb) {
if (typeof opts === 'function' && !cb) {
cb = opts
opts = {}
} else if (typeof opts === 'function' || opts instanceof RegExp) {
} else if (typeof opts === 'function') {
opts = {filter: opts}
}

Expand All @@ -22,6 +22,7 @@ function copy (src, dest, opts, cb) {

opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now
opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber
opts.filter = opts.filter || function () { return true }

// Warn about using preserveTimestamps on 32-bit node
if (opts.preserveTimestamps && process.arch === 'ia32') {
Expand All @@ -47,8 +48,11 @@ function copy (src, dest, opts, cb) {
}

function startCopy (src, dest, opts, cb) {
if (opts.filter && !opts.filter(src, dest)) return cb()
return getStats(src, dest, opts, cb)
Promise.resolve(opts.filter(src, dest))
.then(include => {
if (include) getStats(src, dest, opts, cb)
else cb()
}, error => cb(error))
}

function getStats (src, dest, opts, cb) {
Expand Down

0 comments on commit f2c043d

Please sign in to comment.