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

     1  // Copyright (c) 2022, 2024, 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  }
    40  
    41  // GetAllDirectoriesAndFiles requires a root directory and returns the directories and filenames for all directories and files within a root directory
    42  func GetAllDirectoriesAndFiles(rootDirectory string) (fileMatches []string, err error) {
    43  	if len(rootDirectory) == 0 {
    44  		return nil, errors.New("GetMatchingFiles requires a rootDirectory")
    45  	}
    46  	walkFunc := func(fileName string, fileInfo os.FileInfo, err error) error {
    47  		if fileName == rootDirectory {
    48  			return nil
    49  		}
    50  		fileMatches = append(fileMatches, fileName)
    51  		return nil
    52  	}
    53  
    54  	err = filepath.Walk(rootDirectory, walkFunc)
    55  	return fileMatches, err
    56  }