开源 企业版 高校版 私有云 模力方舟 AI 队友
代码拉取完成,页面将自动刷新
捐赠
捐赠前请先登录
扫描微信二维码支付
取消
支付完成
支付提示
将跳转至支付宝完成支付
确定
取消
1 Star 0 Fork 0

tize/opencode

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
已有帐号? 立即登录
文件
dev
分支 (592)
标签 (1040)
dev
feat/opencode-embedded-api
beta
fix/acp-load-history
feat/core-command-registry
fix/opencode-shell-cancel-race
jlongster/move-session
production
kit/tui-subagent-background-hint
fix/openai-websocket-header-timeout
otui-musl
refactor/remove-aisdk-option-fields
dustin/improve-memory-usage
feat/sdk-oagen-effect-emitter
nxl/consolidate-project-references
chore/bedrock-sdk-bumps
fix/prompt-loop-shutdown
oc-opentui-path-must-be-string
feat/stripe-lake-ingest
kit/tui-scenario-frames
github-v1.2.25
v1.15.13
pr-29948-screenshots
v1.15.12
github-v1.2.24
github-v1.2.23
v1.15.11
v1.15.10
v1.15.9
v1.15.7
v1.15.6
v1.15.5
v1.15.4
v1.15.3
v1.15.2
v1.15.1
v1.15.0
v1.14.51
v1.14.50
v1.14.49
dev
分支 (592)
标签 (1040)
dev
feat/opencode-embedded-api
beta
fix/acp-load-history
feat/core-command-registry
fix/opencode-shell-cancel-race
jlongster/move-session
production
kit/tui-subagent-background-hint
fix/openai-websocket-header-timeout
otui-musl
refactor/remove-aisdk-option-fields
dustin/improve-memory-usage
feat/sdk-oagen-effect-emitter
nxl/consolidate-project-references
chore/bedrock-sdk-bumps
fix/prompt-loop-shutdown
oc-opentui-path-must-be-string
feat/stripe-lake-ingest
kit/tui-scenario-frames
github-v1.2.25
v1.15.13
pr-29948-screenshots
v1.15.12
github-v1.2.24
github-v1.2.23
v1.15.11
v1.15.10
v1.15.9
v1.15.7
v1.15.6
v1.15.5
v1.15.4
v1.15.3
v1.15.2
v1.15.1
v1.15.0
v1.14.51
v1.14.50
v1.14.49
克隆/下载
克隆/下载
提示
下载代码请复制以下命令到终端执行
为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置
初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置
1 生成 RSA 密钥
2 获取 RSA 公钥内容,并配置到 SSH公钥
在 Gitee 上使用 SVN,请访问 使用指南
使用 HTTPS 协议时,命令行会出现如下账号密码验证步骤。基于安全考虑,Gitee 建议 配置并使用私人令牌 替代登录密码进行克隆、推送等操作
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # 私人令牌
dev
分支 (592)
标签 (1040)
dev
feat/opencode-embedded-api
beta
fix/acp-load-history
feat/core-command-registry
fix/opencode-shell-cancel-race
jlongster/move-session
production
kit/tui-subagent-background-hint
fix/openai-websocket-header-timeout
otui-musl
refactor/remove-aisdk-option-fields
dustin/improve-memory-usage
feat/sdk-oagen-effect-emitter
nxl/consolidate-project-references
chore/bedrock-sdk-bumps
fix/prompt-loop-shutdown
oc-opentui-path-must-be-string
feat/stripe-lake-ingest
kit/tui-scenario-frames
github-v1.2.25
v1.15.13
pr-29948-screenshots
v1.15.12
github-v1.2.24
github-v1.2.23
v1.15.11
v1.15.10
v1.15.9
v1.15.7
v1.15.6
v1.15.5
v1.15.4
v1.15.3
v1.15.2
v1.15.1
v1.15.0
v1.14.51
v1.14.50
v1.14.49
opencode
/
script
/
github
/
close-prs.ts
opencode
/
script
/
github
/
close-prs.ts
close-prs.ts 13.10 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 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
#!/usr/bin/env bun
import { parseArgs } from "util"
const defaultRepo = "anomalyco/opencode"
const defaultAgeMonths = 1
const defaultThreshold = 2
const defaultSleepMs = 20_000
const defaultPrintLimit = 50
const positiveReactions = new Set(["THUMBS_UP", "HEART", "HOORAY", "ROCKET"])
const cleanupLabel = "automated-pr-cleanup"
const { values } = parseArgs({
args: Bun.argv.slice(2),
options: {
execute: { type: "boolean", default: false },
"dry-run": { type: "boolean", default: false },
repo: { type: "string", default: defaultRepo },
threshold: { type: "string", default: String(defaultThreshold) },
"age-months": { type: "string", default: String(defaultAgeMonths) },
"max-close": { type: "string" },
"sleep-ms": { type: "string", default: String(defaultSleepMs) },
"print-limit": { type: "string", default: String(defaultPrintLimit) },
help: { type: "boolean", short: "h", default: false },
},
})
if (values.help) {
console.log(`
Usage: bun script/github/close-prs.ts [options]
Dry-run is the default. The script only comments and closes PRs when --execute is passed.
Criteria:
- PRs created within the last month are untouched
- PRs older than one month are closed when they have fewer than 2 positive reactions
- Positive reactions are THUMBS_UP, HEART, HOORAY, and ROCKET reactions on the PR
Options:
--execute Comment and close matching PRs
--dry-run Explicitly run without changing anything
--repo <owner/repo> Repository to clean up (default: ${defaultRepo})
--threshold <n> Positive reaction threshold (default: ${defaultThreshold})
--age-months <n> Age cutoff in months (default: ${defaultAgeMonths})
--max-close <n> Maximum matching PRs to process
--sleep-ms <n> Delay between closing PRs (default: ${defaultSleepMs})
--print-limit <n> Number of matching PRs to print in dry-run (default: ${defaultPrintLimit})
-h, --help Show this help message
Examples:
bun script/github/close-prs.ts
bun script/github/close-prs.ts --threshold 2 --print-limit 100
bun script/github/close-prs.ts --execute --threshold 2 --max-close 25
`)
process.exit(0)
}
if (values.execute && values["dry-run"]) {
console.error("Use either --execute or --dry-run, not both")
process.exit(1)
}
const token = await requireToken()
const repo = requireRepo(values.repo)
const threshold = requirePositiveInteger("threshold", values.threshold)
const ageMonths = requirePositiveInteger("age-months", values["age-months"])
const maxClose =
values["max-close"] === undefined ? undefined : requirePositiveInteger("max-close", values["max-close"])
const sleepMs = requireNonNegativeInteger("sleep-ms", values["sleep-ms"])
const printLimit = requireNonNegativeInteger("print-limit", values["print-limit"])
const cutoff = subtractMonths(new Date(), ageMonths)
const headers = {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
Accept: "application/vnd.github+json",
"X-GitHub-Api-Version": "2022年11月28日",
}
type PullRequest = {
number: number
title: string
url: string
createdAt: string
reactionGroups: Array<{
content: string
users: {
totalCount: number
}
}>
labels: {
nodes: Array<{
name: string
}>
}
}
type GraphqlResponse = {
data?: {
rateLimit: {
cost: number
remaining: number
resetAt: string
}
repository: {
pullRequests: {
pageInfo: {
hasNextPage: boolean
endCursor: string | null
}
nodes: PullRequest[]
}
}
}
errors?: Array<{
message: string
}>
}
type CleanupCandidate = PullRequest & {
positiveReactions: number
}
const message = `Automated PR Cleanup
Thank you for contributing to opencode.
Due to the high volume of PRs from users and AI agents, we periodically close older PRs using automated criteria so maintainers can focus review time on the most active and community-supported contributions.
This PR was closed because it matched the following cleanup criteria:
- The PR was created more than ${ageMonths === 1 ? "1 month" : `${ageMonths} months`} ago
- The PR had fewer than ${threshold} positive reactions
- Positive reactions are counted as thumbs-up, heart, celebration, or rocket reactions on the PR
PRs created within the last ${ageMonths === 1 ? "month are" : `${ageMonths} months are`} not affected by this cleanup.
If you believe this PR was closed incorrectly, or if you are still actively working on it, please leave a comment explaining why it should be reopened. A maintainer can review and reopen it if appropriate.
Thanks again for taking the time to contribute.`
async function main() {
console.log(`${values.execute ? "EXECUTE" : "DRY RUN"}: PR cleanup for ${repo.owner}/${repo.name}`)
console.log(`Cutoff: ${cutoff.toISOString()}`)
console.log(`Threshold: fewer than ${threshold} positive reactions`)
const prs = await fetchOpenPullRequests()
const recentCount = prs.filter((pr) => new Date(pr.createdAt) >= cutoff).length
const matching = prs
.map((pr) => ({ ...pr, positiveReactions: positiveReactionCount(pr) }))
.filter((pr) => new Date(pr.createdAt) < cutoff && pr.positiveReactions < threshold)
const candidates = matching.filter((pr) => !hasPriorCleanup(pr))
const selected = maxClose === undefined ? candidates : candidates.slice(0, maxClose)
console.log(`Fetched ${prs.length} open PRs`)
console.log(`Matching cleanup criteria: ${matching.length}`)
console.log(`Skipped previously cleaned PRs: ${matching.length - candidates.length}`)
console.log(`Recent PRs untouched: ${recentCount}`)
console.log(
`Older PRs with at least ${threshold} positive reactions untouched: ${prs.length - matching.length - recentCount}`,
)
if (selected.length === 0) return
if (!values.execute) {
console.log(`\nDry-run only. Re-run with --execute to comment and close matching PRs.`)
console.log(`Showing ${Math.min(printLimit, selected.length)} of ${selected.length} matching PRs:\n`)
for (const pr of selected.slice(0, printLimit)) {
console.log(`#${pr.number}${pr.createdAt} positive=${pr.positiveReactions}${pr.url}`)
}
if (selected.length > printLimit) console.log(`... ${selected.length - printLimit} more not shown`)
return
}
await ensureCleanupLabel()
console.log(`\nCommenting and closing ${selected.length} PRs...`)
for (const pr of selected) {
await closePullRequest(pr)
if (sleepMs > 0) await sleep(sleepMs)
}
console.log(`Closed ${selected.length} PRs`)
}
async function fetchOpenPullRequests() {
const prs: PullRequest[] = []
let endCursor: string | null = null
while (true) {
const page = await graphql({
query: `query($owner: String!, $name: String!, $endCursor: String) {
rateLimit {
cost
remaining
resetAt
}
repository(owner: $owner, name: $name) {
pullRequests(first: 100, states: OPEN, orderBy: { field: CREATED_AT, direction: ASC }, after: $endCursor) {
pageInfo {
hasNextPage
endCursor
}
nodes {
number
title
url
createdAt
reactionGroups {
content
users {
totalCount
}
}
labels(first: 100) {
nodes {
name
}
}
}
}
}
}`,
variables: {
owner: repo.owner,
name: repo.name,
endCursor,
},
})
prs.push(...page.repository.pullRequests.nodes)
console.log(
`Fetched ${prs.length} PRs, GraphQL rate limit remaining ${page.rateLimit.remaining} (cost ${page.rateLimit.cost})`,
)
if (page.rateLimit.remaining < 100) {
const delay = Math.max(0, new Date(page.rateLimit.resetAt).getTime() - Date.now()) + 1_000
console.warn(`GraphQL rate limit low; sleeping ${Math.ceil(delay / 1000)}s until reset`)
await sleep(delay)
}
if (!page.repository.pullRequests.pageInfo.hasNextPage) return prs
endCursor = page.repository.pullRequests.pageInfo.endCursor
}
}
async function graphql(input: { query: string; variables: Record<string, string | null> }) {
const response = await githubRequest("/graphql", {
method: "POST",
body: JSON.stringify(input),
})
const body = (await response.json()) as GraphqlResponse
if (body.errors?.length)
throw new Error(`GitHub GraphQL error: ${body.errors.map((error) => error.message).join(", ")}`)
if (!body.data) throw new Error("GitHub GraphQL response did not include data")
return body.data
}
async function closePullRequest(pr: CleanupCandidate) {
await githubRequest(`/repos/${repo.owner}/${repo.name}/issues/${pr.number}/comments`, {
method: "POST",
body: JSON.stringify({ body: message }),
})
await githubRequest(`/repos/${repo.owner}/${repo.name}/pulls/${pr.number}`, {
method: "PATCH",
body: JSON.stringify({ state: "closed" }),
})
await githubRequest(`/repos/${repo.owner}/${repo.name}/issues/${pr.number}/labels`, {
method: "POST",
body: JSON.stringify({ labels: [cleanupLabel] }),
})
console.log(`Closed #${pr.number} positive=${pr.positiveReactions}${pr.url}`)
}
async function ensureCleanupLabel() {
const response = await fetch(
`https://api.github.com/repos/${repo.owner}/${repo.name}/labels/${encodeURIComponent(cleanupLabel)}`,
{
headers,
},
)
if (response.ok) return
if (response.status !== 404)
throw new Error(`Failed to check cleanup label: ${response.status}${response.statusText}`)
await githubRequest(`/repos/${repo.owner}/${repo.name}/labels`, {
method: "POST",
body: JSON.stringify({
name: cleanupLabel,
color: "ededed",
description: "PR was closed by automated cleanup",
}),
})
}
async function githubRequest(path: string, init: RequestInit, attempt = 0): Promise<Response> {
const response = await fetch(path.startsWith("https://") ? path : `https://api.github.com${path}`, {
...init,
headers: {
...headers,
...init.headers,
},
})
if (response.ok) return response
const body = await response.text()
const retryAfter = response.headers.get("retry-after")
const reset = response.headers.get("x-ratelimit-reset")
const retryMs = retryAfter
? Number(retryAfter) * 1000
: response.headers.get("x-ratelimit-remaining") === "0" && reset
? Math.max(0, Number(reset) * 1000 - Date.now()) + 1_000
: body.toLowerCase().includes("secondary rate limit")
? 300_000
: response.status >= 500
? Math.min(300_000, 10_000 * 2 ** attempt)
: 0
if ((response.status === 403 || response.status === 429 || response.status >= 500) && retryMs > 0 && attempt < 10) {
console.warn(`GitHub request failed; sleeping ${Math.ceil(retryMs / 1000)}s before retry ${attempt + 1}`)
await sleep(retryMs)
return githubRequest(path, init, attempt + 1)
}
throw new Error(`GitHub request failed: ${response.status}${response.statusText}\n${body}`)
}
function positiveReactionCount(pr: PullRequest) {
return pr.reactionGroups
.filter((group) => positiveReactions.has(group.content))
.reduce((total, group) => total + group.users.totalCount, 0)
}
function hasPriorCleanup(pr: PullRequest) {
return pr.labels.nodes.some((label) => label.name === cleanupLabel)
}
function requireRepo(value: string | undefined) {
if (!value) throw new Error("repo is required")
const [owner, name] = value.split("/")
if (!owner || !name) throw new Error(`Invalid repo ${value}; expected owner/name`)
return { owner, name }
}
async function requireToken() {
const envToken = process.env.GITHUB_TOKEN ?? process.env.GH_TOKEN
if (envToken) return envToken
const proc = Bun.spawn(["gh", "auth", "token"], {
stdout: "pipe",
stderr: "pipe",
})
const stdout = await new Response(proc.stdout).text()
const stderr = await new Response(proc.stderr).text()
const exitCode = await proc.exited
if (exitCode === 0 && stdout.trim()) return stdout.trim()
throw new Error(
`GitHub authentication is required. Set GITHUB_TOKEN/GH_TOKEN or run gh auth login.\n${stderr.trim()}`,
)
}
function requirePositiveInteger(name: string, value: string | undefined) {
const parsed = Number(value)
if (!Number.isInteger(parsed) || parsed <= 0) throw new Error(`${name} must be a positive integer`)
return parsed
}
function requireNonNegativeInteger(name: string, value: string | undefined) {
const parsed = Number(value)
if (!Number.isInteger(parsed) || parsed < 0) throw new Error(`${name} must be a non-negative integer`)
return parsed
}
function subtractMonths(date: Date, months: number) {
const result = new Date(date)
const day = result.getUTCDate()
result.setUTCDate(1)
result.setUTCMonth(result.getUTCMonth() - months)
result.setUTCDate(
Math.min(day, new Date(Date.UTC(result.getUTCFullYear(), result.getUTCMonth() + 1, 0)).getUTCDate()),
)
return result
}
function sleep(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms))
}
void main().catch((error) => {
console.error("Error:", error)
process.exit(1)
})
Loading...
举报
举报成功
我们将于2个工作日内通过站内信反馈结果给你!
请认真填写举报原因,尽可能描述详细。
请选择举报类型
取消
发送
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

简介

暂无描述
取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
编辑仓库简介
简介内容
主页
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/tize/opencode.git
git@gitee.com:tize/opencode.git
tize
opencode
opencode
dev
点此查找更多帮助

搜索帮助

评论
仓库举报
回到顶部
登录提示
该操作需登录 Gitee 帐号,请先登录后再操作。
立即登录
没有帐号,去注册

AltStyle によって変換されたページ (->オリジナル) /