package contributions import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" "strings" "text/template" ) var ghc = http.Client{} var gh_token = os.Getenv("GH_TOKEN") type SearchResponse struct { Items []PRResp } type PRResp struct { Body string Title string HtmlUrl string `json:"html_url"` ClosedAt string `json:"closed_at"` RepositoryUrl string `json:"repository_url"` } type PullRequest struct { Body string Title string ClosedAt string URL string } var prtmpl = template.Must(template.New("pr").Parse(`- Title: {{.Title}} Body: {{.Body}} `)) // String returns a formatted string representation of the PullRequest func (pr PullRequest) String() string { var buf bytes.Buffer err := prtmpl.Execute(&buf, pr) if err != nil { return "" // Return empty string on error } return buf.String() } type PRMap map[string][]PullRequest var prlisttmpl = template.Must(template.New("prlist").Parse(`{{range $k, $v := .}} {{$k}}: {{$v}} {{end}}`)) func (p PRMap) String() string { var buf bytes.Buffer err := prlisttmpl.Execute(&buf, p) if err != nil { return "" // Return empty string on error } return buf.String() } func GetPRs(org, username string, from string, to string) (PRMap, error) { req, err := http.NewRequest( http.MethodGet, fmt.Sprintf( "https://api.github.com/search/issues?q=type:pr+org:%s+author:%s+is:closed+merged:%s..%s", org, username, from, to, ), nil) if err != nil { return nil, fmt.Errorf("error making request: %w", err) } req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", gh_token)) resp, err := ghc.Do(req) if err != nil { return nil, fmt.Errorf("error talking to github: %w", err) } if resp.StatusCode > 400 { b := bytes.NewBuffer(nil) io.Copy(b, resp.Body) return nil, fmt.Errorf("error talking to github: %s", b.String()) } r := &SearchResponse{} dec := json.NewDecoder(resp.Body) err = dec.Decode(&r) if err != nil { return nil, fmt.Errorf("error decoding response: %w", err) } allthings := PRMap{} for _, pr := range r.Items { reponameparts := strings.Split(pr.RepositoryUrl, "/") reponame := reponameparts[len(reponameparts)-1] if prs, ok := allthings[reponame]; !ok { allthings[reponame] = []PullRequest{{pr.Body, pr.Title, pr.ClosedAt, pr.HtmlUrl}} } else { allthings[reponame] = append(prs, PullRequest{pr.Body, pr.Title, pr.ClosedAt, pr.HtmlUrl}) } } return allthings, nil }