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

后端 未结 30 3209
离开以前
离开以前 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:02

    Reading @ofavre's and @stanislav-bashkyrtsev's answers using broken GIT submodule references to create the GIT directories, I'm surprised that nobody has suggested yet this simple amendment of the idea to make the whole thing sane and safe:

    Rather than hacking a fake submodule into GIT, just add an empty real one.

    Enter: https://gitlab.com/empty-repo/empty.git

    A GIT repository with exactly one commit:

    commit e84d7b81f0033399e325b8037ed2b801a5c994e0
    Author: Nobody 
    Date: Thu Jan 1 00:00:00 1970 +0000
    

    No message, no committed files.

    Usage

    To add an empty directory to you GIT repo:

    git submodule add https://gitlab.com/empty-repo/empty.git path/to/dir
    

    To convert all existing empty directories to submodules:

    find . -type d -empty -delete -exec git submodule add -f https://gitlab.com/empty-repo/empty.git \{\} \;
    

    Git will store the latest commit hash when creating the submodule reference, so you don't have to worry about me (or GitLab) using this to inject malicious files. Unfortunately I have not found any way to force which commit ID is used during checkout, so you'll have to manually check that the reference commit ID is e84d7b81f0033399e325b8037ed2b801a5c994e0 using git submodule status after adding the repo.

    Still not a native solution, but the best we probably can have without somebody getting their hands really, really dirty in the GIT codebase.

    Appendix: Recreating this commit

    You should be able to recreate this exact commit using (in an empty directory):

    # Initialize new GIT repository
    git init
    
    # Set author data (don't set it as part of the `git commit` command or your default data will be stored as “commit author”)
    git config --local user.name "Nobody"
    git config --local user.email "none"
    
    # Set both the commit and the author date to the start of the Unix epoch (this cannot be done using `git commit` directly)
    export GIT_AUTHOR_DATE="Thu Jan 1 00:00:00 1970 +0000"
    export GIT_COMMITTER_DATE="Thu Jan 1 00:00:00 1970 +0000"
    
    # Add root commit
    git commit --allow-empty --allow-empty-message --no-edit
    

    Creating reproducible GIT commits is surprisingly hard…

提交回复
热议问题