实用 git 笔记
Daisy Author

Github 是一个很好的平台,而 git 则是一个很强大的工具,因此,掌握 git 指令是十分必要的。

这篇博客主要记录使用 git 进行版本管理的基本指令。

常用 git 指令

1. 初始化仓库

BASH
1
git init

2. 远程仓库交互

BASH
1
2
3
4
5
6
# 克隆远程仓库
git clone <repo url/ssh>
# 拉取远程仓库内容
git pull origin <branch name>
# 向远程仓库提交内容
git push origin <branch name>

3. 查看仓库状态/历史

BASH
1
2
3
4
# 查看状态
git status
# 查看历史(日志)
git log

4. 将文件加入 git 版本控制

BASH
1
2
3
4
5
# 文件追踪
git add <file name>
# 注:git add . 提交当前工作区下所有修改或未被追踪的文件
# 文件提交
git commit -m "提交信息"

5. 分支操作

BASH
1
2
3
4
5
6
# 创建分支
git checkout -b <branch name>
# 切换分支
git checkout <branch name>
# 分支重命名
git branch -M <new branch name>

6. 建立本地仓库与远程仓库连接

BASH
1
2
3
4
5
6
7
8
# 仓库初始化
git init
# 修改本地默认分支名(一般为 master)
git branch -M main
# 建立本地仓库与远程仓库连接
git remote add origin <remote repo url>
# 复核远程仓库信息
git remote -v

多人协作

涉及多分支管理,维护一个主分支,多个分支共同开发。

首先,克隆远程仓库到本地,并在本地新建分支进行开发。

BASH
1
2
3
4
5
git clone <repo url>
git checkout -b <branch dev>
git add .
git commit -m "commit message"
git push origin <branch dev>

提交后,在 Github 仓库页面切换到 <branch dev> 开发分支,网页会显示当前分支有领先主分支的提交,此时可以在网页中直接发起 pr 请求。

pr 被合并后,主分支将会领先开发分支一个提交(merge pr),为了后续开发的进行,我们需要同步两个分支的提交。

BASH
1
2
3
git checkout <brach dev>
git rebase main
git push origin <brach dev>

如果多人协作提交的内容产生冲突,则需要先处理冲突再 merge。

版本管理常用文件

.gitignore

在该文件中添加你不想被 git 追踪的文件的相对路径,git 不会对这些文件执行版本管理。

示例:

1
2
3
.idea/

**/__pycache__/

.gitattributes

统一管理仓库文件格式/编码。

示例:

BASH
1
2
# Auto detect text files and perform LF normalization
* text=auto

提交规范

使用清晰明了的提交信息,规范化提交。

  • 新功能: feat: <brief description>
  • bug修复: fix: <brief description>
  • 文档: doc: <brief description>
  • 重构: refactor: <brief description>