Skip to content

Instantly share code, notes, and snippets.

@asaaki
Last active September 17, 2021 09:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asaaki/df16ae15bd85c6184af379e487f56f9d to your computer and use it in GitHub Desktop.
Save asaaki/df16ae15bd85c6184af379e487f56f9d to your computer and use it in GitHub Desktop.
Automatically delete branches of unmerged pull requests
# .github/workflows/delete-branch.yaml
name: Delete unmerged branch
on:
pull_request:
branches: [ main ]
types: [ closed ]
jobs:
worker:
runs-on: ubuntu-latest
steps:
- name: delete-branch
uses: actions/github-script@v4.1
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const { repo, owner } = context.repo;
const pull_number = context.payload.pull_request.number;
const ref = `heads/${context.payload.pull_request.head.ref}`;
const checkParams = { owner, repo, pull_number };
const deleteParams = { owner, repo, ref };
const isMerged = await (async () => {
try {
await github.pulls.checkIfMerged(checkParams);
return true;
} catch (e) {
if (e.status && e.status === 404) { return false; }
// escalate all unexpected errors
throw e;
}
})();
if (!isMerged) {
console.log(`Deleting branch: "${ref}"`);
try {
github.git.deleteRef(deleteParams);
} catch(e) {
console.log("Cannot delete branch; error:", e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment