Files

58 lines
2.1 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env node
/**
* 给 Gitea 里所有仓库批量加 push webhook。
* GITEA=http://127.0.0.1:3000 TOKEN=xxx SECRET=xxx node add-hooks.mjs [--all] [--owner gitea]
* 默认只处理 owner 名下的仓库;--all 处理全部。
*/
const GITEA = (process.env.GITEA || 'http://127.0.0.1:3000').replace(/\/+$/, '')
const TOKEN = process.env.TOKEN || ''
const SECRET = process.env.SECRET || ''
const HOOK_URL = process.env.HOOK_URL || `http://127.0.0.1:8095/hook/${SECRET}`
const owner = (process.argv.find((a) => a.startsWith('--owner=')) || '').split('=')[1] || ''
const all = process.argv.includes('--all')
if (!TOKEN || !SECRET) {
console.error('用法:GITEA=http://127.0.0.1:3000 TOKEN=xxx SECRET=xxx node add-hooks.mjs')
process.exit(1)
}
const api = async (path, init = {}) => {
const res = await fetch(GITEA + '/api/v1' + path, {
...init,
headers: { Authorization: 'token ' + TOKEN, 'content-type': 'application/json', ...(init.headers || {}) },
})
const text = await res.text()
let body = null
try { body = JSON.parse(text) } catch { body = text }
return { status: res.status, body }
}
const me = await api('/user')
if (me.status !== 200) {
console.error('拿不到用户信息,检查 TOKEN:', me.status, me.body)
process.exit(1)
}
const login = owner || me.body.login
const repos = await api(`/users/${encodeURIComponent(login)}/repos?limit=50`)
if (repos.status !== 200) {
console.error('列仓库失败:', repos.status, repos.body)
process.exit(1)
}
const list = repos.body.filter((r) => all || !r.private || true)
console.log(`仓库 ${list.length} 个,钩子地址 ${HOOK_URL}`)
for (const repo of list) {
const payload = {
type: 'gitea',
active: true,
events: ['push'],
config: { url: HOOK_URL, content_type: 'json', http_method: 'post' },
}
const created = await api(`/repos/${login}/${repo.name}/hooks`, { method: 'POST', body: JSON.stringify(payload) })
if (created.status === 201) {
console.log(' ✓', repo.full_name)
} else {
console.log(' ✗', repo.full_name, created.status, JSON.stringify(created.body).slice(0, 160))
}
}