Git代码提交指南
一、基础流程
1、拉取
-
### 主分支拉取 git clone http://... #对应仓库的代码地址 ### 其他分支拉取 git clone -b xxx_name http://... #对应分支名和仓库地址
2、分支操作
-
### 查看本地分支 git branch ### 查看本地和远程分支 git branch -a ### git branch 查看提交信息 git branch -vv #查看远程提交加-a ### 创建分支 git checkout -b new_branch_xxx #分支名 ### 切换分支 git checkout new_branch_xxx ### 删除分支 git branch -d new_branch_xxx
3、设置远程连接
-
### 查看远程 git remote -v # 结果: # origin https://gitee.com/xxx (fetch) # origin https://gitee.com/xxx (push) ### 添加远程仓库 git remote add origin_name_xxx https://gitee.com/xxx #设置远程名以及远程仓库地址 git remote -v # 结果: # origin https://gitee.com/xxx (fetch) # origin https://gitee.com/xxx (push) # origin_name_xxx https://gitee.com/xxx (fetch) # origin_name_xxx https://gitee.com/xxx (push) ### 添加指定的远程分支 git remote add name_origin_xxx -t branch_name_xxx https://gitee.com/xxx git remote -v # 结果: # origin https://gitee.com/xxx (fetch) # origin https://gitee.com/xxx (push) # origin_name_xxx https://gitee.com/xxx (fetch) # origin_name_xxx https://gitee.com/xxx (push) # name_origin_xxx https://gitee.com/xxx (fetch) # name_origin_xxx https://gitee.com/xxx (push) ### 同步远程代码 ## 相同分支同步 -->没有冲突 git pull #| git pull origin_name_xxx branch_name_xxx #不同分支同步 git fetch origin_name_xxx
4、提交
-
### 查看本地修改 git status ### 添加修改文件 git add file_xxx #文件相对路径 ### 添加修改目录 git add xxx_dir\ #目录相对路径 ### 添加删除文件或目录 git add -u xxx ### 撤销添加的文件或目录 git reset HEAD xxx ### 提交 git commit #然后写入提交信息 ### 把此次修改合并到上个提交里 git commit --amend ### 合入到远程分支 git push #默认为拉取的分支 ### 合入指定分支 git push origin_name_xxx xxx_branch ### 强制合入 git push -f #或者 git push --force ### 查看提交日志 git log
二、解决冲突
-
### 同步含有冲突的分支 git fetch origin_name_xxx #远程名 详看'一/3'节 ### 把fetch的分支代码合入到本地当前分支代码 git rebase origin_name_xxx/branch_name_xxx
-
## 如果有冲突 修改冲突文件 git status #冲突文件:both modified xxx ## 修改后 添加修改文件 git add xxx ## 同步冲突 git rebase --continue
-
### 合入分支 git push -f
三、回退和合并Commit
1、回退commit
-
### 回退上个commit并且把改commit的修改放到暂存区 git reset --soft HEAD ### 回退上个commit,并把该commit修改的代码全部删除 git reset --hard HEAD ### 回退到某个commit git reset --hard commitID #ID可由git log查询 git reset --soft commitID ### 再将回退的代码同步到远程 git push origin_name_xxx branch_name_xxx
2、合并commit
-
git log commitID——1 commitID——2 commitID——3 commitID——4 commitID——5
-
要求合并前三个commit,最终效果:
commitID——1&2&3 commitID——4 commitID——5
① 重新提交方式
-
### 查看最近五个commit,记录commitID git log -5 ### 从版本库恢复文件到暂存区 git reset --soft commitID——4 ### 查看暂存区 git status ### 提交commit git commit ### 合入到远程分支 git push #可选参数: -f origin_name_xxx branch_name_xxx --->详'三/1'节
② 压缩方式
-
git log -5 ### 将前三个commit压缩成一个commit git rebase -i HEAD~3 # 结果: # pick commitID——1 ...... # pick commitID——2 ...... # pick commitID——3 ...... ### 保留第一个pick,其他两个pick修改为fixup # 结果: # pick commitID——1 ...... # fixup commitID——2 ...... # fixup commitID——3 ...... ### 合入 如果出现 error: failed to push some refs to 加’-f‘进行强推 git push -f # 可选 :origin_name_xxx branch_name_xxx
PS:本文章写的比较抽象,适用于有一定基础的玩家把玩,0级新手村玩家慎用。