utils.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "math"
  6. "os"
  7. "os/exec"
  8. "strings"
  9. "time"
  10. "github.com/jguer/yay/aur"
  11. pac "github.com/jguer/yay/pacman"
  12. "github.com/jguer/yay/util"
  13. )
  14. // PassToPacman outsorces execution to pacman binary without modifications.
  15. func PassToPacman(op string, pkgs []string, flags []string) error {
  16. var cmd *exec.Cmd
  17. var args []string
  18. args = append(args, op)
  19. if len(pkgs) != 0 {
  20. args = append(args, pkgs...)
  21. }
  22. if len(flags) != 0 {
  23. args = append(args, flags...)
  24. }
  25. if strings.Contains(op, "-Q") {
  26. cmd = exec.Command("pacman", args...)
  27. } else {
  28. args = append([]string{"pacman"}, args...)
  29. cmd = exec.Command("sudo", args...)
  30. }
  31. cmd.Stdout = os.Stdout
  32. cmd.Stdin = os.Stdin
  33. cmd.Stderr = os.Stderr
  34. err := cmd.Run()
  35. return err
  36. }
  37. // Complete provides completion info for shells
  38. func Complete() (err error) {
  39. path := os.Getenv("HOME") + "/.cache/yay/aur_" + util.Shell + ".cache"
  40. if info, err := os.Stat(path); os.IsNotExist(err) || time.Since(info.ModTime()).Hours() > 48 {
  41. os.MkdirAll(os.Getenv("HOME")+"/.cache/yay", 0755)
  42. out, err := os.Create(path)
  43. if err != nil {
  44. return err
  45. }
  46. if aur.CreateAURList(out) != nil {
  47. defer os.Remove(path)
  48. }
  49. err = pac.CreatePackageList(out)
  50. out.Close()
  51. return err
  52. }
  53. in, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0755)
  54. if err != nil {
  55. return err
  56. }
  57. defer in.Close()
  58. _, err = io.Copy(os.Stdout, in)
  59. return err
  60. }
  61. // Function by pyk https://github.com/pyk/byten
  62. func index(s int64) float64 {
  63. x := math.Log(float64(s)) / math.Log(1024)
  64. return math.Floor(x)
  65. }
  66. // Function by pyk https://github.com/pyk/byten
  67. func countSize(s int64, i float64) float64 {
  68. return float64(s) / math.Pow(1024, math.Floor(i))
  69. }
  70. // Size return a formated string from file size
  71. // Function by pyk https://github.com/pyk/byten
  72. func size(s int64) string {
  73. symbols := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
  74. i := index(s)
  75. if s < 10 {
  76. return fmt.Sprintf("%dB", s)
  77. }
  78. size := countSize(s, i)
  79. format := "%.0f"
  80. if size < 10 {
  81. format = "%.1f"
  82. }
  83. return fmt.Sprintf(format+"%s", size, symbols[int(i)])
  84. }