Created
July 20, 2018 04:39
Star
You must be signed in to star a gist
GitHubのIssueのページネーションに対応した、画像ダウンロードスクリプト
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// zshなら | |
// read -s 'TOKEN?tokenを入れてください>' | |
// go run main.go | xargs wget | |
package main | |
import ( | |
"context" | |
"fmt" | |
"os" | |
"regexp" | |
"strconv" | |
"github.com/google/go-github/github" | |
"golang.org/x/oauth2" | |
) | |
const ( | |
owner = "serinuntius" | |
repo = "hoge" | |
issueNumber = 1 | |
) | |
var ( | |
NextPage = regexp.MustCompile(`<https.*?[?&]page=(.*?)>; rel="next"`) | |
ImageUrl = regexp.MustCompile(`["(](https.*?)[)"]`) | |
token = os.Getenv("TOKEN") | |
) | |
func main() { | |
ctx := context.Background() | |
ts := oauth2.StaticTokenSource( | |
&oauth2.Token{AccessToken: token}, | |
) | |
tc := oauth2.NewClient(ctx, ts) | |
client := github.NewClient(tc) | |
var comments []*github.IssueComment | |
nextPage := 0 | |
for { | |
var ( | |
cs []*github.IssueComment | |
err error | |
) | |
cs, err, nextPage = getComments(ctx, client, &nextPage) | |
if err != nil { | |
fmt.Println(err) | |
break | |
} | |
if nextPage == 0 { | |
comments = append(comments, cs...) | |
break | |
} | |
comments = append(comments, cs...) | |
} | |
for _, comment := range comments { | |
matches := ImageUrl.FindStringSubmatch(*comment.Body) | |
if len(matches) <= 1 { | |
continue | |
} | |
url := matches[1] | |
fmt.Println(url) | |
} | |
} | |
func getComments(ctx context.Context, client *github.Client, nextPage *int) ([]*github.IssueComment, error, int) { | |
opt := &github.IssueListCommentsOptions{ | |
ListOptions: github.ListOptions{ | |
PerPage: 100, // 100 がMaxらしい | |
Page: *nextPage, | |
}, | |
} | |
comments, resp, err := client.Issues.ListComments(ctx, owner, repo, issueNumber, opt) | |
if err != nil { | |
panic(err) | |
} | |
if links, ok := resp.Header["Link"]; ok { | |
for _, link := range links { | |
page := NextPage.FindStringSubmatch(link) | |
if len(page) <= 1 { | |
// マッチしてないので最後 | |
return comments, nil, 0 | |
} | |
if page[1] != "" { | |
p, err := strconv.ParseInt(page[1], 10, 64) | |
if err != nil { | |
return nil, err, 0 | |
} | |
return comments, nil, int(p) | |
} | |
} | |
} | |
return comments, nil, 0 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment