vcs.go 7.0 KB

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