download.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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. "github.com/Jguer/yay/v9/pkg/types"
  13. )
  14. const gitDiffRefName = "AUR_SEEN"
  15. // Decide what download method to use:
  16. // Use the config option when the destination does not already exits
  17. // If .git exists in the destination use git
  18. // Otherwise use a tarrball
  19. func shouldUseGit(path string) bool {
  20. _, err := os.Stat(path)
  21. if os.IsNotExist(err) {
  22. return config.GitClone
  23. }
  24. _, err = os.Stat(filepath.Join(path, ".git"))
  25. return err == nil || os.IsExist(err)
  26. }
  27. func downloadFile(path string, url string) (err error) {
  28. // Create the file
  29. out, err := os.Create(path)
  30. if err != nil {
  31. return err
  32. }
  33. defer out.Close()
  34. // Get the data
  35. resp, err := http.Get(url)
  36. if err != nil {
  37. return err
  38. }
  39. defer resp.Body.Close()
  40. // Writer the body to file
  41. _, err = io.Copy(out, resp.Body)
  42. return err
  43. }
  44. // Update the YAY_DIFF_REVIEW ref to HEAD. We use this ref to determine which diff were
  45. // reviewed by the user
  46. func gitUpdateSeenRef(path string, name string) error {
  47. _, stderr, err := capture(passToGit(filepath.Join(path, name), "update-ref", gitDiffRefName, "HEAD"))
  48. if err != nil {
  49. return fmt.Errorf("%s%s", stderr, err)
  50. }
  51. return nil
  52. }
  53. // Return wether or not we have reviewed a diff yet. It checks for the existence of
  54. // YAY_DIFF_REVIEW in the git ref-list
  55. func gitHasLastSeenRef(path string, name string) bool {
  56. _, _, err := capture(passToGit(filepath.Join(path, name), "rev-parse", "--quiet", "--verify", gitDiffRefName))
  57. return err == nil
  58. }
  59. // Returns the last reviewed hash. If YAY_DIFF_REVIEW exists it will return this hash.
  60. // If it does not it will return empty tree as no diff have been reviewed yet.
  61. func getLastSeenHash(path string, name string) (string, error) {
  62. if gitHasLastSeenRef(path, name) {
  63. stdout, stderr, err := capture(passToGit(filepath.Join(path, name), "rev-parse", gitDiffRefName))
  64. if err != nil {
  65. return "", fmt.Errorf("%s%s", stderr, err)
  66. }
  67. lines := strings.Split(stdout, "\n")
  68. return lines[0], nil
  69. }
  70. return gitEmptyTree, nil
  71. }
  72. // Check whether or not a diff exists between the last reviewed diff and
  73. // HEAD@{upstream}
  74. func gitHasDiff(path string, name string) (bool, error) {
  75. if gitHasLastSeenRef(path, name) {
  76. stdout, stderr, err := capture(passToGit(filepath.Join(path, name), "rev-parse", gitDiffRefName, "HEAD@{upstream}"))
  77. if err != nil {
  78. return false, fmt.Errorf("%s%s", stderr, err)
  79. }
  80. lines := strings.Split(stdout, "\n")
  81. lastseen := lines[0]
  82. upstream := lines[1]
  83. return lastseen != upstream, nil
  84. }
  85. // If YAY_DIFF_REVIEW does not exists, we have never reviewed a diff for this package
  86. // and should display it.
  87. return true, nil
  88. }
  89. // TODO: yay-next passes args through the header, use that to unify ABS and AUR
  90. func gitDownloadABS(url string, path string, name string) (bool, error) {
  91. _, err := os.Stat(filepath.Join(path, name))
  92. if os.IsNotExist(err) {
  93. cmd := passToGit(path, "clone", "--no-progress", "--single-branch",
  94. "-b", "packages/"+name, url, name)
  95. cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0")
  96. _, stderr, err := capture(cmd)
  97. if err != nil {
  98. return false, fmt.Errorf("error cloning %s: %s", name, stderr)
  99. }
  100. return true, nil
  101. } else if err != nil {
  102. return false, fmt.Errorf("error reading %s", filepath.Join(path, name, ".git"))
  103. }
  104. cmd := passToGit(filepath.Join(path, name), "fetch")
  105. cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0")
  106. _, stderr, err := capture(cmd)
  107. if err != nil {
  108. return false, fmt.Errorf("error fetching %s: %s", name, stderr)
  109. }
  110. return true, nil
  111. }
  112. func gitDownload(url string, path string, name string) (bool, error) {
  113. _, err := os.Stat(filepath.Join(path, name, ".git"))
  114. if os.IsNotExist(err) {
  115. cmd := passToGit(path, "clone", "--no-progress", url, name)
  116. cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0")
  117. _, stderr, err := capture(cmd)
  118. if err != nil {
  119. return false, fmt.Errorf("error cloning %s: %s", name, stderr)
  120. }
  121. return true, nil
  122. } else if err != nil {
  123. return false, fmt.Errorf("error reading %s", filepath.Join(path, name, ".git"))
  124. }
  125. cmd := passToGit(filepath.Join(path, name), "fetch")
  126. cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0")
  127. _, stderr, err := capture(cmd)
  128. if err != nil {
  129. return false, fmt.Errorf("error fetching %s: %s", name, stderr)
  130. }
  131. return false, nil
  132. }
  133. func gitMerge(path string, name string) error {
  134. _, stderr, err := capture(passToGit(filepath.Join(path, name), "reset", "--hard", "HEAD"))
  135. if err != nil {
  136. return fmt.Errorf("error resetting %s: %s", name, stderr)
  137. }
  138. _, stderr, err = capture(passToGit(filepath.Join(path, name), "merge", "--no-edit", "--ff"))
  139. if err != nil {
  140. return fmt.Errorf("error merging %s: %s", name, stderr)
  141. }
  142. return nil
  143. }
  144. // DownloadAndUnpack downloads url tgz and extracts to path.
  145. func downloadAndUnpack(url string, path string) error {
  146. err := os.MkdirAll(path, 0755)
  147. if err != nil {
  148. return err
  149. }
  150. fileName := filepath.Base(url)
  151. tarLocation := filepath.Join(path, fileName)
  152. defer os.Remove(tarLocation)
  153. err = downloadFile(tarLocation, url)
  154. if err != nil {
  155. return err
  156. }
  157. _, stderr, err := capture(exec.Command(config.TarBin, "-xf", tarLocation, "-C", path))
  158. if err != nil {
  159. return fmt.Errorf("%s", stderr)
  160. }
  161. return nil
  162. }
  163. func getPkgbuilds(pkgs []string) error {
  164. missing := false
  165. wd, err := os.Getwd()
  166. if err != nil {
  167. return err
  168. }
  169. pkgs = removeInvalidTargets(pkgs)
  170. aur, repo, err := packageSlices(pkgs)
  171. if err != nil {
  172. return err
  173. }
  174. for n := range aur {
  175. _, pkg := splitDBFromName(aur[n])
  176. aur[n] = pkg
  177. }
  178. info, err := aurInfoPrint(aur)
  179. if err != nil {
  180. return err
  181. }
  182. if len(repo) > 0 {
  183. missing, err = getPkgbuildsfromABS(repo, wd)
  184. if err != nil {
  185. return err
  186. }
  187. }
  188. if len(aur) > 0 {
  189. allBases := getBases(info)
  190. bases := make([]Base, 0)
  191. for _, base := range allBases {
  192. name := base.Pkgbase()
  193. _, err = os.Stat(filepath.Join(wd, name))
  194. switch {
  195. case err != nil && !os.IsNotExist(err):
  196. fmt.Fprintln(os.Stderr, bold(red(smallArrow)), err)
  197. continue
  198. case os.IsNotExist(err), cmdArgs.existsArg("f", "force"), shouldUseGit(filepath.Join(wd, name)):
  199. if err = os.RemoveAll(filepath.Join(wd, name)); err != nil {
  200. fmt.Fprintln(os.Stderr, bold(red(smallArrow)), err)
  201. continue
  202. }
  203. default:
  204. fmt.Printf("%s %s %s\n", yellow(smallArrow), cyan(name), "already downloaded -- use -f to overwrite")
  205. continue
  206. }
  207. bases = append(bases, base)
  208. }
  209. if _, err = downloadPkgbuilds(bases, nil, wd); err != nil {
  210. return err
  211. }
  212. missing = missing || len(aur) != len(info)
  213. }
  214. if missing {
  215. err = fmt.Errorf("")
  216. }
  217. return err
  218. }
  219. // GetPkgbuild downloads pkgbuild from the ABS.
  220. func getPkgbuildsfromABS(pkgs []string, path string) (bool, error) {
  221. var wg sync.WaitGroup
  222. var mux sync.Mutex
  223. var errs types.MultiError
  224. names := make(map[string]string)
  225. missing := make([]string, 0)
  226. downloaded := 0
  227. dbList, err := alpmHandle.SyncDBs()
  228. if err != nil {
  229. return false, err
  230. }
  231. for _, pkgN := range pkgs {
  232. var pkg *alpm.Package
  233. var err error
  234. var url string
  235. pkgDB, name := splitDBFromName(pkgN)
  236. if pkgDB != "" {
  237. if db, err := alpmHandle.SyncDBByName(pkgDB); err == nil {
  238. pkg = db.Pkg(name)
  239. }
  240. } else {
  241. _ = dbList.ForEach(func(db alpm.DB) error {
  242. if pkg = db.Pkg(name); pkg != nil {
  243. return fmt.Errorf("")
  244. }
  245. return nil
  246. })
  247. }
  248. if pkg == nil {
  249. missing = append(missing, name)
  250. continue
  251. }
  252. name = pkg.Base()
  253. if name == "" {
  254. name = pkg.Name()
  255. }
  256. // TODO: Check existence with ls-remote
  257. // https://git.archlinux.org/svntogit/packages.git
  258. switch pkg.DB().Name() {
  259. case "core", "extra", "testing":
  260. url = "https://git.archlinux.org/svntogit/packages.git"
  261. case "community", "multilib", "community-testing", "multilib-testing":
  262. url = "https://git.archlinux.org/svntogit/community.git"
  263. default:
  264. missing = append(missing, name)
  265. continue
  266. }
  267. _, err = os.Stat(filepath.Join(path, name))
  268. switch {
  269. case err != nil && !os.IsNotExist(err):
  270. fmt.Fprintln(os.Stderr, bold(red(smallArrow)), err)
  271. continue
  272. case os.IsNotExist(err), cmdArgs.existsArg("f", "force"):
  273. if err = os.RemoveAll(filepath.Join(path, name)); err != nil {
  274. fmt.Fprintln(os.Stderr, bold(red(smallArrow)), err)
  275. continue
  276. }
  277. default:
  278. fmt.Printf("%s %s %s\n", yellow(smallArrow), cyan(name), "already downloaded -- use -f to overwrite")
  279. continue
  280. }
  281. names[name] = url
  282. }
  283. if len(missing) != 0 {
  284. fmt.Println(yellow(bold(smallArrow)), "Missing ABS packages: ", cyan(strings.Join(missing, " ")))
  285. }
  286. download := func(pkg string, url string) {
  287. defer wg.Done()
  288. if _, err := gitDownloadABS(url, config.BuildDir, pkg); err != nil {
  289. errs.Add(fmt.Errorf("%s Failed to get pkgbuild: %s: %s", bold(red(arrow)), bold(cyan(pkg)), bold(red(err.Error()))))
  290. return
  291. }
  292. _, stderr, err := capture(exec.Command("ln", "-s", filepath.Join(config.BuildDir, pkg, "trunk"), filepath.Join(path, pkg)))
  293. mux.Lock()
  294. downloaded++
  295. if err != nil {
  296. errs.Add(fmt.Errorf("%s Failed to link %s: %s", bold(red(arrow)), bold(cyan(pkg)), bold(red(stderr))))
  297. } else {
  298. fmt.Printf(bold(cyan("::"))+" Downloaded PKGBUILD from ABS (%d/%d): %s\n", downloaded, len(names), cyan(pkg))
  299. }
  300. mux.Unlock()
  301. }
  302. count := 0
  303. for name, url := range names {
  304. wg.Add(1)
  305. go download(name, url)
  306. count++
  307. if count%25 == 0 {
  308. wg.Wait()
  309. }
  310. }
  311. wg.Wait()
  312. errs.Add(os.RemoveAll(filepath.Join(config.BuildDir, "packages")))
  313. return len(missing) != 0, errs.Return()
  314. }