-
Notifications
You must be signed in to change notification settings - Fork 0
/
commands.go
130 lines (103 loc) · 2.29 KB
/
commands.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
126
127
128
129
130
package main
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"os"
"time"
"github.com/google/go-github/github"
"github.com/urfave/cli"
"golang.org/x/oauth2"
)
// Commands is supported CLI Command list
var Commands = []cli.Command{
commandRand,
commandIn,
}
var commandRand = cli.Command{
Name: "rand",
Usage: "select random lgtm image",
Description: `
your's github repository search.
select random lgtm image.
`,
Action: doRand,
Flags: []cli.Flag{
cli.BoolFlag{Name: "list, l", Usage: "all list images."},
},
}
var commandIn = cli.Command{
Name: "in",
Usage: "select https://lgtm.in/g image",
Description: `
lgtm.in get image
`,
Action: doIn,
}
func client() (context.Context, *http.Client) {
ctx := context.Background()
token := os.Getenv("LGTM_GITHUB_TOKEN")
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
tc := oauth2.NewClient(ctx, ts)
return ctx, tc
}
func doRand(c *cli.Context) error {
ctx, tc := client()
client := github.NewClient(tc)
owner := os.Getenv("LGTM_GITHUB_OWNER")
repo := os.Getenv("LGTM_GITHUB_REPO")
path := os.Getenv("LGTM_GITHUB_ROOT_PATH")
_, contents, _, err := client.Repositories.GetContents(ctx, owner, repo, path, nil)
if err != nil {
return err
}
exact := func(c *github.RepositoryContent) string { return c.GetHTMLURL() }
urls := mapString(contents, exact)
if c.Bool("list") {
for _, u := range urls {
fmt.Println(u)
}
} else {
url := choice(urls)
fmt.Println(url)
}
return nil
}
type output struct {
ImageURL string `json:"imageUrl"`
}
func doIn(c *cli.Context) error {
url := "https://lgtm.in/g"
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Accept", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
output := output{}
err = json.Unmarshal(body, &output)
fmt.Println(output.ImageURL)
return nil
}
func mapString(rc []*github.RepositoryContent, f func(*github.RepositoryContent) string) []string {
rcm := make([]string, len(rc))
for i, v := range rc {
rcm[i] = f(v)
}
return rcm
}
func choice(urls []string) string {
rand.Seed(time.Now().UnixNano())
return urls[rand.Intn(len(urls))]
}