github.com/diggerhq/digger/libs@v0.0.0-20240604170430-9d61cdf01cc5/digger_config/utils.go (about)

     1  package digger_config
     2  
     3  import (
     4  	"github.com/bmatcuk/doublestar/v4"
     5  	"log"
     6  	"path"
     7  	"path/filepath"
     8  )
     9  
    10  func GetPatternsRelativeToRepo(projectPath string, patterns []string) ([]string, error) {
    11  	res := make([]string, 0)
    12  	for _, pattern := range patterns {
    13  		res = append(res, path.Join(projectPath, pattern))
    14  	}
    15  	return res, nil
    16  }
    17  
    18  func NormalizeFileName(fileName string) string {
    19  	res, err := filepath.Abs(path.Join("/", fileName))
    20  	if err != nil {
    21  		log.Fatalf("Failed to convert path to absolute: %v", err)
    22  	}
    23  	return res
    24  }
    25  
    26  func MatchIncludeExcludePatternsToFile(fileToMatch string, includePatterns []string, excludePatterns []string) bool {
    27  	fileToMatch = NormalizeFileName(fileToMatch)
    28  	for i, _ := range includePatterns {
    29  		includePatterns[i] = NormalizeFileName(includePatterns[i])
    30  	}
    31  	for i, _ := range excludePatterns {
    32  		excludePatterns[i] = NormalizeFileName(excludePatterns[i])
    33  	}
    34  
    35  	matching := false
    36  	for _, ipattern := range includePatterns {
    37  		isMatched, err := doublestar.PathMatch(ipattern, fileToMatch)
    38  		if err != nil {
    39  			log.Fatalf("Failed to match modified files (%v, %v): Error: %v", fileToMatch, ipattern, err)
    40  		}
    41  		if isMatched {
    42  			matching = true
    43  			break
    44  		}
    45  	}
    46  
    47  	for _, epattern := range excludePatterns {
    48  		excluded, err := doublestar.PathMatch(epattern, fileToMatch)
    49  		if err != nil {
    50  			log.Fatalf("Failed to match modified files (%v, %v): Error: %v", fileToMatch, epattern, err)
    51  		}
    52  		if excluded {
    53  			matching = false
    54  			break
    55  		}
    56  	}
    57  
    58  	return matching
    59  }