util.go (1880B)
1 // Copyright 2022 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package scan 6 7 import ( 8 "fmt" 9 "os" 10 "os/exec" 11 "strings" 12 13 "golang.org/x/vuln/internal" 14 "golang.org/x/vuln/internal/govulncheck" 15 ) 16 17 // validateFindings checks that the supplied findings all obey the protocol 18 // rules. 19 func validateFindings(findings ...*govulncheck.Finding) error { 20 for _, f := range findings { 21 if f.OSV == "" { 22 return fmt.Errorf("invalid finding: all findings must have an associated OSV") 23 } 24 if len(f.Trace) < 1 { 25 return fmt.Errorf("invalid finding: all callstacks must have at least one frame") 26 } 27 for _, frame := range f.Trace { 28 if frame.Version != "" && frame.Module == "" { 29 return fmt.Errorf("invalid finding: if Frame.Version (%s) is set, Frame.Module must also be", frame.Version) 30 } 31 if frame.Package != "" && frame.Module == "" { 32 return fmt.Errorf("invalid finding: if Frame.Package (%s) is set, Frame.Module must also be", frame.Package) 33 } 34 if frame.Function != "" && frame.Package == "" { 35 return fmt.Errorf("invalid finding: if Frame.Function (%s) is set, Frame.Package must also be", frame.Function) 36 } 37 } 38 } 39 return nil 40 } 41 42 func moduleVersionString(modulePath, version string) string { 43 if version == "" { 44 return "" 45 } 46 if modulePath == internal.GoStdModulePath || modulePath == internal.GoCmdModulePath { 47 version = semverToGoTag(version) 48 } 49 return version 50 } 51 52 func gomodExists(dir string) bool { 53 cmd := exec.Command("go", "env", "GOMOD") 54 cmd.Dir = dir 55 out, err := cmd.Output() 56 output := strings.TrimSpace(string(out)) 57 // If module-aware mode is enabled, but there is no go.mod, GOMOD will be os.DevNull 58 // If module-aware mode is disabled, GOMOD will be the empty string. 59 return err == nil && !(output == os.DevNull || output == "") 60 }