completions.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "os"
  8. "path/filepath"
  9. "time"
  10. alpm "github.com/jguer/go-alpm"
  11. )
  12. //CreateAURList creates a new completion file
  13. func createAURList(out *os.File, shell string) (err error) {
  14. resp, err := http.Get("https://aur.archlinux.org/packages.gz")
  15. if err != nil {
  16. return err
  17. }
  18. defer resp.Body.Close()
  19. scanner := bufio.NewScanner(resp.Body)
  20. scanner.Scan()
  21. for scanner.Scan() {
  22. fmt.Print(scanner.Text())
  23. out.WriteString(scanner.Text())
  24. if shell == "fish" {
  25. fmt.Print("\tAUR\n")
  26. out.WriteString("\tAUR\n")
  27. } else {
  28. fmt.Print("\n")
  29. out.WriteString("\n")
  30. }
  31. }
  32. return nil
  33. }
  34. //CreatePackageList appends Repo packages to completion cache
  35. func createRepoList(out *os.File, shell string) (err error) {
  36. dbList, err := alpmHandle.SyncDbs()
  37. if err != nil {
  38. return
  39. }
  40. _ = dbList.ForEach(func(db alpm.Db) error {
  41. _ = db.PkgCache().ForEach(func(pkg alpm.Package) error {
  42. fmt.Print(pkg.Name())
  43. out.WriteString(pkg.Name())
  44. if shell == "fish" {
  45. fmt.Print("\t" + pkg.DB().Name() + "\n")
  46. out.WriteString("\t" + pkg.DB().Name() + "\n")
  47. } else {
  48. fmt.Print("\n")
  49. out.WriteString("\n")
  50. }
  51. return nil
  52. })
  53. return nil
  54. })
  55. return nil
  56. }
  57. // Complete provides completion info for shells
  58. func complete(shell string) error {
  59. var path string
  60. if shell == "fish" {
  61. path = filepath.Join(cacheHome, "aur_fish"+".cache")
  62. } else {
  63. path = filepath.Join(cacheHome, "aur_sh"+".cache")
  64. }
  65. info, err := os.Stat(path)
  66. if os.IsNotExist(err) || time.Since(info.ModTime()).Hours() > 48 {
  67. os.MkdirAll(filepath.Dir(path), 0755)
  68. out, errf := os.Create(path)
  69. if errf != nil {
  70. return errf
  71. }
  72. if createAURList(out, shell) != nil {
  73. defer os.Remove(path)
  74. }
  75. erra := createRepoList(out, shell)
  76. out.Close()
  77. return erra
  78. }
  79. in, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0644)
  80. if err != nil {
  81. return err
  82. }
  83. defer in.Close()
  84. _, err = io.Copy(os.Stdout, in)
  85. return err
  86. }