Detailed explanation of git cherry-pick command

git cherry-pick command

If you want to move the code from one branch to another branch, the common practice is the mergeor rebaseinstruction, but if you want to move a commit (or some) of a branch to another branch, you need to use the cherry-pickinstruction .

1. Transfer a commit

masterFor example, there are , feature-newand feature-oldbranches in the warehouse , as shown in the following figure:

image-20220303215735790

Now want to feature-oldapply the G commit of branch to feature-newbranch. Execute the following command:

# 假设现在在master分支

# 从master分支切换到feature-new(要接收别的分支某次提交转移的分支)
git checkout feature-new

# 执行转移操作:git cherry-pick <commitHash>
git cherry-pick G

After executing the above command, the code base is as shown below:

image-20220303220039205

That is , a new commit G was added to the endfeature-new of the branch .

Note: cherry-pick The parameter of the instruction does not have to be the hash value of the commit, and the branch name is also acceptable, indicating that the latest commit of the branch is transferred , as follows:

# 将feature-old分支的最新一次提交H转移到当前分支
git cherry-pick feature-old

2. Transfer some commits

git cherry-pick <commitHashA> <commitHashA> 

The above command applies two commits A and B to the current branch, which results in two corresponding new commits on the current branch.

If you want to transfer a series of consecutive commits, you can use the following shorthand syntax:

git cherry-pick A..B

The above command can transfer all commits from A to B , they must be placed in the correct order: commit A must be earlier than commit B, otherwise the command will fail with no error.

Note: With the above command, commit A will not be included cherry-pickin . If you want to include commit A, you can use the following syntax:

git cherry-pick A^..B 

3. Code conflict

3.1 --continue

git cherry-pick --continue

After the user resolves the code conflict, first re-add the modified file to the temporary storage area ( git add .), and then use the above command to let the cherry-pickprocess continue.

3.2 --abort

git cherry-pick --abort

After a code conflict, abort the merge and go back to the way it was before the operation.

3.3 --quit

git cherry-pick --quit

After a code conflict, exit cherry-pick, but do not return to the way it was before the operation.

Guess you like

Origin blog.csdn.net/weixin_49343190/article/details/123265405