克隆
在多人开发中,不可能在 main 分支上进行开发,而默认拉取的是 main 分支,所以使用下面命令拉取指定的一条分支
git clone -b <remote-branch> <url>分支
# 显示分支(默认只显示本地分支);当前所在分支前用 * 标记
## -r:查看远程分支,-a:查看所有分支,-vv:查看本地分支与远程分支的追踪关系
git branch [-r] [-a] [-vv]
# 创建新分支
git branch <new-branch-name>
# 创建并自动切换到新分支
git switch -c <new-branch-name> [remote/remote-branch]
# 切换分支
git switch <local-branch>
# 删除本地分支
git branch <-d|-D> <local-branch>
# 删除远程分支
git push <remote> :<remote-branch>合并
以 feature 合并到 main 为例
# 普通合并
## 会产生一个 merge commit,保留完整分支结构,历史清晰但可能“分叉多”
git switch main
git merge feature
# 压缩合并
## feature 分支的多个 commit → 合成 1 个,历史更干净,看不到原始提交细节
git switch main
git merge feature --squash
git commit -m "feat: add feature"
# 变基合并
## 历史是一条直线,没有 merge commit,会“改写历史”(commit hash 会变)
git switch feature
git rebase main
git switch main
git merge feature
# or
git switch main
git rebase main feature
git merge feature撤销
# 安全撤销上次提交(保留历史)
git revert HEAD
# 彻底删除上次提交(需谨慎)
## --mixed 这是默认设置,并保持所有文件相同但取消暂存更改
## --soft 这将保留您的文件,并自动暂存所有更改
## --hard 这将完全破坏所有更改并将它们从本地目录中删除
git reset --[mixed|soft|hard] HEAD~2 # 回滚到上一个提交的状态
git reset --[mixed|soft|hard] <commit-id> # 回滚到指定的 commit
其他
# 拉取远程主机某个分支的更新,再与本地的指定分支合并
git pull [remote] [remote-branch[:local-branch]] [--rebase]
# 上传本地分支
git push [remote] [local-branch[:remote-branch]] [-u] [-f]
# 将更改暂时保存在脏工作目录中,很有用
git stash
# 日志
git log --graph --pretty=format:'%C(yellow)%h%Creset -%C(auto)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset'
# 将当前暂存区中的所有文件合并到之前的提交中
git commit --amend --no-edit
# 从一个分支中选择特定提交并将其应用到当前分支
git cherry-pick <commit-hash>
# 全局别名
git config --global alias.lg "log --graph --pretty=format:'%C(yellow)%h%Creset -%C(auto)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset'"
git config --global --unset alias.lg提交规范
提交格式为 <type>[(scope)]: <subject> 注意冒号 : 后有空格。如 feat(miniprogram): 增加了小程序模板消息相关功能
- scope:表示
commit的作用范围,如数据层、视图层,也可以是目录名称 - subject:用于对
commit进行简短的描述 - type:表示提交类型,值有以下几种:
| 值 | 说明 |
|---|---|
| feat | 新功能 |
| fix | 修复 bug |
| docs | 文档注释 |
| style | 代码格式(不影响代码运行的变动) |
| refactor | 重构、优化(既不增加新功能,也不是修复 bug) |
| perf | 性能优化 |
| test | 增加测试 |
| chore | 构建过程或辅助工具的变动 |
| revert | 回退 |
| build | 打包 |