Git分支详解

924 阅读2分钟

Git分支详解

git branch命令

  • 查看分支 git branch
  • 新建分支 git branch branch_name
  • 切换分支 git checkout branch
  • 删除分支 git branch -d branch_name (注意不能删除当前所在的分支)
  • 更改分支名称 git branch -m old_name new_name
  • 创建分支并切换到新创建的分支 git branch -b branch_name
  • 合并分支 git merge branch_name
  • 查看工作区与暂存区差异 git diff
  • 查看提交历史 git log
  • 封存当前暂存区修改 git stash
  • 查看当前保存内容 git stash list
  • 提取暂存区 git stash apply stash@{0}

git分支初步使用

1.首先查看当前目录下的git分支

$ git branch
  admin
* master

当前目录有两个分支,分别是master与admin分支,并且目前我们处于master分支上。 当前的项目文件的内容相同,因为我们没有做修改。 2.对文件进行修改并合并 在master分支下的文件里添加注释

#this is master branch

在admin分支下的文件中添加注释

#this is admin branch

使用git commit -am 'admin branch'提交更改

回到master分支,使用git merge admin命令合并分支

$ git merge admin
Auto-merging dPro/urls.py
CONFLICT (content): Merge conflict in dPro/urls.py
Automatic merge failed; fix conflicts and then commit the result.

可以看到,git提示我们合并失败,因为在文件dPro/url.py内有冲突,他要求我们手动合并并重新提交

在dPro/url.py内显示了冲突的内容

<<<<<<< HEAD
#这是master分支
=======
#this is admin branch
>>>>>>> admin

我们对文件进行修改,将admin分支的内容合并到master分支上,修改结果如下

#this is admin branch

git提示我们合并成功

3.查看版本差异

首先使用git log查看版本历史

commit f387cc59552544a031cbd424f3d516a2781ecbab (HEAD -> master)
Merge: 167823b 8e554e9
Author: Qian <2358979326@qq.com>
Date:   Sun Jun 2 12:36:38 2019 +0800

    mergeadmin fix conflict 

commit 8e554e9a334d31b5acce076d465fb398f6d9ac6c (admin)
Author: Qian <2358979326@qq.com>
Date:   Sun Jun 2 12:19:52 2019 +0800

    admin branch

commit 167823b479d9c932414534bbaa6610674807f907
Author: Qian <2358979326@qq.com>
Date:   Sat Jun 1 23:39:58 2019 +0800

    test


我们选择两个版本比较差异,使用git diff 版本号1 版本号2,一般选择版本号前8位(git使用前7位)。

$ git diff f387cc595 167823b479d
diff --git a/dPro/urls.py b/dPro/urls.py
index f12a399..7ca8aa1 100644
--- a/dPro/urls.py
+++ b/dPro/urls.py
@@ -24,5 +24,4 @@ urlpatterns = [
    url(r'login/',views.login),
    url(r'index/',views.index),
]
-#this is admin branch
-
+#这是master分支

4.封存暂存区 我们对文件进行修改,添加#对暂存区的修改,并保存 接着我们切换到admin分支,使用git checkout admin命令,出现以下错误

error: Your local changes to the following files would be overwritten by checkout:
        dPro/urls.py
Please commit your changes or stash them before you switch branches.
Aborting

git提示我们提交我们的修改,或者是在切换分支之前satsh他们。 我们使用git stash命令暂存。 此时我们的工作区已经变成了修改之前的状态,即之前做的修改已经撤销掉了,可以安全的切换分支了。

5.提取暂存区

当我们将修改暂存并切换分支后,重新回到之前暂存内容的分支时,如何提取之前stash的内容? 首先使用git stash list查看当前保存的内容

$ git stash list
stash@{0}: WIP on master: f387cc5 mergeadmin fix conflict
stash@{1}: WIP on master: f387cc5 mergeadmin fix conflict

使用命令git stash apply stash@{0},打开编辑器,可以看到之前做的修改已经提取出来了。