upgrade.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package upgrade
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/Jguer/yay/v12/pkg/db"
  6. "github.com/Jguer/yay/v12/pkg/intrange"
  7. "github.com/Jguer/yay/v12/pkg/query"
  8. "github.com/Jguer/yay/v12/pkg/text"
  9. )
  10. // Filter decides if specific package should be included in theincluded in the results.
  11. type Filter func(*Upgrade) bool
  12. // Upgrade type describes a system upgrade.
  13. type Upgrade = db.Upgrade
  14. func StylizedNameWithRepository(u *Upgrade) string {
  15. return text.Bold(text.ColorHash(u.Repository)) + "/" + text.Bold(u.Name)
  16. }
  17. // upSlice is a slice of Upgrades.
  18. type UpSlice struct {
  19. Up []Upgrade
  20. Repos []string
  21. }
  22. func (u UpSlice) Len() int { return len(u.Up) }
  23. func (u UpSlice) Swap(i, j int) { u.Up[i], u.Up[j] = u.Up[j], u.Up[i] }
  24. func (u UpSlice) Less(i, j int) bool {
  25. if u.Up[i].Repository == u.Up[j].Repository {
  26. iRunes := []rune(u.Up[i].Name)
  27. jRunes := []rune(u.Up[j].Name)
  28. return text.LessRunes(iRunes, jRunes)
  29. }
  30. for _, db := range u.Repos {
  31. if db == u.Up[i].Repository {
  32. return true
  33. } else if db == u.Up[j].Repository {
  34. return false
  35. }
  36. }
  37. iRunes := []rune(u.Up[i].Repository)
  38. jRunes := []rune(u.Up[j].Repository)
  39. return text.LessRunes(iRunes, jRunes)
  40. }
  41. // Print prints the details of the packages to upgrade.
  42. func (u UpSlice) Print(logger *text.Logger) {
  43. longestName, longestVersion := 0, 0
  44. for k := range u.Up {
  45. upgrade := &u.Up[k]
  46. packNameLen := len(StylizedNameWithRepository(upgrade))
  47. packVersion, _ := query.GetVersionDiff(upgrade.LocalVersion, upgrade.RemoteVersion)
  48. packVersionLen := len(packVersion)
  49. longestName = intrange.Max(packNameLen, longestName)
  50. longestVersion = intrange.Max(packVersionLen, longestVersion)
  51. }
  52. lenUp := len(u.Up)
  53. longestNumber := len(fmt.Sprintf("%v", lenUp))
  54. namePadding := fmt.Sprintf("%%-%ds ", longestName)
  55. versionPadding := fmt.Sprintf("%%-%ds", longestVersion)
  56. numberPadding := fmt.Sprintf("%%%dd ", longestNumber)
  57. for k := range u.Up {
  58. upgrade := &u.Up[k]
  59. left, right := query.GetVersionDiff(upgrade.LocalVersion, upgrade.RemoteVersion)
  60. logger.Printf(text.Magenta(fmt.Sprintf(numberPadding, lenUp-k)))
  61. logger.Printf(namePadding, StylizedNameWithRepository(upgrade))
  62. logger.Printf("%s -> %s\n", fmt.Sprintf(versionPadding, left), right)
  63. if upgrade.Extra != "" {
  64. logger.Println(strings.Repeat(" ", longestNumber), upgrade.Extra)
  65. }
  66. }
  67. }