vcs.go 7.3 KB

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