在 Git 中只提交文件的一部分 [英] Commit only part of a file in Git

查看:36
本文介绍了在 Git 中只提交文件的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在 Git 中对文件进行更改时,如何只提交部分更改?

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

例如,如何在文件中更改的 30 行中只提交 15 行?

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

推荐答案

你可以使用 git add --patch (或简称 -p),并且 git 将开始将您的文件分解为它认为合理的帅哥";(文件的一部分).然后它会提示你这个问题:

You can use git add --patch <filename> (or -p for short), and git will begin to break down your file into what it thinks are sensible "hunks" (portions of the file). It will then prompt you with this question:

Stage this hunk [y,n,q,a,d,/,j,J,g,s,e,?]?

以下是每个选项的说明:

Here is a description of each option:

  • y 为下一次提交准备这个大块
  • n 不要为下一次提交暂存这个大块
  • q 退出;不要上演这个大块头或任何剩余的大块头
  • a 暂存这个大块头和文件中所有后来的大块头
  • d 不要在文件中暂存这个大块或任何后面的大块
  • g 选择一个大块去
  • / 搜索匹配给定正则表达式的大块
  • j让这个大块未决定,看下一个未决定的大块
  • J让这个大块头未定,看下一个大块头
  • k让这个大块未定,看之前的未定大块
  • K让这个帅哥未定,看之前的帅哥
  • s 将当前块分割成更小的块
  • e 手动编辑当前块
    • 然后您可以通过将 +/- 替换为 #(感谢 veksen)
    • y stage this hunk for the next commit
    • n do not stage this hunk for the next commit
    • q quit; do not stage this hunk or any of the remaining hunks
    • a stage this hunk and all later hunks in the file
    • d do not stage this hunk or any of the later hunks in the file
    • g select a hunk to go to
    • / search for a hunk matching the given regex
    • j leave this hunk undecided, see next undecided hunk
    • J leave this hunk undecided, see next hunk
    • k leave this hunk undecided, see previous undecided hunk
    • K leave this hunk undecided, see previous hunk
    • s split the current hunk into smaller hunks
    • e manually edit the current hunk
      • You can then edit the hunk manually by replacing +/- by # (thanks veksen)

      如果文件还没有在仓库中,你可以先执行 git add -N .之后你可以继续使用 git add -p .

      If the file is not in the repository yet, you can first do git add -N <filename>. Afterwards you can go on with git add -p <filename>.

      之后,您可以使用:

      • git diff --staged 以检查您是否进行了正确的更改
      • git reset -p 取消暂存错误添加的帅哥
      • git commit -v 可在您编辑提交消息时查看您的提交.
      • git diff --staged to check that you staged the correct changes
      • git reset -p to unstage mistakenly added hunks
      • git commit -v to view your commit while you edit the commit message.

      请注意,这与 git format-patch 命令大不相同,后者的目的是将提交数据解析为 .patch 文件.

      Note this is far different than the git format-patch command, whose purpose is to parse commit data into a .patch files.

      未来参考:Git 工具 - 交互式分期

      这篇关于在 Git 中只提交文件的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆