golang的私有化定制自动更新插件
zanbin168
2023-05-16 d9247a34e12ad63cc410639f25210a1018e33c85
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Package github provides a GitHub release store.
package github
 
import (
    "context"
    "time"
 
    "github.com/google/go-github/github"
    update "github.com/zan8in/goupdate"
)
 
// Store is the store implementation.
type Store struct {
    Owner   string
    Repo    string
    Version string
}
 
// GetRelease returns the specified release or ErrNotFound.
func (s *Store) GetRelease(version string) (*update.Release, error) {
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
 
    gh := github.NewClient(nil)
 
    r, res, err := gh.Repositories.GetReleaseByTag(ctx, s.Owner, s.Repo, "v"+version)
 
    if res.StatusCode == 404 {
        return nil, update.ErrNotFound
    }
 
    if err != nil {
        return nil, err
    }
 
    return githubRelease(r), nil
}
 
// LatestReleases returns releases newer than Version, or nil.
func (s *Store) LatestReleases() (latest []*update.Release, err error) {
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
 
    gh := github.NewClient(nil)
 
    releases, _, err := gh.Repositories.ListReleases(ctx, s.Owner, s.Repo, nil)
    if err != nil {
        return nil, err
    }
 
    for _, r := range releases {
        tag := r.GetTagName()
 
        if tag == s.Version || "v"+s.Version == tag {
            break
        }
 
        latest = append(latest, githubRelease(r))
    }
 
    return
}
 
// githubRelease returns a Release.
func githubRelease(r *github.RepositoryRelease) *update.Release {
    out := &update.Release{
        Version:     r.GetTagName(),
        Notes:       r.GetBody(),
        PublishedAt: r.GetPublishedAt().Time,
        URL:         r.GetURL(),
    }
 
    for _, a := range r.Assets {
        out.Assets = append(out.Assets, &update.Asset{
            Name:      a.GetName(),
            Size:      a.GetSize(),
            URL:       a.GetBrowserDownloadURL(),
            Downloads: a.GetDownloadCount(),
        })
    }
 
    return out
}