缓存文件,了解git add对同一个文件分多次提交的骚操作

场景: 我们在项目开发过程中, 有时候会遇到经理开始说了两个需求, 我们在项目的基础上直接将两个需求做完了, 正当我们沉浸于提交一天的成果感觉人生已经达到了巅峰的气氛中时, 经理说先上一个一个需求, 另一个需求暂时先不上. 暂且不提心情的落差, 放下了2米4的大砍刀之后,仔细分析了索要提交的文件发现两个需求有几个文件都涉及到了,这可怎么办?

遇到上述场景, 那么git add将是你的重要利器


场景重现

vim a.txt

使用vim命令编辑(也可以自己手动创建文件然后编辑)内容如下并保存

initial a.txt

然后我们将初始化的文件提交到远程仓库.

git add --all
git commit -m "initial a.txt"
git push origin master

这里为什么要先初始化文件呢? 是因为这里多次提交的骚操作只是针对modify文件, 而不是添加的新文件,添加的新文件是没有这种骚操作的.

然后编辑a.txt文件内容如下并保存, 注意上一次的初始化的内容已经被替换了.

change1
change2
change1
change2

然后使用如下命令

git add -p a.txt #或者采用 git add --patch a.txt

出现如下内容

diff --git a/a.txt b/a.txt #这里表示对比修改前后的是哪两个文件
index 6ea572d..cfe5e28 100644 #这这里表示对比修改前后的HEAD指针指向变化
--- a/a.txt
+++ b/a.txt
@@ -1 +1,4 @@
-initial a.txt #'-'表示删除 '+'表示添加
+change1
+change2
+change1
+change2
Stage this hunk [y,n,q,a,d,e,?]?

这里我们输入 ? 并回车查看一下每一种情况代表什么意思

y - stage this hunk #代表直接缓存每一个区块
n - do not stage this hunk #代表不缓存每一个区块
q - quit; do not stage this hunk or any of the remaining ones #不做任何操作直接退出
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 #代表不缓存这个文件
e - manually edit the current hunk #编辑将要缓存的部分!! 就是这个我们可以选择式的提交文件
? - print help

我们输入 e 并回车

# Manual hunk edit mode -- see bottom for a quick guide.
@@ -1 +1,4 @@
-initial a.txt
+change1
+change2
+change1
+change2
# ---
# To remove '-' lines, make them ' ' lines (context).
# To remove '+' lines, delete them.
# Lines starting with # will be removed.
#
# If the patch applies cleanly, the edited hunk will immediately be
# marked for staging.
# If it does not apply cleanly, you will be given an opportunity to
# edit again.  If all lines of the hunk are removed, then the edit is
# aborted and the hunk is left unchanged.

大概的意思就是要是移除减号对应的行使其为空, 那么被删除的行将不会被执行删除. 要是移除加号所在的行,那么这行不会添加的缓存中.所以这里我们要做的就是移除掉change2所在的行. 执行完之后我们提交然后推到远程仓库,那么就会发现change1被提交了. change2被留下了.

git commit -m "push change1" #注意不要在重复git add 了,因为change1已经被缓存了直接提交即可 
git push origin master
#结束只有我们可以使用 git status 查看a.txt的内容是否达到了我们的目的

结束.

猜你喜欢

转载自blog.csdn.net/qq844579582/article/details/85632757