git log --ancestry-path の使用
このステップでは、git log --ancestry-path
コマンドの使い方を探ります。このコマンドは、2 つのコミット間の特定のパスに沿ったコミット履歴を表示するのに便利です。変更の系譜を理解するのに役立ちます。
まず、簡単な Git リポジトリを作成し、いくつかのコミットを行って --ancestry-path
を使用するシナリオを設定しましょう。
プロジェクトディレクトリに移動します。
cd ~/project
この実験用の新しいディレクトリを作成し、Git リポジトリを初期化します。
mkdir ancestry-lab
cd ancestry-lab
git init
空の Git リポジトリが初期化されたことを示す出力が表示されるはずです。
Initialized empty Git repository in /home/labex/project/ancestry-lab/.git/
次に、ファイルを作成し、最初のコミットを行いましょう。
echo "Initial content" > file1.txt
git add file1.txt
git commit -m "Initial commit"
コミットが確認される出力が表示されます。
[master (root-commit) <commit-hash>] Initial commit
1 file changed, 1 insertion(+)
create mode 100644 file1.txt
次に、別のコミットを行いましょう。
echo "Adding more content" >> file1.txt
git add file1.txt
git commit -m "Add more content"
2 番目のコミットの出力が表示されます。
[master <commit-hash>] Add more content
1 file changed, 1 insertion(+)
次に、新しいブランチを作成し、そのブランチでコミットを行いましょう。
git branch feature
git checkout feature
echo "Feature work" > file2.txt
git add file2.txt
git commit -m "Add feature file"
ブランチの作成、切り替え、および新しいコミットの出力が表示されます。
Switched to a new branch 'feature'
[feature <commit-hash>] Add feature file
1 file changed, 1 insertion(+)
create mode 100644 file2.txt
マスターブランチに戻り、別のコミットを行いましょう。
git checkout master
echo "More master work" >> file1.txt
git add file1.txt
git commit -m "More master content"
ブランチの切り替えと新しいコミットの出力が表示されます。
Switched to branch 'master'
[master <commit-hash>] More master content
1 file changed, 1 insertion(+)
これで、ブランチを持つコミット履歴ができました。git log
を使って全履歴を見てみましょう。
git log --all --decorate --oneline
次のようなログが表示されます(コミットハッシュと順序は異なる場合があります)。
<commit-hash> (HEAD -> master) More master content
<commit-hash> Add more content
<commit-hash> (feature) Add feature file
<commit-hash> Initial commit
次に、git log --ancestry-path
を使いましょう。このコマンドには 2 つのコミット参照が必要です。2 番目のコミットの祖先で、1 番目のコミットの子孫であるコミットが表示されます。
「Initial commit」と「More master content」のコミットハッシュを見つけましょう。これらは git log --all --decorate --oneline
の出力から取得できます。<initial-commit-hash>
と <master-commit-hash>
を実際のハッシュに置き換えます。
git log --ancestry-path <initial-commit-hash> <master-commit-hash> --oneline
このコマンドは、初期コミットからマスターブランチの最新コミットまでのパス上のコミットを表示します。「Initial commit」、「Add more content」、および「More master content」のコミットが表示されるはずです。
--ancestry-path
オプションは、履歴内の 2 つのポイント間の直接的な開発の流れを理解するのに便利で、後でマージされた可能性のある他のブランチのコミットは無視します。