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