/
main.go
94 lines (76 loc) · 2.12 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
package main
import (
"context"
"errors"
"io/ioutil"
"net/http"
"path/filepath"
"strings"
"github.com/google/go-github/v50/github"
"github.com/gregjones/httpcache"
"github.com/tmr232/goat"
"golang.org/x/oauth2"
)
//go:generate go run github.com/tmr232/goat/cmd/goater
func getIssues(ctx context.Context, client *github.Client, owner, repo string) ([]*github.Issue, error) {
// TODO: add pagination support
issues, _, err := client.Issues.ListByRepo(ctx, owner, repo, nil)
return issues, err
}
func newClient(token string) *github.Client {
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
tc := &http.Client{
Transport: &oauth2.Transport{
Base: httpcache.NewMemoryCacheTransport(),
Source: ts,
},
}
client := github.NewClient(tc)
return client
}
func renderPost(issue *github.Issue) (string, error) {
if issue.Title == nil {
return "", errors.New("Posts need a title!")
}
if issue.Body == nil {
return "", errors.New("Posts need a body!")
}
title := *issue.Title
body := *issue.Body
date := issue.UpdatedAt.Format("2006-01-02")
return "---\n" + "title: " + title + "\ndate: " + date + "\n---\n\n" + body, nil
}
func splitName(repoName string) (owner, repo string) {
parts := strings.Split(repoName, "/")
owner = parts[0]
repo = parts[1]
return owner, repo
}
func generateBlog(ownerAndRepo string, contentDir string, token string) error {
goat.Flag(ownerAndRepo).Name("repo")
client := newClient(token)
ctx := context.Background()
owner, repo := splitName(ownerAndRepo)
issues, err := getIssues(ctx, client, owner, repo)
if err != nil {
return err
}
for _, issue := range issues {
if issue.AuthorAssociation == nil || (*issue.AuthorAssociation != "COLLABORATOR" && *issue.AuthorAssociation != "OWNER") {
// We only show posts by collaborators.
continue
}
post, _ := renderPost(issue)
err = ioutil.WriteFile(filepath.Join(contentDir, *issue.Title+".md"), []byte(post), 0606)
if err != nil {
return err
}
}
return nil
}
func main() {
goat.Run(generateBlog)
// generateBlog("tmr232/issue-blog", filepath.Join("hugo", "content", "posts"), "token")
}