From 0fd0ccfe92c77d7f5dbbf95ace3da711e1110087 Mon Sep 17 00:00:00 2001 From: Michael Heap Date: Thu, 18 Jun 2020 20:51:31 +0100 Subject: [PATCH] Update branch protections Thanks to https://github.com/gr2m/octokit-plugin-rename-branch for the graphql mutation + code required to do this Resolves #4 --- README.md | 1 + bin/github-default-branch | 9 +++++++++ src/branch-protection.js | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 45 insertions(+) create mode 100644 src/branch-protection.js diff --git a/README.md b/README.md index 0313696..5c3c894 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ For each repo, this tool will: - Update the default branch for the repo - Delete the old branch - Update [known URL patterns](https://github.com/mheap/github-default-branch/blob/main/src/update-content.js) in source files +- Update any branch protections for `$old` to `$new`. (This does **not** work with patterns, it has to be an exact match) ## Installation diff --git a/bin/github-default-branch b/bin/github-default-branch index 4c1e59d..7caf016 100755 --- a/bin/github-default-branch +++ b/bin/github-default-branch @@ -39,6 +39,7 @@ const createBranch = require("../src/create-branch"); const removeBranch = require("../src/remove-branch"); const updateContent = require("../src/update-content"); + const updateBranchProtection = require("../src/branch-protection"); const old = argv.old || "master"; const target = argv.new || "main"; @@ -144,6 +145,14 @@ }); } + if (argv.verbose) { + console.log(`✏️ Changing branch protections`); + } + + if (!isDryRun) { + await updateBranchProtection(owner, repo, old, target, octokit); + } + if (argv.verbose) { console.log(`✏️ Deleting old branch [${old}] in ${repo}`); } diff --git a/src/branch-protection.js b/src/branch-protection.js new file mode 100644 index 0000000..38027f0 --- /dev/null +++ b/src/branch-protection.js @@ -0,0 +1,35 @@ +module.exports = async function (owner, repo, old, target, octokit) { + // Via https://github.com/gr2m/octokit-plugin-rename-branch/blob/5d3c37439515db9f49f049e28510dc596982cb02/src/rename-branch.ts#L56-L90 + const query = `query($owner: String!, $repo: String!) { + repository(owner:$owner,name:$repo) { + branchProtectionRules(first:100) { + nodes { + id + pattern + } + } + } + }`; + const { + repository: { + branchProtectionRules: { nodes: branchProtectionRules }, + }, + } = await octokit.graphql(query, { owner, repo }); + + // there can only be one protection per pattern + const { id } = branchProtectionRules.find((rule) => rule.pattern === old); + await octokit.graphql( + `mutation($branchProtectionRuleId:ID!,$pattern:String!) { + updateBranchProtectionRule (input:{branchProtectionRuleId:$branchProtectionRuleId,pattern:$pattern}) { + branchProtectionRule { + id, + pattern + } + } + }`, + { + branchProtectionRuleId: id, + pattern: target, + } + ); +};