github.com/nextlinux/gosbom@v0.81.1-0.20230627115839-1ff50c281391/gosbom/formats/table/encoder.go (about) 1 package table 2 3 import ( 4 "fmt" 5 "io" 6 "sort" 7 "strings" 8 9 "github.com/nextlinux/gosbom/gosbom/sbom" 10 "github.com/olekukonko/tablewriter" 11 ) 12 13 func encoder(output io.Writer, s sbom.SBOM) error { 14 var rows [][]string 15 16 columns := []string{"Name", "Version", "Type"} 17 for _, p := range s.Artifacts.Packages.Sorted() { 18 row := []string{ 19 p.Name, 20 p.Version, 21 string(p.Type), 22 } 23 rows = append(rows, row) 24 } 25 26 if len(rows) == 0 { 27 _, err := fmt.Fprintln(output, "No packages discovered") 28 return err 29 } 30 31 // sort by name, version, then type 32 sort.SliceStable(rows, func(i, j int) bool { 33 for col := 0; col < len(columns); col++ { 34 if rows[i][col] != rows[j][col] { 35 return rows[i][col] < rows[j][col] 36 } 37 } 38 return false 39 }) 40 rows = removeDuplicateRows(rows) 41 42 table := tablewriter.NewWriter(output) 43 44 table.SetHeader(columns) 45 table.SetHeaderLine(false) 46 table.SetBorder(false) 47 table.SetAutoWrapText(false) 48 table.SetAutoFormatHeaders(true) 49 table.SetHeaderAlignment(tablewriter.ALIGN_LEFT) 50 table.SetAlignment(tablewriter.ALIGN_LEFT) 51 table.SetCenterSeparator("") 52 table.SetColumnSeparator("") 53 table.SetRowSeparator("") 54 table.SetTablePadding(" ") 55 table.SetNoWhiteSpace(true) 56 57 table.AppendBulk(rows) 58 table.Render() 59 60 return nil 61 } 62 63 func removeDuplicateRows(items [][]string) [][]string { 64 seen := map[string][]string{} 65 var result [][]string 66 67 for _, v := range items { 68 key := strings.Join(v, "|") 69 if seen[key] != nil { 70 // dup! 71 continue 72 } 73 74 seen[key] = v 75 result = append(result, v) 76 } 77 return result 78 }