15.2 多用户协同的本地模拟
在本篇的学习过程中,需要一个能够提供多人访问的版本库,显然要找到一个公共服务器,并且能让所有人都尽情发挥不太容易,但幸好可以使用本地协议来模拟。在后面的内容中,会经常使用本地协议地址file:///path/to/repos/<project>.git来代表对某一公共版本库的访问,您可以把file://格式的URL(比直接使用路径方式更逼真)想象为git://或http://格式,并且想象它是在一台远程的服务器上,而非本机。
同样地,为了模拟多人的操作,也不再使用/path/to/my/workspace作为工作区,而是分别使用/path/to/user1/workspace和/path/to/user2/workspace等路径来代表不同用户的工作环境。同样想象/path/to/user1/和/path/to/user2/是在不同的主机上,并由不同的用户进行操作。
下面就来演示一个共享版本库的搭建过程,以及两个用户user1和user2在各自的工作区中是如何工作并进行数据交换的,具体过程如下。
(1)于/path/to/repos/shared.git中创建一个共享的版本库。
别忘了在第2篇的“第13章Git克隆”一章中介绍的,以裸版本库方式创建。
$git init—bare/path/to/repos/shared.git
Initialized empty Git repository in/path/to/repos/shared.git/
(2)用户user1克隆版本库。
从下面的命令输出可以看出,克隆一个刚刚初始化完成的裸版本库会显示一个警告,警告正在克隆的版本库是一个空版本库。
$cd/path/to/user1/workspace
$git clone file:///path/to/repos/shared.git project
Cloning into project…
warning:You appear to have cloned an empty repository.
(3)设置user.name和user.email配置变量。
要在版本库级别设置user.name和user.email配置变量(即运行git config命令时不使用—global或—system参数),以便和全局设置区分开,因为我们的模拟环境中所有用户都共享同一全局设置和系统设置。
$cd project
$git config user.name user1
$git config user.email user1@sun.ossxp.com
(4)用户user1创建初始数据并提交。
$echo Hello.>README
$git add README
$git commit-m "initial commit."
[master(root-commit)5174bf3]initial commit.
1 files changed,1 insertions(+),0 deletions(-)
create mode 100644 README
(5)用户user1将本地版本库的提交推送到上游。
在下面的推送指令中使用了origin别名,其实际指向就是file:///path/to/repos/shared.git。可以从.git/config配置文件中看到是如何实现对origin远程版本库注册的。关于远程版本库的内容将在第19章介绍。
$git push origin master
Counting objects:3,done.
Writing objects:100%(3/3),210 bytes,done.
Total 3(delta 0),reused 0(delta 0)
Unpacking objects:100%(3/3),done.
To file:///path/to/repos/shared.git
*[new branch]master->master
(6)用户user2克隆版本库。
用户user2克隆时没有显示警告,因为此时共享版本库已不再是空版本库了。
$cd/path/to/user2/workspace
$git clone file:///path/to/repos/shared.git project
Cloning into project…
remote:Counting objects:3,done.
remote:Total 3(delta 0),reused 0(delta 0)
Receiving objects:100%(3/3),done.
(7)同样在user2的本地版本库中,设置user.name和user.email配置变量,以区别全局配置设置。
$cd/path/to/user2/workspace/project
$git config user.name user2
$git config user.email user2@moon.ossxp.com
(8)用户user2的本地版本库现在拥有和user1用户同样的提交。
$git log
commit 5174bf33ab31a3999a6242fdcb1ec237e8f3f91a
Author:user1<user1@sun.ossxp.com>
Date:Sun Dec 19 15:52:29 2010+0800
initial commit.