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

     1  package main
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     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/format"
    12  	"github.com/anchore/syft/syft/format/syftjson"
    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  	sbom := getSBOM(src)
    26  
    27  	// take the SBOM object and encode it into the syft-json representation
    28  	bytes := formatSBOM(sbom)
    29  
    30  	// show the SBOM!
    31  	fmt.Println(string(bytes))
    32  }
    33  
    34  func imageReference() string {
    35  	// read an image string reference from the command line or use a default
    36  	if len(os.Args) > 1 {
    37  		return os.Args[1]
    38  	}
    39  	return defaultImage
    40  }
    41  
    42  func getSource(input string) source.Source {
    43  	src, err := syft.GetSource(context.Background(), input, nil)
    44  	if err != nil {
    45  		panic(err)
    46  	}
    47  
    48  	return src
    49  }
    50  
    51  func getSBOM(src source.Source) sbom.SBOM {
    52  	s, err := syft.CreateSBOM(context.Background(), src, nil)
    53  	if err != nil {
    54  		panic(err)
    55  	}
    56  
    57  	return *s
    58  }
    59  
    60  func formatSBOM(s sbom.SBOM) []byte {
    61  	bytes, err := format.Encode(s, syftjson.NewFormatEncoder())
    62  	if err != nil {
    63  		panic(err)
    64  	}
    65  	return bytes
    66  }