/
repos.go
86 lines (72 loc) · 1.86 KB
/
repos.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
package main
import (
"log"
"sync"
"time"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
)
var allRepos []Repo
var mut = new(sync.RWMutex)
var lastCached = time.Now().Add(-40 * time.Minute)
type Repo struct {
ID *int `json:"id"`
Name *string `json:"name"`
FullName *string `json:"full_name"`
HTMLURL *string `json:"html_url"`
StargazersCount *int `json:"stargazers_count"`
Description *string `json:"description"`
}
func RepoCacheIsInDate() bool {
cacheLife := time.Duration(20 * time.Minute)
delta := time.Since(lastCached)
return delta > cacheLife
}
func GetRepos() ([]Repo, error) {
mut.RLock()
if len(allRepos) > 0 && RepoCacheIsInDate() {
log.Print("Using cache")
res := allRepos
mut.RUnlock()
return res, nil
}
mut.RUnlock()
mut.Lock()
defer mut.Unlock()
tc := oauth2.NewClient(oauth2.NoContext, nil)
client := github.NewClient(tc)
githubRepos := make([]github.Repository, 0)
// list all repositories for the authenticated user
opt := &github.RepositoryListByOrgOptions{
Type: "public",
ListOptions: github.ListOptions{PerPage: 50, Page: 1},
}
// get all pages of results
for {
repos, resp, err := client.Repositories.ListByOrg("gophergala2016", opt)
if err != nil {
allRepos = make([]Repo, 0)
return allRepos, err
}
for _, repo := range repos {
if *repo.Size > 0 {
githubRepos = append(githubRepos, repo)
}
}
if resp.NextPage == 0 {
break
}
opt.ListOptions.Page = resp.NextPage
}
for _, githubRepo := range githubRepos {
allRepos = append(allRepos, Repo{
ID: githubRepo.ID,
Name: githubRepo.Name,
FullName: githubRepo.FullName,
HTMLURL: githubRepo.HTMLURL,
StargazersCount: githubRepo.StargazersCount,
Description: githubRepo.Description,
})
}
return allRepos, nil
}