How to edit Git “add patch” hunks/diffs/lines during selective staging?

后端 未结 5 1649
不知归路
不知归路 2020-12-28 14:33

I have a source file where 2 features have been added. In order to allow cherry-picking, I\'d like to commit that in 2 phases: one for each feature. Until now, in similar si

相关标签:
5条回答
  • 2020-12-28 14:57

    Like other people have said, you can use e to edit the hunk you want to split up.

    To only add a portion of the hunk, you can delete the lines from the change you want to split out.

    +Line 1
    +Line 2
    +Line 3
    

    Lets say you want to keep Line 1 and Line 3 in one commit and Line 2 in another. All you have to do is delete Line 2:

    +Line 1
    +Line 3
    

    This will put Line 1 and Line 3 in your staging area. Line 2 will still be indexed but not staged.

    0 讨论(0)
  • 2020-12-28 15:04

    As Alan says, edit the patch by pressing e (instead of s) during git add -p. This will launch your editor with that hunk of the patch so that you can manually edit it. There are comments within the text that explain how to properly discard modifications and it's actually pretty easy.

    When you are done, note that you can test it with only the changes you've just added by doing git stash --keep-index. The changes you did not add to the index will be stashed away and you are now free to test just the changes that you are about to commit. When done, simply git stash pop or git stash apply to get the other changes back.

    0 讨论(0)
  • 2020-12-28 15:19

    There are Git GUIs that will let you select individual lines that you want to stage, allowing you to split lines that you normally wouldn't be able to using the regular git add --patch from the command line.

    Two such GUIs are:

    1. SourceTree.
    2. Git Cola.
    0 讨论(0)
  • 2020-12-28 15:21

    You can edit the patch by pressing e during a git add -p. It will not affect the original file.

    0 讨论(0)
  • 2020-12-28 15:24

    I usually get merge conflicts from the git stash pop described in @Dan's answer. See git stash and edited hunks for a solution that avoids the conflicts.

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题