chabala
10/24/2016 - 9:05 PM

Clear notifications for merged PRs on GitHub

Clear notifications for merged PRs on GitHub

#!/usr/bin/env bash
set -o errexit
set -o nounset
set -o xtrace

#requires curl and jq

auth="Authorization: token YOUR_SECRET_OAuth_TOKEN"

declare -i pages
headers=$(curl -I -H "${auth}" https://api.github.com/notifications)
if [[ $headers == *"Link:"* ]]
then
  links=$(echo ${headers} |grep -e "Link:")
  pages=$(echo ${links} |tr "," "\n" |grep last |grep -Eo "page=[0-9]+" |grep -Eo "[0-9]+")
else
  pages=1
fi

rm -f /tmp/notifications.json

for ((i=1; i<=$pages; i++)); do
  curl -H "${auth}" https://api.github.com/notifications?page=${i} \
    | jq -r '.[] | select(.unread) | select(.subject.type == "PullRequest") | "\(.id) \(.subject.url)"' \
    >>/tmp/notifications.json
done

#check if a pull request has been merged
is_merged() {
  local STATUS=$(curl -H "${auth}" -s -o /dev/null -w "%{http_code}\n" ${1}/merge)
  if [ $STATUS -eq 204 ]
  then
    return 0
  else
    return 1
  fi
}

#call with id and pr_url
mark_read_if_merged() {
  if is_merged $2;
  then
    curl --request PATCH -H "${auth}" https://api.github.com/notifications/threads/${1}
  fi
}

while read notification_id pr_url
do
  mark_read_if_merged $notification_id $pr_url
done < /tmp/notifications.json