{"id":15755605,"url":"https://github.com/parkerbxyz/default-branch-protector","last_synced_at":"2025-03-13T16:32:05.056Z","repository":{"id":39696798,"uuid":"188777348","full_name":"parkerbxyz/default-branch-protector","owner":"parkerbxyz","description":"Automates the protection of the default branch upon creation of new repositories within a GitHub organization.","archived":false,"fork":false,"pushed_at":"2024-02-28T23:25:14.000Z","size":42,"stargazers_count":5,"open_issues_count":3,"forks_count":3,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-02-26T20:22:30.621Z","etag":null,"topics":["automation","github","github-api","octokit","octokit-rb","ruby","smee"],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/parkerbxyz.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-05-27T05:36:44.000Z","updated_at":"2025-02-01T18:56:16.000Z","dependencies_parsed_at":"2024-10-25T06:50:35.004Z","dependency_job_id":"4391b00b-3583-4762-8b10-4a4daf8d723e","html_url":"https://github.com/parkerbxyz/default-branch-protector","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/parkerbxyz%2Fdefault-branch-protector","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/parkerbxyz%2Fdefault-branch-protector/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/parkerbxyz%2Fdefault-branch-protector/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/parkerbxyz%2Fdefault-branch-protector/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/parkerbxyz","download_url":"https://codeload.github.com/parkerbxyz/default-branch-protector/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243441513,"owners_count":20291485,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["automation","github","github-api","octokit","octokit-rb","ruby","smee"],"created_at":"2024-10-04T08:22:31.706Z","updated_at":"2025-03-13T16:32:04.757Z","avatar_url":"https://github.com/parkerbxyz.png","language":"Ruby","funding_links":[],"categories":[],"sub_categories":[],"readme":"Adapted from [github-developer/using-the-github-api-in-your-app](https://github.com/github-developer/using-the-github-api-in-your-app).\n\nThis is an example GitHub App that automates the protection of the default branch upon creation of new repositories within a GitHub organization. The creator of the new repository will be notified with an [@mention](https://help.github.com/en/articles/basic-writing-and-formatting-syntax#mentioning-people-and-teams) in an issue within the repository that outlines the protections that were added.\n\nThis project listens for [organization events](https://developer.github.com/webhooks/#events) and uses the [Octokit.rb](https://github.com/octokit/octokit.rb) library to make REST API calls.\n\n## Prerequisites\n\nTo run this web service on your local machine, you will need to use a tool like Smee to send webhooks to your local machine without exposing it to the internet. If you're already comfortable with similar tools such as [ngrok](https://ngrok.com/) or [localtunnel](https://localtunnel.github.io/www/), feel free to use those instead.\n\n### Start a new Smee channel\n\nGo to \u003chttps://smee.io\u003e and click **Start a new channel**.\n\nStarting a new Smee channel creates a unique domain where GitHub can send webhook payloads. This domain is called a Webhook Proxy URL and looks something like this: `https://smee.io/qrfeVRbFbffd6vD`\n\n**Note:** The following steps are slightly different than the \"Use the CLI\" instructions you'll see on your Smee channel page. You do **not** need to follow the \"Use the Node.js client\" or \"Using Probot's built-in support\" instructions.\n\n1. Install the Smee client\n\n    ```sh\n    npm install --global smee-client\n    ```\n\n1. Run the client (replacing `https://smee.io/qrfeVRbFbffd6vD` with your own domain):\n\n    ```sh\n    smee --url https://smee.io/qrfeVRbFbffd6vD --path /event_handler --port 3000\n    ```\n\n    You should see output like the following:\n\n    ```sh\n    Forwarding https://smee.io/qrfeVRbFbffd6vD to http://127.0.0.1:3000/event_handler\n    Connected https://smee.io/qrfeVRbFbffd6vD\n    ```\n\n### Register a new GitHub App\n\nNext, you will need to register a new GitHub App and install it in your GitHub organization.\n\n1. Visit the settings page in your GitHub organization's profile, and click on GitHub Apps under Developer settings.\n1. Click **New GitHub App**. You'll see a form where you can enter details about your app.\n1. Give your app a name. This can be anything you'd like.\n1. For the \"Homepage URL\", use the domain issued by Smee. For example: `https://smee.io/qrfeVRbFbffd6vD`\n1. For the \"Webhook URL\", again use the domain issued by Smee.\n1. For the \"Webhook secret\", create a password to secure your webhook endpoints.\n\n    You can use the following command to generate a random string with high entropy:\n\n    ```sh\n    ruby -rsecurerandom -e 'puts SecureRandom.hex(20)'\n    ```\n\n    You'll need this secret again later, so make note of it somewhere before moving on.\n\n1. Under Permissions, specify the following **Repository permissions** for your app:\n    - **Administration** (Read \u0026 Write)\n    - **Issues** (Read \u0026 Write)\n\n1. Scroll down to **Subscribe to events** and make sure **Repository** is checked.\n\n1. At the bottom of the page, specify whether this is a private app or a public app. For now, leave the app as private by selecting **Only on this account**.\n\n1. Click **Create GitHub App** to create your app!\n\n### Save your private key and App ID\n\nAfter you create your app, you'll be taken back to the app settings page. You have two more things to do here:\n\n1. **Generate a private key for your app**. This is necessary to authenticate your app later on. Scroll down on the page and click **Generate a private key**. Save the resulting PEM file in a directory where you can find it again.\n\n1. **Note the app ID GitHub has assigned your app**. You'll need this later when you [set your environment variables](#Set-environment-variables).\n\n### Install the app on your organization account\n\nNow it's time to install the app. From your app's settings page, do the following:\n\n1. Click **Install App** in the sidebar. Next to your organization name, click **Install**.\n\n1. You'll be asked whether to install the app on all repositories or selected repositories. Select **All repositories**.\n\n1. Click **Install**.\n\n## Install\n\nRun the following command to clone this repository:\n\n```sh\ngit clone https://github.com/parkerbxyz/default-branch-protector.git\n```\n\nInstall dependencies by running the following command from the project directory:\n\n```sh\ngem install bundler \u0026\u0026 bundle install\n```\n\nWith the dependencies installed, you can [start the server](#Start-the-server).\n\n## Set environment variables\n\n1. Create a copy of the `.env-example` file called `.env`.\n\n    ```sh\n    cp .env-example .env\n    ```\n\n1. Add your GitHub App's private key, app ID, and webhook secret to the `.env` file.\n\n    \u003e **Note:** Copy the entire contents of your PEM file as the value of `GITHUB_PRIVATE_KEY` in your `.env` file.\n\n    Because the PEM file is more than one line you'll need to add quotes around the value like the example below:\n\n    ```pem\n    PRIVATE_KEY=\"-----BEGIN RSA PRIVATE KEY-----\n    ...\n    HkVN9...\n    ...\n    -----END RSA PRIVATE KEY-----\"\n    GITHUB_APP_IDENTIFIER=12345\n    GITHUB_WEBHOOK_SECRET=your-webhook-secret\n    ```\n\n## Start the server\n\n1. Run `ruby server.rb` on the command line. You should see a response like:\n\n    ```sh\n    == Sinatra (v2.0.3) has taken the stage on 3000 for development with backup from Puma\n    Puma starting in single mode...\n    * Version 3.11.2 (ruby 2.4.0-p0), codename: Love Song\n    * Min threads: 0, max threads: 16\n    * Environment: development\n    * Listening on tcp://localhost:3000\n    Use Ctrl-C to stop\n    ```\n\n1. View the Sinatra app at `localhost:3000` to verify your app is connected to the server.\n\nThe web service should now be running and watching for new repositories to be created within your organization! 🚀\n\nWhen you create a new repository in your organization, you should see some output in the Terminal tab where you started `server.rb` that looks something like this:\n\n```sh-session\nD, [2019-05-27T16:59:24.136072 #56585] DEBUG -- : ---- received event repository\nD, [2019-05-27T16:59:24.136107 #56585] DEBUG -- : ----    action created\nD, [2019-05-27T16:59:25.351392 #56585] DEBUG -- : Protecting default branch\nD, [2019-05-27T16:59:25.739671 #56585] DEBUG -- : Creating a new issue\n140.82.115.69 - - [27/May/2019:16:59:26 -0400] \"POST /event_handler HTTP/1.1\" 200 - 2.4251\n127.0.0.1 - - [27/May/2019:16:59:24 EDT] \"POST /event_handler HTTP/1.1\" 200 0\n- -\u003e /event_handler\n```\n\nThis means your app is running on the server as expected. 🙌\n\nIf you don't see the output, make sure Smee is running correctly in another Terminal tab.\n\n## Usage\n\nYou can add, remove, or modify the branch protection rules by changing the parameters inside the `options` array in the `protect_default_branch` helper method:\n\n```ruby\n# Protect the default branch on new repositories\ndef protect_default_branch(payload)\n  @repo = payload['repository']['full_name']\n  @branch = payload['repository']['default_branch']\n\n  # This is where branch protection parameters go\n  options = {\n    # This header is necessary for beta access to the branch_protection API\n    # See https://developer.github.com/v3/repos/branches/#update-branch-protection\n    accept: 'application/vnd.github.luke-cage-preview+json',\n    # Require at least two approving reviews on a pull request before merging\n    required_pull_request_reviews: { required_approving_review_count: 2 },\n    # Enforce all configured restrictions for administrators\n    enforce_admins: true\n  }\n\n  logger.debug 'Protecting default branch'\n  @installation_client.protect_branch(@repo, @branch, options)\nend\n```\n\nYou can find a list of branch protection parameters in the [GitHub Developer Guide](https://developer.github.com/v3/repos/branches/#update-branch-protection).\n\nIf you change any of the branch protection parameters in the `protect_default_branch` helper method, you should update the  `issue_body` variable in the `notify_user` helper method to reflect those changes:\n\n```ruby\n# Open an issue to notify the user of branch protection rules\ndef notify_user(payload)\n  username = payload['sender']['login']\n  help_url = 'https://help.github.com/en/articles/about-protected-branches'\n  issue_title = 'Default Branch Protected 🔐'\n\n  # An outline of the protections that were added to the default branch\n  issue_body = \u003c\u003c~BODY\n    @#{username}: branch protection rules have been added to the `#{@branch}` branch.\n    - Collaborators cannot force push to the protected branch or delete the branch\n    - All commits must be made to a non-protected branch and submitted via a pull request\n    - There must be least 2 approving reviews and no changes requested before a PR can be merged\n    \\n **Note:** All configured restrictions are enforced for administrators.\n    \\n You can learn more about protected branches here: [About protected branches - GitHub Help](#{help_url})\n  BODY\n\n  logger.debug 'Creating a new issue'\n  @installation_client.create_issue(@repo, issue_title, issue_body)\nend\n```\n\n## Troubleshooting\n\nIf you run into any problems, check out the Troubleshooting section in the \"[Setting up your development environment](https://developer.github.com/apps/quickstart-guides/setting-up-your-development-environment/#troubleshooting)\" quickstart guide on [developer.github.com](developer.github.com). If you run into any other trouble, you can [open an issue](https://github.com/parkerbxyz/default-branch-protector/issues/new) in this repository.\n\n## Resources\n\n- [Setting up your development environment | GitHub Developer Guide](https://developer.github.com/apps/quickstart-guides/setting-up-your-development-environment/)\n- [Using the GitHub API in your app | GitHub Developer Guide](https://developer.github.com/apps/quickstart-guides/using-the-github-api-in-your-app/)\n- [Branches | GitHub Developer Guide](https://developer.github.com/v3/repos/branches/#update-branch-protection)\n- [github-developer/using-the-github-api-in-your-app](https://github.com/github-developer/using-the-github-api-in-your-app)\n- \u003chttps://octokit.github.io/octokit.rb/Octokit/Client.html\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fparkerbxyz%2Fdefault-branch-protector","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fparkerbxyz%2Fdefault-branch-protector","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fparkerbxyz%2Fdefault-branch-protector/lists"}