aboutsummaryrefslogtreecommitdiff
path: root/reporter/reporter.go
blob: a794d8a0888a213b7bf518d4be5cb7bbba1eed6e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Package reporter contains functions to generate a basic license count
// report from an in-memory SPDX Package section (version 2.1) whose
// Files have been analyzed.
// SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
package reporter

import (
	"fmt"
	"io"
	"sort"
	"text/tabwriter"

	"github.com/spdx/tools-golang/spdx"
)

// Generate takes a Package whose Files have been analyzed and an
// io.Writer, and outputs to the io.Writer a tabulated count of
// the number of Files for each unique LicenseConcluded in the set.
func Generate(pkg *spdx.Package2_1, w io.Writer) error {
	if pkg.FilesAnalyzed == false {
		return fmt.Errorf("Package FilesAnalyzed is false")
	}
	totalFound, totalNotFound, foundCounts := countLicenses(pkg)

	wr := tabwriter.NewWriter(w, 0, 0, 2, ' ', tabwriter.AlignRight)

	fmt.Fprintf(wr, "%d\t  License found\n", totalFound)
	fmt.Fprintf(wr, "%d\t  License not found\n", totalNotFound)
	fmt.Fprintf(wr, "%d\t  TOTAL\n", totalFound+totalNotFound)
	fmt.Fprintf(wr, "\n")

	counts := []struct {
		lic   string
		count int
	}{}
	for k, v := range foundCounts {
		var entry struct {
			lic   string
			count int
		}
		entry.lic = k
		entry.count = v
		counts = append(counts, entry)
	}

	sort.Slice(counts, func(i, j int) bool { return counts[i].count > counts[j].count })

	for _, c := range counts {
		fmt.Fprintf(wr, "%d\t  %s\n", c.count, c.lic)
	}
	fmt.Fprintf(wr, "%d\t  TOTAL FOUND\n", totalFound)

	wr.Flush()
	return nil
}

func countLicenses(pkg *spdx.Package2_1) (int, int, map[string]int) {
	if pkg == nil || pkg.Files == nil {
		return 0, 0, nil
	}

	totalFound := 0
	totalNotFound := 0
	foundCounts := map[string]int{}
	for _, f := range pkg.Files {
		if f.LicenseConcluded == "" || f.LicenseConcluded == "NOASSERTION" {
			totalNotFound++
		} else {
			totalFound++
			foundCounts[f.LicenseConcluded]++
		}
	}

	return totalFound, totalNotFound, foundCounts
}