github.com/aristanetworks/goarista@v0.0.0-20240514173732-cca2755bbd44/modroot/modroot.go (about) 1 // Copyright (c) 2020 Arista Networks, Inc. 2 // Use of this source code is governed by the Apache License 2.0 3 // that can be found in the COPYING file. 4 5 package modroot 6 7 import ( 8 "os" 9 "path/filepath" 10 ) 11 12 var modRoot string 13 14 // Path returns the returns the module root, as a better alternative to os.Getenv("GOPATH") 15 func Path() string { 16 if modRoot != "" { 17 return modRoot 18 } 19 dir, err := os.Getwd() 20 if err != nil { 21 panic(err) 22 } 23 for { 24 if fi, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil && !fi.IsDir() { 25 modRoot = dir 26 return dir 27 } 28 d := filepath.Dir(dir) 29 if d == dir { 30 break 31 } 32 dir = d 33 } 34 panic("no module root found!") 35 }