Overview
This post discusses how a copy of a Git repository can be created and maintained.
Let's say out want a complete copy of everything present in a Git repository in another repository, essentially, you want a mirror of an existing repository. The way we will do this is:
- Have an existing Git repository in a place like Github (the resource repository)
- Create a new empty repository in Github (the destination repository)
- Setup mirroring
The --mirror option
Using the --mirror option e.g. 'git push --mirror git@github.com:siddharthbarman/testdestination.git' will push everything to the remote repository. This command can be executed while in the context of another Git repository. For example if my current folder is setup to push to git@github.com:siddharthbarman/testsource.git, I can still push to the mirror. This command can be executed manually to build the mirror repository.
Automating pushing to mirror
Git hooks are a wonderful thing. This feature allows one to write scripts that are executed automatically before or after Git commands. They are useful for customizing Git's behavior and automating actions connected to your source control system. We will make use of the 'pre-push' hook to automate the push to the mirror.
Create a file named 'pre-push' in the .git/hooks folder. Note: the file does not have an extension. Suppose the mirror points to git@github.com:siddharthbarman/testdestination.git, the script in the pre-push file will be:
#!/bin/bash remote="$1" url="$2" if [ "$remote" != 'git@github.com:siddharthbarman/testdestination.git' ] then git push --mirror git@github.com:siddharthbarman/testdestination.git fi
Now that the pre-push hook is setup, if we make any changes, commit and then fire a push, this is what will happen:
E:\Temp\git-mirroring\testsource>git add . E:\Temp\git-mirroring\testsource>git commit -m "Added a new song" [master 22290ae] Added a new song 1 file changed, 2 insertions(+), 1 deletion(-) E:\Temp\git-mirroring\testsource>git push Enumerating objects: 5, done. Counting objects: 100% (5/5), done. Delta compression using up to 12 threads Compressing objects: 100% (2/2), done. Writing objects: 100% (3/3), 304 bytes | 304.00 KiB/s, done. Total 3 (delta 1), reused 0 (delta 0), pack-reused 0 remote: Resolving deltas: 100% (1/1), completed with 1 local object. To github.com:siddharthbarman/testdestination.git d48e75d..22290ae master -> master Enumerating objects: 5, done. Counting objects: 100% (5/5), done. Delta compression using up to 12 threads Compressing objects: 100% (2/2), done. Writing objects: 100% (3/3), 304 bytes | 304.00 KiB/s, done. Total 3 (delta 1), reused 0 (delta 0), pack-reused 0 remote: Resolving deltas: 100% (1/1), completed with 1 local object. To github.com:siddharthbarman/testsource.git d48e75d..22290ae master -> master
Notice the push to the mirror.