Git版本控制实用指南
常见问题解决方案
1. 版本回滚后同步远程仓库
当本地版本回滚后,需要同步远程仓库的最新状态时,可以使用以下命令:
1
2
3
4
5
6
7
8
|
# 获取所有远程分支的最新状态
git fetch --all
# 强制重置当前分支到远程master分支
git reset --hard origin/master
# 拉取最新更改
git pull
|
注意:使用--hard
参数会丢失本地未提交的更改,请确保在执行前已备份重要更改。
2. 处理跨平台差异问题
换行符差异处理
在不同操作系统间协作时,经常会遇到换行符问题(CRLF vs LF):
1
2
3
4
5
6
|
# 配置全局换行符处理
git config --global core.whitespace cr-at-eol
# 推荐:配置自动转换
git config --global core.autocrlf input # 在Linux/Mac上
git config --global core.autocrlf true # 在Windows上
|
文件权限差异处理
在不同系统间切换时,文件权限可能导致不必要的差异:
1
2
3
4
5
|
# 忽略文件权限变化
git config core.filemode false
# 查看当前配置
git config --list | grep filemode
|
其他基础Git命令
1. 仓库状态查看
1
2
3
4
5
6
7
8
|
# 查看工作区状态
git status
# 查看变更详情
git diff
# 查看提交历史
git log --oneline --graph
|
2. 分支管理
1
2
3
4
5
6
7
8
|
# 创建并切换分支
git checkout -b feature/new-branch
# 列出所有分支
git branch -a
# 删除分支
git branch -d branch-name
|
3. 提交管理
1
2
3
4
5
6
7
8
|
# 暂存更改
git add .
# 提交更改
git commit -m "描述性的提交信息"
# 修改最后一次提交
git commit --amend
|
4. 远程仓库操作
1
2
3
4
5
6
7
8
|
# 添加远程仓库
git remote add origin [email protected]:username/repo.git
# 推送到远程
git push -u origin master
# 从远程拉取
git pull origin master
|
5. 撤销提交
1
2
3
4
5
|
# 撤销最近一次提交
git reset --soft HEAD^
# 撤销到指定的提交
git reset --soft <commit-hash>
|
Git配置最佳实践
1. 基础配置
1
2
3
4
5
6
|
# 设置用户信息
git config --global user.name "Your Name"
git config --global user.email "[email protected]"
# 设置默认编辑器
git config --global core.editor "vim"
|
2. 别名设置
1
2
3
4
5
|
# 常用命令简化
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
|
3. 差异工具配置
1
2
3
|
# 配置差异比较工具
git config --global diff.tool vimdiff
git config --global merge.tool vimdiff
|
4. 回滚到特定提交
1
|
git revert <commit-hash>
|