├── .github ├── CODEOWNERS ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md └── workflows │ ├── readme.yml │ └── validations.yml ├── .gitignore ├── CODEOWNERS ├── CODE_OF_CONDUCT.md ├── Dockerfile ├── LICENSE ├── README.md ├── automate-branch-rules.py ├── codeowners.py ├── config.py ├── header.txt └── requirements.txt /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @GrenstonGeorge @Hoyg @sriplayground -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. Ubuntu18.04] 28 | - Docker Version: [e.g. 19.03.8] 29 | - Python Version: [e.g. 3.8.1] 30 | 31 | **Additional context** 32 | Add any other context about the problem here. 33 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: 'feature' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/workflows/readme.yml: -------------------------------------------------------------------------------- 1 | name: README-Repos-List 2 | on: 3 | push: 4 | branches: [ main ] 5 | schedule: 6 | - cron: "0 0 * * 1" 7 | jobs: 8 | list: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - name: 'Checkout' 12 | uses: actions/checkout@v2 13 | - name: Run readme-repos-list 14 | uses: koj-co/readme-repos-list@master 15 | with: 16 | token: ${{ secrets.GITHUB_TOKEN }} 17 | query: "Octocat in:readme" 18 | max: 10 19 | -------------------------------------------------------------------------------- /.github/workflows/validations.yml: -------------------------------------------------------------------------------- 1 | name: Validations 2 | 3 | on: 4 | workflow_dispatch: 5 | pull_request: 6 | branches: [ main ] 7 | 8 | jobs: 9 | python: 10 | name: 'Validate Code' 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - name: 'Checkout' 15 | uses: actions/checkout@v2 16 | - name: Set up Python 3.8 17 | uses: actions/setup-python@v2 18 | with: 19 | python-version: 3.8 20 | - name: Install dependencies 21 | run: | 22 | python -m pip install --upgrade pip 23 | pip install flake8 24 | pip install -r requirements.txt 25 | - name: Lint with flake8 26 | run: | 27 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 28 | flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 29 | 30 | docker: 31 | name: 'Validate Docker Image' 32 | runs-on: ubuntu-latest 33 | 34 | steps: 35 | - uses: actions/checkout@v2 36 | name: 'Checkout' 37 | - name: 'Docker Build' 38 | run: docker build . 39 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ -------------------------------------------------------------------------------- /CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @GrenstonGeorge @Hoyg @sriplayground -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at devopstools@ecanarys.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.8-slim 2 | RUN apt-get update -y 3 | RUN pip install --upgrade pip 4 | ADD requirements.txt /requirements.txt 5 | ADD header.txt /header.txt 6 | ADD automate-branch-rules.py /automate-branch-rules.py 7 | ADD config.py /config.py 8 | ADD CODEOWNERS /CODEOWNERS 9 | ADD codeowners.py /codeowners.py 10 | RUN pip install -r /requirements.txt 11 | CMD ["python","/automate-branch-rules.py"] 12 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Canarys Automations 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Automate :curly_loop: Branch Rules (CLI) 2 | 3 | The tool lets you automate the addition, removal or alteration of the branch protection rules for 1 or more branches & repositories in one go. This helps users to bulk update the branch rules which saves lot of time when you have hundreds of branches and repositories in your organization. 4 | 5 | ## Supported branch protection rules 6 | 7 | The tool currently supports adding or modifying the below branch protection rules- 8 | 9 | - Require pull request reviews before merging 10 | - Dismiss stale pull request approvals when new commits are pushed 11 | - Require review from Code Owners 12 | - Restrict who can dismiss pull request reviews 13 | - Require status checks to pass before merging 14 | - Require branches to be up to date before merging 15 | - Require signed commits 16 | - Include administrators 17 | - Restrict who can push to matching branches 18 | - Add or update CODEOWNERS 19 | 20 | ### Prerequisites 21 | 22 | You can run the tool as **Docker Container** or cli using **Python**. Refer to the below sections in both cases. 23 | - A GitHub organization with permissions to update the branch protection rules 24 | - Git installed on your machine.[Click here](https://git-scm.com/downloads) to get the latest version of Git. 25 | 26 | #### Run as a Docker Container :whale: 27 | 28 | - [Docker](https://docs.docker.com/get-docker/) installed on your machine 29 | 30 | #### Run using Python :snake: 31 | 32 | - [Python 3.8](https://www.python.org/downloads/) or above installed on your machine 33 | 34 | - Install the latest version of pip 35 | 36 | ```python -m pip install --upgrade pip``` 37 | 38 | - Install the Python library **stdiomask** 39 | 40 | ```pip install stdiomask``` 41 | 42 | - Install the Python library **PyGithub** 43 | 44 | ```pip install pygithub``` 45 | 46 | **Note** :warning: Run the above commands as a root user **(linux)** or as an administrator mode in command prompt **(windows).** 47 | 48 | 49 | ### Usage Instructions :memo: 50 | 51 | To learn how to setup and use the tool [click here](https://github.com/CanarysDevOps/GitHub-Branch-Protector/wiki/Configure). 52 | 53 | ### Current limitations :x: :x: 54 | 55 | - The tool does not support for [Personal user accounts](https://docs.github.com/en/free-pro-team@latest/github/getting-started-with-github/types-of-github-accounts)
56 | - **Allow force pushes**, **Allow deletions** and **Require linear history** rules are not supported 57 | 58 | ## You can try the web app from [here](https://automatebranchrules.azurewebsites.net/). 59 | 60 | ## License 61 | 62 | The scripts and documentation in this project are released under the [MIT License](./LICENSE) 63 | -------------------------------------------------------------------------------- /automate-branch-rules.py: -------------------------------------------------------------------------------- 1 | """Importing necessary libraries.""" 2 | from github import Github 3 | from github import GithubException 4 | import sys 5 | from stdiomask import getpass 6 | from config import branches 7 | from config import branch_rules 8 | from config import signed_commit 9 | from config import add_codeowners_file 10 | import codeowners 11 | 12 | 13 | def add_all(pat): 14 | """Add all function.""" 15 | print("") 16 | for repo in git.get_organization(org_name).get_repos(): 17 | for branch_name in branches: 18 | try: 19 | repo.get_branch(branch_name) 20 | except GithubException: 21 | print("Error:", repo.name, ",", 22 | branch_name, "-->", sys.exc_info()[1]) 23 | else: 24 | branch = repo.get_branch(branch_name) 25 | if(add_codeowners_file): 26 | codeowners.add(org_name, pat, repo.name, branch_name) 27 | branch.edit_protection(**branch_rules) 28 | if(signed_commit): 29 | branch.add_required_signatures() 30 | else: 31 | branch.remove_required_signatures() 32 | print("Edited the branch protection rules for: " 33 | + repo.name + "," + branch_name) 34 | 35 | 36 | def add_one(pat): 37 | """Add one function.""" 38 | repo_name = input("\nRepository: ") 39 | repo = git.get_repo(org_name+"/"+repo_name) 40 | for branch_name in branches: 41 | try: 42 | repo.get_branch(branch_name) 43 | except GithubException: 44 | print("Error:", repo.name, ",", branch_name, "-->", 45 | sys.exc_info()[1]) 46 | else: 47 | branch = repo.get_branch(branch_name) 48 | if(add_codeowners_file): 49 | codeowners.add(org_name, pat, repo_name, branch_name) 50 | branch.edit_protection(**branch_rules) 51 | if(signed_commit): 52 | branch.add_required_signatures() 53 | else: 54 | branch.remove_required_signatures() 55 | print("Edited the branch protection rules for: " 56 | + repo.name + "," + branch_name) 57 | 58 | 59 | def remove_one(): 60 | """Remove One Function.""" 61 | repo_name = input("\nRepository: ") 62 | repo = git.get_repo(org_name+"/"+repo_name) 63 | for branch_name in branches: 64 | try: 65 | repo.get_branch(branch_name) 66 | except GithubException: 67 | print("Error:", repo.name, ",", 68 | branch_name, "-->", sys.exc_info()[1]) 69 | else: 70 | branch = repo.get_branch(branch_name) 71 | if (branch.protected): 72 | branch.remove_protection() 73 | print("Removed branch protection rules for: " 74 | + repo.name + "," + branch_name) 75 | else: 76 | print("No branch protection rules for: " 77 | + repo.name + "," + branch.name) 78 | 79 | 80 | def remove_all(): 81 | """Remove all function.""" 82 | print("") 83 | for repo in git.get_organization(org_name).get_repos(): 84 | for branch_name in branches: 85 | try: 86 | repo.get_branch(branch_name) 87 | except GithubException: 88 | print("Error:", repo.name, ",", 89 | branch_name, "-->", sys.exc_info()[1]) 90 | else: 91 | branch = repo.get_branch(branch_name) 92 | if (branch.protected): 93 | branch.remove_protection() 94 | print("Removed branch protection rules for: " 95 | + repo.name + "," + branch_name) 96 | else: 97 | print("No branch protection rules for: " 98 | + repo.name + "," + branch.name) 99 | 100 | 101 | header = open("header.txt", "r") 102 | print(header.read()) 103 | org_name = input("\nGitHub Organization name: ") 104 | pat = getpass("PAT: ") 105 | print("") 106 | print("Where do you want to add/remove rules?") 107 | exec_type = input("Add One Repository [O] , Add All Repositories [A] ," 108 | + "Remove Single Repository [S] ," 109 | + "Remove All Repositories [R]: ").upper() 110 | git = Github(pat) 111 | 112 | if (exec_type == 'O'): 113 | add_one(pat) 114 | elif (exec_type == 'A'): 115 | add_all(pat) 116 | elif (exec_type == 'S'): 117 | remove_one() 118 | elif (exec_type == 'R'): 119 | remove_all() 120 | else: 121 | print("Invalid input. Re-run") 122 | -------------------------------------------------------------------------------- /codeowners.py: -------------------------------------------------------------------------------- 1 | """Importing GitHub Module.""" 2 | from github import Github 3 | 4 | 5 | def add(orgname, pat, reponame, branchname): 6 | """Add or Update CODEOWNERS.""" 7 | g = Github(pat) 8 | repo = g.get_organization(orgname).get_repo(reponame) 9 | all_files = [] 10 | contents = repo.get_contents("") 11 | while contents: 12 | file_content = contents.pop(0) 13 | if file_content.type == "dir": 14 | contents.extend(repo.get_contents(file_content.path)) 15 | else: 16 | file = file_content 17 | all_files.append(str(file) 18 | .replace('ContentFile(path="', '') 19 | .replace('")', '')) 20 | 21 | with open('./CODEOWNERS', 'r') as file: 22 | content = file.read() 23 | 24 | # Upload to github 25 | git_prefix = '.github/' 26 | git_file = git_prefix + 'CODEOWNERS' 27 | if git_file in all_files: 28 | contents = repo.get_contents(git_file) 29 | repo.update_file(contents.path, 30 | "updating CODEOWNERS", 31 | content, 32 | contents.sha, 33 | branch=branchname) 34 | print(git_file + ' updated for: ' + reponame) 35 | else: 36 | repo.create_file(git_file, 37 | "adding CODEOWNERS", 38 | content, 39 | branch=branchname) 40 | print(git_file + ' created for: ' + reponame) 41 | -------------------------------------------------------------------------------- /config.py: -------------------------------------------------------------------------------- 1 | """Change the config values.""" 2 | branches = ('master', 'dev') # Note: Single element requires a comma at end. 3 | add_codeowners_file = True 4 | signed_commit = False 5 | branch_rules = {"required_approving_review_count": 1, 6 | "require_code_owner_reviews": True, 7 | "contexts": ["CodeQL"], 8 | "strict": True 9 | } 10 | -------------------------------------------------------------------------------- /header.txt: -------------------------------------------------------------------------------- 1 | ___ _ _ ______ _ ______ _ 2 | / _ \ | | | | | ___ \ | | | ___ \ | | 3 | / /_\ \_ _| |_ ___ _ __ ___ __ _| |_ ___ | |_/ /_ __ __ _ _ __ ___| |__ | |_/ / _| | ___ ___ 4 | | _ | | | | __/ _ \| '_ ` _ \ / _` | __/ _ \ | ___ \ '__/ _` | '_ \ / __| '_ \ | / | | | |/ _ \/ __| 5 | | | | | |_| | || (_) | | | | | | (_| | || __/ | |_/ / | | (_| | | | | (__| | | | | |\ \ |_| | | __/\__ \ 6 | \_| |_/\__,_|\__\___/|_| |_| |_|\__,_|\__\___| \____/|_| \__,_|_| |_|\___|_| |_| \_| \_\__,_|_|\___||___/ 7 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pygithub 2 | stdiomask --------------------------------------------------------------------------------