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

     1  package main
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"os"
     7  
     8  	"github.com/anchore/syft/syft"
     9  	"github.com/anchore/syft/syft/format"
    10  	"github.com/anchore/syft/syft/format/syftjson"
    11  	"github.com/anchore/syft/syft/sbom"
    12  	"github.com/anchore/syft/syft/source"
    13  )
    14  
    15  const defaultImage = "alpine:3.19"
    16  
    17  func main() {
    18  	// automagically get a source.Source for arbitrary string input
    19  	src := getSource(imageReference())
    20  
    21  	// catalog the given source and return a SBOM
    22  	sbom := getSBOM(src)
    23  
    24  	// take the SBOM object and encode it into the syft-json representation
    25  	bytes := formatSBOM(sbom)
    26  
    27  	// show the SBOM!
    28  	fmt.Println(string(bytes))
    29  }
    30  
    31  func imageReference() string {
    32  	// read an image string reference from the command line or use a default
    33  	if len(os.Args) > 1 {
    34  		return os.Args[1]
    35  	}
    36  	return defaultImage
    37  }
    38  
    39  func getSource(input string) source.Source {
    40  	src, err := syft.GetSource(context.Background(), input, nil)
    41  
    42  	if err != nil {
    43  		panic(err)
    44  	}
    45  
    46  	return src
    47  }
    48  
    49  func getSBOM(src source.Source) sbom.SBOM {
    50  	s, err := syft.CreateSBOM(context.Background(), src, nil)
    51  	if err != nil {
    52  		panic(err)
    53  	}
    54  
    55  	return *s
    56  }
    57  
    58  func formatSBOM(s sbom.SBOM) []byte {
    59  	bytes, err := format.Encode(s, syftjson.NewFormatEncoder())
    60  	if err != nil {
    61  		panic(err)
    62  	}
    63  	return bytes
    64  }