Skip to content

Instantly share code, notes, and snippets.

@Pwuts
Last active April 27, 2023 12:52
Show Gist options
  • Save Pwuts/0dda08968e2731388461d464bda97039 to your computer and use it in GitHub Desktop.
Save Pwuts/0dda08968e2731388461d464bda97039 to your computer and use it in GitHub Desktop.
List pull requests that touch/change a specified file or path
#!/bin/bash
# dependencies: jq, gh
if [ -z "$1" ]; then
echo "Usage: list-prs-for-path PATH [branch]";
echo "Lists all PRs touching files starting with PATH";
exit 1;
fi
branch=${2:-$(gh repo view --json defaultBranchRef --jq '.defaultBranchRef.name')}
echo "Querying PRs to branch $branch touching paths starting with '$1'";
cursor=
match_count=0
while true; do
response=$(gh api graphql -f query="query {
repository($(gh repo view --json 'name,owner' --template 'owner: "{{.owner.login}}", name: "{{.name}}"')) {
pullRequests(
first: 100,
${cursor:+"after: \"$cursor\","}
states: OPEN,
baseRefName: \"$branch\",
orderBy: {
field: UPDATED_AT,
direction: DESC
}
) {
totalCount
edges {
node {
number author {
login
}
title updatedAt url
files(first: 100) {
nodes {
path
}
}
}
}
pageInfo {
endCursor
hasNextPage
}
} }
}")
# # uncomment for debugging:
# jq -r '.' <<<"$response"
errors=$(jq -r '.errors' <<< "$response")
if [ ! "$errors" = "null" ]; then
echo "GitHub API Query returned errors: $errors" >&2;
exit 1;
fi
result_set=$(jq -r '.data.repository.pullRequests' <<< "$response")
: ${total_count:=$(jq -r '.totalCount' <<< "$result_set")}
has_next_page=$(jq -r '.pageInfo.hasNextPage | select(.)' <<< "$result_set")
cursor=${has_next_page:+$(jq -r '.pageInfo.endCursor' <<< "$result_set")}
matching_pull_requests=$(jq -r --arg path "$1" '
.edges
| map(.node | select(
.files.nodes | map(select(.path | startswith($path))) | length > 0
))
' <<< "$result_set")
((match_count+=$(jq -r 'length' <<< "$matching_pull_requests")))
jq -r --arg path "$1" '.[]
| {
number: .number, title: .title, author: .author.login,
updatedAt: .updatedAt,
url: .url,
matchingChangedFiles: .files.nodes | map(.path | select(startswith($path)))
}
' <<< "$matching_pull_requests"
[ -n "$cursor" ] || break;
done;
echo "Matched $match_count out of $total_count open pull requests for branch '$branch'";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment