github.com/grafana/tanka@v0.26.1-0.20240506093700-c22cfc35c21a/pkg/jsonnet/files.go (about)

     1  package jsonnet
     2  
     3  import (
     4  	"os"
     5  	"path/filepath"
     6  
     7  	"github.com/gobwas/glob"
     8  	"github.com/karrick/godirwalk"
     9  )
    10  
    11  // FindFiles takes a file / directory and finds all Jsonnet files
    12  func FindFiles(target string, excludes []glob.Glob) ([]string, error) {
    13  	// if it's a file, don't try to find children
    14  	fi, err := os.Stat(target)
    15  	if err != nil {
    16  		return nil, err
    17  	}
    18  	if fi.Mode().IsRegular() {
    19  		return []string{target}, nil
    20  	}
    21  
    22  	var files []string
    23  
    24  	// godirwalk is faster than filepath.Walk, 'cause no os.Stat required
    25  	err = godirwalk.Walk(target, &godirwalk.Options{
    26  		Callback: func(rawPath string, de *godirwalk.Dirent) error {
    27  			// Normalize slashes for Windows
    28  			path := filepath.ToSlash(rawPath)
    29  
    30  			if de.IsDir() {
    31  				return nil
    32  			}
    33  
    34  			// excluded?
    35  			for _, g := range excludes {
    36  				if g.Match(path) {
    37  					return nil
    38  				}
    39  			}
    40  
    41  			// only .jsonnet or .libsonnet
    42  			if ext := filepath.Ext(path); ext == ".jsonnet" || ext == ".libsonnet" {
    43  				files = append(files, path)
    44  			}
    45  			return nil
    46  		},
    47  		// faster, no sort required
    48  		Unsorted: true,
    49  	})
    50  	if err != nil {
    51  		return nil, err
    52  	}
    53  
    54  	return files, nil
    55  }