download.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "os"
  7. "os/exec"
  8. "path/filepath"
  9. "strings"
  10. "sync"
  11. alpm "github.com/Jguer/go-alpm"
  12. )
  13. // Decide what download method to use:
  14. // Use the config option when the destination does not already exits
  15. // If .git exists in the destination use git
  16. // Otherwise use a tarrball
  17. func shouldUseGit(path string) bool {
  18. _, err := os.Stat(path)
  19. if os.IsNotExist(err) {
  20. return config.GitClone
  21. }
  22. _, err = os.Stat(filepath.Join(path, ".git"))
  23. return err == nil || os.IsExist(err)
  24. }
  25. func downloadFile(path string, url string) (err error) {
  26. // Create the file
  27. out, err := os.Create(path)
  28. if err != nil {
  29. return err
  30. }
  31. defer out.Close()
  32. // Get the data
  33. resp, err := http.Get(url)
  34. if err != nil {
  35. return err
  36. }
  37. defer resp.Body.Close()
  38. // Writer the body to file
  39. _, err = io.Copy(out, resp.Body)
  40. return err
  41. }
  42. func gitHasDiff(path string, name string) (bool, error) {
  43. stdout, stderr, err := capture(passToGit(filepath.Join(path, name), "rev-parse", "HEAD", "HEAD@{upstream}"))
  44. if err != nil {
  45. return false, fmt.Errorf("%s%s", stderr, err)
  46. }
  47. lines := strings.Split(stdout, "\n")
  48. head := lines[0]
  49. upstream := lines[1]
  50. return head != upstream, nil
  51. }
  52. func gitDownload(url string, path string, name string) (bool, error) {
  53. _, err := os.Stat(filepath.Join(path, name, ".git"))
  54. if os.IsNotExist(err) {
  55. cmd := passToGit(path, "clone", "--no-progress", url, name)
  56. cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0")
  57. _, stderr, err := capture(cmd)
  58. if err != nil {
  59. return false, fmt.Errorf("error cloning %s: %s", name, stderr)
  60. }
  61. return true, nil
  62. } else if err != nil {
  63. return false, fmt.Errorf("error reading %s", filepath.Join(path, name, ".git"))
  64. }
  65. cmd := passToGit(filepath.Join(path, name), "fetch")
  66. cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0")
  67. _, stderr, err := capture(cmd)
  68. if err != nil {
  69. return false, fmt.Errorf("error fetching %s: %s", name, stderr)
  70. }
  71. return false, nil
  72. }
  73. func gitMerge(path string, name string) error {
  74. _, stderr, err := capture(passToGit(filepath.Join(path, name), "reset", "--hard", "HEAD"))
  75. if err != nil {
  76. return fmt.Errorf("error resetting %s: %s", name, stderr)
  77. }
  78. _, stderr, err = capture(passToGit(filepath.Join(path, name), "merge", "--no-edit", "--ff"))
  79. if err != nil {
  80. return fmt.Errorf("error merging %s: %s", name, stderr)
  81. }
  82. return nil
  83. }
  84. // DownloadAndUnpack downloads url tgz and extracts to path.
  85. func downloadAndUnpack(url string, path string) error {
  86. err := os.MkdirAll(path, 0755)
  87. if err != nil {
  88. return err
  89. }
  90. fileName := filepath.Base(url)
  91. tarLocation := filepath.Join(path, fileName)
  92. defer os.Remove(tarLocation)
  93. err = downloadFile(tarLocation, url)
  94. if err != nil {
  95. return err
  96. }
  97. _, stderr, err := capture(exec.Command(config.TarBin, "-xf", tarLocation, "-C", path))
  98. if err != nil {
  99. return fmt.Errorf("%s", stderr)
  100. }
  101. return nil
  102. }
  103. func getPkgbuilds(pkgs []string) error {
  104. missing := false
  105. wd, err := os.Getwd()
  106. if err != nil {
  107. return err
  108. }
  109. pkgs = removeInvalidTargets(pkgs)
  110. aur, repo, err := packageSlices(pkgs)
  111. if err != nil {
  112. return err
  113. }
  114. for n := range aur {
  115. _, pkg := splitDBFromName(aur[n])
  116. aur[n] = pkg
  117. }
  118. info, err := aurInfoPrint(aur)
  119. if err != nil {
  120. return err
  121. }
  122. if len(repo) > 0 {
  123. missing, err = getPkgbuildsfromABS(repo, wd)
  124. if err != nil {
  125. return err
  126. }
  127. }
  128. if len(aur) > 0 {
  129. allBases := getBases(info)
  130. bases := make([]Base, 0)
  131. for _, base := range allBases {
  132. name := base.Pkgbase()
  133. _, err = os.Stat(filepath.Join(wd, name))
  134. switch {
  135. case err != nil && !os.IsNotExist(err):
  136. fmt.Fprintln(os.Stderr, bold(red(smallArrow)), err)
  137. continue
  138. case os.IsNotExist(err), cmdArgs.existsArg("f", "force"), shouldUseGit(filepath.Join(wd, name)):
  139. if err = os.RemoveAll(filepath.Join(wd, name)); err != nil {
  140. fmt.Fprintln(os.Stderr, bold(red(smallArrow)), err)
  141. continue
  142. }
  143. default:
  144. fmt.Printf("%s %s %s\n", yellow(smallArrow), cyan(name), "already downloaded -- use -f to overwrite")
  145. continue
  146. }
  147. bases = append(bases, base)
  148. }
  149. if _, err = downloadPkgbuilds(bases, nil, wd); err != nil {
  150. return err
  151. }
  152. missing = missing || len(aur) != len(info)
  153. }
  154. if missing {
  155. err = fmt.Errorf("")
  156. }
  157. return err
  158. }
  159. // GetPkgbuild downloads pkgbuild from the ABS.
  160. func getPkgbuildsfromABS(pkgs []string, path string) (bool, error) {
  161. var wg sync.WaitGroup
  162. var mux sync.Mutex
  163. var errs MultiError
  164. names := make(map[string]string)
  165. missing := make([]string, 0)
  166. downloaded := 0
  167. dbList, err := alpmHandle.SyncDBs()
  168. if err != nil {
  169. return false, err
  170. }
  171. for _, pkgN := range pkgs {
  172. var pkg *alpm.Package
  173. var err error
  174. var url string
  175. pkgDB, name := splitDBFromName(pkgN)
  176. if pkgDB != "" {
  177. if db, err := alpmHandle.SyncDBByName(pkgDB); err == nil {
  178. pkg = db.Pkg(name)
  179. }
  180. } else {
  181. dbList.ForEach(func(db alpm.DB) error {
  182. if pkg = db.Pkg(name); pkg != nil {
  183. return fmt.Errorf("")
  184. }
  185. return nil
  186. })
  187. }
  188. if pkg == nil {
  189. missing = append(missing, name)
  190. continue
  191. }
  192. name = pkg.Base()
  193. if name == "" {
  194. name = pkg.Name()
  195. }
  196. switch pkg.DB().Name() {
  197. case "core", "extra", "testing":
  198. url = "https://git.archlinux.org/svntogit/packages.git/snapshot/packages/" + name + ".tar.gz"
  199. case "community", "multilib", "community-testing", "multilib-testing":
  200. url = "https://git.archlinux.org/svntogit/community.git/snapshot/packages/" + name + ".tar.gz"
  201. default:
  202. missing = append(missing, name)
  203. continue
  204. }
  205. _, err = os.Stat(filepath.Join(path, name))
  206. switch {
  207. case err != nil && !os.IsNotExist(err):
  208. fmt.Fprintln(os.Stderr, bold(red(smallArrow)), err)
  209. continue
  210. case os.IsNotExist(err), cmdArgs.existsArg("f", "force"):
  211. if err = os.RemoveAll(filepath.Join(path, name)); err != nil {
  212. fmt.Fprintln(os.Stderr, bold(red(smallArrow)), err)
  213. continue
  214. }
  215. default:
  216. fmt.Printf("%s %s %s\n", yellow(smallArrow), cyan(name), "already downloaded -- use -f to overwrite")
  217. continue
  218. }
  219. names[name] = url
  220. }
  221. if len(missing) != 0 {
  222. fmt.Println(yellow(bold(smallArrow)), "Missing ABS packages: ", cyan(strings.Join(missing, " ")))
  223. }
  224. download := func(pkg string, url string) {
  225. defer wg.Done()
  226. if err := downloadAndUnpack(url, cacheHome); err != nil {
  227. errs.Add(fmt.Errorf("%s Failed to get pkgbuild: %s: %s", bold(red(arrow)), bold(cyan(pkg)), bold(red(err.Error()))))
  228. return
  229. }
  230. _, stderr, err := capture(exec.Command("mv", filepath.Join(cacheHome, "packages", pkg, "trunk"), filepath.Join(path, pkg)))
  231. mux.Lock()
  232. downloaded++
  233. if err != nil {
  234. errs.Add(fmt.Errorf("%s Failed to move %s: %s", bold(red(arrow)), bold(cyan(pkg)), bold(red(string(stderr)))))
  235. } else {
  236. fmt.Printf(bold(cyan("::"))+" Downloaded PKGBUILD from ABS (%d/%d): %s\n", downloaded, len(names), cyan(pkg))
  237. }
  238. mux.Unlock()
  239. }
  240. count := 0
  241. for name, url := range names {
  242. wg.Add(1)
  243. go download(name, url)
  244. count++
  245. if count%25 == 0 {
  246. wg.Wait()
  247. }
  248. }
  249. wg.Wait()
  250. errs.Add(os.RemoveAll(filepath.Join(cacheHome, "packages")))
  251. return len(missing) != 0, errs.Return()
  252. }