Last active
March 29, 2022 20:30
-
-
Save devinburnette/43a2502c5ce51efcac3948b803de83da to your computer and use it in GitHub Desktop.
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
require 'date' | |
require 'graphlient' | |
require 'json' | |
require 'pry' | |
require 'octokit' | |
OWNER, REPO = ARGV | |
GITHUB_TOKEN = ENV['GITHUB_TOKEN'] | |
def rest_client | |
Octokit::Client.new(access_token: GITHUB_TOKEN) | |
end | |
def graphql_client | |
Graphlient::Client.new('https://api.github.com/graphql', | |
headers: { | |
'Authorization' => "Bearer #{GITHUB_TOKEN}" | |
}, | |
http_options: { | |
read_timeout: 20, | |
write_timeout: 30 | |
} | |
) | |
end | |
def branches | |
@branches ||= graphql_client.query <<~EOF | |
{ | |
repository(owner: "#{OWNER}", name: "#{REPO}") { | |
refs(refPrefix: "refs/heads/", first: 100, orderBy: {field: TAG_COMMIT_DATE, direction: ASC}) { | |
edges { | |
node { | |
name | |
branchProtectionRule { | |
restrictsPushes | |
} | |
associatedPullRequests(first: 100, states: [OPEN, CLOSED, MERGED]) { | |
edges { | |
node { | |
url | |
closed | |
merged | |
} | |
} | |
} | |
target { | |
... on Commit { | |
author { | |
user { | |
login | |
} | |
date | |
} | |
} | |
} | |
} | |
} | |
} | |
} | |
} | |
EOF | |
end | |
branches.data.repository.refs.edges.map(&:node).each do |branch| | |
name = branch.name | |
author = branch.target.author.user&.login | |
last_commit_date = Date.parse(branch.target.author.date) | |
protected_branch = branch.branch_protection_rule | |
associated_prs = branch.associated_pull_requests.edges | |
one_year_ago = Date.today - 265 | |
next if name == "main" || name == "master" || protected_branch | |
if associated_prs.any? | |
open_prs = associated_prs.map(&:node).map { |pr| pr.merged == false || pr.closed == false } | |
next if open_prs.any? | |
pr_urls = associated_prs.map(&:node).map(&:url).join(', ') | |
puts "Deleting branch #{name} because associated PRs #{pr_urls} are closed." | |
# rest_client.delete_branch("#{OWNER}/#{REPO}", name) | |
end | |
if last_commit_date < one_year_ago | |
puts "Deleting branch #{name} because it is more than a year old" | |
# rest_client.delete_branch("#{OWNER}/#{REPO}", name) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment