Git 挑选提交代码更改

GitGitBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

Git 是一个强大的版本控制系统,它允许开发者高效地管理他们的代码库。Git 最有用的特性之一是能够从一个或多个提交中挑选更改。这使开发者能够将特定更改应用到他们的代码库,而无需合并整个分支。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL git(("`Git`")) -.-> git/BasicOperationsGroup(["`Basic Operations`"]) git/BasicOperationsGroup -.-> git/commit("`Create Commit`") subgraph Lab Skills git/commit -.-> lab-12744{{"`Git 挑选提交代码更改`"}} end

Git 挑选提交

作为一名开发者,你正在处理一个有多个分支的项目。你发现了之前一次提交中所做的特定更改,并且希望将其应用到你当前的分支上。然而,你并不想合并整个分支,因为其中包含了你不需要的其他更改。在这种情况下,你可以使用 git cherry-pick 命令将特定更改应用到你当前的分支。

对于本次实验,让我们使用来自 https://github.com/labex-labs/git-playground 的仓库。按照以下步骤完成挑战:

  1. 克隆仓库,进入该目录并配置身份:
git clone https://github.com/labex-labs/git-playground
cd git-playground
git config --global user.name "你的用户名"
git config --global user.email "你的邮箱"
  1. 创建并切换到一个名为 one-branch 的分支,创建一个名为 hello.txt 的文件,在其中写入 "hello,world",将其添加到暂存区并提交,提交消息为 "add hello.txt":
git checkout -b one-branch
echo "hello,world" > hello.txt
git add.
git commit -m "add hello.txt"
  1. 确定上一步中创建的提交的哈希值,以便应用到 master 分支:
git log
  1. 检出 master 分支,并将更改应用到 master 分支:
git checkout master
git cherry-pick 1609c283ec86ee4
  1. 验证更改是否已应用到 master 分支:
git log

这是在 master 分支上运行 git log 的结果:

commit e2f3c6af9570f4eac2580dea93ca8133f1547d53 (HEAD -> master)
Author: xiaoshengyunan <@users.noreply.github.com>
Date:   Sat Jul 15 14:30:31 2023 +0800

    add hello.txt

commit d22f46ba8c2d4e07d773c5126e9c803933eb5898 (origin/master, origin/HEAD)
Author: Hang <[email protected]>
Date:   Wed Apr 26 14:16:25 2023 +0800

    Added file2.txt

commit cf80005e40a3c661eb212fcea5fad06f8283f08f
Author: Hang <[email protected]>
Date:   Wed Apr 26 14:16:25 2023 +0800

    Added file1.txt

commit b00b9374a7c549d1af111aa777fdcc868d8a2a01
Author: Hang <[email protected]>
Date:   Wed Apr 26 14:16:00 2023 +0800

    Initial commit

总结

在本次实验中,你学习了如何使用 git cherry-pick 命令将一个或多个提交中的特定更改应用到你当前的分支。这是 Git 的一项强大功能,它使开发者能够高效地管理他们的代码库,并避免合并整个分支。

您可能感兴趣的其他 Git 教程