githubgithub-apibranching-strategy

Enable branch protection rules in Github at the Organisation level


Is it possible to enable branch protection rules at the organisation level in Github so that all repositories part of that organisation inherit these rules for the applied branches. Right now its really a hassle to enable those same set of rules on a per repo basis for same set of branches.


Solution

  • I got it to work using a simple ruby script that makes use of the GitHub APIs :-

    require "json"
    require "logger"
    
    LOGGER = Logger.new(STDOUT)
    
    def run(cmd)
      LOGGER.debug("Running: #{cmd}")
      output = `#{cmd}`
      raise "Error: #{$?}" unless $?.success?
      output
    end
    
    
    def repos(page = 1, list = [])
      cmd = %Q{curl -s --user "user:pwd" https://github_url/api/v3/orgs/org_name/repos?page=#{page}}
      data = JSON.parse(run(cmd))
      list.concat(data)
      repos(page + 1, list) unless data.empty?
      list
    end
    
    repos.each do |repo|
      require 'net/http'
    require 'uri'
    require 'json'
    
    uri = URI.parse("https://github_url/api/v3/repos/org_name/#{repo["name"]}/branches/master/protection")
    request = Net::HTTP::Put.new(uri)
    request.basic_auth("user", "pwd")
    request["Accept"] = "application/vnd.github.luke-cage-preview+jso"
    request.body = JSON.dump({
      "required_status_checks" => {
        "strict" => true,
        "contexts" => [
          "continuous-integration/travis-ci"
        ]
      },
      "enforce_admins" => true,
      "required_pull_request_reviews" => {
        "dismiss_stale_reviews" => true
      },
      "restrictions" => nil
    })
    
    req_options = {
      use_ssl: uri.scheme == "https",
    }
    
    response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
      http.request(request)
    end
    end