跳到主要内容

Git使用遇到的问题

· 阅读需 5 分钟
amass
一个正在躺平的板砖人

解决Git提交冲突问题

每次我在写完代码,要向服务器提交时,经常会忘记提交前确认自己或其他同时是否提交过,而直接执行提交。如果之前确实有人提交,而我又没有同步,那么就会出现如下报错:

amass@AmassPC:~/Projects/Lifestyle$ git push origin
To gitea.amass.fun:amass/Lifestyle.git
! [rejected] main -> main (fetch first)
error: failed to push some refs to 'gitea.amass.fun:amass/Lifestyle.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

如果这时再使用git pull合并,就会出现很恶心的情况。首先,要解决远程仓库和本地仓库的冲突,然后再次commit写提交记录,那么在git log里面就会出现如下记录:

commit 54869cf8fef83261fe08afe596cf9bac891f6ace
Merge: 2c711d6 6c345a7
Author: amass 168062547@qq.com
Date: Sun Sep 4 17:51:39 2022 +0800

Merge branch 'master' of gitee.com:amass9610/Younger

作为一个强迫症,这时不能忍受的。我想如果一个对代码审核有要求的公司,大概率也不会允许的吧。

今天再次碰到这种情况了,在以往我可能是选择从Git服务器在clone一个新的仓库,然后使用Beyond Compare工具进行比对,把我的修改一个一个文件的查找修改至新拉下来的仓库里面,最后再提交,不过这样真心浪费时间,步骤也很繁琐。

今天决心一定要弄清楚这种情况要怎么解决,一番搜索之后,原来git reset就可以解决这个问题。首先我们先查看本地参考的log:

amass@AmassPC:~/Projects/Lifestyle$ git log
commit 571b09d87c86e0dab5ddfdccb14ea00b34192937 (HEAD -> main)
Author: amass 168062547@qq.com
Date: Sat Nov 11 14:20:33 2023 +0800

Add React Material package.

commit b769af4a5f6c2f2e2dd559eb81fe93faf102f732 (origin/main, origin/HEAD)
Author: amass 168062547@qq.com
Date: Sun Nov 5 19:30:53 2023 +0800

Optimize build script.
......

571b09d8就是当前我们已经提交的id,且正处于现在这个节点。b769af4a则是上一次提交记录,也就是最近未发生冲突的节点,所以我们直接回退致改节点,但是不撤销已修改的文件即可:

git reset b769af4a5f6c2f2e2dd559eb81fe93faf102f732

输出如下:

amass@AmassPC:~/Projects/Lifestyle$ git reset b769af4a5f6c2f2e2dd559eb81fe93faf102f732
Unstaged changes after reset:
M docusaurus.config.js
M package.json
M src/pages/LoginPage.jsx

将特定文件回退至指定commit

在平常工作中,也许是代码提交不规范,或种种原因,之前提交了临时代码,然后现在想把代码回退至之前某个历史提交:

git checkout <commit-hash> -- <file-path1> <file-path2>

回退远程提交

有时提交的代码不需要了,且不想有那些提交历史。可以使用强制推送,但是一定要 慎用,少用!!!

git log	# 查找提交记录
git reset --hard <commit-hash> # 使用reset回退到该提交<commit-hash>
git push --force <remote_name> <branch_name> # 强制推送到远程仓库

分支合并

git checkout master 	# 切换到 master 分支
git pull origin master # 确保 master 分支已是最新的
git merge dev # 将 dev 分支合入 master 分支
# 可能会有冲突,解决冲突
# 使用 git commit 提交合并后的代码
git push origin master # 将合并后的更改推送到远程的 master 分支
git branch -d dev # 删除本地 dev 分支
git push origin --delete dev # 删除远程 dev 分支