github.com/nextlinux/gosbom@v0.81.1-0.20230627115839-1ff50c281391/gosbom/formats/common/spdxhelpers/document_namespace.go (about) 1 package spdxhelpers 2 3 import ( 4 "fmt" 5 "net/url" 6 "path" 7 "strings" 8 9 "github.com/google/uuid" 10 "github.com/nextlinux/gosbom/gosbom/source" 11 "github.com/nextlinux/gosbom/internal" 12 ) 13 14 const ( 15 inputImage = "image" 16 inputDirectory = "dir" 17 inputFile = "file" 18 ) 19 20 func DocumentNameAndNamespace(srcMetadata source.Metadata) (string, string) { 21 name := DocumentName(srcMetadata) 22 return name, DocumentNamespace(name, srcMetadata) 23 } 24 25 func DocumentNamespace(name string, srcMetadata source.Metadata) string { 26 name = cleanName(name) 27 input := "unknown-source-type" 28 switch srcMetadata.Scheme { 29 case source.ImageScheme: 30 input = inputImage 31 case source.DirectoryScheme: 32 input = inputDirectory 33 case source.FileScheme: 34 input = inputFile 35 } 36 37 uniqueID := uuid.Must(uuid.NewRandom()) 38 identifier := path.Join(input, uniqueID.String()) 39 if name != "." { 40 identifier = path.Join(input, fmt.Sprintf("%s-%s", name, uniqueID.String())) 41 } 42 43 u := url.URL{ 44 Scheme: "https", 45 Host: "anchore.com", 46 Path: path.Join(internal.ApplicationName, identifier), 47 } 48 49 return u.String() 50 } 51 52 // see: https://spdx.github.io/spdx-spec/v2.3/document-creation-information/#65-spdx-document-namespace-field 53 func cleanName(name string) string { 54 // remove # according to specification 55 name = strings.ReplaceAll(name, "#", "-") 56 // remove : for url construction 57 name = strings.ReplaceAll(name, ":", "-") 58 // clean relative pathing 59 return path.Clean(name) 60 }