"Scans" a Node.FS.Dir for its in-memory entries.
493186
def scan_in_memory(node, env, path=()):
    
    try:
        entries = node.entries
    except AttributeError:
        # It's not a Node.FS.Dir (or doesn't look enough like one for
        # our purposes), which can happen if a target list containing
        # mixed Node types (Dirs and Files, for example) has a Dir as
        # the first entry.
        return []
    entry_list = sorted(filter(do_not_scan, list(entries.keys())))
    return [entries[n] for n in entry_list]
682477
function scanSourceDir() {
		var directoryLen = srcDirectory.length;

		glob.sync(srcDirectory + '/**/*.js').forEach(function(filename) {
			var module = require(filename);

			// Remove the srcDirectory from the file name
			// We don't want that to be part of the module ID
			var moduleFilename = filename.substr(directoryLen+1);
			var newMapping = buildMapping(module, moduleFilename);
			mappings[newMapping.normId.id] = newMapping;
		});
	}
787983
function readDir(path, callback) {
  nodeFs.readdir(path, function (err, names) {
    if (err) {
      if (err.code === "ENOENT") return callback();
      return callback(err);
    }
    return callback(null, names);
  });
}
514042
function scanTreeForNodesModules(moduleName) {
    var dir = settings.coreNodesDir;
    var results = [];
    var userDir;

    if (settings.userDir) {
        userDir = path.join(settings.userDir,"node_modules");
        results = scanDirForNodesModules(userDir,moduleName);
        results.forEach(function(r) { r.local = true; });
    }

    if (dir) {
        var up = path.resolve(path.join(dir,".."));
        while (up !== dir) {
            var pm = path.join(dir,"node_modules");
            if (pm != userDir) {
                results = results.concat(scanDirForNodesModules(pm,moduleName));
            }
            dir = up;
            up = path.resolve(path.join(dir,".."));
        }
    }
    return results;
}
1254020
function readDirectoryFiles(directory) {
  return new Promise((resolve, reject) => {
    fs.readdir(directory, (err, files) => {
      if (err) {
        reject(err);
        return;
      }

      const isFile = fileName => readFileStats(path.join(directory, fileName))
        .then((fstat) => {
          if (fstat.isFile()) {
            return fileName;
          }
          return null;
        });

      Promise.all(files.map(isFile))
        .then(fileList => resolve(fileList.filter(f => f !== null)))
        .catch(reject);
    });
  });
}
670170
function(fn) {
      var visitedDumps = new WeakSet();

      function visit(dump) {
        if (visitedDumps.has(dump))
          return;

        // If this dumps owns another dump which hasn't been visited yet, then
        // wait for this dump to be visited later.
        if (dump.owns !== undefined && !visitedDumps.has(dump.owns.target))
          return;

        // If this dump's parent hasn't been visited yet, then wait for this
        // dump to be visited later.
        if (dump.parent !== undefined && !visitedDumps.has(dump.parent))
          return;

        // Actually visit the current memory allocator dump.
        fn.call(this, dump);
        visitedDumps.add(dump);

        // Visit owners after the dumps they own.
        dump.ownedBy.forEach(function(ownershipLink) {
          visit.call(this, ownershipLink.source);
        }, this);

        // Visit children after parents.
        dump.children.forEach(visit, this);
      }

      this.iterateAllRootAllocatorDumps(visit);
    }
997946
function findSync(dir, callback) {
	var rootStat = fs.statSync(dir);
	if (!rootStat.isDirectory()) {
		if (callback) callback(dir, rootStat);
		return [dir];
	}

	return fs.readdirSync(dir).reduce(function(files, file) {
		var p = path.join(dir, file),
			stat = fs.statSync(p);
		if (callback) callback(p, stat);
		files.push(p);

		if (stat.isDirectory()) {
			files.push.apply(files, findSync(p, callback));
		}

		return files;
	}, []);
}
401292
function getExternals() {
    var fs = require('fs');
    var nodeModules = {};

    fs.readdirSync('node_modules').forEach(function (module) {
      if (module !== '.bin') {
        nodeModules[module] = true;
      }
    });

    var nodeModulesTransform = function(context, request, callback) {
      // search for a '/' indicating a nested module
      var slashIndex = request.indexOf("/");
      var rootModuleName;
      if (slashIndex == -1) {
        rootModuleName = request;
      } else {
        rootModuleName = request.substr(0, slashIndex);
      }

      // Match for root modules that are in our node_modules
      if (nodeModules.hasOwnProperty(rootModuleName)) {
        callback(null, "commonjs " + request);
      } else {
        callback();
      }
    };
    return nodeModulesTransform;
}
401807
private static Collection<Path> findFiles(FileSystem fs, final String contains) throws IOException {
        final ArrayList<Path> rv = new ArrayList<>();
        Iterator<Path> dirs = fs.getRootDirectories().iterator();
        Files.walkFileTree(dirs.next(), new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
                if (file.toString().contains(contains)) {
                    rv.add(file);
                }
                return FileVisitResult.CONTINUE;
            }
        });
        if (dirs.hasNext()) {
            // There is more than one root directory.
            throw new IOException("FileSystem had more than one root directory: " + fs);
        }
        return rv;
    }
859209
def poll(self, force_rescan = False):
      """"""
      # Check for new, deleted, and rotated files.
      if force_rescan or time.time() > self._last_scan + self._interval:
         self._rescan(skip_to_end = False)
         self._last_scan = time.time()

      filereaders = {}
      for path, tailedfile in self._tailedfiles.iteritems():
         filereaders[path] = tailedfile.readlines()

      # One line is read from each file in turn, in an attempt to read
      # from all files evenly. They'll be in an undefined order because
      # of using a dict for filereaders, but that's not a problem
      # because some entropy here is desirable for evenness.
      while len(filereaders) > 0:
         for path in filereaders.keys():
            lines = filereaders[path]
            try:
               line, offset = lines.next()
            except StopIteration:
               # Reached end the of this file.
               del filereaders[path]
               break
            
            yield (path, offset), line
305357
@Override
    public void scanDirectoryNoResults(
            File directory, FileFilter fileFilter, Function<Resource, ?> fileProcessor) {
        this.scanDirectory(directory, null, fileFilter, fileProcessor);
    }
467657
function getModulesByDir (dir, scope = '') {
  const nodeModulesDir = getNodeModulesDir()
  const results = []
  const modules = fs.readdirSync(dir)

  if (!modules.length) {
    return results
  }

  modules.forEach(module => {
    if (module.startsWith('.')) {

    } else if (module.startsWith('@')) {
      const subDir = path.join(nodeModulesDir, module)
      const subModules = getModulesByDir(subDir, module)
      Array.prototype.push.call(results, ...subModules)
    } else {
      results.push(scope ? `${scope}/${module}` : module)
    }
  })

  return results
}
1130773
function listModulesInDirectory(modulesDir) {
    const log = debug('phantomas:modules');
    log('Getting the list of all modules in ' + modulesDir);

    // https://nodejs.org/api/fs.html#fs_fs_readdirsync_path_options
    var ls = fs.readdirSync(modulesDir),
        modules = [];

    ls.forEach(function(entry) {
        // First check whether an entry is a directory, than check if it contains a module file
        // https://nodejs.org/api/fs.html#fs_fs_existssync_path
        if (fs.existsSync(modulesDir + '/' + entry + '/' + entry + '.js')) {
            modules.push(entry);
        }
    });

    return modules.sort();
}
579822
function blockChecksums(fs, path, size, callback) {
  var cache = {};

  fs.readFile(path, function (err, data) {
    if (!err) {
      // cache file
      cache[path] = data;
    } else if (err && err.code === 'ENOENT') {
      cache[path] = [];
    } else {
      return callback(err);
    }

    var length = cache[path].length;
    var incr = size;
    var start = 0;
    var end = incr > length ? length : incr;
    var blockIndex = 0;
    var result = [];
    var chunk;
    var weak;
    var strong;

    while (start < length) {
      chunk  = cache[path].slice(start, end);
      weak   = calcWeak32(chunk).sum;
      strong = md5sum(chunk);

      result.push({
        index: blockIndex,
        weak: weak,
        strong: strong
      });
      // update slice indices
      start += incr;
      end = (end + incr) > length ? length : end + incr;
      // update block index
      blockIndex++;
    }

    callback(null, result);
  });
}
840294
function(dir) {

        // Return if the node_modules directory doesn't exist.
        try {
          FS.statSync(dir);
        } catch (e) {return;}

        // Check each direcory for a monitor-dashboard app
        FS.readdirSync(dir).forEach(function(moduleName) {

          // See if this is a monitor app, and load if it is
          // then load sub-modules
          var moduleDir = dir + '/' + moduleName;
          if (testAppDir(moduleDir) || moduleName === 'monitor') {

            // If it is a monitor-app, process any sub node_modules
            loadNodeModulesDir(moduleDir + '/node_modules');
          }
        });
      }
1271127
function getdirFiles(dir, prefix = '') {
  dir = path.normalize(dir);
  if (!fs.existsSync(dir)) return [];
  const files = fs.readdirSync(dir);
  let result = [];
  files.forEach(item => {
    const currentDir = path.join(dir, item);
    const stat = fs.statSync(currentDir);
    if (stat.isFile()) {
      result.push(path.join(prefix, item));
    } else if (stat.isDirectory()) {
      const cFiles = getdirFiles(currentDir, path.join(prefix, item));
      result = result.concat(cFiles);
    }
  });
  return result;
}
53296
private void scanDirRecursively(final File dir, final LogNode log) {
        if (skipClasspathElement) {
            return;
        }
        // See if this canonical path has been scanned before, so that recursive scanning doesn't get stuck in an
        // infinite loop due to symlinks
        String canonicalPath;
        try {
            canonicalPath = dir.getCanonicalPath();
            if (!scannedCanonicalPaths.add(canonicalPath)) {
                if (log != null) {
                    log.log("Reached symlink cycle, stopping recursion: " + dir);
                }
                return;
            }
        } catch (final IOException | SecurityException e) {
            if (log != null) {
                log.log("Could not canonicalize path: " + dir, e);
            }
            return;
        }

        final String dirPath = dir.getPath();
        final String dirRelativePath = ignorePrefixLen > dirPath.length() ? "/" //
                : dirPath.substring(ignorePrefixLen).replace(File.separatorChar, '/') + "/";

        if (nestedClasspathRootPrefixes != null && nestedClasspathRootPrefixes.contains(dirRelativePath)) {
            if (log != null) {
                log.log("Reached nested classpath root, stopping recursion to avoid duplicate scanning: "
                        + dirRelativePath);
            }
            return;
        }

        // Whitelist/blacklist classpath elements based on dir resource paths
        checkResourcePathWhiteBlackList(dirRelativePath, log);
        if (skipClasspathElement) {
            return;
        }

        final ScanSpecPathMatch parentMatchStatus = scanSpec.dirWhitelistMatchStatus(dirRelativePath);
        if (parentMatchStatus == ScanSpecPathMatch.HAS_BLACKLISTED_PATH_PREFIX) {
            // Reached a non-whitelisted or blacklisted path -- stop the recursive scan
            if (log != null) {
                log.log("Reached blacklisted directory, stopping recursive scan: " + dirRelativePath);
            }
            return;
        }
        if (parentMatchStatus == ScanSpecPathMatch.NOT_WITHIN_WHITELISTED_PATH) {
            // Reached a non-whitelisted and non-blacklisted path -- stop the recursive scan
            return;
        }

        final File[] filesInDir = dir.listFiles();
        if (filesInDir == null) {
            if (log != null) {
                log.log("Invalid directory " + dir);
            }
            return;
        }
        Arrays.sort(filesInDir);
        final LogNode subLog = log == null ? null
                // Log dirs after files (addWhitelistedResources() precedes log entry with "0:")
                : log.log("1:" + canonicalPath, "Scanning directory: " + dir
                        + (dir.getPath().equals(canonicalPath) ? "" : " ; canonical path: " + canonicalPath));

        // Only scan files in directory if directory is not only an ancestor of a whitelisted path
        if (parentMatchStatus != ScanSpecPathMatch.ANCESTOR_OF_WHITELISTED_PATH) {
            // Do preorder traversal (files in dir, then subdirs), to reduce filesystem cache misses
            for (final File fileInDir : filesInDir) {
                // Process files in dir before recursing
                if (fileInDir.isFile()) {
                    final String fileInDirRelativePath = dirRelativePath.isEmpty() || "/".equals(dirRelativePath)
                            ? fileInDir.getName()
                            : dirRelativePath + fileInDir.getName();

                    // Whitelist/blacklist classpath elements based on file resource paths
                    checkResourcePathWhiteBlackList(fileInDirRelativePath, subLog);
                    if (skipClasspathElement) {
                        return;
                    }

                    // If relative path is whitelisted
                    if (parentMatchStatus == ScanSpecPathMatch.HAS_WHITELISTED_PATH_PREFIX
                            || parentMatchStatus == ScanSpecPathMatch.AT_WHITELISTED_PATH
                            || (parentMatchStatus == ScanSpecPathMatch.AT_WHITELISTED_CLASS_PACKAGE
                                    && scanSpec.classfileIsSpecificallyWhitelisted(fileInDirRelativePath))) {
                        // Resource is whitelisted
                        final Resource resource = newResource(fileInDirRelativePath, fileInDir);
                        addWhitelistedResource(resource, parentMatchStatus, subLog);

                        // Save last modified time  
                        fileToLastModified.put(fileInDir, fileInDir.lastModified());
                    } else {
                        if (subLog != null) {
                            subLog.log("Skipping non-whitelisted file: " + fileInDirRelativePath);
                        }
                    }
                }
            }
        } else if (scanSpec.enableClassInfo && dirRelativePath.equals("/")) {
            // Always check for module descriptor in package root, even if package root isn't in whitelist
            for (final File fileInDir : filesInDir) {
                if (fileInDir.getName().equals("module-info.class") && fileInDir.isFile()) {
                    final Resource resource = newResource("module-info.class", fileInDir);
                    addWhitelistedResource(resource, parentMatchStatus, subLog);
                    fileToLastModified.put(fileInDir, fileInDir.lastModified());
                }
            }
        }
        // Recurse into subdirectories
        for (final File fileInDir : filesInDir) {
            if (fileInDir.isDirectory()) {
                scanDirRecursively(fileInDir, subLog);
                // If a blacklisted classpath element resource path was found, it will set skipClasspathElement
                if (skipClasspathElement) {
                    if (subLog != null) {
                        subLog.addElapsedTime();
                    }
                    return;
                }
            }
        }

        if (subLog != null) {
            subLog.addElapsedTime();
        }

        // Save the last modified time of the directory
        fileToLastModified.put(dir, dir.lastModified());
    }