Git 交互式add

版权声明:转载请附明原文链接 https://blog.csdn.net/songyuequan/article/details/85038873

1. 新建项目

我们的项目已经建好了,并做了初始化的提交,项目中只有一个文件 README.md
内容是
在这里插入图片描述

2. 编辑文件

在这里插入图片描述

3. 交互式add

上面的图片我们可以看出,我们为 README.md 文件加了3个方法。
现在为了体现自己写代码的思路以及 Code Review方便,我们将这三个方法分两次提交。
首先 提交 method1() 和 method2() ,再提交 method3()
运行

git add -i

结果如下图所示:
在这里插入图片描述

4. 查看帮助文档

那么,下面这些命令都是什么意思呢?

*** Commands ***
  1: status	  2: update	  3: revert	  4: add untracked
  5: patch	  6: diff	  7: quit	  8: help

此时我们在 what now > 后面输入h 以查看帮助文档
在这里插入图片描述

status        - show paths with changes
update        - add working tree state to the staged set of changes
revert        - revert staged set of changes back to the HEAD version
patch         - pick hunks and update selectively
diff          - view diff between HEAD and index
add untracked - add contents of untracked files to the staged set of changes

根据帮助文档,我们得知,需要的是patch 选择性的一块块捡出来。

5. patch

此时我们在 what now > 后面输入p 以进入patch 环节
在这里插入图片描述

然后输入1

如果同时交互式add 两个文件,这里会显示两个,这里的数字代表文件的序号

6. 选择文件并进入编辑模式

输入1后,还要输入一次回车才能进入文件的交互式add状态。
在这里插入图片描述

如图所示:

Stage this hunk [y,n,q,a,d,s,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
s - split the current hunk into smaller hunks
e - manually edit the current hunk
? - print help

选择y 会直接把这个文件stage
选择nstage这个文件
选择q 会放弃stage这个文件
选择astage这个文件还有以后所有的片段
d 与 a 相反
我们需要的是manually edit the current hunk 所以选择e

7. 手动编辑

在这里插入图片描述

我们想要method()1 和 method2() 形成一个提交,method3() 单独形成一个提交。
所以在界面中删除method3(),这样就不会被添加到暂存区。

注意:这里的删除不是在原文件中删除,而是不会被添加到暂存区

这样method3()不会被暂存,只有method1()和method2()被暂存

在这里插入图片描述

编辑完毕后进入这个状态、
在这里插入图片描述
直接输入q退出

8. 查看交互式add的成果

运行 git diff

以下结果说明 method3() 未被加到暂存区

`
在这里插入图片描述

运行 git diff --cached

以下结果说明 method1() 和 method2() 被加到暂存区

在这里插入图片描述

此时我们的目标完成了。
运行 git status 如图所示
在这里插入图片描述

9. 提交

我们将方法1 和方法2 提交
在这里插入图片描述

再提交方法3
在这里插入图片描述

10. 总结

交互式add 可以让我们暂存修改的粒度变的更小,由文件变成具体到某一行的修改。从而使得提交变得更灵活。便于体现代码的思路,也便于Code Review.

猜你喜欢

转载自blog.csdn.net/songyuequan/article/details/85038873