LoginSignup
45
34

More than 5 years have passed since last update.

【Git】2つのGitリポジトリを履歴を保持して統合したい

Last updated at Posted at 2019-03-28

初めに

基本は以下のリンク先の記事を参考にさせていただいています。
Git 別のリポジトリを履歴を残したまま取り込みたい

環境

  • ubuntu18.04
  • git version 2.17.1

今回やること

現状repo_arepo_Bリポジトリが別々に存在し、以下のような構成になっています。

~/repo_A
   |--- .git
~/repo_b
   |--- .git

これをrepo_A内にrepo_Bをディレクトリとして統合し、repo_Bの履歴も保持したまま以下のような構成にします。

~/repo_A
   |--- .git
   |---repo_B

Treeは下記のようになる想定です。

*       <name>    <commitID> marge repo_B in repo_A
|\     
| *     <name>    <commitID> repo_B HEAD
| *     <name>    <commitID> commit3
| *     <name>    <commitID> commit2
| *     <name>    <commitID> commit1
| *     <name>    <commitID> repo_B init
*       <name>    <commitID> repo_A HEAD
*    <name>    <commitID> repo_A commit1

手順

Homeディレクトリにrepo_Arepo_Bリポジトリをcloneする

$ cd ~ #hemeディレクトリで作業します
$ git clone <repo_Aのurl>
$ git clone <repo_Bのurl>

repo_Bを入れるディレクトリを作成

今回はrepo_Aの中に統合するためrepo_Aの中にあらかじめrepo_Bを入れるディレクトリを作成しておきます。
今回はそのままではありますが、ディレクトリ名をrepo_Bにします。

$ cd repo_A/ 
$ mkdir repo_B
#repo_BディレクトリをGit管理できるよう.gitkeepを作成します
$ touch repo_B/.gitkeep 
$ git add -A repo_B
$ git commit -m "create repo_B dir" #ディレクトリをgitに追加します

repo_Bリポジトリをリモートリポジトリとして追加する

取り込みたいrepo_Bリポジトリをrepo_Aのリモートリポジトリに追加します。

ただし自分はfetchが必要でしたので、以下の記事を参考にさせていただきました。
Git で複数のリポジトリをまとめたり、逆に切り出したりする

$ git remote add repo_B ~/repo_B
$ git fetch repo_B

subtreeとしてマージ

普通にマージしようとしますと以下のエラーが出ました。

$ git merge -X subtree=repo_B repo_B/master
fatal: refusing to merge unrelated histories

エラーメッセージから検索し、以下の記事を参考にさせていただきました。
初めてGitHubリポジトリにpushしたらrejectedエラーになったときの対応メモ

git merge --allow-unrelated-histories -X subtree=repo_B repo_B/master

--allow-unrelated-historiesを付けないと関係のないツリーはマージできない仕様らしいです。

あとは要らなくなった.gitkeep~/repo_Bを消して完了です。

$ cd ~/repo_A/repo_B
$ rm .gitkeep
$ cd ~
$ rm -r repo_B #-rはディレクトリも削除するオプションです

参考にさせていただきました!

ありがとうございます!

45
34
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
45
34