github.com/noqcks/syft@v0.0.0-20230920222752-a9e2c4e288e5/syft/pkg/cataloger/common/cpe/go.go (about)

     1  package cpe
     2  
     3  import (
     4  	"net/url"
     5  	"strings"
     6  )
     7  
     8  // candidateProductForGo attempts to find a single product name in a best-effort attempt. This implementation prefers
     9  // to return no vendor over returning potentially nonsensical results.
    10  func candidateProductForGo(name string) string {
    11  	// note: url.Parse requires a scheme for correct processing, which a golang module will not have, so one is provided.
    12  	u, err := url.Parse("http://" + name)
    13  	if err != nil {
    14  		return ""
    15  	}
    16  
    17  	cleanPath := strings.Trim(u.Path, "/")
    18  	pathElements := strings.Split(cleanPath, "/")
    19  
    20  	switch u.Host {
    21  	case "golang.org", "gopkg.in":
    22  		return cleanPath
    23  	case "google.golang.org":
    24  		return pathElements[0]
    25  	}
    26  
    27  	if len(pathElements) < 2 {
    28  		return ""
    29  	}
    30  
    31  	// returning the rest of the path here means longer CPEs, it helps avoiding false-positives
    32  	// ref: https://github.com/anchore/grype/issues/676
    33  	return strings.Join(pathElements[1:], "/")
    34  }
    35  
    36  // candidateVendorForGo attempts to find a single vendor name in a best-effort attempt. This implementation prefers
    37  // to return no vendor over returning potentially nonsensical results.
    38  func candidateVendorForGo(name string) string {
    39  	// note: url.Parse requires a scheme for correct processing, which a golang module will not have, so one is provided.
    40  	u, err := url.Parse("http://" + name)
    41  	if err != nil {
    42  		return ""
    43  	}
    44  
    45  	cleanPath := strings.Trim(u.Path, "/")
    46  
    47  	switch u.Host {
    48  	case "google.golang.org":
    49  		return "google"
    50  	case "golang.org":
    51  		return "golang"
    52  	case "gopkg.in":
    53  		return ""
    54  	}
    55  
    56  	pathElements := strings.Split(cleanPath, "/")
    57  	if len(pathElements) < 2 {
    58  		return ""
    59  	}
    60  	return pathElements[0]
    61  }