Skip to content

Instantly share code, notes, and snippets.

@koenbollen
Created March 28, 2017 10:31
Show Gist options
  • Save koenbollen/820d547f1bb7933e413e7a8adcb616e1 to your computer and use it in GitHub Desktop.
Save koenbollen/820d547f1bb7933e413e7a8adcb616e1 to your computer and use it in GitHub Desktop.
Watch Github Pull-Request for their status, exit when green.
package main
import (
"context"
"fmt"
"net/http"
"os"
"regexp"
"sort"
"strconv"
"time"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
)
func main() {
ctx := context.Background()
inputURL := os.Args[1]
rx := regexp.MustCompile(`github\.com/(?P<org>[^/]+)/(?P<rep>[^/]+)/pull/(?P<num>\d+)`)
match := rx.FindStringSubmatch(inputURL)
if len(match) < 4 {
fmt.Fprintln(os.Stderr, "invalid input url")
os.Exit(1)
}
owner, repo := match[1], match[2]
number, _ := strconv.Atoi(match[3])
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: "https://github.com/settings/tokens/new"},
)
tc := oauth2.NewClient(context.Background(), ts)
client := github.NewClient(tc)
merged, _, err := client.PullRequests.IsMerged(ctx, owner, repo, number)
if err != nil {
panic(err)
}
if merged {
fmt.Println("merged")
os.Exit(0)
}
for {
pr, _, err := client.PullRequests.Get(ctx, owner, repo, number)
if err != nil {
panic(err)
}
if pr.GetStatusesURL() == "" {
fmt.Fprintln(os.Stderr, "pr without statuses")
os.Exit(1)
}
req, _ := http.NewRequest("GET", pr.GetStatusesURL(), nil)
statuses := []github.StatusEvent{}
_, err = client.Do(ctx, req, &statuses)
if err != nil {
panic(err)
}
current := make(map[string]string)
sort.Slice(statuses, func(i, j int) bool {
return statuses[i].GetUpdatedAt().UnixNano() < statuses[j].GetUpdatedAt().UnixNano()
})
for _, status := range statuses {
current[status.GetContext()] = status.GetState()
}
success := true
for _, state := range current {
if state != "success" {
success = false
break
}
}
if success {
fmt.Println("green")
os.Exit(0)
}
time.Sleep(60 * time.Second)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment