github.com/anchore/syft@v1.38.2/examples/select_catalogers/main.go (about)

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