Search code examples
gitgitignore

How to git ignore folder based on content


Is it possible to ignore a full folder based on some criteria about it's content. For example I want to ignore everything in all folders that contain at least one html file. How can this be done? (If at all)


Solution

  • There is no such functionality in Git, and it doesn't make much sense to have it, anyway.

    If you have some files in a directory you can easily inspect them to find out if there is any .html file amongst them. If there are many directories (with subdirectories) a simple command line can find the .html files and produce the needed rules to put in .gitignore.

    If a .html file is created later in a directory that was not previously ignored, adding the directory path to .gitignore is not enough, you also have to remove the existing tracked files from the repo.

    A simple command to get all .html files and produce the rules to put in .gitignore:

    find . -name '*.html' -exec dirname \{\} \; | sort -u
    

    It finds all the .html files from the current directory and its subdirectories and executes dirname for each of them. The output of find is then piped to sort that sorts them and removes the duplicates (-u).

    (I didn't test its output with Git, it might need small tweaking but this is the idea.)