@@ -91,14 +91,22 @@ main() {
9191
9292 # Create a pull request with a dynamic branch name
9393 BRANCH_PREFIX=" update-tested-up-to-version-"
94- BRANCH_NAME=" $BRANCH_PREFIX $( date +%Y%m%d%H%M%S) "
94+ BRANCH_NAME=" ${ BRANCH_PREFIX} $( date +%Y%m%d%H%M%S) "
9595
96- echo " Checking if a branch with prefix $BRANCH_PREFIX already exists."
97- if git ls-remote --heads origin | grep -q " $BRANCH_PREFIX " ; then
98- echo " A branch with prefix $BRANCH_PREFIX already exists. Exiting."
96+
97+ # All PRs open on the repo. Ones created by this action will have a known branch name.
98+ local OPEN_PRS
99+ OPEN_PRS=$( gh pr list --state open --json number,headRefName)
100+
101+ # Check for exact match and exit if found
102+ local EXACT_MATCH_PR_ID
103+ EXACT_MATCH_PR_ID=$( echo " $OPEN_PRS " | jq -r --arg exact " $BRANCH_NAME " ' .[] | select(.headRefName == $exact) | .number' )
104+ if [[ -n " $EXACT_MATCH_PR_ID " ]]; then
105+ echo " ❌ A PR already exists for branch '$BRANCH_NAME ': #$EXACT_MATCH_PR_ID "
99106 exit 0
100107 fi
101108
109+
102110 echo " Creating a new branch $BRANCH_NAME and pushing changes."
103111 git config user.name " github-actions"
104112 git config user.email
" [email protected] " @@ -142,7 +150,22 @@ main() {
142150 if [[ " ${PR_STATUS:- } " != " open" ]]; then
143151 PR_OPTIONS=" ${PR_OPTIONS} --draft"
144152 fi
145- gh pr create " $PR_OPTIONS "
153+
154+ NEW_PR_URL=$( gh pr create " $PR_OPTIONS " )
155+
156+ local PREFIX_MATCHES
157+ PREFIX_MATCHES=$( echo " $OPEN_PRS " | jq -r --arg prefix " $BRANCH_PREFIX " ' .[] | select(.headRefName | startswith($prefix)) | "\(.number) \(.headRefName)"' )
158+ while read -r pr_line; do
159+ if [[ -z " $pr_line " ]]; then
160+ continue
161+ fi
162+ local pr_number
163+ pr_number=$( echo " $pr_line " | awk ' {print $1}' )
164+ local pr_branch
165+ pr_branch=$( echo " $pr_line " | awk ' {print $2}' )
166+ echo " 🛑 Closing old PR #$pr_number from branch '$pr_branch '"
167+ gh pr close " $pr_number " --comment " Superseded by $NEW_PR_URL "
168+ done <<< " $PREFIX_MATCHES"
146169}
147170
148171main
0 commit comments