git仓库
1 |
|
新建本地仓库(local repository)方法有两种:
-
根据本地已有项目,进入该项目目录,运行:
1
$ git init
-
克隆远端仓库(remote repository)
1
$ git clone https://github.com/***/***.git
git clone完成之后,git会自动将remote repository命名为origin(可以采用-o
文件的状态有四种:untracked、unmodified、modified、staged,查看和修改文件状态可以采用:
1 |
|
删除、移动文件
1 |
|
查看commit历史
1 |
|
撤销操作
1 |
|
远程仓库
1 |
|
1 |
|
注意:git fetch
命令会将数据拉取到你的本地仓库,它并不会自动合并或修改你当前的工作。而git pull
通常会从最初克隆的服务器上抓取数据并自动尝试合并到当前所在的分支。 可以认为git pull
是git fetch
和git merge
两个步骤的结合。
打标签
1 |
|
使用别名
1 |
|
git分支
提交(commit)对象:包含一个指向暂存内容快照的指针,包含本次提交的作者等相关附属信息,包含零个或多个指向该提交对象的父对象指针。git可以认为是管理commit的系统,由一个commit列表(old<-new)构成一个分支(branch),branch本质上是指向commit列表头的可变指针,随着每次提交向新commit的对象移动。
在git服务器(如github)上的是远端分支(remote branch),在本地是本地分支(local branch),在git push之前,所有改动都是在local branch进行,和remote branch是独立(并行)的。gitk显示的是local repository。
remote server/remote repository/remote branch
local host/local repository/local branch
默认创建的branch是master,创建新的branch,本质上是添加一个指向当前commit对象的指针,git保存了一个名为HEAD的特别指针,指向正在工作的local branch
1 |
|
开发新功能的一般步骤:
-
在master切换到新的branch:new_feature,并进行相应的改动
1
2
3$ git checkout -b new_feature $ vim index.html $ git commit -a -m 'added a new footer [new_feature]'
-
突然需要在master进行漏洞修复,先基于master创建一个新的branch:bug_fix,待完整测试无误后再合并到master
1
2
3
4
5
6
7$ git checkout master #切换回master $ git checkout -b bug_fix #新建并切换到bugfix $ vim index.html $ git commit -a -m 'fix bug' $ git checkout master $ git merge bug_fix #由于当前master所在的提交对象是要并入的bug_fix分支的直接上游,只需把master指针直接右移(快进合并) $ git branch -d bug_fix #由于bug_fix和master指向相同commit,可以删掉
-
回到new_feature,继续工作。
1
2
3$ git checkout new_feature $ vim index.html $ git commit -a -m 'finished the new footer [new_feature]'
注意之前bug_fix的修改并没有在new_feature中。如果需要纳入此次修改,可以用
git merge master
把master
合并到new_feature
;或者等new_feature
完成之后,再将new_feature
分支中的更新并入master
。 -
等new_feature完成之后,合并回master
1
2
3
4
5$ git checkout master $ git merge new_feature $ git status #由于master不是new_feature直接上游,出现文件冲突时,先通过git status查阅 $ git mergetool #之后可以通过手工修改,然后git add;或调用可视化工具 $ git status #再运行一次 git status 来确认所有冲突都已解决
或者采用变基(rebase)方式,可以得到一个较为整洁的commit历史,建议采用此方式
1
2
3
4
5$ git checkout new_feature $ git rebase master #将master变为new_feature直接上游 $ git rebase master new_feature #等效于上两个命令 $ git checkout master $ git merge new_feature #可以进行快进合并
奇妙的变基也并非完美无缺,要用它得遵守一条准则:
不要对在你的仓库外有副本的分支执行变基。