Git版本控制基础
Git版本控制基础
Git简介
Git是一个分布式版本控制系统,用于跟踪文件的变更历史。
基本配置
# 设置用户信息
git config --global user.name "Your Name"
git config --global user.email "your@email.com"
# 设置默认分支
git config --global init.defaultBranch main
# 查看配置
git config --list
基本操作
仓库操作
# 初始化仓库
git init
# 克隆仓库
git clone https://github.com/user/repo.git
git clone https://github.com/user/repo.git mydir
提交流程
# 查看状态
git status
# 添加文件
git add file.txt # 添加单个文件
git add . # 添加所有文件
git add *.js # 添加匹配的文件
# 提交
git commit -m "commit message"
git commit -am "message" # 跳过add,直接提交已跟踪文件
# 查看提交历史
git log
git log --oneline
git log -5
git log --graph
分支操作
# 查看分支
git branch
git branch -a # 包含远程分支
# 创建分支
git branch feature
# 切换分支
git checkout feature
git checkout -b feature # 创建并切换
# 合并分支
git checkout main
git merge feature
# 删除分支
git branch -d feature
git branch -D feature # 强制删除
远程操作
# 查看远程仓库
git remote -v
# 添加远程仓库
git remote add origin https://github.com/user/repo.git
# 推送
git push origin main
git push -u origin main # 设置上游分支
# 拉取
git pull origin main
git fetch origin
高级操作
撤销操作
# 撤销工作区修改
git checkout -- file
git restore file
# 撤销暂存
git reset HEAD file
git restore --staged file
# 修改最后一次提交
git commit --amend -m "new message"
# 回退提交
git reset --soft HEAD~1 # 保留修改
git reset --mixed HEAD~1 # 保留修改,取消暂存
git reset --hard HEAD~1 # 丢弃所有修改
Stash
# 暂存修改
git stash
git stash push -m "message"
# 查看暂存
git stash list
# 恢复暂存
git stash pop
git stash apply stash@{0}
# 删除暂存
git stash drop stash@{0}
git stash clear
标签
# 创建标签
git tag v1.0.0
git tag -a v1.0.0 -m "Version 1.0.0"
# 查看标签
git tag
# 推送标签
git push origin v1.0.0
git push origin --tags
# 删除标签
git tag -d v1.0.0
git push origin :refs/tags/v1.0.0
.gitignore
# 依赖目录
node_modules/
vendor/
# 编译产物
dist/
build/
# 环境文件
.env
.env.*
# IDE文件
.idea/
.vscode/
*.swp
# 系统文件
.DS_Store
Thumbs.db
实践:Git工作流
# 1. 创建功能分支
git checkout -b feature/user-auth
# 2. 开发并提交
git add .
git commit -m "feat: add user authentication"
# 3. 同步main分支
git fetch origin
git rebase origin/main
# 4. 推送分支
git push origin feature/user-auth
# 5. 创建Pull Request(在GitHub/GitLab上)
# 6. 合并后删除分支
git checkout main
git pull origin main
git branch -d feature/user-auth
总结
Git是现代软件开发的基础工具。掌握Git的核心概念和常用命令,能够有效地管理代码版本和协作开发。