HEAD是Git的核心概念,它是一个指向当前所在本地分支的指针。可以理解为你在代码库中的"当前位置"。
# 查看当前HEAD指向
cat .git/HEAD当你在分支之间切换时,HEAD指针会在不同分支的最新提交处移动,这确保了你在正确的工作上下文中操作。
# 新增文件到缓存区,让Git开始跟踪该文件
git add filename.jsp
# 提交到本地版本库
git commit -m "描述性提交信息"
# 一次性添加所有变更文件并提交
git add . && git commit -m "批量提交"# 查看当前工作区状态
git status
# 查看提交历史
git log --oneline
# 图形化显示分支历史
git log --graph --oneline --all# 创建新分支
git branch feature-new
# 切换到指定分支
git checkout feature-new
# 创建并立即切换到新分支(推荐)
git checkout -b feature-new
# 查看所有分支
git branch -a# 查看分支最新提交信息
git branch -v
# 查看与远程分支的版本差距
git branch -vv
# 查看已合并到当前分支的分支
git branch --merged
# 查看未合并的分支
git branch --no-merged# 安全删除已合并的分支
git branch -d feature-old
# 强制删除未合并的分支
git branch -D feature-abandoned
# 删除远程分支(GitLab)
git push origin --delete feature-remote# 克隆GitLab远程仓库
git clone https://gitlab.com/your-project/repository.git
# 克隆并自定义远程库名称
git clone -o gitlab https://gitlab.com/your-project/repository.git
# 添加新的远程服务器
git remote add upstream https://gitlab.com/original/repository.git# 获取远程更新(不自动合并)
git fetch origin
# 创建跟踪远程分支的本地分支
git checkout -b feature-remote origin/feature-remote
# 推送本地分支到远程
git push -u origin feature-local
# 推送到远程不同名称的分支
git push origin feature-local:remote-feature# 推荐:先fetch再merge,比直接pull更安全
git fetch origin
git merge origin/develop
# 不推荐:直接pull(相当于fetch + merge)
git pull origin develop当被合并的分支处于当前分支的直接下游时发生:
# 当前分支:develop,要合并feature分支
git checkout develop
git merge featureGit会直接将develop指针移动到feature的最新提交,保持线性历史。
有分叉的分支合并时,Git会:
# 处理合并冲突的完整流程
git merge feature
# 如果出现冲突,Git会暂停合并
# 查看冲突文件
git status
# 手动解决冲突后
git add resolved-file.jsp
git commit -m "合并feature分支,解决冲突"# 从develop创建功能分支
git checkout -b feature/user-authentication develop
# 开发完成后合并回develop
git checkout develop
git merge --no-ff feature/user-authentication
git branch -d feature/user-authentication# 从develop创建发布分支
git checkout -b release/1.2.0 develop
# 修复发布前的bug,测试完成后
git checkout master
git merge --no-ff release/1.2.0
git tag -a v1.2.0
# 同步到develop
git checkout develop
git merge --no-ff release/1.2.0
git branch -d release/1.2.0# 从master创建热修复分支
git checkout -b hotfix/critical-bug master
# 修复并测试完成后
git checkout master
git merge --no-ff hotfix/critical-bug
git tag -a v1.2.1
# 同步到develop
git checkout develop
git merge --no-ff hotfix/critical-bug
git branch -d hotfix/critical-bug在GitLab项目中设置:
# .gitlab-ci.yml示例
stages:
- test
- deploy
unit_tests:
stage: test
script:
- mvn test
deploy_staging:
stage: deploy
script:
- mvn deploy -Dtarget=staging
only:
- develop# 使用语义化提交信息
git commit -m "feat: 添加用户登录功能"
git commit -m "fix: 修复登录页面样式问题"
git commit -m "docs: 更新API文档"# 使用图形化工具解决冲突
git mergetool
# 放弃当前合并
git merge --abort
# 查看冲突文件的双方差异
git diff --ours
git diff --theirs# 撤销未提交的修改
git checkout -- filename.jsp
# 撤销已暂存的文件
git reset HEAD filename.jsp
# 撤销最近一次提交(保持修改)
git reset --soft HEAD~1