如何在Git仓库的子目录中忽略除单个文件外的所有内容?

5
我有一个包含子目录 mod/ 的仓库。我想将这个子目录和其中的 README 文件一起包含在仓库中,但我不想包含 mod/ 中的其他子目录。我尝试了几种在 这里 提出的使用 .gitignore 和提交更改的修复方法,但是 git status 仍然显示 mod/ 中的所有内容都被跟踪。目前,我的 .gitignore 包含以下内容:
mod/* # Ignore everything in 'mod'...
!mod/README.md # ... except this.

但我也尝试将第一行设置为:
/mod
mod/
./mod
./mod/*

一些其他的变化...
每次我编辑.gitignore时,要"应用"这些设置,我运行:
git rm -r --cached .  
git add .gitignore
git add mod/README.md
git commit -m "banging my head on the wall"
git status

并且状态继续显示 mod/ 目录下的未跟踪文件。

4
如果你的代码中出现了 mod/*!mod/README.md(没有注释),那么它们应该是没问题的。 - torek
2
哇,好的...刚刚看到在.gitignore中注释只能从行首开始。 - M. Thompson
2个回答

2

不需要使用异常处理。只需忽略整个目录(mod/*),然后继续操作。

git add -f mod/README.md
git commit

-f告诉git覆盖对这个文件的忽略。它将继续被git跟踪,而其他所有内容都将被忽略。

这是因为.gitignore仅确定git如何处理未跟踪的文件。如果您强制使用-f使git跟踪该文件,则忽略文件中的事实是无关紧要的。


如果它被fork了呢?那.gitignore中的异常会继承过来吗?即使如此,对我来说这似乎太可怕了 - 我更喜欢有明确的逻辑来显示发生了什么。 - M. Thompson
@M.Thompson 这就是为什么你也要将你的.gitignore添加到仓库中。这并不是什么“神秘”的事情。任何你添加到 git 仓库中的文件都会被永久跟踪,直到你明确地将该文件删除,供克隆(或派生)它的任何人使用。 - Max
但为了清晰起见,我认为应该在gitignore中添加类似于“#mod / README.md永久跟踪使用git add -f”的注释。而异常条目则是自说明的,更容易撤销。 - M. Thompson

2

我能想到三种直观的选项:

  1. Add a separate .gitignore to mod:

    *
    !README.md
    
  2. Use your root level .gitignore, with only either a rule or comment on each line, but not both:

    ./mod/*
    !./mod/README.md
    

    I use ./ prefix here for emphasis, but it is not strictly necessary. Since the paths all contain a non-trailing slash, they will be interpreted relative to the directory of the .gitignore regardless.

  3. Don't use .gitignore for the positive rule: ignore mod, but then do

    git add -f mod/README.md
    

    Git keeps tracking any files that were added using the -f/--force flag.


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