Push to Multiple Repositories Simultaneously Using Git Hooks
David Ochiel
Posted on May 15, 2024
Automating repetitive tasks is crucial in software development to enhance workflow efficiency. In this article, we'll dive into leveraging git hooks to automate actions after each commit, to push to two different repositories, one in github, and another in gitea.
What are hooks?
Hooks are scripts that git executes in response to certain events. There are various types of hooks, including pre-commit, post-commit, pre-push, and more. In git, you can use hooks to perform tasks like sending notifications, triggering builds, or updating deployments automatically after each commit. Check out this documentation for more on hooks.
Setting Up a Post-Commit Hook
To set up a post-commit hook in your git repository, follow these steps:
- Create a directory, say, myproject using
mkdir myproject
, where you will place you project files and directories. - Navigate to the directory using
cd myproject/
, customize your development environment using thegit config --global
convention, and initialize a git repository,git init
. - Create the remote repositories for both gitea and github. For github, you will need to have a PAT for push authentication.
# gitea
git remote add gitea <repository-url>
# github
git remote add github https://<your-token>@github.com/<username>/<repository-name>.git
- After that, when you run,
git remote
you should have the following as your remote repositories:
gitea
github
- Navigate to the .git directory and create a post-commit script in the hooks directory. Note that the post-commit script doesn't have to have an extension.
cd .git/
nano hooks/post-commit
The nano text editor will open as in the image below:
Write your desired actions or commands in the script. In this case, copy and paste the following:
# Push changes to Gitea
git push gitea master
# Push changes to GitHub
git push github master
The result should be as per the image below:
To save your file, press CTRL+X, then y, then press ENTER key.
- Ensure the script has execute permissions.
chmod +x hooks/post-commit
- Start working on your project
# move back from the .git directory
cd ..
# work on your project
touch README.md
git add .
git commit -m "first commit"
So why wait? Start using hooks today and take your development workflow to the next level!
If you have any questions, concerns, or want to share your experiences with hooks, feel free to leave a comment below.
Happy coding :)
Posted on May 15, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.