If you have an company/org
with lots of collaborators
who all have write
access to your repositories,
it's a really good idea
to protect you main
branch
from accidental overwrite or deletion.
If anyone in your organisation can
git push main --force
and destroy all history of the repository,
someone could either
accidentally or maliciously
burn down your house!
Note: we didn't create this meme, force-pushing to
main
/master
is widely known to be destructive and potentially catastrophic.
This is relevant to people/orgs that have a few GitHub repositories and want to protect them from accidental (or malicious) destruction.
Elixir
v1.5 (or higher)- Github API Token
- 5 Minutes
You will need a personal access token with admin rights to all of the repos you want to protect. To generate a token, follow this guide from Github Help: https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line
Your token only requires repo access:
Don't give it more permissions than it needs. See: wikipedia.org/wiki/Principle_of_least_privilege
Once you've generated your access token, make it available as an environment variable by running:
export GITHUB_ACCESS_TOKEN=<your-personal-access-token>
Note: we place this export statement in an
.env
file to avoid losing the variable when the terminal session ends.
Clone this repo:
git clone [email protected]:dwyl/protect-main-branch.git
Then cd protect-main-branch
Then run:
mix escript.build
This will create a file called protect
.
Use the script as follows:
./protect --org <name> --rules <path/to/file.json>
OR
./protect --user <name> --rules <path/to/file.json>
Options:
--org: Name of the organization that owns the repos you want to protect.
--user: Name of the user who owns the repos you want to protect.
--rules: A path to a json file where you have defined the rules you want to
apply to the master branch of all your repos.
Either user or org should be passed as an option, never both.
./protect --org dwyl --rules rules.json
You should expect to see output similar to the following:
"/repos/dwyl/learn-vim/branches/master/protection"
"/repos/dwyl/app/branches/master/protection"
"/repos/dwyl/learn-heroku/branches/master/protection"
"/repos/dwyl/learn-amazon-web-services/branches/master/protection"
...
"/repos/dwyl/auth-mvp/branches/master/protection"
"/repos/dwyl/flutter-counter-example/branches/master/protection"
Error 404: why
Error 404: learn-WebAssembly
318 branches successfully protected
2 branches errored
Repos will appear in the output in age order. (oldest repos first)
See
Github API docs
for full details of the protection rules available, and
our rules file
rules.json
for an example.