utils.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
  32. err := cmd.Run()
  33. return err
  34. }
  35. // Complete provides completion info for shells
  36. func complete() (err error) {
  37. path := os.Getenv("HOME") + "/.cache/yay/aur_" + util.Shell + ".cache"
  38. if info, err := os.Stat(path); os.IsNotExist(err) || time.Since(info.ModTime()).Hours() > 48 {
  39. os.MkdirAll(os.Getenv("HOME")+"/.cache/yay/", 0755)
  40. out, err := os.Create(path)
  41. if err != nil {
  42. return err
  43. }
  44. if aur.CreateAURList(out) != nil {
  45. defer os.Remove(path)
  46. }
  47. err = pac.CreatePackageList(out)
  48. out.Close()
  49. return err
  50. }
  51. in, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0755)
  52. if err != nil {
  53. return err
  54. }
  55. defer in.Close()
  56. _, err = io.Copy(os.Stdout, in)
  57. return err
  58. }
  59. // Function by pyk https://github.com/pyk/byten
  60. func index(s int64) float64 {
  61. x := math.Log(float64(s)) / math.Log(1024)
  62. return math.Floor(x)
  63. }
  64. // Function by pyk https://github.com/pyk/byten
  65. func countSize(s int64, i float64) float64 {
  66. return float64(s) / math.Pow(1024, math.Floor(i))
  67. }
  68. // Size return a formated string from file size
  69. // Function by pyk https://github.com/pyk/byten
  70. func size(s int64) string {
  71. symbols := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
  72. i := index(s)
  73. if s < 10 {
  74. return fmt.Sprintf("%dB", s)
  75. }
  76. size := countSize(s, i)
  77. format := "%.0f"
  78. if size < 10 {
  79. format = "%.1f"
  80. }
  81. return fmt.Sprintf(format+"%s", size, symbols[int(i)])
  82. }