Git 使用教程—以 GitLab 上的 Django 项目为例
2020-10-14 本文已影响0人
Wonz
一、代码提交流程
1. clone 代码到本地
有两个命令,第一个是 clone master 主分支代码,第二个是 clone 某个 branch 分支代码。
团队项目开发中,我一般是 clone 别人分支代码进行整合,master 主分支代码很少动。
git clone http://www.xxx.xxx.git
git clone http://www.xxx.xxx.git -b <branch_name>
2. 创建分支
首先确保代码托管平台有这个分支,然后使用命令行在本地创建分支:
git checkout -b <branch_name>

创建完成会自动进入新分支路径,如上图所示,从 dev_zxx 转向了下图所示 dev_wxx 分支。
3. 提交代码到自己分支
查看当前状态:
git status

保存当前进度:
git stash
拉别人代码:
git pull origin <branch_name>

如果有冲突文件,需要使用 IDE 解决冲突。
恢复进度:
git stash pop

将所有改变添加到本地缓存区中:
git add .

添加修改注释:
git commit -m "注释内容,推荐使用英文"
把当前提交到 git 本地仓库的代码 push 到 GitLab 项目的某个分支上:
git push origin <branch_name>

二、分支合并
查看当前分支和全部分支:
git branch
git branch -a

发现本地没有想要合并到的目标分支,需要自己新建一下。
如果本地没有要合并的两个分支,需要先拉取代码到本地:
git fetch origin <dev_merge>:<dev_merge>
比如下图,我是拉取 GitLab 项目上一个 dev_yxx 同事的分支到本地。

切换到要合并的分支:
git checkout <dev_merge>
拉取当前分支最新代码:
git pull

合并某分支到当前分支:
git merge <dev_test>
下图所示是合并 dev_yxx 分支代码到 dev_wxx 分支中。

如果有冲突文件,使用 IDE 解决冲突。使用 Pycharm 打开项目,发现标红的文件都是有冲突的文件。

使用 Pycharm 可以直接查看右侧,点击标红的地方可以直接找到冲突位置进行修改。

下图中下面一行是合并的目标分支 dev_wxx 代码,上面一行是 dev_yxx 分支代码,我选择删掉两个红框里的冲突代码。

并执行以下命令:
git add "冲突文件名"
git commit -m "注释"
如果没有冲突,直接 push:
git push origin dev_merge

这样,就将 dev_yxx 分支代码合并到 dev_wxx 分支中了。同时保证了自己在 dev_wxx 分支中的修改,也保证了同事在 dev_yxx 中的修改。