git 如何将一个存储库的公共子文件夹与另一个存储库同步?

osh3o9ms  于 2023-06-20  发布在  Git
关注(0)|答案(1)|浏览(146)

我有一个软件项目foo在我公司托管的内部GitLab存储库上,并希望将其部分发布为GitHub上的开源项目baa
假设我将public部分放在文件夹"public"中:

foo/public

而私有部分在文件夹“private”中:

foo/private

如何将public文件夹与公共GitHub存储库https://github.com/user/new_repository.git同步?
在我最疯狂的梦里,我会:

    • a)**foo中的自动化管道(gitlab-ci. yml),将public文件夹的每个更改转发/同步到baa
    • b)**允许外部用户对baa做出贡献,并以某种方式将其更改合并回foo
    • c)**作为a)的替代方案,具有仅在满足某些要求(例如:新特征的导出控制)。

我看到了git命令

  1. git子模块
  2. git子树
  3. GitLab的repository mirroring功能:
    https://docs.gitlab.com/ee/user/project/repository/mirror/
    但我不确定它们是否适用于我的用例。
    假设我想使用foo的一部分作为baa的子模块…如何确保只考虑文件夹public而不是整个项目?
    也许我的做法是错误的,我应该首先尝试将公共和私人部分分开,以个别项目。
    相关问题和文章:
    How to link folder from a git repo to another repo?
    How to mirror a GitLab repository to GitHub using SSH keys?
    https://www.atlassian.com/de/git/tutorials/git-subtree
    How do I git "subtree split" but maintain the full folder hierarchy?
cwxwcias

cwxwcias1#

在评论的帮助下,我找到了如下所示的解决方案。

      • A使用submodule,与问题中的a)**更接近。
      • B使用subtree,与问题中的c)**更接近,似乎不那么复杂。

0.将公共文件夹的内容填充到单独的仓库中

将文件夹“public”的内容推送到新存储库:

cd public    
git init --initial-branch=main    
git remote add origin https://github.com/user/new_repository.git    
git add .    
git commit -m "Initial commit"     
git push -u origin main

A.使用单独的仓库作为子模块public

集成子模块

  • 删除主文件夹中的公用文件夹
  • 提交主文件夹(=>应用删除公用文件夹)
  • 添加新仓库作为子模块"public":

git submodule add-b main https://github.com/user/new_repository.git public
git submodule update--remote
git submodule add命令创建一个文件。gitmodules包含

[submodule "public"]
    path = public
    url = https://github.com/user/new_repository.git
    branch = main
  • 提交并推送主文件夹

新鲜克隆

如果其他人对主项目进行了fresh clone,则需要使用recursive选项。否则,子模块文件夹“public”的内容将为空。

提交修改子模块

如果有人更改了子模块的内容,则需要将子模块和主项目分别提交/推送。这似乎是子模块方法的缺点。
如果我更改子模块的文件,主项目不会将其识别为更改(提交对话框列表将为空)。一旦我使用子模块文件夹提交了更改,主项目就识别出了更改(子模块的新版本)。然后,主要项目也需要提交。
TortoiseGit的push对话框的"Recurse submodule"选项的值为"On demand":

因此,至少可以对主项目和子模块项目两者进行推送动作。(如果有一个命令可以提交并推送两者,请告诉我。)

子模块使用相关问题

How do I "git clone" a repo, including its submodules?
How do I "commit" changes in a git submodule?
How to add the content of a git submodule directly in the curent directory, without extra project folder?
git submodule tracking latest

B.使用单独的仓库作为子树public

包含子树

  • 删除主文件夹中的公用文件夹
  • 提交主文件夹(=>应用删除公用文件夹)
  • 使用子树命令在本地包含存储库的文件
git subtree add --prefix public https://github.com/user/new_repository.git main --squash
  • 推送主文件夹(提交已通过subtree add命令完成)

新鲜克隆

  • 新克隆包括子树的所有文件。与子模块相比,不需要额外的命令或选项。

提交子树变更

  • 父/主项目将子树中的更改识别为正常文件更改,并且默认情况下与主项目一起提交。
  • 提交到主项目时,子树的存储库不会自动更新。
  • 要将本地更改应用到子树存储库,请使用以下显式命令:
git subtree push --prefix public https://github.com/user/new_repository.git main --squash

可以使用git add remote为url引入一个别名,这样命令的总长度会变短,请参见https://www.atlassian.com/git/tutorials/git-subtree

拉取子树变化

git subtree pull --prefix public https://github.com/user/new_repository.git main

子树相关文章

相关问题