vcs.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. package vcs
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "os"
  7. "os/exec"
  8. "strings"
  9. "sync"
  10. "time"
  11. gosrc "github.com/Morganamilo/go-srcinfo"
  12. "github.com/leonelquinteros/gotext"
  13. "github.com/Jguer/yay/v11/pkg/settings/exe"
  14. "github.com/Jguer/yay/v11/pkg/text"
  15. )
  16. type Store interface {
  17. Update(ctx context.Context, pkgName string,
  18. sources []gosrc.ArchString, mux sync.Locker, wg *sync.WaitGroup,
  19. )
  20. Save() error
  21. RemovePackage(pkgs []string)
  22. Load() error
  23. }
  24. // InfoStore is a collection of OriginInfoByURL by Package.
  25. // Containing a map of last commit SHAs of a repo.
  26. type InfoStore struct {
  27. OriginsByPackage map[string]OriginInfoByURL
  28. FilePath string
  29. CmdBuilder exe.GitCmdBuilder
  30. }
  31. // OriginInfoByURL stores the OriginInfo of each origin URL provided.
  32. type OriginInfoByURL map[string]OriginInfo
  33. // OriginInfo contains the last commit sha of a repo
  34. // Example:
  35. //
  36. // "github.com/Jguer/yay.git": {
  37. // "protocols": [
  38. // "https"
  39. // ],
  40. // "branch": "next",
  41. // "sha": "c1171d41467c68ffd3c46748182a16366aaaf87b"
  42. // }.
  43. type OriginInfo struct {
  44. Protocols []string `json:"protocols"`
  45. Branch string `json:"branch"`
  46. SHA string `json:"sha"`
  47. }
  48. func NewInfoStore(filePath string, cmdBuilder exe.GitCmdBuilder) *InfoStore {
  49. infoStore := &InfoStore{
  50. CmdBuilder: cmdBuilder,
  51. FilePath: filePath,
  52. OriginsByPackage: map[string]OriginInfoByURL{},
  53. }
  54. return infoStore
  55. }
  56. // GetCommit parses HEAD commit from url and branch.
  57. func (v *InfoStore) getCommit(ctx context.Context, url, branch string, protocols []string) string {
  58. if len(protocols) > 0 {
  59. protocol := protocols[len(protocols)-1]
  60. ctxTimeout, cancel := context.WithTimeout(ctx, 5*time.Second)
  61. defer cancel()
  62. cmd := v.CmdBuilder.BuildGitCmd(ctxTimeout, "", "ls-remote", protocol+"://"+url, branch)
  63. stdout, _, err := v.CmdBuilder.Capture(cmd)
  64. if err != nil {
  65. if exiterr, ok := err.(*exec.ExitError); ok && exiterr.ExitCode() == 128 {
  66. text.Warnln(gotext.Get("devel check for package failed: '%s' encountered an error", cmd.String()))
  67. return ""
  68. }
  69. text.Warnln(err)
  70. return ""
  71. }
  72. split := strings.Fields(stdout)
  73. if len(split) < 2 {
  74. return ""
  75. }
  76. commit := split[0]
  77. return commit
  78. }
  79. return ""
  80. }
  81. func (v *InfoStore) Update(ctx context.Context, pkgName string,
  82. sources []gosrc.ArchString, mux sync.Locker, wg *sync.WaitGroup,
  83. ) {
  84. defer wg.Done()
  85. info := make(OriginInfoByURL)
  86. checkSource := func(source gosrc.ArchString) {
  87. defer wg.Done()
  88. url, branch, protocols := parseSource(source.Value)
  89. if url == "" || branch == "" {
  90. return
  91. }
  92. commit := v.getCommit(ctx, url, branch, protocols)
  93. if commit == "" {
  94. return
  95. }
  96. mux.Lock()
  97. info[url] = OriginInfo{
  98. protocols,
  99. branch,
  100. commit,
  101. }
  102. v.OriginsByPackage[pkgName] = info
  103. text.Warnln(gotext.Get("Found git repo: %s", text.Cyan(url)))
  104. if err := v.Save(); err != nil {
  105. fmt.Fprintln(os.Stderr, err)
  106. }
  107. mux.Unlock()
  108. }
  109. for _, source := range sources {
  110. wg.Add(1)
  111. go checkSource(source)
  112. }
  113. }
  114. // parseSource returns the git url, default branch and protocols it supports.
  115. func parseSource(source string) (url, branch string, protocols []string) {
  116. split := strings.Split(source, "::")
  117. source = split[len(split)-1]
  118. split = strings.SplitN(source, "://", 2)
  119. if len(split) != 2 {
  120. return "", "", nil
  121. }
  122. protocols = strings.SplitN(split[0], "+", 2)
  123. git := false
  124. for _, protocol := range protocols {
  125. if protocol == "git" {
  126. git = true
  127. break
  128. }
  129. }
  130. protocols = protocols[len(protocols)-1:]
  131. if !git {
  132. return "", "", nil
  133. }
  134. split = strings.SplitN(split[1], "#", 2)
  135. if len(split) == 2 {
  136. secondSplit := strings.SplitN(split[1], "=", 2)
  137. if secondSplit[0] != "branch" {
  138. // source has #commit= or #tag= which makes them not vcs
  139. // packages because they reference a specific point
  140. return "", "", nil
  141. }
  142. if len(secondSplit) == 2 {
  143. url = split[0]
  144. branch = secondSplit[1]
  145. }
  146. } else {
  147. url = split[0]
  148. branch = "HEAD"
  149. }
  150. url = strings.Split(url, "?")[0]
  151. branch = strings.Split(branch, "?")[0]
  152. return url, branch, protocols
  153. }
  154. func (v *InfoStore) NeedsUpdate(ctx context.Context, infos OriginInfoByURL) bool {
  155. // used to signal we have gone through all sources and found nothing
  156. finished := make(chan struct{})
  157. alive := 0
  158. // if we find an update we use this to exit early and return true
  159. hasUpdate := make(chan struct{})
  160. closed := make(chan struct{})
  161. defer close(closed)
  162. checkHash := func(url string, info OriginInfo) {
  163. hash := v.getCommit(ctx, url, info.Branch, info.Protocols)
  164. var sendTo chan<- struct{}
  165. if hash != "" && hash != info.SHA {
  166. sendTo = hasUpdate
  167. } else {
  168. sendTo = finished
  169. }
  170. select {
  171. case sendTo <- struct{}{}:
  172. case <-closed:
  173. }
  174. }
  175. for url, info := range infos {
  176. alive++
  177. go checkHash(url, info)
  178. }
  179. for {
  180. select {
  181. case <-hasUpdate:
  182. return true
  183. case <-finished:
  184. alive--
  185. if alive == 0 {
  186. return false
  187. }
  188. }
  189. }
  190. }
  191. func (v *InfoStore) Save() error {
  192. marshalledinfo, err := json.MarshalIndent(v.OriginsByPackage, "", "\t")
  193. if err != nil || string(marshalledinfo) == "null" {
  194. return err
  195. }
  196. in, err := os.OpenFile(v.FilePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o644)
  197. if err != nil {
  198. return err
  199. }
  200. defer in.Close()
  201. if _, errM := in.Write(marshalledinfo); errM != nil {
  202. return errM
  203. }
  204. return in.Sync()
  205. }
  206. // RemovePackage removes package from VCS information.
  207. func (v *InfoStore) RemovePackage(pkgs []string) {
  208. updated := false
  209. for _, pkgName := range pkgs {
  210. if _, ok := v.OriginsByPackage[pkgName]; ok {
  211. delete(v.OriginsByPackage, pkgName)
  212. updated = true
  213. }
  214. }
  215. if updated {
  216. if err := v.Save(); err != nil {
  217. fmt.Fprintln(os.Stderr, err)
  218. }
  219. }
  220. }
  221. // LoadStore reads a json file and populates a InfoStore structure.
  222. func (v InfoStore) Load() error {
  223. vfile, err := os.Open(v.FilePath)
  224. if !os.IsNotExist(err) && err != nil {
  225. return fmt.Errorf("failed to open vcs file '%s': %s", v.FilePath, err)
  226. }
  227. defer vfile.Close()
  228. if !os.IsNotExist(err) {
  229. decoder := json.NewDecoder(vfile)
  230. if err = decoder.Decode(&v.OriginsByPackage); err != nil {
  231. return fmt.Errorf("failed to read vcs '%s': %s", v.FilePath, err)
  232. }
  233. }
  234. return nil
  235. }