首先,我建议通过执行以下操作来检查您的存储库的 URL:git remote -v
。对于续集,我假设您有两个名为origin
and repo2
.
关于你提到的SO问题 -如何克隆Git中的所有远程分支? https://stackoverflow.com/questions/67699/how-to-clone-all-remote-branches-in-git- 应该指出的是,这是unneeded检查所有分支以检索它们,因为git fetch repo2
足以在本地获取远程的整个历史记录repo2
.
根据git fetch 的文档 https://git-scm.com/docs/git-fetch,你也可以这样做git fetch --all
(没有额外的参数)而不是git fetch origin ; git fetch repo2
.
我记得为了列出与远程对应的远程分支,称为repo2
,你可以这样做git branch -r
这将显示类似以下内容:
origin/HEAD -> origin/master
origin/master
origin/name-of-an-origin-branch
...
repo2/HEAD -> repo2/master
repo2/master
repo2/name-of-a-repo2-branch
...
也就是说,所有远程分支都以远程的标识符为前缀。
为了浏览这些远程分支的内容(不需要互联网连接),您可以这样做gitk --all
显示所有分支历史记录的只读摘要,或git checkout name-of-a-repo2-branch
创建与跟踪分支关联的本地分支name-of-a-repo2-branch
(参见git checkout 文档 https://git-scm.com/docs/git-checkout#Documentation/git-checkout.txt-emgitcheckoutemltbranchgt).
或者你可以进行通常的 git 操作,例如merge https://git-scm.com/docs/git-merge (e.g. git merge origin/master
), rebase https://git-scm.com/docs/git-rebase (e.g., git rebase repo2/master
)涉及跟踪远程存储库中的分支。
同步两个存储库的工作流程建议
关于您的主要用例(使用“本地可移动克隆”同步两个不直接通过网络连接的存储库),我认为最简单的配置是拥有一个“裸”可移动中间存储库(即没有工作目录的存储库,请参阅相应的文档 https://git-scm.com/docs/git-clone#Documentation/git-clone.txt---bare)在给定的本地 URL 处,说“file:///path/to/bare-repo.git”。
要设置一个这样的存储库,您可以这样做:
git init --bare /path/to/bare-repo.git
然后在 repo1 中你可以进行以下设置:
git remote add sync file:///path/to/bare-repo.git
git config alias.pull-ff-sync '!f(){ git fetch sync && git for-each-ref --format "%(refname:strip=3)" refs/remotes/sync/ | grep -v -e '\''^HEAD$'\'' | xargs -n1 bash -c '\''git checkout -q "$1" && git pull --ff-only -v sync "$1"'\'' bash; }; f'
git config alias.pull-ff-sync # to check the alias has been properly setup
# and in particular that the «'\''» have been replaced with single «'»
git config push.default matching
for b in master develop ... ; do git push sync ${b}; done
# push all the branches you want to sync
当然,repo2 中也有类似的设置:
git remote add sync file:///path/that/can/be/different/to/bare-repo.git
git config alias.pull-ff-sync '!f(){ git fetch sync && git for-each-ref --format "%(refname:strip=3)" refs/remotes/sync/ | grep -v -e '\''^HEAD$'\'' | xargs -n1 bash -c '\''git checkout -q "$1" && git pull --ff-only -v sync "$1"'\'' bash; }; f'
git config push.default matching
现在,在 repo1 中(或在 repo2 中),您可以通过以下方式同步:
-
获取您选择的所有分支并合并它们(如果操作是)快进 https://git-scm.com/docs/git-merge#Documentation/git-merge.txt---ff-only(所以这个命令比仅仅更强大git fetch sync
因为如果不需要手动合并提交,所有本地分支都将被更新):
git pull-ff-sync
-
推送您选择的所有分支(这依赖于matching
设置的Push.默认配置 https://git-scm.com/docs/git-config#Documentation/git-config.txt-pushdefault):
git push -v sync
注释以避免一个配置步骤
请注意,如果您不想更改push.default
您的两个存储库的配置(例如,如果您还想使用git push
仅将一个分支从 repo1 推送到另一个远程...),您可以改为:
-
replace
git config push.default matching
with
git config push.default upstream # recommended
或者只是与
git config push.default simple # the default config in Git >= 2.0
-
运行下面稍长的命令,一次性将所有匹配的分支从 repo1(resp.repo2)发送到同步远程:
git push -v sync :