怠日記

写真・金魚・昆虫・プログラミングの趣味を語るサイトです。似たようなことをnoteにも書いたり書いてなかったり。

Gitリポジトリのバックアップとリストア

Git のリポジトリをバックアップして、リストアする手順をまとめる。

以下は gitrepo.git をバックアップして、gitrepo-new.git へリストアする手順である。

 
 
 

バックアップ(ベアクローンの作成)

バックアップするリポジトリのベアクローンを作成する。

ベアクローンは git clone --bare コマンドで作成できる。

以下のコマンドを実行すると、リポジトリ gitrepo.git のベアクローンがカレントディレクトリに作られる。

git clone --bare ssh://gitusername@githostname/path/to/gitrepo.git

バックアップ先の指定もできる。
コマンドの最後に追加したパス(C:\Users\username\backup\gitrepo.git)がバックアップ先である。

git clone --bare ssh://gitusername@githostname/path/to/gitrepo.git C:\Users\username\backup\gitrepo.git

次のように出力されたらベアクローン作成は成功である。

Cloning into bare repository ~
done.
 
 
 

リストア(復元)先のリポジトリ作成

Git サーバーでリストア先となるリポジトリを作る。

ここではリストア先リポジトリを gitrepo-new.git としてある。

リポジトリを作ったら Git サーバーでの作業は終わり。

mkdir /path/to/gitrepo-new.git
cd /path/to/gitrepo-new.git
git init --bare --shared

初期化(git init)に成功すると「Initialized empty shared Git repository ~」のメッセージが出力される。

 
 
 

リストア(ベアクローンのミラープッシュ)

ベアクローンしたリポジトリをリストア先へミラープッシュする。

以下のように、ベアクローンしたリポジトリをカレントディレクトリにしたあと、 git push --mirror コマンドでプッシュする。

cd gitrepo.git
git push --mirror ssh://gitusername@githostname/path/to/gitrepo-new.git

これでバックアップとリストアができた。

 
 
 

リストア結果の確認

念のため、リストア先のリポジトリからクローンして、履歴が取れることを確認しておく。

git clone ssh://gitusername@githostname/path/to/gitrepo-new.git
cd gitrepo-new.git
git log --oneline

問題なければベアクローンは削除していい。