-
Notifications
You must be signed in to change notification settings - Fork 0
/
github.go
115 lines (92 loc) · 2.57 KB
/
github.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
package main
import (
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
)
const githubHost = "github.com"
var (
// ErrCanNotSayRespect shows that we can not give a start go github repo
ErrCanNotSayRespect = errors.New("can not say respect")
// ErrCanNotGetUsername shows that we can not get username of github user
ErrCanNotGetUsername = errors.New("can not get username")
// ErrCanNotGetToken show that we can not get access token of github user
ErrCanNotGetToken = errors.New("can not get token")
githubAPI = "https://api.github.com"
)
// GithubRespecter works with github packages
type GithubRespecter struct {
Username string
Token string
Out io.Writer
In io.Reader
}
// CanProcess func checks if we can work with this package
func (g *GithubRespecter) CanProcess(p string) bool {
return strings.Index(p, githubHost) == 0
}
// FilterRespectable func returns packages which with we can work
func (g *GithubRespecter) FilterRespectable(pkgs []string) []string {
pMap := make(map[string]bool)
res := make([]string, 0)
for _, p := range pkgs {
p = g.normalizePackageName(p, true)
if pMap[p] {
continue
}
if g.CanProcess(p) {
pMap[p] = true
res = append(res, p)
}
}
return res
}
// SayRespect func gives a star to github repos
func (g *GithubRespecter) SayRespect(p string) error {
client := http.Client{}
request, err := http.NewRequest(http.MethodPut, githubAPI+"/user/starred/"+g.normalizePackageName(p, false), nil)
if err != nil {
return err
}
request.URL.User = url.UserPassword(g.Username, g.Token)
response, err := client.Do(request)
if err != nil {
return err
}
if response.StatusCode != http.StatusNoContent {
return ErrCanNotSayRespect
}
return nil
}
func promptGithubUsername(out io.Writer, in io.Reader) (string, error) {
var username string
_, err := prompt("Enter github username: ", &username, out, in)
if err != nil {
return "", ErrCanNotGetUsername
}
return username, nil
}
func promptGithubToken(out io.Writer, in io.Reader) (string, error) {
var token string
tokenURL := fmt.Sprintf("https://%s/settings/tokens/new?scopes=public_repo&description=GoRespect", githubHost)
message := fmt.Sprintf("Please, generate and copy token here: %s\nEnter token: ", tokenURL)
_, err := prompt(message, &token, out, in)
if err != nil {
return "", ErrCanNotGetToken
}
return token, nil
}
func (g *GithubRespecter) normalizePackageName(p string, useHost bool) string {
parts := strings.Split(p, "/")
if len(parts) < 3 {
return p
}
start := 1
if useHost {
start = 0
}
return strings.Join(parts[start:3], "/")
}