概要
publicリポジトリを自分用にカスタマイズして使いたい場合、GitHubのUIからforkするとprivateに変更できないという制約があります。そこで、gitコマンドを使ってpublicリポジトリをprivateリポジトリとして手元に取り込む方法の紹介をします。
やり方
事前にプライベートリポジトリを作っておいてください。
今回は、
- プライベートリポジトリを
https://github.com/me/private-repository - fork元リポジトリを
https://github.com/another/public-repository
として定義します。
リポジトリをbareクローン
まず、--bare をつけてgit情報のみをローカルにクローンします。
--bare オプションをつけることでワーキングツリー(実際のファイル群)を持たない、git管理情報だけのクローンが作成されます。そのため通常の git clone と異なり、.git ディレクトリではなく public-repository.git というディレクトリが直接生成されます。
git clone --bare https://github.com/another/public-repository
privateリポジトリにpush
その上で、その内容を自身のprivateリポジトリにpushします。
--mirror オプションは通常のブランチだけでなく、タグや削除済みの参照も含めてすべて同期します。そのため、fork元で削除されたブランチはprivate側でも削除される点に注意してください。
cd ./public-repository.git
git push --mirror https://github.com/me/private-repository
upstreamを設定して同期をとる
これだけだとコピーのリポジトリを作っただけでupstreamが設定されていないので、毎回 --bare してpushしなおす作業が必要です。
~/public-repository.git: git remote -v
origin https://github.com/another/public-repository.git (fetch)
origin https://github.com/another/public-repository.git (push)
~/public-repository.git
ちょっと大変なので、upstreamを設定して git fetch upstream && git push --mirror origin で完結するようにしましょう。
cd ~/public-repository.git
git remote add upstream https://github.com/another/public-repository.git
git remote set-url origin https://github.com/me/private-repository.git
設定後に git remote -v で確認すると以下のようになります。
origin https://github.com/me/private-repository.git (fetch)
origin https://github.com/me/private-repository.git (push)
upstream https://github.com/another/public-repository.git (fetch)
upstream https://github.com/another/public-repository.git (push)
最後に以下を実行して、更新しておくと安心ですね。
git fetch upstream && git push --mirror origin
その他
更新を自動化したい場合は、cronなどで適当に回すと楽です。
# 例: 毎日午前3時に同期
0 3 * * * cd ~/public-repository.git && git fetch upstream && git push --mirror origin