git 忽略除文件、文件夹和该文件夹中的扩展名之外的所有内容

git ignore everything except a file, a folder, and an extension within that folder

我需要创建一个遵循这些规则的 .gitignore 文件:

  1. 忽略 root 中的所有内容
  2. 单个文件除外fil.py
  3. 单个文件夹除外 fol/
  4. 但请忽略 /fol
  5. 中扩展名为 .pyc 的文件

我尝试了多种组合,但无法正常工作。这是我测试过的内容:

1-

# ignore everything in root
*
# except for this file
!fil.py
# except for this folder
!/fol
# But do ignore these files
/fol/*.pyc

这将跟踪对 fol/ 文件夹中的文件所做的更改,但会忽略添加到其中的 所有 个新文件。

2-

# ignore everything in root
*/
# except for this file
!fil.py
# except for this folder
!/fol
# But do ignore these files
/fol/*.pyc

这可以正确跟踪 fol/ 中的旧文件和新文件,同时忽略 *.pyc 个文件;但也会跟踪根文件夹中的文件。

3-

# ignore everything in root
/*
# except for this file
!fil.py
# except for this folder
!/fol
# But do ignore these files
/fol/*.pyc

这可以正确跟踪 fol/ 中的旧文件和新文件,并忽略根文件夹中的文件。但它也会跟踪 fol/ 文件夹中的所有 *.pyc 个文件。

任何帮助将不胜感激。

使用以下 .gitignore,我相信这会如您所愿。

/*
!fil.py
!/fol
*.pyc