Created
February 26, 2022 14:59
-
-
Save abarrak/ed76759154bbb50abc97a4c6c0714ec1 to your computer and use it in GitHub Desktop.
Script: protect Bitbucket repositories form accidental deletion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
## | |
# This scripts protects the specified branches (e.g. dev) from deletion. | |
# | |
# *Usage:* | |
# ======== | |
# protect-branch-against-delete <user> <pass> : [ <branch-name> <api-base-url> ] | |
# | |
# *Prerequisites:* | |
# ================ | |
# - bash. | |
# - curl. | |
# - jq. | |
# | |
# *Paramters:* | |
# ============ | |
# 1. HTTP basic auth username. (required) | |
# 2. HTTP basic auth password. (required) | |
# 3. branch name. (optional) | |
# 'development' by default. | |
# 4. Base url for API. (optional) | |
# | |
# Credientials, target branch, and base url are passed as script arguments. | |
user=$1 | |
pass=$2 | |
branch=${3:-development} | |
base_url=${4:-https://bitbucket-domain} | |
credentials="$user:$pass" | |
# Fetch all repositories. | |
function fetch_all_projects () | |
{ | |
echo "> Fetching all list of projects .." | |
curl -sS -u ${credentials} ${base_url}/rest/api/1.0/projects/?limit=500 > projects.json | |
echo "> Outputted the response to ${pwd}/projects.json." | |
jq -r '.values[] | .key' projects.json > project-keys.txt | |
echo "> Outputted the project keys to ${pwd}/project-keys.txt." | |
} | |
# Use Permission API. | |
api_endpoint="rest/branch-permissions/2.0/projects/_PROJ_KEY_/restrictions" | |
payload=$(cat <<HEREDOC | |
{ | |
"type": "no-deletes", | |
"matcher": { | |
"id": "${branch}", | |
"displayId": "${branch}", | |
"type": { | |
"id": "BRANCH", | |
"name": "Branch" | |
}, | |
"active": true | |
}, | |
"users": [], | |
"groups": [] | |
} | |
HEREDOC | |
) | |
# Loop to chance branch permissions for all projects' repositories. | |
# | |
fetch_all_projects | |
project_keys=`cat project-keys.txt` | |
for k in $project_keys; do | |
key=$(echo $k | xargs) | |
echo "> Setting the 'no-delete' permission for ${key} project." | |
url=$base_url/${api_endpoint/_PROJ_KEY_/$key} | |
echo $payload | curl -X POST -sS -u ${credentials} -H 'Content-Type: application/json' -d @- $url | |
sleep 0.4 | |
done | |
# Remove temp files | |
rm projects.json | |
rm project-keys.txt | |
echo "> Done!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment