寫在最前端
我使用的存放git代碼的工具是GitLab,記得需要和公司要GitLab的賬號和密碼。關(guān)于GitLab的賬號創(chuàng)建、登陸、SSH配置等步驟不是本次的重點,而且網(wǎng)上有很多配置步驟。本次只講解Git托管代碼時多人協(xié)作的使用步驟。
整體使用步驟
GIT會默認給使用者創(chuàng)建一個主分支,名稱為master。
按照下面的循環(huán)進行代碼開發(fā):
先保證master的代碼與遠程倉庫代碼相同(也可以不相同,但是最好養(yǎng)成相同的習(xí)慣,這樣會減少沖突的產(chǎn)生)。創(chuàng)建本地分支test并切換到該分支上,然后在test上進行代碼開發(fā),需要提交時先將master分支合并到test分支上,再將代碼push到遠程倉庫,最后通過pull指令將master分支上的代碼更新成最新的,將test分支刪除。
詳細步驟
1,先在主分支master上拉取最新代碼:
git pull
2,創(chuàng)建本地分支test:
git branch test
3,將android studio切換到test分支,并在在test上寫代碼:
git checkout test
4,下班時,先將test分支上的代碼隔離,將分支切換到master,并更新master上的代碼為遠程倉庫中的最新代碼:
git stash save "暫時隔離的說明信息"
git checkout master
git pull
5,將分支切換到test,先將test分支上隔離的代碼取出,之后將代碼提交,再將master分支合并到test分支上:
git checkout test
git rebase master
git stash pop #注意:在該步驟可能會出現(xiàn)沖突,若出現(xiàn)在該步驟進行沖突合并后再進行下面的操作
git add .
git commit -m"提交的日志"
6,將test分支上的代碼push到遠程倉庫中:
git push 遠程倉庫地址
7,在GitLab中添加 Merge Requests,等待合并完成代碼的郵件,或者如果在GitLab中有合并的權(quán)限,直接自己合并。
8,將分支切換到master分支,并將master分支上的代碼更新為遠程倉庫中最新代碼:
git checkout master
git pull
9,將test分支刪除:
git branch -d test
其他操作
1、 沖突解決
合并文件時,若有沖突會提示如下:
$ git merge feature1
Auto-merging readme.txt
CONFLICT (content): Merge conflict in readme.txt
Automatic merge failed; fix conflicts and then commit the result.
通過git status 查看沖突文件:定位到時readme.txt文件。
$ git status
On branch master
Your branch is ahead of 'origin/master' by 2 commits.
(use "git push" to publish your local commits)
You have unmerged paths.
(fix conflicts and run "git commit")
(use "git merge --abort" to abort the merge)
Unmerged paths:
(use "git add <file>..." to mark resolution)
both modified: readme.txt
no changes added to commit (use "git add" and/or "git commit -a")
打開readme.txt文件,找到?jīng)_突點:
Git is a distributed version control system.
Git is free software distributed under the GPL.
Git has a mutable index called stage.
Git tracks changes of files.
<<<<<<< HEAD
Creating a new branch is quick & simple.
=======
Creating a new branch is quick AND simple.
>>>>>>> feature1
根據(jù)實際業(yè)務(wù)情況,將沖突點處的代碼進行更改后,再進行提交即可:
$ git add readme.txt
$ git commit -m "conflict fixed"
[master cf810e4] conflict fixed
2、 修改本地分支名稱
查看本地所有分支
git branch
更改本地分支名稱
git branch -m old_branch_name new_branch_name
優(yōu)點
代碼的開發(fā)與合并都在重新創(chuàng)建的本地分支上,不會影響master分支與遠程倉庫中的代碼。