filter a dir based on filter rules

@param {String}  dir
@param {Array}   rules
@param {Array}   root
@param {Boolean} included
@return {Promise}
431669
function listdir(dir, rules, root, included) {
  return fs.readdir(dir)
  .then(function(files) {
    return when.all(files.map(function(f) {
      f = path.join(dir, f);
      return when(fs.stat(f), function(stat) {
        return {
          path: f,
          isDirectory: stat.isDirectory()
        };
      });
    }));
  })
  .then(function(arr) {
    var files = [];
    var subdirs = [];
    arr.forEach(function(e) {
      if (e.isDirectory) {
        subdirs.push(e.path);
      } else {
        files.push(e.path);
      }
    });
    files = files.filter(function(f) {
      return filter(f, rules, root, false, included);
    });
    return when.all(subdirs.map(function(d) {
      return listdir(d, rules, root, filter(d, rules, root, true, included));
    }))
    .then(function(list) {
      list = list.reduce(function(ret, i) {
        return ret.concat(i);
      }, files);
      // include current dir only if at least one of its children is included
      if (list.length > 0) {
        list.push(dir);
      }
      return list;
    });
  });
}
690379
static function findSubdirs( $dir, $includeHidden = false, $excludeItems = false )
    {
        return eZDir::findSubitems( $dir, 'd', false, $includeHidden, $excludeItems );
    }
1328787
function stupidDirsExist(dirs) {
  const check = [];
  dirs.forEach((dir) => {
    check.push(dirExist(dir));
  });

  return Promise.all(check).then((results) => {
    // Combine to single object
    return dirs.reduce(function(prev, item, i) {
      prev[item] = !!results[i];

      return prev;
    }, {});
  });
}
1352897
function filterFile(file, callback) {
      // Ensure it matches the extension.
      const correctExtention = path.extname(file) === opts.extname

      // Make sure it has defined files.
      const source = files[file].source || false
      const destination = files[file].destination || '.'
      callback(null, correctExtention && source && destination)
    }
600114
function readDir (dir, regex = /^(?:)$/) {
  return new Promise((resolve, reject) =>
    fs.readdir(dir, (err, files) => err
      ? reject(err)
      : resolve(Promise.all(files.map(checkFileName.bind(null, dir, regex))))))
    .then(values =>
      [].concat(...values)
        .filter(i => i))
}
393037
def _clean_dir(root, keep, exclude_pat):
    '''
    
    '''
    root = os.path.normcase(root)
    real_keep = _find_keep_files(root, keep)
    removed = set()

    def _delete_not_kept(nfn):
        if nfn not in real_keep:
            # -- check if this is a part of exclude_pat(only). No need to
            # check include_pat
            if not salt.utils.stringutils.check_include_exclude(
                    os.path.relpath(nfn, root), None, exclude_pat):
                return
            removed.add(nfn)
            if not __opts__['test']:
                try:
                    os.remove(nfn)
                except OSError:
                    __salt__['file.remove'](nfn)

    for roots, dirs, files in salt.utils.path.os_walk(root):
        for name in itertools.chain(dirs, files):
            _delete_not_kept(os.path.join(roots, name))
    return list(removed)
645528
function RequireFilter(inputTree, options) {
  if (!(this instanceof RequireFilter)) {
    return new RequireFilter(inputTree, options);
  }

  Filter.call(this, inputTree, options); // this._super()

  options = options || {};

  this.inputTree = inputTree;
  this.files = options.files || [];
  this.description = options.description;
  this.amdPackages = options.amdPackages || [];
  this.amdModules = options.amdModules;
  this.excludePaths = options.excludePaths;
}
1045094
function (dirPath) {

		var dirContents = fs.readdirSync(dirPath);
		return dirContents.filter(function (subDirName) {
			// Filter out non-directories.
			var subDirPath = path.join(dirPath, subDirName);
			return fs.lstatSync(subDirPath).isDirectory();
		});
	}
328412
function filter(file) {
    if (files.indexOf(file) !== -1) return false;
    let include = true;
    regexs.forEach((regex) => {
      if (file.search(regex) !== -1) include = false;
    });
    return include;
  }
1108502
def include_file(member,file_filter):
    '''
    '''
    member_path = member.name.replace('.','',1)

    if len(member_path) == 0:
        return False

    # Does the filter skip it explicitly?
    if "skip_files" in file_filter:
        if member_path in file_filter['skip_files']:
            return False

    # Include explicitly?
    if "include_files" in file_filter:
        if member_path in file_filter['include_files']:
            return True

    # Regular expression?
    if "regexp" in file_filter:
        if re.search(file_filter["regexp"],member_path):
            return True
    return False
1215948
function mapDirectory(rootDir, subDir, include, exclude) {
    var dirMap = { "": { subDir: subDir, stats: fs.statSync(path.join(rootDir, subDir)) } };
    mapSubdirectory(rootDir, subDir, "", include, exclude, dirMap);
    return dirMap;

    function mapSubdirectory(rootDir, subDir, relativeDir, include, exclude, dirMap) {
        var itemMapped = false;
        var items = fs.readdirSync(path.join(rootDir, subDir, relativeDir));

        items.forEach(function(item) {
            var relativePath = path.join(relativeDir, item);
            if(!matchGlobArray(relativePath, exclude)) {
                // Stats obtained here (required at least to know where to recurse in directories)
                // are saved for later, where the modified times may also be used. This minimizes
                // the number of file I/O operations performed.
                var fullPath = path.join(rootDir, subDir, relativePath);
                var stats = fs.statSync(fullPath);

                if (stats.isDirectory()) {
                    // Directories are included if either something under them is included or they
                    // match an include glob.
                    if (mapSubdirectory(rootDir, subDir, relativePath, include, exclude, dirMap) ||
                            matchGlobArray(relativePath, include)) {
                        dirMap[relativePath] = { subDir: subDir, stats: stats };
                        itemMapped = true;
                    }
                } else if (stats.isFile()) {
                    // Files are included only if they match an include glob.
                    if (matchGlobArray(relativePath, include)) {
                        dirMap[relativePath] = { subDir: subDir, stats: stats };
                        itemMapped = true;
                    }
                }
            }
        });
        return itemMapped;
    }

    function matchGlobArray(path, globs) {
        return globs.some(function(elem) {
            return minimatch(path, elem, {dot:true});
        });
    }
}
1306844
function load(rulesDir) {
  var newRules = loadRules(rulesDir);
  Object.keys(newRules).forEach(function(ruleId) {
    define(ruleId, newRules[ruleId]);
  });
}
302494
function addAllFilesAndSubdirectories(dir, doneCallback) {
            FileSystem.resolve(dir, function (err, directory) {
                function visitor(entry) {
                    if (entry.isFile) {
                        if (!isFileExcluded(entry)) { // ignore .dotfiles and non-.js files
                            addFilesToTern([entry.fullPath]);
                        }
                    } else {
                        return !isDirectoryExcluded(entry.fullPath) &&
                            entry.name.indexOf(".") !== 0 &&
                            !stopAddingFiles;
                    }
                }

                if (err) {
                    return;
                }

                if (dir === FileSystem.getDirectoryForPath(rootTernDir)) {
                    doneCallback();
                    return;
                }

                directory.visit(visitor, doneCallback);
            });
        }
987054
function getDirectoryTree(dir) {
    const items = [];
    return new Promise(function(resolve) {
        fs.walk(dir)
        .on('data', function (item) {
            items.push(item.path);
        })
        .on('end', function () {
            resolve(items);
        });
    });
}
393870
def and_filter(self, filter_or_string, *args, **kwargs):
        
        self.root_filter.and_filter(filter_or_string, *args, **kwargs)
        return self
896650
function (src, filter) {
    var out = {}, i;
    for (i=0; i<filter.length; i++) {
      if (src[filter[i]] !== undefined) {
        out[filter[i]] = src[filter[i]];
      }
    }
    return out;
  }
1141071
function relative(dir, file) {
    var isDirectory = file.slice(-1) === '/';
    return normalize(path.relative(dir, file)) + (isDirectory? '/': '');
}