-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vin.go
125 lines (106 loc) · 2.15 KB
/
vin.go
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package vin
import (
"context"
"encoding/json"
"io/ioutil"
"os"
"path/filepath"
"github.com/google/go-github/v33/github"
"github.com/naoina/toml"
"golang.org/x/oauth2"
"golang.org/x/sync/errgroup"
)
// Vin represents a Vin client.
type Vin struct {
Apps []App `toml:"app"`
vinDir string
}
// newGitHubClient returns a GitHub client.
func newGitHubClient(token string) *github.Client {
if token == "" {
// w/o authentication
return github.NewClient(nil)
}
// w/ authentication
ctx := context.Background()
sts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
return github.NewClient(oauth2.NewClient(ctx, sts))
}
func DefaultVinDir() (string, error) {
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
return filepath.Join(home, ".vin"), nil
}
func (v *Vin) BinDir() string {
return filepath.Join(v.vinDir, "bin")
}
func (v *Vin) TmpDir() string {
return filepath.Join(v.vinDir, "tmp")
}
type Token struct {
Token string `json:"token"`
}
func TokenFromJSON(path string) (string, error) {
b, err := ioutil.ReadFile(path)
if err != nil {
return "", err
}
var t Token
if err := json.Unmarshal(b, &t); err != nil {
return "", err
}
return t.Token, nil
}
func (v *Vin) ReadTOML(path string) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
if err := toml.NewDecoder(f).Decode(&v); err != nil {
return err
}
return nil
}
func (v *Vin) FetchApps(token string) error {
// fetch apps from GitHub Releases
gh := newGitHubClient(token)
var eg errgroup.Group
for i := range v.Apps {
i := i
eg.Go(func() error {
if err := v.Apps[i].init(gh); err != nil {
return err
}
return nil
})
if err := eg.Wait(); err != nil {
return err
}
}
return nil
}
// New returns a Vin client.
func New(vinDir string) (*Vin, error) {
v := Vin{
vinDir: vinDir,
}
if err := os.MkdirAll(v.BinDir(), os.ModePerm); err != nil {
return nil, err
}
if err := os.MkdirAll(v.TmpDir(), os.ModePerm); err != nil {
return nil, err
}
return &v, nil
}
func (v *Vin) Repos() []string {
r := make([]string, 0)
for _, app := range v.Apps {
r = append(r, app.Repo)
}
return r
}