Lajos Arpad Lajos Arpad - 1 month ago 12
Git Question

When is .gitignore applied?

Let us suppose I want to make sure that there will be a folder called foo and a file inside it called bar. After I have made sure foo/bar exists I do not intend to version it, therefore I add it to .gitignore.

Bullet-proof approach:


  • create foo

  • create foo/bar

  • commit

  • push

  • deploy

  • add foo to .gitignore

  • commit

  • push

  • deploy



Shorter approach:


  • create foo

  • create foo/bar

  • commit

  • add foo/bar to .gitignore

  • commit

  • push

  • deploy



I wonder whether the shorter approach is guaranteed to create the folder, file and to ignore it. I have done a test and the result seemed to confirm my assumption that the shorter approach will add foo/bar at remote locations as well and then stop versioning it. Is this a rule applicable to all versions?

Answer

As the commenters have noted, if you add a file-path to a .gitignore file after the file is committed, it's too late.

You have two different questions combined into one, here:

  1. How do I convince Git to create an empty directory? (This is your practical problem, the one you need to solve for what you're doing.)

  2. How does .gitignore actually work? What rule(s) apply what actions and when? (This is what you are asking in your subject line.)

For item 1, see How can I add an empty directory to a Git repository?

For item 2, see https://git-scm.com/docs/gitignore. Let me extract this sentence from there and put it in bold, though: Files already tracked by Git are not affected. If you've git add-ed a path that would be ignored, it is not ignored. To get it to become ignored, you must explicitly remove it, which has its own pitfalls. See Stop tracking and ignore changes to a file in Git and How to make Git "forget" about a file that was tracked but is now in .gitignore?

Note that when dealing with accidentally tracked configurations, that cannot now be removed, via git update-index, the modern recommendation is --skip-worktree, not --assume-unchanged.

Comments