github.com/anchore/syft@v1.4.2-0.20240516191711-1bec1fc5d397/syft/cataloging/pkgcataloging/selection_request.go (about)

     1  package pkgcataloging
     2  
     3  import (
     4  	"strings"
     5  )
     6  
     7  type SelectionRequest struct {
     8  	DefaultNamesOrTags []string `json:"default,omitempty"`
     9  	SubSelectTags      []string `json:"selection,omitempty"`
    10  	AddNames           []string `json:"addition,omitempty"`
    11  	RemoveNamesOrTags  []string `json:"removal,omitempty"`
    12  }
    13  
    14  func NewSelectionRequest() SelectionRequest {
    15  	return SelectionRequest{}
    16  }
    17  
    18  func (s SelectionRequest) WithExpression(expressions ...string) SelectionRequest {
    19  	expressions = cleanSelection(expressions)
    20  	for _, expr := range expressions {
    21  		switch {
    22  		case strings.HasPrefix(expr, "+"):
    23  			s = s.WithAdditions(strings.TrimPrefix(expr, "+"))
    24  		case strings.HasPrefix(expr, "-"):
    25  			s = s.WithRemovals(strings.TrimPrefix(expr, "-"))
    26  		default:
    27  			s = s.WithSubSelections(expr)
    28  		}
    29  	}
    30  	return s
    31  }
    32  
    33  func (s SelectionRequest) WithDefaults(nameOrTags ...string) SelectionRequest {
    34  	s.DefaultNamesOrTags = append(s.DefaultNamesOrTags, nameOrTags...)
    35  	return s
    36  }
    37  
    38  func (s SelectionRequest) WithSubSelections(tags ...string) SelectionRequest {
    39  	s.SubSelectTags = append(s.SubSelectTags, tags...)
    40  	return s
    41  }
    42  
    43  func (s SelectionRequest) WithAdditions(names ...string) SelectionRequest {
    44  	s.AddNames = append(s.AddNames, names...)
    45  	return s
    46  }
    47  
    48  func (s SelectionRequest) WithRemovals(nameOrTags ...string) SelectionRequest {
    49  	s.RemoveNamesOrTags = append(s.RemoveNamesOrTags, nameOrTags...)
    50  	return s
    51  }
    52  
    53  func cleanSelection(tags []string) []string {
    54  	var cleaned []string
    55  	for _, tag := range tags {
    56  		for _, t := range strings.Split(tag, ",") {
    57  			t = strings.TrimSpace(t)
    58  			if t == "" {
    59  				continue
    60  			}
    61  			cleaned = append(cleaned, t)
    62  		}
    63  	}
    64  	return cleaned
    65  }