Git & Github

 

为何要用版本控制?

假设你在的公司要上线一个新功能,大家开发团队为实现这个新功能,写了大约5000行代码,上线没2天,就发现这个功能用户并不喜欢,你老板让你去掉这个功能,你怎么办?你说简单,直接把5000行代码去掉就好了,可是个人亲,说的简单,你的这个功能写了3周时间,但你还能记得你是新增长了哪5000行代码么?因此你急须要一个工具,能帮你记录每次对代码作了哪些修改,而且能够轻易的把代码回滚到历史上的某个状态。 这个神奇的工具就叫作版本控制。 html

 

 

版本控制工具主要实现2个功能:node

版本管理

在开发中,这是刚需,必须容许能够很容易对产品的版本进行任意回滚,版本控制工具实现这个功能的原理简单来说,就是你每修改一次代码,它就帮你作一次快照python

协做开发

一个复杂点的软件,每每不是一个开发人员能够搞定的,公司为加快产品开发速度,会招聘一堆跟你同样的开发人员开发这个产品,拿微信来举例,如今假设3我的一块儿开发微信,A开发联系人功能,B开发发文字、图片、语音通信功能,C开发视频通话功能, B和C的功能都是要基于通信录的,你说简单,直接把A开发的代码copy过来,在它的基础上开发就行了,能够,可是你在他的代码基础上开发了2周后,这期间A没闲着,对通信录代码做了更新,此时怎么办?你和他的代码不一致了,此时咱们知道,你确定要再把A的新代码拿过来替换掉你手上的旧通信录功能代码, 如今人少,3我的之间沟通很简单,但想一想,若是团队变成30我的呢?来回这样copy代码,很快就乱了, 因此此时亟需一个工具,能确保一直存储最新的代码库,全部人的代码应该和最新的代码库保持一致git

 

常见版本管理工具介绍

一、VSS-- Visual Source Safe
此工具是Microsoft提供的,是使用的至关广泛的工具之一,他能够与VS.net进行无缝集成,成为了独立开发人员和小型开发团队所适合的工具,基本上Window平台上开发的中小型企业,当规模较大后,其性能一般是没法忍受的,对分支与并行开发支持的比较有限。github

二、CVS--Concurrent Versions System,
此工具是一个开源工具,与后面提到的SVN是同一个厂家:Collab.Net提供的。
CVS是源于unix的版本控制工具,对于CVS的安装和使用最好对unix的系统有所了解能更容易学习,CVS的服务器管理须要进行各类命令行操做。目前,CVS的客户端有winCVS的图形化界面,服务器端也有CVSNT的版本,易用性正在提升。
此工具是至关著名,使用得至关普遍的版本控制工具之一,使用成熟的“Copy-Modify-Merge"开发模型,能够大大的提升开发效率,适合于项目比较大,产品发布频繁,分支活动频繁的中大型项目。web

三、SVN --CollabNet Subversion
此工具是在CVS 的基础上,由CollabNet提供开发的,也是开源工具,应用比较普遍。
他修正cvs的一些局限性,适用范围同cvs,目前有一些基于SVN的第三方工具,如TortoiseSVN,是其客户端程序,使用的也至关普遍。在权限管理,分支合并等方面作的很出色,他能够与Apache集成在一块儿进行用户认证。
不过在权限管理方面目前尚未个很好用的界面化工具,SVNManger对于已经使用SVN进行配置的项目来讲,基本上是没法应用的,但对于从头开始的项目是能够的,功能比较强大,可是搭建svnManger比较麻烦。
是一个跨平台的软件,支持大多数常见的操做系统。做为一个开源的版本控制系统,Subversion 管理着随时间改变的数据。 这些数据放置在一个中央资料档案库中。 这个档案库很像一个普通的文件服务器, 不过它会记住每一次文件的变更。 这样你就能够把档案恢复到旧的版本, 或是浏览文件的变更历史。Subversion 是一个通用的系统, 可用来管理任何类型的文件, 其中包括了程序源码。sql


4. GIT
由于最初是从Linux起家的,很是依赖文件系统的一些特性,这些在 Linux 下表现的很好,而 Windows 下特别糟糕Git 中文教程
Git是一个开源的分布式版本控制系统,用以有效、高速的处理从很小到很是大的项目版本管理.
Git 是 Linus Torvalds 为了帮助管理 Linux 内核开发而开发的一个开放源码的版本控制软件。
Torvalds 开始着手开发 Git 是为了做为一种过渡方案来替代 BitKeeper,后者以前一直是 Linux 内核开发人员在全球使用的主要源代码工具。开放源码社区中的有些人以为 BitKeeper 的许可证并不适合开放源码社区的工做,所以 Torvalds 决定着手研究许可证更为灵活的版本控制系统。尽管最初 Git 的开发是为了辅助 Linux 内核开发的过程,可是咱们已经发如今不少其余自由软件项目中也使用了 Git。例如 最近就迁移到 Git 上来了,不少 Freedesktop 的项目也迁移到了 Git 上。数据库

五、BitKeeper
是由BitMover公司提供的,BitKeeper自称是“分布式”可扩缩SCM系统。
不是采用C/S结构,而是采用P2P结构来实现的,一样支持变动任务,全部变动集的操做都是原子的,与svn,cvs一致。bootstrap

 

github介绍

不少人都知道,Linus在1991年建立了开源的Linux,今后,Linux系统不断发展,已经成为最大的服务器系统软件了。ubuntu

Linus虽然建立了Linux,但Linux的壮大是靠全世界热心的志愿者参与的,这么多人在世界各地为Linux编写代码,那Linux的代码是如何管理的呢?

事实是,在2002年之前,世界各地的志愿者把源代码文件经过diff的方式发给Linus,而后由Linus本人经过手工方式合并代码!

你也许会想,为何Linus不把Linux代码放到版本控制系统里呢?不是有CVS、SVN这些免费的版本控制系统吗?由于Linus坚决地反对CVS和SVN,这些集中式的版本控制系统不但速度慢,并且必须联网才能使用。有一些商用的版本控制系统,虽然比CVS、SVN好用,但那是付费的,和Linux的开源精神不符。

不过,到了2002年,Linux系统已经发展了十年了,代码库之大让Linus很难继续经过手工方式管理了,社区的弟兄们也对这种方式表达了强烈不满,因而Linus选择了一个商业的版本控制系统BitKeeper,BitKeeper的东家BitMover公司出于人道主义精神,受权Linux社区无偿使用这个版本控制系统。

安定团结的大好局面在2005年就被打破了,缘由是Linux社区牛人汇集,难免沾染了一些梁山好汉的江湖习气。开发Samba的Andrew试图破解BitKeeper的协议(这么干的其实也不仅他一个),被BitMover公司发现了(监控工做作得不错!),因而BitMover公司怒了,要收回Linux社区的无偿使用权。

Linus能够向BitMover公司道个歉,保证之后严格管教弟兄们,嗯,这是不可能的。实际状况是这样的:

Linus花了两周时间本身用C写了一个分布式版本控制系统,这就是Git!一个月以内,Linux系统的源码已经由Git管理了!牛是怎么定义的呢?你们能够体会一下。

Git迅速成为最流行的分布式版本控制系统,尤为是2008年,GitHub网站上线了(github是一个基于git的代码托管平台,付费用户能够建私人仓库,咱们通常的免费用户只能使用公共仓库,也就是代码要公开。),它为开源项目免费提供Git存储,无数开源项目开始迁移至GitHub,包括jQuery,PHP,Ruby等等。

历史就是这么偶然,若是不是当年BitMover公司威胁Linux社区,可能如今咱们就没有免费而超级好用的Git了。

 

今天,GitHub已经是:

  • 一个拥有143万开发者的社区。其中不乏Linux发明者Torvalds这样的顶级黑客,以及Rails创始人DHH这样的年轻极客。
  • 这个星球上最流行的开源托管服务。目前已托管431万git项目,不只愈来愈多知名开源项目迁入GitHub,好比Ruby on Rails、jQuery、Ruby、Erlang/OTP;近三年流行的开源库每每在GitHub首发,例如:BootStrapNode.jsCoffeScript等。
  • alexa全球排名414的网站。

git安装

官网:https://git-scm.com/downloads

 

版本库建立

什么是版本库呢?版本库又名仓库,英文名repository,你能够简单理解成一个目录,这个目录里面的全部文件均可以被Git管理起来,每一个文件的修改、删除,Git都能跟踪,以便任什么时候刻均可以追踪历史,或者在未来某个时刻能够“还原”。

因此,建立一个版本库很是简单,首先,选择一个合适的地方,建立一个空目录:

shuais-MBP:~ dandyzhang$ mkdir git_test
shuais-MBP:~ dandyzhang$ cd git_test

shuais-MBP:git_test dandyzhang$ git init
Initialized empty Git repository in /Users/dandyzhang/git_test/.git/

瞬间Git就把仓库建好了,并且告诉你是一个空的仓库(empty Git repository),细心的读者能够发现当前目录下多了一个.git的目录,这个目录是Git来跟踪管理版本库的,没事千万不要手动修改这个目录里面的文件,否则改乱了,就把Git仓库给破坏了。

若是你没有看到.git目录,那是由于这个目录默认是隐藏的,用ls -ah命令就能够看见。

shuais-MBP:git_test dandyzhang$ ls -ah
.    ..    .git

 

把文件添加到版本库

首先这里再明确一下,全部的版本控制系统,其实只能跟踪文本文件的改动,好比TXT文件,网页,全部的程序代码等等,Git也不例外。版本控制系统能够告诉你每次的改动,好比在第5行加了一个单词“Linux”,在第8行删了一个单词“Windows”。而图片、视频这些二进制文件,虽然也能由版本控制系统管理,但无法跟踪文件的变化,只能把二进制文件每次改动串起来,也就是只知道图片从100KB改为了120KB,但到底改了啥,版本控制系统不知道,也无法知道。

不幸的是,Microsoft的Word格式是二进制格式,所以,版本控制系统是无法跟踪Word文件的改动的,前面咱们举的例子只是为了演示,若是要真正使用版本控制系统,就要以纯文本方式编写文件。

由于文本是有编码的,好比中文有经常使用的GBK编码,日文有Shift_JIS编码,若是没有历史遗留问题,强烈建议使用标准的UTF-8编码,全部语言使用同一种编码,既没有冲突,又被全部平台所支持。

言归正传,如今咱们编写一个first_git_file.txt文件,内容以下:

shuais-MBP:git_test dandyzhang$ vim first_git_file.txt

first time using git, hello git!

必定要放到git_trainning目录下(子目录也行),由于这是一个Git仓库,放到其余地方Git再厉害也找不到这个文件。

和把大象放到冰箱须要3步相比,把一个文件放到Git仓库只须要两步。

 

第一步,用命令git add告诉Git,把文件添加到仓库:

shuais-MBP:git_test dandyzhang$ git add first_git_file.txt

执行上面的命令,没有任何显示,说明添加成功。

这时候咱们再建立一个文件readme,不add到仓库

shuais-MBP:git_test dandyzhang$ vim Readme
this is readme file

此时使用status查看状态:

shuais-MBP:git_test dandyzhang$ git status
On branch master

No commits yet

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)

    new file:   first_git_file.txt

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    Readme

add后的文件first_git_file.txt被追踪了,而没有添加进git仓库的则不会追踪,空文件夹也不会显示。

第二步,用命令git commit告诉Git,把文件提交到仓库,即上文被追踪的文件已经被管理:

shuais-MBP:git_test dandyzhang$ git commit
hint: Waiting for your editor to close the file... 

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
#
# Committer: 衰 Zzz <dandyzhang@shuais-MBP.lan>
#
# On branch master
#
# Initial commit
#
# Changes to be committed:
#       new file:   first_git_file.txt
#
# Untracked files:
#       Readme
#
~                                                                               
~                                                                               
~                                                                               
~                                                                               
~                                                                               
~                                                                               
~                                                                               
"~/git_test/.git/COMMIT_EDITMSG" 16L, 321C

这里又进入到vim编辑模式,git在提示你写入文件新建或更改的理由,缘由或备注,加入备注在首行:

git first test...
# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
#
# Committer: 衰 Zzz <dandyzhang@shuais-MBP.lan>
#
# On branch master
#
# Initial commit
#
# Changes to be committed:
#       new file:   first_git_file.txt
#
# Untracked files:
#       Readme
#

保存:

shuais-MBP:git_test dandyzhang$ git commit
[master (root-commit) 8dfa740] git first test...
 Committer: 衰 Zzz <dandyzhang@shuais-MBP.lan>
Your name and email address were configured automatically based
on your username and hostname. Please check that they are accurate.
You can suppress this message by setting them explicitly. Run the
following command and follow the instructions in your editor to edit
your configuration file:

    git config --global --edit

After doing this, you may fix the identity used for this commit with:

    git commit --amend --reset-author

 1 file changed, 1 insertion(+)
 create mode 100644 first_git_file.txt

此时查看status:

shuais-MBP:git_test dandyzhang$ git status
On branch master
Untracked files:
  (use "git add <file>..." to include in what will be committed)

    Readme

nothing added to commit but untracked files present (use "git add" to track)

发现只有readme存在。

中间红色部分的意思是,你在往git库里提交代码时,你须要告诉git你是谁,这样git就会纪录下来是谁改的代码,其实就是为了往后查询方便,你只须要提供一个名字和邮件地址就能够,这里个人git直接经过主机名本身建立了一个,但你能够经过git config --global --edit修改

 

简单解释一下git commit命令,-m后面输入的是本次提交的说明,能够输入任意内容,固然最好是有意义的,这样你就能从历史记录里方便地找到改动记录。

嫌麻烦不想输入-m "xxx"行不行?确实有办法能够这么干,可是强烈不建议你这么干,由于输入说明对本身对别人阅读都很重要。

为何Git添加文件须要addcommit一共两步呢?由于commit能够一次提交不少文件,因此你能够屡次add不一样的文件,至关于修改了项目的多个地方的代码最后统一commit,好比:

$ git add file1.txt
$ git add file2.txt file3.txt
$ git commit -m "add 3 files."

 

代码回滚

一、代码修改并提交  

咱们已经成功地添加并提交了一个first_git_file.txt文件,如今,是时候继续工做了,因而,咱们继续修改first_git_file.txt文件,改为以下内容:

shuais-MBP:git_test dandyzhang$ vim first_git_file.txt

first time using git, hello git! update(one)
insert one line here....

如今,运行git status命令看看结果:

shuais-MBP:git_test dandyzhang$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   first_git_file.txt

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    Readme

no changes added to commit (use "git add" and/or "git commit -a")

虽然Git告诉咱们first_git_file.txt被修改了,但若是能看看具体修改了什么内容,天然是很好的。好比你休假两周从国外回来,第一天上班时,已经记不清上次怎么修改的readme.txt,因此,须要用git diff这个命令看看:

shuais-MBP:git_test dandyzhang$ git diff first_git_file.txt
diff --git a/first_git_file.txt b/first_git_file.txt
index 5f48045..7581c01 100644
--- a/first_git_file.txt
+++ b/first_git_file.txt
@@ -1 +1,2 @@
-first time using git, hello git!
+first time using git, hello git! update(one)
+insert one line here....

输出中+号绿色显示的就是修改或新增的内容,-号红色显示的就是去掉或被修改的内容

知道了对first_git_file.txt 做了什么修改后,再把它提交到仓库就放心多了,提交修改和提交新文件是同样的两步,第一步是git add:

shuais-MBP:git_test dandyzhang$ git add .  # 表明把当前目录下全部改动的文件都提交到代码库
shuais-MBP:git_test dandyzhang$ git commit -m 'commit changes 2'
[master f31af7b] commit changes 2
 Committer: 衰 Zzz <dandyzhang@shuais-MBP.lan>
Your name and email address were configured automatically based
on your username and hostname. Please check that they are accurate.
You can suppress this message by setting them explicitly. Run the
following command and follow the instructions in your editor to edit
your configuration file:

    git config --global --edit

After doing this, you may fix the identity used for this commit with:

    git commit --amend --reset-author

 2 files changed, 3 insertions(+), 1 deletion(-)
 create mode 100644 Readme
shuais-MBP:git_test dandyzhang$ 

若是上面的操做,add以后咱们插入一个status操做,会获得提示,一个文件被修改另外一个未被跟踪。

commit以后再查看status:

shuais-MBP:git_test dandyzhang$ git status
On branch master
nothing to commit, working tree clean
shuais-MBP:git_test dandyzhang$ 

这时本地文件状态就所有被清空了。Git告诉咱们当前没有须要提交的修改,并且,工做目录是干净(working directory clean)的。

此时,再修改下readme:

shuais-MBP:git_test dandyzhang$ vim Readme 

this is readme file
insert one line...second times.

shuais-MBP:git_test dandyzhang$ git add .
shuais-MBP:git_test dandyzhang$ git commit -m 'second time modified readme.'
[master f557e4f] second time modified readme.
 Committer: 衰 Zzz <dandyzhang@shuais-MBP.lan>
Your name and email address were configured automatically based
on your username and hostname. Please check that they are accurate.
You can suppress this message by setting them explicitly. Run the
following command and follow the instructions in your editor to edit
your configuration file:

    git config --global --edit

After doing this, you may fix the identity used for this commit with:

    git commit --amend --reset-author

 1 file changed, 1 insertion(+)

 

代码回滚  

上面已经又修改过文件了,有兴趣的话能够多测试几回

像这样,你不断对文件进行修改,而后不断提交修改到版本库里,就比如玩RPG游戏时,每经过一关就会自动把游戏状态存盘,若是某一关没过去,你还能够选择读取前一关的状态。有些时候,在打Boss以前,你会手动存盘,以便万一打Boss失败了,能够从最近的地方从新开始。Git也是同样,每当你以为文件修改到必定程度的时候,就能够“保存一个快照”,这个快照在Git中被称为commit。一旦你把文件改乱了,或者误删了文件,还能够从最近的一个commit恢复,而后继续工做,而不是把几个月的工做成果所有丢失。

如今,测试过几回以后,你们应该也不会很清晰的记得文件的修改状况和版本明细了。而且在实际工做中,咱们脑子里怎么也不可能记得一个几千行的文件每次都改了什么内容,否则要版本控制系统干什么。版本控制系统确定有某个命令能够告诉咱们历史记录,在Git中,咱们用git log命令查看:

shuais-MBP:git_test dandyzhang$ git log
commit f557e4fcd45978b358f21b75e87cfe2f80f381b7 (HEAD -> master)
Author: 衰 Zzz <dandyzhang@shuais-MBP.lan>
Date:   Wed Jul 4 22:59:02 2018 +0800

    second time modified readme.

commit f31af7bf79a2b0114eb9d1adcac82b4fa7128a2b
Author: 衰 Zzz <dandyzhang@shuais-MBP.lan>
Date:   Wed Jul 4 22:50:20 2018 +0800

    commit changes 2

commit 8dfa74052ee22ef3f86b51424172df60c23778c6
Author: 衰 Zzz <dandyzhang@shuais-MBP.lan>
Date:   Wed Jul 4 22:27:56 2018 +0800

    git first test...

git log命令显示从最近到最远的提交日志,能够看到日志一共记录了,第一次测试跟两次修改;若是嫌输出信息太多,看得眼花缭乱的,能够试试加上--pretty=oneline参数:

shuais-MBP:git_test dandyzhang$ git log --pretty=oneline
f557e4fcd45978b358f21b75e87cfe2f80f381b7 (HEAD -> master) second time modified readme.
f31af7bf79a2b0114eb9d1adcac82b4fa7128a2b commit changes 2
8dfa74052ee22ef3f86b51424172df60c23778c6 git first test...

须要友情提示的是,你看到的一大串相似3628164...882e1e0的是commit id(版本号),和SVN不同,Git的commit id不是1,2,3……递增的数字,而是一个SHA1计算出来的一个很是大的数字,用十六进制表示,并且你看到的commit id和个人确定不同,以你本身的为准。为何commit id须要用这么一大串数字表示呢?由于Git是分布式的版本控制系统,后面咱们还要研究多人在同一个版本库里工做,若是你们都用1,2,3……做为版本号,那确定就冲突了。

 

回滚!!!

好了,如今咱们启动时光穿梭机,准备把readme回退到上一个版本,即‘commit changes 2’版本,怎么作呢?

首先,Git必须知道当前版本是哪一个版本,在Git中,用HEAD表示当前版本,也就是最新的提交f557e4fcd45978b358f21b75e87cfe2f80f381b7(注意个人提交ID和你的确定不同),上一个版本就是HEAD^,上上一个版本就是HEAD^^,固然往上100个版本写100个^比较容易数不过来,因此写成HEAD~100

小插曲:

写的太忘我,忘记添加global user.mail&user.name参数。目前,以个人测试,若是不设置话,文件是不会回滚的。

为何设置?
很大程度上,一方面日志里记录了,更新的用户的名字邮箱,若是遇到问题或者不理解的地方,能够及时联系开发者。

因此,别激动,先添加参数,添加好再修改一次文件:

shuais-MBP:git_test dandyzhang$ git config --global user.email 'wuzdandz@163.com'
shuais-MBP:git_test dandyzhang$ git config --global user.name 'dandy zhang'


shuais-MBP:git_test dandyzhang$ vim Readme # 这里就再也不费劲记录了,随便加点东西就行了。

shuais-MBP:git_test dandyzhang$ git add .
shuais-MBP:git_test dandyzhang$ git commit  # 忘记加备注了。。。。
[master b958914] update readme third times  
 1 file changed, 1 insertion(+)

这时候查看日志:

 

如今,咱们要把当前版本“update readme third times”回退到上一个版本“second time modified readme.”,就能够使用git reset命令:

shuais-MBP:git_test dandyzhang$ git reset --hard HEAD^
HEAD is now at f557e4f second time modified readme.

shuais-MBP:git_test dandyzhang$ vim Readme 

this is readme file
insert one line...second times.   

完美!

这时候,也许你会从新查看log:

shuais-MBP:git_test dandyzhang$ git log
commit f557e4fcd45978b358f21b75e87cfe2f80f381b7 (HEAD -> master)
Author: 衰 Zzz <dandyzhang@shuais-MBP.lan>
Date:   Wed Jul 4 22:59:02 2018 +0800

    second time modified readme.

commit f31af7bf79a2b0114eb9d1adcac82b4fa7128a2b
Author: 衰 Zzz <dandyzhang@shuais-MBP.lan>
Date:   Wed Jul 4 22:50:20 2018 +0800

    commit changes 2

commit 8dfa74052ee22ef3f86b51424172df60c23778c6
Author: 衰 Zzz <dandyzhang@shuais-MBP.lan>
Date:   Wed Jul 4 22:27:56 2018 +0800

    git first test...

发现最新的一版已经不见了。假如是真的要回滚到对应的版本却是还好,但是,若是是没注意选错了,就没办法更改了么?

办法其实仍是有的,只要上面的命令行窗口尚未被关掉,你就能够顺着往上找啊找啊,找到那个add new content的commit id是b9589146dd0eeb4f6b6eb5347e7cb373a1c55533,因而就能够指定回到将来的某个版本:

shuais-MBP:git_test dandyzhang$ git reset --hard b95891
HEAD is now at b958914 update readme third times

版本号不必写全,前几位就能够了,Git会自动去找。固然也不能只写前一两位,由于Git可能会找到多个版本号,就没法肯定是哪个了。

这时候再,当心翼翼!!的查看一下readme的内容:

shuais-MBP:git_test dandyzhang$ vim Readme 

this is readme file
insert one line...second times.
insert one line...third time.

发现版本真的改回来了。

Git的版本回退速度很是快,由于Git在内部有个指向当前版本的HEAD指针,当你回退版本的时候,Git仅仅是把HEAD从指向update readme third times

如今,你总算是能够回退到了某个版本,开心的一毛,关掉了电脑,次日早上就后悔了,想恢复到新版本怎么办?找不到新版本的commit id怎么办?

在Git中,老是有后悔药能够吃的。当你用$ git reset --hard HEAD^回退到update again版本时,再想恢复到最新add new content的版本,就必须找到add new contentL的commit id。Git提供了一个命令git reflog用来记录你的每一次命令:

shuais-MBP:git_test dandyzhang$ git reflog
b958914 (HEAD -> master) HEAD@{0}: reset: moving to b95891
f557e4f HEAD@{1}: reset: moving to HEAD^
b958914 (HEAD -> master) HEAD@{2}: commit: update readme third times
f557e4f HEAD@{3}: commit: second time modified readme.
f31af7b HEAD@{4}: commit: commit changes 2
8dfa740 HEAD@{5}: commit (initial): git first test...

这里,就不演示再回滚而后拿最前面的ID,再复原的过程了。记得reflog这个命令的做用便可,git的回滚的意义,在于将指针指向你所须要回到的某一个版本,但并不会删掉其余的版本。

 

也许你还会问这样一个问题,若是回滚代码到过去,再在过去的代码里修改了一些东西,commit以后,后面的版本还存在么?

就像链表同样,链子断开把新的加了进入?仍是至关于时光机通常,我回到过去,修改或杀死了小时候的我,将来的我还在么?

其实这里须要解释一下git的版本存储机制:

如图,若是回到二的版本阶段,修改了代码,git会从新定义一个版本。说的恐怖一点,这有点相似于你创造了一个平行宇宙。。

 

 

工做区和暂存区

Git和其余版本控制系统如SVN的一个不一样之处就是有暂存区的概念。

先来看名词解释。

工做区(Working Directory

就是你在电脑里能看到的目录,好比个人git_test文件夹就是一个工做区:

shuais-MacBook-Pro:~ dandyzhang$ cd git_test/
shuais-MacBook-Pro:git_test dandyzhang$ ls
Readme            first_git_file.txt

版本库(Repository)

工做区有一个隐藏目录.git,这个不算工做区,而是Git的版本库。

Git的版本库里存了不少东西,其中最重要的就是称为stage(或者叫index)的暂存区,还有Git为咱们自动建立的第一个分支master,以及指向master的一个指针叫HEAD

分支和HEAD的概念咱们之后再讲。

前面讲了咱们把文件往Git版本库里添加的时候,是分两步执行的:

第一步是用git add把文件添加进去,实际上就是把文件修改添加到暂存区;

第二步是用git commit提交更改,实际上就是把暂存区的全部内容提交到当前分支。

由于咱们建立Git版本库时,Git自动为咱们建立了惟一一个master分支,因此,如今,git commit就是往master分支上提交更改。

你能够简单理解为,须要提交的文件修改统统放到暂存区,而后,一次性提交暂存区的全部修改。

 

以前,咱们先建立了一个git_first_file.txt并add&commit,而后进行了修改并add&commit,最后又建了一个新readme并add&commit。

当在工做区添加了一个readme文件,没有加入stage的时候。status查看的时候,很明显git在提示readme是untracked files

此时再将readme add到git的stage,status转成了new file。

如今,暂存区的状态就变成这样了:

备注一下:盗的图,这里readme.txt = first_git_file.txt , LICENSE = readme.md

因此,git add命令实际上就是把要提交的全部修改放到暂存区(Stage),而后,执行git commit就能够一次性把暂存区的全部修改提交到分支。

有点至关于,用鼠标选中了这么多文件,进行commit。

一旦提交后,若是你又没有对工做区作任何修改,那么工做区就是“干净”的:

$ git status
On branch master
nothing to commit, working directory clean

如今版本库变成了这样,暂存区就没有任何内容了:

(备注一下,盗的图, 这里readme.txt = first_git_file.txt , LICENSE = readme.md)

 暂存区是Git很是重要的概念,弄明白了暂存区,就弄明白了Git的不少操做到底干了什么。

 

 

撤销修改

某天,你在作某个boss的很奇怪的需求,各类奇葩,火大的很,直接在readme最后写了句:

shuais-MacBook-Pro:git_test dandyzhang$ vim Readme 
this is readme file
insert one line...second times.
insert one line...third time.
fuck IT Director.

在你准备提交前,一杯咖啡起了做用,你猛然发现了有点上头,“fuck IT Director .”可能会让你丢掉绩效奖金

既然错误发现得很及时,就能够很容易地纠正它。你删除了这句话,手动把文件恢复到上一个版本的状态。若是用git status查看一下:

shuais-MacBook-Pro:git_test dandyzhang$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   Readme

no changes added to commit (use "git add" and/or "git commit -a")

你能够发现,Git会告诉你,git checkout -- file能够丢弃工做区的修改:

shuais-MacBook-Pro:git_test dandyzhang$ git checkout -- Readme 
shuais-MacBook-Pro:git_test dandyzhang$ vim Readme 



this is readme file
insert one line...second times.
insert one line...third time.

你刚才添加的 一行骂老板的话就被撤销了,

命令git checkout -- readme.md意思就是,把readme.md文件在工做区的修改所有撤销,这里有两种状况:

一种是readme.md自修改后尚未被放到暂存区,如今,撤销修改就回到和版本库如出一辙的状态;

一种是readme.md已经添加到暂存区后,又做了修改,如今,撤销修改就回到添加到暂存区后的状态。

总之,就是让这个文件回到最近一次git commitgit add时的状态。

 

git checkout -- file命令中的--很重要,没有--,就变成了“切换到另外一个分支”的命令,咱们在后面的分支管理中会再次遇到git checkout命令。  

如今假定是凌晨3点,你不但写了一些胡话,还git add到暂存区了:

shuais-MacBook-Pro:git_test dandyzhang$ vim Readme 
this is readme file
insert one line...second times.
insert one line...third time.
Fuck manager's requirement.
So stupid.

shuais-MacBook-Pro:git_test dandyzhang$ git add Readme 

庆幸的是,在commit以前,你发现了这个问题。用git status查看一下,修改只是添加到了暂存区,尚未提交: 

shuais-MacBook-Pro:git_test dandyzhang$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    modified:   Readme

Git一样告诉咱们,用命令git reset HEAD file能够把暂存区的修改撤销掉(unstage),从新放回工做区:

shuais-MacBook-Pro:git_test dandyzhang$ git reset HEAD Readme 
Unstaged changes after reset:
M    Readme

git reset命令既能够回退版本,也能够把暂存区的修改回退到工做区。当咱们用HEAD时,表示最新的版本。

再用git status查看一下,如今暂存区是干净的,工做区有修改。

shuais-MacBook-Pro:git_test dandyzhang$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   Readme

no changes added to commit (use "git add" and/or "git commit -a")

还记得如何丢弃工做区的修改吗?

shuais-MacBook-Pro:git_test dandyzhang$ git checkout -- Readme 
shuais-MacBook-Pro:git_test dandyzhang$ git status
On branch master
nothing to commit, working tree clean

哈哈,这个世界终于清静了!!

记得千万别commit!!!commit完就已经被git进行版本控制了,再怎么删除也会有记录。除非删除代码库。

em....... 这是个不错的想法。可能你须要收拾下行李,找下一家了。

 

删除操做

在Git中,删除也是一个修改操做,咱们实战一下,先添加一个新文件test.txt到Git而且提交:

shuais-MacBook-Pro:git_test dandyzhang$ vim test.txt

this is a test file.

shuais-MacBook-Pro:git_test dandyzhang$ git add .
shuais-MacBook-Pro:git_test dandyzhang$ git commit -m 'add a new test.txt file'
[master f6afa4f] add a new test.txt file
 1 file changed, 1 insertion(+)
 create mode 100644 test.txt

通常状况下,你一般直接在文件管理器中把没用的文件删了,或者用rm命令删了:

shuais-MacBook-Pro:git_test dandyzhang$ rm test.txt

这个时候,Git知道你删除了文件,所以,工做区和版本库就不一致了,git status命令会马上告诉你哪些文件被删除了:

shuais-MacBook-Pro:git_test dandyzhang$ git status
On branch master
Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    deleted:    test.txt

no changes added to commit (use "git add" and/or "git commit -a")

如今你有两个选择,一是确实要从版本库中删除该文件,那就用命令git rm删掉,而且git commit

shuais-MacBook-Pro:git_test dandyzhang$ git rm test.txt
rm 'test.txt'

shuais-MacBook-Pro:git_test dandyzhang$ git commit -m 'delete test.txt file'
[master b172a52] delete test.txt file
 1 file changed, 1 deletion(-)
 delete mode 100644 test.txt

如今,文件就从版本库中被删除了。

另外一种状况是删错了,由于版本库里还有呢,因此能够很轻松地把误删的文件恢复到最新版本:

shuais-MacBook-Pro:git_test dandyzhang$ git checkout -- test.txt

git checkout实际上是用版本库里的版本替换工做区的版本,不管工做区是修改仍是删除,均可以“一键还原”。

 

远程仓库

到目前为止,咱们已经掌握了如何在Git仓库里对一个文件进行时光穿梭,你不再用担忧文件备份或者丢失的问题了。

但是有用过集中式版本控制系统SVN的童鞋会站出来讲,这些功能在SVN里早就有了,没看出Git有什么特别的地方。

没错,若是只是在一个仓库里管理文件历史,Git和SVN真没啥区别。为了保证你如今所学的Git物超所值,未来绝对不会后悔,同时为了打击已经不幸学了SVN的童鞋,本章开始介绍Git的杀手级功能之一(注意是之一,也就是后面还有之二,之三……):远程仓库。

Git是分布式版本控制系统,同一个Git仓库,能够分布到不一样的机器上。怎么分布呢?最先,确定只有一台机器有一个原始版本库,此后,别的机器能够“克隆”这个原始版本库,并且每台机器的版本库其实都是同样的,并无主次之分。

你确定会想,至少须要两台机器才能玩远程库不是?可是我只有一台电脑,怎么玩?

其实一台电脑上也是能够克隆多个版本库的,只要不在同一个目录下。不过,现实生活中是不会有人这么傻的在一台电脑上搞几个远程库玩,由于一台电脑上搞几个远程库彻底没有意义,并且硬盘挂了会致使全部库都挂掉,因此我也不告诉你在一台电脑上怎么克隆多个仓库。

实际状况每每是这样,找一台电脑充当服务器的角色,天天24小时开机,其余每一个人都从这个“服务器”仓库克隆一份到本身的电脑上,而且各自把各自的提交推送到服务器仓库里,也从服务器仓库中拉取别人的提交。

彻底能够本身搭建一台运行Git的服务器,不过现阶段,为了学Git先搭个服务器绝对是小题大做。好在这个世界上有个叫GitHub的神奇的网站,从名字就能够看出,这个网站就是提供Git仓库托管服务的,因此,只要注册一个GitHub帐号,就能够免费得到Git远程仓库。

在继续阅读后续内容前,请自行注册GitHub帐号。因为你的本地Git仓库和GitHub仓库之间的传输是经过SSH加密的,因此,须要一点设置:

第1步:建立SSH Key。在用户主目录下,看看有没有.ssh目录,若是有,再看看这个目录下有没有id_rsaid_rsa.pub这两个文件,若是已经有了,可直接跳到下一步。若是没有,打开Shell(Windows下打开Git Bash),建立SSH Key:

shuais-MacBook-Pro:~ dandyzhang$ ssh-keygen -t rsa -C 'wuzdandz@163.com'

你须要把邮件地址换成你本身的邮件地址,而后一路回车,使用默认值便可,因为这个Key也不是用于什么机密,因此也无需设置密码。

若是一切顺利的话,能够在用户主目录里找到.ssh目录,里面有id_rsaid_rsa.pub两个文件,这两个就是SSH Key的秘钥对,id_rsa是私钥,不能泄露出去,id_rsa.pub是公钥,能够放心地告诉任何人。

Generating public/private rsa key pair.
Enter file in which to save the key (/Users/dandyzhang/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /Users/dandyzhang/.ssh/id_rsa.
Your public key has been saved in /Users/dandyzhang/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:sNFwTTqMGfE4VInYHtawiA3RVKta8su/zEONeJfvDe4 wuzdandz@163.com
The key's randomart image is:
+---[RSA 2048]----+
|  o+.+B*o+.      |
|   +oo=&o..      |
|  . ooX.*        |
|     ..= .       |
|  . o..oS.       |
|   =. + +        |
|  . .o . ..      |
|   . +.  ..o     |
|    o.=o oE .    |
+----[SHA256]-----+

第2步:登录GitHub,打开“Account settings”,“SSH Keys”页面:

而后,点“Add SSH Key”,填上任意Title,在Key文本框里粘贴id_rsa.pub文件的内容:

shuais-MacBook-Pro:~ dandyzhang$ ls -ah
.            .gitconfig        Library
..            .idlerc            Movies
.CFUserTextEncoding    .python_history        Music
.DS_Store        .ssh            Pictures
.Trash            .viminfo        Public
.bash_history        .wns            PycharmProjects
.bash_profile        Applications        git_test
.bash_profile.pysave    Desktop            venv
.bash_sessions        Documents
.downloader        Downloads
shuais-MacBook-Pro:~ dandyzhang$ cd .ssh
shuais-MacBook-Pro:.ssh dandyzhang$ ls
id_rsa        id_rsa.pub    known_hosts
shuais-MacBook-Pro:.ssh dandyzhang$ vim id_rsa.pub 

点“Add Key”,你就应该看到已经添加的Key

为何GitHub须要SSH Key呢?由于GitHub须要识别出你推送的提交确实是你推送的,而不是别人冒充的,而Git支持SSH协议,因此,GitHub只要知道了你的公钥,就能够确认只有你本身才能推送。

固然,GitHub容许你添加多个Key。假定你有若干电脑,你一下子在公司提交,一下子在家里提交,只要把每台电脑的Key都添加到GitHub,就能够在每台电脑上往GitHub推送了。

最后友情提示,在GitHub上免费托管的Git仓库,任何人均可以看到喔(但只有你本身才能改)。因此,不要把敏感信息放进去。

若是你不想让别人看到Git库,有两个办法,一个是交点保护费,让GitHub把公开的仓库变成私有的,这样别人就看不见了(不可读更不可写)。另外一个办法是本身动手,搭一个Git服务器,由于是你本身的Git服务器,因此别人也是看不见的。这个方法咱们后面会讲到的,至关简单,公司内部开发必备。

确保你拥有一个GitHub帐号后,咱们就即将开始远程仓库的学习。

 

建立远程仓库 

如今的情景是,你已经在本地建立了一个Git仓库后,又想在GitHub建立一个Git仓库,而且让这两个仓库进行远程同步,这样,GitHub上的仓库既能够做为备份,又可让其余人经过该仓库来协做,真是一举多得。

首先,登录GitHub,而后,点击start a project:

 

蓝色的箭头表明我的的私密项目,须要付费的。

建立好的仓库:

红色框1:经过命令行在本地建立一个repo(代码仓库),并推到这个刚建立的远程仓库上来

红色框2:把已经写好代码的本地仓库推到远程来。

红色框3:从其余的代码仓库导入

蓝色框是用来选择连接方式。这里咱们能够选择ssh,由于已经创建了公钥的认证。

目前,在GitHub上的这个Test1仓库仍是空的,GitHub告诉咱们,能够从这个仓库克隆出新的仓库,也能够把一个已有的本地仓库与之关联,而后,把本地仓库的内容推送到GitHub仓库。

如今,咱们根据GitHub的提示,在本地已有的git_trainning仓库下运行命令:

shuais-MacBook-Pro:.ssh dandyzhang$ cd ..
shuais-MacBook-Pro:~ dandyzhang$ cd git_test
shuais-MacBook-Pro:git_test dandyzhang$ ls -af
.            first_git_file.txt    .git
..            Readme
shuais-MacBook-Pro:git_test dandyzhang$ git remote add origin https://github.com/dandy-weeknd/Test1.git
shuais-MacBook-Pro:git_test dandyzhang$ git push -u origin master
fatal: unable to access 'https://github.com/dandy-weeknd/Test1.git/': Could not resolve host: github.com
shuais-MacBook-Pro:git_test dandyzhang$ git push -u origin master
Username for 'https://github.com': wuzdandz@163.com
Password for 'https://wuzdandz@163.com@github.com': 
Enumerating objects: 17, done.
Counting objects: 100% (17/17), done.
Delta compression using up to 4 threads.
Compressing objects: 100% (13/13), done.
Writing objects: 100% (17/17), 1.51 KiB | 775.00 KiB/s, done.
Total 17 (delta 3), reused 0 (delta 0)
remote: Resolving deltas: 100% (3/3), done.
To https://github.com/dandy-weeknd/Test1.git
 * [new branch]      master -> master
Branch 'master' set up to track remote branch 'master' from 'origin'.

这里先选用的是HTTPS的方式来提交代码仓库源代码;此时刷新页面;

从如今起,只本地作了提交,就能够经过命令:

git push origin master

直接提交到远程源代码仓库:

shuais-MacBook-Pro:git_test dandyzhang$ vim index.html

<html>
<head></head>
<body>
github first index html !
</body>
</html>

shuais-MacBook-Pro:git_test dandyzhang$ git add .
shuais-MacBook-Pro:git_test dandyzhang$ git commit
[master 325453e] github first text file !
 1 file changed, 6 insertions(+)
 create mode 100644 index.html
shuais-MacBook-Pro:git_test dandyzhang$ 


shuais-MacBook-Pro:git_test dandyzhang$ git push origin master
Enumerating objects: 4, done.
Counting objects: 100% (4/4), done.
Delta compression using up to 4 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 382 bytes | 382.00 KiB/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To https://github.com/dandy-weeknd/Test1.git
   b172a52..325453e  master -> master 

刷新一下远程仓库:

能够看到文件已经更新过来,而且上面有个7commits。点进去看一下:

从远程库克隆

咱们讲了先有本地库,后有远程库的时候,如何关联远程库。

如今,假设咱们从零开发,那么最好的方式是先建立远程库,而后,从远程库克隆。

首先,登录GitHub,建立一个新的仓库,名字叫Test2_From_Github:

咱们勾选Initialize this repository with a README,这样GitHub会自动为咱们建立一个README.md文件。建立完毕后,能够看到README.md文件:

 

如今,远程库已经准备好了,下一步是用命令git clone克隆一个本地库:

在本地找一个你想存放这个远程仓库的目录,而后在本地命令行用git clone 命令来克隆这个远程库:

shuais-MacBook-Pro:~ dandyzhang$ mkdir git_test2
shuais-MacBook-Pro:~ dandyzhang$ cd git_test2

shuais-MacBook-Pro:git_test2 dandyzhang$ git clone https://github.com/dandy-weeknd/Test2_From_Github.git
Cloning into 'Test2_From_Github'...
remote: Counting objects: 3, done.
remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (3/3), done.


shuais-MacBook-Pro:git_test2 dandyzhang$ ls
Test2_From_Github
shuais-MacBook-Pro:git_test2 dandyzhang$ ls -af
.            ..            Test2_From_Github
shuais-MacBook-Pro:git_test2 dandyzhang$ cd Test2_From_Github/
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ ls -af
.        ..        README.md    .git

若是有多我的协做开发,那么每一个人各自从远程克隆一份就能够了。

你也许还注意到,GitHub给出的地址不止一个,还能够用https://github.com/triaquae/gitskills.git 这样的地址。实际上,Git支持多种协议,默认的git://使用ssh,但也能够使用https等其余协议。

使用https除了速度慢之外,还有个最大的麻烦是每次推送都必须输入口令,可是在某些只开放http端口的公司内部就没法使用ssh协议而只能用https

 

一些小操做

好比,你看到别人的项目代码写的很好,本身又有新的想法,就能够点击fork复制到本身的代码仓库。而后拉取到本地进行更改。

上面咱们提到了如何配置ssh,配置好ssh,如何经过ssh链接提交代码到远程代码库呢?

进入到本地代码库,修改隐藏文件夹.ssh下的config文件,把以前提到的蓝框点到ssh,复制链接。

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ vim README.md 

# Test2_From_Github
using ssh to test

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ vim .git/config  # 编辑可配置文件,修改提交方式从https到ssh link

[core]
        repositoryformatversion = 0
        filemode = true
        bare = false
        logallrefupdates = true
        ignorecase = true
        precomposeunicode = true
[remote "origin"]
        url = git@github.com:dandy-weeknd/Test2_From_Github.git
        fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
        remote = origin
        merge = refs/heads/master


shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git add .
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git commit
[master e5cc600] using ssh in readme.md
 1 file changed, 2 insertions(+), 1 deletion(-)
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git push origin master  # 提交到远程代码库
The authenticity of host 'github.com (52.74.223.119)' can't be established.
RSA key fingerprint is SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8.
Are you sure you want to continue connecting (yes/no)? y
Please type 'yes' or 'no': yes
Warning: Permanently added 'github.com,52.74.223.119' (RSA) to the list of known hosts.

Enumerating objects: 5, done.
Counting objects: 100% (5/5), done.
Writing objects: 100% (3/3), 287 bytes | 287.00 KiB/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To github.com:dandy-weeknd/Test2_From_Github.git
   cf545df..e5cc600  master -> master

已经上传完成,检查一下。

测试一下协做开发代码合并的问题

既然是协同开发就须要先有个协同者下载代码,这里起一台虚拟机模拟下:

dandy@ubuntu01:~$ git clone https://github.com/dandy-weeknd/Test2_From_Github.git
Cloning into 'Test2_From_Github'...
remote: Counting objects: 6, done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 6 (delta 0), reused 3 (delta 0), pack-reused 0
Unpacking objects: 100% (6/6), done.
Checking connectivity... done.
dandy@ubuntu01:~$ ls
Test2_From_Github

这时候,对源代码进行修改,协做开发。

dandy@ubuntu01:~/Test2_From_Github$ vim main.py  # 建立一个新文件

def sayhi(name):
    print('Hi,', name)


dandy@ubuntu01:~/Test2_From_Github$ vim README.md 

# Test2_From_Github
using ssh[ubuntu insert here] to test

this line changed from ubuntu server.

修改完进行提交:

git add .
dandy@ubuntu01:~/Test2_From_Github$ git commit -m 'changed from ubuntu server.'

*** Please tell me who you are.

Run

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

to set your account's default identity.
Omit --global to set the identity only in this repository.

fatal: unable to auto-detect email address (got 'dandy@ubuntu01.(none)')
dandy@ubuntu01:~/Test2_From_Github$ git config --global user.email "dandy@ubuntu.com"
dandy@ubuntu01:~/Test2_From_Github$ git config --global user.name "dandy.ubuntu"
dandy@ubuntu01:~/Test2_From_Github$ git commit -m 'changed from ubuntu server.'
[master de354d3] changed from ubuntu server.
 2 files changed, 5 insertions(+), 1 deletion(-)
 create mode 100644 main.py
dandy@ubuntu01:~/Test2_From_Github$ git push origin master  # 由于须要帐号密码,嫌麻烦,就再创建一个ssh
Username for 'https://github.com': 
Password for 'https://github.com': 
remote: Anonymous access to dandy-weeknd/Test2_From_Github.git denied.
fatal: Authentication failed for 'https://github.com/dandy-weeknd/Test2_From_Github.git/'
dandy@ubuntu01:~/Test2_From_Github$ vim .git/config  # 修改为ssh链接
dandy@ubuntu01:~/Test2_From_Github$ ls ~/
Test2_From_Github
dandy@ubuntu01:~/Test2_From_Github$ ls ~/.ssh
ls: cannot access '/home/dandy/.ssh': No such file or directory
dandy@ubuntu01:~/Test2_From_Github$ sudo ls ~/.ssh
[sudo] password for dandy: 
ls: cannot access '/home/dandy/.ssh': No such file or directory
dandy@ubuntu01:~/Test2_From_Github$ ssh-keygen -t rsa -C "dandy@ubuntu.com"  # 创建秘钥
Generating public/private rsa key pair.
Enter file in which to save the key (/home/dandy/.ssh/id_rsa): 
Created directory '/home/dandy/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/dandy/.ssh/id_rsa.
Your public key has been saved in /home/dandy/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:4VzEuYG59R9y/CkHR9eNu+yMLV9Cl4tcBMRzR76MdrE dandy@ubuntu.com
The key's randomart image is:
+---[RSA 2048]----+
|         +..oo o+|
|        o.=  oo+=|
|        .o.+ .+++|
|       o.o. o.O.=|
|        S    B+Eo|
|            ooB+o|
|             B+..|
|            o +o |
|             o.  |
+----[SHA256]-----+
dandy@ubuntu01:~/Test2_From_Github$ cd ~/.ssh
dandy@ubuntu01:~/.ssh$ ls
id_rsa  id_rsa.pub
dandy@ubuntu01:~/.ssh$ cd ..
dandy@ubuntu01:~$ vim ~/.ssh/config
dandy@ubuntu01:~$ vim ~/.ssh/id_rsa.pub  # copy公钥

 复制出来,注意这一次,不能再像以前那样粘贴在your profile的settings里面了,从做者自己的角度来说,加入公钥,是为了之后经过电脑上传任何代码到远程代码库都没必要输入帐号密码,可是做为一个协同者,显然是不能给它这样的权限。因此应该添加到项目代码仓库的settings中;如图中的deploy keys

如今咱们从新提交一次虚拟机本地代码库到远程github源代码库

dandy@ubuntu01:~$ ls
Test2_From_Github
dandy@ubuntu01:~$ cd Test2_From_Github/
dandy@ubuntu01:~/Test2_From_Github$ git push origin master
The authenticity of host 'github.com (52.74.223.119)' can't be established.
RSA key fingerprint is SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'github.com,52.74.223.119' (RSA) to the list of known hosts.
Counting objects: 4, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (4/4), 407 bytes | 0 bytes/s, done.
Total 4 (delta 0), reused 0 (delta 0)
To git@github.com:dandy-weeknd/Test2_From_Github.git
   e5cc600..de354d3  master -> master

效果图:

这时,假定作为开发者中的另外一个原做者,不知道远程代码库代码已经更新, 仍是在本地修改clone的代码:

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ vim README.md   # 修改了readme

# Test2_From_Github
using ssh to test

I am also editing this project, but i forget to check it from github whether it
is the newest or not?

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ vim setting.py  # 新建了一个文件

import os
Base_dir = os.path.join(__file__)

而后提交到github上:

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git add .
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git commit -m 'i am editing this project in macbook pro'
[master 084fd50] i am editing this project in macbook pro
 2 files changed, 5 insertions(+)
 create mode 100644 setting.py

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git push origin master  # 提交到github上
To github.com:dandy-weeknd/Test2_From_Github.git
 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'git@github.com:dandy-weeknd/Test2_From_Github.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

能够发现,这一次的代码提交被拒绝了,github已经提示:远程包含的工做文件本地不存在,这一般因为另外一个代码仓库提交致使,在你提交到github前,须要整合,合并代码。

这里再引入一个新的git命令:

git pull

用来将远程新的代码下载下来,可是有可能把本地修改过的文件覆盖掉。先试一下:

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git pull
Warning: Permanently added the RSA host key for IP address '13.229.188.59' to the list of known hosts.
remote: Counting objects: 4, done.
remote: Compressing objects: 100% (3/3), done.
remote: Total 4 (delta 0), reused 4 (delta 0), pack-reused 0
Unpacking objects: 100% (4/4), done.
From github.com:dandy-weeknd/Test2_From_Github
   e5cc600..de354d3  master     -> origin/master
Auto-merging README.md
CONFLICT (content): Merge conflict in README.md
Automatic merge failed; fix conflicts and then commit the result.

解释一下上面这段话:开始是计数、压缩、巴拉巴拉。。而后发现有异常就自动合并代码,发现有矛盾问题在readme中,自动合并失败,须要本身解决矛盾并从新提交结果代码。

查看下readme:

head指向的是本地的文件修改状况、=======分隔符后面github上被修改过的代码,最后>>>>>>>后面的应该是双方都有的代码区。仔细一想,代码确定是上面的是新的,因此保留下面的代码对其余协做本地git代码库不会产生影响(只须要pull),因此咱们修改一下这个readme文件

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ vim README.md 

# Test2_From_Github
using ssh to test

I am also editing this project, but i forget to check it from github whether it is the newest or not?

using ssh[ubuntu insert here] to test

this line changed from ubuntu server.

从新再提交一次:

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git add .
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git commit -m 'fix two different version code'
[master 775460f] fix two different version code
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git push origin master
Enumerating objects: 11, done.
Counting objects: 100% (11/11), done.
Delta compression using up to 4 threads.
Compressing objects: 100% (6/6), done.
Writing objects: 100% (7/7), 820 bytes | 410.00 KiB/s, done.
Total 7 (delta 1), reused 0 (delta 0)
remote: Resolving deltas: 100% (1/1), done.
To github.com:dandy-weeknd/Test2_From_Github.git
   de354d3..775460f  master -> master

完美解决。

这里诠释的只是git对于版本矛盾的自主解决方案演示,可是在真正的生产环境下,显然不可能会是这样处理的。这方面的问题,以后再作探讨!

 

 

 

分支管理

 

分支就是科幻电影里面的平行宇宙,当你正在电脑前努力学习Git的时候,另外一个你正在另外一个平行宇宙里努力学习SVN。

若是两个平行宇宙互不干扰,那对如今的你也没啥影响。不过,在某个时间点,两个平行宇宙合并了,结果,你既学会了Git又学会了SVN!

分支在实际中有什么用呢?假设你准备开发一个新功能,可是须要两周才能完成,第一周你写了50%的代码,若是马上提交,因为代码还没写完,不完整的代码库会致使别人不能干活了。若是等代码所有写完再一次提交,又存在丢失天天进度的巨大风险。

如今有了分支,就不用怕了。你建立了一个属于你本身的分支,别人看不到,还继续在原来的分支上正常工做,而你在本身的分支上干活,想提交就提交,直到开发完毕后,再一次性合并到原来的分支上,这样,既安全,又不影响别人工做。

其余版本控制系统如SVN等都有分支管理,可是用过以后你会发现,这些版本控制系统建立和切换分支比蜗牛还慢,简直让人没法忍受,结果分支功能成了摆设,你们都不去用。

但Git的分支是不同凡响的,不管建立、切换和删除分支,Git在1秒钟以内就能完成!不管你的版本库是1个文件仍是1万个文件。

 

 

一、建立与合并分支 

在学习版本回退部分时,你已经知道,每次提交,Git都把它们串成一条时间线,这条时间线就是一个分支。截止到目前,只有一条时间线,在Git里,这个分支叫主分支,即master分支。HEAD严格来讲不是指向提交,而是指向mastermaster才是指向提交的,因此,HEAD指向的就是当前分支。

一开始的时候,master分支是一条线,Git用master指向最新的提交,再用HEAD指向master,就能肯定当前分支,以及当前分支的提交点:

 

每次提交,master分支都会向前移动一步,这样,随着你不断提交,master分支的线也愈来愈长, 当咱们建立新的分支,例如dev时,Git新建了一个指针叫dev,指向master相同的提交,再把HEAD指向dev,就表示当前分支在dev上: 

 

假如咱们在dev上的工做完成了,就能够把dev合并到master上。Git怎么合并呢?最简单的方法,就是直接把master指向dev的当前提交,就完成了合并: 

 

因此Git合并分支也很快!就改改指针,工做区内容也不变!

合并完分支后,甚至能够删除dev分支。删除dev分支就是把dev指针给删掉,删掉后,咱们就剩下了一条master分支:

真是太神奇了,你看得出来有些提交是经过分支完成的吗?

上面这张图就诠释了协做开发的分支与合并的大概流程图。

 

下面开始实战

首先,须要先建立dev分支:

shuais-MacBook-Pro:~ dandyzhang$ ls
Applications    Downloads    Music        PycharmProjects    venv
Desktop        Library        Pictures    git_test
Documents    Movies        Public        git_test2
shuais-MacBook-Pro:~ dandyzhang$ cd git_test2
shuais-MacBook-Pro:git_test2 dandyzhang$ ls
Test2_From_Github
shuais-MacBook-Pro:git_test2 dandyzhang$ cd Test2_From_Github/
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git checkout -b dev
Switched to a new branch 'dev'

git checkout命令加上-b参数表示建立并切换,至关于如下两条命令:

git branch dev  # 建立branch分支
git checkout dev  # 转换到分支dev上

而后,用git branch命令查看当前分支:

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git branch
* dev
  master

git branch命令会列出全部分支,当前分支前面会标一个*号。

而后,咱们就能够在dev分支上正常提交,好比对readme作个修改,加上一行:

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ ls
README.md    main.py        setting.py
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ vim README.md 

# Test2_From_Github
using ssh to test

I am also editing this project, but i forget to check it from github whether it is the newest or not?

using ssh[ubuntu insert here] to [dev add here] test

this line changed from ubuntu server.

here we are using dev to add a new line.

而后提交:

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git add .
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git commit -m 'from branch dev'
[dev 524b382] from branch dev
 1 file changed, 4 insertions(+), 1 deletion(-)

先切换回master分支:

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git checkout master
Switched to branch 'master'
Your branch is up to date with 'origin/master'.
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git branch
  dev
* master

查看readme文件,刚才添加的内容不见了!

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ vim README.md 

# Test2_From_Github
using ssh to test

I am also editing this project, but i forget to check it from github whether it is the newest or not?

using ssh[ubuntu insert here] to test

this line changed from ubuntu server.

由于那个提交是在dev分支上,而master分支此刻的提交点并无变:

如今,咱们把dev分支的工做成果合并到master分支上:

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git merge dev
Updating 775460f..524b382
Fast-forward
 README.md | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)

注意一下上面合并代码到master主线的操做,须要先add到stage并commit到分支仓库,而后切换到master主分支,最后merge 分支。git merge命令用于合并指定分支到当前分支。合并后,再查看readme.txt的内容,就能够看到,和dev分支的最新提交是彻底同样的。

注意到上面的Fast-forward信息,Git告诉咱们,此次合并是“快进模式”,也就是直接把master指向dev的当前提交,因此合并速度很是快。

固然,也不是每次合并都能Fast-forward,咱们后面会讲其余方式的合并。

合并完成后,就能够放心地删除dev分支了:

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git branch -d dev
Deleted branch dev (was 524b382).

删除后,查看branch,就只剩下master分支了:

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git branch
* master

由于建立、合并和删除分支很是快,因此Git鼓励你使用分支完成某个任务,合并后再删掉分支,这和直接在master分支上工做效果是同样的,但过程更安全。

 

二、解决冲突

人生不如意之事十之八九,合并分支每每也不是一路顺风的。

准备新的feature1分支,继续咱们的新分支开发:

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git checkout -b feature1
Switched to a new branch 'feature1'
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git branch
* feature1
  master

修改readme:

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ vim README.md 

# Test2_From_Github
using ssh to test

I am also editing this project, but i forget to check it from github whether it is the newest or not?

using ssh[ubuntu insert here] to [dev add here] test [feature1]

this line changed from ubuntu server.

here we are using dev to add a new line.

another one line insert by feature1.

在feature1分支上提交:

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git add .
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git commit -m 'add by feature1' 
[feature1 7ba88de] add by feature1
 1 file changed, 2 insertions(+), 1 deletion(-)

切换到master分支:

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git checkout master
Switched to branch 'master'
Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)

Git自动的提示咱们当前master分支比远程的feature1落后一个提交。

在master分支上修改readme文件的最后一行:

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ vim README.md 

# Test2_From_Github
using ssh to test

I am also editing this project, but i forget to check it from github whether it is the newest or not?

using ssh[ubuntu insert here] to [dev add here] test

this line changed from ubuntu server.

here we are using dev to add a new line.

add this line from master, do not care whether if exists new branch.

提交:

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git add .
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git commit -m 'master update'
[master f3490d7] master update
 1 file changed, 1 insertion(+), 1 deletion(-)

如今,master分支和feature1分支各自都分别有新的提交,变成了这样:

这种状况下,Git没法执行“快速合并”,只能试图把各自的修改合并起来,但这种合并就可能会有冲突,咱们试试看:

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git merge feature1
Auto-merging README.md
CONFLICT (content): Merge conflict in README.md
Automatic merge failed; fix conflicts and then commit the result.
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ 

不出所料,果真冲突了!Git告诉咱们readme文件存在冲突,必须手动解决冲突后再提交。git status也能够告诉咱们冲突的文件:

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git status
On branch master
Your branch is ahead of 'origin/master' by 2 commits.
  (use "git push" to publish your local commits)

You have unmerged paths.
  (fix conflicts and run "git commit")
  (use "git merge --abort" to abort the merge)

Unmerged paths:
  (use "git add <file>..." to mark resolution)

    both modified:   README.md

no changes added to commit (use "git add" and/or "git commit -a")

咱们能够直接查看readme.txt的内容:

# Test2_From_Github
using ssh to test

I am also editing this project, but i forget to check it from github whether it is the newest or not?

using ssh[ubuntu insert here] to [dev add here] test [feature1]

this line changed from ubuntu server.

here we are using dev to add a new line.

<<<<<<< HEAD
add this line from master, do not care whether if exists new branch.
=======
another one line insert by feature1.

>>>>>>> feature1

Git用<<<<<<<=======>>>>>>>标记出不一样分支的内容,咱们修改以下后保存:

# Test2_From_Github
using ssh to test

I am also editing this project, but i forget to check it from github whether it is the newest or not?

using ssh[ubuntu insert here] to [dev add here] test [feature1]

this line changed from ubuntu server.

here we are using dev to add a new line.

add this line from master, do not care whether if exists new branch.

another one line insert by feature1.

再提交:

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git add .
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git commit -m 'master and feature1 conflict fixed'
[master 0497781] master and feature1 conflict fixed

如今,master分支和feature1分支变成了下图所示:

用带参数的git log也能够看到分支的合并状况:

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git log --graph --pretty=oneline
*   0497781e6ce609ef7a9fa425769a11a5dc7847b9 (HEAD -> master) master and feature1 conflict fixed
|\  
| * 7ba88de0e18caca1681ae66db36fa513d8f5a38c (feature1) add by feature1
* | f3490d750855375bd3717b304ba517cebf987f2d master update
|/  
* 524b382d29793105eed5c0497fd3eb2587a0e3ba from branch dev
*   775460fa81586121344553f09e9f62b58f5d3200 (origin/master, origin/HEAD) fix two different version code
|\  
| * de354d34ee8d5aeefd171d4ba638b0545678a374 changed from ubuntu server.
* | 084fd50f4cdc3255bd26ab1fb8bbee4f020700c6 i am editing this project in macbook pro
|/  
* e5cc600986322beb77930cf428ab3b07f72bd7f7 using ssh in readme.md
* cf545dfa993fcc8ecd43f117286f606922b7d0d1 Initial commit

 

 

三、分支策略

在实际开发中,咱们应该按照几个基本原则进行分支管理:

首先,master分支应该是很是稳定的,也就是仅用来发布新版本,平时不能在上面干活;

那在哪干活呢?干活都在dev分支上,也就是说,dev分支是不稳定的,到某个时候,好比1.0版本发布时,再把dev分支合并到master上,在master分支发布1.0版本;

你和你的小伙伴们每一个人都在dev分支上干活,每一个人都有本身的分支,时不时地往dev分支上合并就能够了。

因此,团队合做的分支看起来就像这样:

 

四、bug分支 

软件开发中,bug就像屡见不鲜同样。有了bug就须要修复,在Git中,因为分支是如此的强大,因此,每一个bug均可以经过一个新的临时分支来修复,修复后,合并分支,而后将临时分支删除。

首先,模拟创立一个分支进行开发:

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git branch 
* master

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git checkout -b dev
Switched to a new branch 'dev'
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git branch
* dev
  master

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ vim README.md 

# Test2_From_Github
using ssh to test

I am also editing this project, but i forget to check it from github whether it is the newest or not?

using ssh[ubuntu insert here] to [dev add here] test [feature1]

this line changed from ubuntu server.

here we are using dev to add a new line.

add this line from master, do not care whether if exists new branch.

another one line insert by feature1.

ignore the lines in front of me, developing the new function now...from new dev
and facing a bug101 need to fix..

当你接到一个修复一个代号101的bug的任务时,很天然地,你想建立一个分支bug101来修复它,可是,等等,当前正在dev上进行的工做尚未提交:

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git status
On branch dev
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   README.md

no changes added to commit (use "git add" and/or "git commit -a")

并非你不想提交,而是工做只进行到一半,还无法提交,预计完成还需1天时间。可是,必须在两个小时内修复该bug,怎么办?

幸亏,Git还提供了一个stash功能,能够把当前工做现场“储藏”起来,等之后恢复现场后继续工做:

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git stash
Saved working directory and index state WIP on dev: 0497781 master and feature1 conflict fixed

# 上面使用了stash命令,dev分支里面的文件如今已经被管理了,查询一下dev工做区状态 shuais
-MacBook-Pro:Test2_From_Github dandyzhang$ git status On branch dev nothing to commit, working tree clean

首先肯定要在哪一个分支上修复bug,假定须要在master分支上修复,就从master建立临时分支:

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git checkout master
Switched to branch 'master'
Your branch is up to date with 'origin/master'.

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git checkout -b bug101
Switched to a new branch 'bug101'

如今须要修复bug,假设bug操做为删除掉readme内容,加上一句hello git stash,而后提交:

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ vim README.md 

# Test2_From_Github
hello git stash !

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git add .
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git commit -m 'fix bug101'
[bug101 0fda0f9] fix bug101
 1 file changed, 1 insertion(+), 13 deletions(-)

修复完成后,切换到master分支,并完成合并,最后删除bug101分支:

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git checkout master
Switched to branch 'master'
Your branch is up to date with 'origin/master'.

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git merge -m "merge fixed bug101 " bug101
Updating 0497781..0fda0f9
Fast-forward (no commit created; -m option ignored)
 README.md | 14 +-------------
 1 file changed, 1 insertion(+), 13 deletions(-)

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ vim README.md 

# Test2_From_Github
hello git stash !

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git branch -d bug101
Deleted branch bug101 (was 0fda0f9).

太棒了,原计划两个小时的bug修复只花了5分钟!如今,是时候接着回到dev分支干活了!

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git checkout dev
Switched to branch 'dev'
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git status
On branch dev
nothing to commit, working tree clean

工做区是干净对的,刚才工做的工做现场到哪去了?用git stash list看看:

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git stash list
stash@{0}: WIP on dev: 0497781 master and feature1 conflict fixed

工做现场还在,Git把stash内容存在某个地方了,可是须要恢复一下,有两个办法:

一是用git stash apply恢复,可是恢复后,stash内容并不删除,你须要用git stash drop来删除;

另外一种方式是用git stash pop,恢复的同时把stash内容也删了:(这一点跟python的list里面的pop很类似,删除最后一个index,并返回)

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git stash pop
On branch dev
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   README.md

no changes added to commit (use "git add" and/or "git commit -a")
Dropped refs/stash@{0} (f43222b3d7f574d3e42baaf83c0378de2ad68f49)

再用git stash list查看,就看不到任何stash内容了.

你能够屡次stash,恢复的时候,先用git stash list查看,而后恢复指定的stash,用命令:

$ git stash apply stash@{0}

 

 

 

忽略特殊文件.gitignore

有些时候,你必须把某些文件放到Git工做目录中,但又不能提交它们,好比保存了数据库密码的配置文件啦,等等,每次git status都会显示Untracked files ...,有强迫症的童鞋内心确定不爽。

好在Git考虑到了你们的感觉,这个问题解决起来也很简单,在Git工做区的根目录下建立一个特殊的.gitignore文件,而后把要忽略的文件名填进去,Git就会自动忽略这些文件。

不须要从头写.gitignore文件,GitHub已经为咱们准备了各类配置文件,只须要组合一下就能够使用了。全部配置文件能够直接在线浏览:https://github.com/github/gitignore

 

忽略文件的原则是:

  1. 忽略操做系统自动生成的文件,好比缩略图等;
  2. 忽略编译生成的中间文件、可执行文件等,也就是若是一个文件是经过另外一个文件自动生成的,那自动生成的文件就不必放进版本库,好比Java编译产生的.class文件;
  3. 忽略你本身的带有敏感信息的配置文件,好比存放口令的配置文件。

举个例子:

假设你在Windows下进行Python开发,Windows会自动在有图片的目录下生成隐藏的缩略图文件,若是有自定义目录,目录下就会有Desktop.ini文件,所以你须要忽略Windows自动生成的垃圾文件:

# Windows:
Thumbs.db
ehthumbs.db
Desktop.ini

而后,继续忽略Python编译产生的.pyc.pyodist等文件或目录:

# Python:
*.py[cod]
*.so
*.egg
*.egg-info
dist
build

加上你本身定义的文件,最终获得一个完整的.gitignore文件,内容以下:

# Windows:
Thumbs.db
ehthumbs.db
Desktop.ini
 
# Python:
*.py[cod]
*.so
*.egg
*.egg-info
dist
build
 
# My configurations:
db.ini
deploy_key_rsa

最后一步就是把.gitignore也提交到Git,就完成了!固然检验.gitignore的标准是git status命令是否是说working directory clean

使用Windows的童鞋注意了,若是你在资源管理器里新建一个.gitignore文件,它会很是弱智地提示你必须输入文件名,可是在文本编辑器里“保存”或者“另存为”就能够把文件保存为.gitignore了。

首先根据上面的链接,下载一份python ignorefile。

首先,咱们先在master分支创建一个文档,放入一个文件:

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ ls
README.md    main.py        setting.py
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ mkdir core
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ ls
README.md    core        main.py        setting.py
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ cd core
shuais-MacBook-Pro:core dandyzhang$ vim main.py

def func1():
    print('before ignore'
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git add .
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git commit -m 'version before gitignore'
[master 52a0beb] version before gitignore
 1 file changed, 2 insertions(+)
 create mode 100644 core/main.py
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git push origin master
Enumerating objects: 9, done.
Counting objects: 100% (9/9), done.
Delta compression using up to 4 threads.
Compressing objects: 100% (4/4), done.
Writing objects: 100% (7/7), 644 bytes | 644.00 KiB/s, done.
Total 7 (delta 1), reused 0 (delta 0)
remote: Resolving deltas: 100% (1/1), done.
To github.com:dandy-weeknd/Test2_From_Github.git
   0497781..52a0beb  master -> master

 

编辑gitignore 文件:

# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
#  Usually these files are written by a python script from a template
#  before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# pyenv
.python-version

# celery beat schedule file
celerybeat-schedule

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/

 

在最后加上一行:core/来测试一下忽略core文件夹

此时,再次编辑core下面的文件

一、修改main.py

def func1():
    print('before ignore'

def func2():
    print('after ignore add this function')

二、在core下面建立新文件core.py

shuais-MacBook-Pro:core dandyzhang$ vim core.py

# new file after add gitignore file.

三、提交测试

shuais-MacBook-Pro:core dandyzhang$ git add .
shuais-MacBook-Pro:core dandyzhang$ git commit -m 'add gitignore'
[master 1c9eba3] add gitignore
 1 file changed, 3 insertions(+)
shuais-MacBook-Pro:core dandyzhang$ git status
On branch master
Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    ../.gitignore

nothing added to commit but untracked files present (use "git add" to track)
shuais-MacBook-Pro:core dandyzhang$ git push origin master
Enumerating objects: 7, done.
Counting objects: 100% (7/7), done.
Delta compression using up to 4 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (4/4), 450 bytes | 450.00 KiB/s, done.
Total 4 (delta 0), reused 0 (delta 0)
To github.com:dandy-weeknd/Test2_From_Github.git
   52a0beb..1c9eba3  master -> master

四、结果

能够得出结论,之于gitignore文件定义以前加入的文件仍是会被git继续追踪,而在gitignore文件定义以后加入的都不会被追踪。

假设存在这样一种状况呢?某个文件夹下,确实要屏蔽或忽视,可是仅有一个文件特殊,须要强制将它加入到Git中。

shuais-MacBook-Pro:core dandyzhang$ vim test.py

def func():
    print('can you ignore me ?')

shuais-MacBook-Pro:core dandyzhang$ git add -f test.py 
shuais-MacBook-Pro:core dandyzhang$ git commit -m 'ignore or not for test.py'
[master 843ce07] ignore or not for test.py
 1 file changed, 2 insertions(+)
 create mode 100644 core/test.py

shuais-MacBook-Pro:core dandyzhang$ git push origin master
Enumerating objects: 6, done.
Counting objects: 100% (6/6), done.
Delta compression using up to 4 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (4/4), 465 bytes | 465.00 KiB/s, done.
Total 4 (delta 0), reused 0 (delta 0)
To github.com:dandy-weeknd/Test2_From_Github.git
   1c9eba3..843ce07  master -> master

有没有点小激动:

或者你发现,多是.gitignore写得有问题,须要找出来到底哪一个规则写错了,能够用git check-ignore命令检查:

shuais-MacBook-Pro:core dandyzhang$ git check-ignore -v core/test.py
.gitignore:106:core/    core/test.py

Git会告诉咱们,.gitignore的第106行规则忽略了该文件,因而咱们就能够知道应该修订哪一个规则。

 

小结

  • 忽略某些文件时,须要编写.gitignore

  • .gitignore文件自己要放到版本库里,而且能够对.gitignore作版本管理!

 

 

多人协做

当你从远程仓库克隆时,实际上Git自动把本地的master分支和远程的master分支对应起来了,而且,远程仓库的默认名称是origin

要查看远程库的信息,用git remote

shuais-MacBook-Pro:core dandyzhang$ git remote
origin

或者,用git remote -v显示更详细的信息:

shuais-MacBook-Pro:core dandyzhang$ git remote -v
origin    git@github.com:dandy-weeknd/Test2_From_Github.git (fetch)
origin    git@github.com:dandy-weeknd/Test2_From_Github.git (push)

上面显示了能够抓取和推送的origin的地址。若是没有推送权限,就看不到push的地址。

 

1 、推送分支

推送分支,就是把该分支上的全部本地提交推送到远程库。推送时,要指定本地分支,这样,Git就会把该分支推送到远程库对应的远程分支上: 

git push origin master

若是要推送其余分支,好比dev,就改为:

git push origin dev

可是,并非必定要把本地分支往远程推送,那么,哪些分支须要推送,哪些不须要呢?

  • master分支是主分支,所以要时刻与远程同步;

  • dev分支是开发分支,团队全部成员都须要在上面工做,因此也须要与远程同步;

  • bug分支只用于在本地修复bug,就不必推到远程了,除非老板要看看你每周到底修复了几个bug;

  • feature分支是否推到远程,取决于你是否和你的小伙伴合做在上面开发。

总之,就是在Git中,分支彻底能够在本地本身藏着玩,是否推送,视你的心情而定!

 

2 、抓取分支

多人协做时,你们都会往masterdev分支上推送各自的修改。

如今,模拟一个你的小伙伴,能够在另外一台电脑(注意要把SSH Key添加到GitHub)或者同一台电脑的另外一个目录下克隆:

dandy@ubuntu01:~/git_test$ git clone git@github.com:dandy-weeknd/Test2_From_Github.git
Cloning into 'Test2_From_Github'...
Warning: Permanently added the RSA host key for IP address '13.250.177.223' to the list of known hosts.
remote: Counting objects: 44, done.
remote: Compressing objects: 100% (27/27), done.
remote: Total 44 (delta 8), reused 39 (delta 6), pack-reused 0
Receiving objects: 100% (44/44), 4.54 KiB | 0 bytes/s, done.
Resolving deltas: 100% (8/8), done.
Checking connectivity... done.

当你的小伙伴从远程库clone时,默认状况下,你的小伙伴只能看到本地的master分支。不信能够用git branch命令看看:

dandy@ubuntu01:~/git_test$ cd Test2_From_Github/
dandy@ubuntu01:~/git_test/Test2_From_Github$ git branch
* master

如今,你的小伙伴要在dev分支上开发,就必须建立远程origindev分支到本地,因而他用这个命令建立本地dev分支:

dandy@ubuntu01:~/git_test/Test2_From_Github$ git checkout -b dev origin/dev
Branch dev set up to track remote branch dev from origin.
Switched to a new branch 'dev'

如今,他就能够在dev上继续修改,而后,时不时地把dev分支push到远程:

dandy@ubuntu01:~/git_test/Test2_From_Github$ vim README.md 

# Test2_From_Github
hello git stash !
....origin/dev
dandy@ubuntu01:~/git_test/Test2_From_Github$ git add .
dandy@ubuntu01:~/git_test/Test2_From_Github$ git commit -m 'dev change' 
[dev 6cb1d87] dev change
 1 file changed, 1 insertion(+), 1 deletion(-)
dandy@ubuntu01:~/git_test/Test2_From_Github$ git branch
* dev
  master
dandy@ubuntu01:~/git_test/Test2_From_Github$ git push origin dev
Warning: Permanently added the RSA host key for IP address '13.229.188.59' to the list of known hosts.
Counting objects: 3, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 383 bytes | 0 bytes/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To git@github.com:dandy-weeknd/Test2_From_Github.git
 * [new branch]      dev -> dev

查看:

你的小伙伴已经向origin/dev分支推送了他的提交,而碰巧你也对一样的文件做了修改,并试图推送:

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ vim README.md 

# Test2_From_Github
hello git stash !
from another client git to modified this file. in dev branch
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ vim README.md 
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git add .
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git commit -m 'modified readme later'
[dev 780d33e] modified readme later
 1 file changed, 1 insertion(+)
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git push origin dev
To github.com:dandy-weeknd/Test2_From_Github.git
 ! [rejected]        dev -> dev (fetch first)
error: failed to push some refs to 'git@github.com:dandy-weeknd/Test2_From_Github.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

推送失败,由于你的小伙伴的最新提交和你试图推送的提交有冲突,解决办法也很简单,Git已经提示咱们,先用git pull把最新的提交从origin/dev抓下来,而后,在本地合并,解决冲突,再推

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git pull
remote: Counting objects: 3, done.
remote: Compressing objects: 100% (3/3), done.
remote: Total 3 (delta 0), reused 3 (delta 0), pack-reused 0
Unpacking objects: 100% (3/3), done.
From github.com:dandy-weeknd/Test2_From_Github
   8767de7..a4de972  dev        -> origin/dev
There is no tracking information for the current branch.
Please specify which branch you want to merge with.
See git-pull(1) for details.
 
    git pull <remote> <branch>
 
If you wish to set tracking information for this branch you can do so with:
 
    git branch --set-upstream-to=origin/<branch> dev

git pull也失败了,缘由是没有指定本地dev分支与远程origin/dev分支的连接,根据提示,设置devorigin/dev的连接:

shuais-MacBook-Pro:Test2_From_Github dandyzhang$  git branch --set-upstream-to=origin/dev dev
Branch 'dev' set up to track remote branch 'dev' from 'origin'.

再pull:

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git pull
Auto-merging README.md
CONFLICT (content): Merge conflict in README.md
Automatic merge failed; fix conflicts and then commit the result.

这回git pull成功,可是合并有冲突,须要手动解决,解决的方法和分支管理中的解决冲突彻底同样。解决后,提交,再push:

shuais-MacBook-Pro:Test2_From_Github dandyzhang$ vim README.md 
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git add .
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git commit -m 'fix two person code'
[dev 9c4e39b] fix two person code
shuais-MacBook-Pro:Test2_From_Github dandyzhang$ git push origin dev
Enumerating objects: 10, done.
Counting objects: 100% (10/10), done.
Delta compression using up to 4 threads.
Compressing objects: 100% (6/6), done.
Writing objects: 100% (6/6), 782 bytes | 391.00 KiB/s, done.
Total 6 (delta 1), reused 0 (delta 0)
remote: Resolving deltas: 100% (1/1), done.
To github.com:dandy-weeknd/Test2_From_Github.git
   a4de972..9c4e39b  dev -> dev

结果图:

所以,多人协做的工做模式一般是这样:

  1. 首先,能够试图用git push origin branch-name推送本身的修改;

  2. 若是推送失败,则由于远程分支比你的本地更新,须要先用git pull试图合并;

  3. 若是合并有冲突,则解决冲突,并在本地提交;

  4. 没有冲突或者解决掉冲突后,再用git push origin branch-name推送就能成功!

若是git pull提示“no tracking information”,则说明本地分支和远程分支的连接关系没有建立,用命令git branch --set-upstream branch-name origin/branch-name

这就是多人协做的工做模式,一旦熟悉了,就很是简单。

 

github使用

咱们一直用GitHub做为免费的远程仓库,若是是我的的开源项目,放到GitHub上是彻底没有问题的。其实GitHub仍是一个开源协做社区,经过GitHub,既可让别人参与你的开源项目,也能够参与别人的开源项目。

在GitHub出现之前,开源项目开源容易,但让广大人民群众参与进来比较困难,由于要参与,就要提交代码,而给每一个想提交代码的群众都开一个帐号那是不现实的,所以,群众也仅限于报个bug,即便能改掉bug,也只能把diff文件用邮件发过去,很不方便。

可是在GitHub上,利用Git极其强大的克隆和分支功能,广大人民群众真正能够第一次自由参与各类开源项目了。

如何参与一个开源项目呢?好比人气极高的bootstrap项目,这是一个很是强大的CSS框架,你能够访问它的项目主页https://github.com/twbs/bootstrap,点“Fork”就在本身的帐号下克隆了一个bootstrap仓库,而后,从本身的帐号下clone:

git clone git@github.com:michaelliao/bootstrap.git

必定要从本身的帐号下clone仓库,这样你才能推送修改。若是从bootstrap的做者的仓库地址git@github.com:twbs/bootstrap.git克隆,由于没有权限,你将不能推送修改。

Bootstrap的官方仓库twbs/bootstrap、你在GitHub上克隆的仓库my/bootstrap,以及你本身克隆到本地电脑的仓库,他们的关系就像下图显示的那样:

 

若是你想修复bootstrap的一个bug,或者新增一个功能,马上就能够开始干活,干完后,往本身的仓库推送。

若是你但愿bootstrap的官方库能接受你的修改,你就能够在GitHub上发起一个pull request。固然,对方是否接受你的pull request就不必定了。

若是没有能力修改的话,能够本身测试。上传代码到github仓库,另外一个帐号区区fork,修改再提交。

小结

  • 在GitHub上,能够任意Fork开源仓库;

  • 本身拥有Fork后的仓库的读写权限;

  • 能够推送pull request给官方仓库来贡献代码。

 

 

参考:http://www.cnblogs.com/alex3714/articles/5930846.html

相关文章
相关标签/搜索