How can I add an empty directory to a Git repository?

后端 未结 30 2488
离开以前
离开以前 2020-11-21 04:52

How can I add an empty directory (that contains no files) to a Git repository?

30条回答
  •  误落风尘
    2020-11-21 05:18

    Why would we need empty versioned folders

    First things first:

    An empty directory cannot be part of a tree under the Git versioning system.

    It simply won't be tracked. But there are scenarios in which "versioning" empty directories can be meaningful, for example:

    • scaffolding a predefined folder structure, making it available to every user/contributor of the repository; or, as a specialized case of the above, creating a folder for temporary files, such as a cache/ or logs/ directories, where we want to provide the folder but .gitignore its contents
    • related to the above, some projects won't work without some folders (which is often a hint of a poorly designed project, but it's a frequent real-world scenario and maybe there could be, say, permission problems to be addressed).

    Some suggested workarounds

    Many users suggest:

    1. Placing a README file or another file with some content in order to make the directory non-empty, or
    2. Creating a .gitignore file with a sort of "reverse logic" (i.e. to include all the files) which, at the end, serves the same purpose of approach #1.

    While both solutions surely work I find them inconsistent with a meaningful approach to Git versioning.

    • Why are you supposed to put bogus files or READMEs that maybe you don't really want in your project?
    • Why use .gitignore to do a thing (keeping files) that is the very opposite of what it's meant for (excluding files), even though it is possible?

    .gitkeep approach

    Use an empty file called .gitkeep in order to force the presence of the folder in the versioning system.

    Although it may seem not such a big difference:

    • You use a file that has the single purpose of keeping the folder. You don't put there any info you don't want to put.

      For instance, you should use READMEs as, well, READMEs with useful information, not as an excuse to keep the folder.

      Separation of concerns is always a good thing, and you can still add a .gitignore to ignore unwanted files.

    • Naming it .gitkeep makes it very clear and straightforward from the filename itself (and also to other developers, which is good for a shared project and one of the core purposes of a Git repository) that this file is

      • A file unrelated to the code (because of the leading dot and the name)
      • A file clearly related to Git
      • Its purpose (keep) is clearly stated and consistent and semantically opposed in its meaning to ignore

    Adoption

    I've seen the .gitkeep approach adopted by very important frameworks like Laravel, Angular-CLI.

提交回复
热议问题