|
| 1 | +/** |
| 2 | + * Removes required CI check |
| 3 | + * |
| 4 | + * @param {import('@octoherd/octokit').Octokit} octokit |
| 5 | + * @param {import('@octokit/openapi-types').components["schemas"]["repository"]} repository |
| 6 | + * @param { {check: string} } options Custom user options passed to the CLI |
| 7 | + */ |
| 8 | +export async function script(octokit, repository, options) { |
| 9 | + if (!options.check) { |
| 10 | + throw new Error(`--check is required`); |
| 11 | + } |
| 12 | + |
| 13 | + const owner = repository.owner.login; |
| 14 | + const repo = repository.name; |
| 15 | + |
| 16 | + if (repository.archived) { |
| 17 | + octokit.log.info( |
| 18 | + { owner, repo, updated: false }, |
| 19 | + `${repository.html_url} is archived` |
| 20 | + ); |
| 21 | + return; |
| 22 | + } |
| 23 | + |
| 24 | + const branches = await octokit.paginate( |
| 25 | + "GET /repos/{owner}/{repo}/branches", |
| 26 | + { |
| 27 | + owner, |
| 28 | + repo, |
| 29 | + protected: true, |
| 30 | + } |
| 31 | + ); |
| 32 | + |
| 33 | + if (branches.length === 0) { |
| 34 | + octokit.log.info( |
| 35 | + { owner, repo, updated: false }, |
| 36 | + `No protected branches in ${owner}/${repo}` |
| 37 | + ); |
| 38 | + } |
| 39 | + |
| 40 | + try { |
| 41 | + for (const { name } of branches) { |
| 42 | + const { |
| 43 | + data: { contexts }, |
| 44 | + } = await octokit.request( |
| 45 | + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", |
| 46 | + { |
| 47 | + owner, |
| 48 | + repo, |
| 49 | + branch: name, |
| 50 | + } |
| 51 | + ); |
| 52 | + |
| 53 | + if (!contexts.includes(options.check)) { |
| 54 | + octokit.log.info( |
| 55 | + { owner, repo, updated: false, contexts }, |
| 56 | + `"${options.check}" not found in "${name}"'s branch protection in ${owner}/${repo}` |
| 57 | + ); |
| 58 | + continue; |
| 59 | + } |
| 60 | + |
| 61 | + await octokit.request( |
| 62 | + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", |
| 63 | + { |
| 64 | + owner, |
| 65 | + repo, |
| 66 | + branch: name, |
| 67 | + contexts: contexts.filter((context) => context !== options.check), |
| 68 | + } |
| 69 | + ); |
| 70 | + |
| 71 | + octokit.log.info( |
| 72 | + { owner, repo, updated: true }, |
| 73 | + `"${options.check}" removed from "${name}"'s branch protection in ${owner}/${repo}` |
| 74 | + ); |
| 75 | + } |
| 76 | + } catch (error) { |
| 77 | + if (/Required status checks not enabled/i.test(error.message)) { |
| 78 | + octokit.log.info( |
| 79 | + { owner, repo, updated: true }, |
| 80 | + `"Required status checks not enabled in ${owner}/${repo}` |
| 81 | + ); |
| 82 | + return; |
| 83 | + } |
| 84 | + |
| 85 | + throw error; |
| 86 | + } |
| 87 | +} |
0 commit comments