非祖先コミットのテスト
前のステップでは、git merge-base --is-ancestor
を使用して、同じブランチ上で古いコミットが新しいコミットの祖先であることを確認しました。今度は、互いに祖先関係にないコミットをテストした場合にどうなるかを調べてみましょう。
リポジトリのディレクトリに移動します。
cd ~/project/git-ancestor-lab
現在、3 つのコミットがある単一のブランチ (master
) があります。非祖先関係をテストするには、新しいブランチを作成し、そのブランチ上でコミットを行う必要があります。これにより、分岐した履歴が作成されます。
まず、feature
という名前の新しいブランチを作成しましょう。
git branch feature
このコマンドは、feature
という名前の新しいブランチポインタを作成し、master
と 同じ コミット(最新のコミット <commit-hash-3>
)を指します。
次に、feature
ブランチに切り替えましょう。
git checkout feature
ブランチが切り替わったことを示す出力が表示されるはずです。
Switched to branch 'feature'
これで feature
ブランチにいます。このブランチ上で新しいコミットを行いましょう。新しいファイルを作成します。
echo "Feature content" > file2.txt
git add file2.txt
git commit -m "Add file2 on feature branch"
feature
ブランチ上でのコミットが確認される出力が表示されます。
[feature <commit-hash-4>] Add file2 on feature branch
1 file changed, 1 insertion(+)
create mode 100644 file2.txt
ここで、git log --oneline --all --graph
を使用して履歴を見てみましょう。--all
フラグはすべてのブランチのコミットを表示し、--graph
はコミット履歴のテキストベースの表現を描画します。
git log --oneline --all --graph
出力には分岐した履歴が表示されます。次のようになるかもしれません(コミットハッシュは異なります)。
* <commit-hash-4> (HEAD -> feature) Add file2 on feature branch
* <commit-hash-3> (master) Add final content to file1
* <commit-hash-2> Add more content to file1
* <commit-hash-1> Add file1 with initial content
このグラフでは、<commit-hash-4>
は feature
ブランチ上の最新のコミットで、<commit-hash-3>
は master
ブランチ上の最新のコミットです。これら 2 つのコミットは互いの祖先では ありません。共通の祖先は <commit-hash-3>
(feature
ブランチが作成されたコミット)です。
git merge-base --is-ancestor
を使用して、<commit-hash-4>
と <commit-hash-3>
の関係をテストしましょう。プレースホルダを実際のコミットハッシュに置き換えます。
git merge-base --is-ancestor <commit-hash-4> <commit-hash-3>
echo $?
このコマンドは、<commit-hash-4>
が <commit-hash-3>
の祖先であるかどうかをチェックします。グラフからわかるように、祖先ではありません。したがって、コマンドはステータス 1
で終了するはずです。
次に、逆の関係をテストしましょう。<commit-hash-3>
は <commit-hash-4>
の祖先ですか?
git merge-base --is-ancestor <commit-hash-3> <commit-hash-4>
echo $?
このコマンドは、<commit-hash-3>
が <commit-hash-4>
の祖先であるかどうかをチェックします。グラフを見ると、<commit-hash-4>
の親は <commit-hash-3>
です。したがって、<commit-hash-3>
は <commit-hash-4>
の祖先 です。コマンドはステータス 0
で終了するはずです。
これは、git merge-base --is-ancestor
が、リポジトリの履歴内の任意の 2 つのコミット間の関係を、異なるブランチをまたいでもプログラム的にチェックするために使用できることを示しています。