Git仓库的结构
Git 仓库分为三个部分:
- 工作区:也就是我们对项目进行直接操作的区域。
- 暂存区:可以理解成一个缓存区,add后的文件都存在这里,等待push。保存在.git/index中,因此也叫index区。
- 版本库:远程仓库,push以后的代码都放在这里。
工作区和暂存区都存在本地,只有自己可以访问和查看;版本库存在远程服务器上,是一个公共的仓库,大家都可以在上面进行clone、push和pull等操作。
另外还要介绍一个概念:HEAD是一个指向我们当前所处的分支的指针,而且是指向当前分支的最先版本。当我们重新进入git会回到之前所处的分支。
创建仓库
我们可以通过两种方式创建仓库:
git clone
通过http克隆:每次与远程仓库进行交互都需要输入用户名和密码,如clone、push、pull
通过ssh克隆【推荐】:我们可以通过ssh-keygen
产生自己的公钥,并添加到GitHub里面,就不需要输入用户名密码了。
git init
该命令执行完后会在当前目录生成一个 .git 目录,里面是这样的:
$ ls -R .git/
HEAD description info refs
config hooks objects
.git//hooks:
applypatch-msg.sample pre-applypatch.sample pre-receive.sample
commit-msg.sample pre-commit.sample prepare-commit-msg.sample
fsmonitor-watchman.sample pre-push.sample update.sample
post-update.sample pre-rebase.sample
.git//info:
exclude
.git//objects:
info pack
.git//objects/info:
.git//objects/pack:
.git//refs:
heads tags
.git//refs/heads:
.git//refs/tags:
-
HEAD,里面存储了当前所在的分支:
ref: refs/heads/master
-
config ,该文件包含你的仓库配置,比如远程的 url ,你的邮箱和用户名等。每次你在控制台使用 git config… 都会对这里产生影响:
[core] repositoryformatversion = 0 filemode = true bare = false logallrefupdates = true ignorecase = true precomposeunicode = true
-
description,显示仓库的描述。
-
hooks (钩子), 这些被称为钩子的脚本可以在提交 (commit)、变基 (rebase)、拉取 ( pull ) 操作的前后运行。脚本命预示着它的执行时机。如我们可以编写 pre-push 的作为钩子,进行推送代码前的检查。
-
info,我们可以将不想被 git 管理的文件记录到 .gitignore 文件中。
git remote
我们通过git init创建了一个仓库以后,可以通过git remote add [<options>] <name> <url>
与远程仓库进行关联。
同时,可以通过git remote
查看当前项目关联的远程仓库。
$ git remote
origion
$ git remote -v
origion git@github.com:pudongkai/demo.git (fetch)
origion git@github.com:pudongkai/demo.git (push)
基本操作
git add
将文件添加到缓存,也就是将当前的文件快照添加到暂存区(缓存)
git status
查看在你上次提交之后是否有修改。也就是暂存区和远程仓库之间的改变。
$ git add README.md
$ git status
On branch master
No commits yet
Changes to be committed:
(use "git rm --cached <file>..." to unstage)
new file: README.md
git diff
显示已写入缓存与已修改但尚未写入缓存的改动的区别。git diff 有两个主要的应用场景。
- 尚未缓存的改动:git diff
- 查看已缓存的改动: git diff --cached
- 查看已缓存的与未缓存的所有改动:git diff HEAD
- 显示摘要而非整个 diff:git diff --stat
git commit
缓存区内容添加到仓库中。可以使用git commit -a
跳过git add
git log
查看提交历史。注意只有提交操作会记录到log里面。
git reset
撤销已缓存的改动,也可以撤回到指定的版本
git rm
删除已经提交的文件
git mv
移动或重命名一个文件、目录、软连接。
git push
提交到远程仓库
分支管理
git branch
- 查看分支:
git branch
、git branch -a
(所有)、git branch -r
(远程分支) - 创建分支
git branch branchName
- 删除分支
git branch -d branchName
git checkout
-
切换分支
git checkout branchName
-
创建分支
git checkout -b branchName
git merge
将分支合并到当前分支git merge branchName
需要注意合并冲突的情况。当出现合并冲突,需要手动去修改。