Git光速入门

Git是什么

Git is the most popular version control system in the world.

Git的作用:

  • 版本控制
  • 协同开发

Git的官网:git-scm.com

GitHub和Gitee是什么

GitHub和Gitee都是*代码托管和*协作开发平台**。我们可以将仓库(repository)托管到这样的平台上。

A repository contains all project files, including the revision history. ——GitHub

我们可以直接通过Git来synchronize our work directly with each other,但这样很complex。

因此,我们可以使用GitHub或Gitee提供的Git hosting service来让协同开发更便捷。

使用Git的方式

  • 通过Terminal来使用Git
  • 通过VS Code(一种code editor)来使用Git
    • 我们可以安装GitLensGit Graph(这两个都是VS Code Extension)来增强VS Code的Git能力
  • 通过GitKraken(一种GUI软件)来使用Git

如果我们基于GitHub来进行协作,那么我们还可以通过GitHub Desktop来使用Git,这种方式对Git新手比较友好。

Git命令

此处,我们通过Terminal来使用Git。

==配置Git==

1
2
git config --global user.name "Your Name"
git config --global user.email example@example.com

==创建仓库==

我们将代码快照存放于仓库中。

在terminal中,先跳转到项目内,然后执行:

1
git init

==克隆仓库==

克隆仓库:

1
git clone https://github.com/vpakati/CDUTCMOJ.git

==提交commit==

什么是commit?

Creating a commit is like taking a snapshot of our project.

Each commit also contains information about what was changed, by who, when, as well as a complete snapshot of our project at the time it was created.

简言之,commit == 项目快照+附加信息

如何创建commit并提交到仓库中?

更新代码并保存,然后执行:

1
2
git add .
git commit -m "Refactor code" # 双引号内的文字是该更新的表述

至此,该commit就被存放到了repository中了。

==查看历史==

查看项目的演进历史:

1
git log --oneline --all --graph

查看所有change了1001.cpp的commit:

1
git log --oneline -- 1001.cpp

查看所有change了1001.cpp的commit以及具体的change:

1
git log --oneline --patch -- 1001.cpp

查看谁在什么时候创建了什么commit:

1
git log --pretty=format:"%Cgreen%an%Creset committed %Cgreen%h%Creset on %Cred%cd%Creset"

查看每位contributor及其创建的commit:

1
git shortlog

查看1001.cpp的第1-3行代码的最后编辑人:

1
git blame -L 1,3 1001.cpp

==操作分支==

每个仓库都有一个主分支,其名字为master。

我们可以基于主分支创建一个新分支,并在该新分支中实现新功能或修改bug,然后将新分支合并(merge)到主分支。

创建bugfix分支:

1
git branch bugfix

切换到bugfix分支:

1
git switch bugfix

查看所有分支:

1
git branch

查看当前所处分支:

1
git status

将bugfix分支上的changes合并到master分支:

1
2
git switch master # 首先需要切换到master分支
git merge bugfix/signup-form # 然后执行合并

查看已被合并到当前分支的分支:

1
git branch --merged

删除bugfix/login-form分支:

1
git branch -d bugfix/login-form

请注意,合并分支时,难免会产生冲突,你可以参考下面的资料来处理冲突:https://www.bilibili.com/video/BV1Xy4y1n7D1?p=4&t=1770.4

fetch

获取其他人的work:

1
git fetch

pull

pull == fetch + merge

1
git pull

==pull request==

With the pull requests, we essentially open a discussion to team before merging a branch into master.

push

1
git push origin main

其他

1
git --version # 查看本机的git的版本

其他学习资料

Git有很多高阶功能,以帮助开发者们更好地进行版本控制和协同开发,可通过以下资料进一步学习: