github.com/nextlinux/gosbom@v0.81.1-0.20230627115839-1ff50c281391/gosbom/license/license.go (about)

     1  // package license provides common methods for working with SPDX license data
     2  package license
     3  
     4  import (
     5  	"fmt"
     6  	"runtime/debug"
     7  
     8  	"github.com/github/go-spdx/v2/spdxexp"
     9  	"github.com/nextlinux/gosbom/internal/spdxlicense"
    10  )
    11  
    12  type Type string
    13  
    14  const (
    15  	Declared  Type = "declared"
    16  	Concluded Type = "concluded"
    17  )
    18  
    19  func ParseExpression(expression string) (ex string, err error) {
    20  	// https://github.com/nextlinux/gosbom/issues/1837
    21  	// The current spdx library can panic when parsing some expressions
    22  	// This is a temporary fix to recover and patch until we can investigate and contribute
    23  	// a fix to the upstream github library
    24  	defer func() {
    25  		if r := recover(); r != nil {
    26  			err = fmt.Errorf("recovered from panic while parsing license expression at: \n%s", string(debug.Stack()))
    27  		}
    28  	}()
    29  
    30  	licenseID, exists := spdxlicense.ID(expression)
    31  	if exists {
    32  		return licenseID, nil
    33  	}
    34  	// If it doesn't exist initially in the SPDX list it might be a more complex expression
    35  	// ignored variable is any invalid expressions
    36  	// TODO: contribute to spdxexp to expose deprecated license IDs
    37  	// https://github.com/nextlinux/gosbom/issues/1814
    38  	valid, _ := spdxexp.ValidateLicenses([]string{expression})
    39  	if !valid {
    40  		return "", fmt.Errorf("invalid SPDX expression: %s", expression)
    41  	}
    42  
    43  	return expression, nil
    44  }