forked from cli/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.go
More file actions
105 lines (89 loc) · 2.09 KB
/
http.go
File metadata and controls
105 lines (89 loc) · 2.09 KB
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
package garden
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/cli/cli/v2/internal/ghinstance"
"github.com/cli/cli/v2/internal/ghrepo"
)
func getCommits(client *http.Client, repo ghrepo.Interface, maxCommits int) ([]*Commit, error) {
type Item struct {
Author struct {
Login string
}
Sha string
}
type Result []Item
commits := []*Commit{}
pathF := func(page int) string {
return fmt.Sprintf("repos/%s/%s/commits?per_page=100&page=%d", repo.RepoOwner(), repo.RepoName(), page)
}
page := 1
paginating := true
for paginating {
if len(commits) >= maxCommits {
break
}
result := Result{}
resp, err := getResponse(client, repo.RepoHost(), pathF(page), &result)
if err != nil {
return nil, err
}
for _, r := range result {
colorFunc := shaToColorFunc(r.Sha)
handle := r.Author.Login
if handle == "" {
handle = "a mysterious stranger"
}
commits = append(commits, &Commit{
Handle: handle,
Sha: r.Sha,
Char: colorFunc(string(handle[0])),
})
}
link := resp.Header["Link"]
if len(link) == 0 || !strings.Contains(link[0], "last") {
paginating = false
}
page++
time.Sleep(500)
}
// reverse to get older commits first
for i, j := 0, len(commits)-1; i < j; i, j = i+1, j-1 {
commits[i], commits[j] = commits[j], commits[i]
}
return commits, nil
}
func getResponse(client *http.Client, host, path string, data interface{}) (*http.Response, error) {
url := ghinstance.RESTPrefix(host) + path
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
success := resp.StatusCode >= 200 && resp.StatusCode < 300
if !success {
return nil, errors.New("api call failed")
}
if resp.StatusCode == http.StatusNoContent {
return resp, nil
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
err = json.Unmarshal(b, &data)
if err != nil {
return nil, err
}
return resp, nil
}