github.com/pdmccormick/importable-docker-buildx@v0.0.0-20240426161518-e47091289030/util/buildflags/attests.go (about)

     1  package buildflags
     2  
     3  import (
     4  	"encoding/csv"
     5  	"fmt"
     6  	"strconv"
     7  	"strings"
     8  
     9  	controllerapi "github.com/docker/buildx/controller/pb"
    10  	"github.com/pkg/errors"
    11  )
    12  
    13  func CanonicalizeAttest(attestType string, in string) string {
    14  	if in == "" {
    15  		return ""
    16  	}
    17  	if b, err := strconv.ParseBool(in); err == nil {
    18  		return fmt.Sprintf("type=%s,disabled=%t", attestType, !b)
    19  	}
    20  	return fmt.Sprintf("type=%s,%s", attestType, in)
    21  }
    22  
    23  func ParseAttests(in []string) ([]*controllerapi.Attest, error) {
    24  	out := []*controllerapi.Attest{}
    25  	found := map[string]struct{}{}
    26  	for _, in := range in {
    27  		in := in
    28  		attest, err := ParseAttest(in)
    29  		if err != nil {
    30  			return nil, err
    31  		}
    32  
    33  		if _, ok := found[attest.Type]; ok {
    34  			return nil, errors.Errorf("duplicate attestation field %s", attest.Type)
    35  		}
    36  		found[attest.Type] = struct{}{}
    37  
    38  		out = append(out, attest)
    39  	}
    40  	return out, nil
    41  }
    42  
    43  func ParseAttest(in string) (*controllerapi.Attest, error) {
    44  	if in == "" {
    45  		return nil, nil
    46  	}
    47  
    48  	csvReader := csv.NewReader(strings.NewReader(in))
    49  	fields, err := csvReader.Read()
    50  	if err != nil {
    51  		return nil, err
    52  	}
    53  
    54  	attest := controllerapi.Attest{
    55  		Attrs: in,
    56  	}
    57  	for _, field := range fields {
    58  		key, value, ok := strings.Cut(field, "=")
    59  		if !ok {
    60  			return nil, errors.Errorf("invalid value %s", field)
    61  		}
    62  		key = strings.TrimSpace(strings.ToLower(key))
    63  
    64  		switch key {
    65  		case "type":
    66  			attest.Type = value
    67  		case "disabled":
    68  			disabled, err := strconv.ParseBool(value)
    69  			if err != nil {
    70  				return nil, errors.Wrapf(err, "invalid value %s", field)
    71  			}
    72  			attest.Disabled = disabled
    73  		}
    74  	}
    75  	if attest.Type == "" {
    76  		return nil, errors.Errorf("attestation type not specified")
    77  	}
    78  
    79  	return &attest, nil
    80  }