10 个基本 Git 命令可简化你的工作流程

使用这些实用命令升级您的 Git 技能,旨在使您的开发过程更加顺畅和高效。

1. git switch:简化分支切换

切换分支过去需要使用“git checkout”,它功能多样,但容易出错。Git 引入了“git switch”,以便以更干净、更安全的方式管理分支:

# Switch to another branch
git switch   

# Create and switch to a new branch
git switch -c 

这消除了分支机构运营期间意外修改文件的风险。

2. git restore:安全地撤消更改

使用 `git restore` 可以更轻松地在不干扰分支历史记录的情况下恢复文件更改:

# Discard changes in your working directory
git restore   

# Unstage changes
git restore --staged 

它是撤消更改的“git checkout”的更安全的替代方法。

3. git 维护:自动化仓库健康

维护存储库性能对于大型项目至关重要。使用以下方法自动优化:

# Start automatic maintenance
git maintenance start  

# Run maintenance tasks manually
git maintenance run

它执行垃圾收集、重新打包数据并更新提交图,以使您的存储库保持快速高效。

4. git sparse-checkout:在 Monorepos 中高效工作

使用“git sparse-checkout”可以更轻松地管理大型 monorepos,它仅获取您需要的文件或目录:

# Enable sparse-checkout mode
git sparse-checkout init  

# Specify directories or files to include
git sparse-checkout set 

避免不必要的下载,节省时间和磁盘空间。

5. git log --remerge-diff:了解合并更改

合并提交通常缺乏详细的背景信息,尤其是在解决冲突之后。使用“git log --remerge-diff”重建合并引入的更改:

git log --remerge-diff

它非常适合调试合并冲突或审查复杂的合并。

6. git blame --ignore-rev:过滤掉嘈杂的提交

批量格式更改可能会使“git blame”变得混乱。使用以下方法排除不相关的提交:

# Ignore a specific commit in blame
git blame --ignore-rev   

# Persist ignored commits
echo  >> .git-blame-ignore-revs  
git config blame.ignoreRevsFile .git-blame-ignore-revs

忽略非功能性更新,专注于有意义的创作。

7. git range-diff:比较提交范围

重新定基或重写历史记录后,比较两个提交范围以了解差异:

git range-diff  

此命令可帮助您跟踪变化的演变方式并确保跨分支的一致性。

8. git worktree:同时在多个分支上工作

通过使用“git worktree”同时处理多个分支来避免工作流程中断:

# Create a new worktree for a branch
git worktree add    

# Remove a worktree when done
git worktree remove 

这对于无需切换分支即可测试或隔离构建特别有用。

9. git rebase --update-refs:保持引用对齐

重新定基通常会使分支指针指向过期的提交。使用以下方法修复此问题:

# Rebase and update references
git rebase --update-refs  

# Enable automatic ref updates
git config rebase.updateRefs true

保持标签和分支与重写历史同步。

10. git commit --fixup & git rebase --autosquash:清理提交历史记录

通过自动修复提交来维护干净的提交历史记录:

# Create a fixup commit targeting a specific commit
git commit --fixup=  

# Squash fixup commits during rebase
git rebase -i --autosquash

这使得合并之前完善您的提交历史变得简单且无错误。