github.com/quay/claircore@v1.5.28/linux/distsearcher.go (about)

     1  package linux
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/quay/claircore"
     7  	"github.com/quay/claircore/indexer"
     8  )
     9  
    10  // DistSearcher uses ClairCore's heuristic to determine a distribution for
    11  // a given layer.
    12  //
    13  // The searcher will first see if distribution information exists for the queried layer.
    14  // Next the searcher will look backwards in the layer history for distribution information.
    15  // Finally the searcher will look forward in the layer history as a final effort to find distribution info.
    16  type DistSearcher struct {
    17  	dists []*claircore.Distribution
    18  }
    19  
    20  func NewDistSearcher(artifacts []*indexer.LayerArtifacts) DistSearcher {
    21  	dists := make([]*claircore.Distribution, len(artifacts))
    22  
    23  	// record where dists show up in layers via slice
    24  	for i, artifact := range artifacts {
    25  		if len(artifact.Dist) > 0 {
    26  			dists[i] = artifact.Dist[0] // we dont support multiple dists found in a layer
    27  		}
    28  	}
    29  	return DistSearcher{dists}
    30  }
    31  
    32  func (ds DistSearcher) Search(n int) (*claircore.Distribution, error) {
    33  	if n >= len(ds.dists) || n < 0 {
    34  		return nil, fmt.Errorf("provided manifest contains %d layers. %d is out of bounds", len(ds.dists), n)
    35  	}
    36  
    37  	if found := ds.dists[n]; found != nil {
    38  		return found, nil
    39  	}
    40  
    41  	// first search backwards
    42  	for i := n - 1; i >= 0; i-- {
    43  		if ds.dists[i] != nil {
    44  			return ds.dists[i], nil
    45  		}
    46  	}
    47  
    48  	// now search forward
    49  	for i := n + 1; i < len(ds.dists); i++ {
    50  		if ds.dists[i] != nil {
    51  			return ds.dists[i], nil
    52  		}
    53  	}
    54  	return nil, nil
    55  }
    56  
    57  func (ds DistSearcher) Dists() []*claircore.Distribution {
    58  	out := make([]*claircore.Distribution, 0)
    59  	for _, dist := range ds.dists {
    60  		if dist != nil {
    61  			out = append(out, dist)
    62  		}
    63  	}
    64  	return out
    65  }