Given a pattern and a base, return files that match the glob pattern
    and also contain the base.
19038
def baseglob(pat, base):
    """"""
    return [f for f in glob(pat) if f.startswith(base)]
951424
def _matches(o, pattern):
    """"""
    if not len(o) == len(pattern):
        return False
    comps = zip(o,pattern)
    return all(isinstance(obj,kind) for obj,kind in comps)
1234138
function pglob(pattern, options) {
  return new Promise((resolve, reject) => {
    glob(pattern, options, (error, files) => {
      if (error) {
        return reject(error)
      }
      resolve(files)
    })
  })
}
1298578
def glob_wildcards(pattern: str, files: Optional[List[str]] = None
                  ) -> Dict[str, Union[List[Any], List[str]]]:
    
    pattern = os.path.normpath(pattern)
    if sys.platform == 'win32':
        # we perform path matching with / slash only
        pattern = pattern.replace('\\', '/')
    first_wildcard = re.search("{[^{]", pattern)
    dirname = os.path.dirname(pattern[:first_wildcard.start()]
                             ) if first_wildcard else os.path.dirname(pattern)
    if not dirname:
        dirname = "."

    names = [match.group('name') for match in SOS_WILDCARD.finditer(pattern)]
    res = {x: [] for x in names}
    pattern = re.compile(regex(pattern))

    if files is None:
        files = ((os.path.join(dirpath, f) if dirpath != "." else f)
                 for dirpath, dirnames, filenames in os.walk(dirname)
                 for f in chain(filenames, dirnames))

    for f in files:
        # we perform path matching with only / slash
        match = re.match(pattern, str(f).replace('\\', '/'))
        if match:
            for name, value in match.groupdict().items():
                res[name].append(value)
    return res
592148
def to_filespec(cls, args, root='', exclude=None):
    
    result = {'globs': [os.path.join(root, arg) for arg in args]}
    if exclude:
      result['exclude'] = []
      for exclude in exclude:
        if hasattr(exclude, 'filespec'):
          result['exclude'].append(exclude.filespec)
        else:
          result['exclude'].append({'globs': [os.path.join(root, x) for x in exclude]})
    return result
502420
def file_matches(filename, patterns):
    """"""
    return any(fnmatch.fnmatch(filename, pat)
               or fnmatch.fnmatch(os.path.basename(filename), pat)
               for pat in patterns)
392060
def get_filebase(path, pattern):
    """"""
    # A pattern can include directories
    tail_len = len(pattern.split(os.path.sep))
    return os.path.join(*str(path).split(os.path.sep)[-tail_len:])
475668
def rglob(root, pattern):
    
    # Thanks to Alex Martelli for basics on Stack Overflow
    retlist = []
    if None not in (pattern, root):
        for base, dirs, files in os.walk(root):
            goodfiles = fnmatch.filter(files, pattern)
            retlist.extend(os.path.join(base, f) for f in goodfiles)
    return retlist
897946
def search_file (pattern, f):
    

    fn_matched = False
    contents_matched = False

    # Use mimetypes to exclude binary files where possible
    if not re.match(r'.+_mqc\.(png|jpg|jpeg)', f['fn']):
        (ftype, encoding) = mimetypes.guess_type(os.path.join(f['root'], f['fn']))
        if encoding is not None:
            return False
        if ftype is not None and ftype.startswith('image'):
            return False

    # Search pattern specific filesize limit
    if pattern.get('max_filesize') is not None and 'filesize' in f:
        if f['filesize'] > pattern.get('max_filesize'):
            logger.debug("Ignoring because exceeded search pattern filesize limit: {}".format(f['fn']))
            return False

    # Search by file name (glob)
    if pattern.get('fn') is not None:
        if fnmatch.fnmatch(f['fn'], pattern['fn']):
            fn_matched = True
            if pattern.get('contents') is None and pattern.get('contents_re') is None:
                return True

    # Search by file name (regex)
    if pattern.get('fn_re') is not None:
        if re.match( pattern['fn_re'], f['fn']):
            fn_matched = True
            if pattern.get('contents') is None and pattern.get('contents_re') is None:
                return True

    # Search by file contents
    if pattern.get('contents') is not None or pattern.get('contents_re') is not None:
        if pattern.get('contents_re') is not None:
            repattern = re.compile(pattern['contents_re'])
        try:
            with io.open (os.path.join(f['root'],f['fn']), "r", encoding='utf-8') as f:
                l = 1
                for line in f:
                    # Search by file contents (string)
                    if pattern.get('contents') is not None:
                        if pattern['contents'] in line:
                            contents_matched = True
                            if pattern.get('fn') is None and pattern.get('fn_re') is None:
                                return True
                            break
                    # Search by file contents (regex)
                    elif pattern.get('contents_re') is not None:
                        if re.search(repattern, line):
                            contents_matched = True
                            if pattern.get('fn') is None and pattern.get('fn_re') is None:
                                return True
                            break
                    # Break if we've searched enough lines for this pattern
                    if pattern.get('num_lines') and l >= pattern.get('num_lines'):
                        break
                    l += 1
        except (IOError, OSError, ValueError, UnicodeDecodeError):
            if config.report_readerrors:
                logger.debug("Couldn't read file when looking for output: {}".format(f['fn']))
                return False

    return fn_matched and contents_matched
114861
def grep(pattern, *files_or_paths):
    """"""
    matches = []

    for fop in files_or_paths:
        with fileobj(fop) as fo:
            matches.extend((line for line in fo if re.match(pattern, line)))

    return matches
1039048
def match(self, filename, isdir):
    

    fnmatch = _fnmatch.fnmatch
    ignored = False
    filename = self.convert_path(filename)
    basename = os.path.basename(filename)

    for pattern in self.patterns:
      if pattern.dir_only and not isdir:
        continue
      if (not ignored or pattern.invert) and pattern.match(filename):
        if pattern.invert: # This file is definitely NOT ignored, no matter what other patterns match
          return MATCH_INCLUDE
        ignored = True
    if ignored:
      return MATCH_IGNORE
    else:
      return MATCH_DEFAULT
754391
function globMatch(match, file) {
    var directiveType = match[1];
    var globPattern = match[2]; // relative file

    // require all files under a directory
    if (directiveType.indexOf('_tree') !== -1) {
      globPattern = globPattern.concat('/**/*');
      directiveType = directiveType.replace('_tree', '');
    }

    // require only first level files in a directory
    if (directiveType.indexOf('_directory') !== -1) {
      globPattern = globPattern.concat('/*');
      directiveType = directiveType.replace('_directory', '');
    }

    // Only require and include directives are allowed
    if (directiveType !== 'require' && directiveType !== 'include') {
      return [];
    }

    // Add file extension to glob pattern if not already set
    var jsExt = '.js';
    if (globPattern.substr(globPattern.length-jsExt.length).indexOf(jsExt) !== 0) {
      globPattern += jsExt;
    } 

    // Append the current dir to include so we can match the glob against the file list
    var relativeDir = getRelativeDir(file);
    globPattern = relativeDir+globPattern;

    var possibleIncludes = [];
    _.each(_.keys(allFiles), function(fileName) {
      // Only process files in the current directory. ../ will not work.
      if (fileName.indexOf(relativeDir) !== 0) {
        return;
      }

      possibleIncludes.push(fileName);
    });
    
    return minimatch.match(possibleIncludes, globPattern);
  }
313920
function getSourceFilesFromGlob(globPattern, ignoreGlobs) {
    return new Promise((fulfil, reject) => {
        glob(globPattern, { ignore: ignoreGlobs }, (err, files) => {
            if (err) {
                reject(err);
            } else {
                fulfil(files);
            }
        });
    });
}
82027
function(pattern, callback) {
    glob(pattern, opts, function(err, globbedFiles) {
      if (isArray(globbedFiles) && globbedFiles.length && !err) {
        callback(null, globbedFiles);
      }
      else {
        console.error('The glob pattern ' + JSON.stringify(pattern) + ' did not match any files!');
        callback(null, []);
      }
    });
  }
100035
def match(path, glob):
    
    path_len = len(path)
    glob_len = len(glob)

    ss = -1
    ss_glob = glob
    if '**' in glob:
        ss = glob.index('**')
        if '**' in glob[ss + 1:]:
            raise dpath.exceptions.InvalidGlob("Invalid glob. Only one '**' is permitted per glob.")

        if path_len >= glob_len:
            # Just right or more stars.
            more_stars = ['*'] * (path_len - glob_len + 1)
            ss_glob = glob[:ss] + more_stars + glob[ss + 1:]
        elif path_len == glob_len - 1:
            # Need one less star.
            ss_glob = glob[:ss] + glob[ss + 1:]

    if path_len == len(ss_glob):
        # Python 3 support
        if PY3:
            return all(map(fnmatch.fnmatch, list(map(str, paths_only(path))), list(map(str, ss_glob))))
        else: # Default to Python 2
            return all(map(fnmatch.fnmatch, map(str, paths_only(path)), map(str, ss_glob)))

    return False
926249
def find_file(pattern, path):
    
    for fname in glob.iglob(path):
        with open(fname) as f:
            if re.search(pattern, f.read()):
                return fname
    return
471825
def iterfiles(self, pattern=None, abspath=False):
        
        if pattern is not None:
            globster = Globster([pattern])
        for root, dirs, files in self.walk():
            for f in files:
                if pattern is None or (pattern is not None and globster.match(f)):
                    if abspath:
                        yield os.path.join(root, f)
                    else:
                        yield self.relpath(os.path.join(root, f))