简体   繁体   中英

How can I ignore everything in a git repository subdirectory except a single file?

I have a repository with a subdirectory called mod/. I want this subdirectory to be included in the repository along with a README file within it, but I do not want other subdirectories within mod/ to be included. I have tried several fixes proposed here using .gitignore and committing changes, but git status still shows everything in mod/ is being tracked. Currently, my .gitignore contains:

mod/* # Ignore everything in 'mod'...
!mod/README.md # ... except this.

But I have also tried setting the first line to:

/mod
mod/
./mod
./mod/*

and a few other variations...

To 'apply' these settings each time I edit .gitignore, I run:

git rm -r --cached .  
git add .gitignore
git add mod/README.md
git commit -m "banging my head on the wall"
git status

and the status continues to show untracked files in mod/.

There's no need for an exception. Just ignore the entire directory (with mod/* ) and then

git add -f mod/README.md
git commit

-f tells git to override the ignore for this one file. It will continue to be tracked by git while everything else is ignored.

This works because .gitignore only determines how git handles untracked files. If you force git to track the file with -f , the fact that it's in the ignore file is irrelevant.

There are three intuitive options I can think of:

  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM