github.com/verrazzano/verrazzano@v1.7.0/pkg/files/files.go (about)

     1  // Copyright (c) 2022, Oracle and/or its affiliates.
     2  // Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
     3  
     4  package files
     5  
     6  import (
     7  	"errors"
     8  	"fmt"
     9  	"os"
    10  	"path/filepath"
    11  	"regexp"
    12  )
    13  
    14  // GetMatchingFiles returns the filenames for files that match a regular expression.
    15  func GetMatchingFiles(rootDirectory string, fileMatchRe *regexp.Regexp) (fileMatches []string, err error) {
    16  	if len(rootDirectory) == 0 {
    17  		return nil, errors.New("GetMatchingFiles requires a rootDirectory")
    18  	}
    19  
    20  	if fileMatchRe == nil {
    21  		return nil, fmt.Errorf("GetMatchingFiles requires a regular expression")
    22  	}
    23  
    24  	walkFunc := func(fileName string, fileInfo os.FileInfo, err error) error {
    25  		if !fileMatchRe.MatchString(fileName) {
    26  			return nil
    27  		}
    28  		if !fileInfo.IsDir() {
    29  			fileMatches = append(fileMatches, fileName)
    30  		}
    31  		return nil
    32  	}
    33  
    34  	err = filepath.Walk(rootDirectory, walkFunc)
    35  	if err != nil {
    36  		return nil, err
    37  	}
    38  	return fileMatches, err
    39  }