使用 git log --ancestry-path
在这一步中,我们将探讨如何使用 git log --ancestry-path
命令。该命令有助于查看两个提交之间特定路径上的提交历史,能让你了解变更的谱系。
首先,让我们创建一个简单的 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"
你会看到第二次提交的输出:
[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
。该命令需要两个提交引用,它将显示作为第二个提交的祖先且是第一个提交的后代的提交。
让我们找到 "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
选项有助于理解历史中两个点之间的直接开发脉络,忽略后续可能合并进来的其他分支上的提交。