Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save yatharthranjan/fdf3b02c80fd274cd90427b2e52cdbba to your computer and use it in GitHub Desktop.
Save yatharthranjan/fdf3b02c80fd274cd90427b2e52cdbba to your computer and use it in GitHub Desktop.
A bash script to fork all repositories from one organisation to other. If repo already exists in destination org, then it creates a PR for the default branch to sync the changes if any.
#!/usr/bin/env bash
# Ask for user input
read -p "Enter the source organization: " source_org
read -p "Enter the destination organization: " dest_org
read -p "Enter the GitHub token: " gh_token
read -p "Enter the repositories to exclude (comma-separated): " excluded_repos_input
# Convert comma-separated excluded repositories to an array
IFS=',' read -r -a excluded_repos <<< "$excluded_repos_input"
per_page=1000
echo "Forking repos from $source_org to $dest_org"
repos=$(hub api -H "Authorization: token $gh_token" "/orgs/$source_org/repos?per_page=$per_page" | jq -r '.[] | .name')
dest_repos=$(hub api -H "Authorization: token $gh_token" "/orgs/$dest_org/repos?per_page=$per_page" | jq -r '.[] | .name')
for repo in $repos; do
if [[ " ${excluded_repos[@]} " =~ " ${repo} " ]]; then
echo "Skipping $repo (excluded)"
continue
fi
if echo "${dest_repos[@]}" | grep -qw "$repo"; then
echo "Checking for new changes in $repo"
temp_dir=$(mktemp -d)
git clone "https://github.com/$dest_org/$repo.git" "$temp_dir/$repo"
cd "$temp_dir/$repo"
git remote add upstream "https://github.com/$source_org/$repo.git"
git fetch upstream
default_branch=$(hub api -H "Authorization: token $gh_token" "/repos/$source_org/$repo" | jq -r '.default_branch')
if git rev-list HEAD...upstream/$default_branch --count | grep -q '^[1-9][0-9]*$'; then
echo "Creating PR to sync $repo (new changes found)"
git checkout -b sync-upstream
git merge upstream/$default_branch
git push origin sync-upstream
hub pull-request -m "Sync with upstream $source_org/$repo" -b $dest_org:main -h $dest_org:sync-upstream
else
echo "No new changes in $repo"
fi
cd -
rm -rf "$temp_dir"
continue
fi
echo "Forking $repo"
hub api -X POST -H "Authorization: token $gh_token" "/repos/$source_org/$repo/forks" \
-F "organization=$dest_org" -F "default_branch_only=false" -F "name=$repo" | jq .
sleep 1
done
@yatharthranjan
Copy link
Author

Pre-requisites

  1. Install jq (https://jqlang.github.io/jq/)
  2. Install hub (https://hub.github.com)
  3. Create a PAT with access to both organisation's repos, see create a fork endpoint on GH docs (https://docs.github.com/en/rest/repos/forks#create-a-fork)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment