Skip to content

Instantly share code, notes, and snippets.

@Fishezzz
Forked from ethomson/mirror.sh
Last active June 11, 2022 09:53
Show Gist options
  • Save Fishezzz/12e94d9a06daaa9af461c897583fe3fd to your computer and use it in GitHub Desktop.
Save Fishezzz/12e94d9a06daaa9af461c897583fe3fd to your computer and use it in GitHub Desktop.
Script to properly mirror a git repository.
#!/bin/sh
#
# Author: ethomson (Edward Thomson)
# Gist: https://gist.github.com/ethomson/3e8e9cabf360917d52a689d57bcf1729
# Article: https://edwardthomson.com/blog/mirroring_git_repositories.html
#
# TL;DR
# Hosting provider stores information about pull requests in special read-only references,
# which cause errors when you want to mirror a repository the Github way.
# This script avoids this by only pulling necessary references.
#
# GitHub way to mirror a repository:
# https://docs.github.com/en/repositories/creating-and-managing-repositories/duplicating-a-repository#mirroring-a-repository
#
#set -eufo pipefail
set -euf
if [ "$#" -ne 2 ]; then
echo "usage: $0 source_repo_url target_repo_url" >&2
exit 1
fi
SOURCE_URL="$1"
TARGET_URL="$2"
WORKDIR="$(mktemp -d)"
echo "Cloning from ${SOURCE_URL} into ${WORKDIR}..."
git init --bare "${WORKDIR}"
cd "${WORKDIR}"
git config remote.origin.url "${SOURCE_URL}"
git config --add remote.origin.fetch '+refs/heads/*:refs/heads/*'
git config --add remote.origin.fetch '+refs/tags/*:refs/tags/*'
git config --add remote.origin.fetch '+refs/notes/*:refs/notes/*'
git config remote.origin.mirror true
git fetch --all
echo ""
echo "Cloned to ${WORKDIR}; pushing to ${TARGET_URL}"
git push --mirror "${TARGET_URL}"
echo ""
echo "Cleaning up temporary directory ${WORKDIR}..."
rm -rf "${WORKDIR}"
echo "Done."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment