-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
163 lines (150 loc) · 4.45 KB
/
main.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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
/*
* Copyright 2022 Ashok Pon Kumar
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"context"
"encoding/csv"
"fmt"
"log"
"os"
"strconv"
"time"
"github.com/ashokponkumar/github-org-stats/info"
"github.com/google/go-github/v39/github"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"golang.org/x/oauth2"
"gopkg.in/yaml.v3"
)
var (
rootCmd *cobra.Command
token string
org string
githubBaseURL string
)
const (
tokenC = "token"
orgC = "org"
)
func init() {
rootCmd = &cobra.Command{
Use: "github-org-stats",
Short: "Get the repository stats summary of any organization",
Long: `github-org-stats uses the github api to get a sense of the stats like stars and fork count of the organisation.`,
PreRun: func(cmd *cobra.Command, args []string) {
if token == "" {
token = os.Getenv("GITHUB_TOKEN")
}
},
Run: func(cmd *cobra.Command, args []string) {
ctx := context.Background()
client, err := getClient(ctx, token, githubBaseURL)
if err != nil {
logrus.Fatalf("%s", err)
}
repos, err := repos(ctx, client, org)
if err != nil {
logrus.Fatalf("Unable to get repositories : %s", err)
}
csvObj := [][]string{
{"Name", "Stars", "Forks", "IsFork", "URL", "Tags"},
}
totalStars := 0
totalForks := 0
for _, repo := range repos {
starCount := repo.GetStargazersCount()
forkCount := repo.GetForksCount()
isFork := repo.GetFork()
csvObj = append(csvObj, []string{repo.GetName(), strconv.Itoa(starCount), strconv.Itoa(forkCount), strconv.FormatBool(isFork), repo.GetURL(), fmt.Sprintf("%+v", repo.Topics)})
totalStars += starCount
totalForks += forkCount
}
f, err := os.Create("github-org-stats.csv")
if err != nil {
logrus.Fatalf("failed to open file : %s", err)
}
defer f.Close()
w := csv.NewWriter(f)
err = w.WriteAll(csvObj) // calls Flush internally
if err != nil {
log.Fatal(err)
}
logrus.Infof("Organization : %s", org)
logrus.Infof("No of stars : %d", totalStars)
logrus.Infof("No of forks : %d", totalForks)
},
}
rootCmd.Flags().StringVarP(&token, tokenC, "t", "", "github personal access token (default $GITHUB_TOKEN)")
rootCmd.Flags().StringVarP(&org, orgC, "o", "", "github organisation name")
rootCmd.MarkFlagRequired(orgC)
rootCmd.Flags().StringVar(&githubBaseURL, "github-base-url", "", "Github base url, if it is not github.com")
long := false
versionCmd := &cobra.Command{
Use: "version",
Short: "Print the version information",
Long: "Print the version information",
Run: func(*cobra.Command, []string) {
if !long {
fmt.Println(info.GetVersion())
return
}
v := info.GetVersionInfo()
ver, _ := yaml.Marshal(v)
fmt.Println(string(ver))
},
}
versionCmd.Flags().BoolVarP(&long, "long", "l", false, "Print the version details.")
rootCmd.AddCommand(versionCmd)
}
func main() {
if err := rootCmd.Execute(); err != nil {
logrus.Errorf("%s", err)
os.Exit(1)
}
}
func getClient(ctx context.Context, token, githubBaseURL string) (*github.Client, error) {
ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})
if githubBaseURL == "" {
return github.NewClient(oauth2.NewClient(ctx, ts)), nil
}
return github.NewEnterpriseClient(githubBaseURL, "", oauth2.NewClient(ctx, ts))
}
func repos(ctx context.Context, client *github.Client, org string) ([]*github.Repository, error) {
opt := &github.RepositoryListByOrgOptions{
ListOptions: github.ListOptions{PerPage: 10},
}
var allRepos []*github.Repository
for {
repos, resp, err := client.Repositories.ListByOrg(ctx, org, opt)
if err, ok := err.(*github.RateLimitError); ok {
s := err.Rate.Reset.UTC().Sub(time.Now().UTC())
if s < 0 {
s = 5 * time.Second
}
time.Sleep(s)
continue
}
if err != nil {
return allRepos, err
}
allRepos = append(allRepos, repos...)
if resp.NextPage == 0 {
break
}
opt.ListOptions.Page = resp.NextPage
}
return allRepos, nil
}