autocrossbow/contributions/gh.go

114 lines
2.4 KiB
Go
Raw Normal View History

2025-09-13 08:40:40 -04:00
package contributions
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"text/template"
2025-09-13 08:40:40 -04:00
)
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
}
2025-11-26 11:34:13 -05:00
var prtmpl = template.Must(template.New("pr").Parse(`- Title: {{.Title}}
Body: {{.Body}}
`))
2025-11-26 11:34:13 -05:00
// 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
2025-11-26 11:34:13 -05:00
err := prlisttmpl.Execute(&buf, p)
if err != nil {
return "" // Return empty string on error
}
2025-11-26 11:34:13 -05:00
return buf.String()
}
2025-11-26 11:34:13 -05:00
func GetPRs(org, username string, from string, to string) (PRMap, error) {
2025-09-13 08:40:40 -04:00
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)
}
2025-11-26 11:34:13 -05:00
allthings := PRMap{}
2025-09-13 08:40:40 -04:00
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
}