Moving a git repository
Moving between repositories
On occasion, you may need to move from one repository to another. Depending on your needs, you may only care about one branch and not care about the history, in that case, you can just check out the code locally, and then add a remote and push to move. However, if you want to keep all the branches and information, you may need to do a bit more work.
Migrating a repository
- Ensure the destination repository exists for each repository that you want to migrate.
- Make the source repositories read-only
- This is not actually necessary but is a great idea to prevent accidental changes to the old repository. Of course, if this is a shared repository, you would want to notify all the users who may have outstanding branches and let them know to make Pull Requests, check in their code first, or else their changes will be lost.
- For bitbucket:
- Go to the repository settings for the Bitbucket repository.
- Click User and group access on the left-side navigation.
- Locate the Users section of the page for a current list of users with access.
- Remove all users besides yourself from the list
- Use the git-mirror.sh script to mirror the repository from source to destination
- git-mirror.sh <src-repo> <dst-repo>
git-mirror.sh
#!/usr/bin/env bash
#
# Script mirrors all branches os source repository to the destination
# repository. Ensure the destination repository exists before running
# this script.
#
# git-mirror.sh <src> <dst>
#
function error_exit() {
echo "$1" >&2
exit 1
}
function usage() {
script="$(basename $0)"
echo "Usage: $script <src repo> <dst repo>"
echo -e "\nThis script will migrate the contents of one repository to another existing repository.\nUse with caution."
exit 0
}
function clone_dir_name() {
echo "$1" | sed -e 's/.*\/\(.*\)\.git$/\1/g'
}
function move_repo() {
src_repo="$1"
dst_repo="$2"
echo "moving $src_repo --> $dst_repo"
local_repo="$PWD/reposdir/$(clone_dir_name "$src_repo")"
mkdir -p "$local_repo"
git clone --mirror "$src_repo" "$local_repo" \
|| git --git-dir "$local_repo" fetch || error_exit "Unable to clone source repository."
cd "$local_repo"
git push --mirror "$dst_repo" || error_exit "Failed to push to destination repository."
return 0
}
if (($# != 2)); then
usage;
fi
hash -r git 2>&1 >/dev/null || error_exit "You must have git installed first.!"
if [ -d '.git' ]; then
error_exit "This script should not be run from within a git repository."
fi
move_repo $1 $2
exit 0