5

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/.

M. Thompson
  • 95
  • 11

2 Answers2

2

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.

Max
  • 21,123
  • 5
  • 49
  • 71
  • What if it's forked? Will that exception to the .gitignore carry over? Even if so though, it seems too 'spooky' to me - I'd prefer to have explicit logic showing exactly what's happening. – M. Thompson Jul 18 '18 at 20:53
  • @M.Thompson That's why you also add your `.gitignore` to the repo. There's nothing "spooky" about this. Any file you add to the git repo will be tracked forever for anyone who clones (or forks) it until you explicitly remove the file – Max Jul 18 '18 at 20:55
  • But for clarity, I would argue that a comment to the tune of something like `# mod/README.md permanently tracked using git add -f` to the gitignore would be called for. Whereas an exception entry is self explanatory and simpler to undo. – M. Thompson Jul 18 '18 at 23:24
2

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.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264