Git: 本地创建版本库用于多处同步

问题背景

目前有一个 Android 和 一个 iOS 项目,两个项目底层使用相同的 C++ 代码。由于在开发迭代中代码时常更新,而且往往是今天 Android 部分修改一小部分,明天 iOS 部分修改一小部分,导致这一套代码渐渐显得有些无法管理。于是我考虑单独建一个 Git 仓库来管理这份代码。

Android 和 iOS 项目各自已经是一个 Git 仓库,出于团队的考虑,不能修改原来的结构,只好重新创建仓库。

Git bare 仓库

假设本地已经有一个普通的 Git 仓库,此时使用git clone命令 clone 一个新的仓库,这两个仓库里面的内容是一样的,包含所有的文件(工作区)和版本库(.git 文件夹),我们称之为对等的,也就是说本质上没有区别。但是不方便的地方在于只能新建的仓库只能git pull从原仓库拉取更新,而不能git push提交修改,会有如下报错:

remote: error: refusing to update checked out branch: refs/heads/master
remote: error: By default, updating the current branch in a non-bare repository
remote: is denied, because it will make the index and work tree inconsistent
remote: with what you pushed, and will require 'git reset --hard' to match
remote: the work tree to HEAD.
remote: 
remote: You can set 'receive.denyCurrentBranch' configuration variable to
remote: 'ignore' or 'warn' in the remote repository to allow pushing into
remote: its current branch; however, this is not recommended unless you
remote: arranged to update its work tree to match what you pushed in some
remote: other way.
remote: 
remote: To squelch this message and still keep the default behaviour, set
remote: 'receive.denyCurrentBranch' configuration variable to 'refuse'.

提交被拒绝。那么也就是说新建的仓库其实就是原来的一个备份。当然原仓库使用git push去更新那个新的仓库同样也是不行的,能做的只有新仓库使用git pull从原来的拉取更新。

鉴于以上情况,我们需要使用裸版本库(bare repository)来做我们要做的事。bare repository 没有工作区(即需要版本控制的文件),只有版本库(即 .git 文件夹)。首先初始化中心的裸版本库

git init --bare center.git 

然后在其他地方分别 clone 即可。

git clone ../demo-center/center.git android-bak
git clone ../demo-center/center.git ios-bak    

clone 两次我就建立了两个新的仓库,分别用于两个项目。

版本控制实践

那么具体的控制两处代码的方法是怎么样的呢?

每次修改了代码以后,将代码同步至相应的备份文件夹,即 git 仓库,然后进行提交,另一个仓库拉取更新并将代码同步至原来的项目中。

例如 Android 项目代码位于project/android/, iOS 项目代码位于project/ios/。然后同步的
git 仓库分别为 android-bak and ios-bak。那么 Android 代码更新后,同步至 android-bak 目录,提交代码并 push,同时 iOS 代码也有更新,同样更新至 ios-bak,然后本地提交代码,注意,此时需要先从 bare repository pull 一下,和本地的 commmit 合在一起了,再 push 上去。那么来自两个仓库的代码更改稳妥地合在一起了。另一边 android-bak 只需要 pull 一下,然后将更新的代码同步至原来的 project/android/ 即可。


参考:

《Git 权威指南》 蒋鑫

原文地址:https://www.cnblogs.com/psklf/p/6840214.html