修补文件时,在文件末尾拆分区块

  • 本文关键字:文件 拆分 分区 修补 git
  • 更新时间 :
  • 英文 :


在运行git add -p时,当两个单独的代码段添加到文件末尾时,是否可以使git将块一分为二?

首先要尝试的是Michael Turczyn的解决方案:git add --patch filename。当你到达最后一个大块时,尝试s来分割它。如果不起作用,你可以选择通过点击e手动编辑当前大块。

有关编辑大块的说明显示在将弹出的编辑器中。对于您描述的案例,请保留要添加的以+开头的行,并删除要暂时不记录的以+开头的行。

是的,通过注释掉第一个chunk中不需要的行(用于添加(或删除前导-(用于删除(。这意味着只有diff中仍然存在的更改才会被暂存(添加到索引中(。例如,让我们考虑对git diff:显示的两个文件的以下更改(添加和删除需要完成(

f1.txt              f2.txt
@@ -1 +1,3 @@       @@ -1,3 +1 @@
test                test
+line1              -line1
+line2              -line2

执行git patch -p后,当出现大块时,您可以为编辑选择e。在编辑器中,注释掉不想暂存的部件(对于f1.txt/additions(和/或删除不想暂存已删除部件的-(对于f2.txt/deletions(:

f1.txt              f2.txt
@@ -1 +1,3 @@       @@ -1,3 +1 @@
test                test
+line1              -line1           <= leave as is (this will be added)
#+line2              line2           <= commented-out / '-' removed

在此之后,git diff显示您现在可以提交的所需结果:

f1.txt              f2.txt
@@ -1 +1,3 @@       @@ -1,3 +1 @@
test                test
line1               line1
+line2              -line2

您可以尝试运行git add --patch filename,但不能保证git能够识别并允许拆分为所需的部分。

例如,我在文件末尾添加了以下内容:

// First hunk to commit

// Second hunk to commit separately

然后运行git add --path并进入交互模式,在那里你可以决定你是想要进一步分割大块还是接受它们,等等。

CCD_ 17代表";分裂大块";,但当我指定它时,git抱怨道:

抱歉,无法拆分此大块

所以,如果你的大块头有可能实现的话,恐怕你必须自己尝试。

或者,只需删除代码的一部分(并临时复制到记事本上(,添加并提交即可。然后只需粘贴回该代码,然后再次添加并提交:(

git add -p肯定很有用,但只有当您想对文件进行一些详细编辑时,它才能让您走到这一步。

作为提醒,另一种方法是简单地备份你的文件并编辑它

以下是一个可能的程序:

# 1. stage the easy parts
git add -p -- the/file
# 2. create a copy of your file on disk
cp the/file the/file.mine
# 3. reset `the/file` to its staged state
git checkout the/file
# 4. now either :
#  - edit the file directly
code the/file                    # obviously, any editor works
#  - or use a visual diff viewer to have a view similar to `git add -p`
kdiff3 the/file.mine the/file    # again, any diff viewer works
# 5. add and commit
git add the/file
git commit
# 6. restore 'the/file.mine'
mv the/file.min the/file

最新更新