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