python - 如何在 Git 中只包含另一个存储库中的一个文件夹?

标签 python git git-submodules

我有一个看起来像这样的 python 模块。

|
|-- my_module/
|-- tests/
|-- .git/

我想在另一个项目中使用它。通常子模块就足够了,但是,我宁愿只放入实际模块,而不像这样将任何其他内容包含到我的应用程序中。

|-- .git/
|-- my_app/
|-- my_module/

有没有办法使用 git 子模块只导入单个文件夹?

If I can't or if it's impractical, how else can I include a single folder from another git-tracked project while keeping it version controlled?

最佳答案

如果您不想使用 git submodule,您可以简单地 checkout 所需的文件夹。

由于没有明确的方法可以只从存储库中获取文件夹,因此您必须像这样手动操作:

- create your desired repositories (you already have it)
- write a script that loop over range of commits
- extract the desired folder content from the current commit
- commit the current folder 

这样做的问题是您不会拥有原始的 SHA-1,因为您只提交了提交快照的部分部分。

代码示例

您的代码应该类似于:

for commit in $(git rev-list $branch)
do
    if git ls-tree --name-only -r $commit | grep '<your desired path>'; then
        // Process the commit content
        git checkout <path>
        git add ....
        git commit .... 
        exit 0
    fi
done

为什么我不能直接从 git 历史中提取文件夹?

原因很简单,就是 git 存储其内容的方式。

Git is stupid content tracker (Linus Tovalds)

这意味着 git 存储内容的方式与我们在工作目录中看到的方式不同。

Git 简单地拍摄当前文件系统的快照(实际上它稍微复杂一点,git 使用 blob、hunks、heuristics 等等)以便从历史中提取特定内容您必须从 commit 本身checkout 特定内容。

关于python - 如何在 Git 中只包含另一个存储库中的一个文件夹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30515860/

相关文章:

python - models.py 越来越大,最好的方法是什么?

python - Python可以用于客户端Web开发吗?

python - 如何使用 Python 从网站中提取表格

python - Flask:无法从 socket.io 监听器中访问 c​​urrent_app

git - 如何自动 pull git 子模块?

xcode - Git:将子模块添加到 XCode 项目,然后当我打开它时 GitBox 崩溃

git - 如何将一个分支 merge 到 master 但继续在该分支上工作?

android - Android Studio 项目的典型 .gitignore 文件

git 错误 : cannot stat <filename> : Protocol error

子模块中的 Git Merge 冲突。如何提交他们的版本?