git cherry-pick to another branch

后端 未结 4 1110
深忆病人
深忆病人 2020-12-06 16:24

I wonder if there is the way to copy one commit to another branch without checking out that branch.

For example, I have two branches: master and p

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-06 17:05

    Here's a small script that creates a temporary clone of the repository, as suggested by user2394284:

    /usr/bin/git-tmp-clone or ~/bin/git-tmp-clone

    #!/bin/bash
    
    gitTopLevel=$(git rev-parse --show-toplevel)
    
    # Unique name for the temporary clone.
    totalhash=$(tar -c "$gitTopLevel/.git" 2> /dev/null | sha256sum | head -c8)
    
    tmprepo="/tmp/$(basename $(pwd))_${totalhash}"
    
    git clone "$gitTopLevel" ${tmprepo}
    
    # Start an interactive shell in the clone. Pass any
    # arguments as initial commands to be executed.
    /bin/bash --init-file <(echo "cd ${tmprepo}; $@")
    
    # Clean up the clone.
    rm -rf ${tmprepo} && echo "Deleted ${tmprepo}"
    

    (This script is less than robust, but it seems to work for me on Ubuntu.)

    You can use this to cherry-pick e.g. the last commit on the current brach to another branch, by running

    git-tmp-clone "git checkout TARGET_BRANCH
                && git cherry-pick $(git rev-parse --short @)
                && git push origin HEAD"
    

    (Note that in this example, the rev-parse is evaluated in the origin repository before the clone is created! That's why it points to the most recent commit. Adapt as needed.)

提交回复
热议问题