Search code examples
gitgitignore

gitignore ignore all except config.xml file inside second-level directory?


I googled but hard to find the proper solution. If I have below files, how can I ignore all files except these three files?

  1. package-01/config.xml
  2. package-02/config.xml
  3. package-03/config.xml
./
|-- .git/
|-- .gitignore
|-- README.md
|-- config.xml
|-- configuration
|-- package-01/
|   |-- settings/
|   |   |-- id
|   |   `-- links
|   |-- config.xml
|   `-- other_files
|-- package-02/
|   |-- settings/
|   |   |-- id
|   |   `-- links
|   |-- config.xml
|   `-- other_files
|-- package-03/
|   |-- settings/
|   |   |-- id
|   |   `-- links
|   |-- external_packages/
|   |   |-- 1/
|   |   |   |-- settings.xml
|   |   |   |-- config.xml
|   |   |   `-- id
|   |   |-- 2/
|   |   |   |-- settings.xml
|   |   |   |-- config.xml
|   |   |   `-- id
|   |-- config.xml
|   `-- other_files

I tried this but failed.

*
!.gitignore
!README.md
!/**/*.xml
!**/*.xml
!**.xml
!/*/*.xml
!*/*.xml

Solution

  • Exclude the directories containing config.xml from being ignored, then ignore all their contents but exclude each config.xml.

    /*
    !.gitignore
    !README.md
    !/package-01
    /package-01/**
    !/package-01/config.xml
    !/package-02
    /package-02/**
    !/package-02/config.xml
    !/package-03
    /package-03/**
    !/package-03/config.xml
    

    The problem with your approach was indeed, as ElpieKay mentioned in a comment:

    It is not possible to re-include a file if a parent directory of that file is excluded.

    (see https://git-scm.com/docs/gitignore)