Skip to content

Mirroring - git

Script sample

Script to clone a repository

#!/usr/bin/env bash

SOURCE=$1
TARGET=$2
CHECKGIT=`whereis git | cut -d":" -f2 | sed 's/ //g'`

if [[ -z $SOURCE ]]; then
  echo "`date +"%d.%m.%Y %H:%M:%S"` ###ERROR### You must specify a source directory. Process aborted."
  exit -1
fi

if [[ -z $TARGET ]]; then
  echo "`date +"%d.%m.%Y %H:%M:%S"` ###ERROR### You must specify a target directory. Process aborted."
  exit -2
fi

if [[ ${TARGET%%/*} != 'ssh:' ]]; then
  echo "`date +"%d.%m.%Y %H:%M:%S"` ###ERROR### Target is internal, so it must start with ssh:"
  exit -4
fi

if [[ -z $CHECKGIT ]]; then
  echo "`date +"%d.%m.%Y %H:%M:%S"` ###ERROR### Git command not found. Process aborted."
  exit -5
else
  echo "`date +"%d.%m.%Y %H:%M:%S"` --- find Git command at $CHECKGIT"
fi

REPONAME=${TARGET##*/}
echo "`date +"%d.%m.%Y %H:%M:%S"` --- Start processing repository $REPONAME"

git clone --bare ${SOURCE}
pushd ./${REPONAME}
git remote add myclone ${TARGET}
git fetch --all
git fetch --tags
git push --all myclone
git push --tags myclone
popd

echo "`date +"%d.%m.%Y %H:%M:%S"` --- Repository $REPONAME fully synchronized."

Allow to clone an existing repository

# If you need to use http
# git config --global credential.helper cache

# Ensure to use already cached credential helper
git config credential.helper store

# Well a git clone is better !
git fetch --verbose --prune ; git pull --rebase

git remote add d4k https://<HOST_NAME>/<GROUP_NAME>/<REPOSITORY_NAME>.git
git push d4k --all ; git push d4k --tags

Using option --mirror

To push all your branches, use either (replace REMOTE with the name of the remote, for example "origin"):

git push REMOTE '*:*'
git push REMOTE --all

To push all your tags:

git push REMOTE --tags

Finally, I think you can do this all in one command with:

git push REMOTE --mirror

However, in addition --mirror, will also push your remotes, so this might not be exactly what you want.