Git cherry-pick使用

   git cherry-pick可以理解为”挑拣”提交,它可以将其它分支的某个提交引入到当前的分支上。在实际使用过程中,可以通过该命令将多个不同分支的提交合到当前分支上,那么就要使用git cherry-pick了。

         其实就是挑挑拣拣,只选想要的提交内容。

用法

git cherry-pick [<options>] <commit-ish>...

常用options:
    --quit                退出当前的chery-pick序列
    --continue            继续当前的chery-pick序列
    --abort               取消当前的chery-pick序列,恢复当前分支
    -n, --no-commit       不自动提交
    -e, --edit            编辑提交信息

git cherry-pick commitid 

在本地仓库中,有两个分支:branch1和branch2,我们先来查看各个分支的提交:

# 切换到branch2分支
$ git checkout branch2
Switched to branch 'branch2'
$
$
# 查看最近三次提交
$ git log --oneline -3
23d9422 [Description]:branch2 commit 3
2555c6e [Description]:branch2 commit 2
b82ba0f [Description]:branch2 commit 1
# 切换到branch1分支
$ git checkout branch1
Switched to branch 'branch1'
# 查看最近三次提交
$ git log --oneline -3
20fe2f9 commit second
c51adbe commit first
ae2bd14 commit 3th

 现在,我想要将branch2分支上的第一次提交内容合入到branch1分支上,则可以使用

git cherry-pick命令:

$ git cherry-pick 6a516e
error: could not apply 6a516e... [Description]:branch2 commit 2
hint: after resolving the conflicts, mark the corrected paths
hint: with 'git add <paths>' or 'git rm <paths>'
hint: and commit the result with 'git commit'

 当cherry-pick时,没有成功自动提交,这说明存在冲突,因此首先需要解决冲突,解决冲突后需要git commit手动进行提交:

$ git commit
[branch1 790f431] [Description]:branch2 commit 2
 Date: Fri Jul 13 18:36:44 2018 +0800
 1 file changed, 1 insertion(+)
 create mode 100644 only-for-branch2.txt

 或者git add .后直接使用git cherry-pick --continue继续。现在查看提交信息:

$ git log --oneline -3
790f431 [Description]:branch2 commit 2
20fe2f9 commit second
c51adbe commit first

 branch2分支上的第二次提交成功合入到了branch1分支上。以上就是git cherry-pick的基本用法,如果没有出现冲突,该命令将自动提交。

git cherry-pick -n

如果不想git cherry-pick自动进行提交,则加参数-n即可。比如将branch2分支上的第三次提交内容合入到branch1分支上:

$ git cherry-pick 23d9422
[branch1 2c67715] [Description]:branch2 commit 3
 Date: Fri Jul 13 18:37:05 2018 +0800
 1 file changed, 1 insertion(+)
$

 查看提交log,它自动合入了branch1分支:

$ git log --oneline -3
2c67715 [Description]:branch2 commit 3
f8bc5db [Description]:branch2 commit 2
20fe2f9 commit second

 如果不想进行自动合入,则使用git cherry-pick -n

# 回退上次提交,再此进行cherry-pick
$ git reset --hard HEAD~
HEAD is now at f8bc5db [Description]:branch2 commit 2
$ git cherry-pick -n 23d9422
$ git status
On branch branch1
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    modified:   only-for-branch2.txt

 这时通过git status查看,发现已将branch2的提交获取但是没有合入

git cherry-pick -e

如果想要在cherr-pick后重新编辑提交信息,则使用git cherry-pick -e命令,比如我们还是要将branch2分支上的第三次提交内容合入到branch1分支上,但是需要修改提交信息:

$ git cherry-pick -e 23d9422

  1 [Description]:branch2 commit 3
  2 #
  3 # It looks like you may be committing a cherry-pick.
  4 # If this is not correct, please remove the file
  5 #       .git/CHERRY_PICK_HEAD
  6 # and try again.

 git cherry-pick –continue, –abort,–quit

当使用git cherry-pick发生冲突后,将会出现如下信息:

$ git cherry-pick 23d9422
error: could not apply 23d9422... [Description]:branch2 commit 3
hint: after resolving the conflicts, mark the corrected paths
hint: with 'git add <paths>' or 'git rm <paths>'
hint: and commit the result with 'git commit'

 这时如果要继续cherry-pick,则首先需要解决冲突,通过git add .将文件标记为已解决,然后可以使用git cherry-pick --continue命令,继续进行cherry-pick操作。如果要中断这次cherry-pick,则使用git cherry-pick --quit,这种情况下当前分支中未冲突的内容状态将为modified,如果要取消这次cherry-pick,则使用git cherry-pick --abort,这种情况下当前分支恢复到cherry-pick前的状态,没有改变。

git cherry-pick < branchname >

如果在git cherry-pick后加一个分支名,则表示将该分支顶端提交进cherry-pick

$ git cherry-pick master

git cherry-pick ..< branchname >
git cherry-pick ^HEAD < branchname >

 以上两个命令作用相同,表示应用所有提交引入的更改,这些提交是branchname的祖先但不是HEAD的祖先,比如,现在我的仓库中有三个分支,其提交历史如下图:

C<---D<---E  branch2
              /
master   A<---B
              \
F<---G<---H  branch3
                         |
HEAD

 如果我使用git cherry-pick ..branch2或者git cherry-pick ^HEAD branch2,那么会将属于branch2的祖先但不属于branch3的祖先的所有提交引入到当前分支branch3上,并生成新的提交,执行命令如下:

$ git cherry-pick ..branch2
[branch3 c95d8b0] [Description]:branch2  add only-for-branch2
 Date: Fri Jul 13 20:34:40 2018 +0800
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 only-for-branch2
[branch3 7199a67] [Description]:branch2 modify for only-for-branch2--1
 Date: Fri Jul 13 20:38:35 2018 +0800
 1 file changed, 1 insertion(+)
[branch3 eb8ab62] [Description]:branch2 modify for only-for-branch2--2
 Date: Fri Jul 13 20:39:09 2018 +0800
 1 file changed, 1 insertion(+)

 执行后的提交历史如下:

C<---D<---E  branch2
/
master   A<---B
\
F<---G<---H<---C'<---D'<---E'  branch3
|
HEAD

 常见问题

 

1.The previous cherry-pick is now empty, possibly due to conflict resolution.

原因:

cherry-pick时出现冲突,解决冲突后本地分支中内容和cherry-pick之前相比没有改变,因此当在以后的步骤中继续git cherry-pick或执行其他命令时,由于此时还处于上次cherry-pick,都会提示该信息,表示可能是由于解决冲突造成上一次cherry-pick内容是空的。

解决方案:

1.执行git cherry-pick --abort取消上次操作。2.执行git commit --allow-empty,表示允许空提交。

2.fatal: You are in the middle of a cherry-pick – cannot amend.

原因:

cherry-pick时出现冲突,没有解决冲突就执行git commit --amend命令,从而会提示该信息。

解决方案:

首先在git commit --amend之前解决冲突,并完成这次cherry-pick:

$ git add .
$ git cherry-pick --continue 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Git-2.21.0-64 for windows Git 2.23 Release Notes ====================== Updates since v2.22 ------------------- Backward compatibility note * The "--base" option of "format-patch" computed the patch-ids for prerequisite patches in an unstable way, which has been updated to compute in a way that is compatible with "git patch-id --stable". * The "git log" command by default behaves as if the --mailmap option was given. UI, Workflows & Features * The "git fast-export/import" pair has been taught to handle commits with log messages in encoding other than UTF-8 better. * In recent versions of Git, per-worktree refs are exposed in refs/worktrees/<wtname>/ hierarchy, which means that worktree names must be a valid refname component. The code now sanitizes the names given to worktrees, to make sure these refs are well-formed. * "git merge" learned "--quit" option that cleans up the in-progress merge while leaving the working tree and the index still in a mess. * "git format-patch" learns a configuration to set the default for its --notes=<ref> option. * The code to show args with potential typo that cannot be interpreted as a commit-ish has been improved. * "git clone --recurse-submodules" learned to set up the submodules to ignore commit object names recorded in the superproject gitlink and instead use the commits that happen to be at the tip of the remote-tracking branches from the get-go, by passing the new "--remote-submodules" option. * The pattern "git diff/grep" use to extract funcname and words boundary for Matlab has been extend to cover Octave, which is more or less equivalent. * "git help git" was hard to discover (well, at least for some people). * The pattern "git diff/grep" use to extract funcname and words boundary for Rust has been added. * "git status" can be told a non-standard default value for the "--[no-]ahead-behind" option with a new configuration variable status.aheadBehind. * "git fetch" and "git pull" reports when a fetch results in non-fast-forward updates to let the user notice unusual situation. The commands learned "--no-show-forced-updates" option to disable this safety feature. * Two new commands "git switch" and "git restore" are introduced to split "checking out a branch to work on advancing its history" and "checking out paths out of the index and/or a tree-ish to work on advancing the current history" out of the single "git checkout" command. * "git branch --list" learned to always output the detached HEAD as the first item (when the HEAD is detached, of course), regardless of the locale. * The conditional inclusion mechanism learned to base the choice on the branch the HEAD currently is on. * "git rev-list --objects" learned the "--no-object-names" option to squelch the path to the object that is used as a grouping hint for pack-objects. * A new tag.gpgSign configuration variable turns "git tag -a" into "git tag -s". * "git multi-pack-index" learned expire and repack subcommands. * "git blame" learned to "ignore" commits in the history, whose effects (as well as their presence) get ignored. * "git cherry-pick/revert" learned a new "--skip" action. * The tips of refs from the alternate object store can be used as starting point for reachability computation now. * Extra blank lines in "git status" output have been reduced. * The commits in a repository can be described by multiple commit-graph files now, which allows the commit-graph files to be updated incrementally. * "git range-diff" output has been tweaked for easier identification of which part of what file the patch shown is about. Performance, Internal Implementation, Development Support etc. * Update supporting parts of "git rebase" to remove code that should no longer be used. * Developer support to emulate unsatisfied prerequisites in tests to ensure that the remainder of the tests still succeeds when tests with prerequisites are skipped. * "git update-server-info" learned not to rewrite the file with the same contents. * The way of specifying the path to find dynamic libraries at runtime has been simplified. The old default to pass -R/path/to/dir has been replaced with the new default to pass -Wl,-rpath,/path/to/dir, which is the more recent GCC uses. Those who need to build with an old GCC can still use "CC_LD_DYNPATH=-R" * Prepare use of reachability index in topological walker that works on a range (A..B). * A new tutorial targeting specifically aspiring git-core developers has been added. * Auto-detect how to tell HP-UX aCC where to use dynamically linked libraries from at runtime. * "git mergetool" and its tests now spawn fewer subprocesses. * Dev support update to help tracing out tests. * Support to build with MSVC has been updated. * "git fetch" that grabs from a group of remotes learned to run the auto-gc only once at the very end. * A handful of Windows build patches have been upstreamed. * The code to read state files used by the sequencer machinery for "git status" has been made more robust against a corrupt or stale state files. * "git for-each-ref" with multiple patterns have been optimized. * The tree-walk API learned to pass an in-core repository instance throughout more codepaths. * When one step in multi step cherry-pick or revert is reset or committed, the command line prompt script failed to notice the current status, which has been improved. * Many GIT_TEST_* environment variables control various aspects of how our tests are run, but a few followed "non-empty is true, empty or unset is false" while others followed the usual "there are a few ways to spell true, like yes, on, etc., and also ways to spell false, like no, off, etc." convention. * Adjust the dir-iterator API and apply it to the local clone optimization codepath. * We have been trying out a few language features outside c89; the coding guidelines document did not talk about them and instead had a blanket ban against them. * A test helper has been introduced to optimize preparation of test repositories with many simple commits, and a handful of test scripts have been updated to use it. Fixes since v2.22 ----------------- * A relative pathname given to "git init --template=<path> <repo>" ought to be relative to the directory "git init" gets invoked in, but it instead was made relative to the repository, which has been corrected. * "git worktree add" used to fail when another worktree connected to the same repository was corrupt, which has been corrected. * The ownership rule for the file descriptor to fast-import remote backend was mixed up, leading to an unrelated file descriptor getting closed, which has been fixed. * A "merge -c" instruction during "git rebase --rebase-merges" should give the user a chance to edit the log message, even when there is otherwise no need to create a new merge and replace the existing one (i.e. fast-forward instead), but did not. Which has been corrected. * Code cleanup and futureproof. * More parameter validation. * "git update-server-info" used to leave stale packfiles in its output, which has been corrected. * The server side support for "git fetch" used to show incorrect value for the HEAD symbolic ref when the namespace feature is in use, which has been corrected. * "git am -i --resolved" segfaulted after trying to see a commit as if it were a tree, which has been corrected. * "git bundle verify" needs to see if prerequisite objects exist in the receiving repository, but the command did not check if we are in a repository upfront, which has been corrected. * "git merge --squash" is designed to update the working tree and the index without creating the commit, and this cannot be countermanded by adding the "--commit" option; the command now refuses to work when both options are given. * The data collected by fsmonitor was not properly written back to the on-disk index file, breaking t7519 tests occasionally, which has been corrected. * Update to Unicode 12.1 width table. * The command line to invoke a "git cat-file" command from inside "git p4" was not properly quoted to protect a caret and running a broken command on Windows, which has been corrected. * "git request-pull" learned to warn when the ref we ask them to pull from in the local repository and in the published repository are different. * When creating a partial clone, the object filtering criteria is recorded for the origin of the clone, but this incorrectly used a hardcoded name "origin" to name that remote; it has been corrected to honor the "--origin <name>" option. * "git fetch" into a lazy clone forgot to fetch base objects that are necessary to complete delta in a thin packfile, which has been corrected. * The filter_data used in the list-objects-filter (which manages a lazily sparse clone repository) did not use the dynamic array API correctly---'nr' is supposed to point at one past the last element of the array in use. This has been corrected. * The description about slashes in gitignore patterns (used to indicate things like "anchored to this level only" and "only matches directories") has been revamped. * The URL decoding code has been updated to avoid going past the end of the string while parsing %-<hex>-<hex> sequence. * The list of for-each like macros used by clang-format has been updated. * "git branch --list" learned to show branches that are checked out in other worktrees connected to the same repository prefixed with '+', similar to the way the currently checked out branch is shown with '*' in front. (merge 6e9381469e nb/branch-show-other-worktrees-head later to maint). * Code restructuring during 2.20 period broke fetching tags via "import" based transports. * The commit-graph file is now part of the "files that the runtime may keep open file descriptors on, all of which would need to be closed when done with the object store", and the file descriptor to an existing commit-graph file now is closed before "gc" finalizes a new instance to replace it. * "git checkout -p" needs to selectively apply a patch in reverse, which did not work well. * Code clean-up to avoid signed integer wraparounds during binary search. * "git interpret-trailers" always treated '#' as the comment character, regardless of core.commentChar setting, which has been corrected. * "git stash show 23" used to work, but no more after getting rewritten in C; this regression has been corrected. * "git rebase --abort" used to leave refs/rewritten/ when concluding "git rebase -r", which has been corrected. * An incorrect list of options was cached after command line completion failed (e.g. trying to complete a command that requires a repository outside one), which has been corrected. * The code to parse scaled numbers out of configuration files has been made more robust and also easier to follow. * The codepath to compute delta islands used to spew progress output without giving the callers any way to squelch it, which has been fixed. * Protocol capabilities that go over wire should never be translated, but it was incorrectly marked for translation, which has been corrected. The output of protocol capabilities for debugging has been tweaked a bit. * Use "Erase in Line" CSI sequence that is already used in the editor support to clear cruft in the progress output. * "git submodule foreach" did not protect command line options passed to the command to be run in each submodule correctly, when the "--recursive" option was in use. * The configuration variable rebase.rescheduleFailedExec should be effective only while running an interactive rebase and should not affect anything when running a non-interactive one, which was not the case. This has been corrected. * The "git clone" documentation refers to command line options in its description in the short form; they have been replaced with long forms to make them more recognisable. * Generation of pack bitmaps are now disabled when .keep files exist, as these are mutually exclusive features. (merge 7328482253 ew/repack-with-bitmaps-by-default later to maint). * "git rm" to resolve a conflicted path leaked an internal message "needs merge" before actually removing the path, which was confusing. This has been corrected. * "git stash --keep-index" did not work correctly on paths that have been removed, which has been fixed. (merge b932f6a5e8 tg/stash-keep-index-with-removed-paths later to maint). * Window 7 update ;-) * A codepath that reads from GPG for signed object verification read past the end of allocated buffer, which has been fixed. * "git clean" silently skipped a path when it cannot lstat() it; now it gives a warning. * "git push --atomic" that goes over the transport-helper (namely, the smart http transport) failed to prevent refs to be pushed when it can locally tell that one of the ref update will fail without having to consult the other end, which has been corrected. * The internal diff machinery can be made to read out of bounds while looking for --function-context line in a corner case, which has been corrected. (merge b777f3fd61 jk/xdiff-clamp-funcname-context-index later to maint). * Other code cleanup, docfix, build fix, etc. (merge fbec05c210 cc/test-oidmap later to maint). (merge 7a06fb038c jk/no-system-includes-in-dot-c later to maint). (merge 81ed2b405c cb/xdiff-no-system-includes-in-dot-c later to maint). (merge d61e6ce1dd sg/fsck-config-in-doc later to maint).

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值