vcs.go 6.6 KB

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