Last active
August 4, 2020 14:01
-
-
Save defeated/ed6e0f8361e4becb81ecd670cfd1eb9e to your computer and use it in GitHub Desktop.
GitHub API GraphQL - list stale branches
This file contains hidden or 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
package main | |
import _ "github.com/joho/godotenv/autoload" | |
import "github.com/shurcooL/githubv4" | |
import "golang.org/x/oauth2" | |
import ( | |
"context" | |
"fmt" | |
"log" | |
"os" | |
"sort" | |
"time" | |
) | |
func main() { | |
token := os.Getenv("GITHUB_ACCESS_TOKEN") | |
owner := os.Getenv("GITHUB_REPO_OWNER") | |
name := os.Getenv("GITHUB_REPO_NAME") | |
src := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token}) | |
httpClient := oauth2.NewClient(context.Background(), src) | |
client := githubv4.NewClient(httpClient) | |
// define the structure of the query and response object | |
var query struct { | |
Repository struct { | |
Refs struct { | |
Nodes []struct { | |
Name string | |
Target struct { | |
Commit struct { | |
CommittedDate time.Time | |
Author struct { | |
User struct { | |
Login string | |
} | |
} | |
} `graphql:"... on Commit"` | |
} | |
} | |
} `graphql:"refs(first: 100, refPrefix: \"refs/heads/\")"` | |
} `graphql:"repository(owner: $owner, name: $name)"` | |
} | |
// pass variables into query | |
vars := map[string]interface{}{ | |
"owner": githubv4.String(owner), | |
"name": githubv4.String(name), | |
} | |
// execute query and handle errors | |
err := client.Query(context.Background(), &query, vars) | |
if err != nil { | |
log.Fatal(err) | |
} | |
// get results and sort by date committed | |
nodes := query.Repository.Refs.Nodes | |
sort.SliceStable(nodes, func(i, j int) bool { | |
return nodes[i].Target.Commit.CommittedDate.Before(nodes[j].Target.Commit.CommittedDate) | |
}) | |
// create type to flatten results | |
type Branch struct { | |
Name string | |
Date time.Time | |
} | |
// group results by user, exclude master branch and recent branches | |
report := make(map[string][]Branch) | |
for _, node := range nodes { | |
committed := node.Target.Commit.CommittedDate | |
cutoff := time.Now().AddDate(0, -1, 0) | |
if node.Name != "master" && committed.Before(cutoff) { | |
login := node.Target.Commit.Author.User.Login | |
report[login] = append(report[login], Branch{node.Name, committed}) | |
} | |
} | |
// output the results | |
for user, branches := range report { | |
fmt.Printf("%v (%d)\n", user, len(branches)) | |
for _, branch := range branches { | |
fmt.Printf("\t%v on %v\n", branch.Name, branch.Date.Format("2006-01-02")) | |
} | |
fmt.Println("") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment