-
Notifications
You must be signed in to change notification settings - Fork 22
/
api.go
93 lines (81 loc) · 2.17 KB
/
api.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
package glice
import (
"context"
"net/http"
"github.com/fatih/color"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
)
type licenseFormat struct {
name string
color color.Attribute
}
var licenseCol = map[string]licenseFormat{
"other": {name: "Other", color: color.FgBlue},
"mit": {name: "MIT", color: color.FgGreen},
"lgpl-3.0": {name: "LGPL-3.0", color: color.FgCyan},
"mpl-2.0": {name: "MPL-2.0", color: color.FgHiBlue},
"agpl-3.0": {name: "AGPL-3.0", color: color.FgHiCyan},
"unlicense": {name: "Unlicense", color: color.FgHiRed},
"apache-2.0": {name: "Apache-2.0", color: color.FgHiGreen},
"gpl-3.0": {name: "GPL-3.0", color: color.FgHiMagenta},
}
// Repository holds information about the repository
type Repository struct {
Name string `json:"name,omitempty"`
Shortname string `json:"-"`
URL string `json:"url,omitempty"`
Host string `json:"host,omitempty"`
Author string `json:"author,omitempty"`
Project string `json:"project,omitempty"`
Text string `json:"-"`
License string `json:"license"`
}
func newGitClient(c context.Context, keys map[string]string, star bool) *gitClient {
var tc *http.Client
var ghLogged bool
if v := keys["github.com"]; v != "" {
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: v},
)
tc = oauth2.NewClient(c, ts)
ghLogged = true
}
return &gitClient{
gh: githubClient{
Client: github.NewClient(tc),
logged: ghLogged,
},
star: star,
}
}
type gitClient struct {
gh githubClient
star bool
}
type githubClient struct {
*github.Client
logged bool
}
// GetLicense for a repository
func (gc *gitClient) GetLicense(ctx context.Context, r *Repository) error {
switch r.Host {
case "github.com":
rl, _, err := gc.gh.Repositories.License(ctx, r.Author, r.Project)
if err != nil {
return err
}
name, clr := licenseCol[*rl.License.Key].name, licenseCol[*rl.License.Key].color
if name == "" {
name = *rl.License.Key
clr = color.FgYellow
}
r.Shortname = color.New(clr).Sprintf(name)
r.License = name
r.Text = rl.GetContent()
if gc.star && gc.gh.logged {
gc.gh.Activity.Star(ctx, r.Author, r.Project)
}
}
return nil
}