github.com/noqcks/syft@v0.0.0-20230920222752-a9e2c4e288e5/syft/pkg/cataloger/golang/options.go (about) 1 package golang 2 3 import ( 4 "os" 5 "path" 6 "strings" 7 8 "github.com/mitchellh/go-homedir" 9 10 "github.com/anchore/syft/internal/log" 11 ) 12 13 const ( 14 defaultProxies = "https://proxy.golang.org,direct" 15 directProxyOnly = "direct" 16 ) 17 18 var ( 19 directProxiesOnly = []string{directProxyOnly} 20 ) 21 22 type GoCatalogerOpts struct { 23 searchLocalModCacheLicenses bool 24 localModCacheDir string 25 searchRemoteLicenses bool 26 proxies []string 27 noProxy []string 28 } 29 30 func (g GoCatalogerOpts) WithSearchLocalModCacheLicenses(input bool) GoCatalogerOpts { 31 g.searchLocalModCacheLicenses = input 32 return g 33 } 34 35 func (g GoCatalogerOpts) WithLocalModCacheDir(input string) GoCatalogerOpts { 36 if input == "" { 37 return g 38 } 39 g.localModCacheDir = input 40 return g 41 } 42 43 func (g GoCatalogerOpts) WithSearchRemoteLicenses(input bool) GoCatalogerOpts { 44 g.searchRemoteLicenses = input 45 return g 46 } 47 48 func (g GoCatalogerOpts) WithProxy(input string) GoCatalogerOpts { 49 if input == "" { 50 return g 51 } 52 if input == "off" { 53 input = directProxyOnly 54 } 55 g.proxies = strings.Split(input, ",") 56 return g 57 } 58 59 func (g GoCatalogerOpts) WithNoProxy(input string) GoCatalogerOpts { 60 if input == "" { 61 return g 62 } 63 g.noProxy = strings.Split(input, ",") 64 return g 65 } 66 67 // NewGoCatalogerOpts create a GoCatalogerOpts with default options, which includes: 68 // - setting the default remote proxy if none is provided 69 // - setting the default no proxy if none is provided 70 // - setting the default local module cache dir if none is provided 71 func NewGoCatalogerOpts() GoCatalogerOpts { 72 g := GoCatalogerOpts{} 73 74 // first process the proxy settings 75 if len(g.proxies) == 0 { 76 goProxy := os.Getenv("GOPROXY") 77 if goProxy == "" { 78 goProxy = defaultProxies 79 } 80 g = g.WithProxy(goProxy) 81 } 82 83 // next process the gonoproxy settings 84 if len(g.noProxy) == 0 { 85 goPrivate := os.Getenv("GOPRIVATE") 86 goNoProxy := os.Getenv("GONOPROXY") 87 // we only use the env var if it was not set explicitly 88 if goPrivate != "" { 89 g.noProxy = append(g.noProxy, strings.Split(goPrivate, ",")...) 90 } 91 92 // next process the goprivate settings; we always add those 93 if goNoProxy != "" { 94 g.noProxy = append(g.noProxy, strings.Split(goNoProxy, ",")...) 95 } 96 } 97 98 if g.localModCacheDir == "" { 99 goPath := os.Getenv("GOPATH") 100 101 if goPath == "" { 102 homeDir, err := homedir.Dir() 103 if err != nil { 104 log.Debug("unable to determine user home dir: %v", err) 105 } else { 106 goPath = path.Join(homeDir, "go") 107 } 108 } 109 if goPath != "" { 110 g.localModCacheDir = path.Join(goPath, "pkg", "mod") 111 } 112 } 113 return g 114 }