Search code examples
gitgitignorepre-commit-hook

Can I make .gitignore ignore all folders that contain a folder with a particular name?


For example, given the worktree below, if I init git repo in folder my_folder and type git add ., I do not want the folders django-backend and test-vue added or tracked by Git.

my_folder/
  audio/
    Michael Jackson.mp3
  images/
    nature.jpg
  projects/
    projects_info.md
    django-backend/
      .git/
      manage.py
      poetry.lock
    test-vue/
      .git/
      yarn.lock

I tried this but didn't get the desired effect:

.git/**/*

Solution

  • If you only wanted to ignore any .git folder anywhere in the worktree, it would be easy:

    **/.git/
    

    But it looks like you want to ignore the parent folder of any .git folder anywhere in the worktree. There is no single line you can add to .gitignore that will do this for you. You either have to manually do it, e.g.

    my_folder/projects/django-backend/
    

    or create a Git pre-commit hook that calls a script that detects new folders that should be ignored and adds them to .gitignore and adds the .gitignore change to the commit. This apparently only work for some versions of git. If you have any trouble see the other answer and comments for that SO question.

    If it turns out your version of git's pre-commit hook does not include the git add in the commit, you can instead simply have the script abort the commit with a warning message. Since the directory will have been added to .gitignore by the script, you can just commit a second time and it will work.

    Here are some SO answers that you can use for more guidance with pre-commit hooks: