我在Gitlab中使用了一个仓库。当我克隆存储库时,它有它通常的remote origin
,指向Gitlab。然而,我还需要将提交推送到第二个repo,因此我在克隆repo时设置了第二个remote
:
git remote add second <url_of_secondary_repo>
我的问题是,有没有一种方法可以将第二个远程存储在Gitlab存储库的git config
中,这样我就不需要在每次克隆存储库时添加它,而是在克隆它并使用git remote -v
查询时,我会得到例如。
origin [email protected]:<user>/<repo>.git (fetch)
origin [email protected]:<user>/<repo>.git (push)
second <url_of_secondary_repo> (fetch)
second <url_of_secondary_repo> (push)
2条答案
按热度按时间inn6fuwd1#
Git配置值不会被跟踪,并且它们不会在存储库之间传输。如果
git clone
有像--extra-remote-name=second --extra-remote-url=<url_of_secondary_repo>
这样的选项就好了。据我所知没有。我认为最直接的方法是编写脚本或函数。这里有一个非常简单的例子,只考虑
git clone [[email protected]](https://stackoverflow.com/cdn-cgi/l/email-protection) :<user>/<repo>.git
。其中一个特例是自定义git命令。如果脚本名为
git-foo
,并且它是可执行的,并且位于$PATH
中的路径下,则可以使用命令git foo [[email protected]](https://stackoverflow.com/cdn-cgi/l/email-protection) :<user>/<repo>.git
来调用它。foo
应该不同于任何现有的git命令,如add
,commit
等。假设它是git-mclone
,您可以使用它来克隆存储库并添加第二个远程。您也可以使用模板目录或后结帐。
默认模板目录是
/usr/share/git-core/templates
,在git-bash
上是/mingw64/share/git-core/templates
或<git-bash-installation-path>/mingw64/share/git-core/templates
。默认情况下,它下面的所有内容都将复制到git init
或git clone
上的存储库的.git/
中。复制默认模板目录。
添加一个默认配置文件
/path/to/foo_templates/config
,其中包含以下行。如果您指定了模板目录,这些行将位于创建的本地存储库的
.git/config
中。默认模板目录下有一个文件夹
hooks
,其中包含示例钩子。您还可以在其中添加可执行文件post-checkout
。如果模板目录在
git clone
中指定,钩子将被复制到存储库的.git/hooks
中。在默认 checkoutmain
或master
之后,将调用.git/hooks/post-checkout
并添加第二个远程。和模板目录一样,你也可以创建一个钩子目录。
在
git clone
中指定hook目录。这样,在默认 checkout 之后,
/path/to/foo_hooks/post-checkout
被调用并添加第二个远程。如果你不想使用不同的git命令或输入额外的选项,如
--template
和-c core.hookspath
,你也可以考虑git config
的条件包含。有两个可能的条件关键字,gitdir和hasconfig:remote.*.url:。如果我们在系统或全局配置中添加这些条件关键字,配置可以包含另一个包含
remote.second.url
和remote.second.fetch
的配置文件。hasconfig:remote.*.url:
看起来很有希望。使用此系统或全局配置值,如果存储库有
[[email protected]](https://stackoverflow.com/cdn-cgi/l/email-protection) :<user>/<repo>.git
,则可以从/path/to/foo_templates/config
中包含remote.second.url
和remote.second.fetch
。但是,remote.second.url
是不允许的。此选项包含的文件(直接或间接)不允许包含远程URL。
这将引发一个错误:
幸运的是,
gitdir
允许这样做,尽管您必须将存储库克隆到指定的文件夹下。wnvonmuf2#
我没有看到在团队中提交和共享git config的方法,虽然有一个解决方案可以通过git hooks共享它,但我认为考虑到你的用例,这不值得。不过,我还是记下来了。
在GIT中,一旦一个仓库被克隆,
post-checkout
钩子就会被调用。你可以在这个钩子文件(.git/hooks/post-checkout
)中放入一个shell命令(git remote add second <url_of_secondary_repo>
)。Git不允许你提交钩子,但是在互联网上有很多关于如何在你的团队中共享git钩子的解决方法。现在只要你的队友克隆这个仓库,post-checkout
钩子就会自动执行,第二个远程将被添加到他们的配置中。请注意,每次运行git checkout命令时都会调用post-checkout钩子,因此如果配置中不存在第二个远程,则必须在post-checkout钩子中放置一个检查,以仅运行add remote命令。
OR
更复杂更好的方法是-
1.在存储库的顶层添加一个名为
gitconfig
的新文件。1.把下面最后提到的配置放在这个gitconfig文件中。
1.将此命令
git config --local include.path ../gitconfig
粘贴到.git/hooks/post-checkout
文件中。如果这个命令get在每次后 checkout 钩子运行时都被执行,这是没有问题的。1.让你的钩子可以共享。
1.提交gitconfig
现在,一旦有人克隆了仓库,post-checkout钩子将被执行,第二个远程将被自动添加,而不是克隆仓库,如果他们下载了它,那么第二个远程将在他们第一次运行checkout命令时被添加。
gitconfig文件的内容-