Create a git patch from the uncommitted changes in the current working directory

后端 未结 7 1491
小蘑菇
小蘑菇 2020-11-27 08:53

Say I have uncommitted changes in my working directory. How can I make a patch from those without having to create a commit?

相关标签:
7条回答
  • 2020-11-27 09:11

    If you haven't yet commited the changes, then:

    git diff > mypatch.patch
    

    But sometimes it happens that part of the stuff you're doing are new files that are untracked and won't be in your git diff output. So, one way to do a patch is to stage everything for a new commit (git add each file, or just git add .) but don't do the commit, and then:

    git diff --cached > mypatch.patch
    

    Add the 'binary' option if you want to add binary files to the patch (e.g. mp3 files):

    git diff --cached --binary > mypatch.patch
    

    You can later apply the patch:

    git apply mypatch.patch
    
    0 讨论(0)
  • 2020-11-27 09:11

    We could also specify the files, to include just the files with relative changes, particularly when they span multiple directories e.x.

    git diff ~/path1/file1.ext ~/path2/file2.ext...fileN.ext > ~/whatever_path/whatever_name.patch
    

    I found this to be not specified in the answers or comments, which are all relevant and correct, so chose to add it. Explicit is better than implicit!

    0 讨论(0)
  • 2020-11-27 09:16

    git diff for unstaged changes.

    git diff --cached for staged changes.

    git diff HEAD for both staged and unstaged changes.

    0 讨论(0)
  • 2020-11-27 09:19

    If you want to do binary, give a --binary option when you run git diff.

    0 讨论(0)
  • 2020-11-27 09:30

    To create a patch with both modified & new files (staged) you can run:

    git diff HEAD > file_name.patch
    
    0 讨论(0)
  • 2020-11-27 09:31

    I like:

    git format-patch HEAD~<N>
    

    where <N> is number of last commits to save as patches.

    The details how to use the command are in the DOC

    UPD
    Here you can find how to apply them then.

    UPD For those who did not get the idea of format-patch
    Add alias:

    git config --global alias.make-patch '!bash -c "cd ${GIT_PREFIX};git add .;git commit -m ''uncommited''; git format-patch HEAD~1; git reset HEAD~1"'
    

    Then at any directory of your project repository run:

    git make-patch
    

    This command will create 0001-uncommited.patch at your current directory. Patch will contain all the changes and untracked files that are visible to next command:

    git status .
    
    0 讨论(0)
提交回复
热议问题