批量删除github仓库

462 阅读1分钟

GitHub没有提供批量删除仓库的功能,要删除仓库,需要一个一个删除,并且要输入用户密码、仓库名二次确认,比较麻烦,但是GitHub提供了接口供你删除。可以通过调用接口的方式批量删除。

第一步:拿到你的 delet_repo token

在 GitHub settings -> Developer settings -> Personal access tokens -> Generate new token 选择 delete_repo

第二步:运行下面的代码,node server.js 即可交互式删除仓库

需要替换

  • options.path 里的 <your githubname>
  • headers 里的 <your delete token>

可以单个删除,也可以多个仓库一起删除,空格分隔

// server.js
const readline = require('node:readline')
const https = require('https')

const options = {
  hostname: 'api.github.com',
  port: 443,
  path: '/repos/<your githubname>/${repo}',
  method: 'DELETE',
  headers: {
    'User-Agent': 'node',
    Accept: 'application/vnd.github.v3+json',
    Authorization: 'token <your delete token>',
  },
}

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: 'OHAI> ',
})

console.log('====请输入仓库名====')
rl.prompt()

// 删除请求
const onDeletRepo = async (repo) => {
  return new Promise((resolve, reject) => {
    const req = https.request(options, (res) => {
      resolve()
    })

    req.on('error', (error) => {
      console.log('error', error)
      reject()
    })
    req.end()
  })
}

// 可以一次删除多个仓库
rl.on('line', async (line) => {
  const repos = line.trim().split(' ')

  while (repos.length) {
    const nextRepo = repos.shift()
    options.path = `/repos/<your githubname>/${nextRepo}`

    console.log('即将删除 repo: ', options.path)

    await onDeletRepo(nextRepo)
    console.log(nextRepo, '删除成功')
    rl.prompt()
  }
}).on('close', () => {
  process.exit(0)
})

还可以用 curl 直接删除

docs.github.com/en/rest/rep…

curl 
-X DELETE 
-H "Accept: application/vnd.github.v3+json"
-H "Authorization: token <TOKEN>" https://api.github.com/repos/<githubname>/<reponame>

使用 curl 的时候不用设置 User-Agent,会默认帮你设置,但是使用node 发送请求的时候需要设置headers.User-Agent,这里我随便设置了一个 'User-Agent': 'node'

参考user-agent-required