github.com/anchore/syft@v1.38.2/syft/cataloging/selection.go (about)

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