Delete stale copilot branches #179
This file contains hidden or 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
| name: Delete stale copilot branches | |
| on: | |
| schedule: | |
| - cron: "0 */6 * * *" | |
| workflow_dispatch: | |
| permissions: | |
| contents: write | |
| jobs: | |
| delete-stale-copilot-branches: | |
| runs-on: ubuntu-latest | |
| steps: | |
| - name: Delete stale copilot branches older than 24 hours | |
| uses: actions/github-script@v8 | |
| with: | |
| script: | | |
| const { owner, repo } = context.repo | |
| const STALE_THRESHOLD_MS = 24 * 60 * 60 * 1000 | |
| const cutoff = Date.now() - STALE_THRESHOLD_MS | |
| const branches = [] | |
| let hasNextPage = true | |
| let cursor = null | |
| while (hasNextPage) { | |
| const result = await github.graphql( | |
| `query ($owner: String!, $repo: String!, $cursor: String) { | |
| repository(owner: $owner, name: $repo) { | |
| refs(refPrefix: "refs/heads/copilot/", first: 100, after: $cursor) { | |
| nodes { | |
| name | |
| target { | |
| __typename | |
| ... on Commit { | |
| committedDate | |
| } | |
| } | |
| } | |
| pageInfo { | |
| hasNextPage | |
| endCursor | |
| } | |
| } | |
| } | |
| }`, | |
| { | |
| owner, | |
| repo, | |
| cursor | |
| } | |
| ) | |
| const refs = result.repository.refs | |
| for (const node of refs.nodes) { | |
| branches.push({ | |
| branchName: `copilot/${node.name}`, | |
| deleteRef: `heads/copilot/${node.name}`, | |
| commitDateRaw: | |
| node.target?.__typename === 'Commit' ? node.target.committedDate : null | |
| }) | |
| } | |
| hasNextPage = refs.pageInfo.hasNextPage | |
| cursor = refs.pageInfo.endCursor | |
| } | |
| if (branches.length === 0) { | |
| core.info('No copilot/* branches found.') | |
| return | |
| } | |
| const staleBranches = [] | |
| for (const branch of branches) { | |
| const { branchName, deleteRef, commitDateRaw } = branch | |
| if (!commitDateRaw) { | |
| core.warning(`Skipping ${branchName}: unable to determine commit date.`) | |
| continue | |
| } | |
| const commitDate = new Date(commitDateRaw).getTime() | |
| if (Number.isNaN(commitDate)) { | |
| core.warning(`Skipping ${branchName}: invalid commit date (${commitDateRaw}).`) | |
| continue | |
| } | |
| if (commitDate < cutoff) { | |
| staleBranches.push({ branchName, deleteRef }) | |
| } | |
| } | |
| if (staleBranches.length === 0) { | |
| core.info('No stale copilot/* branches older than 24 hours were found.') | |
| return | |
| } | |
| for (const { branchName, deleteRef } of staleBranches) { | |
| try { | |
| await github.rest.git.deleteRef({ | |
| owner, | |
| repo, | |
| ref: deleteRef | |
| }) | |
| core.info(`Deleted stale branch: ${branchName}`) | |
| } catch (error) { | |
| core.warning(`Failed to delete ${branchName}: ${error.message}`) | |
| } | |
| } |