metadata_downloader.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. package metadata
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "os"
  7. )
  8. func main() {
  9. // check if cache exists
  10. cachePath := "aur.json"
  11. cacheBytes, err := ReadCache(cachePath)
  12. if err != nil {
  13. fmt.Println(err)
  14. return
  15. }
  16. if len(cacheBytes) == 0 {
  17. cacheBytes, err = MakeCache(cachePath)
  18. if err != nil {
  19. fmt.Println(err)
  20. return
  21. }
  22. }
  23. }
  24. func MakeOrReadCache(cachePath string) ([]byte, error) {
  25. cacheBytes, err := ReadCache(cachePath)
  26. if err != nil {
  27. return nil, err
  28. }
  29. if len(cacheBytes) == 0 {
  30. cacheBytes, err = MakeCache(cachePath)
  31. if err != nil {
  32. return nil, err
  33. }
  34. }
  35. return cacheBytes, nil
  36. }
  37. func ReadCache(cachePath string) ([]byte, error) {
  38. fp, err := os.Open(cachePath)
  39. if err != nil {
  40. if os.IsNotExist(err) {
  41. return nil, nil
  42. }
  43. return nil, err
  44. }
  45. defer fp.Close()
  46. s, err := io.ReadAll(fp)
  47. if err != nil {
  48. return nil, err
  49. }
  50. return s, nil
  51. }
  52. // Download the metadata for aur packages.
  53. // create cache file
  54. // write to cache file
  55. func MakeCache(cachePath string) ([]byte, error) {
  56. body, err := downloadAURMetadata()
  57. if err != nil {
  58. return nil, err
  59. }
  60. defer body.Close()
  61. s, err := io.ReadAll(body)
  62. if err != nil {
  63. return nil, err
  64. }
  65. f, err := os.Create(cachePath)
  66. if err != nil {
  67. return nil, err
  68. }
  69. defer f.Close()
  70. if _, err = f.Write(s); err != nil {
  71. return nil, err
  72. }
  73. return s, err
  74. }
  75. func downloadAURMetadata() (io.ReadCloser, error) {
  76. resp, err := http.Get("https://aur.archlinux.org/packages-meta-ext-v1.json.gz")
  77. if err != nil {
  78. return nil, err
  79. }
  80. if resp.StatusCode != http.StatusOK {
  81. return nil, fmt.Errorf("failed to download metadata: %s", resp.Status)
  82. }
  83. return resp.Body, nil
  84. }