-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathdelete-stale-copilot-branches.yml
More file actions
110 lines (96 loc) · 3.42 KB
/
Copy pathdelete-stale-copilot-branches.yml
File metadata and controls
110 lines (96 loc) · 3.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
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}`)
}
}