Skip to content

Instantly share code, notes, and snippets.

@antfu
Created January 12, 2023 19:51
Show Gist options
  • Save antfu/0a875e70181f12ceabb38db82abb0023 to your computer and use it in GitHub Desktop.
Save antfu/0a875e70181f12ceabb38db82abb0023 to your computer and use it in GitHub Desktop.
Remove members with no team from GitHub's org
import 'dotenv/config'
import { Octokit } from '@octokit/core'
const org = process.env.SPONSORS_ORG!
const token = process.env.SPONSORS_TOKEN!
const octokit = new Octokit({ auth: token })
const allMembers = await fetchMembers(org)
const membersWithoutTeam = new Set(allMembers.map(m => m.login))
const allTeams = await getTeams(org)
const teams = (await Promise.all(
allTeams.map(t => fetchMembers(org, t.slug)),
)).flat()
teams.forEach((element) => {
membersWithoutTeam.delete(element.login)
})
console.log(`${membersWithoutTeam.size} members without a team`)
for (const name of membersWithoutTeam)
await removeUser(org, name)
export async function fetchMembers(org: string, team?: string): Promise<{ login: string }[]> {
const members = []
let page = 1
while (page) {
const res = await octokit.request(
team
? 'GET /orgs/{org}/teams/{team_slug}/members'
: 'GET /orgs/{org}/members',
{
org,
team_slug: team,
per_page: 100,
page,
})
if (res.data.length) {
members.push(...res.data)
page++
}
else {
page = -1
}
}
return members
}
export async function removeUser(org: string, name: string) {
console.log(`Removing ${name} from ${org}`)
await octokit.request('DELETE /orgs/{org}/members/{username}', {
org,
username: name,
})
}
export async function getTeams(org: string) {
const teams = []
let page = 1
while (page) {
const res = await octokit.request('GET /orgs/{org}/teams', {
org,
per_page: 100,
page,
})
if (res.data.length) {
teams.push(...res.data)
page++
}
else {
page = -1
}
}
return teams
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment