Gitignore排除子文件夹(使用**/模式),但保留特定的一个子文件夹。

3

我在SO上搜索了这个答案,但没有找到类似的或者我迷失了方向。我正在尝试排除特定子文件夹中的所有内容,除了一个文件夹。可能我可以手动处理所有路径,但我认为应该有更聪明的方法。我的文件结构:

.gitignore
test/
    file1
    file2
    sim_case/
        file1
        file2
            include/
                file1
                file2

在 .gitignore 文件中,我有以下内容:
**/sim_case

除了sim_case之外的所有内容都被排除了,但我想包括文件夹“include”。我尝试了一些变化,但没有任何效果。

!**/sim_case/include
!**/sim_case/include/
!**/sim_case/include/*
!sim_case/include/
!sim_case/include/
!sim_case/include/*
3个回答

4

我做了一些研究,似乎排除“sim_case”文件夹内的文件的最佳选项是使用:

**/sim_case/*
!**/sim_case/include

这允许拥有更复杂的文件结构。

test/sim_case/include
test1/sim_case/include
etc.

"git status" 的结果:
On branch master

Initial commit

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)

    new file:   .gitignore
    new file:   test/file1
    new file:   test/file2
    new file:   test/sim_case/include/file1
    new file:   test/sim_case/include/file2
    new file:   test1/file1
    new file:   test1/file2
    new file:   test1/sim_case/include/file1
    new file:   test1/sim_case/include/file2

2

Your first assumption **/sim_case is wrong.

test/sim_case/**
!test/sim_case/include/**

字面上来说,你不想忽略整个sim_case目录,但是只想忽略其中的内容,除了include目录中的文件。 git status 提议将sim_case目录添加到版本控制中。请执行以下操作:
$ git status
On branch master

Initial commit

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)

        new file:   sim_case/include/.gitignore
        new file:   sim_case/include/file1
        new file:   sim_case/include/file2

Untracked files:
  (use "git add <file>..." to include in what will be committed)

        .gitignore
        file1
        file2

2
test/sim_case/*
!test/sim_case/include

忽略一个目录会忽略该目录中的所有内容,git会反向扫描忽略条目并使用第一个匹配项,因此最后两个条目表示“忽略test/sim_case目录中的所有内容(但仍然扫描该目录),除了test/sim_case/include”。

1
这将在2.8中改变。https://dev59.com/eW035IYBdhLWcg3wPdkS#20652768。`test/sim_case`后跟`!test/sim_case/include`就足够了。 - VonC

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接