Commit only part of a file in Git

后端 未结 23 1902
一整个雨季
一整个雨季 2020-11-22 05:50

When I make changes to a file in Git, how can I commit only some of the changes?

For example, how could I commit only 15 lines out of 30 lines that have been changed

23条回答
  •  有刺的猬
    2020-11-22 06:41

    Adding on a previous answer, if you prefer using the command line, entering git add -e myfile gives you the choice to choose line by line what you want to commit because this command will open an editor with the differences, like so:

    As you may known lines that start with + are addtions, lines that start with - are deletions. So:

    • To not stage an addition just delete that line.
    • To not stage a deletion just replace - with space .

    This is what git add -h says about adding files this way (patching files):

    added content Added content is represented by lines beginning with "+". You can prevent staging any addition lines by deleting them.

    removed content: Removed content is represented by lines beginning with "-". You can prevent staging their removal by converting the "-" to a " " (space).

    modified content: Modified content is represented by "-" lines (removing the old content) followed by "+" lines (adding the replacement content). You can prevent staging the modification by converting "-" lines to " ", and removing "+" lines. Beware that modifying only half of the pair is likely to introduce confusing changes to the index.

    Caution: do not change the content of the file, this is not a good place to do so. Just change the operators of deleted or added lines.

提交回复
热议问题