gitignore all except file in sub-sub folder

I already tried many combinations of the .gitignore but none worked for what I need. I have this tree:

jobs/
jobs/projecta/config.xml
jobs/projecta/garbage
jobs/projecta/more/garbage
jobs/projectb/config.xml
jobs/projectb/garbage
jobs/projectb/more/garbage

Garbage means any other file. I want to commit only the config.xml files, and ignore everything inside jobs/ except them. So I tried:

/jobs/*
!/jobs/*/config.xml

This way, everything inside jobs are ignored, including the config.xml file. With the inverse order, same happens. So, I can force add all config files and changes to them will be tracked, but if I add a new folder inside jobs, it’s config.xml won’t appear as a untracked file, so this way people can forgot to add them.

I already tried with **, but I got the same.

Any ideas?
Thanks!

  • git very slow with many ignored files
  • How do I tell git to ignore files that start with a tilde?
  • How to git-add only non-whitespace changes and new files?
  • How to git ignore file with same name as container directory?
  • Ignore files that have already been committed to a Git repository
  • how to add all currently untracked files/folders to git ignore?
  • How to gitignore everything except hidden subdir?
  • Coda 2 still publishes files in .gitignore
  • One Solution collect form web for “gitignore all except file in sub-sub folder”

    The question I mentioned in the comments actually answers this scenario; the crucial part is the following:

    If a directory is excluded, Git will never look at the contents of that directory.

    Which is just a rephrasing of this snippet from the gitignore documentation, emphasis mine.

    It is not possible to re-include a file if a parent directory of that file is excluded. Git doesn’t list excluded directories for performance reasons, so any patterns on contained files have no effect, no matter where they are defined.


    Your pattern /jobs/* will ignore each file and folder in jobs. This means that git won’t even look in this ignored folders to see if your !/jobs/*/config.xml pattern matches a file in them.

    In turn you have to explicitly unignore the subfolders and then reignore the contents; after this you can again unignore your config.xml files. This might seem silly but that’s how git handles ignores.

    # Ignore everything in /jobs
    /jobs/*
    # Reinclude all folders in /jobs
    !/jobs/*/
    # Ignore everything in the subfolders of /jobs
    /jobs/*/*
    # Reinclude config.xml files in the first-level subfolders of /jobs
    !/jobs/*/config.xml
    

    This patterns will ignore everything but config.xml files in the first-level subfolders of jobs.

    Git Baby is a git and github fan, let's start git clone.