Skip to content

Instantly share code, notes, and snippets.

@tavallaie
Last active June 10, 2024 13:42
Show Gist options
  • Save tavallaie/b2e1df81af710d08b2f48b2fd293f224 to your computer and use it in GitHub Desktop.
Save tavallaie/b2e1df81af710d08b2f48b2fd293f224 to your computer and use it in GitHub Desktop.
Migrates a repository from GitLab to GitHub, preserving history and branches.
GITHUB_ORGANIZATION=my_github_org
#!/bin/bash
# Exit immediately if a command exits with a non-zero status
set -e
# Load .env file if it exists
if [ -f .env ]; then
export $(grep -v '^#' .env | xargs)
fi
# Function to display usage information
usage() {
echo "Usage: $0 <gitlab_project_url> [<github_repo>]"
echo "Example: $0 ssh://git@mygitlab:8022/project/myproject.git project-myproject"
echo "If <github_repo> is not provided, it will be derived from <gitlab_project_url>."
exit 1
}
# Check if at least the GitLab project URL is provided
if [ "$#" -lt 1 ]; then
usage
fi
GITLAB_PROJECT_URL=$1
GITHUB_REPO=$2
# Check if GITHUB_ORGANIZATION is set
if [ -z "$GITHUB_ORGANIZATION" ]; then
echo "GITHUB_ORGANIZATION is not set. Please set it in the .env file."
exit 1
fi
# Extract the GitLab repo path from the provided URL
GITLAB_REPO_PATH=$(echo $GITLAB_PROJECT_URL | sed 's|ssh://git@||' | sed 's|:[0-9]*/|/|')
# Derive the GitHub repo name if not provided
if [ -z "$GITHUB_REPO" ]; then
GITHUB_REPO=$(basename ${GITLAB_REPO_PATH} .git)
# Transform the GitHub repo name as needed (replace slashes with dashes)
GITHUB_REPO=${GITHUB_REPO//\//-}
fi
# Clone the GitLab repository as a mirror
echo "Cloning the GitLab repository..."
git clone --mirror ${GITLAB_PROJECT_URL}
REPO_NAME=$(basename ${GITLAB_REPO_PATH} .git)
cd ${REPO_NAME}.git
# Add the GitHub repository as a new remote
echo "Adding GitHub as a remote..."
git remote add github [email protected]:${GITHUB_ORGANIZATION}/${GITHUB_REPO}.git
# Push all branches and tags to GitHub
echo "Pushing to GitHub..."
git push --mirror github
echo "Migration completed successfully."
# Clean up by removing the local mirror repository
cd ..
rm -rf ${REPO_NAME}.git
echo "Local repository removed."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment