github.com/anchore/syft@v1.4.2-0.20240516191711-1bec1fc5d397/examples/select_catalogers/main.go (about)

     1  package main
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"os"
     7  
     8  	"github.com/anchore/syft/syft"
     9  	"github.com/anchore/syft/syft/cataloging/pkgcataloging"
    10  	"github.com/anchore/syft/syft/sbom"
    11  	"github.com/anchore/syft/syft/source"
    12  )
    13  
    14  const defaultImage = "alpine:3.19"
    15  
    16  func main() {
    17  	// automagically get a source.Source for arbitrary string input
    18  	src := getSource(imageReference())
    19  
    20  	// catalog the given source and return a SBOM
    21  	// let's explicitly use catalogers that are:
    22  	// - for installed software
    23  	// - used in the directory scan
    24  	sbom := getSBOM(src, pkgcataloging.InstalledTag, pkgcataloging.DirectoryTag)
    25  
    26  	// Show a basic catalogers and input configuration used
    27  	enc := json.NewEncoder(os.Stdout)
    28  	enc.SetIndent("", "  ")
    29  	if err := enc.Encode(sbom.Descriptor.Configuration); err != nil {
    30  		panic(err)
    31  	}
    32  
    33  }
    34  
    35  func imageReference() string {
    36  	// read an image string reference from the command line or use a default
    37  	if len(os.Args) > 1 {
    38  		return os.Args[1]
    39  	}
    40  	return defaultImage
    41  }
    42  
    43  func getSource(input string) source.Source {
    44  	src, err := syft.GetSource(context.Background(), input, nil)
    45  
    46  	if err != nil {
    47  		panic(err)
    48  	}
    49  
    50  	return src
    51  }
    52  
    53  func getSBOM(src source.Source, defaultTags ...string) sbom.SBOM {
    54  	cfg := syft.DefaultCreateSBOMConfig().
    55  		WithCatalogerSelection(
    56  			// here you can sub-select, add, remove catalogers from the default selection...
    57  			// or replace the default selection entirely!
    58  			pkgcataloging.NewSelectionRequest().
    59  				WithDefaults(defaultTags...),
    60  		)
    61  
    62  	s, err := syft.CreateSBOM(context.Background(), src, cfg)
    63  	if err != nil {
    64  		panic(err)
    65  	}
    66  
    67  	return *s
    68  }