github.com/grafana/tanka@v0.26.1-0.20240506093700-c22cfc35c21a/pkg/jsonnet/jpath/jpath.go (about) 1 package jpath 2 3 import ( 4 "os" 5 "path/filepath" 6 ) 7 8 const DefaultEntrypoint = "main.jsonnet" 9 10 // Resolve the given path and resolves the jPath around it. This means it: 11 // - figures out the project root (the one with .jsonnetfile, vendor/ and lib/) 12 // - figures out the environments base directory (usually the main.jsonnet) 13 // 14 // It then constructs a jPath with the base directory, vendor/ and lib/. 15 // This results in predictable imports, as it doesn't matter whether the user called 16 // called the command further down tree or not. A little bit like git. 17 func Resolve(path string, allowMissingBase bool) (jpath []string, base, root string, err error) { 18 root, err = FindRoot(path) 19 if err != nil { 20 return nil, "", "", err 21 } 22 23 base, err = FindBase(path, root) 24 if err != nil && allowMissingBase { 25 base, err = FsDir(path) 26 if err != nil { 27 return nil, "", "", err 28 } 29 } else if err != nil { 30 return nil, "", "", err 31 } 32 33 // The importer iterates through this list in reverse order 34 return []string{ 35 filepath.Join(root, "vendor"), 36 filepath.Join(base, "vendor"), // Look for a vendor folder in the base dir before using the root vendor 37 filepath.Join(root, "lib"), 38 base, 39 }, base, root, nil 40 } 41 42 // Filename returns the name of the entrypoint file. 43 // It DOES NOT return an absolute path, only a plain name like "main.jsonnet" 44 // To obtain an absolute path, use Entrypoint() instead. 45 func Filename(path string) (string, error) { 46 fi, err := os.Stat(path) 47 if err != nil { 48 return "", err 49 } 50 51 if fi.IsDir() { 52 return DefaultEntrypoint, nil 53 } 54 55 return filepath.Base(fi.Name()), nil 56 } 57 58 // Entrypoint returns the absolute path of the environments entrypoint file (the 59 // one passed to jsonnet.EvaluateFile) 60 func Entrypoint(path string) (string, error) { 61 root, err := FindRoot(path) 62 if err != nil { 63 return "", err 64 } 65 66 base, err := FindBase(path, root) 67 if err != nil { 68 return "", err 69 } 70 71 filename, err := Filename(path) 72 if err != nil { 73 return "", err 74 } 75 76 return filepath.Join(base, filename), nil 77 }