for a given path and regexp pattern, return the files that match
546573
def match(Class, path, pattern, flags=re.I, sortkey=None, ext=None):
        """"""
        return sorted(
            [
                Class(fn=fn)
                for fn in rglob(path, f"*{ext or ''}")
                if re.search(pattern, os.path.basename(fn), flags=flags) is not None
                and os.path.basename(fn)[0] != '~'  # omit temp files
            ],
            key=sortkey,
        )
969068
function pathToRegExp(path) {
    if (path instanceof RegExp) {
      return {
        keys: [],
        regexp: path
      };
    }
    if (path instanceof Array) {
      path = '(' + path.join('|') + ')';
    }

    var rtn = {
      keys: [],
      regexp: null
    };

    rtn.regexp = new RegExp((isHashRouter(path) ? '' : '^') + path.replace(/([\/\(]+):/g, '(?:').replace(/\(\?:(\w+)((\(.*?\))*)/g, function (_, key, optional) {
      rtn.keys.push(key);
      var match = null;
      if (optional) {
        match = optional.replace(/\(|\)/g, '');
      } else {
        match = '/?([^/]+)';
      }
      return '(?:' + match + '?)';
    })
    // fix double closing brackets, are there any better cases?
    // make a commit and send us a pull request. XD
    .replace('))', ')').replace(/\*/g, '(.*)') + '((#.+)?)$', 'i');

    return rtn;
  }
1160895
def find_files(args):
    '''
    
    '''
    files_or_dirs = args or ['.']
    filenames = []
    for f in files_or_dirs:
        if path.isdir(f):
            filenames.extend(glob.glob(path.join(f, '**', '*_spec.py'), recursive=True))
        elif path.isfile(f):
            filenames.append(f)
        else:
            raise FileNotFoundError('could not spec file {}'.format(repr(f)))
    return filenames
366501
function extractFilePaths(content, targetPath, opt, tagsRegExp) {
	const files = [];

	const tagMatches = content.match(tagsRegExp.start);
	if (tagMatches) {
		tagMatches.forEach(function (tagMatch) {
			const fileUrl = tagsRegExp.startex.exec(tagMatch)[1];
			const filePath = setFullPath(targetPath, opt.prefix + fileUrl);
			try {
				const fileContent = stripBomBuf(fs.readFileSync(filePath));
				files.push({
					file: new File({
						path: filePath,
						cwd: __dirname,
						base: path.resolve(__dirname, 'expected', path.dirname(filePath)),
						contents: fileContent
					}),
					tags: getRegExpTags(opt, fileUrl)
				});
			} catch (e) {
				if (opt.ignoreError) {
					log(colors.red(filePath + ' not found.'));
				} else {
					throw error(filePath + ' not found.');
				}
			}
			// reset the regex
			tagsRegExp.startex.lastIndex = 0;
		});
	}
	return files;
}
216546
def find(pattern, path='.', exclude=None, recursive=True):
    """"""
    import fnmatch
    import os

    if recursive:
        for root, dirnames, filenames in os.walk(path):
            for pat in _to_list(pattern):
                for filename in fnmatch.filter(filenames, pat):
                    filepath = join(abspath(root), filename)
                    for excl in _to_list(exclude):
                        if excl and fnmatch.fnmatch(filepath, excl):
                            break
                    else:
                        yield filepath
    else:
        for pat in _to_list(pattern):
            for filename in fnmatch.filter(list(path), pat):
                filepath = join(abspath(path), filename)
                for excl in _to_list(exclude):
                    if excl and fnmatch.fnmatch(filepath, excl):
                        break
                    else:
                        yield filepath
631417
def find_files(directory, pattern):
    
    for root, __, files in os.walk(directory):
        for basename in files:
            if fnmatch.fnmatch(basename, pattern):
                filename = os.path.join(root, basename)
                yield filename
999830
def finddirs(pattern, path='.', exclude=None, recursive=True):
    """"""
    import fnmatch
    import os
    if recursive:
        for root, dirnames, filenames in os.walk(path):
            for pat in _to_list(pattern):
                for dirname in fnmatch.filter(dirnames, pat):
                    dirpath = join(abspath(root), dirname)
                    for excl in _to_list(exclude):
                        if excl and fnmatch.fnmatch(dirpath, excl):
                            break
                    else:
                        yield dirpath
    else:
        for pat in _to_list(pattern):
            for dirname in fnmatch.filter(listdirs(path), pat):
                dirpath = join(abspath(path), dirname)
                for excl in _to_list(exclude):
                    if excl and fnmatch.fnmatch(dirpath, excl):
                        break
                else:
                    yield dirpath
143
def match_files(self, matched, unmatched):
        """"""
        for pattern in self.iter():
            pattern.match_files(matched, unmatched)
            if not unmatched:
                # Optimization: If we have matched all files already
                # simply return at this point - nothing else to do
                break
1204066
def _find_paths(self, current_dir, patterns):
        """"""
        pattern = patterns[0]
        patterns = patterns[1:]
        has_wildcard = is_pattern(pattern)
        using_globstar = pattern == "**"

        # This avoids os.listdir() for performance
        if has_wildcard:
            entries = [x.name for x in scandir(current_dir)]
        else:
            entries = [pattern]

        if using_globstar:
            matching_subdirs = map(lambda x: x[0], walk(current_dir))
        else:
            subdirs = [e for e in entries
                       if os.path.isdir(os.path.join(current_dir, e))]
            matching_subdirs = match_entries(subdirs, pattern)

        # For terminal globstar, add a pattern for all files in subdirs
        if using_globstar and not patterns:
            patterns = ['*']

        if patterns:  # we've still got more directories to traverse
            for subdir in matching_subdirs:
                absolute_path = os.path.join(current_dir, subdir)
                for match in self._find_paths(absolute_path, patterns):
                    yield match

        else:  # we've got the last pattern
            if not has_wildcard:
                entries = [pattern + '.wsp', pattern + '.wsp.gz']
            files = [e for e in entries
                     if os.path.isfile(os.path.join(current_dir, e))]
            matching_files = match_entries(files, pattern + '.*')

            for _basename in matching_files + matching_subdirs:
                yield os.path.join(current_dir, _basename)
548674
private function matchByRegex(string $pattern, string $path): array
    {
        $isPatternMatched = (bool) \preg_match_all("~^$pattern$~", $path, $matches);

        if (!$isPatternMatched) {
            return [$isPatternMatched, []];
        }

        foreach ($matches as $k => $match) {
            $match = \array_shift($match);
            if (\is_int($k) || empty($match)) {
                unset($matches[$k]);
                continue;
            }
            $matches[$k] = $match;
        }

        return [$isPatternMatched, $matches];
    }
857717
function getMatches(source, pattern) {
  var matches = [],
      match;

  // Grab all added extensions
  while (match = pattern.exec(source)) {
    matches.push(match[2]);
  }

  return matches;
}
342686
def matchingfiles(self, projectpath):
        """"""
        results = []

        if projectpath[-1] == '/':
            inputpath = projectpath + 'input/'
        else:
            inputpath = projectpath + '/input/'

        for linkf,realf in clam.common.util.globsymlinks(inputpath + '/.*.INPUTTEMPLATE.' + self.id + '.*'):
            seqnr = int(linkf.split('.')[-1])
            results.append( (seqnr, realf[len(inputpath):], self) )
        results = sorted(results)
        if self.unique and len(results) != 1:
            return []
        else:
            return results
634878
def _match_pattern(filename, include, exclude, real, path, follow):
    """"""

    if real:
        symlinks = {}
        if isinstance(filename, bytes):
            curdir = os.fsencode(os.curdir)
            mount = RE_BWIN_MOUNT if util.platform() == "windows" else RE_BMOUNT
        else:
            curdir = os.curdir
            mount = RE_WIN_MOUNT if util.platform() == "windows" else RE_MOUNT

        if not mount.match(filename):
            exists = os.path.lexists(os.path.join(curdir, filename))
        else:
            exists = os.path.lexists(filename)

        if not exists:
            return False
        if path:
            return _match_real(filename, include, exclude, follow, symlinks)

    matched = False
    for pattern in include:
        if pattern.fullmatch(filename):
            matched = True
            break

    if not include and exclude:
        matched = True

    if matched:
        matched = True
        if exclude:
            for pattern in exclude:
                if not pattern.fullmatch(filename):
                    matched = False
                    break
    return matched
1281808
def find_matches(text):
    
    """
    path = os.path.expanduser(text)
    if os.path.isdir(path) and not path.endswith('/'):
        return [ text + '/' ]

    pattern = path + '*'
    is_implicit_cwd = not (path.startswith('/') or path.startswith('./'))
    if is_implicit_cwd:
        pattern = './' + pattern
    rawlist = glob.glob(pattern)
    ret = []
    for fname in rawlist:
        if is_implicit_cwd:
            fname = fname[2:]
        if os.path.isdir(fname):
            ret.append(fname + '/')
        else:
            ret.append(fname)
    return ret
1220846
def find_files(dir_path, extension="*"):
    
    if sys.version_info.major == 3 and sys.version_info.minor >= 5:
        pattern = '/'.join([dir_path, '**', extension])
        for filename in glob.iglob(pattern, recursive=True):
            yield filename
    else:
        for root, dirnames, filenames in os.walk(dir_path):
            for filename in fnmatch.filter(filenames, extension):
                yield os.path.join(root, filename)
504334
def find_macthing_files(match):
    """"""
    last_slash = match.rfind('/')
    if last_slash == -1:
        dirname = '.'
        match_prefix = match
        result_prefix = ''
    else:
        dirname = match[0:last_slash]
        match_prefix = match[last_slash + 1:]
        result_prefix = dirname + '/'
    return [result_prefix + filename for filename in os.listdir(dirname) if filename.startswith(match_prefix)]
283859
function filterPaths(paths, allowed) {
  if (!allowed) { return []; }
  if (!allowed.only.length) { return paths; }

  return paths.filter(
    path => {
      let match = false;

      for (const filter of allowed.only) {
        try {
          switch (typeof filter) {
            case 'function':
              match = filter(path.path);
              break;
            case 'string':
              match = path.path === filter;
              break;
            default:
              match = filter.test(path.path);
         }
        } catch (e) {
          throw new Error(`${ typeof filter } is not an allowed filter type. Must be String, RegExp or Function`);
        }
        if (match) { return match; }
      }
      return match;
    }
  );
}