Git是目前最流行的分布式版本控制系统,被广泛应用于软件开发中。本文将全面介绍 Git 的各种功能和使用方法,包含大量代码示例和实践建议。
Git 基础概念 版本控制系统版本控制系统 (Version Control System, VCS) 是记录文件内容变化,以便将来查阅特定版本修订情况的系统。
Git 的特点分布式 :每个开发者都有完整的仓库副本高效 :大部分操作在本地完成完整性 :使用 SHA-1 哈希保证数据完整性灵活性 :支持多种非线性开发流程 Git 的三个区域工作目录 (Working Directory) :实际文件所在目录暂存区 (Staging Area) :准备提交的文件快照Git 仓库 (Repository) :永久存储的文件快照 Git 文件状态未跟踪 (Untracked) :新文件,未被 Git 管理已修改 (Modified) :文件已修改但未暂存已暂存 (Staged) :文件已修改并标记为下次提交已提交 (Committed) :文件已安全保存在本地数据库 Git 安装与配置 安装 Git Linux1 2 3 4 5 6 7 8 sudo apt-get install git sudo dnf install git sudo yum install git
macOS1 2 3 4 5 brew install git https://git-scm.com/download/mac
Windows下载 Git for Windows: https://git-scm.com/download/win
初始配置配置用户信息:
1 2 git config --global user.name "Your Name" git config --global user.email "your.email@example.com"
配置默认编辑器:
1 git config --global core.editor "vim"
查看配置:
常用别名配置:
1 2 3 4 5 6 git config --global alias.co checkout git config --global alias.br branch git config --global alias.ci commit git config --global alias.st status git config --global alias.unstage 'reset HEAD --' git config --global alias.last 'log -1 HEAD'
Git 仓库创建与管理 初始化新仓库1 2 3 mkdir my-projectcd my-projectgit init
克隆现有仓库1 2 3 git clone https://github.com/user/repo.git git clone https://github.com/user/repo.git my-local-folder git clone --depth 1 https://github.com/user/repo.git
查看仓库状态1 2 git status git status -s
忽略文件创建 .gitignore 文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 *.a !lib.a /TODO build/ doc/*.txt doc/**/*.pdf *.log node_modules/ .env
Git 基本工作流程 添加文件到暂存区1 2 3 4 5 6 git add file1.txt git add file2.txt file3.txt git add . git add -A git add -u git add -p
提交更改1 2 3 4 git commit -m "Initial commit" git commit -a -m "Commit all changes" git commit --amend git commit --amend --no-edit
查看提交历史1 2 3 4 5 6 7 8 9 10 11 12 git log git log -p git log -2 git log --stat git log --pretty=oneline git log --pretty=format:"%h - %an, %ar : %s" git log --since=2.weeks git log --author="John" git log --grep="bug fix" git log -S"function_name" git log -- path/to/file git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
比较差异1 2 3 4 5 6 7 git diff git diff --staged git diff HEAD git diff branch1..branch2 git diff commit1 commit2 git diff --name-only commit1 commit2 git diff --word-diff
Git 分支管理 创建与切换分支1 2 3 4 5 6 7 8 9 10 11 git branch git branch -a git branch new-branch git checkout branch-name git checkout -b new-branch git checkout -b new-branch origin/remote-branch git branch -d branch-name git branch -D branch-name git branch -m old-name new-name git branch --merged git branch --no-merged
合并分支1 2 3 4 git merge branch-name git merge --no-ff branch-name git merge --squash branch-name git merge --abort
解决冲突当合并发生冲突时,Git 会在冲突文件中标记冲突部分:
1 2 3 4 5 <<<<<<< HEAD 当前分支的内容 ======= 要合并的分支的内容 >>>>>>> branch-name
手动解决冲突后:
1 2 git add resolved-file.txt git commit
变基 (Rebase)1 2 3 4 git rebase branch-name git rebase --continue git rebase --abort git rebase -i HEAD~3
交互式变基常用操作:
pick: 使用提交 reword: 使用提交但修改提交信息 edit: 使用提交但暂停修改 squash: 将提交合并到前一个提交 fixup: 类似 squash 但丢弃提交信息 drop: 删除提交 Git 远程仓库操作 查看远程仓库1 2 3 git remote git remote -v git remote show origin
添加/移除远程仓库1 2 3 4 git remote add origin https://github.com/user/repo.git git remote rename origin new-name git remote remove origin git remote set-url origin https://github.com/user/new-repo.git
获取与拉取1 2 3 4 git fetch origin git fetch --prune git pull origin master git pull --rebase
推送1 2 3 4 5 6 7 git push origin master git push -u origin master git push origin --delete branch-name git push origin --tags git push origin HEAD git push --force git push --force-with-lease
Git 撤销与回退 撤销工作目录修改1 2 git checkout -- file.txt git checkout -- .
撤销暂存区修改 修改最后一次提交1 2 git commit --amend git commit --amend --no-edit
回退提交1 2 3 4 git reset --soft HEAD~1 git reset --mixed HEAD~1 git reset --hard HEAD~1 git revert HEAD
恢复删除的文件1 2 git checkout HEAD -- deleted-file.txt git checkout $(git rev-list -n 1 HEAD -- deleted-file.txt)^ -- deleted-file.txt
Git 标签管理 创建标签1 2 3 4 git tag v1.0 git tag -a v1.0 -m "Version 1.0" git tag -a v1.0 9fceb02 git tag -s v1.0 -m "Signed version 1.0"
查看标签1 2 3 git tag git show v1.0 git tag -l "v1.*"
推送标签1 2 git push origin v1.0 git push origin --tags
删除标签1 2 3 git tag -d v1.0 git push origin --delete v1.0 git push origin :refs/tags/v1.0
检出标签1 2 git checkout v1.0 git checkout -b version1 v1.0
Git 高级操作 储藏更改1 2 3 4 5 6 7 8 9 10 11 git stash git stash save "message" git stash list git stash apply git stash apply stash@{1} git stash pop git stash drop stash@{1} git stash clear git stash branch new-branch git stash -u git stash -a
二分查找1 2 3 4 5 git bisect start git bisect bad git bisect good v1.0 git bisect reset git bisect run test-script.sh
子模块1 2 3 4 5 6 git submodule add https://github.com/user/repo.git path/to/submodule git submodule init git submodule update git submodule update --init --recursive git submodule foreach 'git checkout master' git clone --recurse-submodules https://github.com/user/repo.git
重写历史1 2 3 4 5 6 7 8 9 10 git filter-branch --tree-filter 'rm -f passwords.txt' HEAD git filter-branch --commit-filter ' if [ "$GIT_AUTHOR_EMAIL" = "old@email.com" ]; then GIT_AUTHOR_NAME="New Name"; GIT_AUTHOR_EMAIL="new@email.com"; git commit-tree "$@"; else git commit-tree "$@"; fi' HEAD
注意:重写历史会改变提交哈希,只适用于尚未共享的提交。
打包与归档1 2 3 4 git bundle create repo.bundle HEAD master git clone repo.bundle repo -b master git archive --format=zip HEAD > archive.zip git archive --format=tar --prefix=project/ HEAD | gzip > project.tar.gz
Git 协作工作流 集中式工作流开发者克隆中央仓库 在本地提交更改 推送更改到中央仓库 解决冲突(如果有) 功能分支工作流为每个新功能创建独立分支 在功能分支上开发 完成后合并到主分支 删除功能分支 1 2 3 4 5 6 git checkout -b new-feature git commit -a -m "Implement new feature" git checkout master git merge new-feature git branch -d new-feature
Git FlowGit Flow 是一种流行的分支模型,定义严格的分支角色和交互方式。
主要分支:
master: 生产代码 develop: 集成开发分支 支持分支:
feature/*: 功能开发分支 release/*: 准备发布分支 hotfix/*: 紧急修复分支 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 git flow init git flow feature start myfeature git flow feature finish myfeature git flow release start 1.0.0 git flow release finish 1.0.0 git flow hotfix start 1.0.1 git flow hotfix finish 1.0.1
Forking 工作流开发者fork中央仓库 克隆自己的fork到本地 创建功能分支开发 推送更改到自己的fork 创建Pull Request请求合并到中央仓库 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 git clone https://github.com/yourname/repo.git git remote add upstream https://github.com/original/repo.git git fetch upstream git merge upstream/master git checkout -b new-feature git push origin new-feature
Git 问题排查 查看文件修改历史1 2 3 4 git blame file.txt git blame -L 10,20 file.txt git log -p file.txt git show commit-id:file.txt
查找问题提交1 2 3 4 5 git bisect start git bisect bad git bisect good v1.0 git bisect reset
恢复丢失的提交1 2 3 4 git reflog git fsck --lost-found git show commit-id git merge commit-id
清理仓库1 2 3 4 5 git gc git clean -n git clean -f git clean -fd git prune
Git 最佳实践 提交规范提交信息应清晰描述修改内容 第一行不超过50字符,作为摘要 第二行空行 第三行开始详细说明(如有必要) 使用现在时态、命令语气(如"Fix bug"而非"Fixed bug") 示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 Summarize changes in around 50 characters or less More detailed explanatory text, if necessary. Wrap it to about 72 characters or so. In some contexts, the first line is treated as the subject of the commit and the rest of the text as the body. The blank line separating the summary from the body is critical (unless you omit the body entirely); various tools like `log`, `shortlog` and `rebase` can get confused if you run the two together. Explain the problem that this commit is solving. Focus on why you are making this change as opposed to how (the code explains that). Are there side effects or other unintuitive consequences of this change? Here's the place to explain them. Further paragraphs come after blank lines. - Bullet points are okay, too - Typically a hyphen or asterisk is used for the bullet, preceded by a single space, with blank lines in between, but conventions vary here
分支命名规范feature/*: 新功能开发 bugfix/*: 错误修复 hotfix/*: 紧急修复 release/*: 版本发布准备 docs/*: 文档更新 test/*: 测试相关 工作流程建议频繁提交,原子性提交(每个提交只做一件事) 在推送前整理本地提交历史 使用分支进行功能开发和问题修复 定期从上游拉取更改 使用Pull Request进行代码审查 大型项目建议使用子模块或子树管理依赖 使用浅克隆减少下载量 使用稀疏检出只获取需要的文件 使用Git LFS管理大文件 1 2 3 4 5 6 7 8 9 10 git clone --depth 1 https://github.com/user/repo.git git init repo cd repogit remote add origin https://github.com/user/repo.git git config core.sparseCheckout true echo "some/dir/" >> .git/info/sparse-checkoutgit pull origin master
安全性建议不要提交敏感信息(密码、密钥等) 使用.gitignore忽略不必要的文件 定期检查提交历史中的敏感信息 必要时重写历史删除敏感信息 1 2 git log -p | grep "password"
总结Git 是一个功能强大且灵活的工具,掌握它可以极大提高开发效率。本文涵盖了 Git 的各个方面,从基础操作到高级技巧,从个人使用到团队协作。建议读者在实际项目中多加练习,逐步掌握 Git 的各种功能。
记住,Git 的核心概念是快照而非差异,理解这一点有助于更好地使用 Git。同时,遵循最佳实践可以使版本控制更加高效和安全。
Git 的学习曲线可能较陡峭,但一旦掌握,它将成为你开发工作中不可或缺的利器。