GitHub is a powerful platform for collaborative coding and version control, but there’s a quirk that often puzzles users – the inability to create a private repository directly from a forked repository. In this article, we’ll explore a clever workaround that allows you to have the best of both worlds – a private repository that can seamlessly incorporate updates from a public repository, mimicking the behavior of a forked repository.
Mirroring a Public Repository to a Private Repository
Start by creating an empty private repository on GitHub. Once that’s done, open your terminal and execute the following commands:
# Clone the public repository to your local machine
git clone --bare <public-repo-url>
# Mirror-push to the new private repository
git push --mirror [email protected]:<username>/<repo>.git
This sequence of commands performs a bare clone of the public repository and mirrors the contents to your newly created private repository. It essentially duplicates the public repository into a private one.
Note: If the public repository has a default branch other than main, the default branch of the private repository might be set incorrectly. To fix this, go to the private repository’s settings and change the default branch to the correct one.
Linking a Remote Repository to a Public Repository
Now that you have your private repository set up, the next step is to register it as a remote repository with the original public repository. Execute the following commands in your terminal:
# Clone the private repository to your local machine
git clone <private-repo-url>
# Register the public repository as a remote repository.
# You can use any name for <remote_name>
git remote add <remote_name> <public-repo-url>
This establishes a connection between your private repository and the public repository, allowing you to fetch updates from the latter.
Retrieving Changes from a Public Repository
With the remotes set up, you can now easily pull updates from the public repository into your private one. Use the following commands:
# Fetch updates from the public repository
git pull <remote_name> <branch_name>
# Push updates to your private repository
git push origin <branch_name>
The first command fetches changes from the public repository, while the second pushes those changes to your private repository’s master branch.