はじめに

別のRepositoryにpushしたいとき、そのままpushすると今までのコミット履歴がすべて残ってしまう。新しいRepositoryではサイズ圧縮のためだったり、簡潔さのためだったり、セキュリティの問題だったりで、空の状態からコミット履歴を残したい場合にどうすればいいか考える。

shallow clone

まず思いついたのは元のRepositoryから--depth 1でcloneして最新のコミット履歴分のみを持つこと。

git clone --branch master --depth 1 https://元のRepository.git project
cd project
git log
  # 一つだけ表示されている
git remote set-url origin https://別のRepository.git
git push origin master

この方法だとpushしたときに! [remote rejected] master -> master (shallow update not allowed)というエラーがでる。--depth 1をつけてcloneするとshallow cloneとなり、新しいRepositoryにはpushできなくなる。

別の方法を二点考えたが、どちらもはじめの手順はshallow cloneから始めることができ、clone速度を大幅に早くできる。

checkout --orphan

checkoutに--orphanをつけると、履歴が空のブランチ(orphan branch)が作成できる。

tmpという空のブランチを作ってコミットしてから、masterブランチをそれで置き換え、別のRepositoryにpushしている。

git clone --branch master --depth 1 https://元のRepository.git project
cd project
git checkout --orphan tmp
git commit
git checkout -B master
git branch -d tmp
git remote set-url origin https://別のRepository.git
git push origin master

git commitするときのメッセージに元のRepositoryのどのコミットから分岐したのかを書いておくと、後々役立つかもしれない。

created_from=$(git log -1 --pretty=%H)
git checkout --orphan tmp
git commit -m "created from project.git ${created_from}"

.gitを消して、初めからRepositoryを作る

.gitを消してgit initすることで新しいRepositoryを作り、それをremoteにpushにするという方法。

git clone --branch master --depth 1 https://元のRepository.git project
cd project
rm -rf .git
git init
git add .
git commit
git remote add origin https://別のRepository.git
git push origin master

参考