Skip to content

Instantly share code, notes, and snippets.

@hkdnet

hkdnet/main.go Secret

Created February 11, 2018 13:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hkdnet/80cb431ca1337d3f45872a6b769bc595 to your computer and use it in GitHub Desktop.
Save hkdnet/80cb431ca1337d3f45872a6b769bc595 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"fmt"
"log"
"os"
_ "github.com/mattn/go-sqlite3"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
)
type pullsClient struct {
client *github.Client
}
type listPullsOption struct {
org string
repo string
author string
}
func newPullsClient(ctx context.Context, token string) *pullsClient {
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
tc := oauth2.NewClient(ctx, ts)
gc := github.NewClient(tc)
return &pullsClient{
client: gc,
}
}
func (c *pullsClient) listAndProcess(ctx context.Context, opt *listPullsOption, handler pullRequestHandler) error {
page := 1
o := &github.PullRequestListOptions{
State: "closed",
ListOptions: github.ListOptions{PerPage: 100, Page: page},
}
pulls, _, err := c.client.PullRequests.List(ctx, opt.org, opt.repo, o)
if err != nil {
return err
}
handler.handle(pulls)
return nil
// continue?
// c.listPulls(ctx, opt, page+1)
}
func authorPulls(author string, pulls []github.PullRequest) {
for _, pull := range pulls {
user := pull.GetUser()
if user.GetLogin() != author {
continue
}
fmt.Printf("%s: %s(%s)\n", user.GetLogin(), pull.GetTitle(), pull.GetMergedAt().Format("2006-01-02"))
}
}
type pullRequestHandler interface {
handle([]*github.PullRequest) error
}
type dbInserter struct {
db *dbClient
}
func (d dbInserter) handle(pulls []*github.PullRequest) error {
mapped := make([]pullRequestRecord, len(pulls))
for i, pull := range pulls {
mapped[i] = pullRequestRecord{
Number: int64(pull.GetNumber()),
State: pull.GetState(),
Title: pull.GetTitle(),
body: "", // omit
CreatedAt: pull.GetCreatedAt(),
ClosedAt: pull.GetClosedAt(),
MergedAt: pull.GetMergedAt(),
CreatedBy: pull.GetUser().GetLogin(),
Commits: int64(pull.GetCommits()),
}
}
err := d.db.insertPulls(mapped)
if err != nil {
return err
}
return nil
}
func setup() *listPullsOption {
org := os.Args[1]
repo := os.Args[2]
var author string
if len(os.Args) >= 4 {
author = os.Args[3]
}
opt := &listPullsOption{
org: org,
repo: repo,
author: author,
}
return opt
}
func main() {
db, err := newDBClient("./pulls.db")
if err != nil {
log.Fatal(err)
return
}
defer db.close()
di := dbInserter{db: db}
ctx := context.Background()
token := os.Getenv("GITHUB_TOKEN")
if len(os.Args) < 3 {
os.Exit(1)
}
client := newPullsClient(ctx, token)
opt := setup()
err = client.listAndProcess(ctx, opt, di)
if err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment