Search code examples
git

git - apply a commit on another branch to the working copy / Share content between branches and repositories


So I have a commit that has a helpful code change but it's on another branch.

I would like to apply this commit in the other branch to my working copy on my current branch (not as another commit).

Is this possible? How would I do this?

Thought I'd share this is related to my previous question but specific to working copy: git cherry picking one commit to another branch


Solution

  • Use git cherry-pick to apply changes from existing commit(s)

    Default: cherry-pick with immediate committing

    By default, git cherry-pick <SHA-1> ... applies the changes introduced by each given commit and immediately creates one new commit on the current branch per cherry-picked commit. (These default auto-commits can be prevented with the -n/--no-commit option explained in the next section.)

    Below is a simple example. Let one, two and three be commit hashes on a different branch. You would like to "import" the changes from commit two into your current branch, master. This would be done by git cherry-pick two:

    cherry-pick a commit from a branch

    This directly creates a new commit on master. Instead of specific commits you can use a commit range as the argument. Each commit in the range will result in a new commit on the current branch.


    Optional --no-commit

    If you wish to cherry-pick without immediate committing add the -n/--no-commit flag.

    This will allow you to review the changes and commit them manually if you wish or abort it if you run into too many conflicts.

    git cherry-pick -n <hash> ...
    

    This will simply apply and stage all changes in the given commit(s) or range in one go.


    cherry-pick a merge commit

    In case you needed to cherry-pick a merge instead of a commit, use the -m flag

    #
    # In this case, we select the [1] first parent in the commit
    # Use git show <hash> to see a list of available parents
    # 
    git cherry-pick -m 1 <hash> 
    

    Read out the full git cherry-pick documentation for all the options you can use.