1// SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later 2 3// Example for: *reporter*, *tvloader* 4 5// This example demonstrates loading an SPDX tag-value file from disk into memory, 6// generating a basic report listing counts of the concluded licenses for its 7// files, and printing the report to standard output. 8// Run project: go run example_report.go ../sample-docs/tv/hello.spdx 9package main 10 11import ( 12 "fmt" 13 "os" 14 15 "github.com/spdx/tools-golang/reporter" 16 "github.com/spdx/tools-golang/spdxlib" 17 "github.com/spdx/tools-golang/tvloader" 18) 19 20func main() { 21 22 // check that we've received the right number of arguments 23 args := os.Args 24 if len(args) != 2 { 25 fmt.Printf("Usage: %v <spdx-file-in>\n", args[0]) 26 fmt.Printf(" Load SPDX 2.2 tag-value file <spdx-file-in>, and\n") 27 fmt.Printf(" generate and print a report of its concluded licenses.\n") 28 return 29 } 30 31 // open the SPDX file 32 filename := args[1] 33 r, err := os.Open(filename) 34 if err != nil { 35 fmt.Printf("Error while opening %v for reading: %v", filename, err) 36 return 37 } 38 defer r.Close() 39 40 // try to load the SPDX file's contents as a tag-value file, version 2.2 41 doc, err := tvloader.Load2_2(r) 42 if err != nil { 43 fmt.Printf("Error while parsing %v: %v", filename, err) 44 return 45 } 46 47 // if we got here, the file is now loaded into memory. 48 fmt.Printf("Successfully loaded %s\n\n", filename) 49 50 // check whether the SPDX file has at least one package that it describes 51 pkgIDs, err := spdxlib.GetDescribedPackageIDs2_2(doc) 52 if err != nil { 53 fmt.Printf("Unable to get describe packages from SPDX document: %v\n", err) 54 return 55 } 56 57 if len(pkgIDs) == 0 { 58 return 59 } 60 61 // it does, so we'll go through each one 62 for _, pkg := range doc.Packages { 63 var documentDescribesPackage bool 64 for _, describedPackageID := range pkgIDs { 65 if pkg.PackageSPDXIdentifier == describedPackageID { 66 documentDescribesPackage = true 67 break 68 } 69 } 70 71 if !documentDescribesPackage { 72 continue 73 } 74 75 pkgID := pkg.PackageSPDXIdentifier 76 77 // check whether the package had its files analyzed 78 if !pkg.FilesAnalyzed { 79 fmt.Printf("Package %s (%s) had FilesAnalyzed: false\n", string(pkgID), pkg.PackageName) 80 return 81 } 82 83 // also check whether the package has any files present 84 if pkg.Files == nil || len(pkg.Files) < 1 { 85 fmt.Printf("Package %s (%s) has no Files\n", string(pkgID), pkg.PackageName) 86 return 87 } 88 89 // if we got here, there's at least one file 90 // generate and print a report of the Package's Files' LicenseConcluded 91 // values, sorted by # of occurrences 92 fmt.Printf("============================\n") 93 fmt.Printf("Package %s (%s)\n", string(pkgID), pkg.PackageName) 94 err = reporter.Generate2_2(pkg, os.Stdout) 95 if err != nil { 96 fmt.Printf("Error while generating report: %v\n", err) 97 } 98 } 99} 100