github.com/octohelm/cuekit@v0.0.0-20240424021256-e7df8d743066/pkg/mod/module/util.go (about)

     1  package module
     2  
     3  import (
     4  	"cuelang.org/go/mod/module"
     5  	"io/fs"
     6  	"os"
     7  	"path/filepath"
     8  	"strings"
     9  )
    10  
    11  func OSDirFS(dir string) fs.FS {
    12  	return module.OSDirFS(dir)
    13  }
    14  
    15  func BasePath(mpath string) string {
    16  	base, _, ok := module.SplitPathVersion(mpath)
    17  	if ok {
    18  		return base
    19  	}
    20  	return mpath
    21  }
    22  
    23  func SplitPathVersion(path string) (prefix, version string, ok bool) {
    24  	return module.SplitPathVersion(path)
    25  }
    26  
    27  func SourceLocOfOSDir(dir string) SourceLoc {
    28  	return SourceLoc{
    29  		FS:  OSDirFS(dir),
    30  		Dir: ".",
    31  	}
    32  }
    33  
    34  func WalkCueFile(root string, fromPath string) ([]string, error) {
    35  	files := make([]string, 0)
    36  
    37  	walkSubDir := strings.HasSuffix(fromPath, "/...")
    38  
    39  	if walkSubDir {
    40  		fromPath = fromPath[0 : len(fromPath)-4]
    41  	}
    42  
    43  	start := filepath.Join(root, fromPath)
    44  
    45  	err := filepath.Walk(start, func(path string, info os.FileInfo, err error) error {
    46  		if path == start {
    47  			return nil
    48  		}
    49  
    50  		// skip cue.mod
    51  		if isSubDirFor(path, "cue.mod") {
    52  			return filepath.SkipDir
    53  		}
    54  
    55  		if info.IsDir() {
    56  			// skip sub dir which is cuemod root
    57  			if _, err := os.Stat(filepath.Join(path, fileModule)); err == nil {
    58  				return filepath.SkipDir
    59  			}
    60  			if walkSubDir {
    61  				return nil
    62  			}
    63  			return filepath.SkipDir
    64  		}
    65  
    66  		if filepath.Ext(path) == ".cue" {
    67  			files = append(files, path)
    68  		}
    69  
    70  		return nil
    71  	})
    72  
    73  	if err != nil {
    74  		return nil, err
    75  	}
    76  
    77  	return files, nil
    78  }
    79  
    80  func isSubDirFor(targetPath string, root string) bool {
    81  	targetPath = targetPath + "/"
    82  	root = root + "/"
    83  	return strings.HasPrefix(targetPath, root)
    84  }